aria-ease 6.14.0 → 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +1 -1
  2. package/dist/AccordionComponentStrategy-2SWMNUR6.js +1 -0
  3. package/dist/ComboboxComponentStrategy-YSYLR2U5.js +5 -0
  4. package/dist/MenuComponentStrategy-C22BZEBH.js +5 -0
  5. package/dist/RelativeTargetResolver-T4P25J2M.js +1 -0
  6. package/dist/TabsComponentStrategy-ADEEFJXM.js +1 -0
  7. package/dist/audit-WBKVW7H6.js +9 -0
  8. package/dist/badgeHelper-IB5RTMAG.js +11 -0
  9. package/dist/badgeHelper-JSROP5ML.js +1 -0
  10. package/dist/buildContracts-T4XQZBDU.js +13 -0
  11. package/dist/chunk-52I3INNG.js +11 -0
  12. package/dist/chunk-APUMBDOT.js +1 -0
  13. package/dist/chunk-BHNO4ZI3.js +1 -0
  14. package/dist/chunk-CNU4N4AY.js +1 -0
  15. package/dist/chunk-SM6ZKEDR.js +1 -0
  16. package/dist/chunk-ZNQ5BXVJ.js +1 -0
  17. package/dist/cli.cjs +132 -3560
  18. package/dist/cli.js +19 -161
  19. package/dist/configLoader-ZEJVXLX7.js +1 -0
  20. package/dist/configLoader-ZXTSCIP6.js +1 -0
  21. package/dist/contractTestRunnerPlaywright-FOCQTM4L.js +46 -0
  22. package/dist/contractTestRunnerPlaywright-QPU6HZXG.js +46 -0
  23. package/dist/formatters-H3CPDLG5.js +87 -0
  24. package/dist/index.cjs +64 -5103
  25. package/dist/index.d.cts +4 -6
  26. package/dist/index.d.ts +4 -6
  27. package/dist/index.js +17 -2703
  28. package/dist/src/accordion/index.cjs +1 -183
  29. package/dist/src/accordion/index.js +1 -181
  30. package/dist/src/block/index.cjs +1 -124
  31. package/dist/src/block/index.js +1 -122
  32. package/dist/src/checkbox/index.cjs +1 -109
  33. package/dist/src/checkbox/index.js +1 -107
  34. package/dist/src/combobox/index.cjs +1 -265
  35. package/dist/src/combobox/index.js +1 -263
  36. package/dist/src/menu/index.cjs +1 -339
  37. package/dist/src/menu/index.js +1 -337
  38. package/dist/src/radio/index.cjs +1 -117
  39. package/dist/src/radio/index.js +1 -115
  40. package/dist/src/tabs/index.cjs +1 -265
  41. package/dist/src/tabs/index.js +1 -263
  42. package/dist/src/toggle/index.cjs +1 -119
  43. package/dist/src/toggle/index.js +1 -117
  44. package/dist/src/utils/test/AccordionComponentStrategy-X2GSQ5KT.js +1 -0
  45. package/dist/src/utils/test/ComboboxComponentStrategy-SICWLI27.js +5 -0
  46. package/dist/src/utils/test/MenuComponentStrategy-R4VPAHDE.js +5 -0
  47. package/dist/src/utils/test/RelativeTargetResolver-UQQMZHI6.js +1 -0
  48. package/dist/src/utils/test/TabsComponentStrategy-L2PYNEW6.js +1 -0
  49. package/dist/src/utils/test/badgeHelper-ER5ZOHWF.js +11 -0
  50. package/dist/src/utils/test/chunk-APUMBDOT.js +1 -0
  51. package/dist/src/utils/test/chunk-BHNO4ZI3.js +1 -0
  52. package/dist/src/utils/test/configLoader-NCYRL2O6.js +1 -0
  53. package/dist/src/utils/test/contractTestRunnerPlaywright-YZCMF64Q.js +46 -0
  54. package/dist/src/utils/test/dsl/index.cjs +1 -838
  55. package/dist/src/utils/test/dsl/index.d.cts +2 -4
  56. package/dist/src/utils/test/dsl/index.d.ts +2 -4
  57. package/dist/src/utils/test/dsl/index.js +1 -836
  58. package/dist/src/utils/test/index.cjs +64 -2672
  59. package/dist/src/utils/test/index.d.cts +2 -2
  60. package/dist/src/utils/test/index.d.ts +2 -2
  61. package/dist/src/utils/test/index.js +16 -340
  62. package/dist/test-VXSCSKV5.js +19 -0
  63. package/package.json +8 -10
  64. package/dist/AccordionComponentStrategy-4ZEIQ2V6.js +0 -42
  65. package/dist/ComboboxComponentStrategy-DU342VMB.js +0 -64
  66. package/dist/MenuComponentStrategy-VYCC2XOM.js +0 -81
  67. package/dist/RelativeTargetResolver-DJAITO6D.js +0 -7
  68. package/dist/TabsComponentStrategy-3SQURPMX.js +0 -29
  69. package/dist/audit-JYEPKLHR.js +0 -63
  70. package/dist/badgeHelper-JOWO6RQG.js +0 -15
  71. package/dist/badgeHelper-RDOMCC6E.js +0 -108
  72. package/dist/buildContracts-VIV6GM56.js +0 -437
  73. package/dist/chunk-4DU5Z5BR.js +0 -340
  74. package/dist/chunk-GJGUY643.js +0 -182
  75. package/dist/chunk-GLT43UVH.js +0 -43
  76. package/dist/chunk-I2KLQ2HA.js +0 -22
  77. package/dist/chunk-JJEPLK7L.js +0 -107
  78. package/dist/chunk-PK5L2SAF.js +0 -17
  79. package/dist/configLoader-Q7N5XV4P.js +0 -183
  80. package/dist/configLoader-REHK3S3Q.js +0 -7
  81. package/dist/contractTestRunnerPlaywright-B2HLZKKK.js +0 -1394
  82. package/dist/contractTestRunnerPlaywright-RWK52C7S.js +0 -1394
  83. package/dist/formatters-32KQIIYS.js +0 -183
  84. package/dist/src/utils/test/AccordionComponentStrategy-WRHZOEN6.js +0 -38
  85. package/dist/src/utils/test/ComboboxComponentStrategy-XKQ72RFD.js +0 -60
  86. package/dist/src/utils/test/MenuComponentStrategy-6XWU5KLW.js +0 -77
  87. package/dist/src/utils/test/RelativeTargetResolver-G2XDN2VV.js +0 -1
  88. package/dist/src/utils/test/TabsComponentStrategy-BKG53SEV.js +0 -26
  89. package/dist/src/utils/test/badgeHelper-HZKGOPB4.js +0 -102
  90. package/dist/src/utils/test/chunk-4DU5Z5BR.js +0 -332
  91. package/dist/src/utils/test/chunk-GLT43UVH.js +0 -41
  92. package/dist/src/utils/test/configLoader-NA7IBCS3.js +0 -181
  93. package/dist/src/utils/test/contractTestRunnerPlaywright-5FIGA5G4.js +0 -1372
  94. package/dist/test-WDBS5JWO.js +0 -358
