From 5a496ac02162c36e455c93faf6d57455ca63282b Mon Sep 17 00:00:00 2001 From: 7ui77 <7ui77@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:49:19 +0700 Subject: [PATCH 1/3] fix(multisrc/novelfire): restore chapter numbers, optimize parsing, and document Cheerio fast-path (#2840) --- docs/docs.md | 7 + plugins/multisrc/novelfire/sources.json | 4 +- plugins/multisrc/novelfire/template.ts | 90 ++++++++-- scripts/test-novelphoenix.js | 209 ++++++++++++++++++++++++ 4 files changed, 290 insertions(+), 20 deletions(-) create mode 100644 scripts/test-novelphoenix.js diff --git a/docs/docs.md b/docs/docs.md index 5238047f00..cd3bed1af0 100644 --- a/docs/docs.md +++ b/docs/docs.md @@ -1010,6 +1010,13 @@ See the [Cheerio API docs](https://cheerio.js.org/docs/api) for the full set of (`.find()`, `.first()`, `.eq()`, `.attr()`, `.text()`, `.html()`, etc.), and look at existing plugins under `plugins/**` for real examples. +> [!TIP] +> **Performance in high-volume loops**: +> Avoid invoking `parseHTML(string)` repeatedly inside tight loops over chapter lists (e.g. mapping thousands of JSON chapter titles). Constructing a Cheerio DOM tree thousands of times introduces significant CPU and GC overhead. Instead, fast-path plain text strings and only invoke Cheerio when HTML tags or entities are actually present: +> ```ts +> const decoded = raw.includes('<') || raw.includes('&') ? parseHTML(raw).text() : raw; +> ``` + --- ### Custom fetching functions diff --git a/plugins/multisrc/novelfire/sources.json b/plugins/multisrc/novelfire/sources.json index e58eb2afb0..eb3b5fc52f 100644 --- a/plugins/multisrc/novelfire/sources.json +++ b/plugins/multisrc/novelfire/sources.json @@ -6,7 +6,7 @@ "options": { "lang": "English", "minorVer": 4, - "versionIncrement": 5 + "versionIncrement": 6 } }, { @@ -15,7 +15,7 @@ "sourceName": "Novel Phoenix", "options": { "lang": "English", - "versionIncrement": 2 + "versionIncrement": 3 } } ] diff --git a/plugins/multisrc/novelfire/template.ts b/plugins/multisrc/novelfire/template.ts index e9811587f5..ff25d99953 100644 --- a/plugins/multisrc/novelfire/template.ts +++ b/plugins/multisrc/novelfire/template.ts @@ -21,6 +21,39 @@ export type NovelFireMetadata = { filters?: Filters; }; +const CHAPTER_PREFIX_REGEX = /^(chapter|ch\.?)\s*\d+/i; +const LEADING_PUNCT_REGEX = /^[–—\-\s:]+/; +const INVISIBLE_CHARS_REGEX = /[\u200B-\u200D\uFEFF]/g; + +function formatChapterTitle( + rawTitle: string, + chapterPrefixOrNum: number | string, +): string { + const cleanTitle = rawTitle.replace(LEADING_PUNCT_REGEX, '').trim(); + const prefixStr = String(chapterPrefixOrNum).trim(); + const numMatch = prefixStr.match(/\d+/); + const num = numMatch ? numMatch[0] : ''; + + const hasChapterPrefix = + CHAPTER_PREFIX_REGEX.test(cleanTitle) || + (num.length > 0 && + cleanTitle.startsWith(num) && + (cleanTitle.length === num.length || !/\d/.test(cleanTitle[num.length]))); + + if (hasChapterPrefix) { + return cleanTitle; + } + + const prefix = + typeof chapterPrefixOrNum === 'number' + ? `Chapter ${chapterPrefixOrNum}` + : prefixStr.startsWith('Ch') || prefixStr.startsWith('Chapter') + ? prefixStr + : `Chapter ${prefixStr}`; + + return cleanTitle ? `${prefix} ${cleanTitle}` : prefix; +} + export class NovelFirePlugin implements Plugin.PagePlugin { id: string; name: string; @@ -219,21 +252,22 @@ export class NovelFirePlugin implements Plugin.PagePlugin { return (JSON.parse(body).data || []) .flatMap( (idx: { title?: string; slug: string; n_sort: string | number }) => { - const name = load(idx.title || idx.slug) - .text() - .replace(/[\u200B-\u200D\uFEFF]/g, '') - .trim(); const num = Number(idx.n_sort); - - return name && !isNaN(num) - ? [ - { - name, - path: `${novelPath}/chapter-${num}`, - chapterNumber: num, - }, - ] - : []; + if (isNaN(num)) return []; + + const raw = idx.title || idx.slug || ''; + const decoded = + raw.includes('<') || raw.includes('&') ? load(raw).text() : raw; + const cleanRaw = decoded.replace(INVISIBLE_CHARS_REGEX, '').trim(); + const name = formatChapterTitle(cleanRaw, num); + + return [ + { + name, + path: `${novelPath}/chapter-${num}`, + chapterNumber: num, + }, + ]; }, ) .sort( @@ -420,12 +454,32 @@ export class NovelFirePlugin implements Plugin.PagePlugin { const chapters = loadedCheerio('.chapter-list li') .map((_, ele) => { - const chapterName = - loadedCheerio(ele).find('a').attr('title') || 'No Title Found'; - const chapterPath = loadedCheerio(ele).find('a').attr('href'); + const $ele = loadedCheerio(ele); + const $a = $ele.find('a'); + const chapterPath = $a.attr('href'); if (!chapterPath) return null; + const chapterNo = $ele.find('.chapter-no').text().trim(); + const chapterTitle = $ele.find('.chapter-title').text().trim(); + const attrTitle = $a.attr('title')?.trim() || ''; + + let chapterName = ''; + if (chapterNo && chapterTitle) { + chapterName = formatChapterTitle(chapterTitle, chapterNo); + } else if (chapterNo && attrTitle) { + chapterName = formatChapterTitle(attrTitle, chapterNo); + } else if (attrTitle) { + chapterName = attrTitle; + } else if (chapterNo) { + chapterName = chapterNo; + } else if (chapterTitle) { + chapterName = chapterTitle; + } else { + chapterName = + $a.text().replace(/\s+/g, ' ').trim() || 'No Title Found'; + } + return { name: chapterName, path: new URL(chapterPath, this.site).pathname.substring(1), @@ -473,7 +527,7 @@ export class NovelFirePlugin implements Plugin.PagePlugin { ); for (const ele of odds.toArray()) { const tag = ele.name.toString(); - if (tag.length > 5 && tag.substring(0, 1) == 'nf') { + if (tag.length > 5 && tag.startsWith('nf')) { loadedCheerio(ele).remove(); } } diff --git a/scripts/test-novelphoenix.js b/scripts/test-novelphoenix.js new file mode 100644 index 0000000000..6af1f0b3f1 --- /dev/null +++ b/scripts/test-novelphoenix.js @@ -0,0 +1,209 @@ +// Run offline with: node --test scripts/test-novelphoenix.js +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { test } from 'node:test'; +import { runInNewContext } from 'node:vm'; +import ts from 'typescript'; + +const require = createRequire(import.meta.url); + +const templateSource = readFileSync( + new URL('../plugins/multisrc/novelfire/template.ts', import.meta.url), + 'utf8', +); + +function makeTranspiledCode(sourceId, sourceName, sourceSite) { + const pluginScript = ` +${templateSource} +const plugin = new NovelFirePlugin({ + id: "${sourceId}", + sourceSite: "${sourceSite}", + sourceName: "${sourceName}", + options: { + lang: "English", + versionIncrement: 3 + } +}); +exports.plugin = plugin; +export default plugin; +`; + return ts.transpileModule(pluginScript, { + compilerOptions: { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.CommonJS, + }, + }).outputText; +} + +function loadPlugin(code, fetchApi, storageData = {}) { + const exports = {}; + const stubs = { + '@libs/fetch': { fetchApi }, + '@libs/storage': { + storage: { + get: key => storageData[key], + set: (key, val) => { + storageData[key] = val; + }, + }, + }, + '@libs/filterInputs': { FilterTypes: {} }, + '@libs/novelStatus': { NovelStatus: { Unknown: 'Unknown' } }, + '@/types/constants': { defaultCover: 'https://example.com/default.png' }, + }; + + runInNewContext(code, { + exports, + require: name => stubs[name] || require(name), + console, + URL, + URLSearchParams, + Date, + Math, + parseInt, + parseFloat, + Number, + isNaN, + Array, + Set, + String, + RegExp, + }); + + return exports.plugin; +} + +test('NovelPhoenix chapter name includes chapter number from AJAX response', async () => { + const mockAjaxData = { + draw: 1, + recordsTotal: 4, + recordsFiltered: 4, + data: [ + { + chapter_id: 1, + n_sort: 1, + slug: 'chapter-1-1-nightmare-begins', + title: 'Nightmare Begins', + }, + { + chapter_id: 2, + n_sort: 2, + slug: 'chapter-2-2-the-sign', + title: '– The Sign', + }, + { + chapter_id: 3, + n_sort: 3, + slug: 'prologue', + title: 'Prologue', + }, + { + chapter_id: 4, + n_sort: 4, + slug: '4-the-truth', + title: '4. The Truth', + }, + ], + }; + + const fetchApi = async url => { + if (url.includes('ajax/listChapterDataAjax')) { + return { + ok: true, + status: 200, + text: async () => JSON.stringify(mockAjaxData), + }; + } + throw new Error(`Unexpected fetch URL: ${url}`); + }; + + const phoenixCode = makeTranspiledCode( + 'novelphoenix', + 'Novel Phoenix', + 'https://novelphoenix.com/', + ); + const plugin = loadPlugin(phoenixCode, fetchApi); + const chapters = await plugin.getAllChapters('novel/test-novel', '100', '1'); + + assert.equal(chapters.length, 4); + + assert.equal(chapters[0].name, 'Chapter 1 Nightmare Begins'); + assert.equal(chapters[1].name, 'Chapter 2 The Sign'); + assert.equal(chapters[2].name, 'Chapter 3 Prologue'); + assert.equal(chapters[3].name, '4. The Truth'); +}); + +test('NovelPhoenix fallback HTML parsing handles .chapter-no and .chapter-title without attr title short-circuit', async () => { + const html = ` + + `; + + const fetchApi = async url => { + if (url.includes('/chapters?page=1')) { + return { + ok: true, + status: 200, + text: async () => html, + }; + } + throw new Error(`Unexpected fetch URL: ${url}`); + }; + + const phoenixCode = makeTranspiledCode( + 'novelphoenix', + 'Novel Phoenix', + 'https://novelphoenix.com/', + ); + const plugin = loadPlugin(phoenixCode, fetchApi, { pageLength: true }); + const result = await plugin.parsePage('novel/test-novel', '1'); + + assert.equal(result.chapters.length, 2); + assert.equal(result.chapters[0].name, 'Ch. 1 Nightmare Begins'); + assert.equal(result.chapters[1].name, 'Ch. 2 The Sign'); +}); + +test('NovelFire chapter name preserves existing Chapter prefix without duplicating', async () => { + const mockAjaxData = { + draw: 1, + recordsTotal: 1, + recordsFiltered: 1, + data: [ + { + chapter_id: 1, + n_sort: 1, + slug: 'chapter-1-1-nightmare-begins', + title: 'Chapter 1 - 1: Nightmare Begins', + }, + ], + }; + + const fetchApi = async url => { + if (url.includes('ajax/listChapterDataAjax')) { + return { + ok: true, + status: 200, + text: async () => JSON.stringify(mockAjaxData), + }; + } + throw new Error(`Unexpected fetch URL: ${url}`); + }; + + const fireCode = makeTranspiledCode( + 'novelfire', + 'Novel Fire', + 'https://novelfire.net/', + ); + const plugin = loadPlugin(fireCode, fetchApi); + const chapters = await plugin.getAllChapters( + 'novel/shadow-slave', + '2196', + '1', + ); + + assert.equal(chapters.length, 1); + assert.equal(chapters[0].name, 'Chapter 1 - 1: Nightmare Begins'); +}); From 8090861bcc4391af91c69c47519db8749f208ecc Mon Sep 17 00:00:00 2001 From: 7ui77 <99854073+7ui77@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:09:02 +0700 Subject: [PATCH 2/3] Delete test-novelphoenix.js --- scripts/test-novelphoenix.js | 209 ----------------------------------- 1 file changed, 209 deletions(-) delete mode 100644 scripts/test-novelphoenix.js diff --git a/scripts/test-novelphoenix.js b/scripts/test-novelphoenix.js deleted file mode 100644 index 6af1f0b3f1..0000000000 --- a/scripts/test-novelphoenix.js +++ /dev/null @@ -1,209 +0,0 @@ -// Run offline with: node --test scripts/test-novelphoenix.js -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import { createRequire } from 'node:module'; -import { test } from 'node:test'; -import { runInNewContext } from 'node:vm'; -import ts from 'typescript'; - -const require = createRequire(import.meta.url); - -const templateSource = readFileSync( - new URL('../plugins/multisrc/novelfire/template.ts', import.meta.url), - 'utf8', -); - -function makeTranspiledCode(sourceId, sourceName, sourceSite) { - const pluginScript = ` -${templateSource} -const plugin = new NovelFirePlugin({ - id: "${sourceId}", - sourceSite: "${sourceSite}", - sourceName: "${sourceName}", - options: { - lang: "English", - versionIncrement: 3 - } -}); -exports.plugin = plugin; -export default plugin; -`; - return ts.transpileModule(pluginScript, { - compilerOptions: { - target: ts.ScriptTarget.ES2022, - module: ts.ModuleKind.CommonJS, - }, - }).outputText; -} - -function loadPlugin(code, fetchApi, storageData = {}) { - const exports = {}; - const stubs = { - '@libs/fetch': { fetchApi }, - '@libs/storage': { - storage: { - get: key => storageData[key], - set: (key, val) => { - storageData[key] = val; - }, - }, - }, - '@libs/filterInputs': { FilterTypes: {} }, - '@libs/novelStatus': { NovelStatus: { Unknown: 'Unknown' } }, - '@/types/constants': { defaultCover: 'https://example.com/default.png' }, - }; - - runInNewContext(code, { - exports, - require: name => stubs[name] || require(name), - console, - URL, - URLSearchParams, - Date, - Math, - parseInt, - parseFloat, - Number, - isNaN, - Array, - Set, - String, - RegExp, - }); - - return exports.plugin; -} - -test('NovelPhoenix chapter name includes chapter number from AJAX response', async () => { - const mockAjaxData = { - draw: 1, - recordsTotal: 4, - recordsFiltered: 4, - data: [ - { - chapter_id: 1, - n_sort: 1, - slug: 'chapter-1-1-nightmare-begins', - title: 'Nightmare Begins', - }, - { - chapter_id: 2, - n_sort: 2, - slug: 'chapter-2-2-the-sign', - title: '– The Sign', - }, - { - chapter_id: 3, - n_sort: 3, - slug: 'prologue', - title: 'Prologue', - }, - { - chapter_id: 4, - n_sort: 4, - slug: '4-the-truth', - title: '4. The Truth', - }, - ], - }; - - const fetchApi = async url => { - if (url.includes('ajax/listChapterDataAjax')) { - return { - ok: true, - status: 200, - text: async () => JSON.stringify(mockAjaxData), - }; - } - throw new Error(`Unexpected fetch URL: ${url}`); - }; - - const phoenixCode = makeTranspiledCode( - 'novelphoenix', - 'Novel Phoenix', - 'https://novelphoenix.com/', - ); - const plugin = loadPlugin(phoenixCode, fetchApi); - const chapters = await plugin.getAllChapters('novel/test-novel', '100', '1'); - - assert.equal(chapters.length, 4); - - assert.equal(chapters[0].name, 'Chapter 1 Nightmare Begins'); - assert.equal(chapters[1].name, 'Chapter 2 The Sign'); - assert.equal(chapters[2].name, 'Chapter 3 Prologue'); - assert.equal(chapters[3].name, '4. The Truth'); -}); - -test('NovelPhoenix fallback HTML parsing handles .chapter-no and .chapter-title without attr title short-circuit', async () => { - const html = ` - - `; - - const fetchApi = async url => { - if (url.includes('/chapters?page=1')) { - return { - ok: true, - status: 200, - text: async () => html, - }; - } - throw new Error(`Unexpected fetch URL: ${url}`); - }; - - const phoenixCode = makeTranspiledCode( - 'novelphoenix', - 'Novel Phoenix', - 'https://novelphoenix.com/', - ); - const plugin = loadPlugin(phoenixCode, fetchApi, { pageLength: true }); - const result = await plugin.parsePage('novel/test-novel', '1'); - - assert.equal(result.chapters.length, 2); - assert.equal(result.chapters[0].name, 'Ch. 1 Nightmare Begins'); - assert.equal(result.chapters[1].name, 'Ch. 2 The Sign'); -}); - -test('NovelFire chapter name preserves existing Chapter prefix without duplicating', async () => { - const mockAjaxData = { - draw: 1, - recordsTotal: 1, - recordsFiltered: 1, - data: [ - { - chapter_id: 1, - n_sort: 1, - slug: 'chapter-1-1-nightmare-begins', - title: 'Chapter 1 - 1: Nightmare Begins', - }, - ], - }; - - const fetchApi = async url => { - if (url.includes('ajax/listChapterDataAjax')) { - return { - ok: true, - status: 200, - text: async () => JSON.stringify(mockAjaxData), - }; - } - throw new Error(`Unexpected fetch URL: ${url}`); - }; - - const fireCode = makeTranspiledCode( - 'novelfire', - 'Novel Fire', - 'https://novelfire.net/', - ); - const plugin = loadPlugin(fireCode, fetchApi); - const chapters = await plugin.getAllChapters( - 'novel/shadow-slave', - '2196', - '1', - ); - - assert.equal(chapters.length, 1); - assert.equal(chapters[0].name, 'Chapter 1 - 1: Nightmare Begins'); -}); From e377384952b04f070eaf0fb772f83f8592d3c86f Mon Sep 17 00:00:00 2001 From: 7ui77 <7ui77@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:04:36 +0700 Subject: [PATCH 3/3] docs: revert changes to docs/docs.md --- docs/docs.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/docs/docs.md b/docs/docs.md index cd3bed1af0..5238047f00 100644 --- a/docs/docs.md +++ b/docs/docs.md @@ -1010,13 +1010,6 @@ See the [Cheerio API docs](https://cheerio.js.org/docs/api) for the full set of (`.find()`, `.first()`, `.eq()`, `.attr()`, `.text()`, `.html()`, etc.), and look at existing plugins under `plugins/**` for real examples. -> [!TIP] -> **Performance in high-volume loops**: -> Avoid invoking `parseHTML(string)` repeatedly inside tight loops over chapter lists (e.g. mapping thousands of JSON chapter titles). Constructing a Cheerio DOM tree thousands of times introduces significant CPU and GC overhead. Instead, fast-path plain text strings and only invoke Cheerio when HTML tags or entities are actually present: -> ```ts -> const decoded = raw.includes('<') || raw.includes('&') ? parseHTML(raw).text() : raw; -> ``` - --- ### Custom fetching functions