aria-ease 6.14.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/AccordionComponentStrategy-2SWMNUR6.js +1 -0
  2. package/dist/ComboboxComponentStrategy-YSYLR2U5.js +5 -0
  3. package/dist/MenuComponentStrategy-C22BZEBH.js +5 -0
  4. package/dist/RelativeTargetResolver-T4P25J2M.js +1 -0
  5. package/dist/TabsComponentStrategy-ADEEFJXM.js +1 -0
  6. package/dist/audit-APAPHXRO.js +9 -0
  7. package/dist/badgeHelper-IB5RTMAG.js +11 -0
  8. package/dist/badgeHelper-JSROP5ML.js +1 -0
  9. package/dist/buildContracts-T4XQZBDU.js +13 -0
  10. package/dist/chunk-52I3INNG.js +11 -0
  11. package/dist/chunk-APUMBDOT.js +1 -0
  12. package/dist/chunk-BHNO4ZI3.js +1 -0
  13. package/dist/chunk-CNU4N4AY.js +1 -0
  14. package/dist/chunk-SM6ZKEDR.js +1 -0
  15. package/dist/chunk-ZNQ5BXVJ.js +1 -0
  16. package/dist/cli.cjs +132 -3560
  17. package/dist/cli.js +19 -161
  18. package/dist/configLoader-ZEJVXLX7.js +1 -0
  19. package/dist/configLoader-ZXTSCIP6.js +1 -0
  20. package/dist/contractTestRunnerPlaywright-FOCQTM4L.js +46 -0
  21. package/dist/contractTestRunnerPlaywright-QPU6HZXG.js +46 -0
  22. package/dist/formatters-H3CPDLG5.js +87 -0
  23. package/dist/index.cjs +64 -5103
  24. package/dist/index.d.cts +4 -6
  25. package/dist/index.d.ts +4 -6
  26. package/dist/index.js +17 -2703
  27. package/dist/src/accordion/index.cjs +1 -183
  28. package/dist/src/accordion/index.js +1 -181
  29. package/dist/src/block/index.cjs +1 -124
  30. package/dist/src/block/index.js +1 -122
  31. package/dist/src/checkbox/index.cjs +1 -109
  32. package/dist/src/checkbox/index.js +1 -107
  33. package/dist/src/combobox/index.cjs +1 -265
  34. package/dist/src/combobox/index.js +1 -263
  35. package/dist/src/menu/index.cjs +1 -339
  36. package/dist/src/menu/index.js +1 -337
  37. package/dist/src/radio/index.cjs +1 -117
  38. package/dist/src/radio/index.js +1 -115
  39. package/dist/src/tabs/index.cjs +1 -265
  40. package/dist/src/tabs/index.js +1 -263
  41. package/dist/src/toggle/index.cjs +1 -119
  42. package/dist/src/toggle/index.js +1 -117
  43. package/dist/src/utils/test/AccordionComponentStrategy-X2GSQ5KT.js +1 -0
  44. package/dist/src/utils/test/ComboboxComponentStrategy-SICWLI27.js +5 -0
  45. package/dist/src/utils/test/MenuComponentStrategy-R4VPAHDE.js +5 -0
  46. package/dist/src/utils/test/RelativeTargetResolver-UQQMZHI6.js +1 -0
  47. package/dist/src/utils/test/TabsComponentStrategy-L2PYNEW6.js +1 -0
  48. package/dist/src/utils/test/badgeHelper-ER5ZOHWF.js +11 -0
  49. package/dist/src/utils/test/chunk-APUMBDOT.js +1 -0
  50. package/dist/src/utils/test/chunk-BHNO4ZI3.js +1 -0
  51. package/dist/src/utils/test/configLoader-NCYRL2O6.js +1 -0
  52. package/dist/src/utils/test/contractTestRunnerPlaywright-YZCMF64Q.js +46 -0
  53. package/dist/src/utils/test/dsl/index.cjs +1 -838
  54. package/dist/src/utils/test/dsl/index.d.cts +2 -4
  55. package/dist/src/utils/test/dsl/index.d.ts +2 -4
  56. package/dist/src/utils/test/dsl/index.js +1 -836
  57. package/dist/src/utils/test/index.cjs +64 -2672
  58. package/dist/src/utils/test/index.d.cts +2 -2
  59. package/dist/src/utils/test/index.d.ts +2 -2
  60. package/dist/src/utils/test/index.js +16 -340
  61. package/dist/test-VXSCSKV5.js +19 -0
  62. package/package.json +7 -9
  63. package/dist/AccordionComponentStrategy-4ZEIQ2V6.js +0 -42
  64. package/dist/ComboboxComponentStrategy-DU342VMB.js +0 -64
  65. package/dist/MenuComponentStrategy-VYCC2XOM.js +0 -81
  66. package/dist/RelativeTargetResolver-DJAITO6D.js +0 -7
  67. package/dist/TabsComponentStrategy-3SQURPMX.js +0 -29
  68. package/dist/audit-JYEPKLHR.js +0 -63
  69. package/dist/badgeHelper-JOWO6RQG.js +0 -15
  70. package/dist/badgeHelper-RDOMCC6E.js +0 -108
  71. package/dist/buildContracts-VIV6GM56.js +0 -437
  72. package/dist/chunk-4DU5Z5BR.js +0 -340
  73. package/dist/chunk-GJGUY643.js +0 -182
  74. package/dist/chunk-GLT43UVH.js +0 -43
  75. package/dist/chunk-I2KLQ2HA.js +0 -22
  76. package/dist/chunk-JJEPLK7L.js +0 -107
  77. package/dist/chunk-PK5L2SAF.js +0 -17
  78. package/dist/configLoader-Q7N5XV4P.js +0 -183
  79. package/dist/configLoader-REHK3S3Q.js +0 -7
  80. package/dist/contractTestRunnerPlaywright-B2HLZKKK.js +0 -1394
  81. package/dist/contractTestRunnerPlaywright-RWK52C7S.js +0 -1394
  82. package/dist/formatters-32KQIIYS.js +0 -183
  83. package/dist/src/utils/test/AccordionComponentStrategy-WRHZOEN6.js +0 -38
  84. package/dist/src/utils/test/ComboboxComponentStrategy-XKQ72RFD.js +0 -60
  85. package/dist/src/utils/test/MenuComponentStrategy-6XWU5KLW.js +0 -77
  86. package/dist/src/utils/test/RelativeTargetResolver-G2XDN2VV.js +0 -1
  87. package/dist/src/utils/test/TabsComponentStrategy-BKG53SEV.js +0 -26
  88. package/dist/src/utils/test/badgeHelper-HZKGOPB4.js +0 -102
  89. package/dist/src/utils/test/chunk-4DU5Z5BR.js +0 -332
  90. package/dist/src/utils/test/chunk-GLT43UVH.js +0 -41
  91. package/dist/src/utils/test/configLoader-NA7IBCS3.js +0 -181
  92. package/dist/src/utils/test/contractTestRunnerPlaywright-5FIGA5G4.js +0 -1372
  93. package/dist/test-WDBS5JWO.js +0 -358