@@ -1,2690 +1,82 @@
1
- 'use strict';
2
-
3
- var playwright = require('playwright');
4
- var path3 = require('path');
5
- var fs3 = require('fs-extra');
6
- var test = require('@playwright/test');
7
- var url = require('url');
8
- var fs = require('fs');
9
- var chalk = require('chalk');
10
- var readline = require('readline');
11
- var jestAxe = require('jest-axe');
12
- var fs$1 = require('fs/promises');
13
-
14
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
15
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
16
-
17
- var path3__default = /*#__PURE__*/_interopDefault(path3);
18
- var fs3__default = /*#__PURE__*/_interopDefault(fs3);
19
- var chalk__default = /*#__PURE__*/_interopDefault(chalk);
20
- var readline__default = /*#__PURE__*/_interopDefault(readline);
21
- var fs__default = /*#__PURE__*/_interopDefault(fs$1);
22
-
23
- var __defProp = Object.defineProperty;
24
- var __getOwnPropNames = Object.getOwnPropertyNames;
25
- var __esm = (fn, res) => function __init() {
26
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
27
- };
28
- var __export = (target, all) => {
29
- for (var name in all)
30
- __defProp(target, name, { get: all[name], enumerable: true });
31
- };
32
-
33
- // src/utils/test/src/ContractReporter.ts
34
- var ContractReporter;
35
- var init_ContractReporter = __esm({
36
- "src/utils/test/src/ContractReporter.ts"() {
37
- ContractReporter = class {
38
- startTime = 0;
39
- componentName = "";
40
- staticPasses = 0;
41
- staticFailures = 0;
42
- staticWarnings = 0;
43
- dynamicResults = [];
44
- totalTests = 0;
45
- skipped = 0;
46
- warnings = 0;
47
- isPlaywright = false;
48
- isCustomContract = false;
49
- apgUrl = "https://www.w3.org/WAI/ARIA/apg/";
50
- hasPrintedStaticSection = false;
51
- hasPrintedDynamicSection = false;
52
- constructor(isPlaywright = false, isCustomContract = false) {
53
- this.isPlaywright = isPlaywright;
54
- this.isCustomContract = isCustomContract;
55
- }
56
- log(message) {
57
- process.stderr.write(message + "\n");
58
- }
59
- start(componentName, totalTests, apgUrl) {
60
- this.startTime = Date.now();
61
- this.componentName = componentName;
62
- this.totalTests = totalTests;
63
- this.hasPrintedStaticSection = false;
64
- this.hasPrintedDynamicSection = false;
65
- if (apgUrl) {
66
- this.apgUrl = apgUrl;
67
- }
68
- const mode = this.isPlaywright ? "Playwright (Real Browser)" : "jsdom (Fast)";
69
- this.log(`
70
- ${"\u2550".repeat(60)}`);
71
- this.log(`\u{1F50D} Testing ${componentName.charAt(0).toUpperCase() + componentName.slice(1)} Component - ${mode}`);
72
- this.log(`${"\u2550".repeat(60)}
73
- `);
74
- }
75
- reportStatic(passes, failures, warnings = 0) {
76
- this.staticPasses = passes;
77
- this.staticFailures = failures;
78
- this.staticWarnings = warnings;
79
- }
80
- /**
81
- * Report individual static test pass
82
- */
83
- reportStaticTest(description, status, failureMessage, level) {
84
- if (!this.hasPrintedStaticSection) {
85
- this.log(`${"\u2500".repeat(60)}`);
86
- this.log(`\u{1F9EA} Static Assertions`);
87
- this.log(`${"\u2500".repeat(60)}`);
88
- this.hasPrintedStaticSection = true;
89
- }
90
- const icon = status === "pass" ? "\u2713" : status === "warn" ? "\u26A0" : status === "skip" ? "\u25CB" : "\u2717";
91
- this.log(` ${icon} ${description}`);
92
- if (level) {
93
- this.log(` \u21B3 level=${level}`);
94
- }
95
- if ((status === "fail" || status === "warn" || status === "skip") && failureMessage) {
96
- this.log(` \u21B3 ${failureMessage}`);
97
- }
98
- }
99
- /**
100
- * Report individual dynamic test result
101
- */
102
- reportTest(test, status, failureMessage) {
103
- if (!this.hasPrintedDynamicSection) {
104
- this.log("");
105
- this.log(`${"\u2500".repeat(60)}`);
106
- this.log(`\u2328\uFE0F Dynamic Interaction Tests`);
107
- this.log(`${"\u2500".repeat(60)}`);
108
- this.hasPrintedDynamicSection = true;
109
- }
110
- const result = {
111
- description: test.description,
112
- status,
113
- failureMessage,
114
- level: test.level
115
- };
116
- if (status === "skip") {
117
- result.skipReason = "Requires real browser (addEventListener events)";
118
- }
119
- this.dynamicResults.push(result);
120
- const icons = { pass: "\u2713", fail: "\u2717", warn: "\u26A0", skip: "\u25CB" };
121
- const levelPrefix = test.level ? `[${test.level.toUpperCase()}] ` : "";
122
- this.log(` ${icons[status]} ${levelPrefix}${test.description}`);
123
- if (status === "skip" && !this.isPlaywright) {
124
- this.log(` \u21B3 Skipped in jsdom (runs in Playwright)`);
125
- }
126
- if (status === "fail" && failureMessage) {
127
- this.log(` \u21B3 ${failureMessage}`);
128
- }
129
- if (status === "warn" && failureMessage) {
130
- this.log(` \u21B3 ${failureMessage}`);
131
- }
132
- if (status === "skip" && failureMessage) {
133
- this.log(` \u21B3 ${failureMessage}`);
134
- }
135
- }
136
- /**
137
- * Report all failures with actionable context
138
- */
139
- reportFailures(failures) {
140
- if (failures.length === 0) return;
141
- this.log(`
142
- ${"\u2500".repeat(60)}`);
143
- this.log(`\u274C Failures (${failures.length}):
144
- `);
145
- failures.forEach((failure, index) => {
146
- this.log(`${index + 1}. ${failure}`);
147
- if (failure.includes("aria-")) {
148
- this.log(` \u{1F4A1} Add the missing ARIA attribute to improve screen reader support`);
149
- } else if (failure.includes("focus")) {
150
- this.log(` \u{1F4A1} Check keyboard event handlers and focus management`);
151
- } else if (failure.includes("visible")) {
152
- this.log(` \u{1F4A1} Verify display/visibility styles and state management`);
153
- }
154
- this.log("");
155
- });
156
- }
157
- reportWarnings() {
158
- const warnings = this.dynamicResults.filter((r) => r.status === "warn");
159
- if (warnings.length === 0 && this.staticWarnings === 0) return;
160
- this.log(`
161
- ${"\u2500".repeat(60)}`);
162
- this.log(`\u26A0\uFE0F Warnings (${this.staticWarnings + warnings.length}):
163
- `);
164
- this.log(`These checks are failing but treated as warnings under the active strictness mode.
165
- `);
166
- warnings.forEach((test, index) => {
167
- this.log(`${index + 1}. ${test.description}`);
168
- if (test.failureMessage) {
169
- this.log(` \u21B3 ${test.failureMessage}`);
170
- }
171
- if (test.level) {
172
- this.log(` \u21B3 level=${test.level}`);
173
- }
174
- });
175
- if (this.apgUrl) {
176
- this.log(`
177
- Reference: ${this.apgUrl}
178
- `);
179
- }
180
- }
181
- /**
182
- * Report skipped tests with helpful context
183
- */
184
- reportSkipped() {
185
- if (this.skipped === 0 || this.isPlaywright) return;
186
- const skippedTests = this.dynamicResults.filter((r) => r.status === "skip");
187
- this.log(`
188
- ${"\u2500".repeat(60)}`);
189
- this.log(`\u2139\uFE0F Skipped Tests (${this.skipped}):
190
- `);
191
- this.log(`These tests use native keyboard events via addEventListener,`);
192
- this.log(`which jsdom cannot simulate. They run successfully in Playwright.
193
- `);
194
- skippedTests.forEach((test, index) => {
195
- this.log(`${index + 1}. ${test.description}`);
196
- });
197
- this.log(`
198
- \u{1F4A1} Run with Playwright for full validation:`);
199
- this.log(` testUiComponent('${this.componentName}', null, 'http://localhost:5173/test-harness?component=component_name')
200
- `);
201
- }
202
- /**
203
- * Generate final summary with statistics
204
- */
205
- summary(failures) {
206
- const duration = Date.now() - this.startTime;
207
- const dynamicPasses = this.dynamicResults.filter((r) => r.status === "pass").length;
208
- const dynamicFailures = this.dynamicResults.filter((r) => r.status === "fail").length;
209
- const dynamicWarnings = this.dynamicResults.filter((r) => r.status === "warn").length;
210
- this.skipped = this.dynamicResults.filter((r) => r.status === "skip").length;
211
- this.warnings = this.staticWarnings + dynamicWarnings;
212
- const totalPasses = this.staticPasses + dynamicPasses;
213
- const totalFailures = this.staticFailures + dynamicFailures;
214
- const totalRun = totalPasses + totalFailures + this.warnings;
215
- const getComponentMessage = () => {
216
- const componentDisplayName = `${this.componentName.charAt(0).toUpperCase()}${this.componentName.slice(1)}`;
217
- if (this.isCustomContract) {
218
- return `${componentDisplayName} component validates against your custom accessibility policy \u2713`;
219
- }
220
- return `${componentDisplayName} component meets Aria-Ease baseline WAI-ARIA expectations \u2713`;
221
- };
222
- if (failures.length > 0) {
223
- this.reportFailures(failures);
224
- }
225
- this.reportWarnings();
226
- this.reportSkipped();
227
- this.log(`
228
- ${"\u2550".repeat(60)}`);
229
- this.log(`\u{1F4CA} Summary
230
- `);
231
- if (totalFailures === 0 && this.skipped === 0 && this.warnings === 0) {
232
- this.log(`\u2705 All ${totalRun} tests passed!`);
233
- this.log(` ${getComponentMessage()}`);
234
- } else if (totalFailures === 0) {
235
- this.log(`\u2705 ${totalPasses}/${totalRun} tests passed`);
236
- if (this.skipped > 0) {
237
- this.log(`\u25CB ${this.skipped} tests skipped`);
238
- }
239
- if (this.warnings > 0) {
240
- this.log(`\u26A0\uFE0F ${this.warnings} warning${this.warnings > 1 ? "s" : ""}`);
241
- }
242
- this.log(` ${getComponentMessage()}`);
243
- } else {
244
- this.log(`\u274C ${totalFailures} test${totalFailures > 1 ? "s" : ""} failed`);
245
- this.log(`\u2705 ${totalPasses} test${totalPasses > 1 ? "s" : ""} passed`);
246
- if (this.warnings > 0) {
247
- this.log(`\u26A0\uFE0F ${this.warnings} warning${this.warnings > 1 ? "s" : ""}`);
248
- }
249
- if (this.skipped > 0) {
250
- this.log(`\u25CB ${this.skipped} test${this.skipped > 1 ? "s" : ""} skipped`);
251
- }
252
- }
253
- this.log(`\u23F1\uFE0F Duration: ${duration}ms`);
254
- this.log(`${"\u2550".repeat(60)}
255
- `);
256
- if (totalFailures > 0) {
257
- this.log(`\u{1F527} Next Steps:`);
258
- this.log(` 1. Review the failures above`);
259
- this.log(` 2. Fix ARIA attributes and keyboard handlers`);
260
- this.log(` 3. Re-run tests to verify fixes
261
- `);
262
- } else if (!this.isPlaywright && this.skipped > 0) {
263
- this.log(`\u2728 Optional: Run Playwright tests for complete validation
264
- `);
265
- }
266
- return {
267
- passes: totalPasses,
268
- failures: totalFailures,
269
- skipped: this.skipped,
270
- duration
271
- };
272
- }
273
- /**
274
- * Report an error during test execution
275
- */
276
- error(message, context) {
277
- this.log(`
278
- \u274C Error: ${message}`);
279
- if (context) {
280
- this.log(` Context: ${context}`);
281
- }
282
- this.log("");
283
- }
284
- };
285
- }
286
- });
287
-
288
- // src/utils/test/src/strictness.ts
289
- function normalizeLevel(level) {
290
- if (level === "required" || level === "recommended" || level === "optional") {
291
- return level;
292
- }
293
- return FALLBACK_LEVEL;
294
- }
295
- function normalizeStrictness(strictness) {
296
- if (strictness === "minimal" || strictness === "balanced" || strictness === "strict" || strictness === "paranoid") {
297
- return strictness;
298
- }
299
- return "balanced";
300
- }
301
- function resolveEnforcement(level, strictness) {
302
- const matrix = {
303
- minimal: {
304
- required: "error",
305
- recommended: "ignore",
306
- optional: "ignore"
307
- },
308
- balanced: {
309
- required: "error",
310
- recommended: "warning",
311
- optional: "ignore"
312
- },
313
- strict: {
314
- required: "error",
315
- recommended: "error",
316
- optional: "warning"
317
- },
318
- paranoid: {
319
- required: "error",
320
- recommended: "error",
321
- optional: "error"
322
- }
323
- };
324
- return matrix[strictness][level];
325
- }
326
- var FALLBACK_LEVEL;
327
- var init_strictness = __esm({
328
- "src/utils/test/src/strictness.ts"() {
329
- FALLBACK_LEVEL = "required";
330
- }
331
- });
332
- async function getOrCreateBrowser() {
333
- if (!sharedBrowser) {
334
- sharedBrowser = await playwright.chromium.launch({
335
- headless: true,
336
- // Launch with clean browser profile - no extensions, no user data
337
- args: [
338
- "--disable-extensions",
339
- "--disable-blink-features=AutomationControlled"
340
- ]
341
- });
342
- }
343
- return sharedBrowser;
344
- }
345
- async function getOrCreateContext() {
346
- if (!sharedContext) {
347
- const browser = await getOrCreateBrowser();
348
- sharedContext = await browser.newContext({
349
- permissions: [],
350
- ignoreHTTPSErrors: true
351
- });
352
- }
353
- return sharedContext;
354
- }
355
- async function createTestPage() {
356
- const context = await getOrCreateContext();
357
- return await context.newPage();
358
- }
359
- async function closeSharedBrowser() {
360
- if (sharedContext) {
361
- await sharedContext.close();
362
- sharedContext = null;
363
- }
364
- if (sharedBrowser) {
365
- await sharedBrowser.close();
366
- sharedBrowser = null;
367
- }
368
- }
369
- var sharedBrowser, sharedContext;
370
- var init_playwrightTestHarness = __esm({
371
- "src/utils/test/src/playwrightTestHarness.ts"() {
372
- sharedBrowser = null;
373
- sharedContext = null;
374
- }
375
- });
376
-
377
- // src/utils/cli/configLoader.ts
378
- var configLoader_exports = {};
379
- __export(configLoader_exports, {
380
- loadConfig: () => loadConfig
381
- });
382
- function validateConfig(config) {
383
- const errors = [];
384
- if (!config || typeof config !== "object") {
385
- errors.push("Config must be an object");
386
- return { valid: false, errors };
387
- }
388
- const cfg = config;
389
- if (cfg.audit !== void 0) {
390
- if (typeof cfg.audit !== "object" || cfg.audit === null) {
391
- errors.push("audit must be an object");
392
- } else {
393
- if (cfg.audit.urls !== void 0) {
394
- if (!Array.isArray(cfg.audit.urls)) {
395
- errors.push("audit.urls must be an array");
396
- } else if (cfg.audit.urls.some((url) => typeof url !== "string")) {
397
- errors.push("audit.urls must contain only strings");
398
- }
399
- }
400
- if (cfg.audit.output !== void 0) {
401
- if (typeof cfg.audit.output !== "object") {
402
- errors.push("audit.output must be an object");
403
- } else {
404
- const output = cfg.audit.output;
405
- if (output.format !== void 0) {
406
- if (!["json", "csv", "html", "all"].includes(output.format)) {
407
- errors.push("audit.output.format must be one of: json, csv, html, all");
408
- }
409
- }
410
- if (output.out !== void 0 && typeof output.out !== "string") {
411
- errors.push("audit.output.out must be a string");
412
- }
413
- }
414
- }
415
- }
416
- }
417
- if (cfg.test !== void 0) {
418
- if (typeof cfg.test !== "object" || cfg.test === null) {
419
- errors.push("test must be an object");
420
- } else {
421
- if (cfg.test.disableTimeouts !== void 0 && typeof cfg.test.disableTimeouts !== "boolean") {
422
- errors.push("test.disableTimeouts must be a boolean when provided");
423
- }
424
- const testTimeoutFields = [
425
- "actionTimeoutMs",
426
- "assertionTimeoutMs",
427
- "navigationTimeoutMs",
428
- "componentReadyTimeoutMs"
429
- ];
430
- for (const field of testTimeoutFields) {
431
- const value = cfg.test[field];
432
- if (value !== void 0) {
433
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
434
- errors.push(`test.${field} must be a non-negative number when provided`);
435
- }
436
- }
437
- }
438
- if (cfg.test.components !== void 0) {
439
- if (!Array.isArray(cfg.test.components)) {
440
- errors.push("test.components must be an array");
441
- } else {
442
- cfg.test.components.forEach((comp, idx) => {
443
- if (typeof comp !== "object" || comp === null) {
444
- errors.push(`test.components[${idx}] must be an object`);
445
- } else {
446
- if (typeof comp.name !== "string") {
447
- errors.push(`test.components[${idx}].name must be a string`);
448
- }
449
- if (comp.contractPath !== void 0 && typeof comp.contractPath !== "string") {
450
- errors.push(`test.components[${idx}].contractPath must be a string when provided`);
451
- }
452
- if (comp.strategyPath !== void 0 && typeof comp.strategyPath !== "string") {
453
- errors.push(`test.components[${idx}].strategyPath must be a string when provided`);
454
- }
455
- if (comp.strictness !== void 0 && !["minimal", "balanced", "strict", "paranoid"].includes(comp.strictness)) {
456
- errors.push(`test.components[${idx}].strictness must be one of: minimal, balanced, strict, paranoid`);
457
- }
458
- if (comp.disableTimeouts !== void 0 && typeof comp.disableTimeouts !== "boolean") {
459
- errors.push(`test.components[${idx}].disableTimeouts must be a boolean when provided`);
460
- }
461
- const componentTimeoutFields = [
462
- "actionTimeoutMs",
463
- "assertionTimeoutMs",
464
- "navigationTimeoutMs",
465
- "componentReadyTimeoutMs"
466
- ];
467
- for (const field of componentTimeoutFields) {
468
- const value = comp[field];
469
- if (value !== void 0) {
470
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
471
- errors.push(`test.components[${idx}].${field} must be a non-negative number when provided`);
472
- }
473
- }
474
- }
475
- }
476
- });
477
- }
478
- }
479
- if (cfg.test.strictness !== void 0) {
480
- if (!["minimal", "balanced", "strict", "paranoid"].includes(cfg.test.strictness)) {
481
- errors.push("test.strictness must be one of: minimal, balanced, strict, paranoid");
482
- }
483
- }
484
- }
485
- }
486
- if (cfg.contracts !== void 0) {
487
- if (!Array.isArray(cfg.contracts)) {
488
- errors.push("contracts must be an array");
489
- } else {
490
- cfg.contracts.forEach((contract, idx) => {
491
- if (typeof contract !== "object" || contract === null) {
492
- errors.push(`contracts[${idx}] must be an object`);
493
- } else {
494
- if (typeof contract.src !== "string") {
495
- errors.push(`contracts[${idx}].src is required and must be a string`);
496
- }
497
- if (contract.out !== void 0 && typeof contract.out !== "string") {
498
- errors.push(`contracts[${idx}].out must be a string`);
499
- }
500
- }
501
- });
502
- }
503
- }
504
- return { valid: errors.length === 0, errors };
505
- }
506
- async function loadConfigFile(filePath) {
507
- try {
508
- const ext = path3__default.default.extname(filePath);
509
- if (ext === ".json") {
510
- const content = await fs3__default.default.readFile(filePath, "utf-8");
511
- return JSON.parse(content);
512
- } else if ([".js", ".mjs", ".cjs", ".ts"].includes(ext)) {
513
- const imported = await import(filePath);
514
- return imported.default || imported;
515
- }
516
- return null;
517
- } catch {
518
- return null;
519
- }
520
- }
521
- async function loadConfig(cwd = process.cwd()) {
522
- const configNames = [
523
- "ariaease.config.js",
524
- "ariaease.config.mjs",
525
- "ariaease.config.cjs",
526
- "ariaease.config.json",
527
- "ariaease.config.ts"
528
- ];
529
- let loadedConfig = null;
530
- let foundPath = null;
531
- const errors = [];
532
- for (const name of configNames) {
533
- const configPath = path3__default.default.resolve(cwd, name);
534
- if (await fs3__default.default.pathExists(configPath)) {
535
- foundPath = configPath;
536
- loadedConfig = await loadConfigFile(configPath);
537
- if (loadedConfig === null) {
538
- errors.push(`Found config at ${name} but failed to load it. Check for syntax errors.`);
539
- continue;
540
- }
541
- const validation = validateConfig(loadedConfig);
542
- if (!validation.valid) {
543
- errors.push(`Config validation failed in ${name}:`);
544
- errors.push(...validation.errors.map((err) => ` - ${err}`));
545
- loadedConfig = null;
546
- continue;
547
- }
548
- break;
549
- }
550
- }
551
- return {
552
- config: loadedConfig || {},
553
- configPath: loadedConfig ? foundPath : null,
554
- errors
555
- };
556
- }
557
- var init_configLoader = __esm({
558
- "src/utils/cli/configLoader.ts"() {
559
- }
560
- });
561
-
562
- // src/utils/test/src/component-strategies/MenuComponentStrategy.ts
563
- var MenuComponentStrategy_exports = {};
564
- __export(MenuComponentStrategy_exports, {
565
- MenuComponentStrategy: () => MenuComponentStrategy
566
- });
567
- var MenuComponentStrategy;
568
- var init_MenuComponentStrategy = __esm({
569
- "src/utils/test/src/component-strategies/MenuComponentStrategy.ts"() {
570
- MenuComponentStrategy = class {
571
- constructor(mainSelector, selectors, actionTimeoutMs = 400, assertionTimeoutMs = 400) {
572
- this.mainSelector = mainSelector;
573
- this.selectors = selectors;
574
- this.actionTimeoutMs = actionTimeoutMs;
575
- this.assertionTimeoutMs = assertionTimeoutMs;
576
- }
577
- async resetState(page) {
578
- if (!this.selectors.popup) return;
579
- const popupSelector = this.selectors.popup;
580
- const popupElement = page.locator(popupSelector).first();
581
- const isPopupVisible = await popupElement.isVisible().catch(() => false);
582
- if (!isPopupVisible) return;
583
- let menuClosed = false;
584
- let closeSelector = this.selectors.input;
585
- if (!closeSelector && this.selectors.focusable) {
586
- closeSelector = this.selectors.focusable;
587
- } else if (!closeSelector) {
588
- closeSelector = this.selectors.main;
589
- }
590
- if (closeSelector) {
591
- const closeElement = page.locator(closeSelector).first();
592
- await closeElement.focus();
593
- await page.keyboard.press("Escape");
594
- menuClosed = await test.expect(popupElement).toBeHidden({ timeout: this.assertionTimeoutMs }).then(() => true).catch(() => false);
595
- }
596
- if (!menuClosed && this.selectors.main) {
597
- const triggerElement = page.locator(this.selectors.main).first();
598
- await triggerElement.click({ timeout: this.actionTimeoutMs });
599
- menuClosed = await test.expect(popupElement).toBeHidden({ timeout: this.assertionTimeoutMs }).then(() => true).catch(() => false);
600
- }
601
- if (!menuClosed) {
602
- await page.mouse.click(10, 10);
603
- menuClosed = await test.expect(popupElement).toBeHidden({ timeout: this.assertionTimeoutMs }).then(() => true).catch(() => false);
604
- }
605
- if (!menuClosed) {
606
- throw new Error(
607
- `\u274C FATAL: Cannot close menu between tests. Menu remains visible after trying:
1
+ 'use strict';var playwright=require('playwright'),xe=require('path'),Be=require('fs-extra'),test=require('@playwright/test'),url=require('url'),fs=require('fs'),B=require('chalk'),Mt=require('readline');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var xe__default=/*#__PURE__*/_interopDefault(xe);var Be__default=/*#__PURE__*/_interopDefault(Be);var B__default=/*#__PURE__*/_interopDefault(B);var Mt__default=/*#__PURE__*/_interopDefault(Mt);var wt=Object.defineProperty;var L=(c,e)=>()=>(c&&(e=c(c=0)),e);var Y=(c,e)=>{for(var t in e)wt(c,t,{get:e[t],enumerable:true});};async function bt(){return ee||(ee=await playwright.chromium.launch({headless:true,args:["--disable-extensions","--disable-blink-features=AutomationControlled"]})),ee}async function Tt(){return te||(te=await(await bt()).newContext({permissions:[],ignoreHTTPSErrors:true})),te}async function We(){return await(await Tt()).newPage()}async function He(){te&&(await te.close(),te=null),ee&&(await ee.close(),ee=null);}var ee,te,be=L(()=>{ee=null,te=null;});function se(c){return c==="required"||c==="recommended"||c==="optional"?c:$t}function oe(c){return c==="minimal"||c==="balanced"||c==="strict"||c==="paranoid"?c:"balanced"}function Oe(c,e){return {minimal:{required:"error",recommended:"ignore",optional:"ignore"},balanced:{required:"error",recommended:"warning",optional:"ignore"},strict:{required:"error",recommended:"error",optional:"warning"},paranoid:{required:"error",recommended:"error",optional:"error"}}[e][c]}var $t,Te=L(()=>{$t="required";});var Je={};Y(Je,{loadConfig:()=>kt});function St(c){let e=[];if(!c||typeof c!="object")return e.push("Config must be an object"),{valid:false,errors:e};let t=c;if(t.audit!==void 0){if(typeof t.audit!="object"||t.audit===null)e.push("audit must be an object");else if(t.audit.urls!==void 0&&(Array.isArray(t.audit.urls)?t.audit.urls.some(r=>typeof r!="string")&&e.push("audit.urls must contain only strings"):e.push("audit.urls must be an array")),t.audit.output!==void 0)if(typeof t.audit.output!="object")e.push("audit.output must be an object");else {let r=t.audit.output;r.format!==void 0&&(["json","csv","html","all"].includes(r.format)||e.push("audit.output.format must be one of: json, csv, html, all")),r.out!==void 0&&typeof r.out!="string"&&e.push("audit.output.out must be a string");}}if(t.test!==void 0)if(typeof t.test!="object"||t.test===null)e.push("test must be an object");else {t.test.disableTimeouts!==void 0&&typeof t.test.disableTimeouts!="boolean"&&e.push("test.disableTimeouts must be a boolean when provided");let r=["actionTimeoutMs","assertionTimeoutMs","navigationTimeoutMs","componentReadyTimeoutMs"];for(let i of r){let n=t.test[i];n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<0)&&e.push(`test.${i} must be a non-negative number when provided`);}t.test.components!==void 0&&(Array.isArray(t.test.components)?t.test.components.forEach((i,n)=>{if(typeof i!="object"||i===null)e.push(`test.components[${n}] must be an object`);else {typeof i.name!="string"&&e.push(`test.components[${n}].name must be a string`),i.contractPath!==void 0&&typeof i.contractPath!="string"&&e.push(`test.components[${n}].contractPath must be a string when provided`),i.strategyPath!==void 0&&typeof i.strategyPath!="string"&&e.push(`test.components[${n}].strategyPath must be a string when provided`),i.strictness!==void 0&&!["minimal","balanced","strict","paranoid"].includes(i.strictness)&&e.push(`test.components[${n}].strictness must be one of: minimal, balanced, strict, paranoid`),i.disableTimeouts!==void 0&&typeof i.disableTimeouts!="boolean"&&e.push(`test.components[${n}].disableTimeouts must be a boolean when provided`);let o=["actionTimeoutMs","assertionTimeoutMs","navigationTimeoutMs","componentReadyTimeoutMs"];for(let a of o){let p=i[a];p!==void 0&&(typeof p!="number"||!Number.isFinite(p)||p<0)&&e.push(`test.components[${n}].${a} must be a non-negative number when provided`);}}}):e.push("test.components must be an array")),t.test.strictness!==void 0&&(["minimal","balanced","strict","paranoid"].includes(t.test.strictness)||e.push("test.strictness must be one of: minimal, balanced, strict, paranoid"));}return t.contracts!==void 0&&(Array.isArray(t.contracts)?t.contracts.forEach((r,i)=>{typeof r!="object"||r===null?e.push(`contracts[${i}] must be an object`):(typeof r.src!="string"&&e.push(`contracts[${i}].src is required and must be a string`),r.out!==void 0&&typeof r.out!="string"&&e.push(`contracts[${i}].out must be a string`));}):e.push("contracts must be an array")),{valid:e.length===0,errors:e}}async function Ct(c){try{let e=xe__default.default.extname(c);if(e===".json"){let t=await Be__default.default.readFile(c,"utf-8");return JSON.parse(t)}else if([".js",".mjs",".cjs",".ts"].includes(e)){let t=await import(c);return t.default||t}return null}catch{return null}}async function kt(c=process.cwd()){let e=["ariaease.config.js","ariaease.config.mjs","ariaease.config.cjs","ariaease.config.json","ariaease.config.ts"],t=null,r=null,i=[];for(let n of e){let o=xe__default.default.resolve(c,n);if(await Be__default.default.pathExists(o)){if(r=o,t=await Ct(o),t===null){i.push(`Found config at ${n} but failed to load it. Check for syntax errors.`);continue}let a=St(t);if(!a.valid){i.push(`Config validation failed in ${n}:`),i.push(...a.errors.map(p=>` - ${p}`)),t=null;continue}break}}return {config:t||{},configPath:t?r:null,errors:i}}var Ke=L(()=>{});var ze={};Y(ze,{MenuComponentStrategy:()=>Se});var Se,Ge=L(()=>{Se=class{constructor(e,t,r=400,i=400){this.mainSelector=e;this.selectors=t;this.actionTimeoutMs=r;this.assertionTimeoutMs=i;}async resetState(e){if(!this.selectors.popup)return;let t=this.selectors.popup,r=e.locator(t).first();if(!await r.isVisible().catch(()=>false))return;let n=false,o=this.selectors.input;if(!o&&this.selectors.focusable?o=this.selectors.focusable:o||(o=this.selectors.main),o&&(await e.locator(o).first().focus(),await e.keyboard.press("Escape"),n=await test.expect(r).toBeHidden({timeout:this.assertionTimeoutMs}).then(()=>true).catch(()=>false)),!n&&this.selectors.main&&(await e.locator(this.selectors.main).first().click({timeout:this.actionTimeoutMs}),n=await test.expect(r).toBeHidden({timeout:this.assertionTimeoutMs}).then(()=>true).catch(()=>false)),n||(await e.mouse.click(10,10),n=await test.expect(r).toBeHidden({timeout:this.assertionTimeoutMs}).then(()=>true).catch(()=>false)),!n)throw new Error(`\u274C FATAL: Cannot close menu between tests. Menu remains visible after trying:
608
2
  1. Escape key
609
3
  2. Clicking trigger
610
4
  3. Clicking outside
611
- This indicates a problem with the menu component's close functionality.`
612
- );
613
- }
614
- if (this.selectors.input) {
615
- await page.locator(this.selectors.input).first().clear();
616
- }
617
- if (this.selectors.main) {
618
- const triggerElement = page.locator(this.selectors.main).first();
619
- await triggerElement.focus();
620
- }
621
- }
622
- async shouldSkipTest(test, page) {
623
- const requiresSubmenu = test.action.some(
624
- (act) => act.target === "submenu" || act.target === "submenuTrigger" || act.target === "submenuItems"
625
- ) || test.assertions.some(
626
- (assertion) => assertion.target === "submenu" || assertion.target === "submenuTrigger" || assertion.target === "submenuItems"
627
- );
628
- if (!requiresSubmenu) {
629
- return false;
630
- }
631
- const submenuTriggerSelector = this.selectors.submenuTrigger;
632
- if (!submenuTriggerSelector) {
633
- return true;
634
- }
635
- const submenuTriggerCount = await page.locator(submenuTriggerSelector).count();
636
- return submenuTriggerCount === 0;
637
- }
638
- getMainSelector() {
639
- return this.mainSelector;
640
- }
641
- };
642
- }
643
- });
644
-
645
- // src/utils/test/src/component-strategies/AccordionComponentStrategy.ts
646
- var AccordionComponentStrategy_exports = {};
647
- __export(AccordionComponentStrategy_exports, {
648
- AccordionComponentStrategy: () => AccordionComponentStrategy
649
- });
650
- var AccordionComponentStrategy;
651
- var init_AccordionComponentStrategy = __esm({
652
- "src/utils/test/src/component-strategies/AccordionComponentStrategy.ts"() {
653
- AccordionComponentStrategy = class {
654
- constructor(mainSelector, selectors, actionTimeoutMs = 400, assertionTimeoutMs = 400) {
655
- this.mainSelector = mainSelector;
656
- this.selectors = selectors;
657
- this.actionTimeoutMs = actionTimeoutMs;
658
- this.assertionTimeoutMs = assertionTimeoutMs;
659
- }
660
- async resetState(page) {
661
- if (!this.selectors.panel || !this.selectors.trigger || this.selectors.popup) {
662
- return;
663
- }
664
- const triggerSelector = this.selectors.trigger;
665
- const panelSelector = this.selectors.panel;
666
- if (!triggerSelector || !panelSelector) return;
667
- const allTriggers = await page.locator(triggerSelector).all();
668
- for (const trigger of allTriggers) {
669
- const isExpanded = await trigger.getAttribute("aria-expanded") === "true";
670
- const triggerPanel = await trigger.getAttribute("aria-controls");
671
- if (isExpanded && triggerPanel) {
672
- await trigger.click({ timeout: this.actionTimeoutMs });
673
- const panel = page.locator(`#${triggerPanel}`);
674
- await test.expect(panel).toBeHidden({ timeout: this.assertionTimeoutMs }).catch(() => {
675
- });
676
- }
677
- }
678
- }
679
- async shouldSkipTest() {
680
- return false;
681
- }
682
- getMainSelector() {
683
- return this.mainSelector;
684
- }
685
- };
686
- }
687
- });
688
-
689
- // src/utils/test/src/component-strategies/ComboboxComponentStrategy.ts
690
- var ComboboxComponentStrategy_exports = {};
691
- __export(ComboboxComponentStrategy_exports, {
692
- ComboboxComponentStrategy: () => ComboboxComponentStrategy
693
- });
694
- var ComboboxComponentStrategy;
695
- var init_ComboboxComponentStrategy = __esm({
696
- "src/utils/test/src/component-strategies/ComboboxComponentStrategy.ts"() {
697
- ComboboxComponentStrategy = class {
698
- constructor(mainSelector, selectors, actionTimeoutMs = 400, assertionTimeoutMs = 400) {
699
- this.mainSelector = mainSelector;
700
- this.selectors = selectors;
701
- this.actionTimeoutMs = actionTimeoutMs;
702
- this.assertionTimeoutMs = assertionTimeoutMs;
703
- }
704
- async resetState(page) {
705
- if (!this.selectors.popup) return;
706
- const popupSelector = this.selectors.popup;
707
- const popupElement = page.locator(popupSelector).first();
708
- const isPopupVisible = await popupElement.isVisible().catch(() => false);
709
- if (!isPopupVisible) return;
710
- let popupClosed = false;
711
- let closeSelector = this.selectors.input;
712
- if (!closeSelector && this.selectors.focusable) {
713
- closeSelector = this.selectors.focusable;
714
- } else if (!closeSelector) {
715
- closeSelector = this.selectors.button;
716
- }
717
- if (closeSelector) {
718
- const closeElement = page.locator(closeSelector).first();
719
- await closeElement.focus();
720
- await page.keyboard.press("Escape");
721
- popupClosed = await test.expect(popupElement).toBeHidden({ timeout: this.assertionTimeoutMs }).then(() => true).catch(() => false);
722
- }
723
- if (!popupClosed && this.selectors.button) {
724
- const buttonElement = page.locator(this.selectors.button).first();
725
- await buttonElement.click({ timeout: this.actionTimeoutMs });
726
- popupClosed = await test.expect(popupElement).toBeHidden({ timeout: this.assertionTimeoutMs }).then(() => true).catch(() => false);
727
- }
728
- if (!popupClosed) {
729
- await page.mouse.click(10, 10);
730
- popupClosed = await test.expect(popupElement).toBeHidden({ timeout: this.assertionTimeoutMs }).then(() => true).catch(() => false);
731
- }
732
- if (!popupClosed) {
733
- throw new Error(
734
- `\u274C FATAL: Cannot close combobox popup between tests. Popup remains visible after trying:
5
+ This indicates a problem with the menu component's close functionality.`);this.selectors.input&&await e.locator(this.selectors.input).first().clear(),this.selectors.main&&await e.locator(this.selectors.main).first().focus();}async shouldSkipTest(e,t){if(!(e.action.some(o=>o.target==="submenu"||o.target==="submenuTrigger"||o.target==="submenuItems")||e.assertions.some(o=>o.target==="submenu"||o.target==="submenuTrigger"||o.target==="submenuItems")))return false;let i=this.selectors.submenuTrigger;return i?await t.locator(i).count()===0:true}getMainSelector(){return this.mainSelector}};});var Ne={};Y(Ne,{AccordionComponentStrategy:()=>Ce});var Ce,Ye=L(()=>{Ce=class{constructor(e,t,r=400,i=400){this.mainSelector=e;this.selectors=t;this.actionTimeoutMs=r;this.assertionTimeoutMs=i;}async resetState(e){if(!this.selectors.panel||!this.selectors.trigger||this.selectors.popup)return;let t=this.selectors.trigger,r=this.selectors.panel;if(!t||!r)return;let i=await e.locator(t).all();for(let n of i){let o=await n.getAttribute("aria-expanded")==="true",a=await n.getAttribute("aria-controls");if(o&&a){await n.click({timeout:this.actionTimeoutMs});let p=e.locator(`#${a}`);await test.expect(p).toBeHidden({timeout:this.assertionTimeoutMs}).catch(()=>{});}}}async shouldSkipTest(){return false}getMainSelector(){return this.mainSelector}};});var Qe={};Y(Qe,{ComboboxComponentStrategy:()=>Ae});var Ae,Xe=L(()=>{Ae=class{constructor(e,t,r=400,i=400){this.mainSelector=e;this.selectors=t;this.actionTimeoutMs=r;this.assertionTimeoutMs=i;}async resetState(e){if(!this.selectors.popup)return;let t=this.selectors.popup,r=e.locator(t).first();if(!await r.isVisible().catch(()=>false))return;let n=false,o=this.selectors.input;if(!o&&this.selectors.focusable?o=this.selectors.focusable:o||(o=this.selectors.button),o&&(await e.locator(o).first().focus(),await e.keyboard.press("Escape"),n=await test.expect(r).toBeHidden({timeout:this.assertionTimeoutMs}).then(()=>true).catch(()=>false)),!n&&this.selectors.button&&(await e.locator(this.selectors.button).first().click({timeout:this.actionTimeoutMs}),n=await test.expect(r).toBeHidden({timeout:this.assertionTimeoutMs}).then(()=>true).catch(()=>false)),n||(await e.mouse.click(10,10),n=await test.expect(r).toBeHidden({timeout:this.assertionTimeoutMs}).then(()=>true).catch(()=>false)),!n)throw new Error(`\u274C FATAL: Cannot close combobox popup between tests. Popup remains visible after trying:
735
6
  1. Escape key
736
7
  2. Clicking button
737
8
  3. Clicking outside
738
- This indicates a problem with the combobox component's close functionality.`
739
- );
740
- }
741
- if (this.selectors.input) {
742
- await page.locator(this.selectors.input).first().clear();
743
- }
744
- }
745
- async shouldSkipTest() {
746
- return false;
747
- }
748
- getMainSelector() {
749
- return this.mainSelector;
750
- }
751
- };
752
- }
753
- });
754
-
755
- // src/utils/test/src/component-strategies/TabsComponentStrategy.ts
756
- var TabsComponentStrategy_exports = {};
757
- __export(TabsComponentStrategy_exports, {
758
- TabsComponentStrategy: () => TabsComponentStrategy
759
- });
760
- var TabsComponentStrategy;
761
- var init_TabsComponentStrategy = __esm({
762
- "src/utils/test/src/component-strategies/TabsComponentStrategy.ts"() {
763
- TabsComponentStrategy = class {
764
- constructor(mainSelector, selectors) {
765
- this.mainSelector = mainSelector;
766
- this.selectors = selectors;
767
- }
768
- async resetState() {
769
- }
770
- async shouldSkipTest(test, page) {
771
- if (test.isVertical !== void 0 && this.selectors.tablist) {
772
- const tablistSelector = this.selectors.tablist;
773
- const tablist = page.locator(tablistSelector).first();
774
- const orientation = await tablist.getAttribute("aria-orientation");
775
- const isVertical = orientation === "vertical";
776
- if (test.isVertical !== isVertical) {
777
- return true;
778
- }
779
- }
780
- return false;
781
- }
782
- getMainSelector() {
783
- return this.mainSelector;
784
- }
785
- };
786
- }
787
- });
788
- var StrategyRegistry;
789
- var init_StrategyRegistry = __esm({
790
- "src/utils/test/src/StrategyRegistry.ts"() {
791
- StrategyRegistry = class {
792
- builtInStrategies = /* @__PURE__ */ new Map();
793
- constructor() {
794
- this.registerBuiltInStrategies();
795
- }
796
- /**
797
- * Register built-in strategies
798
- */
799
- registerBuiltInStrategies() {
800
- this.builtInStrategies.set(
801
- "menu",
802
- () => Promise.resolve().then(() => (init_MenuComponentStrategy(), MenuComponentStrategy_exports)).then(
803
- (m) => m.MenuComponentStrategy
804
- )
805
- );
806
- this.builtInStrategies.set(
807
- "accordion",
808
- () => Promise.resolve().then(() => (init_AccordionComponentStrategy(), AccordionComponentStrategy_exports)).then(
809
- (m) => m.AccordionComponentStrategy
810
- )
811
- );
812
- this.builtInStrategies.set(
813
- "combobox",
814
- () => Promise.resolve().then(() => (init_ComboboxComponentStrategy(), ComboboxComponentStrategy_exports)).then(
815
- (m) => m.ComboboxComponentStrategy
816
- )
817
- );
818
- this.builtInStrategies.set(
819
- "tabs",
820
- () => Promise.resolve().then(() => (init_TabsComponentStrategy(), TabsComponentStrategy_exports)).then(
821
- (m) => m.TabsComponentStrategy
822
- )
823
- );
824
- }
825
- /**
826
- * Load a strategy - either from custom path or built-in registry
827
- * @param componentName - Component name (e.g., "menu", "accordion")
828
- * @param customStrategyPath - Optional custom strategy file path
829
- * @returns Strategy constructor function or null if not found
830
- */
831
- async loadStrategy(componentName, customStrategyPath, configBaseDir) {
832
- try {
833
- if (customStrategyPath) {
834
- try {
835
- const resolvedCustomPath = path3__default.default.isAbsolute(customStrategyPath) ? customStrategyPath : path3__default.default.resolve(configBaseDir || process.cwd(), customStrategyPath);
836
- const customModule = await import(url.pathToFileURL(resolvedCustomPath).href);
837
- const strategy = customModule.default || customModule;
838
- if (!strategy) {
839
- throw new Error(`No default export found in ${customStrategyPath}`);
840
- }
841
- return strategy;
842
- } catch (error) {
843
- throw new Error(
844
- `Failed to load custom strategy from ${customStrategyPath}: ${error instanceof Error ? error.message : String(error)}`
845
- );
846
- }
847
- }
848
- const builtInLoader = this.builtInStrategies.get(componentName);
849
- if (!builtInLoader) {
850
- return null;
851
- }
852
- return builtInLoader();
853
- } catch (error) {
854
- throw new Error(
855
- `Strategy loading failed for ${componentName}: ${error instanceof Error ? error.message : String(error)}`
856
- );
857
- }
858
- }
859
- /**
860
- * Check if a strategy exists (either built-in or custom path provided)
861
- */
862
- has(componentName, customStrategyPath) {
863
- return !!customStrategyPath || this.builtInStrategies.has(componentName);
864
- }
865
- };
866
- }
867
- });
868
- var ComponentDetector;
869
- var init_ComponentDetector = __esm({
870
- "src/utils/test/src/ComponentDetector.ts"() {
871
- init_StrategyRegistry();
872
- ComponentDetector = class {
873
- static strategyRegistry = new StrategyRegistry();
874
- static isComponentConfig(value) {
875
- return typeof value === "object" && value !== null;
876
- }
877
- /**
878
- * Detect and instantiate a component strategy
879
- * Supports:
880
- * - Built-in strategies (menu, accordion, combobox, tabs)
881
- * - Custom strategies via config (strategyPath)
882
- * - Custom contract paths via config (path)
883
- * @param componentName - Component name
884
- * @param componentConfig - Component config from ariaease.config.js
885
- * @param actionTimeoutMs - Action timeout in milliseconds
886
- * @param assertionTimeoutMs - Assertion timeout in milliseconds
887
- * @returns Instantiated ComponentStrategy or null
888
- */
889
- static async detect(componentName, componentConfig, actionTimeoutMs = 400, assertionTimeoutMs = 400, configBaseDir) {
890
- const typedComponentConfig = this.isComponentConfig(componentConfig) ? componentConfig : void 0;
891
- const contractPath = typedComponentConfig?.contractPath;
892
- if (!contractPath) {
893
- throw new Error(`Contract path not found for component: ${componentName}`);
894
- }
895
- const resolvedPath = (() => {
896
- if (path3__default.default.isAbsolute(contractPath)) return contractPath;
897
- if (configBaseDir) {
898
- const configResolved = path3__default.default.resolve(configBaseDir, contractPath);
899
- try {
900
- fs.readFileSync(configResolved, "utf-8");
901
- return configResolved;
902
- } catch {
903
- }
904
- }
905
- const cwdResolved = path3__default.default.resolve(process.cwd(), contractPath);
906
- try {
907
- fs.readFileSync(cwdResolved, "utf-8");
908
- return cwdResolved;
909
- } catch {
910
- return new URL(contractPath, (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).pathname;
911
- }
912
- })();
913
- const contractData = fs.readFileSync(resolvedPath, "utf-8");
914
- const componentContract = JSON.parse(contractData);
915
- const selectors = componentContract.selectors;
916
- const strategyClass = await this.strategyRegistry.loadStrategy(
917
- componentName,
918
- typedComponentConfig?.strategyPath,
919
- configBaseDir
920
- );
921
- if (!strategyClass) {
922
- return null;
923
- }
924
- const mainSelector = selectors.main;
925
- if (componentName === "tabs") {
926
- return new strategyClass(mainSelector, selectors);
927
- }
928
- return new strategyClass(
929
- mainSelector,
930
- selectors,
931
- actionTimeoutMs,
932
- assertionTimeoutMs
933
- );
934
- }
935
- };
936
- }
937
- });
938
-
939
- // src/utils/test/src/RelativeTargetResolver.ts
940
- var RelativeTargetResolver_exports = {};
941
- __export(RelativeTargetResolver_exports, {
942
- RelativeTargetResolver: () => RelativeTargetResolver
943
- });
944
- var RelativeTargetResolver;
945
- var init_RelativeTargetResolver = __esm({
946
- "src/utils/test/src/RelativeTargetResolver.ts"() {
947
- RelativeTargetResolver = class {
948
- /**
949
- * Resolve a relative target like "first", "second", "last", "next", "previous"
950
- * @param page Playwright page instance
951
- * @param selector Base selector to find elements
952
- * @param relative Relative position (first, second, last, next, previous)
953
- * @returns The resolved Locator or null if not found
954
- */
955
- static async resolve(page, selector, relative) {
956
- const items = await page.locator(selector).all();
957
- switch (relative) {
958
- case "first":
959
- return items[0];
960
- case "second":
961
- return items[1];
962
- case "last":
963
- return items[items.length - 1];
964
- case "next": {
965
- const currentIndex = await page.evaluate(([sel]) => {
966
- const items2 = Array.from(document.querySelectorAll(sel));
967
- return items2.indexOf(document.activeElement);
968
- }, [selector]);
969
- const nextIndex = (currentIndex + 1) % items.length;
970
- return items[nextIndex];
971
- }
972
- case "previous": {
973
- const currentIndex = await page.evaluate(([sel]) => {
974
- const items2 = Array.from(document.querySelectorAll(sel));
975
- return items2.indexOf(document.activeElement);
976
- }, [selector]);
977
- const prevIndex = (currentIndex - 1 + items.length) % items.length;
978
- return items[prevIndex];
979
- }
980
- default:
981
- return null;
982
- }
983
- }
984
- };
985
- }
986
- });
987
-
988
- // src/utils/test/src/ActionExecutor.ts
989
- var ActionExecutor;
990
- var init_ActionExecutor = __esm({
991
- "src/utils/test/src/ActionExecutor.ts"() {
992
- init_RelativeTargetResolver();
993
- ActionExecutor = class {
994
- constructor(page, selectors, timeoutMs = 400) {
995
- this.page = page;
996
- this.selectors = selectors;
997
- this.timeoutMs = timeoutMs;
998
- }
999
- /**
1000
- * Check if error is due to browser/page being closed
1001
- */
1002
- isBrowserClosedError(error) {
1003
- return error instanceof Error && error.message.includes("Target page, context or browser has been closed");
1004
- }
1005
- /**
1006
- * Execute focus action
1007
- */
1008
- /**
1009
- * Execute focus action (supports absolute, relative, and virtual focus)
1010
- * @param target - selector key (e.g. "input", "button", "relative", or "virtual")
1011
- * @param relativeTarget - for relative focus (e.g. "first", "last")
1012
- * @param virtualId - for virtual focus (aria-activedescendant value)
1013
- */
1014
- async focus(target, relativeTarget, virtualId) {
1015
- try {
1016
- if (target === "virtual" && virtualId) {
1017
- const mainSelector = this.selectors.main;
1018
- if (!mainSelector) {
1019
- return { success: false, error: `Main selector not defined for virtual focus.` };
1020
- }
1021
- const main = this.page.locator(mainSelector).first();
1022
- const exists = await main.count();
1023
- if (!exists) {
1024
- return { success: false, error: `Main element not found for virtual focus.` };
1025
- }
1026
- await main.evaluate((el, id) => {
1027
- el.setAttribute("aria-activedescendant", id);
1028
- }, virtualId);
1029
- return { success: true };
1030
- }
1031
- if (target === "relative" && relativeTarget) {
1032
- const relativeSelector = this.selectors.relative;
1033
- if (!relativeSelector) {
1034
- return { success: false, error: `Relative selector not defined for focus action.` };
1035
- }
1036
- const element = await RelativeTargetResolver.resolve(this.page, relativeSelector, relativeTarget);
1037
- if (!element) {
1038
- return { success: false, error: `Could not resolve relative target ${relativeTarget} for focus.` };
1039
- }
1040
- await element.focus({ timeout: this.timeoutMs });
1041
- return { success: true };
1042
- }
1043
- const selector = this.selectors[target];
1044
- if (!selector) {
1045
- return { success: false, error: `Selector for focus target ${target} not found.` };
1046
- }
1047
- await this.page.locator(selector).first().focus({ timeout: this.timeoutMs });
1048
- return { success: true };
1049
- } catch (error) {
1050
- if (this.isBrowserClosedError(error)) {
1051
- return {
1052
- success: false,
1053
- error: `CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`,
1054
- shouldBreak: true
1055
- };
1056
- }
1057
- return {
1058
- success: false,
1059
- error: `Failed to focus ${target}: ${error instanceof Error ? error.message : String(error)}`
1060
- };
1061
- }
1062
- }
1063
- /**
1064
- * Execute type/fill action
1065
- */
1066
- async type(target, value) {
1067
- try {
1068
- const selector = this.selectors[target];
1069
- if (!selector) {
1070
- return { success: false, error: `Selector for type target ${target} not found.` };
1071
- }
1072
- await this.page.locator(selector).first().fill(value, { timeout: this.timeoutMs });
1073
- return { success: true };
1074
- } catch (error) {
1075
- if (this.isBrowserClosedError(error)) {
1076
- return {
1077
- success: false,
1078
- error: `CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`,
1079
- shouldBreak: true
1080
- };
1081
- }
1082
- return {
1083
- success: false,
1084
- error: `Failed to type into ${target}: ${error instanceof Error ? error.message : String(error)}`
1085
- };
1086
- }
1087
- }
1088
- /**
1089
- * Execute click action
1090
- */
1091
- async click(target, relativeTarget) {
1092
- try {
1093
- if (target === "document") {
1094
- await this.page.mouse.click(10, 10);
1095
- return { success: true };
1096
- }
1097
- if (target === "relative" && relativeTarget) {
1098
- const relativeSelector = this.selectors.relative;
1099
- if (!relativeSelector) {
1100
- return { success: false, error: `Relative selector not defined for click action.` };
1101
- }
1102
- const element = await RelativeTargetResolver.resolve(this.page, relativeSelector, relativeTarget);
1103
- if (!element) {
1104
- return { success: false, error: `Could not resolve relative target ${relativeTarget} for click.` };
1105
- }
1106
- await element.click({ timeout: this.timeoutMs });
1107
- return { success: true };
1108
- }
1109
- const selector = this.selectors[target];
1110
- if (!selector) {
1111
- return { success: false, error: `Selector for action target ${target} not found.` };
1112
- }
1113
- await this.page.locator(selector).first().click({ timeout: this.timeoutMs });
1114
- return { success: true };
1115
- } catch (error) {
1116
- if (this.isBrowserClosedError(error)) {
1117
- return {
1118
- success: false,
1119
- error: `CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`,
1120
- shouldBreak: true
1121
- };
1122
- }
1123
- return {
1124
- success: false,
1125
- error: `Failed to click ${target}: ${error instanceof Error ? error.message : String(error)}`
1126
- };
1127
- }
1128
- }
1129
- /**
1130
- * Execute keypress action
1131
- */
1132
- async keypress(target, key) {
1133
- try {
1134
- const keyMap = {
1135
- "Space": "Space",
1136
- "Enter": "Enter",
1137
- "Escape": "Escape",
1138
- "Arrow Up": "ArrowUp",
1139
- "Arrow Down": "ArrowDown",
1140
- "Arrow Left": "ArrowLeft",
1141
- "Arrow Right": "ArrowRight",
1142
- "Home": "Home",
1143
- "End": "End",
1144
- "Tab": "Tab"
1145
- };
1146
- let keyValue = keyMap[key] || key;
1147
- if (keyValue === "Space") {
1148
- keyValue = " ";
1149
- } else if (keyValue.includes(" ")) {
1150
- keyValue = keyValue.replace(/ /g, "");
1151
- }
1152
- if (target === "focusable" && ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Escape", "Home", "End", "Tab", "Shift+Tab"].includes(keyValue)) {
1153
- await this.page.keyboard.press(keyValue);
1154
- return { success: true };
1155
- }
1156
- const selector = this.selectors[target];
1157
- if (!selector) {
1158
- return { success: false, error: `Selector for keypress target ${target} not found.` };
1159
- }
1160
- const locator = this.page.locator(selector).first();
1161
- const elementCount = await locator.count();
1162
- if (elementCount === 0) {
1163
- return {
1164
- success: false,
1165
- error: `${target} element not found.`,
1166
- shouldBreak: true
1167
- // Signal to skip this test
1168
- };
1169
- }
1170
- await locator.press(keyValue, { timeout: this.timeoutMs });
1171
- return { success: true };
1172
- } catch (error) {
1173
- if (this.isBrowserClosedError(error)) {
1174
- return {
1175
- success: false,
1176
- error: `CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`,
1177
- shouldBreak: true
1178
- };
1179
- }
1180
- return {
1181
- success: false,
1182
- error: `Failed to press ${key} on ${target}: ${error instanceof Error ? error.message : String(error)}`
1183
- };
1184
- }
1185
- }
1186
- /**
1187
- * Execute hover action
1188
- */
1189
- async hover(target, relativeTarget) {
1190
- try {
1191
- if (target === "relative" && relativeTarget) {
1192
- const relativeSelector = this.selectors.relative;
1193
- if (!relativeSelector) {
1194
- return { success: false, error: `Relative selector not defined for hover action.` };
1195
- }
1196
- const element = await RelativeTargetResolver.resolve(this.page, relativeSelector, relativeTarget);
1197
- if (!element) {
1198
- return { success: false, error: `Could not resolve relative target ${relativeTarget} for hover.` };
1199
- }
1200
- await element.hover({ timeout: this.timeoutMs });
1201
- return { success: true };
1202
- }
1203
- const selector = this.selectors[target];
1204
- if (!selector) {
1205
- return { success: false, error: `Selector for hover target ${target} not found.` };
1206
- }
1207
- await this.page.locator(selector).first().hover({ timeout: this.timeoutMs });
1208
- return { success: true };
1209
- } catch (error) {
1210
- if (this.isBrowserClosedError(error)) {
1211
- return {
1212
- success: false,
1213
- error: `CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`,
1214
- shouldBreak: true
1215
- };
1216
- }
1217
- return {
1218
- success: false,
1219
- error: `Failed to hover ${target}: ${error instanceof Error ? error.message : String(error)}`
1220
- };
1221
- }
1222
- }
1223
- };
1224
- }
1225
- });
1226
- var AssertionRunner;
1227
- var init_AssertionRunner = __esm({
1228
- "src/utils/test/src/AssertionRunner.ts"() {
1229
- init_RelativeTargetResolver();
1230
- AssertionRunner = class {
1231
- constructor(page, selectors, timeoutMs = 400) {
1232
- this.page = page;
1233
- this.selectors = selectors;
1234
- this.timeoutMs = timeoutMs;
1235
- }
1236
- /**
1237
- * Resolve the target element for an assertion
1238
- */
1239
- async resolveTarget(targetName, relativeTarget, selectorKey) {
1240
- try {
1241
- if (targetName === "relative") {
1242
- const relativeSelector = selectorKey ? this.selectors[selectorKey] : this.selectors.relative;
1243
- if (!relativeSelector) {
1244
- return { target: null, error: "Relative selector is not defined in the contract." };
1245
- }
1246
- if (!relativeTarget) {
1247
- return { target: null, error: "Relative target or expected value is not defined." };
1248
- }
1249
- const target = await RelativeTargetResolver.resolve(this.page, relativeSelector, relativeTarget);
1250
- if (!target) {
1251
- return { target: null, error: `Target ${targetName} not found.` };
1252
- }
1253
- return { target };
1254
- }
1255
- const selector = this.selectors[targetName];
1256
- if (!selector) {
1257
- return { target: null, error: `Selector for assertion target ${targetName} not found.` };
1258
- }
1259
- return { target: this.page.locator(selector).first() };
1260
- } catch (error) {
1261
- return {
1262
- target: null,
1263
- error: `Failed to resolve target ${targetName}: ${error instanceof Error ? error.message : String(error)}`
1264
- };
1265
- }
1266
- }
1267
- /**
1268
- * Validate visibility assertion
1269
- */
1270
- async validateVisibility(target, targetName, expectedVisible, failureMessage, testDescription) {
1271
- try {
1272
- if (expectedVisible) {
1273
- await test.expect(target).toBeVisible({ timeout: this.timeoutMs });
1274
- return {
1275
- success: true,
1276
- passMessage: `${targetName} is visible as expected. Test: "${testDescription}".`
1277
- };
1278
- } else {
1279
- await test.expect(target).toBeHidden({ timeout: this.timeoutMs });
1280
- return {
1281
- success: true,
1282
- passMessage: `${targetName} is not visible as expected. Test: "${testDescription}".`
1283
- };
1284
- }
1285
- } catch {
1286
- const selector = this.selectors[targetName] || "";
1287
- const debugState = await this.page.evaluate((sel) => {
1288
- const el = sel ? document.querySelector(sel) : null;
1289
- if (!el) return "element not found";
1290
- const styles = window.getComputedStyle(el);
1291
- return `display:${styles.display}, visibility:${styles.visibility}, opacity:${styles.opacity}`;
1292
- }, selector);
1293
- if (expectedVisible) {
1294
- return {
1295
- success: false,
1296
- failMessage: `${failureMessage} (actual: ${debugState})`
1297
- };
1298
- } else {
1299
- return {
1300
- success: false,
1301
- failMessage: `${failureMessage} ${targetName} is still visible (actual: ${debugState}).`
1302
- };
1303
- }
1304
- }
1305
- }
1306
- /**
1307
- * Validate attribute assertion
1308
- */
1309
- async validateAttribute(target, targetName, attribute, expectedValue, failureMessage, testDescription) {
1310
- if (expectedValue === "!empty") {
1311
- const attributeValue2 = await target.getAttribute(attribute);
1312
- if (attributeValue2 && attributeValue2.trim() !== "") {
1313
- return {
1314
- success: true,
1315
- passMessage: `${targetName} has non-empty "${attribute}". Test: "${testDescription}".`
1316
- };
1317
- } else {
1318
- return {
1319
- success: false,
1320
- failMessage: `${failureMessage} ${targetName} "${attribute}" should not be empty, found "${attributeValue2}".`
1321
- };
1322
- }
1323
- }
1324
- if (typeof expectedValue !== "string") {
1325
- console.error("[AssertionRunner] expectedValue is not a string:", expectedValue);
1326
- throw new Error(`AssertionRunner: expectedValue for attribute assertion must be a string, but got: ${JSON.stringify(expectedValue)}`);
1327
- }
1328
- const expectedValues = expectedValue.split(" | ").map((v) => v.trim());
1329
- const attributeValue = await target.getAttribute(attribute);
1330
- if (attributeValue !== null && expectedValues.includes(attributeValue)) {
1331
- return {
1332
- success: true,
1333
- passMessage: `${targetName} has expected "${attribute}". Test: "${testDescription}".`
1334
- };
1335
- } else {
1336
- return {
1337
- success: false,
1338
- failMessage: `${failureMessage} ${targetName} "${attribute}" should be "${expectedValue}", found "${attributeValue}".`
1339
- };
1340
- }
1341
- }
1342
- /**
1343
- * Validate input value assertion
1344
- */
1345
- async validateValue(target, targetName, expectedValue, failureMessage, testDescription) {
1346
- const inputValue = await target.inputValue().catch(() => "");
1347
- if (expectedValue === "!empty") {
1348
- if (inputValue && inputValue.trim() !== "") {
1349
- return {
1350
- success: true,
1351
- passMessage: `${targetName} has non-empty value. Test: "${testDescription}".`
1352
- };
1353
- } else {
1354
- return {
1355
- success: false,
1356
- failMessage: `${failureMessage} ${targetName} value should not be empty, found "${inputValue}".`
1357
- };
1358
- }
1359
- }
1360
- if (expectedValue === "") {
1361
- if (inputValue === "") {
1362
- return {
1363
- success: true,
1364
- passMessage: `${targetName} has empty value. Test: "${testDescription}".`
1365
- };
1366
- } else {
1367
- return {
1368
- success: false,
1369
- failMessage: `${failureMessage} ${targetName} value should be empty, found "${inputValue}".`
1370
- };
1371
- }
1372
- }
1373
- if (inputValue === expectedValue) {
1374
- return {
1375
- success: true,
1376
- passMessage: `${targetName} has expected value. Test: "${testDescription}".`
1377
- };
1378
- } else {
1379
- return {
1380
- success: false,
1381
- failMessage: `${failureMessage} ${targetName} value should be "${expectedValue}", found "${inputValue}".`
1382
- };
1383
- }
1384
- }
1385
- /**
1386
- * Validate focus assertion
1387
- */
1388
- async validateFocus(target, targetName, expectedFocus, failureMessage, testDescription) {
1389
- try {
1390
- if (expectedFocus) {
1391
- await test.expect(target).toBeFocused({ timeout: this.timeoutMs });
1392
- return {
1393
- success: true,
1394
- passMessage: `${targetName} has focus as expected. Test: "${testDescription}".`
1395
- };
1396
- } else {
1397
- await test.expect(target).not.toBeFocused({ timeout: this.timeoutMs });
1398
- return {
1399
- success: true,
1400
- passMessage: `${targetName} does not have focus as expected. Test: "${testDescription}".`
1401
- };
1402
- }
1403
- } catch {
1404
- const actualFocus = await this.page.evaluate(() => {
1405
- const focused = document.activeElement;
1406
- return focused ? `${focused.tagName}#${focused.id || "no-id"}.${focused.className || "no-class"}` : "no element focused";
1407
- });
1408
- return {
1409
- success: false,
1410
- failMessage: `${failureMessage} (actual focus: ${actualFocus})`
1411
- };
1412
- }
1413
- }
1414
- /**
1415
- * Validate role assertion
1416
- */
1417
- async validateRole(target, targetName, expectedRole, failureMessage, testDescription) {
1418
- const roleValue = await target.getAttribute("role");
1419
- if (roleValue === expectedRole) {
1420
- return {
1421
- success: true,
1422
- passMessage: `${targetName} has role "${expectedRole}". Test: "${testDescription}".`
1423
- };
1424
- } else {
1425
- return {
1426
- success: false,
1427
- failMessage: `${failureMessage} Expected role "${expectedRole}", found "${roleValue}".`
1428
- };
1429
- }
1430
- }
1431
- /**
1432
- * Main validation method - routes to specific validators
1433
- */
1434
- async validate(assertion, testDescription) {
1435
- if (this.page.isClosed()) {
1436
- return {
1437
- success: false,
1438
- failMessage: `CRITICAL: Browser/page closed before completing all tests. Increase test timeout or reduce test complexity.`
1439
- };
1440
- }
1441
- const { target, error } = await this.resolveTarget(
1442
- assertion.target,
1443
- assertion.relativeTarget || assertion.expectedValue,
1444
- assertion.selectorKey
1445
- );
1446
- if (error || !target) {
1447
- return { success: false, failMessage: error || `Target ${assertion.target} not found.`, target: null };
1448
- }
1449
- if (assertion.target === "input" && assertion.attribute === "aria-activedescendant" && assertion.expectedValue === "!empty" && assertion.relativeTarget && assertion.selectorKey) {
1450
- const optionLocator = await RelativeTargetResolver.resolve(this.page, this.selectors[assertion.selectorKey], assertion.relativeTarget);
1451
- const optionId = optionLocator ? await optionLocator.getAttribute("id") : null;
1452
- const inputId = await target.getAttribute("aria-activedescendant");
1453
- if (optionId && inputId === optionId) {
1454
- return {
1455
- success: true,
1456
- passMessage: `input[aria-activedescendant] matches id of ${assertion.relativeTarget}(${assertion.selectorKey}). Test: "${testDescription}".`
1457
- };
1458
- } else {
1459
- return {
1460
- success: false,
1461
- failMessage: `input[aria-activedescendant] should match id of ${assertion.relativeTarget}(${assertion.selectorKey}), found "${inputId}".`
1462
- };
1463
- }
1464
- }
1465
- switch (assertion.assertion) {
1466
- case "toBeVisible":
1467
- return this.validateVisibility(target, assertion.target, true, assertion.failureMessage || "", testDescription);
1468
- case "notToBeVisible":
1469
- return this.validateVisibility(target, assertion.target, false, assertion.failureMessage || "", testDescription);
1470
- case "toHaveAttribute":
1471
- if (assertion.attribute && assertion.expectedValue !== void 0) {
1472
- return this.validateAttribute(
1473
- target,
1474
- assertion.target,
1475
- assertion.attribute,
1476
- assertion.expectedValue,
1477
- assertion.failureMessage || "",
1478
- testDescription
1479
- );
1480
- }
1481
- return { success: false, failMessage: "Missing attribute or expectedValue for toHaveAttribute assertion" };
1482
- case "toHaveValue":
1483
- if (assertion.expectedValue !== void 0) {
1484
- return this.validateValue(target, assertion.target, assertion.expectedValue, assertion.failureMessage || "", testDescription);
1485
- }
1486
- return { success: false, failMessage: "Missing expectedValue for toHaveValue assertion" };
1487
- case "toHaveFocus":
1488
- return this.validateFocus(target, assertion.target, true, assertion.failureMessage || "", testDescription);
1489
- case "notToHaveFocus":
1490
- return this.validateFocus(target, assertion.target, false, assertion.failureMessage || "", testDescription);
1491
- case "toHaveRole":
1492
- if (assertion.expectedValue !== void 0) {
1493
- return this.validateRole(target, assertion.target, assertion.expectedValue, assertion.failureMessage || "", testDescription);
1494
- }
1495
- return { success: false, failMessage: "Missing expectedValue for toHaveRole assertion" };
1496
- default:
1497
- return { success: false, failMessage: `Unknown assertion type: ${assertion.assertion}` };
1498
- }
1499
- }
1500
- };
1501
- }
1502
- });
1503
-
1504
- // src/utils/test/src/contractTestRunnerPlaywright.ts
1505
- var contractTestRunnerPlaywright_exports = {};
1506
- __export(contractTestRunnerPlaywright_exports, {
1507
- runContractTestsPlaywright: () => runContractTestsPlaywright
1508
- });
1509
- async function runContractTestsPlaywright(componentName, url, strictness, config, configBaseDir) {
1510
- const componentConfig = config?.test?.components?.find((c) => c.name === componentName);
1511
- const isCustomContract = !!componentConfig?.contractPath;
1512
- const reporter = new ContractReporter(true, isCustomContract);
1513
- const defaultTimeouts = { actionTimeoutMs: 400, assertionTimeoutMs: 400, navigationTimeoutMs: 3e4, componentReadyTimeoutMs: 5e3 };
1514
- const globalDisableTimeouts = config?.test?.disableTimeouts === true;
1515
- const componentDisableTimeouts = componentConfig?.disableTimeouts === true;
1516
- const disableTimeouts = componentDisableTimeouts || globalDisableTimeouts;
1517
- const resolveTimeout = (componentValue, globalValue, fallback) => {
1518
- if (disableTimeouts) return 0;
1519
- const value = componentValue ?? globalValue;
1520
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
1521
- return fallback;
1522
- }
1523
- return value;
1524
- };
1525
- const actionTimeoutMs = resolveTimeout(componentConfig?.actionTimeoutMs, config?.test?.actionTimeoutMs, defaultTimeouts.actionTimeoutMs);
1526
- const assertionTimeoutMs = resolveTimeout(
1527
- componentConfig?.assertionTimeoutMs,
1528
- config?.test?.assertionTimeoutMs,
1529
- defaultTimeouts.assertionTimeoutMs
1530
- );
1531
- const navigationTimeoutMs = resolveTimeout(
1532
- componentConfig?.navigationTimeoutMs,
1533
- config?.test?.navigationTimeoutMs,
1534
- defaultTimeouts.navigationTimeoutMs
1535
- );
1536
- const componentReadyTimeoutMs = resolveTimeout(
1537
- componentConfig?.componentReadyTimeoutMs,
1538
- config?.test?.componentReadyTimeoutMs,
1539
- defaultTimeouts.componentReadyTimeoutMs
1540
- );
1541
- const strictnessMode = normalizeStrictness(strictness);
1542
- const contractPath = componentConfig?.contractPath;
1543
- if (!contractPath) {
1544
- throw new Error(`Contract path not found for component: ${componentName}`);
1545
- }
1546
- const resolvedPath = (() => {
1547
- if (path3__default.default.isAbsolute(contractPath)) return contractPath;
1548
- if (configBaseDir) {
1549
- const configResolved = path3__default.default.resolve(configBaseDir, contractPath);
1550
- try {
1551
- fs.readFileSync(configResolved, "utf-8");
1552
- return configResolved;
1553
- } catch {
1554
- }
1555
- }
1556
- const cwdResolved = path3__default.default.resolve(process.cwd(), contractPath);
1557
- try {
1558
- fs.readFileSync(cwdResolved, "utf-8");
1559
- return cwdResolved;
1560
- } catch {
1561
- return new URL(contractPath, (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).pathname;
1562
- }
1563
- })();
1564
- const contractData = fs.readFileSync(resolvedPath, "utf-8");
1565
- const componentContract = JSON.parse(contractData);
1566
- const totalTests = (componentContract.relationships?.length || 0) + (componentContract.static[0]?.assertions.length || 0) + componentContract.dynamic.length;
1567
- const apgUrl = componentContract.meta?.source?.apg;
1568
- const failures = [];
1569
- const warnings = [];
1570
- const passes = [];
1571
- const skipped = [];
1572
- let page = null;
1573
- const classifyFailure = (message, levelRaw) => {
1574
- const level = normalizeLevel(levelRaw);
1575
- const enforcement = resolveEnforcement(level, strictnessMode);
1576
- if (enforcement === "error") {
1577
- failures.push(message);
1578
- return { status: "fail", level, detail: message };
1579
- }
1580
- if (enforcement === "warning") {
1581
- warnings.push(message);
1582
- return { status: "warn", level, detail: message };
1583
- }
1584
- const ignoredMessage = `${message} (ignored by strictness=${strictnessMode}, level=${level})`;
1585
- skipped.push(ignoredMessage);
1586
- return { status: "skip", level, detail: ignoredMessage };
1587
- };
1588
- try {
1589
- page = await createTestPage();
1590
- if (url) {
1591
- try {
1592
- await page.goto(url, {
1593
- waitUntil: "domcontentloaded",
1594
- timeout: navigationTimeoutMs
1595
- });
1596
- } catch (error) {
1597
- throw new Error(
1598
- `Failed to navigate to ${url}. Ensure dev server is running and accessible. Original error: ${error instanceof Error ? error.message : String(error)}`
1599
- );
1600
- }
1601
- await page.addStyleTag({ content: `* { transition: none !important; animation: none !important; }` });
1602
- }
1603
- const strategy = await ComponentDetector.detect(componentName, componentConfig, actionTimeoutMs, assertionTimeoutMs, configBaseDir);
1604
- if (!strategy) {
1605
- throw new Error(`Unsupported component: ${componentName}`);
1606
- }
1607
- const mainSelector = strategy.getMainSelector();
1608
- if (!mainSelector) {
1609
- throw new Error(`CRITICAL: No selector found in contract for ${componentName}`);
1610
- }
1611
- try {
1612
- await page.locator(mainSelector).first().waitFor({ state: "attached", timeout: componentReadyTimeoutMs });
1613
- } catch (error) {
1614
- throw new Error(
1615
- `
9
+ This indicates a problem with the combobox component's close functionality.`);this.selectors.input&&await e.locator(this.selectors.input).first().clear();}async shouldSkipTest(){return false}getMainSelector(){return this.mainSelector}};});var Ze={};Y(Ze,{TabsComponentStrategy:()=>Re});var Re,et=L(()=>{Re=class{constructor(e,t){this.mainSelector=e;this.selectors=t;}async resetState(){}async shouldSkipTest(e,t){if(e.isVertical!==void 0&&this.selectors.tablist){let r=this.selectors.tablist,o=await t.locator(r).first().getAttribute("aria-orientation")==="vertical";if(e.isVertical!==o)return true}return false}getMainSelector(){return this.mainSelector}};});var ue,st=L(()=>{ue=class{builtInStrategies=new Map;constructor(){this.registerBuiltInStrategies();}registerBuiltInStrategies(){this.builtInStrategies.set("menu",()=>Promise.resolve().then(()=>(Ge(),ze)).then(e=>e.MenuComponentStrategy)),this.builtInStrategies.set("accordion",()=>Promise.resolve().then(()=>(Ye(),Ne)).then(e=>e.AccordionComponentStrategy)),this.builtInStrategies.set("combobox",()=>Promise.resolve().then(()=>(Xe(),Qe)).then(e=>e.ComboboxComponentStrategy)),this.builtInStrategies.set("tabs",()=>Promise.resolve().then(()=>(et(),Ze)).then(e=>e.TabsComponentStrategy));}async loadStrategy(e,t,r){try{if(t)try{let n=xe__default.default.isAbsolute(t)?t:xe__default.default.resolve(r||process.cwd(),t),o=await import(url.pathToFileURL(n).href),a=o.default||o;if(!a)throw new Error(`No default export found in ${t}`);return a}catch(n){throw new Error(`Failed to load custom strategy from ${t}: ${n instanceof Error?n.message:String(n)}`)}let i=this.builtInStrategies.get(e);return i?i():null}catch(i){throw new Error(`Strategy loading failed for ${e}: ${i instanceof Error?i.message:String(i)}`)}}has(e,t){return !!t||this.builtInStrategies.has(e)}};});var pe,rt=L(()=>{st();pe=class{static strategyRegistry=new ue;static isComponentConfig(e){return typeof e=="object"&&e!==null}static async detect(e,t,r=400,i=400,n){let o=this.isComponentConfig(t)?t:void 0,a=o?.contractPath;if(!a)throw new Error(`Contract path not found for component: ${e}`);let p=(()=>{if(xe__default.default.isAbsolute(a))return a;if(n){let ce=xe__default.default.resolve(n,a);try{return fs.readFileSync(ce,"utf-8"),ce}catch{}}let Q=xe__default.default.resolve(process.cwd(),a);try{return fs.readFileSync(Q,"utf-8"),Q}catch{return new URL(a,(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).pathname}})(),A=fs.readFileSync(p,"utf-8"),x=JSON.parse(A).selectors,M=await this.strategyRegistry.loadStrategy(e,o?.strategyPath,n);if(!M)return null;let K=x.main;return e==="tabs"?new M(K,x):new M(K,x,r,i)}};});var fe,it=L(()=>{fe=class{startTime=0;componentName="";staticPasses=0;staticFailures=0;staticWarnings=0;dynamicResults=[];totalTests=0;skipped=0;warnings=0;isPlaywright=false;isCustomContract=false;apgUrl="https://www.w3.org/WAI/ARIA/apg/";hasPrintedStaticSection=false;hasPrintedDynamicSection=false;constructor(e=false,t=false){this.isPlaywright=e,this.isCustomContract=t;}log(e){process.stderr.write(e+`
10
+ `);}start(e,t,r){this.startTime=Date.now(),this.componentName=e,this.totalTests=t,this.hasPrintedStaticSection=false,this.hasPrintedDynamicSection=false,r&&(this.apgUrl=r);let i="Playwright (Real Browser)";this.log(`
11
+ ${"\u2550".repeat(60)}`),this.log(`\u{1F50D} Testing ${e.charAt(0).toUpperCase()+e.slice(1)} Component - ${i}`),this.log(`${"\u2550".repeat(60)}
12
+ `);}reportStatic(e,t,r=0){this.staticPasses=e,this.staticFailures=t,this.staticWarnings=r;}reportStaticTest(e,t,r,i){this.hasPrintedStaticSection||(this.log(`${"\u2500".repeat(60)}`),this.log("\u{1F9EA} Static Assertions"),this.log(`${"\u2500".repeat(60)}`),this.hasPrintedStaticSection=true);let n=t==="pass"?"\u2713":t==="warn"?"\u26A0":t==="skip"?"\u25CB":"\u2717";this.log(` ${n} ${e}`),i&&this.log(` \u21B3 level=${i}`),(t==="fail"||t==="warn"||t==="skip")&&r&&this.log(` \u21B3 ${r}`);}reportTest(e,t,r){this.hasPrintedDynamicSection||(this.log(""),this.log(`${"\u2500".repeat(60)}`),this.log("\u2328\uFE0F Dynamic Interaction Tests"),this.log(`${"\u2500".repeat(60)}`),this.hasPrintedDynamicSection=true);let i={description:e.description,status:t,failureMessage:r,level:e.level};t==="skip"&&(i.skipReason="Requires real browser (addEventListener events)"),this.dynamicResults.push(i);let n={pass:"\u2713",fail:"\u2717",warn:"\u26A0",skip:"\u25CB"},o=e.level?`[${e.level.toUpperCase()}] `:"";this.log(` ${n[t]} ${o}${e.description}`),t==="skip"&&!this.isPlaywright&&this.log(" \u21B3 Skipped (runs only in Playwright)"),t==="fail"&&r&&this.log(` \u21B3 ${r}`),t==="warn"&&r&&this.log(` \u21B3 ${r}`),t==="skip"&&r&&this.log(` \u21B3 ${r}`);}reportFailures(e){e.length!==0&&(this.log(`
13
+ ${"\u2500".repeat(60)}`),this.log(`\u274C Failures (${e.length}):
14
+ `),e.forEach((t,r)=>{this.log(`${r+1}. ${t}`),t.includes("aria-")?this.log(" \u{1F4A1} Add the missing ARIA attribute to improve screen reader support"):t.includes("focus")?this.log(" \u{1F4A1} Check keyboard event handlers and focus management"):t.includes("visible")&&this.log(" \u{1F4A1} Verify display/visibility styles and state management"),this.log("");}));}reportWarnings(){let e=this.dynamicResults.filter(t=>t.status==="warn");e.length===0&&this.staticWarnings===0||(this.log(`
15
+ ${"\u2500".repeat(60)}`),this.log(`\u26A0\uFE0F Warnings (${this.staticWarnings+e.length}):
16
+ `),this.log(`These checks are failing but treated as warnings under the active strictness mode.
17
+ `),e.forEach((t,r)=>{this.log(`${r+1}. ${t.description}`),t.failureMessage&&this.log(` \u21B3 ${t.failureMessage}`),t.level&&this.log(` \u21B3 level=${t.level}`);}),this.apgUrl&&this.log(`
18
+ Reference: ${this.apgUrl}
19
+ `));}reportSkipped(){if(this.skipped===0||this.isPlaywright)return;let e=this.dynamicResults.filter(t=>t.status==="skip");this.log(`
20
+ ${"\u2500".repeat(60)}`),this.log(`\u2139\uFE0F Skipped Tests (${this.skipped}):
21
+ `),this.log("These tests use native keyboard events via addEventListener,"),this.log(`which only run in Playwright (real browser).
22
+ `),e.forEach((t,r)=>{this.log(`${r+1}. ${t.description}`);}),this.log(`
23
+ \u{1F4A1} Run with Playwright for full validation:`),this.log(` testUiComponent('${this.componentName}', null, 'http://localhost:5173/test-harness?component=component_name')
24
+ `);}summary(e){let t=Date.now()-this.startTime,r=this.dynamicResults.filter(b=>b.status==="pass").length,i=this.dynamicResults.filter(b=>b.status==="fail").length,n=this.dynamicResults.filter(b=>b.status==="warn").length;this.skipped=this.dynamicResults.filter(b=>b.status==="skip").length,this.warnings=this.staticWarnings+n;let o=this.staticPasses+r,a=this.staticFailures+i,p=o+a+this.warnings,A=()=>{let b=`${this.componentName.charAt(0).toUpperCase()}${this.componentName.slice(1)}`;return this.isCustomContract?`${b} component validates against your custom accessibility policy \u2713`:`${b} component meets Aria-Ease baseline WAI-ARIA expectations \u2713`};return e.length>0&&this.reportFailures(e),this.reportWarnings(),this.reportSkipped(),this.log(`
25
+ ${"\u2550".repeat(60)}`),this.log(`\u{1F4CA} Summary
26
+ `),a===0&&this.skipped===0&&this.warnings===0?(this.log(`\u2705 All ${p} tests passed!`),this.log(` ${A()}`)):a===0?(this.log(`\u2705 ${o}/${p} tests passed`),this.skipped>0&&this.log(`\u25CB ${this.skipped} tests skipped`),this.warnings>0&&this.log(`\u26A0\uFE0F ${this.warnings} warning${this.warnings>1?"s":""}`),this.log(` ${A()}`)):(this.log(`\u274C ${a} test${a>1?"s":""} failed`),this.log(`\u2705 ${o} test${o>1?"s":""} passed`),this.warnings>0&&this.log(`\u26A0\uFE0F ${this.warnings} warning${this.warnings>1?"s":""}`),this.skipped>0&&this.log(`\u25CB ${this.skipped} test${this.skipped>1?"s":""} skipped`)),this.log(`\u23F1\uFE0F Duration: ${t}ms`),this.log(`${"\u2550".repeat(60)}
27
+ `),a>0?(this.log("\u{1F527} Next Steps:"),this.log(" 1. Review the failures above"),this.log(" 2. Fix ARIA attributes and keyboard handlers"),this.log(` 3. Re-run tests to verify fixes
28
+ `)):!this.isPlaywright&&this.skipped>0&&this.log(`\u2728 Optional: Run Playwright tests for complete validation
29
+ `),{passes:o,failures:a,skipped:this.skipped,duration:t}}error(e,t){this.log(`
30
+ \u274C Error: ${e}`),t&&this.log(` Context: ${t}`),this.log("");}};});var nt={};Y(nt,{RelativeTargetResolver:()=>J});var J,ge=L(()=>{J=class{static async resolve(e,t,r){let i=await e.locator(t).all();switch(r){case "first":return i[0];case "second":return i[1];case "last":return i[i.length-1];case "next":{let o=(await e.evaluate(([a])=>Array.from(document.querySelectorAll(a)).indexOf(document.activeElement),[t])+1)%i.length;return i[o]}case "previous":{let o=(await e.evaluate(([a])=>Array.from(document.querySelectorAll(a)).indexOf(document.activeElement),[t])-1+i.length)%i.length;return i[o]}default:return null}}};});var re,ot=L(()=>{ge();re=class{constructor(e,t,r=400){this.page=e;this.selectors=t;this.timeoutMs=r;}isBrowserClosedError(e){return e instanceof Error&&e.message.includes("Target page, context or browser has been closed")}async focus(e,t,r){try{if(e==="virtual"&&r){let n=this.selectors.main;if(!n)return {success:!1,error:"Main selector not defined for virtual focus."};let o=this.page.locator(n).first();return await o.count()?(await o.evaluate((p,A)=>{p.setAttribute("aria-activedescendant",A);},r),{success:!0}):{success:!1,error:"Main element not found for virtual focus."}}if(e==="relative"&&t){let n=this.selectors.relative;if(!n)return {success:!1,error:"Relative selector not defined for focus action."};let o=await J.resolve(this.page,n,t);return o?(await o.focus({timeout:this.timeoutMs}),{success:!0}):{success:!1,error:`Could not resolve relative target ${t} for focus.`}}let i=this.selectors[e];return i?(await this.page.locator(i).first().focus({timeout:this.timeoutMs}),{success:!0}):{success:!1,error:`Selector for focus target ${e} not found.`}}catch(i){return this.isBrowserClosedError(i)?{success:false,error:"CRITICAL: Browser/page closed during test execution. Remaining actions skipped.",shouldBreak:true}:{success:false,error:`Failed to focus ${e}: ${i instanceof Error?i.message:String(i)}`}}}async type(e,t){try{let r=this.selectors[e];return r?(await this.page.locator(r).first().fill(t,{timeout:this.timeoutMs}),{success:!0}):{success:!1,error:`Selector for type target ${e} not found.`}}catch(r){return this.isBrowserClosedError(r)?{success:false,error:"CRITICAL: Browser/page closed during test execution. Remaining actions skipped.",shouldBreak:true}:{success:false,error:`Failed to type into ${e}: ${r instanceof Error?r.message:String(r)}`}}}async click(e,t){try{if(e==="document")return await this.page.mouse.click(10,10),{success:!0};if(e==="relative"&&t){let i=this.selectors.relative;if(!i)return {success:!1,error:"Relative selector not defined for click action."};let n=await J.resolve(this.page,i,t);return n?(await n.click({timeout:this.timeoutMs}),{success:!0}):{success:!1,error:`Could not resolve relative target ${t} for click.`}}let r=this.selectors[e];return r?(await this.page.locator(r).first().click({timeout:this.timeoutMs}),{success:!0}):{success:!1,error:`Selector for action target ${e} not found.`}}catch(r){return this.isBrowserClosedError(r)?{success:false,error:"CRITICAL: Browser/page closed during test execution. Remaining actions skipped.",shouldBreak:true}:{success:false,error:`Failed to click ${e}: ${r instanceof Error?r.message:String(r)}`}}}async keypress(e,t){try{let i={Space:"Space",Enter:"Enter",Escape:"Escape","Arrow Up":"ArrowUp","Arrow Down":"ArrowDown","Arrow Left":"ArrowLeft","Arrow Right":"ArrowRight",Home:"Home",End:"End",Tab:"Tab"}[t]||t;if(i==="Space"?i=" ":i.includes(" ")&&(i=i.replace(/ /g,"")),e==="focusable"&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Escape","Home","End","Tab","Shift+Tab"].includes(i))return await this.page.keyboard.press(i),{success:!0};let n=this.selectors[e];if(!n)return {success:!1,error:`Selector for keypress target ${e} not found.`};let o=this.page.locator(n).first();return await o.count()===0?{success:!1,error:`${e} element not found.`,shouldBreak:!0}:(await o.press(i,{timeout:this.timeoutMs}),{success:!0})}catch(r){return this.isBrowserClosedError(r)?{success:false,error:"CRITICAL: Browser/page closed during test execution. Remaining actions skipped.",shouldBreak:true}:{success:false,error:`Failed to press ${t} on ${e}: ${r instanceof Error?r.message:String(r)}`}}}async hover(e,t){try{if(e==="relative"&&t){let i=this.selectors.relative;if(!i)return {success:!1,error:"Relative selector not defined for hover action."};let n=await J.resolve(this.page,i,t);return n?(await n.hover({timeout:this.timeoutMs}),{success:!0}):{success:!1,error:`Could not resolve relative target ${t} for hover.`}}let r=this.selectors[e];return r?(await this.page.locator(r).first().hover({timeout:this.timeoutMs}),{success:!0}):{success:!1,error:`Selector for hover target ${e} not found.`}}catch(r){return this.isBrowserClosedError(r)?{success:false,error:"CRITICAL: Browser/page closed during test execution. Remaining actions skipped.",shouldBreak:true}:{success:false,error:`Failed to hover ${e}: ${r instanceof Error?r.message:String(r)}`}}}};});var ae,at=L(()=>{ge();ae=class{constructor(e,t,r=400){this.page=e;this.selectors=t;this.timeoutMs=r;}async resolveTarget(e,t,r){try{if(e==="relative"){let n=r?this.selectors[r]:this.selectors.relative;if(!n)return {target:null,error:"Relative selector is not defined in the contract."};if(!t)return {target:null,error:"Relative target or expected value is not defined."};let o=await J.resolve(this.page,n,t);return o?{target:o}:{target:null,error:`Target ${e} not found.`}}let i=this.selectors[e];return i?{target:this.page.locator(i).first()}:{target:null,error:`Selector for assertion target ${e} not found.`}}catch(i){return {target:null,error:`Failed to resolve target ${e}: ${i instanceof Error?i.message:String(i)}`}}}async validateVisibility(e,t,r,i,n){try{return r?(await test.expect(e).toBeVisible({timeout:this.timeoutMs}),{success:!0,passMessage:`${t} is visible as expected. Test: "${n}".`}):(await test.expect(e).toBeHidden({timeout:this.timeoutMs}),{success:!0,passMessage:`${t} is not visible as expected. Test: "${n}".`})}catch{let o=this.selectors[t]||"",a=await this.page.evaluate(p=>{let A=p?document.querySelector(p):null;if(!A)return "element not found";let b=window.getComputedStyle(A);return `display:${b.display}, visibility:${b.visibility}, opacity:${b.opacity}`},o);return r?{success:false,failMessage:`${i} (actual: ${a})`}:{success:false,failMessage:`${i} ${t} is still visible (actual: ${a}).`}}}async validateAttribute(e,t,r,i,n,o){if(i==="!empty"){let A=await e.getAttribute(r);return A&&A.trim()!==""?{success:true,passMessage:`${t} has non-empty "${r}". Test: "${o}".`}:{success:false,failMessage:`${n} ${t} "${r}" should not be empty, found "${A}".`}}if(typeof i!="string")throw console.error("[AssertionRunner] expectedValue is not a string:",i),new Error(`AssertionRunner: expectedValue for attribute assertion must be a string, but got: ${JSON.stringify(i)}`);let a=i.split(" | ").map(A=>A.trim()),p=await e.getAttribute(r);return p!==null&&a.includes(p)?{success:true,passMessage:`${t} has expected "${r}". Test: "${o}".`}:{success:false,failMessage:`${n} ${t} "${r}" should be "${i}", found "${p}".`}}async validateValue(e,t,r,i,n){let o=await e.inputValue().catch(()=>"");return r==="!empty"?o&&o.trim()!==""?{success:true,passMessage:`${t} has non-empty value. Test: "${n}".`}:{success:false,failMessage:`${i} ${t} value should not be empty, found "${o}".`}:r===""?o===""?{success:true,passMessage:`${t} has empty value. Test: "${n}".`}:{success:false,failMessage:`${i} ${t} value should be empty, found "${o}".`}:o===r?{success:true,passMessage:`${t} has expected value. Test: "${n}".`}:{success:false,failMessage:`${i} ${t} value should be "${r}", found "${o}".`}}async validateFocus(e,t,r,i,n){try{return r?(await test.expect(e).toBeFocused({timeout:this.timeoutMs}),{success:!0,passMessage:`${t} has focus as expected. Test: "${n}".`}):(await test.expect(e).not.toBeFocused({timeout:this.timeoutMs}),{success:!0,passMessage:`${t} does not have focus as expected. Test: "${n}".`})}catch{let o=await this.page.evaluate(()=>{let a=document.activeElement;return a?`${a.tagName}#${a.id||"no-id"}.${a.className||"no-class"}`:"no element focused"});return {success:false,failMessage:`${i} (actual focus: ${o})`}}}async validateRole(e,t,r,i,n){let o=await e.getAttribute("role");return o===r?{success:true,passMessage:`${t} has role "${r}". Test: "${n}".`}:{success:false,failMessage:`${i} Expected role "${r}", found "${o}".`}}async validate(e,t){if(this.page.isClosed())return {success:false,failMessage:"CRITICAL: Browser/page closed before completing all tests. Increase test timeout or reduce test complexity."};let{target:r,error:i}=await this.resolveTarget(e.target,e.relativeTarget||e.expectedValue,e.selectorKey);if(i||!r)return {success:false,failMessage:i||`Target ${e.target} not found.`,target:null};if(e.target==="input"&&e.attribute==="aria-activedescendant"&&e.expectedValue==="!empty"&&e.relativeTarget&&e.selectorKey){let n=await J.resolve(this.page,this.selectors[e.selectorKey],e.relativeTarget),o=n?await n.getAttribute("id"):null,a=await r.getAttribute("aria-activedescendant");return o&&a===o?{success:true,passMessage:`input[aria-activedescendant] matches id of ${e.relativeTarget}(${e.selectorKey}). Test: "${t}".`}:{success:false,failMessage:`input[aria-activedescendant] should match id of ${e.relativeTarget}(${e.selectorKey}), found "${a}".`}}switch(e.assertion){case "toBeVisible":return this.validateVisibility(r,e.target,true,e.failureMessage||"",t);case "notToBeVisible":return this.validateVisibility(r,e.target,false,e.failureMessage||"",t);case "toHaveAttribute":return e.attribute&&e.expectedValue!==void 0?this.validateAttribute(r,e.target,e.attribute,e.expectedValue,e.failureMessage||"",t):{success:false,failMessage:"Missing attribute or expectedValue for toHaveAttribute assertion"};case "toHaveValue":return e.expectedValue!==void 0?this.validateValue(r,e.target,e.expectedValue,e.failureMessage||"",t):{success:false,failMessage:"Missing expectedValue for toHaveValue assertion"};case "toHaveFocus":return this.validateFocus(r,e.target,true,e.failureMessage||"",t);case "notToHaveFocus":return this.validateFocus(r,e.target,false,e.failureMessage||"",t);case "toHaveRole":return e.expectedValue!==void 0?this.validateRole(r,e.target,e.expectedValue,e.failureMessage||"",t):{success:false,failMessage:"Missing expectedValue for toHaveRole assertion"};default:return {success:false,failMessage:`Unknown assertion type: ${e.assertion}`}}}};});var ct={};Y(ct,{runContractTestsPlaywright:()=>Et});async function Et(c,e,t,r,i){let n=r?.test?.components?.find(h=>h.name===c),o=!!n?.contractPath,a=new fe(true,o),p={actionTimeoutMs:400,assertionTimeoutMs:400,navigationTimeoutMs:3e4,componentReadyTimeoutMs:5e3},A=r?.test?.disableTimeouts===true,x=n?.disableTimeouts===true||A,M=(h,O,q)=>{if(x)return 0;let U=h??O;return typeof U!="number"||!Number.isFinite(U)||U<0?q:U},K=M(n?.actionTimeoutMs,r?.test?.actionTimeoutMs,p.actionTimeoutMs),Q=M(n?.assertionTimeoutMs,r?.test?.assertionTimeoutMs,p.assertionTimeoutMs),ce=M(n?.navigationTimeoutMs,r?.test?.navigationTimeoutMs,p.navigationTimeoutMs),me=M(n?.componentReadyTimeoutMs,r?.test?.componentReadyTimeoutMs,p.componentReadyTimeoutMs),Le=oe(t),X=n?.contractPath;if(!X)throw new Error(`Contract path not found for component: ${c}`);let gt=(()=>{if(xe__default.default.isAbsolute(X))return X;if(i){let O=xe__default.default.resolve(i,X);try{return fs.readFileSync(O,"utf-8"),O}catch{}}let h=xe__default.default.resolve(process.cwd(),X);try{return fs.readFileSync(h,"utf-8"),h}catch{return new URL(X,(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).pathname}})(),dt=fs.readFileSync(gt,"utf-8"),S=JSON.parse(dt),mt=(S.relationships?.length||0)+(S.static[0]?.assertions.length||0)+S.dynamic.length,ht=S.meta?.source?.apg,H=[],G=[],N=[],I=[],$=null,P=(h,O)=>{let q=se(O),U=Oe(q,Le);if(U==="error")return H.push(h),{status:"fail",level:q,detail:h};if(U==="warning")return G.push(h),{status:"warn",level:q,detail:h};let _=`${h} (ignored by strictness=${Le}, level=${q})`;return I.push(_),{status:"skip",level:q,detail:_}};try{if($=await We(),e){try{await $.goto(e,{waitUntil:"domcontentloaded",timeout:ce});}catch(s){throw new Error(`Failed to navigate to ${e}. Ensure dev server is running and accessible. Original error: ${s instanceof Error?s.message:String(s)}`)}await $.addStyleTag({content:"* { transition: none !important; animation: none !important; }"});}let h=await pe.detect(c,n,K,Q,i);if(!h)throw new Error(`Unsupported component: ${c}`);let O=h.getMainSelector();if(!O)throw new Error(`CRITICAL: No selector found in contract for ${c}`);try{await $.locator(O).first().waitFor({state:"attached",timeout:me});}catch(s){throw new Error(`
1616
31
  \u274C CRITICAL: Component not found on page!
1617
32
  This usually means:
1618
33
  - The component didn't render
1619
34
  - The URL is incorrect
1620
- - The component selector '${mainSelector}' in the contract is wrong
1621
- - Original error: ${error}`
1622
- );
1623
- }
1624
- reporter.start(componentName, totalTests, apgUrl);
1625
- if (componentName === "menu" && componentContract.selectors.main) {
1626
- await page.locator(componentContract.selectors.main).first().waitFor({ state: "visible", timeout: componentReadyTimeoutMs }).catch(() => {
1627
- });
1628
- }
1629
- const hasSubmenuCapability = componentName === "menu" && !!componentContract.selectors.submenuTrigger ? await page.locator(componentContract.selectors.submenuTrigger).count() > 0 : false;
1630
- const isSubmenuRelation = (rel) => rel.type === "aria-reference" && [rel.from, rel.to].some((name) => ["submenu", "submenuTrigger", "submenuItems"].includes(name || "")) || rel.type === "contains" && [rel.parent, rel.child].some((name) => ["submenu", "submenuTrigger", "submenuItems"].includes(name || ""));
1631
- let staticPassed = 0;
1632
- let staticFailed = 0;
1633
- let staticWarnings = 0;
1634
- for (const rel of componentContract.relationships || []) {
1635
- if (strategy && typeof strategy.resetState === "function") {
1636
- try {
1637
- await strategy.resetState(page);
1638
- } catch (err) {
1639
- warnings.push(`Warning: resetState failed before relationship test: ${err instanceof Error ? err.message : String(err)}`);
1640
- }
1641
- }
1642
- const relationshipLevel = normalizeLevel(rel.level);
1643
- if (Array.isArray(rel.setup) && rel.setup.length > 0) {
1644
- let isAllowedType2 = function(t) {
1645
- return allowedTypes.includes(t);
1646
- };
1647
- var isAllowedType = isAllowedType2;
1648
- const actionExecutor = new ActionExecutor(page, componentContract.selectors, actionTimeoutMs);
1649
- const relDescription = rel.type === "aria-reference" ? `${rel.from}.${rel.attribute} references ${rel.to}` : `${rel.parent} contains ${rel.child}`;
1650
- const allowedTypes = ["focus", "type", "click", "keypress", "hover"];
1651
- const toSetupAction = (a) => ({
1652
- ...a,
1653
- type: isAllowedType2(a.type) ? a.type : "click"
1654
- });
1655
- const setupActions = rel.setup.map(toSetupAction);
1656
- const setupResult = await runSetupActions(setupActions, actionExecutor, strategy, page, relDescription, ["submenu", "submenuTrigger", "submenuItems"]);
1657
- if (setupResult.skip) {
1658
- skipped.push(setupResult.message || "Setup action skipped");
1659
- reporter.reportStaticTest(relDescription, "skip", setupResult.message, relationshipLevel);
1660
- continue;
1661
- }
1662
- if (!setupResult.success) {
1663
- const failure = `Relationship setup failed: ${setupResult.error}`;
1664
- const outcome = classifyFailure(failure, rel.level);
1665
- if (outcome.status === "fail") staticFailed += 1;
1666
- if (outcome.status === "warn") staticWarnings += 1;
1667
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
1668
- continue;
1669
- }
1670
- }
1671
- if (componentName === "menu" && !hasSubmenuCapability) {
1672
- const involvesSubmenu = isSubmenuRelation(rel);
1673
- if (involvesSubmenu) {
1674
- const relDescription = rel.type === "aria-reference" ? `${rel.from}.${rel.attribute} references ${rel.to}` : `${rel.parent} contains ${rel.child}`;
1675
- const skipMessage = `Skipping submenu relationship assertion: no submenu capability detected in rendered component.`;
1676
- skipped.push(skipMessage);
1677
- reporter.reportStaticTest(relDescription, "skip", skipMessage, relationshipLevel);
1678
- continue;
1679
- }
1680
- }
1681
- if (rel.type === "aria-reference") {
1682
- const relDescription = `${rel.from}.${rel.attribute} references ${rel.to}`;
1683
- const fromSelector = componentContract.selectors[rel.from];
1684
- const toSelector = componentContract.selectors[rel.to];
1685
- if (!fromSelector || !toSelector) {
1686
- const outcome = classifyFailure(
1687
- `Relationship selector missing: from="${rel.from}" or to="${rel.to}" not found in selectors.`,
1688
- rel.level
1689
- );
1690
- if (outcome.status === "fail") staticFailed += 1;
1691
- if (outcome.status === "warn") staticWarnings += 1;
1692
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
1693
- continue;
1694
- }
1695
- const fromTarget = page.locator(fromSelector).first();
1696
- const toTarget = page.locator(toSelector).first();
1697
- const fromExists = await fromTarget.count() > 0;
1698
- const toExists = await toTarget.count() > 0;
1699
- if (!fromExists || !toExists) {
1700
- if (componentName === "menu" && isSubmenuRelation(rel)) {
1701
- const skipMessage = "Skipping submenu relationship assertion in static phase: submenu elements are not present until submenu is opened.";
1702
- skipped.push(skipMessage);
1703
- reporter.reportStaticTest(relDescription, "skip", skipMessage, relationshipLevel);
1704
- continue;
1705
- }
1706
- const outcome = classifyFailure(
1707
- `Relationship target not found: ${!fromExists ? rel.from : rel.to}.`,
1708
- rel.level
1709
- );
1710
- if (outcome.status === "fail") staticFailed += 1;
1711
- if (outcome.status === "warn") staticWarnings += 1;
1712
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
1713
- continue;
1714
- }
1715
- const attrValue = await fromTarget.getAttribute(rel.attribute);
1716
- const toId = await toTarget.getAttribute("id");
1717
- if (!toId) {
1718
- const outcome = classifyFailure(
1719
- `Relationship target "${rel.to}" must have an id for ${rel.attribute} validation.`,
1720
- rel.level
1721
- );
1722
- if (outcome.status === "fail") staticFailed += 1;
1723
- if (outcome.status === "warn") staticWarnings += 1;
1724
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
1725
- continue;
1726
- }
1727
- const references = (attrValue || "").split(/\s+/).filter(Boolean);
1728
- const matches = references.includes(toId);
1729
- if (!matches) {
1730
- const outcome = classifyFailure(
1731
- `Expected ${rel.from} ${rel.attribute} to reference id "${toId}", found "${attrValue || ""}".`,
1732
- rel.level
1733
- );
1734
- if (outcome.status === "fail") staticFailed += 1;
1735
- if (outcome.status === "warn") staticWarnings += 1;
1736
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
1737
- continue;
1738
- }
1739
- passes.push(`Relationship valid: ${rel.from}.${rel.attribute} -> ${rel.to} (id=${toId}).`);
1740
- staticPassed += 1;
1741
- reporter.reportStaticTest(relDescription, "pass", void 0, relationshipLevel);
1742
- continue;
1743
- }
1744
- if (rel.type === "contains") {
1745
- const relDescription = `${rel.parent} contains ${rel.child}`;
1746
- const parentSelector = componentContract.selectors[rel.parent];
1747
- const childSelector = componentContract.selectors[rel.child];
1748
- if (!parentSelector || !childSelector) {
1749
- const outcome = classifyFailure(
1750
- `Relationship selector missing: parent="${rel.parent}" or child="${rel.child}" not found in selectors.`,
1751
- rel.level
1752
- );
1753
- if (outcome.status === "fail") staticFailed += 1;
1754
- if (outcome.status === "warn") staticWarnings += 1;
1755
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
1756
- continue;
1757
- }
1758
- const parent = page.locator(parentSelector).first();
1759
- const parentExists = await parent.count() > 0;
1760
- if (!parentExists) {
1761
- if (componentName === "menu" && isSubmenuRelation(rel)) {
1762
- const skipMessage = "Skipping submenu relationship assertion in static phase: submenu container is not present until submenu is opened.";
1763
- skipped.push(skipMessage);
1764
- reporter.reportStaticTest(relDescription, "skip", skipMessage, relationshipLevel);
1765
- continue;
1766
- }
1767
- const outcome = classifyFailure(`Relationship parent target not found: ${rel.parent}.`, rel.level);
1768
- if (outcome.status === "fail") staticFailed += 1;
1769
- if (outcome.status === "warn") staticWarnings += 1;
1770
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
1771
- continue;
1772
- }
1773
- const descendants = parent.locator(childSelector);
1774
- const descendantCount = await descendants.count();
1775
- if (descendantCount < 1) {
1776
- if (componentName === "menu" && isSubmenuRelation(rel)) {
1777
- const skipMessage = "Skipping submenu relationship assertion in static phase: submenu descendants are not present until submenu is opened.";
1778
- skipped.push(skipMessage);
1779
- reporter.reportStaticTest(relDescription, "skip", skipMessage, relationshipLevel);
1780
- continue;
1781
- }
1782
- const outcome = classifyFailure(
1783
- `Expected ${rel.parent} to contain descendant matching selector for ${rel.child}.`,
1784
- rel.level
1785
- );
1786
- if (outcome.status === "fail") staticFailed += 1;
1787
- if (outcome.status === "warn") staticWarnings += 1;
1788
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
1789
- continue;
1790
- }
1791
- passes.push(`Relationship valid: ${rel.parent} contains ${rel.child}.`);
1792
- staticPassed += 1;
1793
- reporter.reportStaticTest(relDescription, "pass", void 0, relationshipLevel);
1794
- }
1795
- }
1796
- async function resolveExpectedValue(expectedValue, selectors, page2, context = {}) {
1797
- if (!expectedValue || typeof expectedValue !== "object" || !("ref" in expectedValue)) return expectedValue;
1798
- let refSelector;
1799
- if (expectedValue.ref === "relative") {
1800
- if (!expectedValue.relativeTarget || !context.relativeBaseSelector) return void 0;
1801
- const baseLocator = page2.locator(context.relativeBaseSelector);
1802
- const count = await baseLocator.count();
1803
- let idx = 0;
1804
- if (expectedValue.relativeTarget === "first") idx = 0;
1805
- else if (expectedValue.relativeTarget === "second") idx = 1;
1806
- else if (expectedValue.relativeTarget === "last") idx = count - 1;
1807
- else if (!isNaN(Number(expectedValue.relativeTarget))) idx = Number(expectedValue.relativeTarget);
1808
- else idx = 0;
1809
- if (idx < 0 || idx >= count) return void 0;
1810
- const relElem = baseLocator.nth(idx);
1811
- return await getPropertyFromLocator(relElem, expectedValue.property || expectedValue.attribute);
1812
- } else {
1813
- refSelector = selectors[expectedValue.ref];
1814
- if (!refSelector) throw new Error(`Selector for ref '${expectedValue.ref}' not found in contract selectors.`);
1815
- const refLocator = page2.locator(refSelector).first();
1816
- return await getPropertyFromLocator(refLocator, expectedValue.property || expectedValue.attribute);
1817
- }
1818
- }
1819
- async function getPropertyFromLocator(locator, property) {
1820
- if (!locator) return void 0;
1821
- if (!property || property === "id") {
1822
- return await locator.getAttribute("id") ?? void 0;
1823
- } else if (property === "class") {
1824
- return await locator.getAttribute("class") ?? void 0;
1825
- } else if (property === "textContent") {
1826
- return await locator.evaluate((el) => el.textContent ?? void 0);
1827
- } else if (property.startsWith("aria-")) {
1828
- return await locator.getAttribute(property) ?? void 0;
1829
- } else if (property.endsWith("*")) {
1830
- const attrs = await locator.evaluate((el) => {
1831
- const out = [];
1832
- for (const attr of Array.from(el.attributes)) {
1833
- if (attr.name.startsWith("aria-")) out.push(`${attr.name}=${attr.value}`);
1834
- }
1835
- return out.join(";");
1836
- });
1837
- return attrs;
1838
- } else {
1839
- return await locator.getAttribute(property) ?? void 0;
1840
- }
1841
- }
1842
- const staticAssertionRunner = new AssertionRunner(page, componentContract.selectors, assertionTimeoutMs);
1843
- async function runSetupActions(setup, actionExecutor, strategy2, page2, description, skipKeywords = []) {
1844
- if (!Array.isArray(setup) || setup.length === 0) return { success: true };
1845
- if (strategy2 && typeof strategy2.resetState === "function") {
1846
- await strategy2.resetState(page2);
1847
- }
1848
- for (const setupAct of setup) {
1849
- let setupResult = { success: true };
1850
- try {
1851
- if (setupAct.type === "focus") {
1852
- if (setupAct.target === "relative" && setupAct.relativeTarget) {
1853
- setupResult = await actionExecutor.focus("relative", setupAct.relativeTarget);
1854
- } else {
1855
- setupResult = await actionExecutor.focus(setupAct.target);
1856
- }
1857
- } else if (setupAct.type === "type" && setupAct.value) {
1858
- setupResult = await actionExecutor.type(setupAct.target, setupAct.value);
1859
- } else if (setupAct.type === "click") {
1860
- setupResult = await actionExecutor.click(setupAct.target, setupAct.relativeTarget);
1861
- } else if (setupAct.type === "keypress" && setupAct.key) {
1862
- setupResult = await actionExecutor.keypress(setupAct.target, setupAct.key);
1863
- } else if (setupAct.type === "hover") {
1864
- setupResult = await actionExecutor.hover(setupAct.target, setupAct.relativeTarget);
1865
- } else {
1866
- continue;
1867
- }
1868
- } catch (err) {
1869
- setupResult = { success: false, error: err instanceof Error ? err.message : String(err) };
1870
- }
1871
- if (!setupResult.success) {
1872
- const setupMsg = setupResult.error || "Setup action failed";
1873
- const isSkip = skipKeywords.some((kw) => description.includes(kw) || setupMsg.includes(kw));
1874
- if (isSkip) {
1875
- return { success: false, skip: true, message: `Skipping test - capability not present: ${setupMsg}` };
1876
- }
1877
- return { success: false, error: setupMsg };
1878
- }
1879
- }
1880
- return { success: true };
1881
- }
1882
- for (const test of componentContract.static[0]?.assertions || []) {
1883
- if (strategy && typeof strategy.resetState === "function") {
1884
- try {
1885
- await strategy.resetState(page);
1886
- } catch (err) {
1887
- warnings.push(`Warning: resetState failed before static test: ${err instanceof Error ? err.message : String(err)}`);
1888
- }
1889
- }
1890
- if (test.target === "relative") continue;
1891
- const staticDescription = `${test.target}${test.attribute ? ` (${test.attribute})` : ""}`;
1892
- const staticLevel = normalizeLevel(test.level);
1893
- if (componentName === "menu" && test.target === "submenuTrigger" && !hasSubmenuCapability) {
1894
- const skipMessage = `Skipping submenu static assertion for ${test.target}: no submenu capability detected in rendered component.`;
1895
- skipped.push(skipMessage);
1896
- reporter.reportStaticTest(staticDescription, "skip", skipMessage, staticLevel);
1897
- continue;
1898
- }
1899
- if (Array.isArray(test.setup) && test.setup.length > 0) {
1900
- let isAllowedType2 = function(t) {
1901
- return allowedTypes.includes(t);
1902
- };
1903
- var isAllowedType = isAllowedType2;
1904
- const actionExecutor = new ActionExecutor(page, componentContract.selectors, actionTimeoutMs);
1905
- const allowedTypes = ["focus", "type", "click", "keypress", "hover"];
1906
- const toSetupAction = (a) => ({
1907
- ...a,
1908
- type: isAllowedType2(a.type) ? a.type : "click"
1909
- });
1910
- const setupActions = test.setup.map(toSetupAction);
1911
- const setupResult = await runSetupActions(setupActions, actionExecutor, strategy, page, staticDescription, ["submenu", "submenuTrigger", "submenuItems"]);
1912
- if (setupResult.skip) {
1913
- skipped.push(setupResult.message || "Setup action skipped");
1914
- reporter.reportStaticTest(staticDescription, "skip", setupResult.message, staticLevel);
1915
- continue;
1916
- }
1917
- if (!setupResult.success) {
1918
- const failure = `Static setup failed: ${setupResult.error}`;
1919
- const outcome = classifyFailure(failure, test.level);
1920
- if (outcome.status === "fail") staticFailed += 1;
1921
- if (outcome.status === "warn") staticWarnings += 1;
1922
- reporter.reportStaticTest(staticDescription, outcome.status, outcome.detail, outcome.level);
1923
- continue;
1924
- }
1925
- }
1926
- const targetSelector = componentContract.selectors[test.target];
1927
- if (!targetSelector) {
1928
- const failure = `Selector for target ${test.target} not found.`;
1929
- const outcome = classifyFailure(failure, test.level);
1930
- if (outcome.status === "fail") staticFailed += 1;
1931
- if (outcome.status === "warn") staticWarnings += 1;
1932
- reporter.reportStaticTest(staticDescription, outcome.status, outcome.detail, outcome.level);
1933
- continue;
1934
- }
1935
- const target = page.locator(targetSelector).first();
1936
- const exists = await target.count() > 0;
1937
- if (!exists) {
1938
- const failure = `Target ${test.target} not found.`;
1939
- const outcome = classifyFailure(failure, test.level);
1940
- if (outcome.status === "fail") staticFailed += 1;
1941
- if (outcome.status === "warn") staticWarnings += 1;
1942
- reporter.reportStaticTest(staticDescription, outcome.status, outcome.detail, outcome.level);
1943
- continue;
1944
- }
1945
- const isRedundantCheck = (selector, attrName, expectedVal) => {
1946
- const attrPattern = new RegExp(`\\[${attrName}(?:=["']?([^\\]"']+)["']?)?\\]`);
1947
- const match = selector.match(attrPattern);
1948
- if (!match) return false;
1949
- if (!expectedVal) return true;
1950
- const selectorValue = match[1];
1951
- if (selectorValue) {
1952
- const expectedValues = expectedVal.split(" | ");
1953
- return expectedValues.includes(selectorValue);
1954
- }
1955
- return false;
1956
- };
1957
- let expectedValue = test.expectedValue;
1958
- if (test.expectedValue && typeof test.expectedValue === "object" && "ref" in test.expectedValue) {
1959
- const context = {};
1960
- const relTarget = test.relativeTarget;
1961
- if (test.expectedValue.ref === "relative" && test.target === "relative" && relTarget) {
1962
- const baseSel = componentContract.selectors[relTarget];
1963
- if (!baseSel) throw new Error(`Selector for relativeTarget '${relTarget}' not found in contract selectors.`);
1964
- context.relativeBaseSelector = baseSel;
1965
- } else if (test.expectedValue.ref === "relative" && relTarget) {
1966
- const baseSel = componentContract.selectors[relTarget];
1967
- if (!baseSel) throw new Error(`Selector for relativeTarget '${relTarget}' not found in contract selectors.`);
1968
- context.relativeBaseSelector = baseSel;
1969
- }
1970
- expectedValue = await resolveExpectedValue(test.expectedValue, componentContract.selectors, page, context);
1971
- console.log("Expected value in static check", expectedValue);
1972
- }
1973
- if (!test.expectedValue) {
1974
- const attributes = test.attribute.split(" | ");
1975
- let hasAny = false;
1976
- let allRedundant = true;
1977
- for (const attr of attributes) {
1978
- const attrTrimmed = attr.trim();
1979
- if (isRedundantCheck(targetSelector, attrTrimmed)) {
1980
- passes.push(`${attrTrimmed} on ${test.target} verified by selector (already present in: ${targetSelector}).`);
1981
- hasAny = true;
1982
- continue;
1983
- }
1984
- allRedundant = false;
1985
- const value = await target.getAttribute(attrTrimmed);
1986
- if (value !== null) {
1987
- hasAny = true;
1988
- break;
1989
- }
1990
- }
1991
- if (!hasAny && !allRedundant) {
1992
- const failure = test.failureMessage + ` None of the attributes "${test.attribute}" are present.`;
1993
- const outcome = classifyFailure(failure, test.level);
1994
- if (outcome.status === "fail") staticFailed += 1;
1995
- if (outcome.status === "warn") staticWarnings += 1;
1996
- reporter.reportStaticTest(staticDescription, outcome.status, outcome.detail, outcome.level);
1997
- } else if (!allRedundant && hasAny) {
1998
- passes.push(`At least one of the attributes "${test.attribute}" exists on the element.`);
1999
- staticPassed += 1;
2000
- reporter.reportStaticTest(staticDescription, "pass", void 0, staticLevel);
2001
- } else {
2002
- staticPassed += 1;
2003
- reporter.reportStaticTest(staticDescription, "pass", void 0, staticLevel);
2004
- }
2005
- } else {
2006
- if (isRedundantCheck(targetSelector, test.attribute, typeof expectedValue === "string" ? expectedValue : void 0)) {
2007
- passes.push(`${test.attribute}="${expectedValue}" on ${test.target} verified by selector (already present in: ${targetSelector}).`);
2008
- staticPassed += 1;
2009
- reporter.reportStaticTest(staticDescription, "pass", void 0, staticLevel);
2010
- } else {
2011
- const valueToCheck = expectedValue ?? "";
2012
- const result = await staticAssertionRunner.validateAttribute(
2013
- target,
2014
- test.target,
2015
- test.attribute,
2016
- valueToCheck,
2017
- test.failureMessage,
2018
- "Static ARIA Test"
2019
- );
2020
- if (result.success && result.passMessage) {
2021
- passes.push(result.passMessage);
2022
- staticPassed += 1;
2023
- reporter.reportStaticTest(staticDescription, "pass", void 0, staticLevel);
2024
- } else if (!result.success && result.failMessage) {
2025
- const outcome = classifyFailure(result.failMessage, test.level);
2026
- if (outcome.status === "fail") staticFailed += 1;
2027
- if (outcome.status === "warn") staticWarnings += 1;
2028
- reporter.reportStaticTest(staticDescription, outcome.status, outcome.detail, outcome.level);
2029
- }
2030
- }
2031
- }
2032
- }
2033
- for (const dynamicTest of componentContract.dynamic || []) {
2034
- if (!page || page.isClosed()) {
2035
- console.warn(`
2036
- \u26A0\uFE0F Browser closed - skipping remaining ${componentContract.dynamic.length - componentContract.dynamic.indexOf(dynamicTest)} tests
2037
- `);
2038
- failures.push(`CRITICAL: Browser/page closed before completing all tests. ${componentContract.dynamic.length - componentContract.dynamic.indexOf(dynamicTest)} tests skipped.`);
2039
- break;
2040
- }
2041
- try {
2042
- await strategy.resetState(page);
2043
- } catch (error) {
2044
- const errorMessage = error instanceof Error ? error.message : String(error);
2045
- reporter.error(errorMessage);
2046
- throw error;
2047
- }
2048
- const { setup = [], action, assertions } = dynamicTest;
2049
- const dynamicLevel = normalizeLevel(dynamicTest.level);
2050
- const actionExecutor = new ActionExecutor(page, componentContract.selectors, actionTimeoutMs);
2051
- if (Array.isArray(setup) && setup.length > 0) {
2052
- let isAllowedType2 = function(t) {
2053
- return allowedTypes.includes(t);
2054
- };
2055
- var isAllowedType = isAllowedType2;
2056
- const allowedTypes = ["focus", "type", "click", "keypress", "hover"];
2057
- const toSetupAction = (a) => ({
2058
- ...a,
2059
- type: isAllowedType2(a.type) ? a.type : "click"
2060
- });
2061
- const setupActions = setup.map(toSetupAction);
2062
- const setupResult = await runSetupActions(setupActions, actionExecutor, strategy, page, dynamicTest.description, ["submenu", "submenuTrigger", "submenuItems"]);
2063
- if (setupResult.skip) {
2064
- skipped.push(setupResult.message || "Setup action skipped");
2065
- reporter.reportTest({ description: dynamicTest.description, level: dynamicLevel }, "skip", setupResult.message);
2066
- continue;
2067
- }
2068
- if (!setupResult.success) {
2069
- const outcome = classifyFailure(`Setup failed: ${setupResult.error}`, dynamicTest.level);
2070
- reporter.reportTest({ description: dynamicTest.description, level: dynamicLevel }, outcome.status, outcome.detail);
2071
- continue;
2072
- }
2073
- }
2074
- const failuresBeforeTest = failures.length;
2075
- const warningsBeforeTest = warnings.length;
2076
- const skippedBeforeTest = skipped.length;
2077
- const shouldSkipTest = await strategy.shouldSkipTest(dynamicTest, page);
2078
- if (shouldSkipTest) {
2079
- const skipMessage = `Skipping test - component-specific conditions not met`;
2080
- skipped.push(skipMessage);
2081
- reporter.reportTest({ description: dynamicTest.description, level: dynamicLevel }, "skip", skipMessage);
2082
- continue;
2083
- }
2084
- const assertionRunner = new AssertionRunner(page, componentContract.selectors, assertionTimeoutMs);
2085
- let shouldAbortCurrentTest = false;
2086
- let actionOutcome = null;
2087
- for (const act of action) {
2088
- if (!page || page.isClosed()) {
2089
- failures.push(`CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`);
2090
- shouldAbortCurrentTest = true;
2091
- break;
2092
- }
2093
- let result;
2094
- if (act.type === "focus") {
2095
- if (act.target === "relative" && act.relativeTarget) {
2096
- result = await actionExecutor.focus("relative", act.relativeTarget);
2097
- } else {
2098
- result = await actionExecutor.focus(act.target);
2099
- }
2100
- } else if (act.type === "type" && act.value) {
2101
- result = await actionExecutor.type(act.target, act.value);
2102
- } else if (act.type === "click") {
2103
- result = await actionExecutor.click(act.target, act.relativeTarget);
2104
- } else if (act.type === "keypress" && act.key) {
2105
- result = await actionExecutor.keypress(act.target, act.key);
2106
- } else if (act.type === "hover") {
2107
- result = await actionExecutor.hover(act.target, act.relativeTarget);
2108
- } else {
2109
- continue;
2110
- }
2111
- if (!result.success) {
2112
- if (result.error) {
2113
- const outcome = classifyFailure(result.error, dynamicTest.level);
2114
- actionOutcome = { status: outcome.status, detail: outcome.detail };
2115
- }
2116
- shouldAbortCurrentTest = true;
2117
- break;
2118
- }
2119
- }
2120
- if (shouldAbortCurrentTest) {
2121
- reporter.reportTest(
2122
- { description: dynamicTest.description, level: dynamicLevel },
2123
- actionOutcome?.status || "fail",
2124
- actionOutcome?.detail || failures[failures.length - 1]
2125
- );
2126
- continue;
2127
- }
2128
- for (const assertion of assertions) {
2129
- let expectedValue;
2130
- if (assertion.expectedValue && typeof assertion.expectedValue === "object" && "ref" in assertion.expectedValue) {
2131
- if (assertion.expectedValue.ref === "relative") {
2132
- const { RelativeTargetResolver: RelativeTargetResolver2 } = await Promise.resolve().then(() => (init_RelativeTargetResolver(), RelativeTargetResolver_exports));
2133
- const relativeSelector = componentContract.selectors.relative;
2134
- if (!relativeSelector) throw new Error("Relative selector not defined in contract selectors.");
2135
- const relTarget = assertion.relativeTarget || "first";
2136
- const relElem = await RelativeTargetResolver2.resolve(page, relativeSelector, relTarget);
2137
- if (!relElem) throw new Error(`Could not resolve relative target '${relTarget}' for expectedValue.`);
2138
- const prop = assertion.expectedValue.property || assertion.expectedValue.attribute || "id";
2139
- if (prop === "textContent") {
2140
- expectedValue = await relElem.evaluate((el) => el.textContent ?? void 0);
2141
- } else {
2142
- const attr = await relElem.getAttribute(prop);
2143
- expectedValue = attr === null ? void 0 : attr;
2144
- }
2145
- } else {
2146
- expectedValue = await resolveExpectedValue(assertion.expectedValue, componentContract.selectors, page, {});
2147
- }
2148
- } else if (typeof assertion.expectedValue === "string" || typeof assertion.expectedValue === "undefined") {
2149
- expectedValue = assertion.expectedValue;
2150
- } else {
2151
- expectedValue = "";
2152
- }
2153
- const assertionToRun = { ...assertion, expectedValue };
2154
- const valueToCheck = expectedValue ?? "";
2155
- const result = await assertionRunner.validate({ ...assertionToRun, expectedValue: valueToCheck }, dynamicTest.description);
2156
- if (result.success && result.passMessage) {
2157
- passes.push(result.passMessage);
2158
- } else if (!result.success && result.failMessage) {
2159
- const assertionLevel = normalizeLevel(assertion.level || dynamicTest.level);
2160
- const outcome = classifyFailure(result.failMessage, assertionLevel);
2161
- if (outcome.status === "skip") {
2162
- continue;
2163
- }
2164
- }
2165
- }
2166
- const failuresAfterTest = failures.length;
2167
- const warningsAfterTest = warnings.length;
2168
- const skippedAfterTest = skipped.length;
2169
- if (failuresAfterTest > failuresBeforeTest) {
2170
- reporter.reportTest(
2171
- { description: dynamicTest.description, level: dynamicLevel },
2172
- "fail",
2173
- failures[failures.length - 1]
2174
- );
2175
- } else if (warningsAfterTest > warningsBeforeTest) {
2176
- reporter.reportTest(
2177
- { description: dynamicTest.description, level: dynamicLevel },
2178
- "warn",
2179
- warnings[warnings.length - 1]
2180
- );
2181
- } else if (skippedAfterTest > skippedBeforeTest) {
2182
- reporter.reportTest(
2183
- { description: dynamicTest.description, level: dynamicLevel },
2184
- "skip",
2185
- skipped[skipped.length - 1]
2186
- );
2187
- } else {
2188
- reporter.reportTest({ description: dynamicTest.description, level: dynamicLevel }, "pass");
2189
- }
2190
- }
2191
- reporter.reportStatic(staticPassed, staticFailed, staticWarnings);
2192
- reporter.summary(failures);
2193
- } catch (error) {
2194
- if (error instanceof Error) {
2195
- if (error.message.includes("Executable doesn't exist") || error.message.includes("browserType.launch")) {
2196
- throw new Error("\n\u274C CRITICAL: Playwright browsers not found!\n\u{1F4E6} Run: npx playwright install chromium");
2197
- } else if (error.message.includes("net::ERR_CONNECTION_REFUSED") || error.message.includes("NS_ERROR_CONNECTION_REFUSED")) {
2198
- throw new Error(`
35
+ - The component selector '${O}' in the contract is wrong
36
+ - Original error: ${s}`)}a.start(c,mt,ht),c==="menu"&&S.selectors.main&&await $.locator(S.selectors.main).first().waitFor({state:"visible",timeout:me}).catch(()=>{});let q=c==="menu"&&S.selectors.submenuTrigger?await $.locator(S.selectors.submenuTrigger).count()>0:!1,U=s=>s.type==="aria-reference"&&[s.from,s.to].some(f=>["submenu","submenuTrigger","submenuItems"].includes(f||""))||s.type==="contains"&&[s.parent,s.child].some(f=>["submenu","submenuTrigger","submenuItems"].includes(f||"")),_=0,F=0,V=0;for(let s of S.relationships||[]){if(h&&typeof h.resetState=="function")try{await h.resetState($);}catch(m){G.push(`Warning: resetState failed before relationship test: ${m instanceof Error?m.message:String(m)}`);}let f=se(s.level);if(Array.isArray(s.setup)&&s.setup.length>0){let C=function(l){return T.includes(l)};var Fe=C;let m=new re($,S.selectors,K),k=s.type==="aria-reference"?`${s.from}.${s.attribute} references ${s.to}`:`${s.parent} contains ${s.child}`,T=["focus","type","click","keypress","hover"],w=l=>({...l,type:C(l.type)?l.type:"click"}),v=s.setup.map(w),g=await he(v,m,h,$,k,["submenu","submenuTrigger","submenuItems"]);if(g.skip){I.push(g.message||"Setup action skipped"),a.reportStaticTest(k,"skip",g.message,f);continue}if(!g.success){let l=`Relationship setup failed: ${g.error}`,d=P(l,s.level);d.status==="fail"&&(F+=1),d.status==="warn"&&(V+=1),a.reportStaticTest(k,d.status,d.detail,d.level);continue}}if(c==="menu"&&!q&&U(s)){let k=s.type==="aria-reference"?`${s.from}.${s.attribute} references ${s.to}`:`${s.parent} contains ${s.child}`,T="Skipping submenu relationship assertion: no submenu capability detected in rendered component.";I.push(T),a.reportStaticTest(k,"skip",T,f);continue}if(s.type==="aria-reference"){let m=`${s.from}.${s.attribute} references ${s.to}`,k=S.selectors[s.from],T=S.selectors[s.to];if(!k||!T){let y=P(`Relationship selector missing: from="${s.from}" or to="${s.to}" not found in selectors.`,s.level);y.status==="fail"&&(F+=1),y.status==="warn"&&(V+=1),a.reportStaticTest(m,y.status,y.detail,y.level);continue}let C=$.locator(k).first(),w=$.locator(T).first(),v=await C.count()>0,g=await w.count()>0;if(!v||!g){if(c==="menu"&&U(s)){let ne="Skipping submenu relationship assertion in static phase: submenu elements are not present until submenu is opened.";I.push(ne),a.reportStaticTest(m,"skip",ne,f);continue}let y=P(`Relationship target not found: ${v?s.to:s.from}.`,s.level);y.status==="fail"&&(F+=1),y.status==="warn"&&(V+=1),a.reportStaticTest(m,y.status,y.detail,y.level);continue}let l=await C.getAttribute(s.attribute),d=await w.getAttribute("id");if(!d){let y=P(`Relationship target "${s.to}" must have an id for ${s.attribute} validation.`,s.level);y.status==="fail"&&(F+=1),y.status==="warn"&&(V+=1),a.reportStaticTest(m,y.status,y.detail,y.level);continue}if(!(l||"").split(/\s+/).filter(Boolean).includes(d)){let y=P(`Expected ${s.from} ${s.attribute} to reference id "${d}", found "${l||""}".`,s.level);y.status==="fail"&&(F+=1),y.status==="warn"&&(V+=1),a.reportStaticTest(m,y.status,y.detail,y.level);continue}N.push(`Relationship valid: ${s.from}.${s.attribute} -> ${s.to} (id=${d}).`),_+=1,a.reportStaticTest(m,"pass",void 0,f);continue}if(s.type==="contains"){let m=`${s.parent} contains ${s.child}`,k=S.selectors[s.parent],T=S.selectors[s.child];if(!k||!T){let l=P(`Relationship selector missing: parent="${s.parent}" or child="${s.child}" not found in selectors.`,s.level);l.status==="fail"&&(F+=1),l.status==="warn"&&(V+=1),a.reportStaticTest(m,l.status,l.detail,l.level);continue}let C=$.locator(k).first();if(!(await C.count()>0)){if(c==="menu"&&U(s)){let d="Skipping submenu relationship assertion in static phase: submenu container is not present until submenu is opened.";I.push(d),a.reportStaticTest(m,"skip",d,f);continue}let l=P(`Relationship parent target not found: ${s.parent}.`,s.level);l.status==="fail"&&(F+=1),l.status==="warn"&&(V+=1),a.reportStaticTest(m,l.status,l.detail,l.level);continue}if(await C.locator(T).count()<1){if(c==="menu"&&U(s)){let d="Skipping submenu relationship assertion in static phase: submenu descendants are not present until submenu is opened.";I.push(d),a.reportStaticTest(m,"skip",d,f);continue}let l=P(`Expected ${s.parent} to contain descendant matching selector for ${s.child}.`,s.level);l.status==="fail"&&(F+=1),l.status==="warn"&&(V+=1),a.reportStaticTest(m,l.status,l.detail,l.level);continue}N.push(`Relationship valid: ${s.parent} contains ${s.child}.`),_+=1,a.reportStaticTest(m,"pass",void 0,f);}}async function Ve(s,f,m,k={}){if(!s||typeof s!="object"||!("ref"in s))return s;let T;if(s.ref==="relative"){if(!s.relativeTarget||!k.relativeBaseSelector)return;let C=m.locator(k.relativeBaseSelector),w=await C.count(),v=0;if(s.relativeTarget==="first"?v=0:s.relativeTarget==="second"?v=1:s.relativeTarget==="last"?v=w-1:isNaN(Number(s.relativeTarget))?v=0:v=Number(s.relativeTarget),v<0||v>=w)return;let g=C.nth(v);return await Ue(g,s.property||s.attribute)}else {if(T=f[s.ref],!T)throw new Error(`Selector for ref '${s.ref}' not found in contract selectors.`);let C=m.locator(T).first();return await Ue(C,s.property||s.attribute)}}async function Ue(s,f){if(s)return !f||f==="id"?await s.getAttribute("id")??void 0:f==="class"?await s.getAttribute("class")??void 0:f==="textContent"?await s.evaluate(m=>m.textContent??void 0):f.startsWith("aria-")?await s.getAttribute(f)??void 0:f.endsWith("*")?await s.evaluate(k=>{let T=[];for(let C of Array.from(k.attributes))C.name.startsWith("aria-")&&T.push(`${C.name}=${C.value}`);return T.join(";")}):await s.getAttribute(f)??void 0}let yt=new ae($,S.selectors,Q);async function he(s,f,m,k,T,C=[]){if(!Array.isArray(s)||s.length===0)return {success:!0};m&&typeof m.resetState=="function"&&await m.resetState(k);for(let w of s){let v={success:!0};try{if(w.type==="focus")w.target==="relative"&&w.relativeTarget?v=await f.focus("relative",w.relativeTarget):v=await f.focus(w.target);else if(w.type==="type"&&w.value)v=await f.type(w.target,w.value);else if(w.type==="click")v=await f.click(w.target,w.relativeTarget);else if(w.type==="keypress"&&w.key)v=await f.keypress(w.target,w.key);else if(w.type==="hover")v=await f.hover(w.target,w.relativeTarget);else continue}catch(g){v={success:!1,error:g instanceof Error?g.message:String(g)};}if(!v.success){let g=v.error||"Setup action failed";return C.some(d=>T.includes(d)||g.includes(d))?{success:!1,skip:!0,message:`Skipping test - capability not present: ${g}`}:{success:!1,error:g}}}return {success:!0}}for(let s of S.static[0]?.assertions||[]){if(h&&typeof h.resetState=="function")try{await h.resetState($);}catch(g){G.push(`Warning: resetState failed before static test: ${g instanceof Error?g.message:String(g)}`);}if(s.target==="relative")continue;let f=`${s.target}${s.attribute?` (${s.attribute})`:""}`,m=se(s.level);if(c==="menu"&&s.target==="submenuTrigger"&&!q){let g=`Skipping submenu static assertion for ${s.target}: no submenu capability detected in rendered component.`;I.push(g),a.reportStaticTest(f,"skip",g,m);continue}if(Array.isArray(s.setup)&&s.setup.length>0){let d=function(z){return l.includes(z)};var Fe=d;let g=new re($,S.selectors,K),l=["focus","type","click","keypress","hover"],j=z=>({...z,type:d(z.type)?z.type:"click"}),E=s.setup.map(j),y=await he(E,g,h,$,f,["submenu","submenuTrigger","submenuItems"]);if(y.skip){I.push(y.message||"Setup action skipped"),a.reportStaticTest(f,"skip",y.message,m);continue}if(!y.success){let z=`Static setup failed: ${y.error}`,u=P(z,s.level);u.status==="fail"&&(F+=1),u.status==="warn"&&(V+=1),a.reportStaticTest(f,u.status,u.detail,u.level);continue}}let k=S.selectors[s.target];if(!k){let g=`Selector for target ${s.target} not found.`,l=P(g,s.level);l.status==="fail"&&(F+=1),l.status==="warn"&&(V+=1),a.reportStaticTest(f,l.status,l.detail,l.level);continue}let T=$.locator(k).first();if(!(await T.count()>0)){let g=`Target ${s.target} not found.`,l=P(g,s.level);l.status==="fail"&&(F+=1),l.status==="warn"&&(V+=1),a.reportStaticTest(f,l.status,l.detail,l.level);continue}let w=(g,l,d)=>{let j=new RegExp(`\\[${l}(?:=["']?([^\\]"']+)["']?)?\\]`),E=g.match(j);if(!E)return !1;if(!d)return !0;let y=E[1];return y?d.split(" | ").includes(y):!1},v=s.expectedValue;if(s.expectedValue&&typeof s.expectedValue=="object"&&"ref"in s.expectedValue){let g={},l=s.relativeTarget;if(s.expectedValue.ref==="relative"&&s.target==="relative"&&l){let d=S.selectors[l];if(!d)throw new Error(`Selector for relativeTarget '${l}' not found in contract selectors.`);g.relativeBaseSelector=d;}else if(s.expectedValue.ref==="relative"&&l){let d=S.selectors[l];if(!d)throw new Error(`Selector for relativeTarget '${l}' not found in contract selectors.`);g.relativeBaseSelector=d;}v=await Ve(s.expectedValue,S.selectors,$,g),console.log("Expected value in static check",v);}if(s.expectedValue)if(w(k,s.attribute,typeof v=="string"?v:void 0))N.push(`${s.attribute}="${v}" on ${s.target} verified by selector (already present in: ${k}).`),_+=1,a.reportStaticTest(f,"pass",void 0,m);else {let g=v??"",l=await yt.validateAttribute(T,s.target,s.attribute,g,s.failureMessage,"Static ARIA Test");if(l.success&&l.passMessage)N.push(l.passMessage),_+=1,a.reportStaticTest(f,"pass",void 0,m);else if(!l.success&&l.failMessage){let d=P(l.failMessage,s.level);d.status==="fail"&&(F+=1),d.status==="warn"&&(V+=1),a.reportStaticTest(f,d.status,d.detail,d.level);}}else {let g=s.attribute.split(" | "),l=!1,d=!0;for(let j of g){let E=j.trim();if(w(k,E)){N.push(`${E} on ${s.target} verified by selector (already present in: ${k}).`),l=!0;continue}if(d=!1,await T.getAttribute(E)!==null){l=!0;break}}if(!l&&!d){let j=s.failureMessage+` None of the attributes "${s.attribute}" are present.`,E=P(j,s.level);E.status==="fail"&&(F+=1),E.status==="warn"&&(V+=1),a.reportStaticTest(f,E.status,E.detail,E.level);}else !d&&l?(N.push(`At least one of the attributes "${s.attribute}" exists on the element.`),_+=1,a.reportStaticTest(f,"pass",void 0,m)):(_+=1,a.reportStaticTest(f,"pass",void 0,m));}}for(let s of S.dynamic||[]){if(!$||$.isClosed()){console.warn(`
37
+ \u26A0\uFE0F Browser closed - skipping remaining ${S.dynamic.length-S.dynamic.indexOf(s)} tests
38
+ `),H.push(`CRITICAL: Browser/page closed before completing all tests. ${S.dynamic.length-S.dynamic.indexOf(s)} tests skipped.`);break}try{await h.resetState($);}catch(u){let R=u instanceof Error?u.message:String(u);throw a.error(R),u}let{setup:f=[],action:m,assertions:k}=s,T=se(s.level),C=new re($,S.selectors,K);if(Array.isArray(f)&&f.length>0){let R=function(W){return u.includes(W)};var Fe=R;let u=["focus","type","click","keypress","hover"],Z=W=>({...W,type:R(W.type)?W.type:"click"}),ye=f.map(Z),D=await he(ye,C,h,$,s.description,["submenu","submenuTrigger","submenuItems"]);if(D.skip){I.push(D.message||"Setup action skipped"),a.reportTest({description:s.description,level:T},"skip",D.message);continue}if(!D.success){let W=P(`Setup failed: ${D.error}`,s.level);a.reportTest({description:s.description,level:T},W.status,W.detail);continue}}let w=H.length,v=G.length,g=I.length;if(await h.shouldSkipTest(s,$)){let u="Skipping test - component-specific conditions not met";I.push(u),a.reportTest({description:s.description,level:T},"skip",u);continue}let d=new ae($,S.selectors,Q),j=!1,E=null;for(let u of m){if(!$||$.isClosed()){H.push("CRITICAL: Browser/page closed during test execution. Remaining actions skipped."),j=!0;break}let R;if(u.type==="focus")u.target==="relative"&&u.relativeTarget?R=await C.focus("relative",u.relativeTarget):R=await C.focus(u.target);else if(u.type==="type"&&u.value)R=await C.type(u.target,u.value);else if(u.type==="click")R=await C.click(u.target,u.relativeTarget);else if(u.type==="keypress"&&u.key)R=await C.keypress(u.target,u.key);else if(u.type==="hover")R=await C.hover(u.target,u.relativeTarget);else continue;if(!R.success){if(R.error){let Z=P(R.error,s.level);E={status:Z.status,detail:Z.detail};}j=!0;break}}if(j){a.reportTest({description:s.description,level:T},E?.status||"fail",E?.detail||H[H.length-1]);continue}for(let u of k){let R;if(u.expectedValue&&typeof u.expectedValue=="object"&&"ref"in u.expectedValue)if(u.expectedValue.ref==="relative"){let{RelativeTargetResolver:we}=await Promise.resolve().then(()=>(ge(),nt)),W=S.selectors.relative;if(!W)throw new Error("Relative selector not defined in contract selectors.");let je=u.relativeTarget||"first",ve=await we.resolve($,W,je);if(!ve)throw new Error(`Could not resolve relative target '${je}' for expectedValue.`);let De=u.expectedValue.property||u.expectedValue.attribute||"id";if(De==="textContent")R=await ve.evaluate(le=>le.textContent??void 0);else {let le=await ve.getAttribute(De);R=le===null?void 0:le;}}else R=await Ve(u.expectedValue,S.selectors,$,{});else typeof u.expectedValue=="string"||typeof u.expectedValue>"u"?R=u.expectedValue:R="";let Z={...u,expectedValue:R},ye=R??"",D=await d.validate({...Z,expectedValue:ye},s.description);if(D.success&&D.passMessage)N.push(D.passMessage);else if(!D.success&&D.failMessage){let we=se(u.level||s.level);if(P(D.failMessage,we).status==="skip")continue}}let y=H.length,ne=G.length,z=I.length;y>w?a.reportTest({description:s.description,level:T},"fail",H[H.length-1]):ne>v?a.reportTest({description:s.description,level:T},"warn",G[G.length-1]):z>g?a.reportTest({description:s.description,level:T},"skip",I[I.length-1]):a.reportTest({description:s.description,level:T},"pass");}a.reportStatic(_,F,V),a.summary(H);}catch(h){if(h instanceof Error)throw h.message.includes("Executable doesn't exist")||h.message.includes("browserType.launch")?new Error(`
39
+ \u274C CRITICAL: Playwright browsers not found!
40
+ \u{1F4E6} Run: npx playwright install chromium`):h.message.includes("net::ERR_CONNECTION_REFUSED")||h.message.includes("NS_ERROR_CONNECTION_REFUSED")?new Error(`
2199
41
  \u274C CRITICAL: Cannot connect to dev server!
2200
- Make sure your dev server is running at ${url}`);
2201
- } else if (error.message.includes("Timeout") && error.message.includes("waitFor")) {
2202
- throw new Error(
2203
- `
42
+ Make sure your dev server is running at ${e}`):h.message.includes("Timeout")&&h.message.includes("waitFor")?new Error(`
2204
43
  \u274C CRITICAL: Component not found on page!
2205
- The component selector could not be found within ${componentReadyTimeoutMs}ms.
44
+ The component selector could not be found within ${me}ms.
2206
45
  This usually means:
2207
46
  - The component didn't render
2208
47
  - The URL is incorrect
2209
48
  - The component selector was not provided to the component utility, or a wrong selector was used
2210
- `
2211
- );
2212
- } else if (error.message.includes("Target page, context or browser has been closed")) {
2213
- throw new Error(
2214
- "\n\u274C CRITICAL: Browser/page was closed unexpectedly!\nThis usually means:\n - The test timeout was too short\n - The browser crashed\n - An external process killed the browser"
2215
- );
2216
- } else {
2217
- throw error;
2218
- }
2219
- }
2220
- } finally {
2221
- if (page) await page.close();
2222
- }
2223
- return { passes, failures, skipped, warnings };
2224
- }
2225
- var init_contractTestRunnerPlaywright = __esm({
2226
- "src/utils/test/src/contractTestRunnerPlaywright.ts"() {
2227
- init_playwrightTestHarness();
2228
- init_ComponentDetector();
2229
- init_ContractReporter();
2230
- init_ActionExecutor();
2231
- init_AssertionRunner();
2232
- init_strictness();
2233
- }
2234
- });
2235
-
2236
- // src/utils/cli/badgeHelper.ts
2237
- var badgeHelper_exports = {};
2238
- __export(badgeHelper_exports, {
2239
- BADGE_CONFIGS: () => BADGE_CONFIGS,
2240
- displayAllBadges: () => displayAllBadges,
2241
- displayBadgeInfo: () => displayBadgeInfo,
2242
- getBadgeMarkdown: () => getBadgeMarkdown,
2243
- promptAddBadge: () => promptAddBadge
2244
- });
2245
- function getBadgeMarkdown(badgeType) {
2246
- const config = BADGE_CONFIGS[badgeType];
2247
- return `[![${config.label}](${config.markdownUrl})](https://github.com/aria-ease/aria-ease)`;
2248
- }
2249
- function displayBadgeInfo(badgeType) {
2250
- const markdown = getBadgeMarkdown(badgeType);
2251
- console.log(chalk__default.default.cyan("\n\u{1F3C5} Show your accessibility commitment!"));
2252
- console.log(chalk__default.default.white(" Add this badge to your README.md:\n"));
2253
- console.log(chalk__default.default.green(" " + markdown));
2254
- console.log(chalk__default.default.dim("\n This helps others discover accessibility tools and shows you care!\n"));
2255
- }
2256
- async function promptAddBadge(badgeType, cwd = process.cwd()) {
2257
- const readmePath = path3__default.default.join(cwd, "README.md");
2258
- const readmeExists = await fs3__default.default.pathExists(readmePath);
2259
- if (!readmeExists) {
2260
- console.log(chalk__default.default.yellow(" \u2139\uFE0F No README.md found in current directory"));
2261
- return;
2262
- }
2263
- const readmeContent = await fs3__default.default.readFile(readmePath, "utf-8");
2264
- const markdown = getBadgeMarkdown(badgeType);
2265
- if (readmeContent.includes(markdown) || readmeContent.includes(BADGE_CONFIGS[badgeType].fileName)) {
2266
- console.log(chalk__default.default.gray(" \u2713 Badge already in README.md"));
2267
- return;
2268
- }
2269
- const rl = readline__default.default.createInterface({
2270
- input: process.stdin,
2271
- output: process.stdout
2272
- });
2273
- const answer = await new Promise((resolve) => {
2274
- rl.question(chalk__default.default.cyan(" Add badge to README.md now? (y/n): "), (ans) => {
2275
- rl.close();
2276
- resolve(ans.toLowerCase().trim());
2277
- });
2278
- });
2279
- if (answer === "y" || answer === "yes") {
2280
- await addBadgeToReadme(readmePath, readmeContent, markdown);
2281
- console.log(chalk__default.default.green(" \u2713 Badge added to README.md!"));
2282
- } else {
2283
- console.log(chalk__default.default.gray(" Skipped. You can add it manually anytime."));
2284
- }
2285
- }
2286
- async function addBadgeToReadme(readmePath, content, badge) {
2287
- const lines = content.split("\n");
2288
- let insertIndex = 0;
2289
- for (let i = 0; i < lines.length; i++) {
2290
- const line = lines[i].trim();
2291
- if (line.startsWith("[![") || line.startsWith("[!")) {
2292
- insertIndex = i + 1;
2293
- continue;
2294
- }
2295
- if (insertIndex > 0 && !line.startsWith("[![") && !line.startsWith("[!") && line.length > 0) {
2296
- break;
2297
- }
2298
- if (insertIndex === 0 && line.startsWith("#")) {
2299
- insertIndex = i + 2;
2300
- break;
2301
- }
2302
- }
2303
- if (insertIndex === 0) {
2304
- insertIndex = 1;
2305
- }
2306
- lines.splice(insertIndex, 0, badge);
2307
- await fs3__default.default.writeFile(readmePath, lines.join("\n"), "utf-8");
2308
- }
2309
- function displayAllBadges() {
2310
- console.log(chalk__default.default.cyan("\n\u{1F4CD} Available badges:"));
2311
- console.log(chalk__default.default.white("\n For audits:"));
2312
- console.log(chalk__default.default.green(" " + getBadgeMarkdown("audit")));
2313
- console.log(chalk__default.default.white("\n For component testing:"));
2314
- console.log(chalk__default.default.green(" " + getBadgeMarkdown("component")));
2315
- console.log(chalk__default.default.white("\n For both (verified):"));
2316
- console.log(chalk__default.default.green(" " + getBadgeMarkdown("verified")));
2317
- console.log("");
2318
- }
2319
- var BADGE_CONFIGS;
2320
- var init_badgeHelper = __esm({
2321
- "src/utils/cli/badgeHelper.ts"() {
2322
- BADGE_CONFIGS = {
2323
- audit: {
2324
- type: "audit",
2325
- fileName: "audited-by-aria-ease.svg",
2326
- label: "Audited by aria-ease",
2327
- markdownUrl: "https://cdn.jsdelivr.net/gh/aria-ease/aria-ease@main/badges/audited-by-aria-ease.svg"
2328
- },
2329
- component: {
2330
- type: "component",
2331
- fileName: "components-tested-aria-ease.svg",
2332
- label: "Components tested: aria-ease",
2333
- markdownUrl: "https://cdn.jsdelivr.net/gh/aria-ease/aria-ease@main/badges/components-tested-aria-ease.svg"
2334
- },
2335
- verified: {
2336
- type: "verified",
2337
- fileName: "verified-by-aria-ease.svg",
2338
- label: "Verified by aria-ease",
2339
- markdownUrl: "https://cdn.jsdelivr.net/gh/aria-ease/aria-ease@main/badges/verified-by-aria-ease.svg"
2340
- }
2341
- };
2342
- }
2343
- });
2344
-
2345
- // src/utils/test/src/contractTestRunner.ts
2346
- init_ContractReporter();
2347
- init_strictness();
2348
- async function runContractTests(contractPath, componentName, component, strictness) {
2349
- const reporter = new ContractReporter(false);
2350
- const strictnessMode = normalizeStrictness(strictness);
2351
- if (!contractPath) {
2352
- throw new Error(`No contract path provided for component: ${componentName}`);
2353
- }
2354
- const contractData = await fs__default.default.readFile(contractPath, "utf-8");
2355
- const componentContract = JSON.parse(contractData);
2356
- const totalTests = (componentContract.relationships?.length || 0) + (componentContract.static[0]?.assertions.length || 0) + componentContract.dynamic.length;
2357
- reporter.start(componentName, totalTests);
2358
- const failures = [];
2359
- const passes = [];
2360
- const skipped = [];
2361
- const warnings = [];
2362
- const classifyFailure = (message, levelRaw) => {
2363
- const level = normalizeLevel(levelRaw);
2364
- const enforcement = resolveEnforcement(level, strictnessMode);
2365
- if (enforcement === "error") {
2366
- failures.push(message);
2367
- return { status: "fail", level, detail: message };
2368
- }
2369
- if (enforcement === "warning") {
2370
- warnings.push(message);
2371
- return { status: "warn", level, detail: message };
2372
- }
2373
- const ignoredMessage = `${message} (ignored by strictness=${strictnessMode}, level=${level})`;
2374
- skipped.push(ignoredMessage);
2375
- return { status: "skip", level, detail: ignoredMessage };
2376
- };
2377
- let staticPassed = 0;
2378
- let staticFailed = 0;
2379
- let staticWarnings = 0;
2380
- for (const rel of componentContract.relationships || []) {
2381
- const relationshipLevel = normalizeLevel(rel.level);
2382
- if (rel.type === "aria-reference") {
2383
- const fromSelector = componentContract.selectors[rel.from];
2384
- const toSelector = componentContract.selectors[rel.to];
2385
- const relDescription = `${rel.from}.${rel.attribute} references ${rel.to}`;
2386
- if (!fromSelector || !toSelector) {
2387
- const outcome = classifyFailure(`Relationship selector missing: from="${rel.from}" or to="${rel.to}" not found in selectors.`, rel.level);
2388
- if (outcome.status === "fail") staticFailed += 1;
2389
- if (outcome.status === "warn") staticWarnings += 1;
2390
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
2391
- continue;
2392
- }
2393
- const fromTarget = component.querySelector(fromSelector);
2394
- const toTarget = component.querySelector(toSelector);
2395
- if (!fromTarget || !toTarget) {
2396
- const outcome = classifyFailure(`Relationship target not found: ${!fromTarget ? rel.from : rel.to}.`, rel.level);
2397
- if (outcome.status === "fail") staticFailed += 1;
2398
- if (outcome.status === "warn") staticWarnings += 1;
2399
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
2400
- continue;
2401
- }
2402
- const toId = toTarget.getAttribute("id");
2403
- const attrValue = fromTarget.getAttribute(rel.attribute) || "";
2404
- if (!toId) {
2405
- const outcome = classifyFailure(`Relationship target "${rel.to}" must have an id for ${rel.attribute} validation.`, rel.level);
2406
- if (outcome.status === "fail") staticFailed += 1;
2407
- if (outcome.status === "warn") staticWarnings += 1;
2408
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
2409
- continue;
2410
- }
2411
- const references = attrValue.split(/\s+/).filter(Boolean);
2412
- if (!references.includes(toId)) {
2413
- const outcome = classifyFailure(`Expected ${rel.from} ${rel.attribute} to reference id "${toId}", found "${attrValue}".`, rel.level);
2414
- if (outcome.status === "fail") staticFailed += 1;
2415
- if (outcome.status === "warn") staticWarnings += 1;
2416
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
2417
- continue;
2418
- }
2419
- passes.push(`Relationship valid: ${rel.from}.${rel.attribute} -> ${rel.to} (id=${toId}).`);
2420
- staticPassed += 1;
2421
- reporter.reportStaticTest(relDescription, "pass", void 0, relationshipLevel);
2422
- continue;
2423
- }
2424
- if (rel.type === "contains") {
2425
- const parentSelector = componentContract.selectors[rel.parent];
2426
- const childSelector = componentContract.selectors[rel.child];
2427
- const relDescription = `${rel.parent} contains ${rel.child}`;
2428
- if (!parentSelector || !childSelector) {
2429
- const outcome = classifyFailure(`Relationship selector missing: parent="${rel.parent}" or child="${rel.child}" not found in selectors.`, rel.level);
2430
- if (outcome.status === "fail") staticFailed += 1;
2431
- if (outcome.status === "warn") staticWarnings += 1;
2432
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
2433
- continue;
2434
- }
2435
- const parentTarget = component.querySelector(parentSelector);
2436
- if (!parentTarget) {
2437
- const outcome = classifyFailure(`Relationship parent target not found: ${rel.parent}.`, rel.level);
2438
- if (outcome.status === "fail") staticFailed += 1;
2439
- if (outcome.status === "warn") staticWarnings += 1;
2440
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
2441
- continue;
2442
- }
2443
- const nestedChild = parentTarget.querySelector(childSelector);
2444
- if (!nestedChild) {
2445
- const outcome = classifyFailure(`Expected ${rel.parent} to contain descendant matching selector for ${rel.child}.`, rel.level);
2446
- if (outcome.status === "fail") staticFailed += 1;
2447
- if (outcome.status === "warn") staticWarnings += 1;
2448
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
2449
- continue;
2450
- }
2451
- passes.push(`Relationship valid: ${rel.parent} contains ${rel.child}.`);
2452
- staticPassed += 1;
2453
- reporter.reportStaticTest(relDescription, "pass", void 0, relationshipLevel);
2454
- }
2455
- }
2456
- for (const test of componentContract.static[0].assertions) {
2457
- if (test.target !== "relative") {
2458
- const staticLevel = normalizeLevel(test.level);
2459
- const selector = componentContract.selectors[test.target];
2460
- if (!selector) {
2461
- const outcome = classifyFailure(`Selector for target ${test.target} not found.`, test.level);
2462
- if (outcome.status === "fail") staticFailed += 1;
2463
- if (outcome.status === "warn") staticWarnings += 1;
2464
- reporter.reportStaticTest(`${test.target} has required ARIA attributes`, outcome.status, outcome.detail, outcome.level);
2465
- continue;
2466
- }
2467
- const target = component.querySelector(selector);
2468
- if (!target) {
2469
- const outcome = classifyFailure(`Target ${test.target} not found.`, test.level);
2470
- if (outcome.status === "fail") staticFailed += 1;
2471
- if (outcome.status === "warn") staticWarnings += 1;
2472
- reporter.reportStaticTest(`${test.target} has required ARIA attributes`, outcome.status, outcome.detail, outcome.level);
2473
- continue;
2474
- }
2475
- const attributeValue = target.getAttribute(test.attribute);
2476
- if (!test.expectedValue) {
2477
- const attributes = test.attribute.split(" | ");
2478
- const hasAnyAttribute = attributes.some((attr) => target.hasAttribute(attr));
2479
- if (!hasAnyAttribute) {
2480
- const outcome = classifyFailure(test.failureMessage + ` None of the attributes "${test.attribute}" are present.`, test.level);
2481
- if (outcome.status === "fail") staticFailed += 1;
2482
- if (outcome.status === "warn") staticWarnings += 1;
2483
- reporter.reportStaticTest(`${test.target} has ${test.attribute}`, outcome.status, outcome.detail, outcome.level);
2484
- } else {
2485
- passes.push(`At least one of the attributes "${test.attribute}" exists on the element.`);
2486
- staticPassed += 1;
2487
- reporter.reportStaticTest(`${test.target} has ${test.attribute}`, "pass", void 0, staticLevel);
2488
- }
2489
- } else if (!attributeValue || typeof test.expectedValue === "string" && !test.expectedValue.split(" | ").includes(attributeValue)) {
2490
- const outcome = classifyFailure(test.failureMessage + ` Attribute value does not match expected value. Expected: ${test.expectedValue}, Found: ${attributeValue}`, test.level);
2491
- if (outcome.status === "fail") staticFailed += 1;
2492
- if (outcome.status === "warn") staticWarnings += 1;
2493
- reporter.reportStaticTest(`${test.target} has ${test.attribute}="${test.expectedValue}"`, outcome.status, outcome.detail, outcome.level);
2494
- } else {
2495
- passes.push(`Attribute value matches expected value. Expected: ${test.expectedValue}, Found: ${attributeValue}`);
2496
- staticPassed += 1;
2497
- reporter.reportStaticTest(`${test.target} has ${test.attribute}="${attributeValue}"`, "pass", void 0, staticLevel);
2498
- }
2499
- }
2500
- }
2501
- for (const dynamicTest of componentContract.dynamic) {
2502
- skipped.push(dynamicTest.description);
2503
- reporter.reportTest({ description: dynamicTest.description, level: dynamicTest.level }, "skip");
2504
- }
2505
- reporter.reportStatic(staticPassed, staticFailed, staticWarnings);
2506
- reporter.summary(failures);
2507
- return { passes, failures, skipped, warnings };
2508
- }
2509
-
2510
- // src/utils/test/src/test.ts
2511
- init_playwrightTestHarness();
2512
- init_strictness();
2513
- async function testUiComponent(componentName, component, url, options = {}) {
2514
- if (!componentName || typeof componentName !== "string") {
2515
- throw new Error("\u274C testUiComponent requires a valid componentName (string)");
2516
- }
2517
- if (!url && (!component || !(component instanceof HTMLElement))) {
2518
- throw new Error("\u274C testUiComponent requires either a valid component (HTMLElement) or a URL");
2519
- }
2520
- if (url && typeof url !== "string") {
2521
- throw new Error("\u274C testUiComponent url parameter must be a string");
2522
- }
2523
- let results;
2524
- if (component) {
2525
- try {
2526
- results = await jestAxe.axe(component);
2527
- } catch (error) {
2528
- throw new Error(
2529
- `\u274C Axe accessibility scan failed
2530
- Error: ${error instanceof Error ? error.message : String(error)}`
2531
- );
2532
- }
2533
- } else {
2534
- results = { violations: [] };
2535
- }
2536
- async function checkDevServer(url2) {
2537
- try {
2538
- const response = await fetch(url2, {
2539
- method: "HEAD",
2540
- signal: AbortSignal.timeout(1e3)
2541
- });
2542
- if (response.ok || response.status === 304) {
2543
- return url2;
2544
- }
2545
- } catch {
2546
- return null;
2547
- }
2548
- return null;
2549
- }
2550
- let strictness = normalizeStrictness(options.strictness);
2551
- let config = {};
2552
- let configBaseDir = typeof process !== "undefined" ? process.cwd() : "";
2553
- if (typeof process !== "undefined" && typeof process.cwd === "function") {
2554
- try {
2555
- const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_configLoader(), configLoader_exports));
2556
- const result2 = await loadConfig2(process.cwd());
2557
- config = result2.config;
2558
- if (result2.configPath) {
2559
- configBaseDir = path3__default.default.dirname(result2.configPath);
2560
- }
2561
- if (options.strictness === void 0) {
2562
- const componentStrictness = config.test?.components?.find((comp) => comp?.name === componentName)?.strictness;
2563
- strictness = normalizeStrictness(componentStrictness ?? config.test?.strictness);
2564
- }
2565
- } catch {
2566
- if (options.strictness === void 0) {
2567
- strictness = "balanced";
2568
- }
2569
- }
2570
- }
2571
- let contract;
2572
- try {
2573
- if (url) {
2574
- const devServerUrl = await checkDevServer(url);
2575
- if (devServerUrl) {
2576
- console.log(`\u{1F3AD} Running Playwright tests on ${devServerUrl}`);
2577
- const { runContractTestsPlaywright: runContractTestsPlaywright2 } = await Promise.resolve().then(() => (init_contractTestRunnerPlaywright(), contractTestRunnerPlaywright_exports));
2578
- contract = await runContractTestsPlaywright2(componentName, devServerUrl, strictness, config, configBaseDir);
2579
- } else {
2580
- throw new Error(
2581
- `\u274C Dev server not running at ${url}
2582
- Please start your dev server and try again.`
2583
- );
2584
- }
2585
- } else if (component) {
2586
- console.log(`\u{1F3AD} Running component contract tests in JSDOM mode`);
2587
- const contractPath = config.test?.components?.find((comp) => comp?.name === componentName)?.contractPath;
2588
- if (!contractPath) {
2589
- throw new Error(`\u274C No contract path found for component: ${componentName}`);
2590
- }
2591
- contract = await runContractTests(
2592
- path3__default.default.resolve(configBaseDir, contractPath),
2593
- componentName,
2594
- component,
2595
- strictness
2596
- );
2597
- } else {
2598
- throw new Error("\u274C Either component or URL must be provided");
2599
- }
2600
- } catch (error) {
2601
- if (error instanceof Error) {
2602
- throw error;
2603
- }
2604
- throw new Error(`\u274C Contract test execution failed: ${String(error)}`);
2605
- }
2606
- const result = {
2607
- violations: results.violations,
2608
- raw: results,
2609
- contract
2610
- };
2611
- if (contract.failures.length > 0 && url === "Playwright") {
2612
- throw new Error(
2613
- `
2614
- \u274C ${contract.failures.length} accessibility contract test${contract.failures.length > 1 ? "s" : ""} failed (Playwright mode)
2615
- \u2705 ${contract.passes.length} test${contract.passes.length > 1 ? "s" : ""} passed
49
+ `):h.message.includes("Target page, context or browser has been closed")?new Error(`
50
+ \u274C CRITICAL: Browser/page was closed unexpectedly!
51
+ This usually means:
52
+ - The test timeout was too short
53
+ - The browser crashed
54
+ - An external process killed the browser`):h}finally{$&&await $.close();}return {passes:N,failures:H,skipped:I,warnings:G}}var lt=L(()=>{be();rt();it();ot();at();Te();});var ut={};Y(ut,{BADGE_CONFIGS:()=>Ie,displayAllBadges:()=>Lt,displayBadgeInfo:()=>Pt,getBadgeMarkdown:()=>ie,promptAddBadge:()=>Bt});function ie(c){let e=Ie[c];return `[![${e.label}](${e.markdownUrl})](https://github.com/aria-ease/aria-ease)`}function Pt(c){let e=ie(c);console.log(B__default.default.cyan(`
55
+ \u{1F3C5} Show your accessibility commitment!`)),console.log(B__default.default.white(` Add this badge to your README.md:
56
+ `)),console.log(B__default.default.green(" "+e)),console.log(B__default.default.dim(`
57
+ This helps others discover accessibility tools and shows you care!
58
+ `));}async function Bt(c,e=process.cwd()){let t=xe__default.default.join(e,"README.md");if(!await Be__default.default.pathExists(t)){console.log(B__default.default.yellow(" \u2139\uFE0F No README.md found in current directory"));return}let i=await Be__default.default.readFile(t,"utf-8"),n=ie(c);if(i.includes(n)||i.includes(Ie[c].fileName)){console.log(B__default.default.gray(" \u2713 Badge already in README.md"));return}let o=Mt__default.default.createInterface({input:process.stdin,output:process.stdout}),a=await new Promise(p=>{o.question(B__default.default.cyan(" Add badge to README.md now? (y/n): "),A=>{o.close(),p(A.toLowerCase().trim());});});a==="y"||a==="yes"?(await It(t,i,n),console.log(B__default.default.green(" \u2713 Badge added to README.md!"))):console.log(B__default.default.gray(" Skipped. You can add it manually anytime."));}async function It(c,e,t){let r=e.split(`
59
+ `),i=0;for(let n=0;n<r.length;n++){let o=r[n].trim();if(o.startsWith("[![")||o.startsWith("[!")){i=n+1;continue}if(i>0&&!o.startsWith("[![")&&!o.startsWith("[!")&&o.length>0)break;if(i===0&&o.startsWith("#")){i=n+2;break}}i===0&&(i=1),r.splice(i,0,t),await Be__default.default.writeFile(c,r.join(`
60
+ `),"utf-8");}function Lt(){console.log(B__default.default.cyan(`
61
+ \u{1F4CD} Available badges:`)),console.log(B__default.default.white(`
62
+ For audits:`)),console.log(B__default.default.green(" "+ie("audit"))),console.log(B__default.default.white(`
63
+ For component testing:`)),console.log(B__default.default.green(" "+ie("component"))),console.log(B__default.default.white(`
64
+ For both (verified):`)),console.log(B__default.default.green(" "+ie("verified"))),console.log("");}var Ie,pt=L(()=>{Ie={audit:{type:"audit",fileName:"audited-by-aria-ease.svg",label:"Audited by aria-ease",markdownUrl:"https://cdn.jsdelivr.net/gh/aria-ease/aria-ease@main/badges/audited-by-aria-ease.svg"},component:{type:"component",fileName:"components-tested-aria-ease.svg",label:"Components tested: aria-ease",markdownUrl:"https://cdn.jsdelivr.net/gh/aria-ease/aria-ease@main/badges/components-tested-aria-ease.svg"},verified:{type:"verified",fileName:"verified-by-aria-ease.svg",label:"Verified by aria-ease",markdownUrl:"https://cdn.jsdelivr.net/gh/aria-ease/aria-ease@main/badges/verified-by-aria-ease.svg"}};});be();Te();async function Vt(c,e,t={}){if(!c||typeof c!="string")throw new Error("\u274C testUiComponent requires a valid componentName (string)");if(!e)throw new Error("\u274C testUiComponent requires a URL");if(e&&typeof e!="string")throw new Error("\u274C testUiComponent url parameter must be a string");let r={violations:[]};async function i(b){try{let x=await fetch(b,{method:"HEAD",signal:AbortSignal.timeout(1e3)});if(x.ok||x.status===304)return b}catch{return null}return null}let n=oe(t.strictness),o={},a=typeof process<"u"?process.cwd():"";if(typeof process<"u"&&typeof process.cwd=="function")try{let{loadConfig:b}=await Promise.resolve().then(()=>(Ke(),Je)),x=await b(process.cwd());if(o=x.config,x.configPath&&(a=xe__default.default.dirname(x.configPath)),t.strictness===void 0){let M=o.test?.components?.find(K=>K?.name===c)?.strictness;n=oe(M??o.test?.strictness);}}catch{t.strictness===void 0&&(n="balanced");}let p;try{if(e){let b=await i(e);if(b){console.log(`\u{1F3AD} Running Playwright tests on ${b}`);let{runContractTestsPlaywright:x}=await Promise.resolve().then(()=>(lt(),ct));p=await x(c,b,n,o,a);}else throw new Error(`\u274C Dev server not running at ${e}
65
+ Please start your dev server and try again.`)}else throw new Error("\u274C URL is required for component testing. Please provide a URL to run full accessibility tests with testUiComponent.")}catch(b){throw b instanceof Error?b:new Error(`\u274C Contract test execution failed: ${String(b)}`)}let A={violations:r.violations,raw:r,contract:p};if(p.failures.length>0&&e==="Playwright")throw new Error(`
66
+ \u274C ${p.failures.length} accessibility contract test${p.failures.length>1?"s":""} failed (Playwright mode)
67
+ \u2705 ${p.passes.length} test${p.passes.length>1?"s":""} passed
2616
68
 
2617
69
  \u{1F4CB} Review the detailed test report above for specific failures.
2618
- \u{1F4A1} Contract tests validate ARIA attributes and keyboard interactions per W3C APG guidelines.`
2619
- );
2620
- }
2621
- if (results.violations.length > 0) {
2622
- const violationCount = results.violations.length;
2623
- const violationDetails = results.violations.map(
2624
- (v) => `
2625
- - ${v.id}: ${v.description}
2626
- Impact: ${v.impact}
2627
- Affected elements: ${v.nodes.length}
2628
- Help: ${v.helpUrl}`
2629
- ).join("\n");
2630
- throw new Error(
2631
- `
2632
- \u274C ${violationCount} axe accessibility violation${violationCount > 1 ? "s" : ""} detected
2633
- ${violationDetails}
2634
-
2635
- \u{1F4CB} Full details available in result.violations`
2636
- );
2637
- }
2638
- return result;
2639
- }
2640
- exports.runTest = async () => {
2641
- return {
2642
- passes: [],
2643
- failures: [],
2644
- skipped: []
2645
- };
2646
- };
2647
- if (typeof window === "undefined") {
2648
- exports.runTest = async () => {
2649
- console.log(`\u{1F680} Running component accessibility tests...
2650
- `);
2651
- const { exec } = await import('child_process');
2652
- const chalk2 = (await import('chalk')).default;
2653
- return new Promise((resolve, reject) => {
2654
- exec(
2655
- `npx vitest --run --reporter verbose`,
2656
- async (error, stdout, stderr) => {
2657
- console.log(stdout);
2658
- if (stderr) console.error(stderr);
2659
- const testsPassed = !error || error.code === 0;
2660
- if (testsPassed) {
2661
- try {
2662
- const { displayBadgeInfo: displayBadgeInfo2, promptAddBadge: promptAddBadge2 } = await Promise.resolve().then(() => (init_badgeHelper(), badgeHelper_exports));
2663
- displayBadgeInfo2("component");
2664
- await promptAddBadge2("component", process.cwd());
2665
- console.log(chalk2.dim("\n" + "\u2500".repeat(60)));
2666
- console.log(chalk2.cyan("\u{1F499} Found aria-ease helpful?"));
2667
- console.log(chalk2.white(" \u2022 Star us on GitHub: ") + chalk2.blue.underline("https://github.com/aria-ease/aria-ease"));
2668
- console.log(chalk2.white(" \u2022 Share feedback: ") + chalk2.blue.underline("https://github.com/aria-ease/aria-ease/discussions"));
2669
- console.log(chalk2.dim("\u2500".repeat(60) + "\n"));
2670
- } catch (badgeError) {
2671
- console.error("Warning: Could not display badge prompt:", badgeError);
2672
- }
2673
- resolve({ passes: [], failures: [], skipped: [] });
2674
- process.exit(0);
2675
- } else {
2676
- const exitCode = error?.code || 1;
2677
- reject(new Error(`Tests failed with code ${exitCode}`));
2678
- process.exit(exitCode);
2679
- }
2680
- }
2681
- );
2682
- });
2683
- };
2684
- }
2685
- async function cleanupTests() {
2686
- await closeSharedBrowser();
2687
- }
2688
-
2689
- exports.cleanupTests = cleanupTests;
2690
- exports.testUiComponent = testUiComponent;
70
+ \u{1F4A1} Contract tests validate ARIA attributes and keyboard interactions per W3C APG guidelines.`);if(r.violations.length>0){let b=r.violations.length,x=r.violations.map(M=>`
71
+ - ${M.id}: ${M.description}
72
+ Impact: ${M.impact}
73
+ Affected elements: ${M.nodes.length}
74
+ Help: ${M.helpUrl}`).join(`
75
+ `);throw new Error(`
76
+ \u274C ${b} axe accessibility violation${b>1?"s":""} detected
77
+ ${x}
78
+
79
+ \u{1F4CB} Full details available in result.violations`)}return A}exports.runTest=async()=>({passes:[],failures:[],skipped:[]});typeof window>"u"&&(exports.runTest=async()=>{console.log(`\u{1F680} Running component accessibility tests...
80
+ `);let{exec:c}=await import('child_process'),e=(await import('chalk')).default;return new Promise((t,r)=>{c("npx vitest --run --reporter verbose",async(i,n,o)=>{if(console.log(n),o&&console.error(o),!i||i.code===0){try{let{displayBadgeInfo:p,promptAddBadge:A}=await Promise.resolve().then(()=>(pt(),ut));p("component"),await A("component",process.cwd()),console.log(e.dim(`
81
+ `+"\u2500".repeat(60))),console.log(e.cyan("\u{1F499} Found aria-ease helpful?")),console.log(e.white(" \u2022 Star us on GitHub: ")+e.blue.underline("https://github.com/aria-ease/aria-ease")),console.log(e.white(" \u2022 Share feedback: ")+e.blue.underline("https://github.com/aria-ease/aria-ease/discussions")),console.log(e.dim("\u2500".repeat(60)+`
82
+ `));}catch(p){console.error("Warning: Could not display badge prompt:",p);}t({passes:[],failures:[],skipped:[]}),process.exit(0);}else {let p=i?.code||1;r(new Error(`Tests failed with code ${p}`)),process.exit(p);}});})});async function Ut(){await He();}exports.cleanupTests=Ut;exports.testUiComponent=Vt;