1
2
3
4import { gunzipSync } from 'node:zlib';
5
6const USER_AGENT = 'sitemap-url-list/1.0 (Apify Actor; reads public sitemaps)';
7const COMMON_PATHS = ['/sitemap.xml', '/sitemap_index.xml', '/sitemap-index.xml', '/wp-sitemap.xml', '/sitemap.txt'];
8
9const decode = (s) => s
10 .replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1')
11 .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
12 .replace(/"/g, '"').replace(/'/g, "'")
13 .trim();
14
15const tag = (block, name) => {
16 const m = block.match(new RegExp(`<(?:[a-z0-9]+:)?${name}[^>]*>([\\s\\S]*?)</(?:[a-z0-9]+:)?${name}>`, 'i'));
17 return m ? decode(m[1]) : null;
18};
19
20export function parseSitemap(text) {
21 const body = text.trim();
22 if (/<(?:[a-z0-9]+:)?sitemapindex[\s>]/i.test(body)) {
23 const children = [...body.matchAll(/<(?:[a-z0-9]+:)?sitemap[\s>][\s\S]*?<\/(?:[a-z0-9]+:)?sitemap>/gi)]
24 .map((m) => ({ loc: tag(m[0], 'loc'), lastmod: tag(m[0], 'lastmod') }))
25 .filter((c) => c.loc);
26 return { kind: 'index', children, urls: [] };
27 }
28 if (/<(?:[a-z0-9]+:)?urlset[\s>]/i.test(body)) {
29 const urls = [...body.matchAll(/<(?:[a-z0-9]+:)?url[\s>][\s\S]*?<\/(?:[a-z0-9]+:)?url>/gi)].map((m) => {
30 const block = m[0];
31 return {
32 url: tag(block, 'loc'),
33 lastmod: tag(block, 'lastmod'),
34 changefreq: tag(block, 'changefreq'),
35 priority: tag(block, 'priority'),
36 imageCount: (block.match(/<image:image[\s>]/gi) ?? []).length,
37 };
38 }).filter((u) => u.url);
39 return { kind: 'urlset', children: [], urls };
40 }
41
42 if (!body.startsWith('<')) {
43 const urls = body.split(/\r?\n/).map((l) => l.trim()).filter((l) => /^https?:\/\//i.test(l))
44 .map((url) => ({ url, lastmod: null, changefreq: null, priority: null, imageCount: 0 }));
45 if (urls.length) return { kind: 'text', children: [], urls };
46 }
47 return { kind: 'unknown', children: [], urls: [] };
48}
49
50export async function fetchText(url, { timeoutMs = 45_000 } = {}) {
51 const res = await fetch(url, {
52 headers: { 'User-Agent': USER_AGENT, Accept: 'application/xml,text/xml,text/plain,*/*' },
53 redirect: 'follow',
54 signal: AbortSignal.timeout(timeoutMs),
55 });
56 if (!res.ok) return { ok: false, status: res.status, text: '' };
57 let buf = Buffer.from(await res.arrayBuffer());
58 if (buf.length > 2 && buf[0] === 0x1f && buf[1] === 0x8b) {
59 try { buf = gunzipSync(buf); } catch { return { ok: false, status: 'bad-gzip', text: '' }; }
60 }
61 return { ok: true, status: res.status, text: buf.toString('utf8'), finalUrl: res.url };
62}
63
64export function normaliseStart(input) {
65 let s = String(input).trim();
66 if (!s) return null;
67 if (!/^https?:\/\//i.test(s)) s = `https://${s}`;
68 try {
69 const u = new URL(s);
70 const looksLikeSitemap = /sitemap|\.xml(\.gz)?$|\.txt$/i.test(u.pathname);
71 return { origin: u.origin, sitemap: looksLikeSitemap ? u.toString() : null };
72 } catch {
73 return null;
74 }
75}
76
77
78export async function discoverSitemaps(origin, log) {
79 const found = new Set();
80 try {
81 const robots = await fetchText(`${origin}/robots.txt`, { timeoutMs: 20_000 });
82 if (robots.ok) {
83 for (const m of robots.text.matchAll(/^\s*sitemap:\s*(\S+)/gim)) found.add(m[1].trim());
84 }
85 } catch (err) {
86 log.debug(`robots.txt not readable for ${origin}: ${err.message}`);
87 }
88 if (found.size) return [...found];
89 for (const p of COMMON_PATHS) {
90 try {
91 const r = await fetchText(origin + p, { timeoutMs: 20_000 });
92 if (r.ok && parseSitemap(r.text).kind !== 'unknown') return [origin + p];
93 } catch { }
94 }
95 return [];
96}