Spaces:
Paused
Paused
feat(design-system): implement absolute inversion principle, typographic audits, waitlist interactive features & WCAG 2.1 compliance
d8804ab Download audit-scanner.mjs from samirhosninet/HubAPI: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/samirhosninet/HubAPI/resolve/main/audit-scanner.mjs
- Command line
-
hf download hf://spaces/samirhosninet/HubAPI/audit-scanner.mjs
-
curl -L -o audit-scanner.mjs https://huggingface.co/spaces/samirhosninet/HubAPI/resolve/main/audit-scanner.mjs
11.6 kB
| import http from 'http'; | |
| // Helper to fetch HTML content from the local server | |
| function fetchHtml(url) { | |
| return new Promise((resolve, reject) => { | |
| http.get(url, (res) => { | |
| const { statusCode } = res; | |
| if (statusCode !== 200) { | |
| reject(new Error(`Failed to fetch page. Status Code: ${statusCode}`)); | |
| return; | |
| } | |
| res.setEncoding('utf8'); | |
| let rawData = ''; | |
| res.on('data', (chunk) => { rawData += chunk; }); | |
| res.on('end', () => { | |
| resolve(rawData); | |
| }); | |
| }).on('error', (e) => { | |
| reject(new Error(`Error fetching URL: ${e.message}`)); | |
| }); | |
| }); | |
| } | |
| // Custom parser to extract tags, attributes, and text | |
| function parseHtml(html) { | |
| const tags = []; | |
| const tagRegExp = /<([a-z0-9-]+)(?:\s+([^>]*))?>/gi; | |
| const attrRegExp = /([a-z0-9-]+)(?:=(?:"([^"]*)"|'([^']*)'|([^>\s]+)))?/gi; | |
| let match; | |
| while ((match = tagRegExp.exec(html)) !== null) { | |
| const tagName = match[1].toLowerCase(); | |
| const attrString = match[2] || ''; | |
| const attrs = {}; | |
| let attrMatch; | |
| while ((attrMatch = attrRegExp.exec(attrString)) !== null) { | |
| const attrName = attrMatch[1].toLowerCase(); | |
| const attrValue = attrMatch[2] || attrMatch[3] || attrMatch[4] || ''; | |
| attrs[attrName] = attrValue; | |
| } | |
| // Attempt to extract text content after this tag until next tag | |
| const startIndex = match.index + match[0].length; | |
| const nextTagIndex = html.indexOf('<', startIndex); | |
| const textContent = nextTagIndex > startIndex ? html.slice(startIndex, nextTagIndex).trim() : ''; | |
| tags.push({ | |
| name: tagName, | |
| attrs, | |
| text: textContent, | |
| outerHtml: match[0], | |
| index: match.index | |
| }); | |
| } | |
| return tags; | |
| } | |
| async function runAudit() { | |
| const url = process.env.AUDIT_URL || 'http://localhost:3001'; | |
| console.log(`\n======================================================`); | |
| console.log(`π HUBAPI AUTOMATED STATIC CODE & ACCESSIBILITY AUDIT`); | |
| console.log(`======================================================`); | |
| console.log(`π‘ Connecting to local server: ${url}...`); | |
| let html; | |
| try { | |
| html = await fetchHtml(url); | |
| console.log(`β Connection established successfully. Pages HTML loaded (${html.length} bytes).`); | |
| } catch (error) { | |
| console.error(`β Connection failed: ${error.message}`); | |
| console.log(`π‘ Ensure Next.js dev server is running on http://localhost:3000`); | |
| process.exit(1); | |
| } | |
| const tags = parseHtml(html); | |
| let passed = 0; | |
| let failed = 0; | |
| const warnings = []; | |
| const successes = []; | |
| // 1. HTML lang attribute | |
| const htmlTag = tags.find(t => t.name === 'html'); | |
| if (htmlTag && htmlTag.attrs.lang) { | |
| successes.push(`SEO/a11y: <html> tag specifies valid lang attribute ("${htmlTag.attrs.lang}")`); | |
| passed++; | |
| } else { | |
| warnings.push(`a11y: <html> tag does not specify a "lang" attribute (critical for screen readers).`); | |
| failed++; | |
| } | |
| // 2. Page Title | |
| const titleTag = tags.find(t => t.name === 'title'); | |
| if (titleTag && titleTag.text) { | |
| successes.push(`SEO: Title tag found: "${titleTag.text}"`); | |
| passed++; | |
| } else { | |
| warnings.push(`SEO: Page <title> tag is missing or empty.`); | |
| failed++; | |
| } | |
| // 3. Viewport Meta | |
| const metaTags = tags.filter(t => t.name === 'meta'); | |
| const viewportMeta = metaTags.find(t => t.attrs.name === 'viewport'); | |
| if (viewportMeta) { | |
| successes.push(`SEO: Viewport meta tag found for responsive layouts.`); | |
| passed++; | |
| } else { | |
| warnings.push(`SEO: Responsive meta viewport tag is missing.`); | |
| failed++; | |
| } | |
| // 4. Meta Description | |
| const descMeta = metaTags.find(t => t.attrs.name === 'description'); | |
| if (descMeta && descMeta.attrs.content) { | |
| successes.push(`SEO: Meta description found: "${descMeta.attrs.content}"`); | |
| passed++; | |
| } else { | |
| warnings.push(`SEO: Meta description is missing (important for search previews).`); | |
| failed++; | |
| } | |
| // 5. Semantic Landmarks | |
| const mainTag = tags.find(t => t.name === 'main'); | |
| const headerTag = tags.find(t => t.name === 'header'); | |
| const footerTag = tags.find(t => t.name === 'footer'); | |
| const navTag = tags.find(t => t.name === 'nav'); | |
| if (mainTag) { successes.push(`Semantics: <main> landmark tag is correctly implemented.`); passed++; } | |
| else { warnings.push(`Semantics: Missing <main> landmark tag.`); failed++; } | |
| if (headerTag) { successes.push(`Semantics: <header> landmark tag is correctly implemented.`); passed++; } | |
| else { warnings.push(`Semantics: Missing <header> landmark tag.`); failed++; } | |
| if (footerTag) { successes.push(`Semantics: <footer> landmark tag is correctly implemented.`); passed++; } | |
| else { warnings.push(`Semantics: Missing <footer> landmark tag.`); failed++; } | |
| if (navTag) { successes.push(`Semantics: <nav> navigation landmark tag is correctly implemented.`); passed++; } | |
| else { warnings.push(`Semantics: No <nav> tag found. Navigation links should be wrapped in <nav>.`); failed++; } | |
| // 6. Heading Hierarchy | |
| const headings = tags.filter(t => ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(t.name)); | |
| const h1Count = headings.filter(h => h.name === 'h1').length; | |
| if (h1Count === 1) { | |
| successes.push(`SEO/Semantics: Found exactly 1 <h1> tag.`); | |
| passed++; | |
| } else if (h1Count > 1) { | |
| warnings.push(`SEO: Multiple <h1> tags found (${h1Count}). Standard practice recommends a single primary heading.`); | |
| failed++; | |
| } else { | |
| warnings.push(`SEO: No <h1> tag found on the page.`); | |
| failed++; | |
| } | |
| // Check for skip levels (e.g. H1 followed by H3) | |
| let prevLevel = 0; | |
| let skippedHeading = false; | |
| for (const h of headings) { | |
| const currentLevel = parseInt(h.name[1]); | |
| if (prevLevel > 0 && currentLevel - prevLevel > 1) { | |
| warnings.push(`Semantics: Heading hierarchy skip: H${prevLevel} to H${currentLevel} ("${h.text || h.outerHtml}")`); | |
| skippedHeading = true; | |
| } | |
| prevLevel = currentLevel; | |
| } | |
| if (!skippedHeading && headings.length > 0) { | |
| successes.push(`Semantics: Heading hierarchy levels are correctly ordered.`); | |
| passed++; | |
| } | |
| // 7. Accessibility - Images alt | |
| const images = tags.filter(t => t.name === 'img'); | |
| let missingAlt = 0; | |
| images.forEach(img => { | |
| if (img.attrs.alt === undefined) { | |
| missingAlt++; | |
| } | |
| }); | |
| if (missingAlt === 0) { | |
| successes.push(`a11y: All <img> tags (${images.length}) specify an alt attribute.`); | |
| passed++; | |
| } else { | |
| warnings.push(`a11y: ${missingAlt} <img> tag(s) missing alt attribute(s).`); | |
| failed++; | |
| } | |
| // 8. Accessibility - Button labels | |
| const buttonRegex = /<button\s*([^>]*?)>([\s\S]*?)<\/button>/gi; | |
| let unlabelledButtons = 0; | |
| const failingButtonsList = []; | |
| let btnMatch; | |
| let totalButtonsCount = 0; | |
| while ((btnMatch = buttonRegex.exec(html)) !== null) { | |
| totalButtonsCount++; | |
| const attrString = btnMatch[1]; | |
| const innerHtml = btnMatch[2]; | |
| // Parse attributes | |
| const attrs = {}; | |
| const attrRegExp = /([a-z0-9-]+)(?:=(?:"([^"]*)"|'([^']*)'|([^>\s]+)))?/gi; | |
| let attrM; | |
| while ((attrM = attrRegExp.exec(attrString)) !== null) { | |
| attrs[attrM[1].toLowerCase()] = attrM[2] || attrM[3] || attrM[4] || ''; | |
| } | |
| // Strip HTML tags from innerHtml to get text | |
| const textContent = innerHtml.replace(/<[^>]*>/g, '').trim(); | |
| const hasLabel = attrs['aria-label'] || attrs['aria-labelledby'] || attrs.title || textContent; | |
| if (!hasLabel) { | |
| unlabelledButtons++; | |
| failingButtonsList.push(btnMatch[0].slice(0, 150) + '...'); | |
| } | |
| } | |
| if (unlabelledButtons === 0) { | |
| successes.push(`a11y: All <button> elements (${totalButtonsCount}) are fully accessible/labeled.`); | |
| passed++; | |
| } else { | |
| warnings.push(`a11y: ${unlabelledButtons} of ${totalButtonsCount} <button> element(s) missing descriptive text, title, or aria-label: \n ${failingButtonsList.join('\n ')}`); | |
| failed++; | |
| } | |
| // 9. Accessibility - Interactive element focus & keyboard readiness | |
| const linkRegex = /<a\s*([^>]*?)>([\s\S]*?)<\/a>/gi; | |
| let emptyLinks = 0; | |
| const failingLinksList = []; | |
| let linkMatch; | |
| let totalLinksCount = 0; | |
| while ((linkMatch = linkRegex.exec(html)) !== null) { | |
| totalLinksCount++; | |
| const attrString = linkMatch[1]; | |
| const innerHtml = linkMatch[2]; | |
| // Parse attributes | |
| const attrs = {}; | |
| const attrRegExp = /([a-z0-9-]+)(?:=(?:"([^"]*)"|'([^']*)'|([^>\s]+)))?/gi; | |
| let attrM; | |
| while ((attrM = attrRegExp.exec(attrString)) !== null) { | |
| attrs[attrM[1].toLowerCase()] = attrM[2] || attrM[3] || attrM[4] || ''; | |
| } | |
| // Strip HTML tags from innerHtml to get text | |
| const textContent = innerHtml.replace(/<[^>]*>/g, '').trim(); | |
| const hasText = textContent || attrs['aria-label'] || attrs.title; | |
| if (!hasText) { | |
| emptyLinks++; | |
| failingLinksList.push(linkMatch[0].slice(0, 150) + '...'); | |
| } | |
| } | |
| if (emptyLinks === 0) { | |
| successes.push(`a11y: All <a> anchor links (${totalLinksCount}) contain inner content or ARIA descriptors.`); | |
| passed++; | |
| } else { | |
| warnings.push(`a11y: ${emptyLinks} of ${totalLinksCount} anchor link(s) are empty or missing accessible labels: \n ${failingLinksList.slice(0, 10).join('\n ')}${failingLinksList.length > 10 ? `\n ...and ${failingLinksList.length - 10} more` : ''}`); | |
| failed++; | |
| } | |
| // 10. Forms and Labels | |
| const inputs = tags.filter(t => t.name === 'input'); | |
| let missingInputLabel = 0; | |
| inputs.forEach(input => { | |
| if (input.attrs.type === 'hidden') return; | |
| const hasLabel = input.attrs.id && tags.some(t => t.name === 'label' && t.attrs.for === input.attrs.id); | |
| const hasAria = input.attrs['aria-label'] || input.attrs['aria-labelledby'] || input.attrs.placeholder; | |
| if (!hasLabel && !hasAria) { | |
| missingInputLabel++; | |
| } | |
| }); | |
| if (missingInputLabel === 0) { | |
| successes.push(`a11y: All input fields specify accessible labels, aria-labels, or context placeholders.`); | |
| passed++; | |
| } else { | |
| warnings.push(`a11y: ${missingInputLabel} input field(s) have no linked <label> or ARIA description.`); | |
| failed++; | |
| } | |
| // 11. Unique IDs | |
| const idCounts = {}; | |
| tags.forEach(t => { | |
| if (t.attrs.id) { | |
| idCounts[t.attrs.id] = (idCounts[t.attrs.id] || 0) + 1; | |
| } | |
| }); | |
| const duplicateIds = Object.keys(idCounts).filter(id => idCounts[id] > 1); | |
| if (duplicateIds.length === 0) { | |
| successes.push(`HTML: Standard unique ID compliance passed. Zero duplicate element IDs found.`); | |
| passed++; | |
| } else { | |
| warnings.push(`HTML: Duplicate IDs found: ${duplicateIds.join(', ')}`); | |
| failed++; | |
| } | |
| // Calculate scores | |
| const total = passed + failed; | |
| const score = Math.round((passed / total) * 100); | |
| console.log(`\n======================================================`); | |
| console.log(`π AUDIT METRICS & SUMMARY`); | |
| console.log(`======================================================`); | |
| console.log(`β Overall Score: ${score}/100`); | |
| console.log(`β Passed Checks: ${passed}`); | |
| console.log(`β οΈ Warnings/Fixes needed: ${failed}`); | |
| console.log(`------------------------------------------------------`); | |
| if (successes.length > 0) { | |
| console.log(`\nπ’ SUCCESSES:`); | |
| successes.forEach(s => console.log(` βοΈ ${s}`)); | |
| } | |
| if (warnings.length > 0) { | |
| console.log(`\nπ‘ CRITICAL OBSERVATIONS / IMPROVEMENTS:`); | |
| warnings.forEach(w => console.log(` β οΈ ${w}`)); | |
| } else { | |
| console.log(`\nπ PERFECT CODE COMPLIANCE! No accessibility, SEO, or structural flaws detected.`); | |
| } | |
| console.log(`\n======================================================\n`); | |
| } | |
| runAudit(); | |