pi-unsloth-webtools 0.8.0 → 0.9.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.
package/web-render.ts DELETED
@@ -1,100 +0,0 @@
1
- import { collapseWhitespace } from "./html-to-md.ts";
2
- import { checkUrlAccess, MAX_SIGNAL_TIMEOUT_MS, normalizeUrlScheme, type WebsitePolicy } from "./web-access.ts";
3
- import { parseLocalPath, resolveAndValidateHost, truncatePageText } from "./web-fetch.ts";
4
-
5
- const DEFAULT_RENDER_TIMEOUT_MS = 60_000;
6
- const JINA_READER_URL = "https://r.jina.ai/";
7
- const CANCELLED_MESSAGE = "Failed to render URL: cancelled.";
8
- const TIMED_OUT_MESSAGE = "Failed to render URL: timed out.";
9
- const LOCAL_FILE_MESSAGE = "Blocked: the Jina Reader cannot fetch local files.";
10
- const EMPTY_READER_MESSAGE = "Failed to render URL: the Jina Reader returned no content.";
11
-
12
- export interface RenderPageOptions {
13
- timeoutMs?: number;
14
- maxChars?: number;
15
- signal?: AbortSignal;
16
- websitePolicy?: WebsitePolicy | null;
17
- apiKey?: string;
18
- }
19
-
20
- interface JinaReaderData {
21
- title?: string;
22
- url?: string;
23
- content?: string;
24
- }
25
-
26
- interface JinaReaderPayload {
27
- data?: JinaReaderData;
28
- }
29
-
30
- function clampTimeout(value: number | undefined): number {
31
- if (value === undefined || !Number.isFinite(value)) return DEFAULT_RENDER_TIMEOUT_MS;
32
- return Math.min(MAX_SIGNAL_TIMEOUT_MS, Math.max(1, Math.floor(value)));
33
- }
34
-
35
- function budgetMessage(caller: AbortSignal | undefined, signal: AbortSignal): string | null {
36
- if (caller?.aborted) return CANCELLED_MESSAGE;
37
- if (signal.aborted) return TIMED_OUT_MESSAGE;
38
- return null;
39
- }
40
-
41
- async function readerErrorDetail(response: Response): Promise<string> {
42
- try {
43
- const body = (await response.json()) as { readableMessage?: unknown; message?: unknown; detail?: unknown };
44
- const detail = [body.readableMessage, body.message, body.detail].find(
45
- (value) => typeof value === "string" && value.trim().length > 0,
46
- );
47
- if (detail) return `${response.status} ${detail}`;
48
- } catch {}
49
- return `${response.status} ${response.statusText}`.trim();
50
- }
51
-
52
- function formatRenderedPage(data: JinaReaderData, fallbackUrl: string, maxChars: number | undefined): string {
53
- const title = collapseWhitespace(String(data.title ?? ""));
54
- const finalUrl = collapseWhitespace(String(data.url ?? "")) || fallbackUrl;
55
- const content = String(data.content ?? "").trim();
56
- if (!content) return truncatePageText("", maxChars);
57
- const header: string[] = [];
58
- if (title) header.push(`Title: ${title}`);
59
- header.push(`URL: ${finalUrl}`);
60
- header.push("Rendered via the Jina Reader (r.jina.ai).");
61
- return truncatePageText(`${header.join("\n")}\n\n${content}`, maxChars);
62
- }
63
-
64
- export async function renderPageText(url: string, options: RenderPageOptions = {}): Promise<string> {
65
- const target = typeof url === "string" ? url.trim() : "";
66
- const policy = options.websitePolicy ?? null;
67
- if (!target) return checkUrlAccess("", policy)[1];
68
- if (parseLocalPath(target) !== null) return LOCAL_FILE_MESSAGE;
69
- const normalized = normalizeUrlScheme(target);
70
- const [allowed, reason, hostname] = checkUrlAccess(normalized, policy);
71
- if (!allowed) return reason;
72
- const timeoutSignal = AbortSignal.timeout(clampTimeout(options.timeoutMs));
73
- const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
74
- const resolved = await resolveAndValidateHost(hostname, signal, false);
75
- const resolutionBudget = budgetMessage(options.signal, signal);
76
- if (resolutionBudget !== null) return resolutionBudget;
77
- if (!resolved.ok) return resolved.reason.startsWith("Blocked:") ? resolved.reason : `Failed to render URL: ${resolved.reason}`;
78
- const headers: Record<string, string> = { Accept: "application/json" };
79
- const apiKey = options.apiKey?.trim();
80
- if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
81
- let response: Response;
82
- try {
83
- response = await fetch(JINA_READER_URL + encodeURIComponent(normalized), { headers, signal });
84
- } catch (err) {
85
- const budget = budgetMessage(options.signal, signal);
86
- if (budget !== null) return budget;
87
- return `Failed to render URL: ${err instanceof Error ? err.message : String(err)}`;
88
- }
89
- if (!response.ok) return `Failed to render URL: ${await readerErrorDetail(response)}`;
90
- let payload: JinaReaderPayload;
91
- try {
92
- payload = (await response.json()) as JinaReaderPayload;
93
- } catch {
94
- const budget = budgetMessage(options.signal, signal);
95
- if (budget !== null) return budget;
96
- return `Failed to render URL: the Jina Reader returned a non-JSON response (HTTP ${response.status}).`;
97
- }
98
- if (!payload || !payload.data) return EMPTY_READER_MESSAGE;
99
- return formatRenderedPage(payload.data, normalized, options.maxChars);
100
- }