Spaces:
Paused
Paused
File size: 11,643 Bytes
d8804ab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | 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();
|