/** * crawl — a platform-agnostic linked-text-document crawler. * * Fetches raw text starting from one URL, follows markdown `[label](url)` * and HTML `` links (both valid in CommonMark inline HTML, so * both extractors run on every document), and returns pages in deterministic * BFS discovery order. * * ZERO dependencies and ZERO internal imports: this module is fully * self-contained and can be published standalone or vendored verbatim. * Nothing here knows about MD-LD — the consumer decides how to interpret * the text (see "Consuming with mdld-parse" below). * * ── Cache ──────────────────────────────────────────────────────────────── * Inject any adapter implementing: * get(url) → Promise<{text, contentType, finalUrl, etag, lastModified, timestamp} | null> * set(url, e) → Promise * delete?(url)→ Promise * Cache failures are swallowed: a broken cache degrades to "no cache", * never to a failed crawl. Default: in-process LRU (`memoryCache`). * Conditional requests reuse stored ETag/Last-Modified. fetch runs with * `cache: 'no-store'` so this module's cache is the single authority. * * ── Guarantees ─────────────────────────────────────────────────────────── * - Deterministic: pages return in BFS discovery order, never completion order. * - Partial-result-safe: HTTP/network failures land in `errors`; the crawl * continues. 5xx/network failure with a cached copy → stale-if-error. * - Cancellable: pass `signal`; resolves with `aborted: true` plus partial results. * - Bounded: `maxDepth`, `maxPages` (default 100), optional `sameOrigin`, * http(s)-only protocol allow-list, binary content-types rejected. * * @example * // Generic use: crawl a docs site, get text + edges * const { pages, errors, aborted } = await crawl("/docs/index.md", { sameOrigin: true }); * for (const p of pages) console.log(p.url, "→", p.links.length, "outgoing links"); */ const HTTP_PROTOCOLS = new Set(["http:", "https:"]); const ACCEPT = "text/markdown, text/x-mdld, text/plain;q=0.9, text/html;q=0.8, application/xhtml+xml;q=0.8, */*;q=0.5"; const DEFAULT_MAX_DEPTH = 5; const DEFAULT_CONCURRENCY = 5; const DEFAULT_MAX_PAGES = 100; const DEFAULT_ACCEPT_RE = /\.(md|mdld|markdown|html?|xhtml)$/i; const BINARY_CT = /image\/|audio\/|video\/|font\/|application\/(octet-stream|zip|gzip|pdf|wasm|protobuf)/i; /** * In-process LRU cache. O(1) get/set, recency refreshed on read. * @param {number} [maxEntries=500] */ export function memoryCache(maxEntries = 500) { const map = new Map(); return { async get(url) { const entry = map.get(url); if (entry === undefined) return null; map.delete(url); map.set(url, entry); return entry; }, async set(url, entry) { if (map.has(url)) map.delete(url); map.set(url, entry); if (map.size > maxEntries) map.delete(map.keys().next().value); }, async delete(url) { map.delete(url); }, }; } // ═══════════════════════════ URL helpers ═══════════════════════════ /** Resolve + validate. Absolute http(s) URL without fragment, or null. */ function normalizeUrl(raw, base) { if (raw == null) return null; const s = String(raw).trim(); if (!s) return null; try { const url = new URL(s, base || undefined); if (!HTTP_PROTOCOLS.has(url.protocol)) return null; // no file:, javascript:, data:, mailto: url.hash = ""; return url.href; } catch { return null; } } /** Default target filter: docs extensions + extensionless clean URLs. */ function defaultAccept(url) { let file = url.slice(url.lastIndexOf("/") + 1); const q = file.indexOf("?"); if (q !== -1) file = file.slice(0, q); if (!file.includes(".")) return true; // SSR routes, clean URLs return DEFAULT_ACCEPT_RE.test(file); } /** Cheap hint for consumers (they decide how to interpret the text). */ function looksLikeHTML(contentType, text) { if (contentType) { const ct = contentType.toLowerCase(); if (ct.includes("html")) return true; if (/(markdown|mdld|json|javascript|css)/.test(ct)) return false; } const head = text.slice(0, 256).trimStart().slice(0, 32).toLowerCase(); return head.startsWith(" links and // HTML documents can carry markdown link syntax — scanning for both is the // only correct posture for mixed content. /** * Extract all http(s) links from a text document (markdown + HTML syntaxes). * Character-scanned: fence-aware, code-span-aware, comment-aware, and * `