@absolutejs/search 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1062 @@
1
+ // @bun
2
+ // src/web/evidence.ts
3
+ import { parseHTML } from "linkedom";
4
+
5
+ // src/web/transport.ts
6
+ import {
7
+ isPublicNetworkAddress,
8
+ networkAddressBlockReason,
9
+ pinnedPublicRequest
10
+ } from "@absolutejs/egress/transport";
11
+ import { lookup } from "dns/promises";
12
+ import { isIP } from "net";
13
+ import { brotliDecompressSync, gunzipSync, inflateSync } from "zlib";
14
+ var blockReasons = new Set([
15
+ "unsupported_protocol",
16
+ "url_credentials",
17
+ "nonstandard_port",
18
+ "local_hostname",
19
+ "empty_dns",
20
+ "ipv4_this_network",
21
+ "ipv4_private",
22
+ "ipv4_loopback",
23
+ "ipv4_multicast_reserved",
24
+ "ipv4_shared",
25
+ "ipv4_link_local",
26
+ "ipv4_protocol_assignment",
27
+ "ipv4_documentation",
28
+ "ipv4_transition",
29
+ "ipv4_benchmark",
30
+ "invalid_address",
31
+ "ipv6_non_global",
32
+ "ipv6_transition",
33
+ "ipv6_special",
34
+ "ipv6_documentation"
35
+ ]);
36
+ var transportCodes = new Set([
37
+ "ENOTFOUND",
38
+ "EAI_AGAIN",
39
+ "ECONNREFUSED",
40
+ "ECONNRESET",
41
+ "ETIMEDOUT",
42
+ "ENETUNREACH",
43
+ "EHOSTUNREACH",
44
+ "HPE_HEADER_OVERFLOW",
45
+ "ERR_RESPONSE_BODY_TOO_LARGE",
46
+ "ERR_BUFFER_TOO_LARGE",
47
+ "CERT_HAS_EXPIRED",
48
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
49
+ "SELF_SIGNED_CERT_IN_CHAIN",
50
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
51
+ "ERR_TLS_CERT_ALTNAME_INVALID",
52
+ "CERT_NOT_YET_VALID",
53
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
54
+ "Z_DATA_ERROR"
55
+ ]);
56
+ var webReadFailureDetails = (value) => {
57
+ if (!value || typeof value !== "object")
58
+ return;
59
+ const stage = Reflect.get(value, "stage");
60
+ if (!["url", "dns", "request", "decode", "navigation", "render"].includes(stage))
61
+ return;
62
+ const code = Reflect.get(value, "transportCode"), limit = Reflect.get(value, "limitBytes");
63
+ const reason = Reflect.get(value, "blockReason"), hop = Reflect.get(value, "redirectHop");
64
+ return {
65
+ stage,
66
+ ...typeof reason === "string" && blockReasons.has(reason) ? { blockReason: reason } : {},
67
+ ...Number.isInteger(hop) && hop >= 0 && hop <= 5 ? { redirectHop: hop } : {},
68
+ ...typeof code === "string" && transportCodes.has(code) ? { transportCode: code } : {},
69
+ ...Number.isSafeInteger(limit) && limit > 0 ? { limitBytes: limit } : {}
70
+ };
71
+ };
72
+ var webTransportFailure = (error, stage, limitBytes) => {
73
+ if (isWebReadError(error))
74
+ return error;
75
+ let current = error, transportCode;
76
+ for (let depth = 0;depth < 4 && current && typeof current === "object"; depth++) {
77
+ const code = Reflect.get(current, "code");
78
+ if (typeof code === "string" && transportCodes.has(code)) {
79
+ transportCode = code;
80
+ break;
81
+ }
82
+ current = Reflect.get(current, "cause");
83
+ }
84
+ let code = "fetch_failed";
85
+ if (transportCode === "ENOTFOUND")
86
+ code = "dns_not_found";
87
+ else if (transportCode === "EAI_AGAIN")
88
+ code = "dns_unavailable";
89
+ else if (transportCode === "HPE_HEADER_OVERFLOW")
90
+ code = "response_headers_too_large";
91
+ else if (["ERR_RESPONSE_BODY_TOO_LARGE", "ERR_BUFFER_TOO_LARGE"].includes(transportCode ?? ""))
92
+ code = "response_body_too_large";
93
+ else if (transportCode === "ETIMEDOUT" || error instanceof Error && error.name === "TimeoutError")
94
+ code = "timeout";
95
+ else if (error instanceof Error && error.name === "AbortError")
96
+ code = "aborted";
97
+ else if (transportCode?.includes("CERT") || transportCode === "UNABLE_TO_VERIFY_LEAF_SIGNATURE")
98
+ code = "tls_error";
99
+ else if (["ECONNREFUSED", "ECONNRESET", "ENETUNREACH", "EHOSTUNREACH"].includes(transportCode ?? ""))
100
+ code = "connection_failed";
101
+ else if (stage === "decode")
102
+ code = "response_decode_failed";
103
+ return new WebReadError(code, `Website retrieval failed (${code}).`, {
104
+ attempts: [],
105
+ failure: {
106
+ stage,
107
+ ...transportCode ? { transportCode } : {},
108
+ ...(code === "response_headers_too_large" || code === "response_body_too_large") && limitBytes ? { limitBytes } : {}
109
+ }
110
+ });
111
+ };
112
+ var diagnosticUrl = (value) => {
113
+ if (typeof value !== "string")
114
+ return;
115
+ try {
116
+ const url = new URL(value);
117
+ if (!["http:", "https:"].includes(url.protocol))
118
+ return;
119
+ return `${url.origin}${url.pathname}`;
120
+ } catch {
121
+ return;
122
+ }
123
+ };
124
+ var webReadDiagnostics = (value) => ({
125
+ failure: webReadFailureDetails(value.failure),
126
+ url: diagnosticUrl(value.url),
127
+ finalUrl: diagnosticUrl(value.finalUrl),
128
+ method: value.method === "http" || value.method === "browser" ? value.method : undefined,
129
+ attempts: Array.isArray(value.attempts) ? value.attempts.slice(0, 16).flatMap((attempt) => {
130
+ if (!attempt || typeof attempt !== "object" || !["http", "browser"].includes(attempt.method) || typeof attempt.status !== "string" || !/^[a-z_]{1,64}$/u.test(attempt.status))
131
+ return [];
132
+ return [
133
+ {
134
+ method: attempt.method,
135
+ status: attempt.status,
136
+ ...webReadFailureDetails(attempt.failure) ? { failure: webReadFailureDetails(attempt.failure) } : {},
137
+ ...Array.isArray(attempt.resourceFailures) ? {
138
+ resourceFailures: attempt.resourceFailures.slice(0, 8).flatMap((v) => {
139
+ const safe = webReadFailureDetails(v);
140
+ return safe ? [safe] : [];
141
+ })
142
+ } : {},
143
+ ...Number.isInteger(attempt.httpStatus) && attempt.httpStatus >= 100 && attempt.httpStatus <= 599 ? { httpStatus: attempt.httpStatus } : {},
144
+ ...Number.isInteger(attempt.extractedChars) && attempt.extractedChars >= 0 ? { extractedChars: attempt.extractedChars } : {}
145
+ }
146
+ ];
147
+ }) : []
148
+ });
149
+ var WEB_READ_ERROR = Symbol.for("@absolutejs/rag/WebReadError");
150
+
151
+ class WebReadError extends Error {
152
+ code;
153
+ diagnostics;
154
+ [WEB_READ_ERROR] = true;
155
+ constructor(code, message, diagnostics) {
156
+ super(message);
157
+ this.code = code;
158
+ this.diagnostics = diagnostics;
159
+ this.name = "WebReadError";
160
+ }
161
+ }
162
+ var isWebReadError = (error) => error instanceof Error && Reflect.get(error, WEB_READ_ERROR) === true && typeof Reflect.get(error, "code") === "string";
163
+ var isPublicWebAddress = (address) => isPublicNetworkAddress(address);
164
+ var blockedUrl = (reason, stage, redirectHop = 0) => new WebReadError("blocked_url", "Source excluded by public-network policy.", {
165
+ attempts: [],
166
+ failure: { stage, blockReason: reason, redirectHop }
167
+ });
168
+ var validatePublicWebUrl = (raw, redirectHop = 0) => {
169
+ let url;
170
+ try {
171
+ url = new URL(raw);
172
+ } catch {
173
+ throw new WebReadError("invalid_url", "Provide a valid public HTTP or HTTPS URL.");
174
+ }
175
+ if (!["http:", "https:"].includes(url.protocol))
176
+ throw blockedUrl("unsupported_protocol", "url", redirectHop);
177
+ if (url.username || url.password)
178
+ throw blockedUrl("url_credentials", "url", redirectHop);
179
+ if (url.port && !["80", "443"].includes(url.port))
180
+ throw blockedUrl("nonstandard_port", "url", redirectHop);
181
+ const host = url.hostname.replace(/^\[|\]$/gu, "").toLowerCase();
182
+ if (host === "localhost" || /\.(?:localhost|local|internal)$/u.test(host))
183
+ throw blockedUrl("local_hostname", "url", redirectHop);
184
+ if (isIP(host)) {
185
+ const reason = networkAddressBlockReason(host);
186
+ if (reason)
187
+ throw blockedUrl(reason, "url", redirectHop);
188
+ }
189
+ return url;
190
+ };
191
+ var fetchPublicWebResource = async (raw, options = {}) => {
192
+ const signal = options.signal ?? AbortSignal.timeout(15000);
193
+ const maxBytes = options.maxBytes ?? 5000000;
194
+ let url = validatePublicWebUrl(raw);
195
+ const redirects = [];
196
+ let method = options.method ?? "GET";
197
+ let body = options.body;
198
+ for (let hop = 0;hop <= 5; hop++) {
199
+ signal.throwIfAborted();
200
+ const host = url.hostname.replace(/^\[|\]$/gu, "");
201
+ const addresses = await lookup(host, { all: true }).catch((error) => {
202
+ throw webTransportFailure(error, "dns");
203
+ });
204
+ if (!addresses.length)
205
+ throw blockedUrl("empty_dns", "dns", hop);
206
+ for (const { address } of addresses) {
207
+ const reason = networkAddressBlockReason(address);
208
+ if (reason)
209
+ throw blockedUrl(reason, "dns", hop);
210
+ }
211
+ signal.throwIfAborted();
212
+ const selected = addresses.find(({ family }) => family === 4) ?? addresses[0];
213
+ const incoming = await pinnedPublicRequest(new Request(url, {
214
+ method,
215
+ body,
216
+ signal,
217
+ headers: {
218
+ "user-agent": "AbsoluteJSReader/1.0",
219
+ accept: "*/*",
220
+ "accept-encoding": "identity",
221
+ ...options.headers,
222
+ host: url.host
223
+ }
224
+ }), {
225
+ hostname: host,
226
+ address: selected.address,
227
+ maxResponseBytes: maxBytes,
228
+ maxResponseHeaderBytes: options.maxHeaderBytes ?? 65536
229
+ }).catch((error) => {
230
+ const failure = webTransportFailure(error, "request");
231
+ if (failure.diagnostics?.failure) {
232
+ if (failure.code === "response_headers_too_large")
233
+ failure.diagnostics.failure.limitBytes = options.maxHeaderBytes ?? 65536;
234
+ if (failure.code === "response_body_too_large")
235
+ failure.diagnostics.failure.limitBytes = maxBytes;
236
+ }
237
+ throw failure;
238
+ });
239
+ let data = new Uint8Array(await incoming.arrayBuffer());
240
+ const encoding = incoming.headers.get("content-encoding");
241
+ const limits = { maxOutputLength: maxBytes };
242
+ try {
243
+ if (encoding === "gzip")
244
+ data = gunzipSync(data, limits);
245
+ else if (encoding === "br")
246
+ data = brotliDecompressSync(data, limits);
247
+ else if (encoding === "deflate")
248
+ data = inflateSync(data, limits);
249
+ } catch (error) {
250
+ throw webTransportFailure(error, "decode", maxBytes);
251
+ }
252
+ const response = {
253
+ url: url.href,
254
+ status: incoming.status,
255
+ headers: Object.fromEntries([...incoming.headers].filter(([key]) => ![
256
+ "content-encoding",
257
+ "content-length",
258
+ "transfer-encoding",
259
+ "set-cookie"
260
+ ].includes(key))),
261
+ body: data
262
+ };
263
+ if (options.redirect === "manual")
264
+ return response;
265
+ if ([301, 302, 303, 307, 308].includes(response.status) && response.headers.location) {
266
+ const next = validatePublicWebUrl(new URL(response.headers.location, url).href, hop + 1);
267
+ redirects.push({
268
+ from: url.href,
269
+ to: next.href,
270
+ kind: "http",
271
+ status: response.status
272
+ });
273
+ url = next;
274
+ if (response.status === 303 || [301, 302].includes(response.status) && method === "POST") {
275
+ method = "GET";
276
+ body = undefined;
277
+ }
278
+ continue;
279
+ }
280
+ return { ...response, redirects };
281
+ }
282
+ throw new WebReadError("redirect_limit", "The site exceeded the redirect limit.");
283
+ };
284
+
285
+ // src/web/evidence.ts
286
+ var compact = (value) => (value ?? "").replace(/\s+/gu, " ").trim().slice(0, 600);
287
+ var publicHref = (value, base) => {
288
+ if (!value)
289
+ return null;
290
+ try {
291
+ return validatePublicWebUrl(new URL(value, base).href).href;
292
+ } catch {
293
+ return null;
294
+ }
295
+ };
296
+ var extractWebEvidence = (html, url) => {
297
+ const { document } = parseHTML(html);
298
+ const label = (element) => compact(element.getAttribute("aria-label")) || compact(element.getAttribute("title")) || compact(element.textContent) || compact(element.querySelector("img")?.getAttribute("alt"));
299
+ const links = [];
300
+ const seen = new Set;
301
+ for (const element of document.querySelectorAll("a[href]")) {
302
+ const href = publicHref(element.getAttribute("href"), url);
303
+ if (!href || seen.has(href) || links.length >= 100)
304
+ continue;
305
+ seen.add(href);
306
+ links.push({ url: href, label: label(element) });
307
+ }
308
+ const images = [];
309
+ const seenImages = new Set;
310
+ for (const element of document.querySelectorAll("img,svg,[role=img]")) {
311
+ if (images.length >= 80)
312
+ break;
313
+ const imageLabel = compact(element.getAttribute("alt") || (element.getAttribute("aria-labelledby") ?? "").split(/\s+/u).filter(Boolean).map((id) => document.getElementById(id)?.textContent ?? "").join(" ").trim() || element.getAttribute("aria-label") || element.querySelector("title")?.textContent || element.getAttribute("title"));
314
+ const section = element.closest("section,figure,article");
315
+ const imageUrl = publicHref(element.getAttribute("src") || element.getAttribute("data-src"), url);
316
+ const context = compact(section?.querySelector("h1,h2,h3,figcaption")?.textContent);
317
+ const key = `${imageUrl ?? ""}:${imageLabel}:${context}`;
318
+ if (!imageUrl && !imageLabel || seenImages.has(key))
319
+ continue;
320
+ seenImages.add(key);
321
+ images.push({ url: imageUrl, label: imageLabel, context });
322
+ }
323
+ const media = [];
324
+ for (const element of document.querySelectorAll("video,audio,video source,audio source,iframe,track")) {
325
+ if (media.length >= 30)
326
+ break;
327
+ const href = publicHref(element.getAttribute("src"), url);
328
+ if (!href)
329
+ continue;
330
+ const tag = element.tagName.toLowerCase();
331
+ media.push({
332
+ kind: tag === "track" ? "captions" : tag === "iframe" ? "embed" : tag === "audio" || element.closest("audio") ? "audio" : "video",
333
+ url: href,
334
+ label: compact(element.getAttribute("label")) || label(element)
335
+ });
336
+ }
337
+ return {
338
+ links,
339
+ images,
340
+ media,
341
+ canonicalUrl: publicHref(document.querySelector('link[rel="canonical"]')?.getAttribute("href") ?? null, url)
342
+ };
343
+ };
344
+ var hasIncompleteAppContent = (html) => {
345
+ const { document } = parseHTML(html);
346
+ if (!document.querySelector("script[src],script[type=module]"))
347
+ return false;
348
+ const main = document.querySelector("main,[role=main],#root,#app,#__next,app-root");
349
+ if (!main)
350
+ return false;
351
+ main.querySelectorAll("script,style,nav,header,footer").forEach((element) => element.remove());
352
+ const text = compact(main.textContent);
353
+ return text.length < 100 || /^(?:loading|please wait)(?:[.\s]|$)/iu.test(text);
354
+ };
355
+ var hasEmptyAppRoot = (html) => {
356
+ const { document } = parseHTML(html);
357
+ return Array.from(document.querySelectorAll("div,main,section")).some((element) => {
358
+ const attributes = Array.from(element.attributes);
359
+ const id = attributes.find((attribute) => attribute.name.toLowerCase() === "id")?.value.toLowerCase();
360
+ const classes = attributes.find((attribute) => attribute.name.toLowerCase() === "class")?.value.toLowerCase().split(/\s+/u) ?? [];
361
+ return (id !== undefined && ["root", "app", "__next"].includes(id) || classes.includes("todoapp")) && element.children.length === 0 && !element.textContent?.trim();
362
+ });
363
+ };
364
+
365
+ // src/web/text.ts
366
+ import { parseHTML as parseHTML2 } from "linkedom";
367
+ var websiteHtmlText = (html) => {
368
+ const { document } = parseHTML2(html);
369
+ document.querySelectorAll("script,style,template,noscript,svg,[hidden],[aria-hidden=true]").forEach((element) => element.remove());
370
+ const root = document.body?.textContent?.trim() ? document.body : document.documentElement;
371
+ const parts = [];
372
+ const blocks = /^(?:ADDRESS|ARTICLE|ASIDE|BLOCKQUOTE|BR|DIV|DL|DT|DD|FIGCAPTION|FIGURE|FOOTER|H[1-6]|HEADER|HR|LI|MAIN|NAV|OL|P|SECTION|TABLE|TD|TH|TR|UL)$/u;
373
+ const walk = (node) => {
374
+ if (node.nodeType === 3) {
375
+ parts.push((node.textContent ?? "").replace(/\s+/gu, " "));
376
+ return;
377
+ }
378
+ const block = blocks.test(node.nodeName);
379
+ if (block)
380
+ parts.push(`
381
+ `);
382
+ node.childNodes.forEach(walk);
383
+ if (block)
384
+ parts.push(`
385
+ `);
386
+ };
387
+ if (root)
388
+ walk(root);
389
+ return parts.join("").split(`
390
+ `).map((line) => line.trim()).filter(Boolean).join(`
391
+ `);
392
+ };
393
+ // src/web/website.ts
394
+ var pagePriority = (url, label) => {
395
+ const path = new URL(url).pathname;
396
+ if (/\/(?:news|thought-leadership|careers|contact)(?:\/|$)/iu.test(path))
397
+ return 0;
398
+ if (/client|customer|case.?stud|success/iu.test(path))
399
+ return 3;
400
+ if (/service|capabilit|solution|what.we.do/iu.test(path))
401
+ return 2;
402
+ if (/about|who.we.are|company/iu.test(path))
403
+ return 1;
404
+ if (/^(?:our )?(?:clients|customers|client successes|case studies)\b/iu.test(label))
405
+ return 3;
406
+ if (/^(?:our )?(?:services|capabilities|solutions|what we do)\b/iu.test(label))
407
+ return 2;
408
+ if (/^(?:about|who we are|company info)\b/iu.test(label))
409
+ return 1;
410
+ return 0;
411
+ };
412
+ var readWebsite = async (options) => {
413
+ const signal = options.signal ?? AbortSignal.timeout(75000);
414
+ const maxPages = Math.max(1, Math.min(options.maxPages ?? 8, 12));
415
+ const maxChars = Math.max(1000, Math.min(options.maxChars ?? 48000, 1e5));
416
+ const pages = [];
417
+ const queue = [
418
+ { url: options.url, label: "Requested page" }
419
+ ];
420
+ const visited = new Set;
421
+ const topicVisits = new Map;
422
+ let origin;
423
+ while (queue.length && pages.length < maxPages && !signal.aborted) {
424
+ const next = queue.shift();
425
+ let key;
426
+ try {
427
+ key = new URL(next.url);
428
+ } catch {
429
+ pages.push(await readWebpage({ ...options, signal }));
430
+ break;
431
+ }
432
+ key.hash = "";
433
+ if (visited.has(key.href))
434
+ continue;
435
+ visited.add(key.href);
436
+ const topic = pagePriority(next.url, next.label);
437
+ topicVisits.set(topic, (topicVisits.get(topic) ?? 0) + 1);
438
+ const page = await readWebpage({
439
+ ...options,
440
+ url: next.url,
441
+ maxChars,
442
+ signal: AbortSignal.any([signal, AbortSignal.timeout(30000)])
443
+ });
444
+ pages.push(page);
445
+ visited.add(page.finalUrl.split("#")[0]);
446
+ origin ??= new URL(page.finalUrl).origin;
447
+ if (page.status === "error")
448
+ continue;
449
+ const links = page.evidence.links.filter((link) => new URL(link.url).origin === origin && pagePriority(link.url, link.label) > 0 && !visited.has(link.url.split("#")[0]));
450
+ queue.push(...links);
451
+ queue.sort((a, b) => {
452
+ const aTopic = pagePriority(a.url, a.label);
453
+ const bTopic = pagePriority(b.url, b.label);
454
+ return (topicVisits.get(aTopic) ?? 0) - (topicVisits.get(bTopic) ?? 0) || bTopic - aTopic;
455
+ });
456
+ }
457
+ const first = pages[0] ?? await readWebpage({ ...options, signal });
458
+ const captionEvidence = [];
459
+ const tracks = [
460
+ ...new Set(pages.flatMap((page) => page.evidence.media.filter((media) => media.kind === "captions").map((media) => media.url)))
461
+ ].slice(0, 2);
462
+ for (const url of tracks) {
463
+ if (signal.aborted)
464
+ break;
465
+ try {
466
+ const response = await (options.fetchResource ?? fetchPublicWebResource)(url, {
467
+ signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]),
468
+ maxBytes: 250000
469
+ });
470
+ if (response.status !== 200)
471
+ throw new Error(`HTTP ${response.status}`);
472
+ const text = new TextDecoder().decode(response.body).replace(/^WEBVTT.*$/gmu, "").replace(/^.*-->.*$/gmu, "").replace(/^\d+$/gmu, "").replace(/<[^>]*>/gu, "").trim().slice(0, 6000);
473
+ captionEvidence.push({ url: response.url, text });
474
+ } catch (error) {
475
+ captionEvidence.push({
476
+ url,
477
+ text: "",
478
+ error: error instanceof Error ? error.message : "Caption retrieval failed"
479
+ });
480
+ }
481
+ }
482
+ const sources = pages.filter((page) => page.status !== "error" && page.text).map((page, index) => {
483
+ const title = (page.title || new URL(page.finalUrl).hostname).replace(/\s+/gu, " ").trim();
484
+ const label = title.replace(/[\\[\]]/gu, "\\$&");
485
+ const href = page.finalUrl.replace(/[<>]/gu, encodeURIComponent);
486
+ return {
487
+ id: `source-${index + 1}`,
488
+ title,
489
+ url: page.finalUrl,
490
+ citation: `[${label}](<${href}>)`,
491
+ inlineCitation: `[${index + 1}](<${href}>)`
492
+ };
493
+ });
494
+ let remainingDocumentChars = maxChars;
495
+ const documents = sources.flatMap((source) => {
496
+ const page = pages.find((item) => item.finalUrl === source.url && item.text);
497
+ if (!page)
498
+ return [];
499
+ const imageLabels = page.evidence.images.filter((image) => image.label).map((image) => `${image.context ? `${image.context}: ` : ""}${image.label}`);
500
+ const fullText = [
501
+ page.fullText ?? page.text,
502
+ ...imageLabels.length ? [
503
+ "Image labels supplied by the website (not independently verified customer relationships):",
504
+ ...imageLabels
505
+ ] : []
506
+ ].join(`
507
+ `);
508
+ const text = fullText.slice(0, Math.max(0, remainingDocumentChars));
509
+ remainingDocumentChars -= text.length;
510
+ return [
511
+ {
512
+ sourceId: source.id,
513
+ text,
514
+ fullText,
515
+ originalChars: fullText.length,
516
+ sourceTruncated: page.status !== "ok" || page.fullText === undefined && page.truncated,
517
+ truncated: page.fullText === undefined && page.truncated || text.length < fullText.length
518
+ }
519
+ ];
520
+ });
521
+ const evidenceText = pages.filter((page) => page.status !== "error").map((page) => `SOURCE: ${page.finalUrl}
522
+ CITATION: ${sources.find((source) => source.url === page.finalUrl)?.citation ?? page.finalUrl}
523
+ TITLE: ${page.title ?? "Untitled"}
524
+ ${page.text}`).join(`
525
+
526
+ `);
527
+ const readable = pages.filter((page) => page.status !== "error" && page.text);
528
+ const incomplete = pages.some((page) => page.status !== "ok") || signal.aborted;
529
+ const unvisited = queue.filter((link) => !visited.has(link.url.split("#")[0]));
530
+ return {
531
+ kind: "website_evidence",
532
+ documents,
533
+ sources,
534
+ citationRequirements: "The final answer must contain clickable Markdown source links, not just source names or bare domain mentions. Reuse sources[].citation beside the factual paragraph, list or table row it supports. Cite the actual supporting page, not the homepage for everything. Every factual section needs its supporting links. Do not invent sources or use unread links as evidence. Before responding, check that company facts, service descriptions, customer examples and numerical claims have supporting links; retrieve or omit unsupported claims. A list of large customers does not prove smaller customers are excluded. Preserve the brands actually named in the evidence; do not append parent companies, ownership relationships, current-account status, market rankings or rebrand history from memory. Label reasoned inferences as such. A verified brand change needs at most one short, cited sentence unless the user asks for its history.",
535
+ ...first,
536
+ fullText: undefined,
537
+ status: readable.length ? incomplete ? "partial" : "ok" : "error",
538
+ text: evidenceText.slice(0, maxChars),
539
+ truncated: evidenceText.length > maxChars || pages.some((page) => page.truncated),
540
+ pages: pages.map(({ text: _text, fullText: _fullText, ...page }) => page),
541
+ captionEvidence,
542
+ coverage: {
543
+ pagesRead: pages.length,
544
+ pageLimit: maxPages,
545
+ remainingRelevantLinks: [
546
+ ...new Set(unvisited.map((link) => link.url))
547
+ ].slice(0, 20),
548
+ deadlineReached: signal.aborted,
549
+ exhaustive: false,
550
+ stopReason: signal.aborted ? "deadline" : unvisited.length ? "page_limit" : "links_exhausted",
551
+ incompleteReads: pages.filter((page) => page.status !== "ok" || page.fullText === undefined && page.truncated).map((page) => ({
552
+ url: page.finalUrl,
553
+ status: page.status,
554
+ truncated: page.fullText === undefined && page.truncated,
555
+ error: page.error
556
+ }))
557
+ },
558
+ citationGuidance: "Answer the user's question first, with exact source page URLs. Distinguish retrieved facts from inference. A page limit bounds this call, not the research task: if a material question remains unanswered, read the relevant remaining links in another call, using maxPages 1 for targeted detail pages. Do not stop with a list of next steps when those reads are needed to finish the request. Conversely, unvisited links do not by themselves mean the answer is incomplete. Report only gaps that materially limit the answer, unless a retrieval audit was explicitly requested. Successful browser fallback is a completed read, not an incomplete read. Normally summarize a redirected destination in one brief sentence; omit HTTP codes, hop chains, character counts and rendering mechanics unless explicitly requested for debugging. A redirect alone does not prove a rebrand; verify that claim from a source. Image labels do not establish customer relationships and media URLs are not watched video evidence."
559
+ };
560
+ };
561
+ // src/web/remote.ts
562
+ var parseWebsiteServiceResult = (value) => {
563
+ if (!value || typeof value !== "object" || Array.isArray(value))
564
+ throw new Error("Website reader returned an invalid response");
565
+ const row = value;
566
+ if (typeof row.text !== "string" || !["ok", "partial", "error"].includes(String(row.status)))
567
+ throw new Error("Website reader returned an invalid response");
568
+ if (row.limitations !== undefined && (!Array.isArray(row.limitations) || !row.limitations.every((item) => typeof item === "string")))
569
+ throw new Error("Invalid website limitations");
570
+ if (row.sources !== undefined && (!Array.isArray(row.sources) || !row.sources.every((source) => {
571
+ if (!source || typeof source !== "object" || typeof source.url !== "string")
572
+ return false;
573
+ try {
574
+ const url = new URL(source.url);
575
+ return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password;
576
+ } catch {
577
+ return false;
578
+ }
579
+ })))
580
+ throw new Error("Invalid website sources");
581
+ return row;
582
+ };
583
+ var createWebsiteReaderClient = (options) => async (input) => {
584
+ const timeoutMs = options.timeoutMs ?? 85000, reserveMs = options.fallback ? options.fallbackReserveMs ?? 15000 : 0;
585
+ if (!(reserveMs >= 0 && timeoutMs > reserveMs))
586
+ throw new Error("Reader deadline must reserve fallback time");
587
+ const signal = AbortSignal.any([
588
+ ...input.signal ? [input.signal] : [],
589
+ AbortSignal.timeout(timeoutMs)
590
+ ]);
591
+ signal.throwIfAborted();
592
+ const request = {
593
+ url: input.url,
594
+ maxPages: input.maxPages ?? 8,
595
+ mode: input.mode ?? "auto"
596
+ };
597
+ if (!Number.isInteger(request.maxPages) || request.maxPages < 1 || request.maxPages > 12)
598
+ throw new Error("Reader page limit must be 1\u201312");
599
+ try {
600
+ const response = await (options.fetch ?? fetch)(options.endpoint, {
601
+ method: "POST",
602
+ headers: { "content-type": "application/json" },
603
+ body: JSON.stringify(request),
604
+ signal: AbortSignal.any([
605
+ signal,
606
+ AbortSignal.timeout(timeoutMs - reserveMs)
607
+ ])
608
+ });
609
+ if (response.status === 503)
610
+ return {
611
+ status: "error",
612
+ text: "",
613
+ error: {
614
+ code: "reader_busy",
615
+ message: "Website reader is busy. Retry shortly; this is not evidence of missing information.",
616
+ retryAfterSeconds: 2
617
+ }
618
+ };
619
+ if (response.status === 502 && !options.fallback) {
620
+ const value = await response.json().catch(() => null);
621
+ if (value && typeof value === "object") {
622
+ const failure = Reflect.get(value, "error");
623
+ const code = failure && typeof failure === "object" ? Reflect.get(failure, "code") : undefined;
624
+ if ([
625
+ "reader_deadline",
626
+ "reader_worker_exit",
627
+ "reader_protocol_error",
628
+ "reader_parse_failed",
629
+ "renderer_disconnected",
630
+ "reader_failed"
631
+ ].includes(code))
632
+ return {
633
+ status: "error",
634
+ text: "",
635
+ ...webReadDiagnostics(value),
636
+ error: {
637
+ code,
638
+ message: `Isolated website reader failed (${code}).`
639
+ }
640
+ };
641
+ }
642
+ }
643
+ if (!response.ok)
644
+ throw new Error(`Website reader returned ${response.status}`);
645
+ const result = parseWebsiteServiceResult(await response.json());
646
+ signal.throwIfAborted();
647
+ return result;
648
+ } catch (error) {
649
+ signal.throwIfAborted();
650
+ if (!options.fallback)
651
+ return {
652
+ status: "error",
653
+ text: "",
654
+ error: {
655
+ code: "reader_unavailable",
656
+ message: "Website reader unavailable. Retry shortly; no website evidence was retrieved."
657
+ }
658
+ };
659
+ const result = parseWebsiteServiceResult(await options.fallback({ ...request, signal }));
660
+ signal.throwIfAborted();
661
+ return {
662
+ ...result,
663
+ limitations: [
664
+ ...result.limitations ?? [],
665
+ "Browser service unavailable; static fallback may omit JavaScript-only evidence."
666
+ ]
667
+ };
668
+ }
669
+ };
670
+ var createWebpageReaderClient = (options) => {
671
+ const read = createWebsiteReaderClient(options);
672
+ return async (input) => {
673
+ const result = await read({
674
+ url: input.url,
675
+ maxPages: 1,
676
+ mode: input.mode,
677
+ signal: input.signal
678
+ });
679
+ if (result.status === "error") {
680
+ const error = result.error;
681
+ throw new WebReadError(error?.code ?? "reader_unavailable", error?.message ?? "Isolated page read failed", webReadDiagnostics({ ...result, url: input.url }));
682
+ }
683
+ const documents = result.documents;
684
+ const sources = result.sources;
685
+ const source = sources?.length === 1 ? sources[0] : undefined;
686
+ const document = documents?.length === 1 ? documents[0] : undefined;
687
+ if (!source || !document || source.id !== document.sourceId || typeof document.text !== "string" || typeof result.finalUrl !== "string" || source.url !== result.finalUrl || result.url !== input.url || typeof result.fetchedAt !== "string" || !Number.isFinite(Date.parse(result.fetchedAt)) || !["http", "browser"].includes(String(result.method)) || !Array.isArray(result.attempts) || !Array.isArray(result.redirects) || !result.evidence || typeof result.evidence !== "object")
688
+ throw new Error("Reader did not return attributable single-page evidence");
689
+ const evidence = result.evidence;
690
+ if (![evidence.links, evidence.images, evidence.media].every(Array.isArray))
691
+ throw new Error("Invalid page evidence");
692
+ const limit = Math.max(1000, Math.min(input.maxChars ?? 24000, 1e5));
693
+ const fullText = typeof document.fullText === "string" ? document.fullText : document.text;
694
+ return {
695
+ status: result.status,
696
+ url: input.url,
697
+ finalUrl: result.finalUrl,
698
+ title: typeof result.title === "string" ? result.title : null,
699
+ text: fullText.slice(0, limit),
700
+ fullText,
701
+ originalChars: fullText.length,
702
+ method: result.method,
703
+ truncated: result.truncated === true || document.truncated === true || document.text.length > limit,
704
+ fetchedAt: result.fetchedAt,
705
+ attempts: result.attempts,
706
+ redirects: result.redirects,
707
+ evidence,
708
+ limitations: result.limitations ?? []
709
+ };
710
+ };
711
+ };
712
+ // src/web/map.ts
713
+ var MAX_SITEMAPS = 20;
714
+ var locs = (xml) => [...xml.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/giu)].map((match) => (match[1] ?? "").replace(/&amp;/gu, "&").replace(/&lt;/gu, "<").replace(/&gt;/gu, ">").replace(/&quot;/gu, '"').replace(/&apos;/gu, "'"));
715
+ var sameOrigin = (origin, candidate) => {
716
+ try {
717
+ const url = new URL(candidate);
718
+ url.hash = "";
719
+ return url.origin === origin ? url.toString() : null;
720
+ } catch {
721
+ return null;
722
+ }
723
+ };
724
+ var mapWebsite = async (options) => {
725
+ const fetchResource = options.fetchResource ?? fetchPublicWebResource;
726
+ const signal = options.signal ?? AbortSignal.timeout(45000);
727
+ const maxUrls = Math.max(1, Math.min(options.maxUrls ?? 500, 5000));
728
+ const { origin } = new URL(options.url);
729
+ const text = async (url) => {
730
+ try {
731
+ const response = await fetchResource(url, { signal });
732
+ return response.status >= 200 && response.status < 300 ? new TextDecoder().decode(response.body) : null;
733
+ } catch (error) {
734
+ if (signal.aborted)
735
+ throw error;
736
+ return null;
737
+ }
738
+ };
739
+ const robots = await text(`${origin}/robots.txt`) ?? "";
740
+ const queue = [
741
+ ...robots.matchAll(/^\s*sitemap\s*:\s*(\S+)/gimu)
742
+ ].flatMap((match) => sameOrigin(origin, match[1] ?? "") ?? []);
743
+ if (queue.length === 0)
744
+ queue.push(`${origin}/sitemap.xml`);
745
+ const sitemaps = [];
746
+ const urls = new Set;
747
+ let truncated = false;
748
+ while (queue.length > 0 && sitemaps.length < MAX_SITEMAPS) {
749
+ const sitemap = queue.shift();
750
+ if (sitemaps.includes(sitemap))
751
+ continue;
752
+ const xml = await text(sitemap);
753
+ if (!xml || !/<(?:urlset|sitemapindex)\b/iu.test(xml))
754
+ continue;
755
+ sitemaps.push(sitemap);
756
+ const entries = locs(xml).flatMap((loc) => sameOrigin(origin, loc) ?? []);
757
+ if (/<sitemapindex\b/iu.test(xml)) {
758
+ queue.push(...entries);
759
+ continue;
760
+ }
761
+ for (const entry of entries) {
762
+ if (urls.size >= maxUrls) {
763
+ truncated = true;
764
+ break;
765
+ }
766
+ urls.add(entry);
767
+ }
768
+ }
769
+ if (queue.length > 0)
770
+ truncated = true;
771
+ if (urls.size > 0)
772
+ return {
773
+ sitemaps,
774
+ source: "sitemap",
775
+ truncated,
776
+ url: options.url,
777
+ urls: [...urls]
778
+ };
779
+ const home = await readWebpage({
780
+ fetchResource,
781
+ render: options.render,
782
+ signal,
783
+ url: options.url
784
+ });
785
+ const linked = [
786
+ home.finalUrl,
787
+ ...home.evidence.links.map((link) => link.url)
788
+ ].flatMap((link) => sameOrigin(origin, link) ?? []);
789
+ const unique = [...new Set(linked)];
790
+ return {
791
+ sitemaps,
792
+ source: "links",
793
+ truncated: unique.length > maxUrls,
794
+ url: options.url,
795
+ urls: unique.slice(0, maxUrls)
796
+ };
797
+ };
798
+ // src/web/extract.ts
799
+ import { Value } from "@sinclair/typebox/value";
800
+ var extractWebpage = async (options) => {
801
+ const { schema, extract, instructions, ...read } = options;
802
+ const signal = read.signal ?? AbortSignal.timeout(90000);
803
+ const page = await readWebpage({
804
+ ...read,
805
+ maxChars: read.maxChars ?? 1e5,
806
+ signal
807
+ });
808
+ if (page.status === "error" || !page.text)
809
+ return {
810
+ error: page.error ?? {
811
+ code: "empty_page",
812
+ message: "The page had no readable text to extract from."
813
+ },
814
+ page,
815
+ status: "error"
816
+ };
817
+ const received = await extract({
818
+ instructions,
819
+ schema,
820
+ signal,
821
+ text: page.fullText ?? page.text,
822
+ title: page.title,
823
+ url: page.finalUrl
824
+ });
825
+ if (!Value.Check(schema, received))
826
+ return {
827
+ error: {
828
+ code: "schema_mismatch",
829
+ message: [...Value.Errors(schema, received)].slice(0, 5).map((error) => `${error.path || "/"}: ${error.message}`).join("; ") || "The extracted data did not match the schema."
830
+ },
831
+ page,
832
+ received,
833
+ status: "error"
834
+ };
835
+ return { data: received, page, status: "ok" };
836
+ };
837
+
838
+ // src/web/index.ts
839
+ var messageFor = (error) => error instanceof Error ? error.message : "Website retrieval failed.";
840
+ var codeFor = (error) => isWebReadError(error) ? error.code : error instanceof Error && /^(?:AbortError|TimeoutError)$/u.test(error.name) ? "timeout" : "fetch_failed";
841
+ var cleanHtml = websiteHtmlText;
842
+ var titleOf = (html) => {
843
+ const title = /<title\b[^>]*>([\s\S]*?)<\/title>/iu.exec(html)?.[1];
844
+ return title ? websiteHtmlText(`<html><body>${title}</body></html>`).replace(/\s+/gu, " ").trim() || null : null;
845
+ };
846
+ var isPlainText = (mime) => mime === "" || /^text\/|\/(?:json|xml|csv|markdown)\b|\+(?:json|xml)\b/iu.test(mime);
847
+ var isShell = (html, text) => text.length < 300 || hasIncompleteAppContent(html) || /(?:enable|requires?|turn on)\s+javascript|javascript\s+(?:is\s+)?(?:disabled|required)/iu.test(text) || hasEmptyAppRoot(html);
848
+ var isChallenge = (text) => /verify (?:that )?you are human|checking your browser|just a moment|enable javascript and cookies to continue|access denied/iu.test(text.slice(0, 1000));
849
+ var readWebpage = async (options) => {
850
+ const attempts = [];
851
+ const redirects = [];
852
+ const limitations = [
853
+ "A page read is not exhaustive company research. Image labels are evidence supplied by the site, not independently verified customer relationships. Videos are not watched or transcribed unless caption text is returned."
854
+ ];
855
+ let evidence = {
856
+ links: [],
857
+ images: [],
858
+ media: [],
859
+ canonicalUrl: null
860
+ };
861
+ const signal = options.signal ?? AbortSignal.timeout(45000);
862
+ const maxChars = Math.max(1000, Math.min(options.maxChars ?? 24000, 1e5));
863
+ let finalUrl = options.url, text = "", title = null, method = "http";
864
+ let failure;
865
+ const result = (status, error) => ({
866
+ status,
867
+ url: options.url,
868
+ finalUrl,
869
+ title,
870
+ text: text.slice(0, maxChars),
871
+ fullText: text,
872
+ originalChars: text.length,
873
+ method,
874
+ truncated: text.length > maxChars,
875
+ attempts,
876
+ redirects,
877
+ evidence,
878
+ limitations,
879
+ failure,
880
+ fetchedAt: new Date().toISOString(),
881
+ ...error ? { error } : {}
882
+ });
883
+ try {
884
+ validatePublicWebUrl(options.url);
885
+ let response;
886
+ try {
887
+ response = await (options.fetchResource ?? fetchPublicWebResource)(options.url, { signal, maxBytes: 5000000 });
888
+ } catch (error) {
889
+ if (isWebReadError(error))
890
+ failure = webReadFailureDetails(error.diagnostics?.failure);
891
+ attempts.push({
892
+ method: "http",
893
+ status: codeFor(error),
894
+ ...isWebReadError(error) ? { failure: error.diagnostics?.failure } : {}
895
+ });
896
+ if (isWebReadError(error) && [
897
+ "blocked_url",
898
+ "dns_not_found",
899
+ "dns_unavailable",
900
+ "tls_error",
901
+ "response_headers_too_large",
902
+ "response_body_too_large",
903
+ "aborted"
904
+ ].includes(error.code))
905
+ throw error;
906
+ if (!options.render)
907
+ throw error;
908
+ }
909
+ let needsBrowser = options.mode === "browser" || !response;
910
+ if (response) {
911
+ finalUrl = response.url;
912
+ redirects.push(...response.redirects ?? []);
913
+ const mime = response.headers["content-type"] ?? "";
914
+ const raw = new TextDecoder().decode(response.body);
915
+ const html = /html/iu.test(mime) || /^\s*(?:<!doctype html|<html)/iu.test(raw);
916
+ if (response.status >= 200 && response.status < 300) {
917
+ if (html) {
918
+ evidence = extractWebEvidence(raw, finalUrl);
919
+ text = cleanHtml(raw);
920
+ title = titleOf(raw);
921
+ needsBrowser ||= isShell(raw, text) || isChallenge(text);
922
+ } else {
923
+ if (isPlainText(mime)) {
924
+ text = raw.replace(/\r\n?/gu, `
925
+ `).trim();
926
+ } else if (options.readDocument) {
927
+ const doc = await options.readDocument({
928
+ body: response.body,
929
+ contentType: mime,
930
+ url: finalUrl
931
+ });
932
+ text = doc.text;
933
+ title = doc.title ?? null;
934
+ } else
935
+ return result("error", {
936
+ code: "unsupported_content",
937
+ message: `Website returned ${mime || "an unknown content type"}, which needs a document reader.`
938
+ });
939
+ }
940
+ attempts.push({
941
+ method: "http",
942
+ status: text ? "extracted" : "empty",
943
+ httpStatus: response.status,
944
+ extractedChars: text.length
945
+ });
946
+ } else {
947
+ attempts.push({
948
+ method: "http",
949
+ status: "http_error",
950
+ httpStatus: response.status
951
+ });
952
+ if (![401, 403, 429, 503].includes(response.status))
953
+ return result("error", {
954
+ code: "http_error",
955
+ message: `Website returned HTTP ${response.status}.`
956
+ });
957
+ needsBrowser = true;
958
+ }
959
+ }
960
+ if (needsBrowser) {
961
+ if (!options.render)
962
+ return result(text ? "partial" : "error", {
963
+ code: "rendering_required",
964
+ message: "Static HTML was incomplete. Browser rendering is required; this is not evidence that the site has no information."
965
+ });
966
+ try {
967
+ method = "browser";
968
+ const rendered = await options.render(finalUrl, { signal });
969
+ finalUrl = rendered.url;
970
+ validatePublicWebUrl(finalUrl);
971
+ redirects.push(...rendered.redirects ?? []);
972
+ const previous = { text, title, evidence };
973
+ evidence = extractWebEvidence(rendered.html, finalUrl);
974
+ if (rendered.settled === false)
975
+ limitations.push("Browser content did not reach the readability threshold before the wait limit.");
976
+ text = rendered.text?.trim() ?? cleanHtml(rendered.html);
977
+ title = titleOf(rendered.html) ?? title;
978
+ attempts.push({
979
+ method: "browser",
980
+ ...rendered.resourceFailures?.length ? { resourceFailures: rendered.resourceFailures } : {},
981
+ status: text ? "extracted" : "empty",
982
+ httpStatus: rendered.status,
983
+ extractedChars: text.length
984
+ });
985
+ const renderingFailure = (error) => {
986
+ if (previous.text && !isChallenge(previous.text)) {
987
+ text = previous.text;
988
+ title = previous.title;
989
+ evidence = previous.evidence;
990
+ return result("partial", error);
991
+ }
992
+ return result("error", error);
993
+ };
994
+ if (rendered.status === 401)
995
+ return renderingFailure({
996
+ code: "authentication_required",
997
+ message: "This page requires sign-in."
998
+ });
999
+ if ([403, 429].includes(rendered.status) || isChallenge(text))
1000
+ return renderingFailure({
1001
+ code: "access_blocked",
1002
+ message: "The website blocked automated access or presented a verification challenge."
1003
+ });
1004
+ if (rendered.status >= 400)
1005
+ return renderingFailure({
1006
+ code: "http_error",
1007
+ message: `Website returned HTTP ${rendered.status}.`
1008
+ });
1009
+ if (!text || /^(?:loading[.\s]*|please wait[.\s]*)$/iu.test(text) || /(?:enable|requires?)\s+javascript/iu.test(text))
1010
+ return renderingFailure({
1011
+ code: "rendering_incomplete",
1012
+ message: "The page still provided no usable text after browser rendering."
1013
+ });
1014
+ if (rendered.settled === false)
1015
+ return result("partial", {
1016
+ code: "rendering_incomplete",
1017
+ message: "Some content was extracted, but the application did not reach the readability threshold. Do not treat it as complete."
1018
+ });
1019
+ } catch (error) {
1020
+ if (isWebReadError(error))
1021
+ failure = webReadFailureDetails(error.diagnostics?.failure);
1022
+ attempts.push({
1023
+ method: "browser",
1024
+ status: codeFor(error),
1025
+ ...isWebReadError(error) ? { failure: error.diagnostics?.failure } : {}
1026
+ });
1027
+ return result(text ? "partial" : "error", {
1028
+ code: codeFor(error),
1029
+ message: messageFor(error)
1030
+ });
1031
+ }
1032
+ }
1033
+ return text ? result("ok") : result("error", {
1034
+ code: "no_readable_content",
1035
+ message: "The page returned no readable text."
1036
+ });
1037
+ } catch (error) {
1038
+ if (isWebReadError(error))
1039
+ failure = webReadFailureDetails(error.diagnostics?.failure);
1040
+ return result("error", {
1041
+ code: codeFor(error),
1042
+ message: messageFor(error)
1043
+ });
1044
+ }
1045
+ };
1046
+ export {
1047
+ WebReadError,
1048
+ createWebpageReaderClient,
1049
+ createWebsiteReaderClient,
1050
+ extractWebpage,
1051
+ fetchPublicWebResource,
1052
+ isPublicWebAddress,
1053
+ isWebReadError,
1054
+ mapWebsite,
1055
+ parseWebsiteServiceResult,
1056
+ readWebpage,
1057
+ readWebsite,
1058
+ validatePublicWebUrl,
1059
+ webReadDiagnostics,
1060
+ webReadFailureDetails,
1061
+ webTransportFailure
1062
+ };