@acanthis-dec/linovelib 1.1.2 → 1.3.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/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { BrowserFetchClient, CloudflareBlockError, defaultRetryPolicy } from "@acanthis-dec/browser-fetch";
2
2
  import { deepmerge } from "deepmerge-ts";
3
- import z$1, { z } from "zod";
4
- import { buildDescrambleMapping, runTimeout } from "@acanthis-dec/core";
3
+ import z, { z as z$1 } from "zod";
4
+ import { buildDescrambleMapping } from "@acanthis-dec/core";
5
5
  import * as cheerio from "cheerio";
6
6
  import { load } from "cheerio";
7
7
  import { deobfuscate } from "@acanthis-dec/deobfuscator";
@@ -10,20 +10,27 @@ import traverseModule from "@babel/traverse";
10
10
  import * as t from "@babel/types";
11
11
  import PQueue from "p-queue";
12
12
  import { Mutex } from "async-mutex";
13
- //#region src/coefficients.ts
13
+ import { existsSync } from "node:fs";
14
+ import { readFile } from "node:fs/promises";
15
+ import { join } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { decode } from "fast-png";
18
+ // src/coefficients.ts
14
19
  const traverse = traverseModule.default ?? traverseModule;
15
- const descrambleCoefficientsSchema = z.object({
16
- modulus: z.number().int(),
17
- increment: z.number().int(),
18
- multiplier: z.number().int(),
19
- seedOffset: z.number().int(),
20
- seedMultiplier: z.number().int()
20
+ const descrambleCoefficientsSchema = z$1.object({
21
+ modulus: z$1.number().int(),
22
+ increment: z$1.number().int(),
23
+ multiplier: z$1.number().int(),
24
+ seedOffset: z$1.number().int(),
25
+ seedMultiplier: z$1.number().int()
21
26
  });
22
27
  function getObfuscatedPart(fullCode) {
23
28
  return fullCode.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "").slice(-2).join("\n");
24
29
  }
25
30
  async function extractCoefficients(script) {
26
- const ast = parse(await deobfuscate(getObfuscatedPart(script)), {
31
+ const obfuscatedPart = getObfuscatedPart(script);
32
+ const deObfCode = await deobfuscate(obfuscatedPart);
33
+ const ast = parse(deObfCode, {
27
34
  sourceType: "module",
28
35
  plugins: ["jsx"]
29
36
  });
@@ -73,8 +80,7 @@ async function getCoefficientsFromPage(html, fetchClient, cachedVersion) {
73
80
  version
74
81
  };
75
82
  }
76
- //#endregion
77
- //#region src/utils.ts
83
+ // src/utils.ts
78
84
  function extractNovelIdFromUrl(url) {
79
85
  const match = url.match(/\/novel\/(\d+)\.html/);
80
86
  return match ? match[1] : void 0;
@@ -188,8 +194,7 @@ function transformContent(content) {
188
194
  };
189
195
  return content.replace(/./g, (char) => contentTransDict[char] || char);
190
196
  }
191
- //#endregion
192
- //#region src/chapter.ts
197
+ // src/chapter.ts
193
198
  function extractChapterId($) {
194
199
  const scriptTags = $("script");
195
200
  let chapterId = "";
@@ -247,7 +252,8 @@ async function decrypt(html, fetchClient, cachedJsVersion, cachedCoefficients) {
247
252
  const mapping = buildDescrambleMapping(sortableEntries.length, seed, coefficients, 20);
248
253
  const restoredChildren = [...allChildren];
249
254
  sortableEntries.forEach((entry, i) => {
250
- const actualSlot = sortableEntries[mapping[i] ?? i]?.originalPos ?? 0;
255
+ const targetIndex = mapping[i] ?? i;
256
+ const actualSlot = sortableEntries[targetIndex]?.originalPos ?? 0;
251
257
  restoredChildren[actualSlot] = entry.element;
252
258
  });
253
259
  const newContainer = $("<div></div>");
@@ -287,8 +293,7 @@ async function getChapter(id, novelId, chapterQueue, fetchClient, cachedJsVersio
287
293
  };
288
294
  return content;
289
295
  }
290
- //#endregion
291
- //#region src/novel.ts
296
+ // src/novel.ts
292
297
  function extractVolumesArray(catalog) {
293
298
  const $ = cheerio.load(catalog);
294
299
  const results = [];
@@ -303,20 +308,63 @@ function processVolumeName(novelTitle, volumeName) {
303
308
  if (!Number.isNaN(Number(volumeName))) return `第 ${volumeName} 卷`;
304
309
  return volumeName.trim();
305
310
  }
311
+ function isUnresolvedChapterId(id) {
312
+ return id.startsWith("TOBEDETERMINED");
313
+ }
306
314
  function parseVolumeOrChapterId(url) {
307
315
  if (url.includes("javascript:cid(0)")) return "TOBEDETERMINED";
308
316
  const match = url.match(/\/novel\/\d+\/(\d+|vol_\d+)\.html/);
309
317
  return match ? match[1] ?? "" : "";
310
318
  }
311
- async function parseChapterIdFromNextChapter(nextChapterEl, chapterQueue) {
312
- const nextChapterPath = nextChapterEl.attribs.href ?? "";
313
- const nextChapterContent = await chapterQueue.fetchChapterPart(`https://www.linovelib.com${nextChapterPath}`);
314
- return parseVolumeOrChapterId(cheerio.load(nextChapterContent)("div.mlfy_page a:first").attr("href") ?? nextChapterContent.match(/url_previous:'(\/novel\/\d+\/[\d_]+\.html)'/)?.[1] ?? "");
319
+ function extractChapterIdFromLink(href, novelId) {
320
+ if (!href) return "";
321
+ const match = href.match(/\/novel\/(\d+)\/(\d+)(?:_\d+)?\.html/);
322
+ if (!match || match[1] !== novelId) return "";
323
+ const chapterId = match[2] ?? "";
324
+ return /^\d+$/.test(chapterId) ? chapterId : "";
325
+ }
326
+ async function parseChapterIdFromNextChapter(novelId, nextChapterId, chapterQueue) {
327
+ if (!/^\d+$/.test(nextChapterId)) return "";
328
+ try {
329
+ const nextChapterContent = await chapterQueue.fetchChapterPart(`https://www.linovelib.com/novel/${novelId}/${nextChapterId}.html`);
330
+ const domChapterId = extractChapterIdFromLink(cheerio.load(nextChapterContent)("div.mlfy_page a:first").attr("href"), novelId);
331
+ if (domChapterId) return domChapterId;
332
+ return extractChapterIdFromLink(nextChapterContent.match(/url_previous\s*:\s*['"](\/novel\/\d+\/[\d_]+\.html)['"]/)?.[1], novelId);
333
+ } catch {
334
+ return "";
335
+ }
336
+ }
337
+ async function parseNextChapterIdFromPrevChapter(novelId, prevChapterId, chapterQueue) {
338
+ if (!/^\d+$/.test(prevChapterId)) return "";
339
+ const MAX_PAGES = 50;
340
+ const visited = /* @__PURE__ */ new Set();
341
+ let currentPageId = prevChapterId;
342
+ for (let page = 0; page < MAX_PAGES; page++) {
343
+ if (visited.has(currentPageId)) return "";
344
+ visited.add(currentPageId);
345
+ let html = "";
346
+ try {
347
+ html = await chapterQueue.fetchChapterPart(`https://www.linovelib.com/novel/${novelId}/${currentPageId}.html`);
348
+ } catch {
349
+ return "";
350
+ }
351
+ const domMatch = cheerio.load(html)("div.mlfy_page a:last").attr("href")?.match(/\/novel\/(\d+)\/([\d_]+)\.html/);
352
+ const scriptMatch = html.match(/url_next\s*:\s*['"]\/novel\/(\d+)\/([\d_]+)\.html['"]/);
353
+ const nextPageId = (domMatch?.[1] === novelId ? domMatch[2] : void 0) ?? (scriptMatch?.[1] === novelId ? scriptMatch[2] : void 0) ?? "";
354
+ if (!nextPageId || visited.has(nextPageId)) return "";
355
+ if (nextPageId.startsWith(`${prevChapterId}_`)) {
356
+ currentPageId = nextPageId;
357
+ continue;
358
+ }
359
+ if (/^\d+$/.test(nextPageId) && nextPageId !== prevChapterId) return nextPageId;
360
+ return "";
361
+ }
362
+ return "";
315
363
  }
316
- async function getNovelVolumes(title, url, fetchClient, retry, chapterQueue) {
364
+ async function getNovelVolumes(novelId, title, url, fetchClient, retry, chapterQueue) {
317
365
  const volumeEls = extractVolumesArray((await fetchClient.text(url, { retry })).data);
318
366
  const volumes = [];
319
- const fixTasks = [];
367
+ const flatChapters = [];
320
368
  const parsedVolumes = volumeEls.map((el) => {
321
369
  const $ = cheerio.load(el);
322
370
  return {
@@ -329,38 +377,24 @@ async function getNovelVolumes(title, url, fetchClient, retry, chapterQueue) {
329
377
  });
330
378
  for (let vIndex = 0; vIndex < parsedVolumes.length; vIndex++) {
331
379
  const vData = parsedVolumes[vIndex];
380
+ if (!vData) continue;
332
381
  const chapters = [];
333
382
  for (let cIndex = 0; cIndex < vData.chapterEls.length; cIndex++) {
334
383
  const chapterEl = vData.chapterEls[cIndex];
335
384
  if (!chapterEl) continue;
336
385
  const chapterName = cheerio.load(chapterEl).text().trim();
337
- const chapterId = parseVolumeOrChapterId(chapterEl.attribs.href ?? "");
338
386
  const chapterObj = {
339
- id: chapterId,
387
+ id: parseVolumeOrChapterId(chapterEl.attribs.href ?? ""),
340
388
  platform: "linovelib",
341
389
  title: chapterName,
342
390
  volumeId: vData.volumeId
343
391
  };
344
392
  chapters.push(chapterObj);
345
- if (chapterId === "TOBEDETERMINED" && chapterQueue) {
346
- let nextChapterEl = null;
347
- if (cIndex < vData.chapterEls.length - 1) {
348
- const potentialNextEl = vData.chapterEls[cIndex + 1];
349
- if (potentialNextEl) nextChapterEl = potentialNextEl;
350
- } else if (vIndex < parsedVolumes.length - 1) {
351
- const nextVolData = parsedVolumes[vIndex + 1];
352
- if (nextVolData) {
353
- if (nextVolData.chapterEls.length > 0) {
354
- const potentialNextEl = nextVolData.chapterEls[0];
355
- if (potentialNextEl) nextChapterEl = potentialNextEl;
356
- }
357
- }
358
- }
359
- if (nextChapterEl) fixTasks.push({
360
- chapter: chapterObj,
361
- nextChapterEl
362
- });
363
- }
393
+ flatChapters.push({
394
+ chapter: chapterObj,
395
+ vIndex,
396
+ cIndex: chapters.length - 1
397
+ });
364
398
  }
365
399
  volumes.push({
366
400
  id: vData.volumeId,
@@ -370,10 +404,30 @@ async function getNovelVolumes(title, url, fetchClient, retry, chapterQueue) {
370
404
  chapters
371
405
  });
372
406
  }
373
- if (fixTasks.length > 0 && chapterQueue) await Promise.all(fixTasks.map(async (task) => {
374
- const realId = await parseChapterIdFromNextChapter(task.nextChapterEl, chapterQueue);
375
- if (realId) task.chapter.id = realId;
376
- }));
407
+ if (chapterQueue) {
408
+ const phase1Tasks = [];
409
+ for (let i = 0; i < flatChapters.length; i++) {
410
+ const current = flatChapters[i];
411
+ const next = flatChapters[i + 1];
412
+ if (current && next && current.chapter.id === "TOBEDETERMINED" && /^\d+$/.test(next.chapter.id)) {
413
+ const nextChapterId = next.chapter.id;
414
+ phase1Tasks.push((async () => {
415
+ const realId = await parseChapterIdFromNextChapter(novelId, nextChapterId, chapterQueue);
416
+ if (/^\d+$/.test(realId) && realId !== nextChapterId) current.chapter.id = realId;
417
+ })());
418
+ }
419
+ }
420
+ if (phase1Tasks.length > 0) await Promise.all(phase1Tasks);
421
+ for (let i = 0; i < flatChapters.length; i++) {
422
+ const current = flatChapters[i];
423
+ const prev = flatChapters[i - 1];
424
+ if (current && prev && current.chapter.id === "TOBEDETERMINED" && /^\d+$/.test(prev.chapter.id)) {
425
+ const realId = await parseNextChapterIdFromPrevChapter(novelId, prev.chapter.id, chapterQueue);
426
+ if (/^\d+$/.test(realId) && realId !== prev.chapter.id) current.chapter.id = realId;
427
+ }
428
+ }
429
+ }
430
+ for (const entry of flatChapters) if (entry.chapter.id === "TOBEDETERMINED" || entry.chapter.id === "") entry.chapter.id = `TOBEDETERMINED_${entry.vIndex}_${entry.cIndex}`;
377
431
  return volumes;
378
432
  }
379
433
  async function getNovelInfo(id, fetchClient, retry, chapterQueue) {
@@ -400,7 +454,7 @@ async function getNovelInfo(id, fetchClient, retry, chapterQueue) {
400
454
  genres: $("div.book-label span").children("a").map((_, el) => $(el).text()).toArray().join(",").split(",").map((g) => g.trim()),
401
455
  volumes: []
402
456
  };
403
- novel.volumes = (await getNovelVolumes(title, `https://www.linovelib.com${$("a.read-btn").attr("href")}`, fetchClient, retry, chapterQueue)).map((v) => {
457
+ novel.volumes = (await getNovelVolumes(id, title, `https://www.linovelib.com${$("a.read-btn").attr("href")}`, fetchClient, retry, chapterQueue)).map((v) => {
404
458
  v.novelId = novel.id;
405
459
  return v;
406
460
  });
@@ -419,8 +473,7 @@ async function getUpdateInfo(id, fetchClient, retry) {
419
473
  chapterCount
420
474
  };
421
475
  }
422
- //#endregion
423
- //#region src/cover.ts
476
+ // src/cover.ts
424
477
  function novelIdToCoverUrl(novelId) {
425
478
  return `https://www.linovelib.com/files/article/image/${novelId.length > 3 ? novelId[0] : "0"}/${novelId}/${novelId}s.jpg`;
426
479
  }
@@ -434,8 +487,7 @@ async function getVolumeCoverUrl(id, novelId, fetchClient) {
434
487
  if (!volume) throw new Error(`Volume not found for ID: ${id}`);
435
488
  return $(volume).find("a.volume-cover img").attr("data-original") || "";
436
489
  }
437
- //#endregion
438
- //#region src/queue.ts
490
+ // src/queue.ts
439
491
  /**
440
492
  * Simple backoff strategy for request rate limiting
441
493
  * - Normal delay: 500-1000ms random
@@ -464,10 +516,10 @@ var NovelChapterQueue = class {
464
516
  this.client = client;
465
517
  this.backoff = new SimpleBackoff();
466
518
  this.logger = logger;
467
- this.queue.on("add", () => {
519
+ this.queue.addEventListener("add", () => {
468
520
  this.logger?.debug(`[NovelChapterQueue] 任务已添加,当前排队数: ${this.queue.size} (等待中任务数: ${this.queue.pending})`);
469
521
  });
470
- this.queue.on("next", () => {
522
+ this.queue.addEventListener("next", () => {
471
523
  this.logger?.debug(`[NovelChapterQueue] 任务完成或超时,开始下一个任务。剩余:${this.queue.size} `);
472
524
  });
473
525
  }
@@ -525,10 +577,10 @@ var NovelInfoQueue = class {
525
577
  this.backoff = new SimpleBackoff();
526
578
  this.chapterQueue = chapterQueue;
527
579
  this.logger = logger;
528
- this.queue.on("add", () => {
580
+ this.queue.addEventListener("add", () => {
529
581
  this.logger?.debug(`[NovelInfoQueue] 任务已添加,当前排队数: ${this.queue.size} (等待中任务数: ${this.queue.pending})`);
530
582
  });
531
- this.queue.on("next", () => {
583
+ this.queue.addEventListener("next", () => {
532
584
  this.logger?.debug(`[NovelInfoQueue] 任务完成或超时,开始下一个任务。剩余:${this.queue.size} `);
533
585
  });
534
586
  }
@@ -602,8 +654,7 @@ var NovelInfoQueue = class {
602
654
  });
603
655
  }
604
656
  };
605
- //#endregion
606
- //#region src/search/common.ts
657
+ // src/search/common.ts
607
658
  function parseSearchHtml($) {
608
659
  const results = [];
609
660
  $("div.search-html-box div.search-result-list").each((_, el) => {
@@ -628,139 +679,348 @@ function parseBookHtml($) {
628
679
  coverUrl: $("div.book-img img").attr("src") || ""
629
680
  };
630
681
  }
631
- //#endregion
632
- //#region src/search/v2.ts
633
- async function refreshSearchTicket(fetchClient) {
634
- await fetchClient.text("https://www.linovelib.com/S6/?search_guard=css", { headers: {
635
- origin: "https://www.linovelib.com",
636
- referer: "https://www.linovelib.com/",
637
- "Sec-Fetch-Site": "same-origin"
638
- } });
639
- const guardJsResp = await fetchClient.text("https://www.linovelib.com/S6/?search_guard=js", { headers: {
640
- origin: "https://www.linovelib.com",
641
- referer: "https://www.linovelib.com/",
642
- "Sec-Fetch-Site": "same-origin"
643
- } });
644
- if (guardJsResp.mimeType !== "application/javascript") throw new Error(`Unexpected response type: ${guardJsResp.mimeType}`);
645
- const guardJsToken = guardJsResp.data.match(/jieqiSearchJs=([^;"]+)/)?.[1];
646
- if (!guardJsToken) throw new Error("Failed to extract jieqiSearchJs token from guard JS response");
647
- await fetchClient.cookieStore.set("jieqiSearchJs", guardJsToken, {
648
- domain: "www.linovelib.com",
649
- path: "/",
650
- maxAge: 3600,
651
- sameSite: "Lax",
652
- secure: true,
653
- httpOnly: true
654
- });
655
- const request = async () => fetchClient.text(`https://www.linovelib.com/S6/?search_guard=redeem&r=${Date.now()}`, { headers: {
656
- origin: "https://www.linovelib.com",
657
- referer: "https://www.linovelib.com/",
658
- "Sec-Fetch-Site": "same-origin"
659
- } });
660
- await runTimeout(request, 120);
661
- await runTimeout(request, 800);
662
- await runTimeout(request, 2e3);
682
+ // src/search/captcha.ts
683
+ const MODEL_FILENAME = "captcha_cropped.onnx";
684
+ const TARGET_HEIGHT = 64;
685
+ const CHARSET = ["", ..."0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];
686
+ let sessionPromise;
687
+ function moduleDirectory() {
688
+ return fileURLToPath(new URL(".", import.meta.url));
663
689
  }
664
- var EmptyBodyError = class extends Error {
690
+ /**
691
+ * 模型可能出现的几个位置:
692
+ * - 环境变量显式指定(部署时最可靠)
693
+ * - 与当前模块同级(api-server 打包后把模型拷到 dist 目录)
694
+ * - 包内 dist/../assets(npm 发布形态 / linovelib tsdown 产物)
695
+ * - 包内 src/search/../../assets(workspace 内直接执行 TS 源码)
696
+ * - 进程工作目录(Docker 镜像内 /app/captcha_cropped.onnx)
697
+ */
698
+ function resolveModelPath() {
699
+ const candidates = [
700
+ process.env.LINOVELIB_CAPTCHA_MODEL_PATH,
701
+ join(moduleDirectory(), MODEL_FILENAME),
702
+ join(moduleDirectory(), "..", "assets", MODEL_FILENAME),
703
+ join(moduleDirectory(), "..", "..", "assets", MODEL_FILENAME),
704
+ join(process.cwd(), MODEL_FILENAME)
705
+ ].filter((candidate) => Boolean(candidate));
706
+ for (const candidate of candidates) if (existsSync(candidate)) return candidate;
707
+ throw new Error(`无法找到搜索验证码识别模型 ${MODEL_FILENAME},尝试过的路径: ${candidates.join(", ")}`);
708
+ }
709
+ async function getSession() {
710
+ if (!sessionPromise) {
711
+ sessionPromise = (async () => {
712
+ const ort = await import("onnxruntime-node");
713
+ ort.env.logLevel = "error";
714
+ const model = await readFile(resolveModelPath());
715
+ return await ort.InferenceSession.create(model, {
716
+ executionProviders: ["cpu"],
717
+ graphOptimizationLevel: "all",
718
+ intraOpNumThreads: 1,
719
+ interOpNumThreads: 1
720
+ });
721
+ })();
722
+ sessionPromise.catch(() => {
723
+ sessionPromise = void 0;
724
+ });
725
+ }
726
+ return sessionPromise;
727
+ }
728
+ /**
729
+ * 验证码字符使用高饱和度颜色绘制在浅色噪点背景上。
730
+ * 直接转灰度会让部分颜色的字符与背景对比度不足,因此同时尝试多种通道变换,
731
+ * 让模型对同一张图投票,可以明显降低误识别率。
732
+ */
733
+ function channelVariants(image) {
734
+ const { width, height, channels, data } = image;
735
+ const total = width * height;
736
+ const saturation = new Uint8Array(total);
737
+ const maxChannel = new Uint8Array(total);
738
+ const minChannel = new Uint8Array(total);
739
+ for (let i = 0; i < total; i++) {
740
+ const offset = i * channels;
741
+ const r = data[offset] ?? 0;
742
+ const g = data[offset + 1] ?? r;
743
+ const b = data[offset + 2] ?? g;
744
+ const max = Math.max(r, g, b);
745
+ const min = Math.min(r, g, b);
746
+ saturation[i] = max - min;
747
+ maxChannel[i] = max;
748
+ minChannel[i] = min;
749
+ }
750
+ return [
751
+ saturation,
752
+ maxChannel,
753
+ minChannel
754
+ ];
755
+ }
756
+ function resizeBilinear(source, sourceWidth, sourceHeight, targetWidth, targetHeight) {
757
+ const output = new Uint8Array(targetWidth * targetHeight);
758
+ const scaleX = sourceWidth / targetWidth;
759
+ const scaleY = sourceHeight / targetHeight;
760
+ for (let y = 0; y < targetHeight; y++) {
761
+ const sourceY = Math.min(sourceHeight - 1, Math.max(0, (y + .5) * scaleY - .5));
762
+ const y0 = Math.floor(sourceY);
763
+ const y1 = Math.min(sourceHeight - 1, y0 + 1);
764
+ const weightY = sourceY - y0;
765
+ for (let x = 0; x < targetWidth; x++) {
766
+ const sourceX = Math.min(sourceWidth - 1, Math.max(0, (x + .5) * scaleX - .5));
767
+ const x0 = Math.floor(sourceX);
768
+ const x1 = Math.min(sourceWidth - 1, x0 + 1);
769
+ const weightX = sourceX - x0;
770
+ const topLeft = source[y0 * sourceWidth + x0] ?? 0;
771
+ const topRight = source[y0 * sourceWidth + x1] ?? topLeft;
772
+ const bottomLeft = source[y1 * sourceWidth + x0] ?? topLeft;
773
+ const bottomRight = source[y1 * sourceWidth + x1] ?? bottomLeft;
774
+ const top = topLeft + (topRight - topLeft) * weightX;
775
+ const bottom = bottomLeft + (bottomRight - bottomLeft) * weightX;
776
+ output[y * targetWidth + x] = Math.round(top + (bottom - top) * weightY);
777
+ }
778
+ }
779
+ return output;
780
+ }
781
+ function decodeCtcOutput(data, dims) {
782
+ const steps = dims[0] ?? 0;
783
+ const classes = dims[dims.length - 1] ?? 0;
784
+ let text = "";
785
+ let previous = -1;
786
+ let confidenceSum = 0;
787
+ for (let step = 0; step < steps; step++) {
788
+ const offset = step * classes;
789
+ let bestIndex = 0;
790
+ let bestValue = Number.NEGATIVE_INFINITY;
791
+ for (let index = 0; index < classes; index++) {
792
+ const value = data[offset + index] ?? Number.NEGATIVE_INFINITY;
793
+ if (value > bestValue) {
794
+ bestValue = value;
795
+ bestIndex = index;
796
+ }
797
+ }
798
+ let expSum = 0;
799
+ for (let index = 0; index < classes; index++) expSum += Math.exp((data[offset + index] ?? 0) - bestValue);
800
+ confidenceSum += expSum > 0 ? 1 / expSum : 0;
801
+ if (bestIndex !== previous && bestIndex !== 0) text += CHARSET[bestIndex] ?? "";
802
+ previous = bestIndex;
803
+ }
804
+ return {
805
+ text,
806
+ confidence: steps > 0 ? confidenceSum / steps : 0
807
+ };
808
+ }
809
+ function chooseBest(decoded) {
810
+ const fourCharacter = decoded.filter((item) => item.text.length === 4);
811
+ if (fourCharacter.length === 0) return decoded.reduce((best, item) => item.confidence > best.confidence ? item : best);
812
+ const votes = /* @__PURE__ */ new Map();
813
+ for (const item of fourCharacter) {
814
+ const current = votes.get(item.text);
815
+ if (current) {
816
+ current.count += 1;
817
+ current.confidence = Math.max(current.confidence, item.confidence);
818
+ } else votes.set(item.text, {
819
+ count: 1,
820
+ confidence: item.confidence
821
+ });
822
+ }
823
+ let winner = fourCharacter[0];
824
+ let winnerCount = -1;
825
+ let winnerConfidence = -1;
826
+ for (const [text, vote] of votes) if (vote.count > winnerCount || vote.count === winnerCount && vote.confidence > winnerConfidence) {
827
+ winner = {
828
+ text,
829
+ confidence: vote.confidence
830
+ };
831
+ winnerCount = vote.count;
832
+ winnerConfidence = vote.confidence;
833
+ }
834
+ return winner;
835
+ }
836
+ /**
837
+ * 识别 linovelib 搜索验证码(4 位数字/字母图片)。
838
+ * 使用 ddddocr 的 common_old 裁剪模型(MIT),见 assets/THIRD-PARTY-NOTICES.md。
839
+ */
840
+ async function solveCaptcha(image) {
841
+ const decoded = decode(image);
842
+ const targetWidth = Math.round(decoded.width * TARGET_HEIGHT / decoded.height);
843
+ const ort = await import("onnxruntime-node");
844
+ const session = await getSession();
845
+ const inputName = session.inputNames[0];
846
+ const outputName = session.outputNames[0];
847
+ if (!inputName || !outputName) throw new Error("验证码识别模型缺少输入或输出节点");
848
+ const decodedTexts = [];
849
+ for (const variant of channelVariants(decoded)) {
850
+ const resized = resizeBilinear(variant, decoded.width, decoded.height, targetWidth, TARGET_HEIGHT);
851
+ const input = new Float32Array(resized.length);
852
+ for (let i = 0; i < resized.length; i++) input[i] = (resized[i] ?? 0) / 255;
853
+ const output = (await session.run({ [inputName]: new ort.Tensor("float32", input, [
854
+ 1,
855
+ 1,
856
+ TARGET_HEIGHT,
857
+ targetWidth
858
+ ]) }))[outputName];
859
+ if (!output) throw new Error("验证码识别模型没有返回结果");
860
+ decodedTexts.push(decodeCtcOutput(output.data, output.dims));
861
+ }
862
+ if (decodedTexts.length === 0) throw new Error("验证码识别失败:没有任何可用结果");
863
+ return chooseBest(decodedTexts).text;
864
+ }
865
+ // src/search/v3.ts
866
+ const SEARCH_URL = "https://www.linovelib.com/S6/";
867
+ const ORIGIN = "https://www.linovelib.com";
868
+ /** 站点要求两次搜索 POST 之间至少间隔 5 秒,这里留一点余量。 */
869
+ const MIN_SEARCH_INTERVAL_MS = 5200;
870
+ const MAX_VERIFICATION_ATTEMPTS = 3;
871
+ const MAX_RATE_LIMIT_ATTEMPTS = 3;
872
+ const NEXT_PAGE_DELAY_MIN_MS = 300;
873
+ const searchRequestHeaders = {
874
+ origin: ORIGIN,
875
+ referer: `${ORIGIN}/`
876
+ };
877
+ const searchRefererHeaders = {
878
+ origin: ORIGIN,
879
+ referer: SEARCH_URL
880
+ };
881
+ function sleep(ms) {
882
+ return new Promise((resolve) => setTimeout(resolve, ms));
883
+ }
884
+ function isVerificationPage(html) {
885
+ return html.includes("name=\"search_challenge\"") || html.includes("<title>搜索验证</title>");
886
+ }
887
+ function isRateLimitedPage(html) {
888
+ return html.includes("两次搜索的间隔时间不得少于");
889
+ }
890
+ function isBookPage(html) {
891
+ return html.includes("book-html-box");
892
+ }
893
+ /** 搜索验证流程无法自动完成时抛出,便于上层区分站点验证码问题。 */
894
+ var SearchVerificationError = class extends Error {
665
895
  constructor(message) {
666
896
  super(message);
667
- this.name = "EmptyBodyError";
897
+ this.name = "SearchVerificationError";
668
898
  }
669
899
  };
670
- var SearchTicketManager = class {
900
+ var SearchRateLimitError = class extends Error {
901
+ constructor(message) {
902
+ super(message);
903
+ this.name = "SearchRateLimitError";
904
+ }
905
+ };
906
+ /**
907
+ * 新版搜索会话。
908
+ *
909
+ * 站点现状(2026-11):
910
+ * - 未验证客户端 POST/GET 搜索页会返回「搜索验证」图片验证码页;
911
+ * - 提交正确验证码后服务端会下发约 30 分钟有效的验证 cookie,期间搜索免验证;
912
+ * - 两次搜索间隔不得少于 5 秒,否则返回错误页;
913
+ * - 验证过期后任意搜索/翻页请求都会重新出现验证码页。
914
+ *
915
+ * 该类负责串行化搜索请求、维护最小搜索间隔、自动识别并提交验证码,并复用验证态。
916
+ */
917
+ var SearchSession = class {
671
918
  fetchClient;
672
919
  mutex = new Mutex();
673
- ticketCookieKey = "jieqiSearchTicket";
674
- domain = "www.linovelib.com";
675
- prefetching = false;
920
+ lastSearchAt = 0;
676
921
  constructor(fetchClient) {
677
922
  this.fetchClient = fetchClient;
678
923
  }
679
- async hasValidTicket() {
680
- return (await this.fetchClient.cookieStore.getForUrl(`https://${this.domain}/`)).some((c) => c.name === this.ticketCookieKey);
924
+ async search(keyword) {
925
+ return await this.mutex.runExclusive(async () => {
926
+ const html = await this.requestSearch(keyword);
927
+ return await this.parseResults(html);
928
+ });
681
929
  }
682
- async consumeTicket() {
683
- await this.fetchClient.cookieStore.delete(this.ticketCookieKey, this.domain);
930
+ async parseResults(html) {
931
+ const $ = load(html);
932
+ if (isBookPage(html) && $("div.book-html-box").length > 0) return [parseBookHtml($)];
933
+ const results = parseSearchHtml($);
934
+ const totalPages = Number($("em#pagestats").text().match(/1\/(\d+)/)?.[1] ?? "1");
935
+ const nextHref = $("a.next").attr("href");
936
+ if (totalPages > 1 && nextHref) results.push(...await this.collectNextPages(nextHref));
937
+ return results;
684
938
  }
685
- /**
686
- * 唯一入口:确保 ticket 存在 -> 执行业务请求 -> 消费(清空) ticket。
687
- * 整个过程串行、互斥,同一时刻只允许一个调用在跑。
688
- */
689
- async runExclusive(task) {
690
- return this.mutex.runExclusive(async () => {
691
- if (!await this.hasValidTicket()) await refreshSearchTicket(this.fetchClient);
692
- while (true) try {
693
- const result = await task();
694
- await this.consumeTicket();
695
- return result;
939
+ async collectNextPages(startHref) {
940
+ const results = [];
941
+ let href = startHref;
942
+ while (href) {
943
+ await sleep(NEXT_PAGE_DELAY_MIN_MS + Math.random() * 500);
944
+ const html = await this.fetchPage(new URL(href, SEARCH_URL).toString());
945
+ const $ = load(html);
946
+ results.push(...parseSearchHtml($));
947
+ href = $("a.next").attr("href") || void 0;
948
+ }
949
+ return results;
950
+ }
951
+ async fetchPage(url) {
952
+ let response = await this.fetchClient.text(url, { headers: searchRefererHeaders });
953
+ if (response.mimeType !== "text/html") throw new Error(`Unexpected response type: ${response.mimeType}`);
954
+ if (isVerificationPage(response.data)) {
955
+ await this.verifySearch(response.data);
956
+ response = await this.fetchClient.text(url, { headers: searchRefererHeaders });
957
+ if (response.mimeType !== "text/html") throw new Error(`Unexpected response type: ${response.mimeType}`);
958
+ if (isVerificationPage(response.data)) throw new SearchVerificationError("搜索验证后翻页仍被要求验证");
959
+ }
960
+ if (response.data === "") throw new Error("Empty response body when fetching search page");
961
+ return response.data;
962
+ }
963
+ async requestSearch(keyword) {
964
+ for (let attempt = 0; attempt < MAX_RATE_LIMIT_ATTEMPTS; attempt++) {
965
+ await this.waitForSearchSlot();
966
+ const response = await this.fetchClient.text(SEARCH_URL, {
967
+ method: "POST",
968
+ body: new URLSearchParams({ searchkey: keyword }),
969
+ headers: searchRequestHeaders
970
+ });
971
+ this.lastSearchAt = Date.now();
972
+ if (response.mimeType !== "text/html") throw new Error(`Unexpected response type: ${response.mimeType}`);
973
+ if (response.data === "") throw new Error("Empty response body when fetching search results");
974
+ if (isRateLimitedPage(response.data)) continue;
975
+ if (isVerificationPage(response.data)) return await this.verifySearch(response.data);
976
+ return response.data;
977
+ }
978
+ throw new SearchRateLimitError(`搜索请求被站点限流,已重试 ${MAX_RATE_LIMIT_ATTEMPTS} 次`);
979
+ }
980
+ async verifySearch(verificationHtml) {
981
+ let currentHtml = verificationHtml;
982
+ for (let attempt = 0; attempt < MAX_VERIFICATION_ATTEMPTS; attempt++) {
983
+ const $ = load(currentHtml);
984
+ const challenge = $("input[name=search_challenge]").attr("value");
985
+ const searchkey = $("input[name=searchkey]").attr("value");
986
+ const searchtype = $("input[name=searchtype]").attr("value") ?? "all";
987
+ const imageSrc = $("#search-captcha").attr("src");
988
+ if (!challenge || !imageSrc || !searchkey) throw new SearchVerificationError("无法解析搜索验证码页面");
989
+ const image = await this.fetchClient.binary(new URL(imageSrc, SEARCH_URL).toString(), { headers: searchRefererHeaders });
990
+ if (!image.mimeType.startsWith("image/")) throw new SearchVerificationError(`验证码图片响应类型异常: ${image.mimeType}`);
991
+ let code;
992
+ try {
993
+ code = await solveCaptcha(image.data);
696
994
  } catch (error) {
697
- if (error instanceof EmptyBodyError) {
698
- await refreshSearchTicket(this.fetchClient);
699
- continue;
700
- }
701
- await this.consumeTicket();
702
- throw error;
995
+ throw new SearchVerificationError(`验证码识别失败: ${error instanceof Error ? error.message : String(error)}`);
703
996
  }
704
- });
997
+ await this.waitForSearchSlot();
998
+ const response = await this.fetchClient.text(SEARCH_URL, {
999
+ method: "POST",
1000
+ body: new URLSearchParams({
1001
+ searchkey,
1002
+ searchtype,
1003
+ search_challenge: challenge,
1004
+ search_code: code
1005
+ }),
1006
+ headers: searchRefererHeaders
1007
+ });
1008
+ this.lastSearchAt = Date.now();
1009
+ if (response.mimeType !== "text/html") throw new Error(`Unexpected response type: ${response.mimeType}`);
1010
+ if (!isVerificationPage(response.data)) return response.data;
1011
+ currentHtml = response.data;
1012
+ }
1013
+ throw new SearchVerificationError(`搜索验证码连续识别失败(已尝试 ${MAX_VERIFICATION_ATTEMPTS} 次)`);
705
1014
  }
706
- /**
707
- * 后台预取:模拟源站"成功页面里嵌入 refresh 逻辑"的行为。
708
- * 不在调用方持有的锁内执行,而是自己重新抢锁,
709
- * 这样不会拖慢刚刚那次请求的 return。
710
- */
711
- schedulePrefetch() {
712
- if (this.prefetching) return;
713
- this.prefetching = true;
714
- this.mutex.runExclusive(async () => {
715
- if (await this.hasValidTicket()) return;
716
- await refreshSearchTicket(this.fetchClient);
717
- }).catch((err) => {
718
- console.error("[SearchTicketManager] prefetch failed:", err);
719
- }).finally(() => {
720
- this.prefetching = false;
721
- });
1015
+ async waitForSearchSlot() {
1016
+ const elapsed = Date.now() - this.lastSearchAt;
1017
+ if (elapsed < MIN_SEARCH_INTERVAL_MS) await sleep(MIN_SEARCH_INTERVAL_MS - elapsed);
722
1018
  }
723
1019
  };
724
- async function obtainFromNextPage(path, fetchClient, ticketManager) {
725
- const $ = load(await ticketManager.runExclusive(async () => {
726
- const response = await fetchClient.text(`https://www.linovelib.com${path}`, { headers: {
727
- origin: "https://www.linovelib.com",
728
- referer: "https://www.linovelib.com/S6/"
729
- } });
730
- if (response.mimeType !== "text/html") throw new Error(`Unexpected response type: ${response.mimeType}`);
731
- if (response.data === "") throw new EmptyBodyError("Empty response body when fetching next page");
732
- return response.data;
733
- }));
734
- const results = [];
735
- results.push(...parseSearchHtml($));
736
- if ($("a.next").length > 0) results.push(...await obtainFromNextPage($("a.next").attr("href") || "", fetchClient, ticketManager));
737
- return results;
1020
+ async function searchNovelsV3(keyword, _fetchClient, session) {
1021
+ return await session.search(keyword);
738
1022
  }
739
- async function searchNovelsV2(keyword, fetchClient, ticketManager) {
740
- const searchHtml = await ticketManager.runExclusive(async () => {
741
- const tr = await fetchClient.text("https://www.linovelib.com/S6/", {
742
- method: "POST",
743
- body: new URLSearchParams({ searchkey: keyword }),
744
- headers: {
745
- origin: "https://www.linovelib.com",
746
- referer: "https://www.linovelib.com/"
747
- }
748
- });
749
- if (tr?.mimeType !== "text/html") throw new Error(`Unexpected response type: ${tr?.mimeType}`);
750
- if (tr?.data === "") throw new EmptyBodyError("Empty response body when fetching search results");
751
- return tr.data;
752
- });
753
- const results = [];
754
- const $ = load(searchHtml);
755
- if ($("div.book-html-box").length > 0) return [parseBookHtml($)];
756
- results.push(...parseSearchHtml($));
757
- const pages = $("em#pagestats").text().match(/1\/(\d+)/)?.[1] || "1";
758
- if (Number(pages) > 1) results.push(...await obtainFromNextPage($("a.next").attr("href") || "", fetchClient, ticketManager));
759
- ticketManager.schedulePrefetch();
760
- return results;
761
- }
762
- //#endregion
763
- //#region src/session.ts
1023
+ // src/session.ts
764
1024
  async function refreshSessionId(fetchClient, loginConfig) {
765
1025
  await fetchClient.request({
766
1026
  url: "https://www.linovelib.com/login.php",
@@ -790,14 +1050,13 @@ async function ensureValidSession(fetchClient, loginConfig) {
790
1050
  }
791
1051
  return true;
792
1052
  }
793
- //#endregion
794
- //#region src/client.ts
1053
+ // src/client.ts
795
1054
  var LinovelibClient = class {
796
1055
  storage;
797
1056
  fetchClient;
798
1057
  novelChapterQueue;
799
1058
  novelInfoQueue;
800
- searchTicketManager;
1059
+ searchSession;
801
1060
  options;
802
1061
  logger;
803
1062
  isSessionValid = void 0;
@@ -851,7 +1110,7 @@ var LinovelibClient = class {
851
1110
  this.fetchClient = new BrowserFetchClient(browserFetchOptions);
852
1111
  this.novelChapterQueue = new NovelChapterQueue(this.fetchClient, this.logger);
853
1112
  this.novelInfoQueue = new NovelInfoQueue(this.fetchClient, this.novelChapterQueue, this.logger);
854
- this.searchTicketManager = new SearchTicketManager(this.fetchClient);
1113
+ this.searchSession = new SearchSession(this.fetchClient);
855
1114
  }
856
1115
  async getNovelInfo(id) {
857
1116
  if (this.options?.session.enabled && !this.isSessionValid) this.isSessionValid = await ensureValidSession(this.fetchClient, {
@@ -872,7 +1131,7 @@ var LinovelibClient = class {
872
1131
  username: this.options.session.username,
873
1132
  password: this.options.session.password
874
1133
  });
875
- return await searchNovelsV2(keyword, this.fetchClient, this.searchTicketManager);
1134
+ return await searchNovelsV3(keyword, this.fetchClient, this.searchSession);
876
1135
  }
877
1136
  async getNovelCover(id) {
878
1137
  if (this.options?.session.enabled && !this.isSessionValid) this.isSessionValid = await ensureValidSession(this.fetchClient, {
@@ -899,12 +1158,19 @@ var LinovelibClient = class {
899
1158
  async getCover(url, referer) {
900
1159
  return await this.fetchClient.binary(url, { headers: { Referer: referer || "https://www.linovelib.com/" } });
901
1160
  }
1161
+ async getIllustration(url, referer) {
1162
+ if (this.options?.session.enabled && !this.isSessionValid) this.isSessionValid = await ensureValidSession(this.fetchClient, {
1163
+ username: this.options.session.username,
1164
+ password: this.options.session.password
1165
+ });
1166
+ return await this.getCover(url, referer || "https://www.linovelib.com/");
1167
+ }
902
1168
  async getChapter(novelId, chapterId) {
903
1169
  if (this.options?.session.enabled && !this.isSessionValid) this.isSessionValid = await ensureValidSession(this.fetchClient, {
904
1170
  username: this.options.session.username,
905
1171
  password: this.options.session.password
906
1172
  });
907
- const cachedJsVersion = this.storage ? await this.storage.getCache("chapterlog_js_version", z$1.string()) ?? void 0 : void 0;
1173
+ const cachedJsVersion = this.storage ? await this.storage.getCache("chapterlog_js_version", z.string()) ?? void 0 : void 0;
908
1174
  const cachedCoefficients = this.storage ? await this.storage.getCache("coefficients", descrambleCoefficientsSchema) ?? void 0 : void 0;
909
1175
  const result = await getChapter(chapterId, novelId, this.novelChapterQueue, this.fetchClient, cachedJsVersion, cachedCoefficients);
910
1176
  if (this.storage && result) {
@@ -914,7 +1180,33 @@ var LinovelibClient = class {
914
1180
  return result?.content;
915
1181
  }
916
1182
  };
917
- //#endregion
918
- export { LinovelibClient, novelIdToCoverUrl };
1183
+ // src/illustration.ts
1184
+ function normalizeIllustrationUrl(rawSrc) {
1185
+ if (!rawSrc) return;
1186
+ const trimmed = rawSrc.trim();
1187
+ if (!trimmed) return;
1188
+ const normalized = trimmed.startsWith("//") ? `https:${trimmed}` : trimmed;
1189
+ if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) return;
1190
+ return normalized;
1191
+ }
1192
+ function extractChapterIllustrationUrls(html) {
1193
+ const $ = load(html, null, false);
1194
+ const urls = /* @__PURE__ */ new Set();
1195
+ $("img").each((_, el) => {
1196
+ const normalized = normalizeIllustrationUrl($(el).attr("src"));
1197
+ if (normalized) urls.add(normalized);
1198
+ });
1199
+ return [...urls];
1200
+ }
1201
+ function rewriteChapterIllustrations(html, mapUrl) {
1202
+ const $ = load(html, null, false);
1203
+ $("img").each((_, el) => {
1204
+ const $el = $(el);
1205
+ const normalized = normalizeIllustrationUrl($el.attr("src"));
1206
+ if (normalized) $el.attr("src", mapUrl(normalized));
1207
+ });
1208
+ return $.html();
1209
+ }
1210
+ export { LinovelibClient, extractChapterIllustrationUrls, isUnresolvedChapterId, novelIdToCoverUrl, rewriteChapterIllustrations };
919
1211
 
920
1212
  //# sourceMappingURL=index.mjs.map