From de817322c6130b070a1e992cd89b192547d6e1e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 10:36:44 +0000 Subject: [PATCH] feat: Add @libs/pluginError Shim for Plugin Runtime Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014f4X6LNWovDsaULDcLLoCX --- .changeset/quiet-plugins-error.md | 6 + .../plugin-runtime/src/plugins/shims/index.ts | 10 +- .../src/plugins/shims/pluginError.ts | 153 ++++++++++++++++++ .../plugin-runtime/src/types/constants.ts | 17 ++ .../plugin-runtime/test/pluginError.test.ts | 63 ++++++++ 5 files changed, 247 insertions(+), 2 deletions(-) create mode 100644 .changeset/quiet-plugins-error.md create mode 100644 packages/plugin-runtime/src/plugins/shims/pluginError.ts create mode 100644 packages/plugin-runtime/test/pluginError.test.ts diff --git a/.changeset/quiet-plugins-error.md b/.changeset/quiet-plugins-error.md new file mode 100644 index 0000000..8b5d908 --- /dev/null +++ b/.changeset/quiet-plugins-error.md @@ -0,0 +1,6 @@ +--- +'@lnreader/cli': patch +'@lnreader/plugin-runtime': patch +--- + +Support plugins that import `@libs/pluginError`, such as NovelFire and NovelPhoenix. diff --git a/packages/plugin-runtime/src/plugins/shims/index.ts b/packages/plugin-runtime/src/plugins/shims/index.ts index 462bc94..7669e13 100644 --- a/packages/plugin-runtime/src/plugins/shims/index.ts +++ b/packages/plugin-runtime/src/plugins/shims/index.ts @@ -3,10 +3,15 @@ import * as cheerio from 'cheerio'; import dayjs from 'dayjs'; import * as htmlparser2 from 'htmlparser2'; import urlencode from 'urlencode'; -import { defaultCover, NovelStatus } from '../../types/constants.js'; +import { + defaultCover, + NovelStatus, + PluginError, +} from '../../types/constants.js'; import { FilterTypes } from '../../types/filters.js'; import { UnshimmedImportError } from '../errors.js'; import { createFetchShim, type FetchShimDeps } from './fetch.js'; +import * as pluginError from './pluginError.js'; import { PluginStorage, WebStorage } from './storage.js'; export type ShimDeps = FetchShimDeps & { @@ -30,7 +35,7 @@ export const isUrlAbsolute = (url: string): boolean => { /** Builds the module table a single plugin can `require`. */ export function createShims(deps: ShimDeps) { const fetchShim = createFetchShim(deps); - const constants = { NovelStatus, defaultCover }; + const constants = { NovelStatus, PluginError, defaultCover }; const modules: Record = { '@libs/fetch': fetchShim, '@libs/storage': { @@ -43,6 +48,7 @@ export function createShims(deps: ShimDeps) { '@libs/filterInputs': { FilterTypes }, '@libs/isAbsoluteUrl': { isUrlAbsolute }, '@libs/aes': { gcm }, + '@libs/pluginError': pluginError, '@/types/constants': constants, cheerio: cheerio, htmlparser2: htmlparser2, diff --git a/packages/plugin-runtime/src/plugins/shims/pluginError.ts b/packages/plugin-runtime/src/plugins/shims/pluginError.ts new file mode 100644 index 0000000..5adf317 --- /dev/null +++ b/packages/plugin-runtime/src/plugins/shims/pluginError.ts @@ -0,0 +1,153 @@ +/* + * Vendored from LNReader/lnreader-plugins (src/lib/pluginError.ts). + * Copyright (c) LNReader contributors, MIT License. + */ + +import { PluginError } from '../../types/constants.js'; + +export { PluginError }; + +export type PluginErrorCode = (typeof PluginError)[keyof typeof PluginError]; + +export type PluginErrorOptions = { + status?: number; + message?: string; + url?: string; +}; + +export type PluginErrorInstance = Error & { + code: PluginErrorCode; + status?: number; + url?: string; +}; + +export type CheckResponseOptions = { + search?: boolean; + notFoundCode?: PluginErrorCode; + message?: string; +}; + +const PLUGIN_ERROR_CODES: readonly string[] = Object.keys(PluginError).map( + key => PluginError[key as keyof typeof PluginError], +); + +const STATUS_TO_CODE: Record = { + 401: PluginError.AuthRequired, + 403: PluginError.Cloudflare, + 404: PluginError.NotFound, + 429: PluginError.RateLimited, + 503: PluginError.Cloudflare, +}; + +const CHALLENGE_TITLES = [ + 'bot verification', + 'you are being redirected...', + 'un instant...', + 'one moment...', + 'just a moment...', + 'redirecting...', + 'attention required! | cloudflare', +]; + +function getHostnameBase(url: string): string { + const match = url.match(/^https?:\/\/([^/?#]+)/i); + const host = (match?.[1] ?? '').toLowerCase().replace(/^www\./, ''); + if (!host) return ''; + const parts = host.split('.'); + if (parts.length > 1) { + parts.pop(); + } + return parts.join('.'); +} + +export function createPluginError( + code: PluginErrorCode, + options?: PluginErrorOptions, +): PluginErrorInstance { + const message = options?.message || code; + const error = new Error(message) as PluginErrorInstance; + error.name = 'PluginError'; + error.code = code; + if (options?.status !== undefined) { + error.status = options.status; + } + if (options?.url) { + error.url = options.url; + } + return error; +} + +export function httpError( + status: number, + message?: string, + url?: string, +): PluginErrorInstance { + const code = STATUS_TO_CODE[status] ?? PluginError.NetworkError; + const fallbackMessage = + code === PluginError.NetworkError && status + ? `Could not reach site (${status}), please try to open in webview.` + : code; + return createPluginError(code, { + status, + message: message || fallbackMessage, + url, + }); +} + +export function checkResponse( + response: Response, + options?: CheckResponseOptions, +): Response { + if (response.ok || (options?.search && response.status === 404)) { + return response; + } + if (response.status === 404 && options?.notFoundCode) { + throw createPluginError(options.notFoundCode, { + status: response.status, + message: options.message, + url: response.url || undefined, + }); + } + throw httpError(response.status, options?.message, response.url || undefined); +} + +export function isChallengeHtml( + html: string, + requestUrl?: string, + responseUrl?: string, +): boolean { + if (requestUrl && responseUrl) { + const reqHost = getHostnameBase(requestUrl); + const resHost = getHostnameBase(responseUrl); + if (reqHost && resHost && reqHost !== resHost) { + return true; + } + } + const titleMatch = html.match(/]*>([^<]*)<\/title>/i); + const title = titleMatch?.[1]?.trim().toLowerCase() ?? ''; + if (!title) return false; + return ( + CHALLENGE_TITLES.indexOf(title) !== -1 || /\bcloudflare\b/i.test(title) + ); +} + +export function assertNoChallenge( + html: string, + requestUrl?: string, + responseUrl?: string, + message?: string, +): void { + if (isChallengeHtml(html, requestUrl, responseUrl)) { + throw createPluginError(PluginError.Captcha, { + status: 403, + message, + url: responseUrl || requestUrl, + }); + } +} + +export function isPluginError(error: unknown): error is PluginErrorInstance { + if (!(error instanceof Error)) return false; + const code = (error as Partial).code; + return typeof code === 'string' && PLUGIN_ERROR_CODES.indexOf(code) !== -1; +} diff --git a/packages/plugin-runtime/src/types/constants.ts b/packages/plugin-runtime/src/types/constants.ts index 6b42d50..cc8edad 100644 --- a/packages/plugin-runtime/src/types/constants.ts +++ b/packages/plugin-runtime/src/types/constants.ts @@ -15,5 +15,22 @@ export const NovelStatus = { Inactive: 'Inactive', } as const; +/** Error messages that double as codes for `@libs/pluginError`. */ +export const PluginError = { + Captcha: 'Captcha error, please open in webview', + Cloudflare: 'Cloudflare is blocking requests. Try again later.', + RateLimited: 'Too many requests (429). Please try again later.', + NotFound: + 'Content not found (404), it may have been removed from this source.', + NovelNotFound: + 'Novel not found (404), it may have been removed from this source.', + ChapterNotFound: + 'Chapter not found (404), it may have been removed from this source.', + AuthRequired: 'Authentication required. Please log in via WebView.', + EmptyContent: 'No readable content was found.', + InvalidResponse: 'Invalid response from source.', + NetworkError: 'Could not reach site, please try to open in webview.', +} as const; + export const defaultCover = 'https://github.com/LNReader/lnreader-plugins/blob/main/icons/src/coverNotAvailable.jpg?raw=true'; diff --git a/packages/plugin-runtime/test/pluginError.test.ts b/packages/plugin-runtime/test/pluginError.test.ts new file mode 100644 index 0000000..380ff49 --- /dev/null +++ b/packages/plugin-runtime/test/pluginError.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; +import * as pluginError from '../src/plugins/shims/pluginError.js'; +import { PluginError } from '../src/types/constants.js'; + +const { + assertNoChallenge, + checkResponse, + createPluginError, + httpError, + isChallengeHtml, + isPluginError, +} = pluginError; + +const response = (status: number, url = 'https://novels.test/x') => { + const res = new Response('', { status }); + Object.defineProperty(res, 'url', { value: url }); + return res; +}; + +describe('@libs/pluginError shim', () => { + it('creates errors carrying a code, status and url', () => { + const error = createPluginError(PluginError.NotFound, { + status: 404, + url: 'https://novels.test/x', + }); + expect(error).toBeInstanceOf(Error); + expect(error.name).toBe('PluginError'); + expect(error.message).toBe(PluginError.NotFound); + expect(error).toMatchObject({ status: 404, url: 'https://novels.test/x' }); + expect(isPluginError(error)).toBe(true); + expect(isPluginError(new Error('plain'))).toBe(false); + }); + + it('maps HTTP statuses to codes', () => { + expect(httpError(403).code).toBe(PluginError.Cloudflare); + expect(httpError(429).code).toBe(PluginError.RateLimited); + const other = httpError(500); + expect(other.code).toBe(PluginError.NetworkError); + expect(other.message).toContain('(500)'); + }); + + it('checks responses', () => { + const ok = response(200); + expect(checkResponse(ok)).toBe(ok); + const missing = response(404); + expect(checkResponse(missing, { search: true })).toBe(missing); + expect(() => + checkResponse(missing, { notFoundCode: PluginError.NovelNotFound }), + ).toThrow(PluginError.NovelNotFound); + expect(() => checkResponse(response(429))).toThrow(PluginError.RateLimited); + }); + + it('detects challenge pages', () => { + expect(isChallengeHtml('Just a moment...')).toBe(true); + expect(isChallengeHtml('Chapter 1')).toBe(false); + expect( + isChallengeHtml('', 'https://novels.test/a', 'https://other.test/b'), + ).toBe(true); + expect(() => + assertNoChallenge('Attention Required! | Cloudflare'), + ).toThrow(PluginError.Captcha); + }); +});