fetched-web-sources.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import type { ContextualWebCitation } from './markdown-source-citation.js';
  2. const MAX_DOCUMENT_CHARS = 2_000_000;
  3. const MAX_DOCUMENT_SOURCES = 100;
  4. /**
  5. * Read source metadata from a fetched document, not arbitrary outbound links.
  6. * Search hits are supported only for the known DuckDuckGo HTML result markup.
  7. * Keeping this pure lets persisted messages and both runtime hosts use the same evidence.
  8. */
  9. export function collectFetchedWebSources(
  10. source: ContextualWebCitation,
  11. content: unknown,
  12. ): ContextualWebCitation[] {
  13. const pageUrl = httpUrl(source.url);
  14. if (!pageUrl) return [];
  15. const html = documentText(content)
  16. .replace(/<!--[\s\S]*?-->/gu, '')
  17. .replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/giu, '');
  18. const head = html.split(/<body\b/iu, 1)[0]?.slice(0, 65_536) ?? '';
  19. const title = /<title\b[^>]*>([^<]*)<\/title\s*>/iu.exec(head)?.[1];
  20. const name = title ? decodeHtml(title).trim() : source.name;
  21. let canonical: string | undefined;
  22. let favicon = source.favicon;
  23. for (const match of head.matchAll(/<link\b[^>]*>/giu)) {
  24. const attrs = attributes(match[0]);
  25. const rel = attrs.rel?.toLowerCase().split(/\s+/u) ?? [];
  26. if (rel.includes('canonical')) canonical ??= httpUrl(attrs.href, pageUrl);
  27. if (rel.includes('icon') && !attrs.mask) favicon ??= httpUrl(attrs.href, pageUrl);
  28. }
  29. const primary = { ...source, ...(favicon ? { favicon } : {}) };
  30. const output: ContextualWebCitation[] = [primary];
  31. if (canonical && canonical !== pageUrl) output.push({ ...primary, name, url: canonical });
  32. // Baike's /item/<title> route is its named alias. Older externalized fetches
  33. // retain the official document title but not the HTML head. Do not infer
  34. // aliases from answer labels, domains alone, or an arbitrary numeric ID.
  35. const baikeAlias = baikeTitleUrl(pageUrl, name);
  36. if (baikeAlias) output.push({ ...primary, name, url: baikeAlias });
  37. collectDuckDuckGoResults(pageUrl, html, output);
  38. const unique = new Map<string, ContextualWebCitation>();
  39. for (const entry of output) {
  40. if (!unique.has(entry.url)) unique.set(entry.url, entry);
  41. }
  42. return Array.from(unique.values());
  43. }
  44. function documentText(content: unknown, depth = 0): string {
  45. if (depth > 8) return '';
  46. if (typeof content === 'string') return content.slice(0, MAX_DOCUMENT_CHARS);
  47. if (Array.isArray(content)) {
  48. let text = '';
  49. for (const entry of content) {
  50. text += documentText(entry, depth + 1).slice(0, MAX_DOCUMENT_CHARS - text.length);
  51. if (text.length >= MAX_DOCUMENT_CHARS) break;
  52. }
  53. return text;
  54. }
  55. if (!content || typeof content !== 'object') return '';
  56. const record = content as Record<string, unknown>;
  57. return documentText(record.content ?? record.text ?? record.output, depth + 1);
  58. }
  59. function httpUrl(value: string | undefined, base?: string): string | undefined {
  60. if (!value?.trim()) return undefined;
  61. try {
  62. const url = new URL(value, base);
  63. if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) return;
  64. return url.href;
  65. } catch {
  66. return undefined;
  67. }
  68. }
  69. function decodeHtml(value: string): string {
  70. const entities: Record<string, string> = { amp: '&', quot: '"', apos: "'", lt: '<', gt: '>' };
  71. return value.replace(/&(#x[0-9a-f]+|#\d+|amp|quot|apos|lt|gt);/giu, (raw, entity: string) => {
  72. if (!entity.startsWith('#')) return entities[entity.toLowerCase()] ?? raw;
  73. const hex = entity[1]?.toLowerCase() === 'x';
  74. const point = Number.parseInt(entity.slice(hex ? 2 : 1), hex ? 16 : 10);
  75. return point > 0 && point <= 0x10ffff ? String.fromCodePoint(point) : raw;
  76. });
  77. }
  78. function attributes(tag: string): Record<string, string> {
  79. const output: Record<string, string> = {};
  80. for (const match of tag.matchAll(/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gu)) {
  81. const key = match[1]?.toLowerCase();
  82. if (key) output[key] = decodeHtml(match[2] ?? match[3] ?? match[4] ?? '');
  83. }
  84. return output;
  85. }
  86. function baikeTitleUrl(pageUrl: string, title: string): string | undefined {
  87. const url = new URL(pageUrl);
  88. if (url.hostname !== 'baike.baidu.com' || !/^\/item\/[^/]+\/?$/u.test(url.pathname)) {
  89. return undefined;
  90. }
  91. const name = /^(.{1,120})_百度百科$/u.exec(title)?.[1]?.trim();
  92. if (!name || /[/?#]/u.test(name)) return undefined;
  93. return `${url.origin}/item/${encodeURIComponent(name)}`;
  94. }
  95. function collectDuckDuckGoResults(
  96. pageUrl: string,
  97. html: string,
  98. output: ContextualWebCitation[],
  99. ): void {
  100. const page = new URL(pageUrl);
  101. if (
  102. !['duckduckgo.com', 'html.duckduckgo.com'].includes(page.hostname) ||
  103. !/^\/html\/?$/u.test(page.pathname)
  104. ) {
  105. return;
  106. }
  107. for (const match of html.matchAll(/<a\b([^>]*)>([\s\S]*?)<\/a\s*>/giu)) {
  108. if (output.length >= MAX_DOCUMENT_SOURCES) break;
  109. const attrs = attributes(match[1] ?? '');
  110. if (!attrs.class?.split(/\s+/u).includes('result__a')) continue;
  111. let url = httpUrl(attrs.href, pageUrl);
  112. if (!url) continue;
  113. const link = new URL(url);
  114. if (['duckduckgo.com', 'html.duckduckgo.com'].includes(link.hostname)) {
  115. if (link.pathname !== '/l/') continue;
  116. url = httpUrl(link.searchParams.get('uddg') ?? undefined);
  117. }
  118. const name = decodeHtml((match[2] ?? '').replace(/<[^>]*>/gu, '')).trim();
  119. if (url && name) output.push({ url, name, evidence: name });
  120. }
  121. }