// Fetch a web page: prints a page's title and words, its markup taken out. A news feed (RSS or Atom) prints its // headlines instead, each with its date and link. Run it from its form in CLIDE, or here: // bun fetch-a-web-page.ts https://example.com /** The most it prints, so a long page doesn't drown whoever reads it. */ const MOST = 20_000; const address = (process.argv[2] ?? "").trim(); let url: URL; try { url = new URL(/^[a-z]+:\/\//i.test(address) ? address : `https://${address}`); if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(); } catch { console.error(`"${address}" isn't a web address. Give one like https://example.com`); process.exit(2); } let response: Response; try { response = await fetch(url, { headers: { "User-Agent": "CLIDE (Fetch a web page)" }, signal: AbortSignal.timeout(30_000), redirect: "follow" }); } catch (error) { console.error(`${url.host} didn't answer: ${error instanceof Error ? error.message : String(error)}`); process.exit(1); } if (!response.ok) { console.error(`${url.host} answered ${response.status} ${response.statusText}.${response.status === 401 || response.status === 403 ? " It may need a sign-in." : ""}`); process.exit(1); } const body = await response.text(); const type = response.headers.get("content-type") ?? ""; /** The few named characters pages use most, and every numbered one. */ function decode(text: string): string { const named: Record = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", mdash: "—", ndash: "–", hellip: "…", rsquo: "’", lsquo: "‘", rdquo: "”", ldquo: "“" }; return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, code: string) => { if (code[0] === "#") { const n = code[1] === "x" || code[1] === "X" ? parseInt(code.slice(2), 16) : parseInt(code.slice(1), 10); return Number.isFinite(n) ? String.fromCodePoint(n) : whole; } return named[code.toLowerCase()] ?? whole; }); } /** What's inside the first …, its own markup taken out. */ function inside(text: string, tag: string): string { const found = new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*?)`, "i").exec(text)?.[1] ?? ""; return decode(found.replace(//g, "$1").replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim(); } function cut(text: string): string { return text.length > MOST ? `${text.slice(0, MOST)}\n\n… cut at ${MOST.toLocaleString("en")} characters.` : text; } const isFeed = /xml|rss|atom/i.test(type) || /^\s*(<\?xml[^>]*>\s*)?<(rss|feed)\b/i.test(body); if (isFeed) { const entries = [...body.matchAll(/<(item|entry)\b[\s\S]*?<\/\1>/gi)].map((match) => match[0]); const lines = entries.slice(0, 40).map((entry) => { const title = inside(entry, "title") || "(no title)"; const date = inside(entry, "pubDate") || inside(entry, "updated") || inside(entry, "published") || inside(entry, "dc:date"); const link = inside(entry, "link") || /]*href="([^"]+)"/i.exec(entry)?.[1] || ""; const summary = (inside(entry, "description") || inside(entry, "summary")).slice(0, 300); return [`- ${title}`, date && ` ${date}`, link && ` ${link}`, summary && ` ${summary}`].filter(Boolean).join("\n"); }); console.log(cut([`# ${inside(body, "title") || url.host}`, `${url.href}`, `${entries.length} entries${entries.length > 40 ? ", the newest 40 here" : ""}.`, "", ...lines].join("\n"))); process.exit(0); } if (!/html|text\/plain/i.test(type) && type !== "") { console.error(`${url.href} is ${type.split(";")[0]}, not a page of words.`); process.exit(1); } const title = inside(body, "title"); const words = decode( body .replace(//g, " ") .replace(/<(head|script|style|noscript|svg|nav|header|footer|form|iframe|template)\b[\s\S]*?<\/\1>/gi, " ") .replace(/<(br|\/p|\/div|\/li|\/h[1-6]|\/tr|\/section|\/article)\b[^>]*>/gi, "\n") .replace(/]*>/gi, "\n- ") .replace(/]*>/gi, (_, level: string) => `\n${"#".repeat(Number(level))} `) .replace(/<[^>]+>/g, " "), ) .split("\n") .map((line) => line.replace(/[ \t ]+/g, " ").trim()) .filter((line, i, all) => line !== "" || (i > 0 && all[i - 1] !== "")) .join("\n") .trim(); const out = [`# ${title || url.host}`, url.href, "", words].join("\n"); console.log(cut(out)); if (words.length < 200) console.log("\nThis page gave little text: it may need a sign-in, or be drawn by scripts in the browser.");