ally-mcp-server 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2090 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Ally MCP Server
4
+ *
5
+ * Exposes project-specific accessibility patterns to GitHub Copilot CLI.
6
+ * This enables Copilot to generate fixes that are consistent with your codebase.
7
+ */
8
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
9
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
10
+ import { APCAcontrast, sRGBtoY } from 'apca-w3';
11
+ import { spawn } from 'node:child_process';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { existsSync } from 'fs';
14
+ import { readdir, readFile } from 'fs/promises';
15
+ import { dirname, extname, join } from 'path';
16
+ import { z } from 'zod';
17
+ // Create server instance
18
+ const server = new McpServer({
19
+ name: 'ally-patterns',
20
+ version: '1.0.2',
21
+ });
22
+ // Telemetry to track tool usage
23
+ const telemetry = {
24
+ calls: new Map(),
25
+ lastCalled: new Map(),
26
+ log(toolName) {
27
+ const count = this.calls.get(toolName) || 0;
28
+ this.calls.set(toolName, count + 1);
29
+ this.lastCalled.set(toolName, new Date());
30
+ console.error(`[MCP Telemetry] ${new Date().toISOString()} | ${toolName} called (${count + 1}x total)`);
31
+ },
32
+ };
33
+ // Cache for analyzed patterns
34
+ const patternCache = new Map();
35
+ const tokenCache = new Map();
36
+ // Tool: Get component ARIA patterns from codebase
37
+ server.tool('get_component_patterns', 'Analyze existing ARIA patterns in React/Vue components to ensure consistent accessibility fixes', {
38
+ directory: z
39
+ .string()
40
+ .optional()
41
+ .describe('Directory to analyze (defaults to current directory)'),
42
+ component: z.string().optional().describe('Specific component name to analyze'),
43
+ }, async ({ directory, component }) => {
44
+ telemetry.log('get_component_patterns');
45
+ const targetDir = directory || process.cwd();
46
+ try {
47
+ const patterns = await analyzeComponentPatterns(targetDir, component);
48
+ if (patterns.length === 0) {
49
+ return {
50
+ content: [
51
+ {
52
+ type: 'text',
53
+ text: 'No component patterns found. This might be a new project or use a different framework.',
54
+ },
55
+ ],
56
+ };
57
+ }
58
+ const summary = patterns.map((p) => {
59
+ const features = [];
60
+ if (p.patterns.hasAriaLabel)
61
+ features.push('aria-label');
62
+ if (p.patterns.hasAriaDescribedBy)
63
+ features.push('aria-describedby');
64
+ if (p.patterns.hasRole)
65
+ features.push('role attributes');
66
+ if (p.patterns.hasFocusManagement)
67
+ features.push('focus management');
68
+ if (p.patterns.hasKeyboardHandlers)
69
+ features.push('keyboard handlers');
70
+ return `## ${p.component} (${p.file})
71
+ ARIA Features: ${features.length > 0 ? features.join(', ') : 'none found'}
72
+ ${p.examples.length > 0 ? `\nExamples:\n${p.examples.slice(0, 2).join('\n')}` : ''}`;
73
+ });
74
+ return {
75
+ content: [
76
+ {
77
+ type: 'text',
78
+ text: `# Component ARIA Patterns\n\n${summary.join('\n\n')}`,
79
+ },
80
+ ],
81
+ };
82
+ }
83
+ catch (error) {
84
+ return {
85
+ content: [
86
+ {
87
+ type: 'text',
88
+ text: `Error analyzing patterns: ${error instanceof Error ? error.message : String(error)}`,
89
+ },
90
+ ],
91
+ isError: true,
92
+ };
93
+ }
94
+ });
95
+ // Tool: Get design tokens for contrast-safe color suggestions
96
+ server.tool('get_design_tokens', 'Extract design tokens (colors, spacing) from CSS/SCSS/Tailwind config for WCAG-compliant fixes', {
97
+ directory: z.string().optional().describe('Directory to search for design tokens'),
98
+ }, async ({ directory }) => {
99
+ telemetry.log('get_design_tokens');
100
+ const targetDir = directory || process.cwd();
101
+ try {
102
+ const tokens = await extractDesignTokens(targetDir);
103
+ if (!tokens.colors.length && !tokens.spacing.length) {
104
+ return {
105
+ content: [
106
+ {
107
+ type: 'text',
108
+ text: 'No design tokens found. Consider using a CSS variables file or Tailwind config.',
109
+ },
110
+ ],
111
+ };
112
+ }
113
+ const wcagCompliantColors = tokens.colors.filter((c) => c.wcagAACompliant);
114
+ let response = '# Design Tokens\n\n';
115
+ if (wcagCompliantColors.length > 0) {
116
+ response += '## WCAG AA Compliant Colors\n';
117
+ response += wcagCompliantColors
118
+ .map((c) => `- ${c.name}: ${c.value} (contrast: ${c.contrastRatio?.toFixed(1) || 'unknown'})`)
119
+ .join('\n');
120
+ response += '\n\n';
121
+ }
122
+ if (tokens.colors.length > 0) {
123
+ response += '## All Colors\n';
124
+ response += tokens.colors.map((c) => `- ${c.name}: ${c.value}`).join('\n');
125
+ response += '\n\n';
126
+ }
127
+ if (tokens.spacing.length > 0) {
128
+ response += '## Spacing\n';
129
+ response += tokens.spacing.map((s) => `- ${s}`).join('\n');
130
+ }
131
+ return {
132
+ content: [
133
+ {
134
+ type: 'text',
135
+ text: response,
136
+ },
137
+ ],
138
+ };
139
+ }
140
+ catch (error) {
141
+ return {
142
+ content: [
143
+ {
144
+ type: 'text',
145
+ text: `Error extracting tokens: ${error instanceof Error ? error.message : String(error)}`,
146
+ },
147
+ ],
148
+ isError: true,
149
+ };
150
+ }
151
+ });
152
+ // Tool: Get previous fix history for consistency
153
+ server.tool('get_fix_history', 'Retrieve previously applied accessibility fixes to maintain consistency', {
154
+ issueType: z
155
+ .string()
156
+ .optional()
157
+ .describe("Filter by issue type (e.g., 'image-alt', 'button-name')"),
158
+ }, async ({ issueType }) => {
159
+ telemetry.log('get_fix_history');
160
+ try {
161
+ const historyPath = join(process.cwd(), '.ally', 'fix-history.json');
162
+ if (!existsSync(historyPath)) {
163
+ return {
164
+ content: [
165
+ {
166
+ type: 'text',
167
+ text: "No fix history found. Run 'ally fix' to start building a history of applied fixes.",
168
+ },
169
+ ],
170
+ };
171
+ }
172
+ const historyContent = await readFile(historyPath, 'utf-8');
173
+ const history = JSON.parse(historyContent);
174
+ let filtered = history;
175
+ if (issueType) {
176
+ filtered = history.filter((h) => h.issueType === issueType);
177
+ }
178
+ if (filtered.length === 0) {
179
+ return {
180
+ content: [
181
+ {
182
+ type: 'text',
183
+ text: issueType
184
+ ? `No fixes found for issue type: ${issueType}`
185
+ : 'No fixes in history yet.',
186
+ },
187
+ ],
188
+ };
189
+ }
190
+ const summary = filtered.slice(-10).map((h) => {
191
+ return `- **${h.issueType}** in ${h.file}
192
+ Before: \`${h.before.slice(0, 60)}...\`
193
+ After: \`${h.after.slice(0, 60)}...\``;
194
+ });
195
+ return {
196
+ content: [
197
+ {
198
+ type: 'text',
199
+ text: `# Recent Fixes\n\n${summary.join('\n\n')}`,
200
+ },
201
+ ],
202
+ };
203
+ }
204
+ catch (error) {
205
+ return {
206
+ content: [
207
+ {
208
+ type: 'text',
209
+ text: `Error reading fix history: ${error instanceof Error ? error.message : String(error)}`,
210
+ },
211
+ ],
212
+ isError: true,
213
+ };
214
+ }
215
+ });
216
+ // Tool: Get scan results summary
217
+ server.tool('get_scan_summary', 'Get a summary of current accessibility issues from the latest scan', {}, async () => {
218
+ telemetry.log('get_scan_summary');
219
+ try {
220
+ const scanPath = join(process.cwd(), '.ally', 'scan.json');
221
+ if (!existsSync(scanPath)) {
222
+ return {
223
+ content: [
224
+ {
225
+ type: 'text',
226
+ text: "No scan results found. Run 'ally scan' first.",
227
+ },
228
+ ],
229
+ };
230
+ }
231
+ const scanContent = await readFile(scanPath, 'utf-8');
232
+ const scan = JSON.parse(scanContent);
233
+ const summary = `# Accessibility Scan Summary
234
+
235
+ **Score:** ${scan.summary.score}/100
236
+ **Total Issues:** ${scan.summary.totalViolations}
237
+
238
+ ## By Severity
239
+ - Critical: ${scan.summary.bySeverity.critical || 0}
240
+ - Serious: ${scan.summary.bySeverity.serious || 0}
241
+ - Moderate: ${scan.summary.bySeverity.moderate || 0}
242
+ - Minor: ${scan.summary.bySeverity.minor || 0}
243
+
244
+ ## Top Issues
245
+ ${scan.summary.topIssues.map((i) => `- ${i.description} (${i.count} occurrences)`).join('\n')}`;
246
+ return {
247
+ content: [
248
+ {
249
+ type: 'text',
250
+ text: summary,
251
+ },
252
+ ],
253
+ };
254
+ }
255
+ catch (error) {
256
+ return {
257
+ content: [
258
+ {
259
+ type: 'text',
260
+ text: `Error reading scan results: ${error instanceof Error ? error.message : String(error)}`,
261
+ },
262
+ ],
263
+ isError: true,
264
+ };
265
+ }
266
+ });
267
+ const wcagCriteria = {
268
+ '1.1.1': {
269
+ id: '1.1.1',
270
+ title: 'Non-text Content',
271
+ level: 'A',
272
+ description: 'All non-text content that is presented to the user has a text alternative that serves the equivalent purpose, except for controls, input, time-based media, tests, sensory experiences, CAPTCHA, and decoration.',
273
+ techniques: [
274
+ 'G94: Providing short text alternative for non-text content',
275
+ 'G95: Providing short text alternatives that identify non-text content',
276
+ 'H37: Using alt attributes on img elements',
277
+ 'H67: Using null alt text and no title attribute for images decoration',
278
+ 'ARIA6: Using aria-label to provide labels for objects',
279
+ 'ARIA10: Using aria-labelledby to provide a text alternative for non-text content',
280
+ ],
281
+ failures: [
282
+ 'F3: Using CSS to include images that convey important information',
283
+ 'F20: Not updating text alternatives when non-text content changes',
284
+ 'F30: Using text alternatives that are not alternatives',
285
+ 'F38: Not marking up decorative images to be ignored by assistive technology',
286
+ 'F39: Providing a text alternative that is not null for images that should be ignored',
287
+ 'F65: Omitting the alt attribute or text alternative on img elements',
288
+ ],
289
+ relatedViolations: ['image-alt', 'input-image-alt', 'area-alt', 'object-alt', 'svg-img-alt'],
290
+ },
291
+ '1.3.1': {
292
+ id: '1.3.1',
293
+ title: 'Info and Relationships',
294
+ level: 'A',
295
+ description: 'Information, structure, and relationships conveyed through presentation can be programmatically determined or are available in text.',
296
+ techniques: [
297
+ 'G115: Using semantic elements to mark up structure',
298
+ 'G140: Separating information and structure from presentation',
299
+ 'H42: Using h1-h6 to identify headings',
300
+ 'H44: Using label elements to associate text labels with form controls',
301
+ 'H48: Using ol, ul and dl for lists',
302
+ 'H51: Using table markup for tabular information',
303
+ 'ARIA11: Using ARIA landmarks to identify regions of a page',
304
+ 'ARIA12: Using role=heading to identify headings',
305
+ ],
306
+ failures: [
307
+ 'F2: Using changes in text presentation to convey information without semantic markup',
308
+ 'F33: Using white space characters to create visual lists',
309
+ 'F34: Using white space characters to format tables',
310
+ 'F43: Failing to identify content using ARIA semantic roles',
311
+ 'F46: Failing to identify content using proper heading markup',
312
+ ],
313
+ relatedViolations: [
314
+ 'heading-order',
315
+ 'list',
316
+ 'listitem',
317
+ 'table-fake-caption',
318
+ 'td-headers-attr',
319
+ 'th-has-data-cells',
320
+ ],
321
+ },
322
+ '1.3.5': {
323
+ id: '1.3.5',
324
+ title: 'Identify Input Purpose',
325
+ level: 'AA',
326
+ description: 'The purpose of each input field collecting information about the user can be programmatically determined when the input field serves a purpose identified in the Input Purposes for User Interface Components section.',
327
+ techniques: [
328
+ 'H98: Using HTML5.2 autocomplete attributes',
329
+ 'Identify the purpose of contact information fields using autocomplete',
330
+ ],
331
+ failures: ['Failure to use autocomplete attribute when collecting user information'],
332
+ relatedViolations: ['autocomplete-valid'],
333
+ },
334
+ '1.4.1': {
335
+ id: '1.4.1',
336
+ title: 'Use of Color',
337
+ level: 'A',
338
+ description: 'Color is not used as the only visual means of conveying information, indicating an action, prompting a response, or distinguishing a visual element.',
339
+ techniques: [
340
+ 'G14: Using a non-text contrast ratio of at least 3:1',
341
+ 'G182: Ensuring that additional visual cues are available when text color differences are used',
342
+ 'G183: Using a contrast ratio of 3:1 with surrounding text and providing additional visual cues on focus for links or controls',
343
+ ],
344
+ failures: [
345
+ 'F13: Failure due to having a text alternative that does not include information conveyed by color differences',
346
+ 'F73: Failure due to creating links that are not visually evident without color vision',
347
+ 'F81: Failure due to identifying required or error fields using color differences only',
348
+ ],
349
+ relatedViolations: ['link-in-text-block'],
350
+ },
351
+ '1.4.3': {
352
+ id: '1.4.3',
353
+ title: 'Contrast (Minimum)',
354
+ level: 'AA',
355
+ description: 'The visual presentation of text and images of text has a contrast ratio of at least 4.5:1, except for large text (3:1), incidental text, and logotypes.',
356
+ techniques: [
357
+ 'G18: Ensuring a contrast ratio of at least 4.5:1 between text and background',
358
+ 'G145: Ensuring a contrast ratio of at least 3:1 for large text',
359
+ 'G174: Providing a control with sufficient contrast ratio to toggle high contrast',
360
+ 'G148: Not specifying background color and not specifying text color',
361
+ ],
362
+ failures: [
363
+ 'F24: Failure due to specifying foreground without specifying background colors',
364
+ 'F83: Failure due to using background images that do not provide sufficient contrast',
365
+ ],
366
+ relatedViolations: ['color-contrast', 'color-contrast-enhanced'],
367
+ },
368
+ '1.4.11': {
369
+ id: '1.4.11',
370
+ title: 'Non-text Contrast',
371
+ level: 'AA',
372
+ description: 'The visual presentation of user interface components and graphical objects have a contrast ratio of at least 3:1 against adjacent colors.',
373
+ techniques: [
374
+ 'G195: Using an author-supplied, visible focus indicator',
375
+ 'G207: Ensuring that a contrast ratio of 3:1 is provided for icons',
376
+ 'G209: Providing sufficient contrast at the boundaries between adjoining colors',
377
+ ],
378
+ failures: ['F78: Failure due to using purely decorative elements with insufficient contrast'],
379
+ relatedViolations: ['focus-visible', 'link-in-text-block'],
380
+ },
381
+ '2.1.1': {
382
+ id: '2.1.1',
383
+ title: 'Keyboard',
384
+ level: 'A',
385
+ description: 'All functionality of the content is operable through a keyboard interface without requiring specific timings for individual keystrokes.',
386
+ techniques: [
387
+ 'G202: Ensuring keyboard control for all functionality',
388
+ 'H91: Using HTML form controls and links',
389
+ 'SCR2: Using redundant keyboard and mouse event handlers',
390
+ 'SCR20: Using both keyboard and other device-specific functions',
391
+ ],
392
+ failures: [
393
+ 'F42: Failure due to using scripting events to emulate links without proper keyboard access',
394
+ 'F54: Failure due to using only pointing-device-specific event handlers',
395
+ 'F55: Failure due to using script to remove focus when focus is received',
396
+ ],
397
+ relatedViolations: ['accesskeys', 'focus-order-semantics', 'scrollable-region-focusable'],
398
+ },
399
+ '2.1.2': {
400
+ id: '2.1.2',
401
+ title: 'No Keyboard Trap',
402
+ level: 'A',
403
+ description: 'If keyboard focus can be moved to a component using a keyboard interface, then focus can be moved away from that component using only a keyboard interface.',
404
+ techniques: [
405
+ 'G21: Ensuring users are not trapped in content',
406
+ 'FLASH17: Providing keyboard access to a Flash object and avoiding a keyboard trap',
407
+ ],
408
+ failures: [
409
+ 'F10: Failure due to combining multiple content formats in a way that traps users inside one format type',
410
+ ],
411
+ relatedViolations: ['focus-trap'],
412
+ },
413
+ '2.4.1': {
414
+ id: '2.4.1',
415
+ title: 'Bypass Blocks',
416
+ level: 'A',
417
+ description: 'A mechanism is available to bypass blocks of content that are repeated on multiple Web pages.',
418
+ techniques: [
419
+ 'G1: Adding a skip link at the top of each page',
420
+ 'G123: Adding a link at the beginning of a block of repeated content',
421
+ 'G124: Adding links at the top of the page to each area of the content',
422
+ 'ARIA11: Using ARIA landmarks to identify regions of a page',
423
+ 'H69: Providing heading elements at the beginning of each section of content',
424
+ ],
425
+ failures: ['No specific failures defined'],
426
+ relatedViolations: ['bypass', 'region', 'landmark-one-main'],
427
+ },
428
+ '2.4.2': {
429
+ id: '2.4.2',
430
+ title: 'Page Titled',
431
+ level: 'A',
432
+ description: 'Web pages have titles that describe topic or purpose.',
433
+ techniques: [
434
+ 'G88: Providing descriptive titles for Web pages',
435
+ 'H25: Providing a title using the title element',
436
+ ],
437
+ failures: ['F25: Failure due to the title of a Web page not identifying the contents'],
438
+ relatedViolations: ['document-title', 'page-has-heading-one'],
439
+ },
440
+ '2.4.3': {
441
+ id: '2.4.3',
442
+ title: 'Focus Order',
443
+ level: 'A',
444
+ description: 'If a Web page can be navigated sequentially and the navigation sequences affect meaning or operation, focusable components receive focus in an order that preserves meaning and operability.',
445
+ techniques: [
446
+ 'G59: Placing the interactive elements in an order that follows sequences and relationships within the content',
447
+ 'H4: Creating a logical tab order through links, form controls, and objects',
448
+ 'C27: Making the DOM order match the visual order',
449
+ ],
450
+ failures: [
451
+ 'F44: Failure due to using tabindex to create a tab order that does not preserve meaning and operability',
452
+ 'F85: Failure due to using dialogs or menus that are not adjacent to their trigger control in the sequence',
453
+ ],
454
+ relatedViolations: ['tabindex', 'focus-order-semantics'],
455
+ },
456
+ '2.4.4': {
457
+ id: '2.4.4',
458
+ title: 'Link Purpose (In Context)',
459
+ level: 'A',
460
+ description: 'The purpose of each link can be determined from the link text alone or from the link text together with its programmatically determined link context.',
461
+ techniques: [
462
+ 'G91: Providing link text that describes the purpose of a link',
463
+ 'H30: Providing link text that describes the purpose of a link for anchor elements',
464
+ 'H77: Identifying the purpose of a link using link text combined with its enclosing list item',
465
+ 'ARIA7: Using aria-labelledby for link purpose',
466
+ 'ARIA8: Using aria-label for link purpose',
467
+ ],
468
+ failures: [
469
+ 'F63: Failure due to providing link context only in content that is not related to the link',
470
+ 'F89: Failure due to not providing an accessible name for an image which is the only content in a link',
471
+ ],
472
+ relatedViolations: ['link-name', 'empty-links'],
473
+ },
474
+ '2.4.6': {
475
+ id: '2.4.6',
476
+ title: 'Headings and Labels',
477
+ level: 'AA',
478
+ description: 'Headings and labels describe topic or purpose.',
479
+ techniques: ['G130: Providing descriptive headings', 'G131: Providing descriptive labels'],
480
+ failures: ['No specific failures defined'],
481
+ relatedViolations: ['empty-heading', 'heading-order', 'label'],
482
+ },
483
+ '2.4.7': {
484
+ id: '2.4.7',
485
+ title: 'Focus Visible',
486
+ level: 'AA',
487
+ description: 'Any keyboard operable user interface has a mode of operation where the keyboard focus indicator is visible.',
488
+ techniques: [
489
+ 'G149: Using user interface components that are highlighted by the user agent when they receive focus',
490
+ 'G165: Using the default focus indicator for the platform',
491
+ 'G195: Using an author-supplied, visible focus indicator',
492
+ 'C15: Using CSS to change the presentation of a user interface component when it receives focus',
493
+ ],
494
+ failures: [
495
+ 'F55: Failure due to using script to remove focus when focus is received',
496
+ 'F78: Failure due to styling element outlines and borders in a way that removes or renders non-visible the visible focus indicator',
497
+ ],
498
+ relatedViolations: ['focus-visible'],
499
+ },
500
+ '3.1.1': {
501
+ id: '3.1.1',
502
+ title: 'Language of Page',
503
+ level: 'A',
504
+ description: 'The default human language of each Web page can be programmatically determined.',
505
+ techniques: ['H57: Using the language attribute on the HTML element'],
506
+ failures: ['No specific failures defined'],
507
+ relatedViolations: ['html-has-lang', 'html-lang-valid', 'html-xml-lang-mismatch'],
508
+ },
509
+ '3.1.2': {
510
+ id: '3.1.2',
511
+ title: 'Language of Parts',
512
+ level: 'AA',
513
+ description: 'The human language of each passage or phrase in the content can be programmatically determined except for proper names, technical terms, words of indeterminate language, and words or phrases that have become part of the vernacular.',
514
+ techniques: ['H58: Using language attributes to identify changes in the human language'],
515
+ failures: ['No specific failures defined'],
516
+ relatedViolations: ['valid-lang'],
517
+ },
518
+ '3.3.1': {
519
+ id: '3.3.1',
520
+ title: 'Error Identification',
521
+ level: 'A',
522
+ description: 'If an input error is automatically detected, the item that is in error is identified and the error is described to the user in text.',
523
+ techniques: [
524
+ 'G83: Providing text descriptions to identify required fields that were not completed',
525
+ 'G84: Providing a text description when the user provides information that is not in the list of allowed values',
526
+ 'G85: Providing a text description when user input falls outside the required format or values',
527
+ 'ARIA21: Using aria-invalid to indicate an error field',
528
+ ],
529
+ failures: ['No specific failures defined'],
530
+ relatedViolations: ['aria-valid-attr-value', 'aria-input-field-name'],
531
+ },
532
+ '3.3.2': {
533
+ id: '3.3.2',
534
+ title: 'Labels or Instructions',
535
+ level: 'A',
536
+ description: 'Labels or instructions are provided when content requires user input.',
537
+ techniques: [
538
+ 'G131: Providing descriptive labels',
539
+ 'H44: Using label elements to associate text labels with form controls',
540
+ 'H71: Providing a description for groups of form controls using fieldset and legend elements',
541
+ 'ARIA1: Using the aria-describedby property to provide a descriptive label for user interface controls',
542
+ 'ARIA9: Using aria-labelledby to concatenate a label from several text nodes',
543
+ ],
544
+ failures: [
545
+ 'F82: Failure due to visually formatting a set of phone number fields but not including a text label',
546
+ ],
547
+ relatedViolations: ['label', 'form-field-multiple-labels', 'select-name'],
548
+ },
549
+ '4.1.1': {
550
+ id: '4.1.1',
551
+ title: 'Parsing',
552
+ level: 'A',
553
+ description: 'In content implemented using markup languages, elements have complete start and end tags, elements are nested according to their specifications, elements do not contain duplicate attributes, and any IDs are unique.',
554
+ techniques: [
555
+ 'G134: Validating Web pages',
556
+ 'G192: Fully conforming to specifications',
557
+ 'H74: Ensuring that opening and closing tags are used according to specification',
558
+ 'H93: Ensuring that id attributes are unique on a Web page',
559
+ 'H94: Ensuring that elements do not contain duplicate attributes',
560
+ ],
561
+ failures: [
562
+ 'F70: Failure due to incorrect use of start and end tags or attribute markup',
563
+ 'F77: Failure due to duplicate values of type ID',
564
+ ],
565
+ relatedViolations: ['duplicate-id', 'duplicate-id-active', 'duplicate-id-aria'],
566
+ },
567
+ '4.1.2': {
568
+ id: '4.1.2',
569
+ title: 'Name, Role, Value',
570
+ level: 'A',
571
+ description: 'For all user interface components, the name and role can be programmatically determined; states, properties, and values that can be set by the user can be programmatically set; and notification of changes to these items is available to user agents, including assistive technologies.',
572
+ techniques: [
573
+ 'G108: Using markup features to expose the name and role',
574
+ 'H64: Using the title attribute of the iframe element',
575
+ 'H91: Using HTML form controls and links',
576
+ 'ARIA4: Using a WAI-ARIA role to expose the role of a user interface component',
577
+ 'ARIA5: Using WAI-ARIA state and property attributes to expose the state of a user interface component',
578
+ 'ARIA14: Using aria-label to provide an accessible name',
579
+ 'ARIA16: Using aria-labelledby to provide a name for user interface controls',
580
+ ],
581
+ failures: [
582
+ 'F15: Failure due to implementing custom controls that do not use an accessibility API',
583
+ 'F20: Failure due to not updating text alternatives when changes occur',
584
+ 'F59: Failure due to using script to make div or span a user interface control without first adding the role',
585
+ 'F68: Failure due to the association of label and user interface controls not being programmatically determined',
586
+ 'F79: Failure due to focus not being set when the state of a radio button, checkbox or select list is changed',
587
+ ],
588
+ relatedViolations: [
589
+ 'aria-allowed-attr',
590
+ 'aria-allowed-role',
591
+ 'aria-required-attr',
592
+ 'aria-required-children',
593
+ 'aria-required-parent',
594
+ 'aria-roles',
595
+ 'button-name',
596
+ 'input-button-name',
597
+ 'role-img-alt',
598
+ ],
599
+ },
600
+ };
601
+ // Mapping from violation IDs to WCAG criteria
602
+ const violationToWcag = {
603
+ 'image-alt': '1.1.1',
604
+ 'input-image-alt': '1.1.1',
605
+ 'area-alt': '1.1.1',
606
+ 'object-alt': '1.1.1',
607
+ 'svg-img-alt': '1.1.1',
608
+ 'heading-order': '1.3.1',
609
+ list: '1.3.1',
610
+ listitem: '1.3.1',
611
+ 'table-fake-caption': '1.3.1',
612
+ 'td-headers-attr': '1.3.1',
613
+ 'th-has-data-cells': '1.3.1',
614
+ 'autocomplete-valid': '1.3.5',
615
+ 'link-in-text-block': '1.4.1',
616
+ 'color-contrast': '1.4.3',
617
+ 'color-contrast-enhanced': '1.4.3',
618
+ 'focus-visible': '1.4.11',
619
+ accesskeys: '2.1.1',
620
+ 'focus-order-semantics': '2.1.1',
621
+ 'scrollable-region-focusable': '2.1.1',
622
+ 'focus-trap': '2.1.2',
623
+ bypass: '2.4.1',
624
+ region: '2.4.1',
625
+ 'landmark-one-main': '2.4.1',
626
+ 'document-title': '2.4.2',
627
+ 'page-has-heading-one': '2.4.2',
628
+ tabindex: '2.4.3',
629
+ 'link-name': '2.4.4',
630
+ 'empty-links': '2.4.4',
631
+ 'empty-heading': '2.4.6',
632
+ label: '2.4.6',
633
+ 'duplicate-id': '4.1.1',
634
+ 'duplicate-id-active': '4.1.1',
635
+ 'duplicate-id-aria': '4.1.1',
636
+ 'aria-allowed-attr': '4.1.2',
637
+ 'aria-allowed-role': '4.1.2',
638
+ 'aria-required-attr': '4.1.2',
639
+ 'aria-required-children': '4.1.2',
640
+ 'aria-required-parent': '4.1.2',
641
+ 'aria-roles': '4.1.2',
642
+ 'button-name': '4.1.2',
643
+ 'input-button-name': '4.1.2',
644
+ 'role-img-alt': '4.1.2',
645
+ 'html-has-lang': '3.1.1',
646
+ 'html-lang-valid': '3.1.1',
647
+ 'html-xml-lang-mismatch': '3.1.1',
648
+ 'valid-lang': '3.1.2',
649
+ 'aria-valid-attr-value': '3.3.1',
650
+ 'aria-input-field-name': '3.3.1',
651
+ 'form-field-multiple-labels': '3.3.2',
652
+ 'select-name': '3.3.2',
653
+ };
654
+ const ariaPatterns = {
655
+ modal: {
656
+ name: 'Modal Dialog',
657
+ description: 'A dialog is a window overlaid on the primary window. Focus is trapped within the dialog until it is dismissed.',
658
+ roles: ['dialog', 'alertdialog'],
659
+ states: ["aria-modal='true'"],
660
+ properties: ['aria-labelledby', 'aria-describedby'],
661
+ keyboardInteractions: [
662
+ {
663
+ key: 'Tab',
664
+ action: 'Move focus to next focusable element inside dialog (wraps to first when at end)',
665
+ },
666
+ {
667
+ key: 'Shift+Tab',
668
+ action: 'Move focus to previous focusable element inside dialog (wraps to last when at start)',
669
+ },
670
+ { key: 'Escape', action: 'Close the dialog' },
671
+ ],
672
+ codeExample: `<div
673
+ role="dialog"
674
+ aria-modal="true"
675
+ aria-labelledby="dialog-title"
676
+ aria-describedby="dialog-description"
677
+ >
678
+ <h2 id="dialog-title">Dialog Title</h2>
679
+ <p id="dialog-description">Dialog description text.</p>
680
+ <button>Action</button>
681
+ <button>Cancel</button>
682
+ </div>
683
+
684
+ // Focus management
685
+ const dialog = document.querySelector('[role="dialog"]');
686
+ const firstFocusable = dialog.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
687
+ firstFocusable.focus();
688
+
689
+ // Trap focus within dialog
690
+ dialog.addEventListener('keydown', (e) => {
691
+ if (e.key === 'Tab') {
692
+ const focusable = dialog.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
693
+ const first = focusable[0];
694
+ const last = focusable[focusable.length - 1];
695
+
696
+ if (e.shiftKey && document.activeElement === first) {
697
+ e.preventDefault();
698
+ last.focus();
699
+ } else if (!e.shiftKey && document.activeElement === last) {
700
+ e.preventDefault();
701
+ first.focus();
702
+ }
703
+ }
704
+ if (e.key === 'Escape') closeDialog();
705
+ });`,
706
+ },
707
+ dialog: {
708
+ name: 'Modal Dialog',
709
+ description: 'A dialog is a window overlaid on the primary window. Focus is trapped within the dialog until it is dismissed.',
710
+ roles: ['dialog', 'alertdialog'],
711
+ states: ["aria-modal='true'"],
712
+ properties: ['aria-labelledby', 'aria-describedby'],
713
+ keyboardInteractions: [
714
+ {
715
+ key: 'Tab',
716
+ action: 'Move focus to next focusable element inside dialog (wraps to first when at end)',
717
+ },
718
+ {
719
+ key: 'Shift+Tab',
720
+ action: 'Move focus to previous focusable element inside dialog (wraps to last when at start)',
721
+ },
722
+ { key: 'Escape', action: 'Close the dialog' },
723
+ ],
724
+ codeExample: `<div
725
+ role="dialog"
726
+ aria-modal="true"
727
+ aria-labelledby="dialog-title"
728
+ aria-describedby="dialog-description"
729
+ >
730
+ <h2 id="dialog-title">Dialog Title</h2>
731
+ <p id="dialog-description">Dialog description text.</p>
732
+ <button>Action</button>
733
+ <button>Cancel</button>
734
+ </div>`,
735
+ },
736
+ tabs: {
737
+ name: 'Tabs',
738
+ description: 'A set of layered sections of content, where one panel is displayed at a time.',
739
+ roles: ['tablist', 'tab', 'tabpanel'],
740
+ states: ["aria-selected='true|false'"],
741
+ properties: ['aria-controls', 'aria-labelledby'],
742
+ keyboardInteractions: [
743
+ { key: 'Tab', action: 'Move focus into the tab list, then to the active tabpanel' },
744
+ { key: 'ArrowLeft/ArrowRight', action: 'Move focus between tabs (horizontal tablist)' },
745
+ { key: 'ArrowUp/ArrowDown', action: 'Move focus between tabs (vertical tablist)' },
746
+ { key: 'Home', action: 'Move focus to first tab' },
747
+ { key: 'End', action: 'Move focus to last tab' },
748
+ { key: 'Space/Enter', action: 'Activate the focused tab (if activation is manual)' },
749
+ ],
750
+ codeExample: `<div role="tablist" aria-label="Entertainment options">
751
+ <button
752
+ role="tab"
753
+ aria-selected="true"
754
+ aria-controls="panel-1"
755
+ id="tab-1"
756
+ tabindex="0"
757
+ >
758
+ Tab 1
759
+ </button>
760
+ <button
761
+ role="tab"
762
+ aria-selected="false"
763
+ aria-controls="panel-2"
764
+ id="tab-2"
765
+ tabindex="-1"
766
+ >
767
+ Tab 2
768
+ </button>
769
+ </div>
770
+
771
+ <div
772
+ role="tabpanel"
773
+ id="panel-1"
774
+ aria-labelledby="tab-1"
775
+ tabindex="0"
776
+ >
777
+ Panel 1 content
778
+ </div>
779
+
780
+ <div
781
+ role="tabpanel"
782
+ id="panel-2"
783
+ aria-labelledby="tab-2"
784
+ tabindex="0"
785
+ hidden
786
+ >
787
+ Panel 2 content
788
+ </div>
789
+
790
+ // Keyboard navigation
791
+ tablist.addEventListener('keydown', (e) => {
792
+ const tabs = Array.from(tablist.querySelectorAll('[role="tab"]'));
793
+ const currentIndex = tabs.indexOf(document.activeElement);
794
+
795
+ if (e.key === 'ArrowRight') {
796
+ const nextIndex = (currentIndex + 1) % tabs.length;
797
+ tabs[nextIndex].focus();
798
+ } else if (e.key === 'ArrowLeft') {
799
+ const prevIndex = (currentIndex - 1 + tabs.length) % tabs.length;
800
+ tabs[prevIndex].focus();
801
+ }
802
+ });`,
803
+ },
804
+ tabpanel: {
805
+ name: 'Tabs',
806
+ description: 'A set of layered sections of content, where one panel is displayed at a time.',
807
+ roles: ['tablist', 'tab', 'tabpanel'],
808
+ states: ["aria-selected='true|false'"],
809
+ properties: ['aria-controls', 'aria-labelledby'],
810
+ keyboardInteractions: [
811
+ { key: 'Tab', action: 'Move focus into the tab list, then to the active tabpanel' },
812
+ { key: 'ArrowLeft/ArrowRight', action: 'Move focus between tabs (horizontal tablist)' },
813
+ { key: 'Home', action: 'Move focus to first tab' },
814
+ { key: 'End', action: 'Move focus to last tab' },
815
+ ],
816
+ codeExample: `See 'tabs' pattern for full implementation.`,
817
+ },
818
+ menu: {
819
+ name: 'Menu',
820
+ description: 'A menu offers a list of choices to the user, such as actions or functions.',
821
+ roles: ['menu', 'menuitem', 'menuitemcheckbox', 'menuitemradio'],
822
+ states: [
823
+ "aria-expanded='true|false'",
824
+ "aria-checked='true|false' (for menuitemcheckbox/radio)",
825
+ ],
826
+ properties: ["aria-haspopup='menu'", 'aria-labelledby'],
827
+ keyboardInteractions: [
828
+ { key: 'Enter/Space', action: 'Activate menu item and close menu' },
829
+ { key: 'ArrowDown', action: 'Move focus to next menu item' },
830
+ { key: 'ArrowUp', action: 'Move focus to previous menu item' },
831
+ { key: 'ArrowRight', action: 'Open submenu (if available) and move focus to first item' },
832
+ { key: 'ArrowLeft', action: 'Close submenu and return focus to parent menu item' },
833
+ { key: 'Escape', action: 'Close the menu' },
834
+ { key: 'Home', action: 'Move focus to first menu item' },
835
+ { key: 'End', action: 'Move focus to last menu item' },
836
+ ],
837
+ codeExample: `<button
838
+ aria-haspopup="menu"
839
+ aria-expanded="false"
840
+ aria-controls="menu-1"
841
+ >
842
+ Menu
843
+ </button>
844
+
845
+ <ul role="menu" id="menu-1" aria-labelledby="menu-button">
846
+ <li role="menuitem" tabindex="-1">Action 1</li>
847
+ <li role="menuitem" tabindex="-1">Action 2</li>
848
+ <li role="menuitem" tabindex="-1">Action 3</li>
849
+ </ul>
850
+
851
+ // Open menu and manage focus
852
+ button.addEventListener('click', () => {
853
+ const expanded = button.getAttribute('aria-expanded') === 'true';
854
+ button.setAttribute('aria-expanded', !expanded);
855
+ if (!expanded) {
856
+ menu.querySelector('[role="menuitem"]').focus();
857
+ }
858
+ });
859
+
860
+ menu.addEventListener('keydown', (e) => {
861
+ const items = Array.from(menu.querySelectorAll('[role="menuitem"]'));
862
+ const currentIndex = items.indexOf(document.activeElement);
863
+
864
+ switch (e.key) {
865
+ case 'ArrowDown':
866
+ e.preventDefault();
867
+ items[(currentIndex + 1) % items.length].focus();
868
+ break;
869
+ case 'ArrowUp':
870
+ e.preventDefault();
871
+ items[(currentIndex - 1 + items.length) % items.length].focus();
872
+ break;
873
+ case 'Escape':
874
+ button.setAttribute('aria-expanded', 'false');
875
+ button.focus();
876
+ break;
877
+ }
878
+ });`,
879
+ },
880
+ menubar: {
881
+ name: 'Menubar',
882
+ description: 'A horizontal menu typically used as a main navigation element.',
883
+ roles: ['menubar', 'menuitem', 'menu'],
884
+ states: ["aria-expanded='true|false'"],
885
+ properties: ["aria-haspopup='menu'", 'aria-labelledby'],
886
+ keyboardInteractions: [
887
+ { key: 'ArrowLeft/ArrowRight', action: 'Move focus between menubar items' },
888
+ { key: 'ArrowDown', action: 'Open submenu and move focus to first item' },
889
+ { key: 'ArrowUp', action: 'Open submenu and move focus to last item' },
890
+ { key: 'Enter/Space', action: 'Open submenu or activate item' },
891
+ { key: 'Escape', action: 'Close submenu' },
892
+ ],
893
+ codeExample: `<nav aria-label="Main">
894
+ <ul role="menubar">
895
+ <li role="none">
896
+ <button
897
+ role="menuitem"
898
+ aria-haspopup="menu"
899
+ aria-expanded="false"
900
+ >
901
+ File
902
+ </button>
903
+ <ul role="menu">
904
+ <li role="menuitem" tabindex="-1">New</li>
905
+ <li role="menuitem" tabindex="-1">Open</li>
906
+ <li role="menuitem" tabindex="-1">Save</li>
907
+ </ul>
908
+ </li>
909
+ <li role="none">
910
+ <button role="menuitem">Edit</button>
911
+ </li>
912
+ </ul>
913
+ </nav>`,
914
+ },
915
+ accordion: {
916
+ name: 'Accordion',
917
+ description: 'Vertically stacked headings that reveal or hide associated content.',
918
+ roles: ['button (for headers)', 'region (optional for panels)'],
919
+ states: ["aria-expanded='true|false'"],
920
+ properties: ['aria-controls', 'aria-labelledby'],
921
+ keyboardInteractions: [
922
+ { key: 'Enter/Space', action: 'Toggle the accordion panel' },
923
+ { key: 'ArrowDown', action: 'Move focus to next accordion header' },
924
+ { key: 'ArrowUp', action: 'Move focus to previous accordion header' },
925
+ { key: 'Home', action: 'Move focus to first accordion header' },
926
+ { key: 'End', action: 'Move focus to last accordion header' },
927
+ ],
928
+ codeExample: `<div class="accordion">
929
+ <h3>
930
+ <button
931
+ aria-expanded="true"
932
+ aria-controls="panel-1"
933
+ id="header-1"
934
+ >
935
+ Section 1
936
+ </button>
937
+ </h3>
938
+ <div
939
+ id="panel-1"
940
+ role="region"
941
+ aria-labelledby="header-1"
942
+ >
943
+ <p>Content for section 1</p>
944
+ </div>
945
+
946
+ <h3>
947
+ <button
948
+ aria-expanded="false"
949
+ aria-controls="panel-2"
950
+ id="header-2"
951
+ >
952
+ Section 2
953
+ </button>
954
+ </h3>
955
+ <div
956
+ id="panel-2"
957
+ role="region"
958
+ aria-labelledby="header-2"
959
+ hidden
960
+ >
961
+ <p>Content for section 2</p>
962
+ </div>
963
+ </div>
964
+
965
+ // Toggle accordion
966
+ button.addEventListener('click', () => {
967
+ const expanded = button.getAttribute('aria-expanded') === 'true';
968
+ button.setAttribute('aria-expanded', !expanded);
969
+ panel.hidden = expanded;
970
+ });`,
971
+ },
972
+ combobox: {
973
+ name: 'Combobox / Autocomplete',
974
+ description: 'A composite widget with a text input and a popup listbox for selecting a value.',
975
+ roles: ['combobox', 'listbox', 'option'],
976
+ states: ["aria-expanded='true|false'", "aria-selected='true|false'", 'aria-activedescendant'],
977
+ properties: [
978
+ 'aria-controls',
979
+ "aria-autocomplete='list|both|inline'",
980
+ "aria-haspopup='listbox'",
981
+ ],
982
+ keyboardInteractions: [
983
+ { key: 'ArrowDown', action: 'Open listbox (if closed) or move focus to next option' },
984
+ { key: 'ArrowUp', action: 'Move focus to previous option' },
985
+ { key: 'Enter', action: 'Select the focused option and close listbox' },
986
+ { key: 'Escape', action: 'Close the listbox without selecting' },
987
+ { key: 'Home', action: 'Move focus to first option' },
988
+ { key: 'End', action: 'Move focus to last option' },
989
+ { key: 'Type characters', action: 'Filter options or jump to matching option' },
990
+ ],
991
+ codeExample: `<div class="combobox-wrapper">
992
+ <label id="label" for="combobox">Choose a fruit:</label>
993
+ <input
994
+ type="text"
995
+ id="combobox"
996
+ role="combobox"
997
+ aria-controls="listbox"
998
+ aria-expanded="false"
999
+ aria-haspopup="listbox"
1000
+ aria-autocomplete="list"
1001
+ aria-activedescendant=""
1002
+ />
1003
+ <ul
1004
+ role="listbox"
1005
+ id="listbox"
1006
+ aria-labelledby="label"
1007
+ hidden
1008
+ >
1009
+ <li role="option" id="opt-1">Apple</li>
1010
+ <li role="option" id="opt-2">Banana</li>
1011
+ <li role="option" id="opt-3">Cherry</li>
1012
+ </ul>
1013
+ </div>
1014
+
1015
+ // Manage active descendant
1016
+ input.addEventListener('keydown', (e) => {
1017
+ if (e.key === 'ArrowDown') {
1018
+ e.preventDefault();
1019
+ listbox.hidden = false;
1020
+ input.setAttribute('aria-expanded', 'true');
1021
+ // Update aria-activedescendant to next option
1022
+ const currentId = input.getAttribute('aria-activedescendant');
1023
+ const options = Array.from(listbox.querySelectorAll('[role="option"]'));
1024
+ const currentIndex = options.findIndex(o => o.id === currentId);
1025
+ const nextOption = options[(currentIndex + 1) % options.length];
1026
+ input.setAttribute('aria-activedescendant', nextOption.id);
1027
+ }
1028
+ if (e.key === 'Enter') {
1029
+ const activeId = input.getAttribute('aria-activedescendant');
1030
+ const activeOption = document.getElementById(activeId);
1031
+ input.value = activeOption.textContent;
1032
+ listbox.hidden = true;
1033
+ input.setAttribute('aria-expanded', 'false');
1034
+ }
1035
+ if (e.key === 'Escape') {
1036
+ listbox.hidden = true;
1037
+ input.setAttribute('aria-expanded', 'false');
1038
+ }
1039
+ });`,
1040
+ },
1041
+ autocomplete: {
1042
+ name: 'Combobox / Autocomplete',
1043
+ description: 'A composite widget with a text input and a popup listbox for selecting a value.',
1044
+ roles: ['combobox', 'listbox', 'option'],
1045
+ states: ["aria-expanded='true|false'", "aria-selected='true|false'", 'aria-activedescendant'],
1046
+ properties: [
1047
+ 'aria-controls',
1048
+ "aria-autocomplete='list|both|inline'",
1049
+ "aria-haspopup='listbox'",
1050
+ ],
1051
+ keyboardInteractions: [
1052
+ { key: 'ArrowDown', action: 'Open listbox or move focus to next option' },
1053
+ { key: 'ArrowUp', action: 'Move focus to previous option' },
1054
+ { key: 'Enter', action: 'Select the focused option' },
1055
+ { key: 'Escape', action: 'Close the listbox' },
1056
+ ],
1057
+ codeExample: `See 'combobox' pattern for full implementation.`,
1058
+ },
1059
+ tooltip: {
1060
+ name: 'Tooltip',
1061
+ description: 'A popup displaying a description for an element when the element receives keyboard focus or hover.',
1062
+ roles: ['tooltip'],
1063
+ states: [],
1064
+ properties: ['aria-describedby'],
1065
+ keyboardInteractions: [
1066
+ { key: 'Escape', action: 'Dismiss the tooltip' },
1067
+ { key: 'Focus/Blur', action: 'Show/hide tooltip on keyboard focus' },
1068
+ ],
1069
+ codeExample: `<button aria-describedby="tooltip-1">
1070
+ Save
1071
+ </button>
1072
+ <div role="tooltip" id="tooltip-1" hidden>
1073
+ Save your changes (Ctrl+S)
1074
+ </div>
1075
+
1076
+ // Show tooltip on focus/hover
1077
+ button.addEventListener('focus', () => {
1078
+ tooltip.hidden = false;
1079
+ });
1080
+ button.addEventListener('blur', () => {
1081
+ tooltip.hidden = true;
1082
+ });
1083
+ button.addEventListener('mouseenter', () => {
1084
+ tooltip.hidden = false;
1085
+ });
1086
+ button.addEventListener('mouseleave', () => {
1087
+ tooltip.hidden = true;
1088
+ });
1089
+
1090
+ // Hide on Escape
1091
+ button.addEventListener('keydown', (e) => {
1092
+ if (e.key === 'Escape') {
1093
+ tooltip.hidden = true;
1094
+ }
1095
+ });
1096
+
1097
+ /* CSS for positioning */
1098
+ [role="tooltip"] {
1099
+ position: absolute;
1100
+ background: #333;
1101
+ color: white;
1102
+ padding: 4px 8px;
1103
+ border-radius: 4px;
1104
+ font-size: 14px;
1105
+ }`,
1106
+ },
1107
+ alert: {
1108
+ name: 'Alert',
1109
+ description: 'A live region containing important, time-sensitive information. Alerts are assertive and announced immediately.',
1110
+ roles: ['alert', 'alertdialog', 'status'],
1111
+ states: [],
1112
+ properties: ["aria-live='assertive'", "aria-atomic='true'"],
1113
+ keyboardInteractions: [
1114
+ {
1115
+ key: 'None required',
1116
+ action: 'Alerts do not require keyboard interaction - they are announced automatically',
1117
+ },
1118
+ ],
1119
+ codeExample: `<!-- Simple alert (auto-announced) -->
1120
+ <div role="alert">
1121
+ Your session will expire in 5 minutes.
1122
+ </div>
1123
+
1124
+ <!-- Alert with live region (for dynamic content) -->
1125
+ <div
1126
+ role="alert"
1127
+ aria-live="assertive"
1128
+ aria-atomic="true"
1129
+ >
1130
+ Error: Please enter a valid email address.
1131
+ </div>
1132
+
1133
+ <!-- Status message (polite, less urgent) -->
1134
+ <div role="status" aria-live="polite">
1135
+ File uploaded successfully.
1136
+ </div>
1137
+
1138
+ // Dynamically add alert
1139
+ function showAlert(message) {
1140
+ const alert = document.createElement('div');
1141
+ alert.setAttribute('role', 'alert');
1142
+ alert.textContent = message;
1143
+ document.body.appendChild(alert);
1144
+
1145
+ // Remove after announcement
1146
+ setTimeout(() => alert.remove(), 5000);
1147
+ }`,
1148
+ },
1149
+ tree: {
1150
+ name: 'Tree View',
1151
+ description: 'A hierarchical list that allows users to expand and collapse nested groups of items.',
1152
+ roles: ['tree', 'treeitem', 'group'],
1153
+ states: ["aria-expanded='true|false'", "aria-selected='true|false'"],
1154
+ properties: ['aria-level', 'aria-setsize', 'aria-posinset', 'aria-owns'],
1155
+ keyboardInteractions: [
1156
+ { key: 'ArrowDown', action: 'Move focus to next visible treeitem' },
1157
+ { key: 'ArrowUp', action: 'Move focus to previous visible treeitem' },
1158
+ { key: 'ArrowRight', action: 'Expand node (if collapsed) or move to first child' },
1159
+ { key: 'ArrowLeft', action: 'Collapse node (if expanded) or move to parent' },
1160
+ { key: 'Enter', action: 'Activate the focused treeitem' },
1161
+ { key: 'Home', action: 'Move focus to first treeitem' },
1162
+ { key: 'End', action: 'Move focus to last visible treeitem' },
1163
+ { key: '* (asterisk)', action: 'Expand all siblings at the current level' },
1164
+ ],
1165
+ codeExample: `<ul role="tree" aria-label="File browser">
1166
+ <li
1167
+ role="treeitem"
1168
+ aria-expanded="true"
1169
+ aria-level="1"
1170
+ aria-setsize="2"
1171
+ aria-posinset="1"
1172
+ tabindex="0"
1173
+ >
1174
+ Documents
1175
+ <ul role="group">
1176
+ <li
1177
+ role="treeitem"
1178
+ aria-level="2"
1179
+ aria-setsize="2"
1180
+ aria-posinset="1"
1181
+ tabindex="-1"
1182
+ >
1183
+ report.pdf
1184
+ </li>
1185
+ <li
1186
+ role="treeitem"
1187
+ aria-level="2"
1188
+ aria-setsize="2"
1189
+ aria-posinset="2"
1190
+ tabindex="-1"
1191
+ >
1192
+ notes.txt
1193
+ </li>
1194
+ </ul>
1195
+ </li>
1196
+ <li
1197
+ role="treeitem"
1198
+ aria-expanded="false"
1199
+ aria-level="1"
1200
+ aria-setsize="2"
1201
+ aria-posinset="2"
1202
+ tabindex="-1"
1203
+ >
1204
+ Images
1205
+ <ul role="group" hidden>
1206
+ <li role="treeitem" aria-level="2" tabindex="-1">photo.jpg</li>
1207
+ </ul>
1208
+ </li>
1209
+ </ul>
1210
+
1211
+ // Keyboard navigation
1212
+ tree.addEventListener('keydown', (e) => {
1213
+ const current = document.activeElement;
1214
+ const items = Array.from(tree.querySelectorAll('[role="treeitem"]:not([hidden])'));
1215
+ const index = items.indexOf(current);
1216
+
1217
+ switch (e.key) {
1218
+ case 'ArrowDown':
1219
+ e.preventDefault();
1220
+ if (index < items.length - 1) items[index + 1].focus();
1221
+ break;
1222
+ case 'ArrowUp':
1223
+ e.preventDefault();
1224
+ if (index > 0) items[index - 1].focus();
1225
+ break;
1226
+ case 'ArrowRight':
1227
+ if (current.getAttribute('aria-expanded') === 'false') {
1228
+ current.setAttribute('aria-expanded', 'true');
1229
+ current.querySelector('[role="group"]').hidden = false;
1230
+ }
1231
+ break;
1232
+ case 'ArrowLeft':
1233
+ if (current.getAttribute('aria-expanded') === 'true') {
1234
+ current.setAttribute('aria-expanded', 'false');
1235
+ current.querySelector('[role="group"]').hidden = true;
1236
+ }
1237
+ break;
1238
+ }
1239
+ });`,
1240
+ },
1241
+ treeitem: {
1242
+ name: 'Tree View',
1243
+ description: 'A hierarchical list that allows users to expand and collapse nested groups of items.',
1244
+ roles: ['tree', 'treeitem', 'group'],
1245
+ states: ["aria-expanded='true|false'", "aria-selected='true|false'"],
1246
+ properties: ['aria-level', 'aria-setsize', 'aria-posinset'],
1247
+ keyboardInteractions: [
1248
+ { key: 'ArrowDown', action: 'Move focus to next visible treeitem' },
1249
+ { key: 'ArrowUp', action: 'Move focus to previous visible treeitem' },
1250
+ { key: 'ArrowRight', action: 'Expand node or move to first child' },
1251
+ { key: 'ArrowLeft', action: 'Collapse node or move to parent' },
1252
+ ],
1253
+ codeExample: `See 'tree' pattern for full implementation.`,
1254
+ },
1255
+ };
1256
+ // Tool: Get WCAG success criterion details
1257
+ server.tool('get_wcag_guideline', 'Get full WCAG success criterion details for a violation', {
1258
+ criterionId: z
1259
+ .string()
1260
+ .describe("WCAG criterion like '1.1.1' or violation id like 'image-alt'"),
1261
+ }, async ({ criterionId }) => {
1262
+ telemetry.log('get_wcag_guideline');
1263
+ try {
1264
+ // Check if it's a violation ID first
1265
+ let wcagId = criterionId;
1266
+ if (violationToWcag[criterionId]) {
1267
+ wcagId = violationToWcag[criterionId];
1268
+ }
1269
+ // Look up the criterion
1270
+ const criterion = wcagCriteria[wcagId];
1271
+ if (!criterion) {
1272
+ // Try to find partial matches
1273
+ const matches = Object.keys(wcagCriteria).filter((k) => k.includes(criterionId));
1274
+ if (matches.length > 0) {
1275
+ return {
1276
+ content: [
1277
+ {
1278
+ type: 'text',
1279
+ text: `No exact match for "${criterionId}". Did you mean one of these?\n${matches.map((m) => `- ${m}: ${wcagCriteria[m].title}`).join('\n')}`,
1280
+ },
1281
+ ],
1282
+ };
1283
+ }
1284
+ return {
1285
+ content: [
1286
+ {
1287
+ type: 'text',
1288
+ text: `WCAG criterion "${criterionId}" not found. Try a criterion ID like "1.1.1" or a violation ID like "image-alt".`,
1289
+ },
1290
+ ],
1291
+ };
1292
+ }
1293
+ const response = `# WCAG ${criterion.id}: ${criterion.title}
1294
+
1295
+ **Level:** ${criterion.level}
1296
+
1297
+ ## Description
1298
+ ${criterion.description}
1299
+
1300
+ ## Techniques
1301
+ ${criterion.techniques.map((t) => `- ${t}`).join('\n')}
1302
+
1303
+ ## Common Failures
1304
+ ${criterion.failures.map((f) => `- ${f}`).join('\n')}
1305
+
1306
+ ## Related Violations
1307
+ ${criterion.relatedViolations.map((v) => `- ${v}`).join('\n')}`;
1308
+ return {
1309
+ content: [
1310
+ {
1311
+ type: 'text',
1312
+ text: response,
1313
+ },
1314
+ ],
1315
+ };
1316
+ }
1317
+ catch (error) {
1318
+ return {
1319
+ content: [
1320
+ {
1321
+ type: 'text',
1322
+ text: `Error looking up WCAG criterion: ${error instanceof Error ? error.message : String(error)}`,
1323
+ },
1324
+ ],
1325
+ isError: true,
1326
+ };
1327
+ }
1328
+ });
1329
+ // Tool: Suggest ARIA pattern for a component type
1330
+ server.tool('suggest_aria_pattern', 'Suggest ARIA pattern for a component type', {
1331
+ componentType: z.string().describe("e.g., 'modal', 'tabs', 'menu', 'accordion'"),
1332
+ }, async ({ componentType }) => {
1333
+ telemetry.log('suggest_aria_pattern');
1334
+ try {
1335
+ // Normalize the component type
1336
+ const normalizedType = componentType.toLowerCase().trim();
1337
+ // Look up the pattern
1338
+ const pattern = ariaPatterns[normalizedType];
1339
+ if (!pattern) {
1340
+ // Try to find partial matches
1341
+ const matches = Object.keys(ariaPatterns).filter((k) => k.includes(normalizedType) || normalizedType.includes(k));
1342
+ if (matches.length > 0) {
1343
+ return {
1344
+ content: [
1345
+ {
1346
+ type: 'text',
1347
+ text: `No exact match for "${componentType}". Did you mean one of these?\n${matches.map((m) => `- ${m}: ${ariaPatterns[m].name}`).join('\n')}\n\nAvailable patterns: ${Object.keys(ariaPatterns).join(', ')}`,
1348
+ },
1349
+ ],
1350
+ };
1351
+ }
1352
+ return {
1353
+ content: [
1354
+ {
1355
+ type: 'text',
1356
+ text: `ARIA pattern for "${componentType}" not found.\n\nAvailable patterns: ${Object.keys(ariaPatterns).join(', ')}`,
1357
+ },
1358
+ ],
1359
+ };
1360
+ }
1361
+ const response = `# ${pattern.name}
1362
+
1363
+ ## Description
1364
+ ${pattern.description}
1365
+
1366
+ ## ARIA Roles
1367
+ ${pattern.roles.map((r) => `- \`${r}\``).join('\n')}
1368
+
1369
+ ## States
1370
+ ${pattern.states.length > 0 ? pattern.states.map((s) => `- \`${s}\``).join('\n') : '- None required'}
1371
+
1372
+ ## Properties
1373
+ ${pattern.properties.length > 0 ? pattern.properties.map((p) => `- \`${p}\``).join('\n') : '- None required'}
1374
+
1375
+ ## Keyboard Interactions
1376
+ | Key | Action |
1377
+ |-----|--------|
1378
+ ${pattern.keyboardInteractions.map((k) => `| ${k.key} | ${k.action} |`).join('\n')}
1379
+
1380
+ ## Code Example
1381
+ \`\`\`html
1382
+ ${pattern.codeExample}
1383
+ \`\`\``;
1384
+ return {
1385
+ content: [
1386
+ {
1387
+ type: 'text',
1388
+ text: response,
1389
+ },
1390
+ ],
1391
+ };
1392
+ }
1393
+ catch (error) {
1394
+ return {
1395
+ content: [
1396
+ {
1397
+ type: 'text',
1398
+ text: `Error looking up ARIA pattern: ${error instanceof Error ? error.message : String(error)}`,
1399
+ },
1400
+ ],
1401
+ isError: true,
1402
+ };
1403
+ }
1404
+ });
1405
+ // Tool: Check color contrast
1406
+ server.tool('check_color_contrast', 'Calculate WCAG contrast ratio and APCA Lc value between two colors and check compliance', {
1407
+ foreground: z.string().describe('Foreground color (hex, rgb, or named)'),
1408
+ background: z.string().describe('Background color (hex, rgb, or named)'),
1409
+ fontSize: z
1410
+ .number()
1411
+ .optional()
1412
+ .describe('Font size in pixels (optional, for AA/AAA thresholds)'),
1413
+ isBold: z.boolean().optional().describe('Whether text is bold (optional)'),
1414
+ }, async ({ foreground, background, fontSize, isBold }) => {
1415
+ telemetry.log('check_color_contrast');
1416
+ try {
1417
+ // Parse colors
1418
+ const fgColor = parseColor(foreground);
1419
+ const bgColor = parseColor(background);
1420
+ if (!fgColor) {
1421
+ return {
1422
+ content: [
1423
+ {
1424
+ type: 'text',
1425
+ text: `Unable to parse foreground color: "${foreground}". Supported formats: hex (#RGB, #RRGGBB), rgb(r, g, b), or named colors (e.g., "red", "blue").`,
1426
+ },
1427
+ ],
1428
+ isError: true,
1429
+ };
1430
+ }
1431
+ if (!bgColor) {
1432
+ return {
1433
+ content: [
1434
+ {
1435
+ type: 'text',
1436
+ text: `Unable to parse background color: "${background}". Supported formats: hex (#RGB, #RRGGBB), rgb(r, g, b), or named colors (e.g., "red", "blue").`,
1437
+ },
1438
+ ],
1439
+ isError: true,
1440
+ };
1441
+ }
1442
+ // Calculate WCAG 2.x contrast ratio
1443
+ const contrastRatio = calculateContrastRatio(fgColor, bgColor);
1444
+ const roundedRatio = Math.round(contrastRatio * 100) / 100;
1445
+ // Calculate APCA Lc value (Advanced Perceptual Contrast Algorithm)
1446
+ const fgArray = [fgColor.r, fgColor.g, fgColor.b];
1447
+ const bgArray = [bgColor.r, bgColor.g, bgColor.b];
1448
+ const apcaLc = APCAcontrast(sRGBtoY(fgArray), sRGBtoY(bgArray));
1449
+ const roundedLc = Math.round(apcaLc * 10) / 10;
1450
+ const absLc = Math.abs(roundedLc);
1451
+ // APCA thresholds (based on WCAG 3.0 draft guidelines)
1452
+ // Lc 90+ : Preferred for body text
1453
+ // Lc 75+ : Minimum for body text
1454
+ // Lc 60+ : Large text and headlines
1455
+ // Lc 45+ : Non-text elements, graphics
1456
+ const apcaCompliance = {
1457
+ bodyTextPreferred: absLc >= 90,
1458
+ bodyTextMinimum: absLc >= 75,
1459
+ largeText: absLc >= 60,
1460
+ nonText: absLc >= 45,
1461
+ };
1462
+ // Determine if text is large
1463
+ const largeText = isLargeText(fontSize, isBold);
1464
+ // WCAG 2.x thresholds
1465
+ // AA: 4.5:1 for normal text, 3:1 for large text
1466
+ // AAA: 7:1 for normal text, 4.5:1 for large text
1467
+ const wcagAA = {
1468
+ normalText: contrastRatio >= 4.5,
1469
+ largeText: contrastRatio >= 3,
1470
+ };
1471
+ const wcagAAA = {
1472
+ normalText: contrastRatio >= 7,
1473
+ largeText: contrastRatio >= 4.5,
1474
+ };
1475
+ // Generate recommendation
1476
+ let recommendation = '';
1477
+ const passesAA = largeText ? wcagAA.largeText : wcagAA.normalText;
1478
+ const passesAAA = largeText ? wcagAAA.largeText : wcagAAA.normalText;
1479
+ if (passesAAA) {
1480
+ recommendation =
1481
+ 'Excellent! This color combination meets WCAG AAA standards for all text sizes.';
1482
+ }
1483
+ else if (passesAA) {
1484
+ recommendation = 'Good. This color combination meets WCAG AA standards.';
1485
+ if (!wcagAAA.largeText) {
1486
+ recommendation += ' To achieve AAA compliance, increase contrast to at least 7:1.';
1487
+ }
1488
+ }
1489
+ else if (wcagAA.largeText) {
1490
+ recommendation = `This combination only passes for large text (18pt+ or 14pt+ bold). For normal text, increase contrast to at least 4.5:1. Current ratio: ${roundedRatio}:1.`;
1491
+ }
1492
+ else {
1493
+ const requiredRatio = largeText ? 3 : 4.5;
1494
+ recommendation = `Insufficient contrast (${roundedRatio}:1). Minimum required: ${requiredRatio}:1 for ${largeText ? 'large' : 'normal'} text. Consider:\n`;
1495
+ recommendation += '- Darkening the foreground color\n';
1496
+ recommendation += '- Lightening the background color\n';
1497
+ recommendation += '- Choosing colors with greater luminance difference';
1498
+ }
1499
+ // Build result object
1500
+ const result = {
1501
+ contrastRatio: roundedRatio,
1502
+ apcaLc: roundedLc,
1503
+ wcagAA,
1504
+ wcagAAA,
1505
+ apcaCompliance,
1506
+ recommendation,
1507
+ };
1508
+ // Format response
1509
+ const passStatus = passesAA
1510
+ ? passesAAA
1511
+ ? 'PASS (AAA)'
1512
+ : 'PASS (AA)'
1513
+ : wcagAA.largeText
1514
+ ? 'PARTIAL (large text only)'
1515
+ : 'FAIL';
1516
+ // APCA status string
1517
+ let apcaStatus = '';
1518
+ if (apcaCompliance.bodyTextPreferred) {
1519
+ apcaStatus = 'Preferred for body text';
1520
+ }
1521
+ else if (apcaCompliance.bodyTextMinimum) {
1522
+ apcaStatus = 'Minimum for body text';
1523
+ }
1524
+ else if (apcaCompliance.largeText) {
1525
+ apcaStatus = 'Large text/headlines only';
1526
+ }
1527
+ else if (apcaCompliance.nonText) {
1528
+ apcaStatus = 'Non-text elements only';
1529
+ }
1530
+ else {
1531
+ apcaStatus = 'Insufficient';
1532
+ }
1533
+ const response = `# Color Contrast Check
1534
+
1535
+ **Foreground:** ${foreground} → rgb(${fgColor.r}, ${fgColor.g}, ${fgColor.b})
1536
+ **Background:** ${background} → rgb(${bgColor.r}, ${bgColor.g}, ${bgColor.b})
1537
+ ${fontSize ? `**Text size:** ${fontSize}px${isBold ? ' (bold)' : ''}` : ''}
1538
+
1539
+ ## Result: ${passStatus}
1540
+
1541
+ **WCAG 2.x Contrast Ratio:** ${roundedRatio}:1
1542
+ **APCA Lc Value:** ${roundedLc} (${apcaStatus})
1543
+
1544
+ ### WCAG 2.x Compliance
1545
+ | Level | Normal Text (< 18pt) | Large Text (≥ 18pt) |
1546
+ |-------|---------------------|---------------------|
1547
+ | AA | ${wcagAA.normalText ? '✓ Pass (≥ 4.5:1)' : '✗ Fail (< 4.5:1)'} | ${wcagAA.largeText ? '✓ Pass (≥ 3:1)' : '✗ Fail (< 3:1)'} |
1548
+ | AAA | ${wcagAAA.normalText ? '✓ Pass (≥ 7:1)' : '✗ Fail (< 7:1)'} | ${wcagAAA.largeText ? '✓ Pass (≥ 4.5:1)' : '✗ Fail (< 4.5:1)'} |
1549
+
1550
+ ### APCA Compliance (Experimental - WCAG 3.0 Draft)
1551
+ | Use Case | Threshold | Status |
1552
+ |----------|-----------|--------|
1553
+ | Body text (preferred) | Lc ≥ 90 | ${apcaCompliance.bodyTextPreferred ? '✓ Pass' : '✗ Fail'} |
1554
+ | Body text (minimum) | Lc ≥ 75 | ${apcaCompliance.bodyTextMinimum ? '✓ Pass' : '✗ Fail'} |
1555
+ | Large text/headlines | Lc ≥ 60 | ${apcaCompliance.largeText ? '✓ Pass' : '✗ Fail'} |
1556
+ | Non-text elements | Lc ≥ 45 | ${apcaCompliance.nonText ? '✓ Pass' : '✗ Fail'} |
1557
+
1558
+ *Note: APCA uses signed values. Negative Lc indicates light text on dark background.*
1559
+
1560
+ ## Recommendation
1561
+ ${recommendation}
1562
+
1563
+ ---
1564
+ *Data (JSON):*
1565
+ \`\`\`json
1566
+ ${JSON.stringify(result, null, 2)}
1567
+ \`\`\``;
1568
+ return {
1569
+ content: [
1570
+ {
1571
+ type: 'text',
1572
+ text: response,
1573
+ },
1574
+ ],
1575
+ };
1576
+ }
1577
+ catch (error) {
1578
+ return {
1579
+ content: [
1580
+ {
1581
+ type: 'text',
1582
+ text: `Error checking color contrast: ${error instanceof Error ? error.message : String(error)}`,
1583
+ },
1584
+ ],
1585
+ isError: true,
1586
+ };
1587
+ }
1588
+ });
1589
+ // Helper: Analyze component patterns
1590
+ async function analyzeComponentPatterns(directory, componentFilter) {
1591
+ const patterns = [];
1592
+ const extensions = ['.jsx', '.tsx', '.vue', '.svelte'];
1593
+ async function scanDir(dir) {
1594
+ try {
1595
+ const entries = await readdir(dir, { withFileTypes: true });
1596
+ for (const entry of entries) {
1597
+ const fullPath = join(dir, entry.name);
1598
+ if (entry.isDirectory()) {
1599
+ if (!entry.name.startsWith('.') &&
1600
+ entry.name !== 'node_modules' &&
1601
+ entry.name !== 'dist') {
1602
+ await scanDir(fullPath);
1603
+ }
1604
+ }
1605
+ else if (extensions.includes(extname(entry.name))) {
1606
+ if (componentFilter &&
1607
+ !entry.name.toLowerCase().includes(componentFilter.toLowerCase())) {
1608
+ continue;
1609
+ }
1610
+ try {
1611
+ const content = await readFile(fullPath, 'utf-8');
1612
+ const pattern = analyzeComponent(entry.name, fullPath, content);
1613
+ if (pattern) {
1614
+ patterns.push(pattern);
1615
+ }
1616
+ }
1617
+ catch {
1618
+ // Skip files that can't be read
1619
+ }
1620
+ }
1621
+ }
1622
+ }
1623
+ catch {
1624
+ // Skip directories that can't be read
1625
+ }
1626
+ }
1627
+ await scanDir(directory);
1628
+ return patterns;
1629
+ }
1630
+ function analyzeComponent(name, file, content) {
1631
+ const hasAriaLabel = /aria-label/i.test(content);
1632
+ const hasAriaDescribedBy = /aria-describedby/i.test(content);
1633
+ const hasRole = /role=["']/i.test(content);
1634
+ const hasFocusManagement = /focus\(\)|useRef|tabIndex|onFocus|onBlur/i.test(content);
1635
+ const hasKeyboardHandlers = /onKeyDown|onKeyUp|onKeyPress|@keydown|@keyup/i.test(content);
1636
+ // Extract examples of ARIA usage
1637
+ const examples = [];
1638
+ const ariaLabelMatches = content.match(/aria-label=["'][^"']+["']/gi);
1639
+ if (ariaLabelMatches) {
1640
+ examples.push(...ariaLabelMatches.slice(0, 3));
1641
+ }
1642
+ const roleMatches = content.match(/role=["'][^"']+["']/gi);
1643
+ if (roleMatches) {
1644
+ examples.push(...roleMatches.slice(0, 3));
1645
+ }
1646
+ return {
1647
+ component: name.replace(/\.(jsx|tsx|vue|svelte)$/, ''),
1648
+ file,
1649
+ patterns: {
1650
+ hasAriaLabel,
1651
+ hasAriaDescribedBy,
1652
+ hasRole,
1653
+ hasFocusManagement,
1654
+ hasKeyboardHandlers,
1655
+ },
1656
+ examples,
1657
+ };
1658
+ }
1659
+ // Helper: Extract design tokens
1660
+ async function extractDesignTokens(directory) {
1661
+ const tokens = {
1662
+ colors: [],
1663
+ spacing: [],
1664
+ typography: [],
1665
+ };
1666
+ // Look for common token files
1667
+ const tokenFiles = [
1668
+ 'tailwind.config.js',
1669
+ 'tailwind.config.ts',
1670
+ 'theme.js',
1671
+ 'theme.ts',
1672
+ 'tokens.js',
1673
+ 'tokens.ts',
1674
+ 'variables.css',
1675
+ 'tokens.css',
1676
+ '_variables.scss',
1677
+ 'design-tokens.json',
1678
+ ];
1679
+ for (const filename of tokenFiles) {
1680
+ const filePath = join(directory, filename);
1681
+ if (existsSync(filePath)) {
1682
+ try {
1683
+ const content = await readFile(filePath, 'utf-8');
1684
+ extractTokensFromContent(content, filename, tokens);
1685
+ }
1686
+ catch {
1687
+ // Skip files that can't be read
1688
+ }
1689
+ }
1690
+ }
1691
+ // Also check src directory
1692
+ const srcPath = join(directory, 'src');
1693
+ if (existsSync(srcPath)) {
1694
+ for (const filename of tokenFiles) {
1695
+ const filePath = join(srcPath, filename);
1696
+ if (existsSync(filePath)) {
1697
+ try {
1698
+ const content = await readFile(filePath, 'utf-8');
1699
+ extractTokensFromContent(content, filename, tokens);
1700
+ }
1701
+ catch {
1702
+ // Skip files that can't be read
1703
+ }
1704
+ }
1705
+ }
1706
+ }
1707
+ return tokens;
1708
+ }
1709
+ function extractTokensFromContent(content, filename, tokens) {
1710
+ // Extract CSS custom properties
1711
+ const cssVarMatches = content.matchAll(/--([a-zA-Z0-9-]+):\s*([^;]+);/g);
1712
+ for (const match of cssVarMatches) {
1713
+ const name = match[1];
1714
+ const value = match[2].trim();
1715
+ if (name.includes('color') ||
1716
+ value.startsWith('#') ||
1717
+ value.startsWith('rgb') ||
1718
+ value.startsWith('hsl')) {
1719
+ tokens.colors.push({ name: `--${name}`, value });
1720
+ }
1721
+ else if (name.includes('space') ||
1722
+ name.includes('gap') ||
1723
+ name.includes('margin') ||
1724
+ name.includes('padding')) {
1725
+ tokens.spacing.push(`--${name}: ${value}`);
1726
+ }
1727
+ }
1728
+ // Extract Tailwind colors
1729
+ const tailwindColorMatches = content.matchAll(/'([a-zA-Z]+)':\s*['"]?(#[a-fA-F0-9]{3,8})['"]?/g);
1730
+ for (const match of tailwindColorMatches) {
1731
+ tokens.colors.push({ name: match[1], value: match[2] });
1732
+ }
1733
+ // Calculate contrast ratios (simplified - assuming white background)
1734
+ tokens.colors = tokens.colors.map((color) => {
1735
+ const ratio = estimateContrastRatio(color.value);
1736
+ return {
1737
+ ...color,
1738
+ contrastRatio: ratio,
1739
+ wcagAACompliant: ratio >= 4.5,
1740
+ wcagAAACompliant: ratio >= 7,
1741
+ };
1742
+ });
1743
+ }
1744
+ /**
1745
+ * Named CSS colors to hex mapping
1746
+ */
1747
+ const namedColors = {
1748
+ black: '#000000',
1749
+ white: '#ffffff',
1750
+ red: '#ff0000',
1751
+ green: '#008000',
1752
+ blue: '#0000ff',
1753
+ yellow: '#ffff00',
1754
+ cyan: '#00ffff',
1755
+ magenta: '#ff00ff',
1756
+ gray: '#808080',
1757
+ grey: '#808080',
1758
+ silver: '#c0c0c0',
1759
+ maroon: '#800000',
1760
+ olive: '#808000',
1761
+ lime: '#00ff00',
1762
+ aqua: '#00ffff',
1763
+ teal: '#008080',
1764
+ navy: '#000080',
1765
+ fuchsia: '#ff00ff',
1766
+ purple: '#800080',
1767
+ orange: '#ffa500',
1768
+ pink: '#ffc0cb',
1769
+ brown: '#a52a2a',
1770
+ coral: '#ff7f50',
1771
+ crimson: '#dc143c',
1772
+ darkblue: '#00008b',
1773
+ darkgray: '#a9a9a9',
1774
+ darkgreen: '#006400',
1775
+ darkred: '#8b0000',
1776
+ gold: '#ffd700',
1777
+ indigo: '#4b0082',
1778
+ ivory: '#fffff0',
1779
+ khaki: '#f0e68c',
1780
+ lavender: '#e6e6fa',
1781
+ lightblue: '#add8e6',
1782
+ lightgray: '#d3d3d3',
1783
+ lightgreen: '#90ee90',
1784
+ lightyellow: '#ffffe0',
1785
+ midnightblue: '#191970',
1786
+ mintcream: '#f5fffa',
1787
+ mistyrose: '#ffe4e1',
1788
+ moccasin: '#ffe4b5',
1789
+ navajowhite: '#ffdead',
1790
+ oldlace: '#fdf5e6',
1791
+ olivedrab: '#6b8e23',
1792
+ orangered: '#ff4500',
1793
+ orchid: '#da70d6',
1794
+ palegoldenrod: '#eee8aa',
1795
+ palegreen: '#98fb98',
1796
+ paleturquoise: '#afeeee',
1797
+ palevioletred: '#db7093',
1798
+ papayawhip: '#ffefd5',
1799
+ peachpuff: '#ffdab9',
1800
+ peru: '#cd853f',
1801
+ plum: '#dda0dd',
1802
+ powderblue: '#b0e0e6',
1803
+ rosybrown: '#bc8f8f',
1804
+ royalblue: '#4169e1',
1805
+ saddlebrown: '#8b4513',
1806
+ salmon: '#fa8072',
1807
+ sandybrown: '#f4a460',
1808
+ seagreen: '#2e8b57',
1809
+ seashell: '#fff5ee',
1810
+ sienna: '#a0522d',
1811
+ skyblue: '#87ceeb',
1812
+ slateblue: '#6a5acd',
1813
+ slategray: '#708090',
1814
+ snow: '#fffafa',
1815
+ springgreen: '#00ff7f',
1816
+ steelblue: '#4682b4',
1817
+ tan: '#d2b48c',
1818
+ thistle: '#d8bfd8',
1819
+ tomato: '#ff6347',
1820
+ turquoise: '#40e0d0',
1821
+ violet: '#ee82ee',
1822
+ wheat: '#f5deb3',
1823
+ whitesmoke: '#f5f5f5',
1824
+ yellowgreen: '#9acd32',
1825
+ rebeccapurple: '#663399',
1826
+ transparent: '#00000000',
1827
+ };
1828
+ /**
1829
+ * Parse a color string (hex, rgb, or named) to RGB values
1830
+ */
1831
+ function parseColor(color) {
1832
+ const trimmed = color.trim().toLowerCase();
1833
+ // Check named colors
1834
+ if (namedColors[trimmed]) {
1835
+ return parseColor(namedColors[trimmed]);
1836
+ }
1837
+ // Hex format: #RGB, #RGBA, #RRGGBB, #RRGGBBAA
1838
+ if (trimmed.startsWith('#')) {
1839
+ const hex = trimmed.slice(1);
1840
+ if (hex.length === 3) {
1841
+ // #RGB -> #RRGGBB
1842
+ return {
1843
+ r: parseInt(hex[0] + hex[0], 16),
1844
+ g: parseInt(hex[1] + hex[1], 16),
1845
+ b: parseInt(hex[2] + hex[2], 16),
1846
+ };
1847
+ }
1848
+ else if (hex.length === 4) {
1849
+ // #RGBA -> #RRGGBBAA (ignore alpha)
1850
+ return {
1851
+ r: parseInt(hex[0] + hex[0], 16),
1852
+ g: parseInt(hex[1] + hex[1], 16),
1853
+ b: parseInt(hex[2] + hex[2], 16),
1854
+ };
1855
+ }
1856
+ else if (hex.length >= 6) {
1857
+ // #RRGGBB or #RRGGBBAA
1858
+ return {
1859
+ r: parseInt(hex.slice(0, 2), 16),
1860
+ g: parseInt(hex.slice(2, 4), 16),
1861
+ b: parseInt(hex.slice(4, 6), 16),
1862
+ };
1863
+ }
1864
+ }
1865
+ // RGB format: rgb(r, g, b) or rgba(r, g, b, a)
1866
+ const rgbMatch = trimmed.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
1867
+ if (rgbMatch) {
1868
+ return {
1869
+ r: parseInt(rgbMatch[1], 10),
1870
+ g: parseInt(rgbMatch[2], 10),
1871
+ b: parseInt(rgbMatch[3], 10),
1872
+ };
1873
+ }
1874
+ // RGB percentage format: rgb(r%, g%, b%)
1875
+ const rgbPercentMatch = trimmed.match(/rgba?\s*\(\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%/);
1876
+ if (rgbPercentMatch) {
1877
+ return {
1878
+ r: Math.round((parseFloat(rgbPercentMatch[1]) / 100) * 255),
1879
+ g: Math.round((parseFloat(rgbPercentMatch[2]) / 100) * 255),
1880
+ b: Math.round((parseFloat(rgbPercentMatch[3]) / 100) * 255),
1881
+ };
1882
+ }
1883
+ return null;
1884
+ }
1885
+ /**
1886
+ * Calculate relative luminance per WCAG 2.1 specification
1887
+ * https://www.w3.org/WAI/GL/wiki/Relative_luminance
1888
+ */
1889
+ function getLuminance(r, g, b) {
1890
+ // Convert 8-bit RGB to sRGB
1891
+ const rSrgb = r / 255;
1892
+ const gSrgb = g / 255;
1893
+ const bSrgb = b / 255;
1894
+ // Apply gamma correction
1895
+ const gammaCorrect = (c) => {
1896
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
1897
+ };
1898
+ const rLin = gammaCorrect(rSrgb);
1899
+ const gLin = gammaCorrect(gSrgb);
1900
+ const bLin = gammaCorrect(bSrgb);
1901
+ // Calculate relative luminance
1902
+ return 0.2126 * rLin + 0.7152 * gLin + 0.0722 * bLin;
1903
+ }
1904
+ /**
1905
+ * Calculate contrast ratio between two colors per WCAG 2.1
1906
+ * https://www.w3.org/WAI/GL/wiki/Contrast_ratio
1907
+ */
1908
+ function calculateContrastRatio(fg, bg) {
1909
+ const fgLum = getLuminance(fg.r, fg.g, fg.b);
1910
+ const bgLum = getLuminance(bg.r, bg.g, bg.b);
1911
+ const lighter = Math.max(fgLum, bgLum);
1912
+ const darker = Math.min(fgLum, bgLum);
1913
+ return (lighter + 0.05) / (darker + 0.05);
1914
+ }
1915
+ /**
1916
+ * Determine if text is "large" per WCAG definition
1917
+ * Large text: 18pt (24px) or 14pt (18.67px) bold
1918
+ */
1919
+ function isLargeText(fontSize, isBold) {
1920
+ if (!fontSize)
1921
+ return false;
1922
+ // 18pt = 24px
1923
+ if (fontSize >= 24)
1924
+ return true;
1925
+ // 14pt bold = 18.67px bold
1926
+ if (fontSize >= 18.67 && isBold)
1927
+ return true;
1928
+ return false;
1929
+ }
1930
+ /**
1931
+ * Calculate contrast ratio using WCAG 2.1 formula with proper sRGB gamma correction
1932
+ * (Legacy function for backward compatibility with design token analysis)
1933
+ */
1934
+ function estimateContrastRatio(color) {
1935
+ if (!color.startsWith('#'))
1936
+ return 0;
1937
+ const hex = color.replace('#', '');
1938
+ if (hex.length < 6)
1939
+ return 0;
1940
+ // Parse RGB values
1941
+ const rRaw = parseInt(hex.slice(0, 2), 16) / 255;
1942
+ const gRaw = parseInt(hex.slice(2, 4), 16) / 255;
1943
+ const bRaw = parseInt(hex.slice(4, 6), 16) / 255;
1944
+ // Apply sRGB gamma correction (WCAG 2.1 specification)
1945
+ const gammaCorrect = (c) => {
1946
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
1947
+ };
1948
+ const r = gammaCorrect(rRaw);
1949
+ const g = gammaCorrect(gRaw);
1950
+ const b = gammaCorrect(bRaw);
1951
+ // Calculate relative luminance
1952
+ const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
1953
+ // Contrast ratio against white background (luminance = 1)
1954
+ const ratio = (1 + 0.05) / (luminance + 0.05);
1955
+ return Math.round(ratio * 10) / 10;
1956
+ }
1957
+ function resolveAllyCli() {
1958
+ const here = dirname(fileURLToPath(import.meta.url));
1959
+ const candidates = [
1960
+ join(here, '../../dist/cli.js'),
1961
+ join(process.cwd(), 'dist/cli.js'),
1962
+ join(process.cwd(), 'node_modules/ally-a11y/dist/cli.js'),
1963
+ join(process.cwd(), 'node_modules/ally/dist/cli.js'),
1964
+ ];
1965
+ for (const candidate of candidates) {
1966
+ if (existsSync(candidate))
1967
+ return candidate;
1968
+ }
1969
+ throw new Error('ally CLI not found. From this repo run `pnpm run build`, or install ally-a11y in the project.');
1970
+ }
1971
+ function runAlly(args, timeoutMs = 120_000) {
1972
+ return new Promise((resolvePromise, reject) => {
1973
+ const child = spawn(process.execPath, [resolveAllyCli(), ...args], {
1974
+ cwd: process.cwd(),
1975
+ stdio: ['ignore', 'pipe', 'pipe'],
1976
+ shell: false,
1977
+ });
1978
+ let stdout = '';
1979
+ let stderr = '';
1980
+ let settled = false;
1981
+ const timer = setTimeout(() => {
1982
+ child.kill('SIGTERM');
1983
+ if (!settled) {
1984
+ settled = true;
1985
+ reject(new Error(`ally timed out after ${timeoutMs}ms`));
1986
+ }
1987
+ }, timeoutMs);
1988
+ child.stdout?.on('data', (chunk) => {
1989
+ stdout += chunk.toString();
1990
+ });
1991
+ child.stderr?.on('data', (chunk) => {
1992
+ stderr += chunk.toString();
1993
+ });
1994
+ child.on('error', (error) => {
1995
+ clearTimeout(timer);
1996
+ if (!settled) {
1997
+ settled = true;
1998
+ reject(error);
1999
+ }
2000
+ });
2001
+ child.on('close', (status) => {
2002
+ clearTimeout(timer);
2003
+ if (!settled) {
2004
+ settled = true;
2005
+ resolvePromise({ stdout, stderr, status });
2006
+ }
2007
+ });
2008
+ });
2009
+ }
2010
+ server.tool('scan_accessibility', 'Run an accessibility scan with ally (axe-core). Use this instead of guessing WCAG issues. Pass a local path or a running URL.', {
2011
+ path: z.string().optional().describe('Directory or file to scan (default: current directory)'),
2012
+ url: z.string().optional().describe('Running page URL to scan instead of files'),
2013
+ standard: z.string().optional().describe('WCAG standard tag such as wcag22aa'),
2014
+ }, async ({ path: targetPath, url, standard }) => {
2015
+ telemetry.log('scan_accessibility');
2016
+ try {
2017
+ const args = ['scan', '--json', '--ci'];
2018
+ if (url) {
2019
+ args.push('--url', url);
2020
+ }
2021
+ else if (targetPath) {
2022
+ args.push(targetPath);
2023
+ }
2024
+ else {
2025
+ args.push('.');
2026
+ }
2027
+ if (standard) {
2028
+ args.push('--standard', standard);
2029
+ }
2030
+ const result = await runAlly(args);
2031
+ const output = result.stdout.trim() || result.stderr.trim() || 'Scan finished with no output.';
2032
+ return {
2033
+ content: [{ type: 'text', text: output }],
2034
+ isError: result.status !== 0 && result.status !== 1,
2035
+ };
2036
+ }
2037
+ catch (error) {
2038
+ return {
2039
+ content: [
2040
+ {
2041
+ type: 'text',
2042
+ text: error instanceof Error ? error.message : String(error),
2043
+ },
2044
+ ],
2045
+ isError: true,
2046
+ };
2047
+ }
2048
+ });
2049
+ server.tool('fix_accessibility', 'Apply ally high-confidence accessibility fixes from the latest scan. Prefer dryRun first.', {
2050
+ dryRun: z.boolean().optional().describe('Preview fixes without writing files (default true)'),
2051
+ auto: z.boolean().optional().describe('Apply fixes without prompting (ignored when dryRun is true)'),
2052
+ }, async ({ dryRun = true, auto = false }) => {
2053
+ telemetry.log('fix_accessibility');
2054
+ try {
2055
+ const args = ['fix'];
2056
+ if (dryRun) {
2057
+ args.push('--dry-run');
2058
+ }
2059
+ else if (auto) {
2060
+ args.push('--auto');
2061
+ }
2062
+ const result = await runAlly(args);
2063
+ const output = result.stdout.trim() || result.stderr.trim() || 'Fix finished with no output.';
2064
+ return {
2065
+ content: [{ type: 'text', text: output }],
2066
+ isError: result.status !== 0,
2067
+ };
2068
+ }
2069
+ catch (error) {
2070
+ return {
2071
+ content: [
2072
+ {
2073
+ type: 'text',
2074
+ text: error instanceof Error ? error.message : String(error),
2075
+ },
2076
+ ],
2077
+ isError: true,
2078
+ };
2079
+ }
2080
+ });
2081
+ // Run the server
2082
+ async function main() {
2083
+ const transport = new StdioServerTransport();
2084
+ await server.connect(transport);
2085
+ console.error('Ally MCP Server running on stdio');
2086
+ }
2087
+ main().catch((error) => {
2088
+ console.error('Fatal error:', error);
2089
+ process.exit(1);
2090
+ });