|
| 1 | +/** |
| 2 | + * Inlined from astro-broken-links-checker v1.0.6 |
| 3 | + * Original source: https://github.com/imazen/astro-broken-link-checker |
| 4 | + * License: Apache-2.0 |
| 5 | + * Author: Lilith River |
| 6 | + * |
| 7 | + * This file is a local copy of check-links.js from the plugin, modified to |
| 8 | + * allow custom behavior adjustments without forking the upstream package. |
| 9 | + */ |
| 10 | +import {parse} from 'node-html-parser'; |
| 11 | +import fs from 'fs'; |
| 12 | +import fetch from 'node-fetch'; |
| 13 | +import {URL, fileURLToPath} from 'url'; |
| 14 | +import path from 'path'; |
| 15 | +import pLimit from 'p-limit'; |
| 16 | + |
| 17 | +export async function checkLinksInHtml( |
| 18 | + htmlContent, |
| 19 | + brokenLinksMap, |
| 20 | + baseUrl, |
| 21 | + documentPath, |
| 22 | + checkedLinks = new Map(), |
| 23 | + distPath = '', |
| 24 | + astroConfigRedirects = {}, |
| 25 | + logger, |
| 26 | + checkExternalLinks = true, |
| 27 | + trailingSlash = 'ignore', |
| 28 | + basePath = '', |
| 29 | +) { |
| 30 | + const root = parse(htmlContent); |
| 31 | + const linkElements = root.querySelectorAll('a[href]'); |
| 32 | + const links = linkElements.map((el) => el.getAttribute('href')); |
| 33 | + // add img src |
| 34 | + const imgElements = root.querySelectorAll('img[src]'); |
| 35 | + const imgLinks = imgElements.map((el) => el.getAttribute('src')); |
| 36 | + links.push(...imgLinks); |
| 37 | + |
| 38 | + const limit = pLimit(50); // Limit to 10 concurrent link checks |
| 39 | + |
| 40 | + const checkLinkPromises = links.map((link) => |
| 41 | + limit(async () => { |
| 42 | + if (!isValidUrl(link)) { |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + let absoluteLink; |
| 47 | + try { |
| 48 | + // Differentiate between absolute, domain-relative, and relative links |
| 49 | + if (/^https?:\/\//i.test(link) || /^:\/\//i.test(link)) { |
| 50 | + // Absolute URL |
| 51 | + absoluteLink = link; |
| 52 | + } else { |
| 53 | + absoluteLink = new URL(link, "https://localhost" + baseUrl).pathname; |
| 54 | + // if (link !== absoluteLink) { |
| 55 | + // logger.info(`Link ${link} was resolved to ${absoluteLink}`); |
| 56 | + // } |
| 57 | + } |
| 58 | + } catch (err) { |
| 59 | + // Invalid URL, skip |
| 60 | + logger.error(`Invalid URL in ${normalizePath(documentPath)} ${link} ${err}`); |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + let fetchLink = link; |
| 65 | + if (absoluteLink.startsWith('/') && distPath) { |
| 66 | + fetchLink = absoluteLink; |
| 67 | + } |
| 68 | + |
| 69 | + // Strip the base path prefix from internal links so they resolve correctly |
| 70 | + // against the dist directory. e.g. /docs/page -> /page when base is /docs/ |
| 71 | + let fetchLinkWithoutBase = fetchLink; |
| 72 | + if (basePath && fetchLink.startsWith(basePath)) { |
| 73 | + fetchLinkWithoutBase = fetchLink.slice(basePath.length) || '/'; |
| 74 | + } |
| 75 | + |
| 76 | + // Redirect lookup uses the link without base prefix (redirects are defined without base) |
| 77 | + if (astroConfigRedirects[fetchLinkWithoutBase]) { |
| 78 | + const redirect = astroConfigRedirects[fetchLinkWithoutBase]; |
| 79 | + if (redirect) { |
| 80 | + fetchLinkWithoutBase = redirect.destination ? redirect.destination : redirect; |
| 81 | + fetchLink = basePath + fetchLinkWithoutBase; |
| 82 | + } |
| 83 | + } else if (astroConfigRedirects[fetchLink]) { |
| 84 | + // fallback: try with full link including base |
| 85 | + const redirect = astroConfigRedirects[fetchLink]; |
| 86 | + if (redirect) { |
| 87 | + fetchLink = redirect.destination ? redirect.destination : redirect; |
| 88 | + fetchLinkWithoutBase = basePath && fetchLink.startsWith(basePath) |
| 89 | + ? fetchLink.slice(basePath.length) || '/' |
| 90 | + : fetchLink; |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + if (checkedLinks.has(fetchLink)) { |
| 95 | + const isBroken = !checkedLinks.get(fetchLink); |
| 96 | + if (isBroken) { |
| 97 | + addBrokenLink(brokenLinksMap, documentPath, link, distPath); |
| 98 | + } |
| 99 | + return; |
| 100 | + } |
| 101 | + |
| 102 | + let isBroken = false; |
| 103 | + |
| 104 | + if (fetchLink.startsWith('/') && distPath) { |
| 105 | + // Internal link in build mode, check if file exists. |
| 106 | + // Astro's base path is part of the URL but NOT reflected in the dist |
| 107 | + // directory structure — files are output at the root of dist/. |
| 108 | + // So we strip the base prefix and resolve against distPath directly. |
| 109 | + const relativePath = fetchLinkWithoutBase; |
| 110 | + // Potential file paths to check |
| 111 | + const possiblePaths = [ |
| 112 | + path.join(distPath, relativePath), |
| 113 | + path.join(distPath, relativePath, 'index.html'), |
| 114 | + path.join(distPath, `${relativePath}.html`), |
| 115 | + ]; |
| 116 | + |
| 117 | + // Check if any of the possible paths exist |
| 118 | + if (!possiblePaths.some((p) => fs.existsSync(p))) { |
| 119 | + // console.log('Failed paths', possiblePaths); |
| 120 | + isBroken = true; |
| 121 | + // Fall back to checking a redirect file if it exists. |
| 122 | + } |
| 123 | + |
| 124 | + // check trailing slash is correct on internal links |
| 125 | + const re = /\/$|\.[a-z0-9]+$/; // match trailing slash or file extension |
| 126 | + if (trailingSlash === 'always' && !fetchLink.match(re)) { |
| 127 | + isBroken = true; |
| 128 | + } else if (trailingSlash === 'never' && fetchLink !== '/' && fetchLink.endsWith('/')) { |
| 129 | + isBroken = true; |
| 130 | + } |
| 131 | + } else { |
| 132 | + // External link, check via HTTP request. Retry 3 times if ECONNRESET |
| 133 | + if (checkExternalLinks) { |
| 134 | + let retries = 0; |
| 135 | + while (retries < 3) { |
| 136 | + try { |
| 137 | + const response = await fetch(fetchLink, {method: 'GET'}); |
| 138 | + isBroken = !response.ok; |
| 139 | + if (isBroken) { |
| 140 | + logger.error(`${response.status} Error fetching ${fetchLink}`); |
| 141 | + } |
| 142 | + break; |
| 143 | + } catch (error) { |
| 144 | + isBroken = true; |
| 145 | + let statusCodeNumber = error.errno === 'ENOTFOUND' ? 404 : (error.errno); |
| 146 | + logger.error(`${statusCodeNumber} error fetching ${fetchLink}`); |
| 147 | + if (error.errno === 'ECONNRESET') { |
| 148 | + retries++; |
| 149 | + continue; |
| 150 | + } |
| 151 | + break; |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + // Cache the link's validity |
| 158 | + checkedLinks.set(fetchLink, !isBroken); |
| 159 | + checkedLinks.set(absoluteLink, !isBroken); |
| 160 | + |
| 161 | + if (isBroken) { |
| 162 | + addBrokenLink(brokenLinksMap, documentPath, link, distPath); |
| 163 | + } |
| 164 | + }) |
| 165 | + ); |
| 166 | + |
| 167 | + await Promise.all(checkLinkPromises); |
| 168 | +} |
| 169 | + |
| 170 | +function isValidUrl(url) { |
| 171 | + // Skip mailto:, tel:, javascript:, and empty links |
| 172 | + return !( |
| 173 | + url.startsWith('mailto:') || |
| 174 | + url.startsWith('tel:') || |
| 175 | + url.startsWith('javascript:') || |
| 176 | + url.startsWith('#') || |
| 177 | + url.trim() === '' |
| 178 | + ); |
| 179 | +} |
| 180 | + |
| 181 | +function normalizePath(p) { |
| 182 | + p = p.toString(); |
| 183 | + // Remove query parameters and fragments |
| 184 | + p = p.split('?')[0].split('#')[0]; |
| 185 | + |
| 186 | + // Remove '/index.html' or '.html' suffixes |
| 187 | + if (p.endsWith('/index.html')) { |
| 188 | + p = p.slice(0, -'index.html'.length); |
| 189 | + } else if (p.endsWith('.html')) { |
| 190 | + p = p.slice(0, -'.html'.length); |
| 191 | + } |
| 192 | + |
| 193 | + // Ensure leading '/' |
| 194 | + if (!p.startsWith('/')) { |
| 195 | + p = '/' + p; |
| 196 | + } |
| 197 | + |
| 198 | + return p; |
| 199 | +} |
| 200 | + |
| 201 | +export function normalizeHtmlFilePath(filePath, distPath = '') { |
| 202 | + return normalizePath(distPath ? path.relative(distPath, filePath) : filePath); |
| 203 | +} |
| 204 | + |
| 205 | +function addBrokenLink(brokenLinksMap, documentPath, brokenLink, distPath) { |
| 206 | + // Normalize document path |
| 207 | + documentPath = normalizeHtmlFilePath(documentPath, distPath); |
| 208 | + |
| 209 | + // Normalize broken link for reporting |
| 210 | + let normalizedBrokenLink = brokenLink; |
| 211 | + |
| 212 | + if (!brokenLinksMap.has(normalizedBrokenLink)) { |
| 213 | + brokenLinksMap.set(normalizedBrokenLink, new Set()); |
| 214 | + } |
| 215 | + brokenLinksMap.get(normalizedBrokenLink).add(documentPath); |
| 216 | +} |
0 commit comments