@@ -1,1372 +0,0 @@
1
- import { ContractReporter, normalizeStrictness, createTestPage, normalizeLevel, resolveEnforcement } from './chunk-4DU5Z5BR.js';
2
- import { RelativeTargetResolver } from './chunk-GLT43UVH.js';
3
- import { readFileSync } from 'fs';
4
- import path2 from 'path';
5
- import { pathToFileURL } from 'url';
6
- import { expect } from '@playwright/test';
7
-
8
- var StrategyRegistry = class {
9
- builtInStrategies = /* @__PURE__ */ new Map();
10
- constructor() {
11
- this.registerBuiltInStrategies();
12
- }
13
- /**
14
- * Register built-in strategies
15
- */
16
- registerBuiltInStrategies() {
17
- this.builtInStrategies.set(
18
- "menu",
19
- () => import('./MenuComponentStrategy-6XWU5KLW.js').then(
20
- (m) => m.MenuComponentStrategy
21
- )
22
- );
23
- this.builtInStrategies.set(
24
- "accordion",
25
- () => import('./AccordionComponentStrategy-WRHZOEN6.js').then(
26
- (m) => m.AccordionComponentStrategy
27
- )
28
- );
29
- this.builtInStrategies.set(
30
- "combobox",
31
- () => import('./ComboboxComponentStrategy-XKQ72RFD.js').then(
32
- (m) => m.ComboboxComponentStrategy
33
- )
34
- );
35
- this.builtInStrategies.set(
36
- "tabs",
37
- () => import('./TabsComponentStrategy-BKG53SEV.js').then(
38
- (m) => m.TabsComponentStrategy
39
- )
40
- );
41
- }
42
- /**
43
- * Load a strategy - either from custom path or built-in registry
44
- * @param componentName - Component name (e.g., "menu", "accordion")
45
- * @param customStrategyPath - Optional custom strategy file path
46
- * @returns Strategy constructor function or null if not found
47
- */
48
- async loadStrategy(componentName, customStrategyPath, configBaseDir) {
49
- try {
50
- if (customStrategyPath) {
51
- try {
52
- const resolvedCustomPath = path2.isAbsolute(customStrategyPath) ? customStrategyPath : path2.resolve(configBaseDir || process.cwd(), customStrategyPath);
53
- const customModule = await import(pathToFileURL(resolvedCustomPath).href);
54
- const strategy = customModule.default || customModule;
55
- if (!strategy) {
56
- throw new Error(`No default export found in ${customStrategyPath}`);
57
- }
58
- return strategy;
59
- } catch (error) {
60
- throw new Error(
61
- `Failed to load custom strategy from ${customStrategyPath}: ${error instanceof Error ? error.message : String(error)}`
62
- );
63
- }
64
- }
65
- const builtInLoader = this.builtInStrategies.get(componentName);
66
- if (!builtInLoader) {
67
- return null;
68
- }
69
- return builtInLoader();
70
- } catch (error) {
71
- throw new Error(
72
- `Strategy loading failed for ${componentName}: ${error instanceof Error ? error.message : String(error)}`
73
- );
74
- }
75
- }
76
- /**
77
- * Check if a strategy exists (either built-in or custom path provided)
78
- */
79
- has(componentName, customStrategyPath) {
80
- return !!customStrategyPath || this.builtInStrategies.has(componentName);
81
- }
82
- };
83
-
84
- // src/utils/test/src/ComponentDetector.ts
85
- var ComponentDetector = class {
86
- static strategyRegistry = new StrategyRegistry();
87
- static isComponentConfig(value) {
88
- return typeof value === "object" && value !== null;
89
- }
90
- /**
91
- * Detect and instantiate a component strategy
92
- * Supports:
93
- * - Built-in strategies (menu, accordion, combobox, tabs)
94
- * - Custom strategies via config (strategyPath)
95
- * - Custom contract paths via config (path)
96
- * @param componentName - Component name
97
- * @param componentConfig - Component config from ariaease.config.js
98
- * @param actionTimeoutMs - Action timeout in milliseconds
99
- * @param assertionTimeoutMs - Assertion timeout in milliseconds
100
- * @returns Instantiated ComponentStrategy or null
101
- */
102
- static async detect(componentName, componentConfig, actionTimeoutMs = 400, assertionTimeoutMs = 400, configBaseDir) {
103
- const typedComponentConfig = this.isComponentConfig(componentConfig) ? componentConfig : void 0;
104
- const contractPath = typedComponentConfig?.contractPath;
105
- if (!contractPath) {
106
- throw new Error(`Contract path not found for component: ${componentName}`);
107
- }
108
- const resolvedPath = (() => {
109
- if (path2.isAbsolute(contractPath)) return contractPath;
110
- if (configBaseDir) {
111
- const configResolved = path2.resolve(configBaseDir, contractPath);
112
- try {
113
- readFileSync(configResolved, "utf-8");
114
- return configResolved;
115
- } catch {
116
- }
117
- }
118
- const cwdResolved = path2.resolve(process.cwd(), contractPath);
119
- try {
120
- readFileSync(cwdResolved, "utf-8");
121
- return cwdResolved;
122
- } catch {
123
- return new URL(contractPath, import.meta.url).pathname;
124
- }
125
- })();
126
- const contractData = readFileSync(resolvedPath, "utf-8");
127
- const componentContract = JSON.parse(contractData);
128
- const selectors = componentContract.selectors;
129
- const strategyClass = await this.strategyRegistry.loadStrategy(
130
- componentName,
131
- typedComponentConfig?.strategyPath,
132
- configBaseDir
133
- );
134
- if (!strategyClass) {
135
- return null;
136
- }
137
- const mainSelector = selectors.main;
138
- if (componentName === "tabs") {
139
- return new strategyClass(mainSelector, selectors);
140
- }
141
- return new strategyClass(
142
- mainSelector,
143
- selectors,
144
- actionTimeoutMs,
145
- assertionTimeoutMs
146
- );
147
- }
148
- };
149
-
150
- // src/utils/test/src/ActionExecutor.ts
151
- var ActionExecutor = class {
152
- constructor(page, selectors, timeoutMs = 400) {
153
- this.page = page;
154
- this.selectors = selectors;
155
- this.timeoutMs = timeoutMs;
156
- }
157
- /**
158
- * Check if error is due to browser/page being closed
159
- */
160
- isBrowserClosedError(error) {
161
- return error instanceof Error && error.message.includes("Target page, context or browser has been closed");
162
- }
163
- /**
164
- * Execute focus action
165
- */
166
- /**
167
- * Execute focus action (supports absolute, relative, and virtual focus)
168
- * @param target - selector key (e.g. "input", "button", "relative", or "virtual")
169
- * @param relativeTarget - for relative focus (e.g. "first", "last")
170
- * @param virtualId - for virtual focus (aria-activedescendant value)
171
- */
172
- async focus(target, relativeTarget, virtualId) {
173
- try {
174
- if (target === "virtual" && virtualId) {
175
- const mainSelector = this.selectors.main;
176
- if (!mainSelector) {
177
- return { success: false, error: `Main selector not defined for virtual focus.` };
178
- }
179
- const main = this.page.locator(mainSelector).first();
180
- const exists = await main.count();
181
- if (!exists) {
182
- return { success: false, error: `Main element not found for virtual focus.` };
183
- }
184
- await main.evaluate((el, id) => {
185
- el.setAttribute("aria-activedescendant", id);
186
- }, virtualId);
187
- return { success: true };
188
- }
189
- if (target === "relative" && relativeTarget) {
190
- const relativeSelector = this.selectors.relative;
191
- if (!relativeSelector) {
192
- return { success: false, error: `Relative selector not defined for focus action.` };
193
- }
194
- const element = await RelativeTargetResolver.resolve(this.page, relativeSelector, relativeTarget);
195
- if (!element) {
196
- return { success: false, error: `Could not resolve relative target ${relativeTarget} for focus.` };
197
- }
198
- await element.focus({ timeout: this.timeoutMs });
199
- return { success: true };
200
- }
201
- const selector = this.selectors[target];
202
- if (!selector) {
203
- return { success: false, error: `Selector for focus target ${target} not found.` };
204
- }
205
- await this.page.locator(selector).first().focus({ timeout: this.timeoutMs });
206
- return { success: true };
207
- } catch (error) {
208
- if (this.isBrowserClosedError(error)) {
209
- return {
210
- success: false,
211
- error: `CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`,
212
- shouldBreak: true
213
- };
214
- }
215
- return {
216
- success: false,
217
- error: `Failed to focus ${target}: ${error instanceof Error ? error.message : String(error)}`
218
- };
219
- }
220
- }
221
- /**
222
- * Execute type/fill action
223
- */
224
- async type(target, value) {
225
- try {
226
- const selector = this.selectors[target];
227
- if (!selector) {
228
- return { success: false, error: `Selector for type target ${target} not found.` };
229
- }
230
- await this.page.locator(selector).first().fill(value, { timeout: this.timeoutMs });
231
- return { success: true };
232
- } catch (error) {
233
- if (this.isBrowserClosedError(error)) {
234
- return {
235
- success: false,
236
- error: `CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`,
237
- shouldBreak: true
238
- };
239
- }
240
- return {
241
- success: false,
242
- error: `Failed to type into ${target}: ${error instanceof Error ? error.message : String(error)}`
243
- };
244
- }
245
- }
246
- /**
247
- * Execute click action
248
- */
249
- async click(target, relativeTarget) {
250
- try {
251
- if (target === "document") {
252
- await this.page.mouse.click(10, 10);
253
- return { success: true };
254
- }
255
- if (target === "relative" && relativeTarget) {
256
- const relativeSelector = this.selectors.relative;
257
- if (!relativeSelector) {
258
- return { success: false, error: `Relative selector not defined for click action.` };
259
- }
260
- const element = await RelativeTargetResolver.resolve(this.page, relativeSelector, relativeTarget);
261
- if (!element) {
262
- return { success: false, error: `Could not resolve relative target ${relativeTarget} for click.` };
263
- }
264
- await element.click({ timeout: this.timeoutMs });
265
- return { success: true };
266
- }
267
- const selector = this.selectors[target];
268
- if (!selector) {
269
- return { success: false, error: `Selector for action target ${target} not found.` };
270
- }
271
- await this.page.locator(selector).first().click({ timeout: this.timeoutMs });
272
- return { success: true };
273
- } catch (error) {
274
- if (this.isBrowserClosedError(error)) {
275
- return {
276
- success: false,
277
- error: `CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`,
278
- shouldBreak: true
279
- };
280
- }
281
- return {
282
- success: false,
283
- error: `Failed to click ${target}: ${error instanceof Error ? error.message : String(error)}`
284
- };
285
- }
286
- }
287
- /**
288
- * Execute keypress action
289
- */
290
- async keypress(target, key) {
291
- try {
292
- const keyMap = {
293
- "Space": "Space",
294
- "Enter": "Enter",
295
- "Escape": "Escape",
296
- "Arrow Up": "ArrowUp",
297
- "Arrow Down": "ArrowDown",
298
- "Arrow Left": "ArrowLeft",
299
- "Arrow Right": "ArrowRight",
300
- "Home": "Home",
301
- "End": "End",
302
- "Tab": "Tab"
303
- };
304
- let keyValue = keyMap[key] || key;
305
- if (keyValue === "Space") {
306
- keyValue = " ";
307
- } else if (keyValue.includes(" ")) {
308
- keyValue = keyValue.replace(/ /g, "");
309
- }
310
- if (target === "focusable" && ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Escape", "Home", "End", "Tab", "Shift+Tab"].includes(keyValue)) {
311
- await this.page.keyboard.press(keyValue);
312
- return { success: true };
313
- }
314
- const selector = this.selectors[target];
315
- if (!selector) {
316
- return { success: false, error: `Selector for keypress target ${target} not found.` };
317
- }
318
- const locator = this.page.locator(selector).first();
319
- const elementCount = await locator.count();
320
- if (elementCount === 0) {
321
- return {
322
- success: false,
323
- error: `${target} element not found.`,
324
- shouldBreak: true
325
- // Signal to skip this test
326
- };
327
- }
328
- await locator.press(keyValue, { timeout: this.timeoutMs });
329
- return { success: true };
330
- } catch (error) {
331
- if (this.isBrowserClosedError(error)) {
332
- return {
333
- success: false,
334
- error: `CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`,
335
- shouldBreak: true
336
- };
337
- }
338
- return {
339
- success: false,
340
- error: `Failed to press ${key} on ${target}: ${error instanceof Error ? error.message : String(error)}`
341
- };
342
- }
343
- }
344
- /**
345
- * Execute hover action
346
- */
347
- async hover(target, relativeTarget) {
348
- try {
349
- if (target === "relative" && relativeTarget) {
350
- const relativeSelector = this.selectors.relative;
351
- if (!relativeSelector) {
352
- return { success: false, error: `Relative selector not defined for hover action.` };
353
- }
354
- const element = await RelativeTargetResolver.resolve(this.page, relativeSelector, relativeTarget);
355
- if (!element) {
356
- return { success: false, error: `Could not resolve relative target ${relativeTarget} for hover.` };
357
- }
358
- await element.hover({ timeout: this.timeoutMs });
359
- return { success: true };
360
- }
361
- const selector = this.selectors[target];
362
- if (!selector) {
363
- return { success: false, error: `Selector for hover target ${target} not found.` };
364
- }
365
- await this.page.locator(selector).first().hover({ timeout: this.timeoutMs });
366
- return { success: true };
367
- } catch (error) {
368
- if (this.isBrowserClosedError(error)) {
369
- return {
370
- success: false,
371
- error: `CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`,
372
- shouldBreak: true
373
- };
374
- }
375
- return {
376
- success: false,
377
- error: `Failed to hover ${target}: ${error instanceof Error ? error.message : String(error)}`
378
- };
379
- }
380
- }
381
- };
382
- var AssertionRunner = class {
383
- constructor(page, selectors, timeoutMs = 400) {
384
- this.page = page;
385
- this.selectors = selectors;
386
- this.timeoutMs = timeoutMs;
387
- }
388
- /**
389
- * Resolve the target element for an assertion
390
- */
391
- async resolveTarget(targetName, relativeTarget, selectorKey) {
392
- try {
393
- if (targetName === "relative") {
394
- const relativeSelector = selectorKey ? this.selectors[selectorKey] : this.selectors.relative;
395
- if (!relativeSelector) {
396
- return { target: null, error: "Relative selector is not defined in the contract." };
397
- }
398
- if (!relativeTarget) {
399
- return { target: null, error: "Relative target or expected value is not defined." };
400
- }
401
- const target = await RelativeTargetResolver.resolve(this.page, relativeSelector, relativeTarget);
402
- if (!target) {
403
- return { target: null, error: `Target ${targetName} not found.` };
404
- }
405
- return { target };
406
- }
407
- const selector = this.selectors[targetName];
408
- if (!selector) {
409
- return { target: null, error: `Selector for assertion target ${targetName} not found.` };
410
- }
411
- return { target: this.page.locator(selector).first() };
412
- } catch (error) {
413
- return {
414
- target: null,
415
- error: `Failed to resolve target ${targetName}: ${error instanceof Error ? error.message : String(error)}`
416
- };
417
- }
418
- }
419
- /**
420
- * Validate visibility assertion
421
- */
422
- async validateVisibility(target, targetName, expectedVisible, failureMessage, testDescription) {
423
- try {
424
- if (expectedVisible) {
425
- await expect(target).toBeVisible({ timeout: this.timeoutMs });
426
- return {
427
- success: true,
428
- passMessage: `${targetName} is visible as expected. Test: "${testDescription}".`
429
- };
430
- } else {
431
- await expect(target).toBeHidden({ timeout: this.timeoutMs });
432
- return {
433
- success: true,
434
- passMessage: `${targetName} is not visible as expected. Test: "${testDescription}".`
435
- };
436
- }
437
- } catch {
438
- const selector = this.selectors[targetName] || "";
439
- const debugState = await this.page.evaluate((sel) => {
440
- const el = sel ? document.querySelector(sel) : null;
441
- if (!el) return "element not found";
442
- const styles = window.getComputedStyle(el);
443
- return `display:${styles.display}, visibility:${styles.visibility}, opacity:${styles.opacity}`;
444
- }, selector);
445
- if (expectedVisible) {
446
- return {
447
- success: false,
448
- failMessage: `${failureMessage} (actual: ${debugState})`
449
- };
450
- } else {
451
- return {
452
- success: false,
453
- failMessage: `${failureMessage} ${targetName} is still visible (actual: ${debugState}).`
454
- };
455
- }
456
- }
457
- }
458
- /**
459
- * Validate attribute assertion
460
- */
461
- async validateAttribute(target, targetName, attribute, expectedValue, failureMessage, testDescription) {
462
- if (expectedValue === "!empty") {
463
- const attributeValue2 = await target.getAttribute(attribute);
464
- if (attributeValue2 && attributeValue2.trim() !== "") {
465
- return {
466
- success: true,
467
- passMessage: `${targetName} has non-empty "${attribute}". Test: "${testDescription}".`
468
- };
469
- } else {
470
- return {
471
- success: false,
472
- failMessage: `${failureMessage} ${targetName} "${attribute}" should not be empty, found "${attributeValue2}".`
473
- };
474
- }
475
- }
476
- if (typeof expectedValue !== "string") {
477
- console.error("[AssertionRunner] expectedValue is not a string:", expectedValue);
478
- throw new Error(`AssertionRunner: expectedValue for attribute assertion must be a string, but got: ${JSON.stringify(expectedValue)}`);
479
- }
480
- const expectedValues = expectedValue.split(" | ").map((v) => v.trim());
481
- const attributeValue = await target.getAttribute(attribute);
482
- if (attributeValue !== null && expectedValues.includes(attributeValue)) {
483
- return {
484
- success: true,
485
- passMessage: `${targetName} has expected "${attribute}". Test: "${testDescription}".`
486
- };
487
- } else {
488
- return {
489
- success: false,
490
- failMessage: `${failureMessage} ${targetName} "${attribute}" should be "${expectedValue}", found "${attributeValue}".`
491
- };
492
- }
493
- }
494
- /**
495
- * Validate input value assertion
496
- */
497
- async validateValue(target, targetName, expectedValue, failureMessage, testDescription) {
498
- const inputValue = await target.inputValue().catch(() => "");
499
- if (expectedValue === "!empty") {
500
- if (inputValue && inputValue.trim() !== "") {
501
- return {
502
- success: true,
503
- passMessage: `${targetName} has non-empty value. Test: "${testDescription}".`
504
- };
505
- } else {
506
- return {
507
- success: false,
508
- failMessage: `${failureMessage} ${targetName} value should not be empty, found "${inputValue}".`
509
- };
510
- }
511
- }
512
- if (expectedValue === "") {
513
- if (inputValue === "") {
514
- return {
515
- success: true,
516
- passMessage: `${targetName} has empty value. Test: "${testDescription}".`
517
- };
518
- } else {
519
- return {
520
- success: false,
521
- failMessage: `${failureMessage} ${targetName} value should be empty, found "${inputValue}".`
522
- };
523
- }
524
- }
525
- if (inputValue === expectedValue) {
526
- return {
527
- success: true,
528
- passMessage: `${targetName} has expected value. Test: "${testDescription}".`
529
- };
530
- } else {
531
- return {
532
- success: false,
533
- failMessage: `${failureMessage} ${targetName} value should be "${expectedValue}", found "${inputValue}".`
534
- };
535
- }
536
- }
537
- /**
538
- * Validate focus assertion
539
- */
540
- async validateFocus(target, targetName, expectedFocus, failureMessage, testDescription) {
541
- try {
542
- if (expectedFocus) {
543
- await expect(target).toBeFocused({ timeout: this.timeoutMs });
544
- return {
545
- success: true,
546
- passMessage: `${targetName} has focus as expected. Test: "${testDescription}".`
547
- };
548
- } else {
549
- await expect(target).not.toBeFocused({ timeout: this.timeoutMs });
550
- return {
551
- success: true,
552
- passMessage: `${targetName} does not have focus as expected. Test: "${testDescription}".`
553
- };
554
- }
555
- } catch {
556
- const actualFocus = await this.page.evaluate(() => {
557
- const focused = document.activeElement;
558
- return focused ? `${focused.tagName}#${focused.id || "no-id"}.${focused.className || "no-class"}` : "no element focused";
559
- });
560
- return {
561
- success: false,
562
- failMessage: `${failureMessage} (actual focus: ${actualFocus})`
563
- };
564
- }
565
- }
566
- /**
567
- * Validate role assertion
568
- */
569
- async validateRole(target, targetName, expectedRole, failureMessage, testDescription) {
570
- const roleValue = await target.getAttribute("role");
571
- if (roleValue === expectedRole) {
572
- return {
573
- success: true,
574
- passMessage: `${targetName} has role "${expectedRole}". Test: "${testDescription}".`
575
- };
576
- } else {
577
- return {
578
- success: false,
579
- failMessage: `${failureMessage} Expected role "${expectedRole}", found "${roleValue}".`
580
- };
581
- }
582
- }
583
- /**
584
- * Main validation method - routes to specific validators
585
- */
586
- async validate(assertion, testDescription) {
587
- if (this.page.isClosed()) {
588
- return {
589
- success: false,
590
- failMessage: `CRITICAL: Browser/page closed before completing all tests. Increase test timeout or reduce test complexity.`
591
- };
592
- }
593
- const { target, error } = await this.resolveTarget(
594
- assertion.target,
595
- assertion.relativeTarget || assertion.expectedValue,
596
- assertion.selectorKey
597
- );
598
- if (error || !target) {
599
- return { success: false, failMessage: error || `Target ${assertion.target} not found.`, target: null };
600
- }
601
- if (assertion.target === "input" && assertion.attribute === "aria-activedescendant" && assertion.expectedValue === "!empty" && assertion.relativeTarget && assertion.selectorKey) {
602
- const optionLocator = await RelativeTargetResolver.resolve(this.page, this.selectors[assertion.selectorKey], assertion.relativeTarget);
603
- const optionId = optionLocator ? await optionLocator.getAttribute("id") : null;
604
- const inputId = await target.getAttribute("aria-activedescendant");
605
- if (optionId && inputId === optionId) {
606
- return {
607
- success: true,
608
- passMessage: `input[aria-activedescendant] matches id of ${assertion.relativeTarget}(${assertion.selectorKey}). Test: "${testDescription}".`
609
- };
610
- } else {
611
- return {
612
- success: false,
613
- failMessage: `input[aria-activedescendant] should match id of ${assertion.relativeTarget}(${assertion.selectorKey}), found "${inputId}".`
614
- };
615
- }
616
- }
617
- switch (assertion.assertion) {
618
- case "toBeVisible":
619
- return this.validateVisibility(target, assertion.target, true, assertion.failureMessage || "", testDescription);
620
- case "notToBeVisible":
621
- return this.validateVisibility(target, assertion.target, false, assertion.failureMessage || "", testDescription);
622
- case "toHaveAttribute":
623
- if (assertion.attribute && assertion.expectedValue !== void 0) {
624
- return this.validateAttribute(
625
- target,
626
- assertion.target,
627
- assertion.attribute,
628
- assertion.expectedValue,
629
- assertion.failureMessage || "",
630
- testDescription
631
- );
632
- }
633
- return { success: false, failMessage: "Missing attribute or expectedValue for toHaveAttribute assertion" };
634
- case "toHaveValue":
635
- if (assertion.expectedValue !== void 0) {
636
- return this.validateValue(target, assertion.target, assertion.expectedValue, assertion.failureMessage || "", testDescription);
637
- }
638
- return { success: false, failMessage: "Missing expectedValue for toHaveValue assertion" };
639
- case "toHaveFocus":
640
- return this.validateFocus(target, assertion.target, true, assertion.failureMessage || "", testDescription);
641
- case "notToHaveFocus":
642
- return this.validateFocus(target, assertion.target, false, assertion.failureMessage || "", testDescription);
643
- case "toHaveRole":
644
- if (assertion.expectedValue !== void 0) {
645
- return this.validateRole(target, assertion.target, assertion.expectedValue, assertion.failureMessage || "", testDescription);
646
- }
647
- return { success: false, failMessage: "Missing expectedValue for toHaveRole assertion" };
648
- default:
649
- return { success: false, failMessage: `Unknown assertion type: ${assertion.assertion}` };
650
- }
651
- }
652
- };
653
-
654
- // src/utils/test/src/contractTestRunnerPlaywright.ts
655
- async function runContractTestsPlaywright(componentName, url, strictness, config, configBaseDir) {
656
- const componentConfig = config?.test?.components?.find((c) => c.name === componentName);
657
- const isCustomContract = !!componentConfig?.contractPath;
658
- const reporter = new ContractReporter(true, isCustomContract);
659
- const defaultTimeouts = { actionTimeoutMs: 400, assertionTimeoutMs: 400, navigationTimeoutMs: 3e4, componentReadyTimeoutMs: 5e3 };
660
- const globalDisableTimeouts = config?.test?.disableTimeouts === true;
661
- const componentDisableTimeouts = componentConfig?.disableTimeouts === true;
662
- const disableTimeouts = componentDisableTimeouts || globalDisableTimeouts;
663
- const resolveTimeout = (componentValue, globalValue, fallback) => {
664
- if (disableTimeouts) return 0;
665
- const value = componentValue ?? globalValue;
666
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
667
- return fallback;
668
- }
669
- return value;
670
- };
671
- const actionTimeoutMs = resolveTimeout(componentConfig?.actionTimeoutMs, config?.test?.actionTimeoutMs, defaultTimeouts.actionTimeoutMs);
672
- const assertionTimeoutMs = resolveTimeout(
673
- componentConfig?.assertionTimeoutMs,
674
- config?.test?.assertionTimeoutMs,
675
- defaultTimeouts.assertionTimeoutMs
676
- );
677
- const navigationTimeoutMs = resolveTimeout(
678
- componentConfig?.navigationTimeoutMs,
679
- config?.test?.navigationTimeoutMs,
680
- defaultTimeouts.navigationTimeoutMs
681
- );
682
- const componentReadyTimeoutMs = resolveTimeout(
683
- componentConfig?.componentReadyTimeoutMs,
684
- config?.test?.componentReadyTimeoutMs,
685
- defaultTimeouts.componentReadyTimeoutMs
686
- );
687
- const strictnessMode = normalizeStrictness(strictness);
688
- const contractPath = componentConfig?.contractPath;
689
- if (!contractPath) {
690
- throw new Error(`Contract path not found for component: ${componentName}`);
691
- }
692
- const resolvedPath = (() => {
693
- if (path2.isAbsolute(contractPath)) return contractPath;
694
- if (configBaseDir) {
695
- const configResolved = path2.resolve(configBaseDir, contractPath);
696
- try {
697
- readFileSync(configResolved, "utf-8");
698
- return configResolved;
699
- } catch {
700
- }
701
- }
702
- const cwdResolved = path2.resolve(process.cwd(), contractPath);
703
- try {
704
- readFileSync(cwdResolved, "utf-8");
705
- return cwdResolved;
706
- } catch {
707
- return new URL(contractPath, import.meta.url).pathname;
708
- }
709
- })();
710
- const contractData = readFileSync(resolvedPath, "utf-8");
711
- const componentContract = JSON.parse(contractData);
712
- const totalTests = (componentContract.relationships?.length || 0) + (componentContract.static[0]?.assertions.length || 0) + componentContract.dynamic.length;
713
- const apgUrl = componentContract.meta?.source?.apg;
714
- const failures = [];
715
- const warnings = [];
716
- const passes = [];
717
- const skipped = [];
718
- let page = null;
719
- const classifyFailure = (message, levelRaw) => {
720
- const level = normalizeLevel(levelRaw);
721
- const enforcement = resolveEnforcement(level, strictnessMode);
722
- if (enforcement === "error") {
723
- failures.push(message);
724
- return { status: "fail", level, detail: message };
725
- }
726
- if (enforcement === "warning") {
727
- warnings.push(message);
728
- return { status: "warn", level, detail: message };
729
- }
730
- const ignoredMessage = `${message} (ignored by strictness=${strictnessMode}, level=${level})`;
731
- skipped.push(ignoredMessage);
732
- return { status: "skip", level, detail: ignoredMessage };
733
- };
734
- try {
735
- page = await createTestPage();
736
- if (url) {
737
- try {
738
- await page.goto(url, {
739
- waitUntil: "domcontentloaded",
740
- timeout: navigationTimeoutMs
741
- });
742
- } catch (error) {
743
- throw new Error(
744
- `Failed to navigate to ${url}. Ensure dev server is running and accessible. Original error: ${error instanceof Error ? error.message : String(error)}`
745
- );
746
- }
747
- await page.addStyleTag({ content: `* { transition: none !important; animation: none !important; }` });
748
- }
749
- const strategy = await ComponentDetector.detect(componentName, componentConfig, actionTimeoutMs, assertionTimeoutMs, configBaseDir);
750
- if (!strategy) {
751
- throw new Error(`Unsupported component: ${componentName}`);
752
- }
753
- const mainSelector = strategy.getMainSelector();
754
- if (!mainSelector) {
755
- throw new Error(`CRITICAL: No selector found in contract for ${componentName}`);
756
- }
757
- try {
758
- await page.locator(mainSelector).first().waitFor({ state: "attached", timeout: componentReadyTimeoutMs });
759
- } catch (error) {
760
- throw new Error(
761
- `
762
- \u274C CRITICAL: Component not found on page!
763
- This usually means:
764
- - The component didn't render
765
- - The URL is incorrect
766
- - The component selector '${mainSelector}' in the contract is wrong
767
- - Original error: ${error}`
768
- );
769
- }
770
- reporter.start(componentName, totalTests, apgUrl);
771
- if (componentName === "menu" && componentContract.selectors.main) {
772
- await page.locator(componentContract.selectors.main).first().waitFor({ state: "visible", timeout: componentReadyTimeoutMs }).catch(() => {
773
- });
774
- }
775
- const hasSubmenuCapability = componentName === "menu" && !!componentContract.selectors.submenuTrigger ? await page.locator(componentContract.selectors.submenuTrigger).count() > 0 : false;
776
- 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 || ""));
777
- let staticPassed = 0;
778
- let staticFailed = 0;
779
- let staticWarnings = 0;
780
- for (const rel of componentContract.relationships || []) {
781
- if (strategy && typeof strategy.resetState === "function") {
782
- try {
783
- await strategy.resetState(page);
784
- } catch (err) {
785
- warnings.push(`Warning: resetState failed before relationship test: ${err instanceof Error ? err.message : String(err)}`);
786
- }
787
- }
788
- const relationshipLevel = normalizeLevel(rel.level);
789
- if (Array.isArray(rel.setup) && rel.setup.length > 0) {
790
- let isAllowedType2 = function(t) {
791
- return allowedTypes.includes(t);
792
- };
793
- var isAllowedType = isAllowedType2;
794
- const actionExecutor = new ActionExecutor(page, componentContract.selectors, actionTimeoutMs);
795
- const relDescription = rel.type === "aria-reference" ? `${rel.from}.${rel.attribute} references ${rel.to}` : `${rel.parent} contains ${rel.child}`;
796
- const allowedTypes = ["focus", "type", "click", "keypress", "hover"];
797
- const toSetupAction = (a) => ({
798
- ...a,
799
- type: isAllowedType2(a.type) ? a.type : "click"
800
- });
801
- const setupActions = rel.setup.map(toSetupAction);
802
- const setupResult = await runSetupActions(setupActions, actionExecutor, strategy, page, relDescription, ["submenu", "submenuTrigger", "submenuItems"]);
803
- if (setupResult.skip) {
804
- skipped.push(setupResult.message || "Setup action skipped");
805
- reporter.reportStaticTest(relDescription, "skip", setupResult.message, relationshipLevel);
806
- continue;
807
- }
808
- if (!setupResult.success) {
809
- const failure = `Relationship setup failed: ${setupResult.error}`;
810
- const outcome = classifyFailure(failure, rel.level);
811
- if (outcome.status === "fail") staticFailed += 1;
812
- if (outcome.status === "warn") staticWarnings += 1;
813
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
814
- continue;
815
- }
816
- }
817
- if (componentName === "menu" && !hasSubmenuCapability) {
818
- const involvesSubmenu = isSubmenuRelation(rel);
819
- if (involvesSubmenu) {
820
- const relDescription = rel.type === "aria-reference" ? `${rel.from}.${rel.attribute} references ${rel.to}` : `${rel.parent} contains ${rel.child}`;
821
- const skipMessage = `Skipping submenu relationship assertion: no submenu capability detected in rendered component.`;
822
- skipped.push(skipMessage);
823
- reporter.reportStaticTest(relDescription, "skip", skipMessage, relationshipLevel);
824
- continue;
825
- }
826
- }
827
- if (rel.type === "aria-reference") {
828
- const relDescription = `${rel.from}.${rel.attribute} references ${rel.to}`;
829
- const fromSelector = componentContract.selectors[rel.from];
830
- const toSelector = componentContract.selectors[rel.to];
831
- if (!fromSelector || !toSelector) {
832
- const outcome = classifyFailure(
833
- `Relationship selector missing: from="${rel.from}" or to="${rel.to}" not found in selectors.`,
834
- rel.level
835
- );
836
- if (outcome.status === "fail") staticFailed += 1;
837
- if (outcome.status === "warn") staticWarnings += 1;
838
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
839
- continue;
840
- }
841
- const fromTarget = page.locator(fromSelector).first();
842
- const toTarget = page.locator(toSelector).first();
843
- const fromExists = await fromTarget.count() > 0;
844
- const toExists = await toTarget.count() > 0;
845
- if (!fromExists || !toExists) {
846
- if (componentName === "menu" && isSubmenuRelation(rel)) {
847
- const skipMessage = "Skipping submenu relationship assertion in static phase: submenu elements are not present until submenu is opened.";
848
- skipped.push(skipMessage);
849
- reporter.reportStaticTest(relDescription, "skip", skipMessage, relationshipLevel);
850
- continue;
851
- }
852
- const outcome = classifyFailure(
853
- `Relationship target not found: ${!fromExists ? rel.from : rel.to}.`,
854
- rel.level
855
- );
856
- if (outcome.status === "fail") staticFailed += 1;
857
- if (outcome.status === "warn") staticWarnings += 1;
858
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
859
- continue;
860
- }
861
- const attrValue = await fromTarget.getAttribute(rel.attribute);
862
- const toId = await toTarget.getAttribute("id");
863
- if (!toId) {
864
- const outcome = classifyFailure(
865
- `Relationship target "${rel.to}" must have an id for ${rel.attribute} validation.`,
866
- rel.level
867
- );
868
- if (outcome.status === "fail") staticFailed += 1;
869
- if (outcome.status === "warn") staticWarnings += 1;
870
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
871
- continue;
872
- }
873
- const references = (attrValue || "").split(/\s+/).filter(Boolean);
874
- const matches = references.includes(toId);
875
- if (!matches) {
876
- const outcome = classifyFailure(
877
- `Expected ${rel.from} ${rel.attribute} to reference id "${toId}", found "${attrValue || ""}".`,
878
- rel.level
879
- );
880
- if (outcome.status === "fail") staticFailed += 1;
881
- if (outcome.status === "warn") staticWarnings += 1;
882
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
883
- continue;
884
- }
885
- passes.push(`Relationship valid: ${rel.from}.${rel.attribute} -> ${rel.to} (id=${toId}).`);
886
- staticPassed += 1;
887
- reporter.reportStaticTest(relDescription, "pass", void 0, relationshipLevel);
888
- continue;
889
- }
890
- if (rel.type === "contains") {
891
- const relDescription = `${rel.parent} contains ${rel.child}`;
892
- const parentSelector = componentContract.selectors[rel.parent];
893
- const childSelector = componentContract.selectors[rel.child];
894
- if (!parentSelector || !childSelector) {
895
- const outcome = classifyFailure(
896
- `Relationship selector missing: parent="${rel.parent}" or child="${rel.child}" not found in selectors.`,
897
- rel.level
898
- );
899
- if (outcome.status === "fail") staticFailed += 1;
900
- if (outcome.status === "warn") staticWarnings += 1;
901
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
902
- continue;
903
- }
904
- const parent = page.locator(parentSelector).first();
905
- const parentExists = await parent.count() > 0;
906
- if (!parentExists) {
907
- if (componentName === "menu" && isSubmenuRelation(rel)) {
908
- const skipMessage = "Skipping submenu relationship assertion in static phase: submenu container is not present until submenu is opened.";
909
- skipped.push(skipMessage);
910
- reporter.reportStaticTest(relDescription, "skip", skipMessage, relationshipLevel);
911
- continue;
912
- }
913
- const outcome = classifyFailure(`Relationship parent target not found: ${rel.parent}.`, rel.level);
914
- if (outcome.status === "fail") staticFailed += 1;
915
- if (outcome.status === "warn") staticWarnings += 1;
916
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
917
- continue;
918
- }
919
- const descendants = parent.locator(childSelector);
920
- const descendantCount = await descendants.count();
921
- if (descendantCount < 1) {
922
- if (componentName === "menu" && isSubmenuRelation(rel)) {
923
- const skipMessage = "Skipping submenu relationship assertion in static phase: submenu descendants are not present until submenu is opened.";
924
- skipped.push(skipMessage);
925
- reporter.reportStaticTest(relDescription, "skip", skipMessage, relationshipLevel);
926
- continue;
927
- }
928
- const outcome = classifyFailure(
929
- `Expected ${rel.parent} to contain descendant matching selector for ${rel.child}.`,
930
- rel.level
931
- );
932
- if (outcome.status === "fail") staticFailed += 1;
933
- if (outcome.status === "warn") staticWarnings += 1;
934
- reporter.reportStaticTest(relDescription, outcome.status, outcome.detail, outcome.level);
935
- continue;
936
- }
937
- passes.push(`Relationship valid: ${rel.parent} contains ${rel.child}.`);
938
- staticPassed += 1;
939
- reporter.reportStaticTest(relDescription, "pass", void 0, relationshipLevel);
940
- }
941
- }
942
- async function resolveExpectedValue(expectedValue, selectors, page2, context = {}) {
943
- if (!expectedValue || typeof expectedValue !== "object" || !("ref" in expectedValue)) return expectedValue;
944
- let refSelector;
945
- if (expectedValue.ref === "relative") {
946
- if (!expectedValue.relativeTarget || !context.relativeBaseSelector) return void 0;
947
- const baseLocator = page2.locator(context.relativeBaseSelector);
948
- const count = await baseLocator.count();
949
- let idx = 0;
950
- if (expectedValue.relativeTarget === "first") idx = 0;
951
- else if (expectedValue.relativeTarget === "second") idx = 1;
952
- else if (expectedValue.relativeTarget === "last") idx = count - 1;
953
- else if (!isNaN(Number(expectedValue.relativeTarget))) idx = Number(expectedValue.relativeTarget);
954
- else idx = 0;
955
- if (idx < 0 || idx >= count) return void 0;
956
- const relElem = baseLocator.nth(idx);
957
- return await getPropertyFromLocator(relElem, expectedValue.property || expectedValue.attribute);
958
- } else {
959
- refSelector = selectors[expectedValue.ref];
960
- if (!refSelector) throw new Error(`Selector for ref '${expectedValue.ref}' not found in contract selectors.`);
961
- const refLocator = page2.locator(refSelector).first();
962
- return await getPropertyFromLocator(refLocator, expectedValue.property || expectedValue.attribute);
963
- }
964
- }
965
- async function getPropertyFromLocator(locator, property) {
966
- if (!locator) return void 0;
967
- if (!property || property === "id") {
968
- return await locator.getAttribute("id") ?? void 0;
969
- } else if (property === "class") {
970
- return await locator.getAttribute("class") ?? void 0;
971
- } else if (property === "textContent") {
972
- return await locator.evaluate((el) => el.textContent ?? void 0);
973
- } else if (property.startsWith("aria-")) {
974
- return await locator.getAttribute(property) ?? void 0;
975
- } else if (property.endsWith("*")) {
976
- const attrs = await locator.evaluate((el) => {
977
- const out = [];
978
- for (const attr of Array.from(el.attributes)) {
979
- if (attr.name.startsWith("aria-")) out.push(`${attr.name}=${attr.value}`);
980
- }
981
- return out.join(";");
982
- });
983
- return attrs;
984
- } else {
985
- return await locator.getAttribute(property) ?? void 0;
986
- }
987
- }
988
- const staticAssertionRunner = new AssertionRunner(page, componentContract.selectors, assertionTimeoutMs);
989
- async function runSetupActions(setup, actionExecutor, strategy2, page2, description, skipKeywords = []) {
990
- if (!Array.isArray(setup) || setup.length === 0) return { success: true };
991
- if (strategy2 && typeof strategy2.resetState === "function") {
992
- await strategy2.resetState(page2);
993
- }
994
- for (const setupAct of setup) {
995
- let setupResult = { success: true };
996
- try {
997
- if (setupAct.type === "focus") {
998
- if (setupAct.target === "relative" && setupAct.relativeTarget) {
999
- setupResult = await actionExecutor.focus("relative", setupAct.relativeTarget);
1000
- } else {
1001
- setupResult = await actionExecutor.focus(setupAct.target);
1002
- }
1003
- } else if (setupAct.type === "type" && setupAct.value) {
1004
- setupResult = await actionExecutor.type(setupAct.target, setupAct.value);
1005
- } else if (setupAct.type === "click") {
1006
- setupResult = await actionExecutor.click(setupAct.target, setupAct.relativeTarget);
1007
- } else if (setupAct.type === "keypress" && setupAct.key) {
1008
- setupResult = await actionExecutor.keypress(setupAct.target, setupAct.key);
1009
- } else if (setupAct.type === "hover") {
1010
- setupResult = await actionExecutor.hover(setupAct.target, setupAct.relativeTarget);
1011
- } else {
1012
- continue;
1013
- }
1014
- } catch (err) {
1015
- setupResult = { success: false, error: err instanceof Error ? err.message : String(err) };
1016
- }
1017
- if (!setupResult.success) {
1018
- const setupMsg = setupResult.error || "Setup action failed";
1019
- const isSkip = skipKeywords.some((kw) => description.includes(kw) || setupMsg.includes(kw));
1020
- if (isSkip) {
1021
- return { success: false, skip: true, message: `Skipping test - capability not present: ${setupMsg}` };
1022
- }
1023
- return { success: false, error: setupMsg };
1024
- }
1025
- }
1026
- return { success: true };
1027
- }
1028
- for (const test of componentContract.static[0]?.assertions || []) {
1029
- if (strategy && typeof strategy.resetState === "function") {
1030
- try {
1031
- await strategy.resetState(page);
1032
- } catch (err) {
1033
- warnings.push(`Warning: resetState failed before static test: ${err instanceof Error ? err.message : String(err)}`);
1034
- }
1035
- }
1036
- if (test.target === "relative") continue;
1037
- const staticDescription = `${test.target}${test.attribute ? ` (${test.attribute})` : ""}`;
1038
- const staticLevel = normalizeLevel(test.level);
1039
- if (componentName === "menu" && test.target === "submenuTrigger" && !hasSubmenuCapability) {
1040
- const skipMessage = `Skipping submenu static assertion for ${test.target}: no submenu capability detected in rendered component.`;
1041
- skipped.push(skipMessage);
1042
- reporter.reportStaticTest(staticDescription, "skip", skipMessage, staticLevel);
1043
- continue;
1044
- }
1045
- if (Array.isArray(test.setup) && test.setup.length > 0) {
1046
- let isAllowedType2 = function(t) {
1047
- return allowedTypes.includes(t);
1048
- };
1049
- var isAllowedType = isAllowedType2;
1050
- const actionExecutor = new ActionExecutor(page, componentContract.selectors, actionTimeoutMs);
1051
- const allowedTypes = ["focus", "type", "click", "keypress", "hover"];
1052
- const toSetupAction = (a) => ({
1053
- ...a,
1054
- type: isAllowedType2(a.type) ? a.type : "click"
1055
- });
1056
- const setupActions = test.setup.map(toSetupAction);
1057
- const setupResult = await runSetupActions(setupActions, actionExecutor, strategy, page, staticDescription, ["submenu", "submenuTrigger", "submenuItems"]);
1058
- if (setupResult.skip) {
1059
- skipped.push(setupResult.message || "Setup action skipped");
1060
- reporter.reportStaticTest(staticDescription, "skip", setupResult.message, staticLevel);
1061
- continue;
1062
- }
1063
- if (!setupResult.success) {
1064
- const failure = `Static setup failed: ${setupResult.error}`;
1065
- const outcome = classifyFailure(failure, test.level);
1066
- if (outcome.status === "fail") staticFailed += 1;
1067
- if (outcome.status === "warn") staticWarnings += 1;
1068
- reporter.reportStaticTest(staticDescription, outcome.status, outcome.detail, outcome.level);
1069
- continue;
1070
- }
1071
- }
1072
- const targetSelector = componentContract.selectors[test.target];
1073
- if (!targetSelector) {
1074
- const failure = `Selector for target ${test.target} not found.`;
1075
- const outcome = classifyFailure(failure, test.level);
1076
- if (outcome.status === "fail") staticFailed += 1;
1077
- if (outcome.status === "warn") staticWarnings += 1;
1078
- reporter.reportStaticTest(staticDescription, outcome.status, outcome.detail, outcome.level);
1079
- continue;
1080
- }
1081
- const target = page.locator(targetSelector).first();
1082
- const exists = await target.count() > 0;
1083
- if (!exists) {
1084
- const failure = `Target ${test.target} not found.`;
1085
- const outcome = classifyFailure(failure, test.level);
1086
- if (outcome.status === "fail") staticFailed += 1;
1087
- if (outcome.status === "warn") staticWarnings += 1;
1088
- reporter.reportStaticTest(staticDescription, outcome.status, outcome.detail, outcome.level);
1089
- continue;
1090
- }
1091
- const isRedundantCheck = (selector, attrName, expectedVal) => {
1092
- const attrPattern = new RegExp(`\\[${attrName}(?:=["']?([^\\]"']+)["']?)?\\]`);
1093
- const match = selector.match(attrPattern);
1094
- if (!match) return false;
1095
- if (!expectedVal) return true;
1096
- const selectorValue = match[1];
1097
- if (selectorValue) {
1098
- const expectedValues = expectedVal.split(" | ");
1099
- return expectedValues.includes(selectorValue);
1100
- }
1101
- return false;
1102
- };
1103
- let expectedValue = test.expectedValue;
1104
- if (test.expectedValue && typeof test.expectedValue === "object" && "ref" in test.expectedValue) {
1105
- const context = {};
1106
- const relTarget = test.relativeTarget;
1107
- if (test.expectedValue.ref === "relative" && test.target === "relative" && relTarget) {
1108
- const baseSel = componentContract.selectors[relTarget];
1109
- if (!baseSel) throw new Error(`Selector for relativeTarget '${relTarget}' not found in contract selectors.`);
1110
- context.relativeBaseSelector = baseSel;
1111
- } else if (test.expectedValue.ref === "relative" && relTarget) {
1112
- const baseSel = componentContract.selectors[relTarget];
1113
- if (!baseSel) throw new Error(`Selector for relativeTarget '${relTarget}' not found in contract selectors.`);
1114
- context.relativeBaseSelector = baseSel;
1115
- }
1116
- expectedValue = await resolveExpectedValue(test.expectedValue, componentContract.selectors, page, context);
1117
- console.log("Expected value in static check", expectedValue);
1118
- }
1119
- if (!test.expectedValue) {
1120
- const attributes = test.attribute.split(" | ");
1121
- let hasAny = false;
1122
- let allRedundant = true;
1123
- for (const attr of attributes) {
1124
- const attrTrimmed = attr.trim();
1125
- if (isRedundantCheck(targetSelector, attrTrimmed)) {
1126
- passes.push(`${attrTrimmed} on ${test.target} verified by selector (already present in: ${targetSelector}).`);
1127
- hasAny = true;
1128
- continue;
1129
- }
1130
- allRedundant = false;
1131
- const value = await target.getAttribute(attrTrimmed);
1132
- if (value !== null) {
1133
- hasAny = true;
1134
- break;
1135
- }
1136
- }
1137
- if (!hasAny && !allRedundant) {
1138
- const failure = test.failureMessage + ` None of the attributes "${test.attribute}" are present.`;
1139
- const outcome = classifyFailure(failure, test.level);
1140
- if (outcome.status === "fail") staticFailed += 1;
1141
- if (outcome.status === "warn") staticWarnings += 1;
1142
- reporter.reportStaticTest(staticDescription, outcome.status, outcome.detail, outcome.level);
1143
- } else if (!allRedundant && hasAny) {
1144
- passes.push(`At least one of the attributes "${test.attribute}" exists on the element.`);
1145
- staticPassed += 1;
1146
- reporter.reportStaticTest(staticDescription, "pass", void 0, staticLevel);
1147
- } else {
1148
- staticPassed += 1;
1149
- reporter.reportStaticTest(staticDescription, "pass", void 0, staticLevel);
1150
- }
1151
- } else {
1152
- if (isRedundantCheck(targetSelector, test.attribute, typeof expectedValue === "string" ? expectedValue : void 0)) {
1153
- passes.push(`${test.attribute}="${expectedValue}" on ${test.target} verified by selector (already present in: ${targetSelector}).`);
1154
- staticPassed += 1;
1155
- reporter.reportStaticTest(staticDescription, "pass", void 0, staticLevel);
1156
- } else {
1157
- const valueToCheck = expectedValue ?? "";
1158
- const result = await staticAssertionRunner.validateAttribute(
1159
- target,
1160
- test.target,
1161
- test.attribute,
1162
- valueToCheck,
1163
- test.failureMessage,
1164
- "Static ARIA Test"
1165
- );
1166
- if (result.success && result.passMessage) {
1167
- passes.push(result.passMessage);
1168
- staticPassed += 1;
1169
- reporter.reportStaticTest(staticDescription, "pass", void 0, staticLevel);
1170
- } else if (!result.success && result.failMessage) {
1171
- const outcome = classifyFailure(result.failMessage, test.level);
1172
- if (outcome.status === "fail") staticFailed += 1;
1173
- if (outcome.status === "warn") staticWarnings += 1;
1174
- reporter.reportStaticTest(staticDescription, outcome.status, outcome.detail, outcome.level);
1175
- }
1176
- }
1177
- }
1178
- }
1179
- for (const dynamicTest of componentContract.dynamic || []) {
1180
- if (!page || page.isClosed()) {
1181
- console.warn(`
1182
- \u26A0\uFE0F Browser closed - skipping remaining ${componentContract.dynamic.length - componentContract.dynamic.indexOf(dynamicTest)} tests
1183
- `);
1184
- failures.push(`CRITICAL: Browser/page closed before completing all tests. ${componentContract.dynamic.length - componentContract.dynamic.indexOf(dynamicTest)} tests skipped.`);
1185
- break;
1186
- }
1187
- try {
1188
- await strategy.resetState(page);
1189
- } catch (error) {
1190
- const errorMessage = error instanceof Error ? error.message : String(error);
1191
- reporter.error(errorMessage);
1192
- throw error;
1193
- }
1194
- const { setup = [], action, assertions } = dynamicTest;
1195
- const dynamicLevel = normalizeLevel(dynamicTest.level);
1196
- const actionExecutor = new ActionExecutor(page, componentContract.selectors, actionTimeoutMs);
1197
- if (Array.isArray(setup) && setup.length > 0) {
1198
- let isAllowedType2 = function(t) {
1199
- return allowedTypes.includes(t);
1200
- };
1201
- var isAllowedType = isAllowedType2;
1202
- const allowedTypes = ["focus", "type", "click", "keypress", "hover"];
1203
- const toSetupAction = (a) => ({
1204
- ...a,
1205
- type: isAllowedType2(a.type) ? a.type : "click"
1206
- });
1207
- const setupActions = setup.map(toSetupAction);
1208
- const setupResult = await runSetupActions(setupActions, actionExecutor, strategy, page, dynamicTest.description, ["submenu", "submenuTrigger", "submenuItems"]);
1209
- if (setupResult.skip) {
1210
- skipped.push(setupResult.message || "Setup action skipped");
1211
- reporter.reportTest({ description: dynamicTest.description, level: dynamicLevel }, "skip", setupResult.message);
1212
- continue;
1213
- }
1214
- if (!setupResult.success) {
1215
- const outcome = classifyFailure(`Setup failed: ${setupResult.error}`, dynamicTest.level);
1216
- reporter.reportTest({ description: dynamicTest.description, level: dynamicLevel }, outcome.status, outcome.detail);
1217
- continue;
1218
- }
1219
- }
1220
- const failuresBeforeTest = failures.length;
1221
- const warningsBeforeTest = warnings.length;
1222
- const skippedBeforeTest = skipped.length;
1223
- const shouldSkipTest = await strategy.shouldSkipTest(dynamicTest, page);
1224
- if (shouldSkipTest) {
1225
- const skipMessage = `Skipping test - component-specific conditions not met`;
1226
- skipped.push(skipMessage);
1227
- reporter.reportTest({ description: dynamicTest.description, level: dynamicLevel }, "skip", skipMessage);
1228
- continue;
1229
- }
1230
- const assertionRunner = new AssertionRunner(page, componentContract.selectors, assertionTimeoutMs);
1231
- let shouldAbortCurrentTest = false;
1232
- let actionOutcome = null;
1233
- for (const act of action) {
1234
- if (!page || page.isClosed()) {
1235
- failures.push(`CRITICAL: Browser/page closed during test execution. Remaining actions skipped.`);
1236
- shouldAbortCurrentTest = true;
1237
- break;
1238
- }
1239
- let result;
1240
- if (act.type === "focus") {
1241
- if (act.target === "relative" && act.relativeTarget) {
1242
- result = await actionExecutor.focus("relative", act.relativeTarget);
1243
- } else {
1244
- result = await actionExecutor.focus(act.target);
1245
- }
1246
- } else if (act.type === "type" && act.value) {
1247
- result = await actionExecutor.type(act.target, act.value);
1248
- } else if (act.type === "click") {
1249
- result = await actionExecutor.click(act.target, act.relativeTarget);
1250
- } else if (act.type === "keypress" && act.key) {
1251
- result = await actionExecutor.keypress(act.target, act.key);
1252
- } else if (act.type === "hover") {
1253
- result = await actionExecutor.hover(act.target, act.relativeTarget);
1254
- } else {
1255
- continue;
1256
- }
1257
- if (!result.success) {
1258
- if (result.error) {
1259
- const outcome = classifyFailure(result.error, dynamicTest.level);
1260
- actionOutcome = { status: outcome.status, detail: outcome.detail };
1261
- }
1262
- shouldAbortCurrentTest = true;
1263
- break;
1264
- }
1265
- }
1266
- if (shouldAbortCurrentTest) {
1267
- reporter.reportTest(
1268
- { description: dynamicTest.description, level: dynamicLevel },
1269
- actionOutcome?.status || "fail",
1270
- actionOutcome?.detail || failures[failures.length - 1]
1271
- );
1272
- continue;
1273
- }
1274
- for (const assertion of assertions) {
1275
- let expectedValue;
1276
- if (assertion.expectedValue && typeof assertion.expectedValue === "object" && "ref" in assertion.expectedValue) {
1277
- if (assertion.expectedValue.ref === "relative") {
1278
- const { RelativeTargetResolver: RelativeTargetResolver2 } = await import('./RelativeTargetResolver-G2XDN2VV.js');
1279
- const relativeSelector = componentContract.selectors.relative;
1280
- if (!relativeSelector) throw new Error("Relative selector not defined in contract selectors.");
1281
- const relTarget = assertion.relativeTarget || "first";
1282
- const relElem = await RelativeTargetResolver2.resolve(page, relativeSelector, relTarget);
1283
- if (!relElem) throw new Error(`Could not resolve relative target '${relTarget}' for expectedValue.`);
1284
- const prop = assertion.expectedValue.property || assertion.expectedValue.attribute || "id";
1285
- if (prop === "textContent") {
1286
- expectedValue = await relElem.evaluate((el) => el.textContent ?? void 0);
1287
- } else {
1288
- const attr = await relElem.getAttribute(prop);
1289
- expectedValue = attr === null ? void 0 : attr;
1290
- }
1291
- } else {
1292
- expectedValue = await resolveExpectedValue(assertion.expectedValue, componentContract.selectors, page, {});
1293
- }
1294
- } else if (typeof assertion.expectedValue === "string" || typeof assertion.expectedValue === "undefined") {
1295
- expectedValue = assertion.expectedValue;
1296
- } else {
1297
- expectedValue = "";
1298
- }
1299
- const assertionToRun = { ...assertion, expectedValue };
1300
- const valueToCheck = expectedValue ?? "";
1301
- const result = await assertionRunner.validate({ ...assertionToRun, expectedValue: valueToCheck }, dynamicTest.description);
1302
- if (result.success && result.passMessage) {
1303
- passes.push(result.passMessage);
1304
- } else if (!result.success && result.failMessage) {
1305
- const assertionLevel = normalizeLevel(assertion.level || dynamicTest.level);
1306
- const outcome = classifyFailure(result.failMessage, assertionLevel);
1307
- if (outcome.status === "skip") {
1308
- continue;
1309
- }
1310
- }
1311
- }
1312
- const failuresAfterTest = failures.length;
1313
- const warningsAfterTest = warnings.length;
1314
- const skippedAfterTest = skipped.length;
1315
- if (failuresAfterTest > failuresBeforeTest) {
1316
- reporter.reportTest(
1317
- { description: dynamicTest.description, level: dynamicLevel },
1318
- "fail",
1319
- failures[failures.length - 1]
1320
- );
1321
- } else if (warningsAfterTest > warningsBeforeTest) {
1322
- reporter.reportTest(
1323
- { description: dynamicTest.description, level: dynamicLevel },
1324
- "warn",
1325
- warnings[warnings.length - 1]
1326
- );
1327
- } else if (skippedAfterTest > skippedBeforeTest) {
1328
- reporter.reportTest(
1329
- { description: dynamicTest.description, level: dynamicLevel },
1330
- "skip",
1331
- skipped[skipped.length - 1]
1332
- );
1333
- } else {
1334
- reporter.reportTest({ description: dynamicTest.description, level: dynamicLevel }, "pass");
1335
- }
1336
- }
1337
- reporter.reportStatic(staticPassed, staticFailed, staticWarnings);
1338
- reporter.summary(failures);
1339
- } catch (error) {
1340
- if (error instanceof Error) {
1341
- if (error.message.includes("Executable doesn't exist") || error.message.includes("browserType.launch")) {
1342
- throw new Error("\n\u274C CRITICAL: Playwright browsers not found!\n\u{1F4E6} Run: npx playwright install chromium");
1343
- } else if (error.message.includes("net::ERR_CONNECTION_REFUSED") || error.message.includes("NS_ERROR_CONNECTION_REFUSED")) {
1344
- throw new Error(`
1345
- \u274C CRITICAL: Cannot connect to dev server!
1346
- Make sure your dev server is running at ${url}`);
1347
- } else if (error.message.includes("Timeout") && error.message.includes("waitFor")) {
1348
- throw new Error(
1349
- `
1350
- \u274C CRITICAL: Component not found on page!
1351
- The component selector could not be found within ${componentReadyTimeoutMs}ms.
1352
- This usually means:
1353
- - The component didn't render
1354
- - The URL is incorrect
1355
- - The component selector was not provided to the component utility, or a wrong selector was used
1356
- `
1357
- );
1358
- } else if (error.message.includes("Target page, context or browser has been closed")) {
1359
- throw new Error(
1360
- "\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"
1361
- );
1362
- } else {
1363
- throw error;
1364
- }
1365
- }
1366
- } finally {
1367
- if (page) await page.close();
1368
- }
1369
- return { passes, failures, skipped, warnings };
1370
- }
1371
-
1372
- export { runContractTestsPlaywright };