repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/web/fetch.ts

Raw
File outline
// HTTP fetch helper — returns body as Buffer + content-type for routing

import type { FetchResult } from "./constants.js";
import { BROWSER_HEADERS, DEFAULT_TIMEOUT_MS } from "./constants.js";

export async function fetchUrlStream(
	url: string,
	onProgress?: (loaded: number, total: number) => void,
	signal?: AbortSignal,
): Promise<FetchResult> {
	const parsed = new URL(url);
	const headers: Record<string, string> = {
		...BROWSER_HEADERS,
		Referer: `${parsed.protocol}//${parsed.host}/`,
	};

	const response = await fetch(url, {
		headers,
		signal: signal ?? AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
	});

	if (!response.ok) {
		throw new Error(`HTTP ${response.status}: ${response.statusText}`);
	}

	const contentType = response.headers.get("content-type") ?? "";
	const contentLength = parseInt(
		response.headers.get("content-length") ?? "0",
		10,
	);

	if (!response.body) {
		throw new Error("No response body");
	}

	const reader = response.body.getReader();
	let loaded = 0;
	const chunks: Uint8Array[] = [];

	while (true) {
		const { done, value } = await reader.read();
		if (done) break;
		loaded += value.length;
		chunks.push(value);
		onProgress?.(loaded, contentLength);
	}

	const body = Buffer.concat(chunks);

	return {
		body,
		contentType,
		contentLength,
		status: response.status,
	};
}

// DuckDuckGo search fetch (separate because it uses DDG-specific headers)
export async function fetchSearchHtml(
	url: string,
	signal?: AbortSignal,
	timeout?: number,
): Promise<string> {
	const response = await fetch(url, {
		headers: BROWSER_HEADERS,
		signal: signal ?? AbortSignal.timeout(timeout ?? DEFAULT_TIMEOUT_MS),
	});

	if (!response.ok) {
		throw new Error(`HTTP ${response.status}: ${response.statusText}`);
	}

	return response.text();
}