1import { Actor, log } from 'apify';
2import { extractLinks, isInternal, looksLikePage, parseRobots } from './links.js';
3
4const PAGE_EVENT = 'page-checked';
5const USER_AGENT = 'Mozilla/5.0 (compatible; BrokenLinkChecker/1.0; +https://apify.com/coresight-data/broken-link-checker)';
6const BROWSER_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
7const MAX_HTML = 5_000_000;
8const MAX_SOURCES_PER_LINK = 50;
9
10const BOT_BLOCK_CODES = new Set([401, 403, 405, 406, 429, 999]);
11
12const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
13
14function normaliseStart(input) {
15 let s = String(typeof input === 'string' ? input : input?.url ?? '').trim();
16 if (!s) return null;
17 if (!/^https?:\/\//i.test(s)) s = `https://${s}`;
18 try { const u = new URL(s); u.hash = ''; return u.toString(); } catch { return null; }
19}
20
21async function request(url, { method = 'GET', timeoutMs, ua = USER_AGENT, readBody = false }) {
22 const res = await fetch(url, {
23 method,
24 headers: { 'User-Agent': ua, Accept: method === 'HEAD' ? '*/*' : 'text/html,application/xhtml+xml,*/*;q=0.8', 'Accept-Language': 'en-GB,en;q=0.9' },
25 redirect: 'follow',
26 signal: AbortSignal.timeout(timeoutMs),
27 });
28 let body = null;
29 if (readBody) {
30 body = await res.text();
31 if (body.length > MAX_HTML) body = body.slice(0, MAX_HTML);
32 } else {
33 try { await res.body?.cancel(); } catch { }
34 }
35 return { status: res.status, finalUrl: res.url, contentType: res.headers.get('content-type') ?? '', body };
36}
37
38const FRIENDLY = {
39 ENOTFOUND: 'Domain not found',
40 EAI_AGAIN: 'Domain not found',
41 ECONNREFUSED: 'Connection refused',
42 ECONNRESET: 'Connection reset',
43 ETIMEDOUT: 'Timed out',
44 UND_ERR_CONNECT_TIMEOUT: 'Timed out',
45 UND_ERR_HEADERS_TIMEOUT: 'Timed out',
46 CERT_HAS_EXPIRED: 'SSL certificate expired',
47 ERR_TLS_CERT_ALTNAME_INVALID: 'SSL certificate does not match the domain',
48 DEPTH_ZERO_SELF_SIGNED_CERT: 'Self-signed SSL certificate',
49 UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'SSL certificate problem',
50};
51const errorName = (err) => {
52 if (err?.name === 'TimeoutError' || err?.name === 'AbortError') return 'Timed out';
53 const code = err?.cause?.code ?? err?.cause?.errors?.[0]?.code ?? err?.code;
54 if (code) return FRIENDLY[code] ?? code;
55 if (/redirect/i.test(err?.cause?.message ?? '')) return 'Too many redirects';
56 return 'Could not connect';
57};
58
59
60async function checkLink(url, timeoutMs) {
61 try {
62 let r = await request(url, { method: 'HEAD', timeoutMs });
63 if (r.status >= 400) r = await request(url, { method: 'GET', timeoutMs, ua: BROWSER_UA });
64 return { status: r.status, error: null };
65 } catch (err) {
66 try {
67 const r = await request(url, { method: 'GET', timeoutMs, ua: BROWSER_UA });
68 return { status: r.status, error: null };
69 } catch (err2) {
70 return { status: null, error: errorName(err2) };
71 }
72 }
73}
74
75async function pool(items, concurrency, fn) {
76 let i = 0;
77 await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => {
78 while (i < items.length) await fn(items[i++]);
79 }));
80}
81
82await Actor.init();
83
84try {
85 const input = (await Actor.getInput()) ?? {};
86 const starts = [...new Set((Array.isArray(input.startUrls) ? input.startUrls : []).map(normaliseStart).filter(Boolean))];
87 if (!starts.length) throw new Error('Add at least one website, for example example.com.');
88 const maxPages = Math.max(1, Math.min(Number(input.maxPagesPerSite) || 200, 50_000));
89 const checkExternal = input.checkExternalLinks !== false;
90 const checkResources = input.checkImagesAndFiles !== false;
91 const reportBlocked = input.reportBotBlocks === true;
92 const concurrency = Math.max(1, Math.min(Number(input.maxConcurrency) || 5, 20));
93 const timeoutMs = Math.max(5, Math.min(Number(input.timeoutSecs) || 20, 60)) * 1000;
94 const charging = Actor.getChargingManager();
95 const summary = [];
96 let budgetHit = false;
97
98 for (const start of starts) {
99 if (budgetHit) break;
100 const site = new URL(start);
101 const host = site.hostname;
102 log.info(`Checking ${site.origin} (up to ${maxPages} pages)`);
103
104 let allowed = () => true;
105 try {
106 const robots = await request(`${site.origin}/robots.txt`, { timeoutMs, readBody: true });
107 if (robots.status === 200) allowed = parseRobots(robots.body);
108 } catch { }
109
110 const sources = new Map();
111 const status = new Map();
112 const queued = new Set([start]);
113 const queue = [start];
114 let pagesChecked = 0;
115 let skippedByRobots = 0;
116
117 const note = (target, from, type, text) => {
118 let list = sources.get(target);
119 if (!list) { list = []; sources.set(target, list); }
120 if (list.length < MAX_SOURCES_PER_LINK && !list.some((s) => s.page === from && s.type === type)) list.push({ page: from, type, text });
121 };
122
123
124 while (queue.length && pagesChecked < maxPages && !budgetHit) {
125 const batch = queue.splice(0, Math.min(concurrency, maxPages - pagesChecked));
126 await Promise.all(batch.map(async (pageUrl) => {
127 if (charging.calculateMaxEventChargeCountWithinLimit(PAGE_EVENT) <= 0) { budgetHit = true; return; }
128 let res;
129 try {
130 res = await request(pageUrl, { timeoutMs, readBody: true });
131 } catch (err) {
132 status.set(pageUrl, { status: null, error: errorName(err) });
133 pagesChecked++;
134 await Actor.charge({ eventName: PAGE_EVENT });
135 return;
136 }
137 pagesChecked++;
138 await Actor.charge({ eventName: PAGE_EVENT });
139 status.set(pageUrl, { status: res.status, error: null });
140 if (res.status >= 400 || !/html/i.test(res.contentType)) return;
141
142 const base = isInternal(res.finalUrl, host) ? res.finalUrl : null;
143 if (!base) return;
144 for (const link of extractLinks(res.body, base)) {
145 note(link.url, pageUrl, link.type, link.text);
146 if (link.type === 'page' && isInternal(link.url, host) && looksLikePage(link.url) && !queued.has(link.url)) {
147 queued.add(link.url);
148 if (allowed(link.url)) queue.push(link.url);
149 else skippedByRobots++;
150 }
151 }
152 }));
153 if (queue.length) await sleep(200);
154 }
155 if (budgetHit) log.warning('Stopped: the spending limit set for this run has been reached.');
156
157
158 const toCheck = [...sources.keys()].filter((u) => {
159 if (status.has(u)) return false;
160 const internal = isInternal(u, host);
161 const s = sources.get(u);
162 const onlyResources = s.every((x) => x.type !== 'page');
163 if (!internal && !checkExternal) return false;
164 if (onlyResources && !checkResources) return false;
165 if (internal && !allowed(u)) return false;
166 return true;
167 });
168 log.info(`${site.origin}: crawled ${pagesChecked} pages, now checking ${toCheck.length} other links`);
169 await pool(toCheck, concurrency * 2, async (u) => { status.set(u, await checkLink(u, timeoutMs)); });
170
171
172 let broken = 0;
173 let blockedSkipped = 0;
174 const rows = [];
175 for (const [target, list] of sources) {
176 const st = status.get(target);
177 if (!st) continue;
178 const bad = st.error !== null || st.status >= 400;
179 if (!bad) continue;
180 const external = !isInternal(target, host);
181 if (external && st.status && BOT_BLOCK_CODES.has(st.status) && !reportBlocked) { blockedSkipped++; continue; }
182 broken++;
183 for (const s of list) {
184 rows.push({
185 website: site.origin,
186 pageUrl: s.page,
187 brokenUrl: target,
188 linkText: s.text,
189 linkType: s.type,
190 statusCode: st.status,
191 error: st.error ?? (st.status === 404 ? 'Not found' : st.status === 410 ? 'Gone' : st.status === 401 ? 'Needs a login' : st.status === 403 ? 'Access denied' : st.status === 429 ? 'Too many requests' : st.status >= 500 ? 'Server error' : `HTTP ${st.status}`),
192 external,
193 });
194 }
195 }
196 if (rows.length) await Actor.pushData(rows);
197 const result = {
198 website: site.origin,
199 pagesChecked,
200 linksChecked: status.size,
201 brokenLinks: broken,
202 brokenLinkPlacements: rows.length,
203 externalLinksSkippedAsBotBlocked: blockedSkipped,
204 pagesSkippedByRobotsTxt: skippedByRobots,
205 hitPageLimit: pagesChecked >= maxPages && queue.length > 0,
206 };
207 summary.push(result);
208 log.info(`${site.origin}: ${broken} broken link(s) across ${pagesChecked} pages`);
209 }
210
211 await Actor.setValue('SUMMARY', summary);
212 const pages = summary.reduce((n, s) => n + s.pagesChecked, 0);
213 const brokenTotal = summary.reduce((n, s) => n + s.brokenLinks, 0);
214 await Actor.exit(`Checked ${pages} page${pages === 1 ? '' : 's'} on ${summary.length} site${summary.length === 1 ? '' : 's'}; found ${brokenTotal} broken link${brokenTotal === 1 ? '' : 's'}.`);
215} catch (err) {
216 await Actor.fail(err.message);
217}