diff --git a/src/handlers/handler-input.ts b/src/handlers/handler-input.ts new file mode 100644 index 0000000..72a13d1 --- /dev/null +++ b/src/handlers/handler-input.ts @@ -0,0 +1,46 @@ +import { JSDOM } from "jsdom"; +import { generateProxyUrl } from "../utils/generate"; + +export class HandlerInput { + private data: string; + private url: string; + private requestUrl: URL; + private engine?: string; + private redirectPath: string; + + constructor( + data: string, + url: string, + requestUrl: URL, + engine?: string, + redirectPath: string = "get", + ) { + this.data = data; + this.url = url; + this.requestUrl = requestUrl; + this.engine = engine; + this.redirectPath = redirectPath; + } + + parseDom() { + const dom = new JSDOM(this.data, { url: this.url }); + + const links = dom.window.document.getElementsByTagName("a"); + for (const link of links) { + try { + link.href = generateProxyUrl( + this.requestUrl, + link.href, + this.engine, + this.redirectPath, + ); + } catch (_err) { + // ignore TypeError: Invalid URL + } + } + } + + getUrl() { + return this.url; + } +} diff --git a/src/handlers/main.ts b/src/handlers/main.ts index 9b1ce0f..a6ff350 100644 --- a/src/handlers/main.ts +++ b/src/handlers/main.ts @@ -14,12 +14,13 @@ import { generateProxyUrl } from "../utils/generate"; import isLocalResource from "../utils/islocal"; import { LocalResourceError, NotHtmlMimetypeError } from "../errors/main"; +import { HandlerInput } from "./handler-input"; export default async function handlePage( url: string, // remote URL requestUrl: URL, // proxy URL engine?: string, - redirect_path: string = "get", + redirectPath: string = "get", ): Promise { const urlObj = new URL(url); @@ -34,22 +35,15 @@ export default async function handlePage( throw new NotHtmlMimetypeError(url); } - const window = new JSDOM(response.data, { url }).window; - - [...window.document.getElementsByTagName("a")].forEach((link) => { - try { - link.href = generateProxyUrl( - requestUrl, - link.href, - engine, - redirect_path, - ); - } catch (_err) { - // ignore TypeError: Invalid URL - } - }); - - return getFallbackEngine(urlObj.hostname, engine)(window); + return getFallbackEngine(urlObj.hostname, engine)( + new HandlerInput( + response.data, + url, + requestUrl, + engine, + redirectPath, + ) + ); } function getFallbackEngine(host: string, specified?: string): EngineFunction { diff --git a/src/types/handlers.ts b/src/types/handlers.ts index c5ec05e..846eeda 100644 --- a/src/types/handlers.ts +++ b/src/types/handlers.ts @@ -1,4 +1,4 @@ -import { DOMWindow } from "jsdom"; +import { HandlerInput } from "../handlers/handler-input"; import { IHandlerOutput } from "../handlers/handler.interface"; export interface Engines { @@ -10,5 +10,5 @@ export type EngineMatch = { engine: EngineFunction; }; -export type EngineFunction = (window: DOMWindow) => Promise; +export type EngineFunction = (input: HandlerInput) => Promise; export type EnginesMatch = EngineMatch[];