multporn-api-sdk 0.1.3 → 0.1.4

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.
@@ -1,3 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
1
7
  // src/http.ts
2
8
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
3
9
  function hasAbortController() {
@@ -208,245 +214,1611 @@ var HttpClient = class {
208
214
  }
209
215
  };
210
216
 
211
- // src/client-core.ts
212
- var DEFAULT_HEADERS = {
213
- Referer: "https://multporn.net",
214
- Origin: "https://multporn.net",
215
- Accept: "*/*",
216
- "User-Agent": "Mozilla/5.0 (Linux; Android 12; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0 Mobile Safari/537.36"
217
- };
218
- function absolutize(base, href) {
217
+ // src/api/alphabet.ts
218
+ var alphabet_exports = {};
219
+ __export(alphabet_exports, {
220
+ alphabetItems: () => alphabetItems,
221
+ alphabetLetters: () => alphabetLetters
222
+ });
223
+
224
+ // src/parsers/alphabet.ts
225
+ import * as cheerio2 from "cheerio/slim";
226
+
227
+ // src/utils.ts
228
+ function toAbsolute(baseURL, href) {
219
229
  if (!href) return void 0;
220
230
  try {
221
- if (href.startsWith("//")) return new URL("https:" + href).href;
222
- return new URL(href, base).href;
231
+ return new URL(href).toString();
232
+ } catch {
233
+ if (href.startsWith("//")) {
234
+ const base = new URL(baseURL);
235
+ return `${base.protocol}${href}`;
236
+ }
237
+ return new URL(href.replace(/^\//, ""), baseURL.replace(/\/+$/, "") + "/").toString();
238
+ }
239
+ }
240
+ function uniq(arr) {
241
+ return Array.from(new Set(arr));
242
+ }
243
+ function absUrl(base, href) {
244
+ if (!href) return null;
245
+ try {
246
+ return new URL(href, base).toString();
223
247
  } catch {
224
- return void 0;
248
+ return null;
225
249
  }
226
250
  }
227
- function looksLikeListingUrl(u) {
228
- return /\/(comics|manga|munga|pictures|video|gay_porn_comics|hentai_manga)\//i.test(u);
251
+ function normSpace(s) {
252
+ return (s ?? "").replace(/\s+/g, " ").trim();
229
253
  }
230
- function shouldSkipThumb(u) {
231
- if (!u) return true;
232
- return /(logo|avatar|sprite|icon|favicon)/i.test(u);
254
+ function parseNumberLike(s) {
255
+ if (!s) return void 0;
256
+ const m = String(s).replace(/[^\d.,]/g, "").replace(",", ".");
257
+ const n = parseFloat(m);
258
+ return Number.isFinite(n) ? n : void 0;
233
259
  }
234
- var MultpornClientCore = class {
235
- http;
236
- baseURL;
237
- dom;
238
- constructor(opts) {
239
- this.baseURL = (opts.baseURL ?? "https://multporn.net").replace(/\/+$/, "");
240
- this.http = new HttpClient({
241
- baseURL: this.baseURL,
242
- headers: { ...DEFAULT_HEADERS, ...opts.headers ?? {} },
243
- timeoutMs: opts.timeoutMs ?? 15e3,
244
- retry: opts.retry,
245
- userAgent: opts.userAgent
260
+ function parseIntLike(s) {
261
+ if (!s) return void 0;
262
+ const n = parseInt(String(s).replace(/[^\d]/g, ""), 10);
263
+ return Number.isFinite(n) ? n : void 0;
264
+ }
265
+ function guessKindFromPath(path) {
266
+ const p = path.split("?")[0].split("#")[0];
267
+ if (p.includes("/hentai_manga/") || p.includes("/munga/")) return "manga";
268
+ if (p.includes("/comics/")) return "comics";
269
+ if (p.includes("/pictures/")) return "pictures";
270
+ if (p.includes("/humor/")) return "humor";
271
+ if (p.includes("/video/")) return "video";
272
+ if (p.includes("/games/")) return "game";
273
+ return "other";
274
+ }
275
+ function guessAlphabetSectionFromPath(path) {
276
+ const slug = String(path || "").trim().replace(/^\//, "").split("/")[0]?.toLowerCase();
277
+ const map = {
278
+ comics: "alphabetical_order_comics",
279
+ manga: "alphabetical_order_manga",
280
+ pictures: "alphabetical_order_pipictures",
281
+ porn_gifs: "alphabetical_order_gif",
282
+ characters: "alphabetical_order_characters",
283
+ category_comic: "alphabetical_order_category_comic",
284
+ authors_comics: "alphabetical_order_authors_comics",
285
+ authors_hentai: "alphabetical_order_authors_hentai",
286
+ pipictures: "alphabetical_order_pipictures"
287
+ };
288
+ return map[slug] || (slug ? `alphabetical_order_${slug}` : "alphabetical_order");
289
+ }
290
+
291
+ // src/parsers/pagination.ts
292
+ import * as cheerio from "cheerio/slim";
293
+ function pageIndexFromParam(raw) {
294
+ if (!raw) return null;
295
+ const decoded = decodeURIComponent(String(raw));
296
+ const parts = decoded.split(",").map((s) => parseInt(s.trim(), 10)).filter((n) => Number.isFinite(n));
297
+ if (!parts.length) return null;
298
+ return Math.max(...parts);
299
+ }
300
+ function pageIndexFromHref(href) {
301
+ if (!href) return null;
302
+ try {
303
+ const u = new URL(href, "https://example.com");
304
+ return pageIndexFromParam(u.searchParams.get("page"));
305
+ } catch {
306
+ const m = href.match(/[?&]page=([^&#]+)/i);
307
+ return m ? pageIndexFromParam(m[1]) : null;
308
+ }
309
+ }
310
+ function extractTotalPages(html) {
311
+ const $ = cheerio.load(html);
312
+ const root = $(
313
+ "ul.pager, nav.pagination, .pagination, .item-list .pager, #content .pager"
314
+ ).first();
315
+ if (!root.length) return 1;
316
+ const lastHref = root.find('li.pager-last a[href], a[rel="last"], a[title*="Last"], a[title*="\u041F\u043E\u0441\u043B\u0435\u0434\u043D\u044F\u044F"]').attr("href") || void 0;
317
+ if (lastHref) {
318
+ const idx = pageIndexFromHref(lastHref);
319
+ if (idx != null) return Math.max(1, idx + 1);
320
+ }
321
+ let maxPages = 0;
322
+ root.find("a[href]").each((_, a) => {
323
+ const href = String($(a).attr("href") || "");
324
+ const idx = pageIndexFromHref(href);
325
+ if (idx != null) maxPages = Math.max(maxPages, idx + 1);
326
+ });
327
+ root.find("a, li, span").each((_, el) => {
328
+ const n = Number(($(el).text() || "").trim());
329
+ if (Number.isFinite(n)) maxPages = Math.max(maxPages, n);
330
+ });
331
+ return Math.max(1, maxPages || 1);
332
+ }
333
+
334
+ // src/parsers/alphabet.ts
335
+ function parseAlphabetLetters(html, baseURL) {
336
+ const $ = cheerio2.load(html);
337
+ const letters = [];
338
+ $(".views-summary a[href]").each((_, a) => {
339
+ const el = $(a);
340
+ const raw = normSpace(el.text());
341
+ if (!raw) return;
342
+ const count = parseIntLike(raw);
343
+ const label = raw.replace(/\(\s*\d+\s*\)\s*$/, "").trim() || raw;
344
+ const hrefRel = el.attr("href") || "";
345
+ const href = toAbsolute(baseURL, hrefRel) || "";
346
+ const lastSeg = decodeURIComponent((hrefRel.split("/").filter(Boolean).pop() || "").trim());
347
+ if (!label || !href) return;
348
+ letters.push({
349
+ label,
350
+ value: lastSeg || label,
351
+ href,
352
+ count: typeof count === "number" ? count : void 0,
353
+ active: el.hasClass("active") || /(^|\s)active(\s|$)/.test(el.attr("class") || "")
354
+ });
355
+ });
356
+ const uniq3 = /* @__PURE__ */ new Map();
357
+ for (const l of letters) if (!uniq3.has(l.value)) uniq3.set(l.value, l);
358
+ return Array.from(uniq3.values());
359
+ }
360
+ function parseAlphabetInline(html, baseURL) {
361
+ const $ = cheerio2.load(html);
362
+ const containers = [];
363
+ containers.push(...$(".view-glossary-comics").toArray());
364
+ if (containers.length === 0) containers.push(...$(".view-glossary").toArray());
365
+ if (containers.length === 0) {
366
+ const anyNodes = $(".view").has(".views-summary a").toArray();
367
+ const onlyElements = anyNodes.filter((n) => n?.type === "tag");
368
+ containers.push(...onlyElements);
369
+ }
370
+ if (containers.length === 0) return null;
371
+ const grouped = /* @__PURE__ */ new Map();
372
+ for (const cont of containers) {
373
+ const $cont = $(cont);
374
+ $cont.find(".views-summary a[href]").each((__, a) => {
375
+ const el = $(a);
376
+ const raw = normSpace(el.text());
377
+ if (!raw) return;
378
+ const count = parseIntLike(raw);
379
+ const label = raw.replace(/\(\s*\d+\s*\)\s*$/, "").trim() || raw;
380
+ const hrefRel = el.attr("href") || "";
381
+ const hrefAbs = toAbsolute(baseURL, hrefRel);
382
+ if (!hrefAbs) return;
383
+ let section = "";
384
+ try {
385
+ const p = new URL(hrefAbs).pathname;
386
+ const m = p.match(/^\/([^/]+)/);
387
+ section = m ? m[1] : "";
388
+ } catch {
389
+ }
390
+ const value = decodeURIComponent((hrefRel.split("/").filter(Boolean).pop() || "").trim()) || label;
391
+ const entry = {
392
+ label,
393
+ value,
394
+ href: hrefAbs,
395
+ count: typeof count === "number" ? count : void 0,
396
+ active: el.hasClass("active") || /(^|\s)active(\s|$)/.test(el.attr("class") || "")
397
+ };
398
+ const arr = grouped.get(section) ?? [];
399
+ if (!arr.some((x) => x.value === entry.value)) arr.push(entry);
400
+ grouped.set(section, arr);
246
401
  });
247
- this.dom = opts.dom;
248
402
  }
249
- text(el) {
250
- return this.dom.text(el);
403
+ if (!grouped.size) return null;
404
+ let chosen = null;
405
+ for (const [sec, letters] of grouped.entries()) {
406
+ if (letters.some((l) => l.active)) {
407
+ chosen = { section: sec, letters };
408
+ break;
409
+ }
251
410
  }
252
- attr(el, n) {
253
- return this.dom.attr(el, n) ?? "";
411
+ if (!chosen) {
412
+ let bestSec = "";
413
+ let bestArr = [];
414
+ for (const [sec, letters] of grouped.entries()) {
415
+ if (letters.length > bestArr.length) {
416
+ bestSec = sec;
417
+ bestArr = letters;
418
+ }
419
+ }
420
+ chosen = { section: bestSec, letters: bestArr };
254
421
  }
255
- pickImg(el) {
256
- if (!el) return void 0;
257
- const inNode = el.querySelector?.("img") ?? null;
258
- const imgEl = inNode || el;
259
- const src = this.attr(imgEl, "data-src") || this.attr(imgEl, "data-original") || this.attr(imgEl, "src");
260
- return absolutize(this.baseURL, src);
422
+ if (!chosen) {
423
+ const [sec, letters] = grouped.entries().next().value;
424
+ chosen = { section: sec, letters };
261
425
  }
262
- parseListing(html) {
263
- const doc = this.dom.parse(html);
264
- const root = doc.documentElement ?? doc;
265
- const anchors = this.dom.qsa(root, "a[href]");
266
- const seen = /* @__PURE__ */ new Set();
267
- const out = [];
268
- for (const a of anchors) {
269
- const href = this.attr(a, "href");
270
- const url = absolutize(this.baseURL, href);
271
- if (!url || !looksLikeListingUrl(url)) continue;
272
- if (seen.has(url)) continue;
273
- const img = this.pickImg(a) || this.pickImg(this.dom.closest(a, "figure")) || this.pickImg(this.dom.closest(a, ".thumb")) || this.pickImg(a.parentNode);
274
- const title = this.attr(a, "title") || this.text(a);
275
- if (!title) continue;
276
- const thumb = shouldSkipThumb(img) ? void 0 : img;
277
- out.push({ title, url, thumb });
426
+ chosen.letters.sort((a, b) => a.label.localeCompare(b.label, "en"));
427
+ if (!looksLikeAlphabet(chosen.letters)) return null;
428
+ return { section: chosen.section, letters: chosen.letters };
429
+ }
430
+ function looksLikeAlphabet(letters) {
431
+ const short = letters.filter((l) => /^[A-Z#]$/i.test(l.label.trim())).length;
432
+ return letters.length >= 10 && short >= 10;
433
+ }
434
+ function pickFromSrcset(srcset) {
435
+ if (!srcset) return;
436
+ const first = srcset.split(",")[0]?.trim();
437
+ if (!first) return;
438
+ const url = first.split(/\s+/)[0];
439
+ return url || void 0;
440
+ }
441
+ function pickFromStyle(style) {
442
+ if (!style) return;
443
+ const m = style.match(/url\((['"]?)(.*?)\1\)/i);
444
+ return m?.[2] || void 0;
445
+ }
446
+ function pickThumbUrl(scope, baseURL) {
447
+ const candidates = [
448
+ ".views-field-field-comg-preview img",
449
+ ".views-field-field-cat-preview img",
450
+ ".views-field-field-category-preview img",
451
+ ".views-field-field-man-preview-1 img",
452
+ ".views-field-field-man-preview img",
453
+ ".views-field-field-author-preview img",
454
+ ".views-field-field-authors-pre img",
455
+ ".views-field-field-gif-pre-1 img",
456
+ ".views-field-field-gif-preview img",
457
+ ".views-field-field-gif-pre img",
458
+ ".views-field-field-gif img",
459
+ ".views-field-field-preview img",
460
+ ".views-field-field-image img",
461
+ ".views-field-field-avatar img",
462
+ ".field-content a > img",
463
+ ".field-content img",
464
+ "a > img",
465
+ "img"
466
+ ];
467
+ for (const sel of candidates) {
468
+ const img = scope.find(sel).first();
469
+ if (img.length) {
470
+ const ds = img.attr("data-src") || img.attr("data-original");
471
+ const ss = pickFromSrcset(img.attr("srcset") || "");
472
+ const src = ds || ss || img.attr("src");
473
+ const abs = toAbsolute(baseURL, src || "");
474
+ if (abs) return abs;
475
+ }
476
+ }
477
+ const srcset = pickFromSrcset(scope.find("picture source").first().attr("srcset") || "");
478
+ if (srcset) {
479
+ const abs = toAbsolute(baseURL, srcset);
480
+ if (abs) return abs;
481
+ }
482
+ const bg = pickFromStyle(
483
+ scope.attr("style") || scope.find('[style*="background-image"]').first().attr("style")
484
+ );
485
+ if (bg) {
486
+ const abs = toAbsolute(baseURL, bg);
487
+ if (abs) return abs;
488
+ }
489
+ return void 0;
490
+ }
491
+ function parseAlphabetListing(html, baseURL, page) {
492
+ const $ = cheerio2.load(html);
493
+ const items = [];
494
+ $("table.views-view-grid td").each((_, td) => {
495
+ const scope = $(td);
496
+ const a = scope.find(
497
+ ".views-field-title a[href], .views-field-name a[href], strong a[href], h5 a[href], a[href]"
498
+ ).first();
499
+ const href = a.attr("href") || "";
500
+ const url = toAbsolute(baseURL, href);
501
+ const title = (a.text() || scope.find(".views-field-title .field-content").text() || scope.find(".views-field-name .field-content").text() || scope.find("strong").first().text() || scope.find("h5").first().text() || "").trim();
502
+ const thumb = pickThumbUrl(scope, baseURL);
503
+ if (url && title) items.push({ title, url, thumb });
504
+ });
505
+ if (items.length === 0) {
506
+ $(".view .view-content .views-row").each((_, row) => {
507
+ const el = $(row);
508
+ const a = el.find(
509
+ ".views-field-title a[href], .views-field-name a[href], strong a[href], h5 a[href], a[href]"
510
+ ).first();
511
+ const href = a.attr("href") || "";
512
+ const url = toAbsolute(baseURL, href);
513
+ const title = (a.text() || el.find(".views-field-title .field-content").text() || el.find(".views-field-name .field-content").text() || el.find("strong").first().text() || el.find("h5").first().text() || "").trim();
514
+ const thumb = pickThumbUrl(el, baseURL);
515
+ if (url && title) items.push({ title, url, thumb });
516
+ });
517
+ }
518
+ const totalPages = extractTotalPages(html);
519
+ const hasNext = page + 1 < totalPages;
520
+ return { items, page, hasNext, totalPages };
521
+ }
522
+
523
+ // src/api/alphabet.ts
524
+ var ALPHA_CFG = {
525
+ comics: { hubPath: "/comic", alphaPrefix: "/alphabetical_order_comics" },
526
+ category_comic: { hubPath: "/category_comic", alphaPrefix: "/category_comic/alphabetical" },
527
+ characters: { hubPath: "/characters", alphaPrefix: "/alphabetical_order_characters" },
528
+ authors_comics: { hubPath: "/authors_comics", alphaPrefix: "/alphabetical_order_authors" },
529
+ pipictures: { hubPath: "/pipictures", alphaPrefix: "/alphabetical_order_pictures" },
530
+ porn_gifs: { hubPath: "/porn_gifs", alphaPrefix: "/alphabetical_order_gif" },
531
+ manga: { hubPath: "/munga", alphaPrefix: "/alphabetical_order_manga" },
532
+ authors_hentai: { hubPath: "/authors_hentai", alphaPrefix: "/authors_hentai/alphabetical" }
533
+ };
534
+ async function alphabetLetters(http, baseURL, section) {
535
+ const cfg = ALPHA_CFG[section];
536
+ const hub = cfg.hubPath;
537
+ const html = await http.getHtml(hub);
538
+ return parseAlphabetLetters(html, baseURL);
539
+ }
540
+ async function alphabetItems(http, baseURL, section, letter, page = 0) {
541
+ const cfg = ALPHA_CFG[section];
542
+ const letterSeg = encodeURIComponent(letter);
543
+ const html = await http.getHtml(`${cfg.alphaPrefix}/${letterSeg}?page=${page}`);
544
+ return parseAlphabetListing(html, baseURL, page);
545
+ }
546
+
547
+ // src/api/listings.ts
548
+ var listings_exports = {};
549
+ __export(listings_exports, {
550
+ latest: () => latest,
551
+ listByPath: () => listByPath
552
+ });
553
+
554
+ // src/parsers/listing.ts
555
+ import * as cheerio3 from "cheerio/slim";
556
+
557
+ // src/parsers/sorting.ts
558
+ function parseExposedSorting(html, baseURL) {
559
+ const vfIdx = html.search(/<div[^>]+class=["'][^"']*view-filters[^"']*["'][^>]*>/i);
560
+ if (vfIdx < 0) return void 0;
561
+ const formStart = html.indexOf("<form", vfIdx);
562
+ if (formStart < 0) return void 0;
563
+ const formEnd = html.indexOf("</form>", formStart);
564
+ if (formEnd < 0) return void 0;
565
+ const formHtml = html.slice(formStart, formEnd + 7);
566
+ const actionMatch = /<form[^>]*\baction=["']([^"']+)["'][^>]*>/i.exec(formHtml);
567
+ if (!actionMatch) return void 0;
568
+ const abs = toAbsolute(baseURL, actionMatch[1] || "");
569
+ if (!abs) return void 0;
570
+ let actionPath = "/";
571
+ try {
572
+ actionPath = new URL(abs).pathname || "/";
573
+ } catch {
574
+ actionPath = "/";
575
+ }
576
+ const labels = /* @__PURE__ */ new Map();
577
+ const reLabel = /<label[^>]*\bfor=["']([^"']+)["'][^>]*>([\s\S]*?)<\/label>/gi;
578
+ let lm;
579
+ while (lm = reLabel.exec(formHtml)) {
580
+ const id = lm[1];
581
+ const raw = (lm[2] || "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
582
+ if (id && raw) labels.set(id, raw);
583
+ }
584
+ const selects = [];
585
+ const reSelect = /<select\b([^>]*)>([\s\S]*?)<\/select>/gi;
586
+ let sm;
587
+ while (sm = reSelect.exec(formHtml)) {
588
+ const attrs = sm[1] || "";
589
+ const inner = sm[2] || "";
590
+ const name = /(?:^|\s)name=["']([^"']+)["']/i.exec(attrs)?.[1];
591
+ if (!name) continue;
592
+ const idAttr = /(?:^|\s)id=["']([^"']+)["']/i.exec(attrs)?.[1];
593
+ const label = idAttr ? labels.get(idAttr) : void 0;
594
+ const options = [];
595
+ const reOpt = /<option\b([^>]*)>([\s\S]*?)<\/option>/gi;
596
+ let om;
597
+ while (om = reOpt.exec(inner)) {
598
+ const oattrs = om[1] || "";
599
+ const text = (om[2] || "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
600
+ const val = /(?:^|\s)value=["']([^"']*)["']/i.exec(oattrs)?.[1] ?? text;
601
+ const selected = /\bselected\b/i.test(oattrs) || /\bselected=["']selected["']/i.test(oattrs);
602
+ options.push({ value: val, label: text || val, selected });
603
+ }
604
+ selects.push({ name, label, options });
605
+ }
606
+ if (!selects.length) return void 0;
607
+ const appliedParams = {};
608
+ for (const s of selects) {
609
+ const selected = s.options.find((o) => o.selected);
610
+ if (selected && selected.value !== void 0) {
611
+ appliedParams[s.name] = String(selected.value);
612
+ }
613
+ }
614
+ return { actionPath, selects, appliedParams };
615
+ }
616
+
617
+ // src/parsers/listing.ts
618
+ function pickFromSrcset2(srcset) {
619
+ if (!srcset) return;
620
+ const first = srcset.split(",")[0]?.trim();
621
+ if (!first) return;
622
+ const url = first.split(/\s+/)[0];
623
+ return url || void 0;
624
+ }
625
+ function pickFromStyle2(style) {
626
+ if (!style) return;
627
+ const m = style.match(/url\((['"]?)(.*?)\1\)/i);
628
+ return m?.[2] || void 0;
629
+ }
630
+ function pickThumb($scope, baseURL) {
631
+ const cands = [
632
+ ".views-field-field-preview img",
633
+ ".views-field-field-image img",
634
+ ".views-field-field-avatar img",
635
+ ".views-field-field-cat-preview img",
636
+ ".views-field-field-category-preview img",
637
+ ".views-field-field-comg-preview img",
638
+ ".views-field-field-gif-preview img",
639
+ ".views-field-field-gif-pre img",
640
+ ".views-field-field-gif img",
641
+ ".views-field-field-files img",
642
+ "img"
643
+ ];
644
+ for (const sel of cands) {
645
+ const img = $scope.find(sel).first();
646
+ if (img.length) {
647
+ const ds = img.attr("data-src") || img.attr("data-original");
648
+ const ss = pickFromSrcset2(img.attr("srcset") || "");
649
+ const src = ds || ss || img.attr("src");
650
+ const abs = toAbsolute(baseURL, src || "");
651
+ if (abs) return abs;
652
+ }
653
+ }
654
+ const srcset = pickFromSrcset2($scope.find("picture source").first().attr("srcset") || "");
655
+ if (srcset) return toAbsolute(baseURL, srcset);
656
+ const bg = pickFromStyle2(
657
+ $scope.attr("style") || $scope.find('[style*="background-image"]').first().attr("style")
658
+ );
659
+ if (bg) return toAbsolute(baseURL, bg);
660
+ return void 0;
661
+ }
662
+ function findTitleLink($scope) {
663
+ const sel = $scope.find(".views-field-title a[href]").first().length ? ".views-field-title a[href]" : $scope.find(".views-field-name a[href]").first().length ? ".views-field-name a[href]" : $scope.find(".views-field-nothing-1 h3 a[href]").first().length ? ".views-field-nothing-1 h3 a[href]" : $scope.find("strong a[href]").first().length ? "strong a[href]" : $scope.find("h5 a[href]").first().length ? "h5 a[href]" : "a[href]";
664
+ return $scope.find(sel).first();
665
+ }
666
+ function textFrom($el) {
667
+ return ($el.text() || "").replace(/\s+/g, " ").trim();
668
+ }
669
+ function isPager($a) {
670
+ return !!$a.closest("ul.pager, .pager, nav.pagination").length;
671
+ }
672
+ function cardRoot($a) {
673
+ const r = $a.closest("li, .views-row, td, .node, .views-col, .view-content > div, tr").first();
674
+ return r.length ? r : $a.parent();
675
+ }
676
+ function parseHubListing(html, baseURL, page) {
677
+ const $ = cheerio3.load(html);
678
+ const items = [];
679
+ const seen = /* @__PURE__ */ new Set();
680
+ const views = $(".view");
681
+ const scopes = views.length ? views.toArray() : [$("body").get(0)];
682
+ for (const v of scopes) {
683
+ const $view = $(v);
684
+ const $root = $view.find(".view-content").length ? $view.find(".view-content") : $view;
685
+ $root.find("table.views-table tbody tr").each((_, tr) => {
686
+ const $tr = $(tr);
687
+ let a = $tr.find(".views-field-nothing-1 h3 a[href]").first();
688
+ if (!a.length) {
689
+ const cand = $tr.find("a[href]").first();
690
+ if (cand.length && !isPager(cand)) a = cand;
691
+ }
692
+ const href = a.attr("href") || "";
693
+ const url = toAbsolute(baseURL, href);
694
+ if (!url || seen.has(url)) return;
695
+ const title = textFrom($tr.find(".views-field-nothing-1 h3").first()) || textFrom(a) || a.attr("title") || "";
696
+ if (!title.trim()) return;
697
+ const thumbCell = $tr.find(".views-field-field-files").first();
698
+ const thumb = pickThumb(thumbCell, baseURL) || pickThumb($tr, baseURL);
699
+ items.push({ title: title.trim(), url, thumb });
700
+ seen.add(url);
701
+ });
702
+ $root.find("table.views-view-grid td").each((_, td) => {
703
+ const $td = $(td);
704
+ const a = findTitleLink($td);
705
+ const href = a.attr("href") || "";
706
+ const url = toAbsolute(baseURL, href);
707
+ if (!url || seen.has(url)) return;
708
+ const title = textFrom(a) || textFrom($td.find(".views-field-title .field-content")) || textFrom($td.find(".views-field-name .field-content")) || a.attr("title") || "";
709
+ const thumb = pickThumb($td, baseURL);
710
+ if (title) {
711
+ items.push({ title, url, thumb });
712
+ seen.add(url);
713
+ }
714
+ });
715
+ $root.find(".views-row, .node, li").each((_, row) => {
716
+ const $row = $(row);
717
+ const a = findTitleLink($row);
718
+ const href = a.attr("href") || "";
719
+ const url = toAbsolute(baseURL, href);
720
+ if (!url || seen.has(url)) return;
721
+ const title = textFrom(a) || textFrom($row.find(".views-field-title .field-content")) || textFrom($row.find(".views-field-name .field-content")) || a.attr("title") || "";
722
+ const thumb = pickThumb($row, baseURL);
723
+ if (title) {
724
+ items.push({ title, url, thumb });
725
+ seen.add(url);
726
+ }
727
+ });
728
+ $root.find("a[href] img").each((_, imgEl) => {
729
+ const $a = $(imgEl).closest("a[href]");
730
+ if (isPager($a)) return;
731
+ const url = toAbsolute(baseURL, $a.attr("href") || "");
732
+ if (!url || seen.has(url)) return;
733
+ const $card = cardRoot($a);
734
+ const title = textFrom($card.find(".views-field-title .field-content").first()) || textFrom($card.find(".views-field-name .field-content").first()) || textFrom($card.find(".views-field-nothing-1 h3").first()) || $a.attr("title") || $(imgEl).attr("alt") || "";
735
+ if (!title.trim()) return;
736
+ const thumb = pickThumb($card, baseURL) || pickThumb($a, baseURL) || toAbsolute(baseURL, $(imgEl).attr("src") || "");
737
+ items.push({ title: title.trim(), url, thumb });
278
738
  seen.add(url);
739
+ });
740
+ }
741
+ const totalPages = extractTotalPages(html);
742
+ const hasNext = page + 1 < totalPages;
743
+ const alphabet = parseAlphabetInline(html, baseURL) || void 0;
744
+ const sorting = parseExposedSorting(html, baseURL);
745
+ return {
746
+ items,
747
+ page,
748
+ hasNext,
749
+ totalPages,
750
+ pageSize: void 0,
751
+ alphabet,
752
+ sorting
753
+ };
754
+ }
755
+
756
+ // src/api/listings.ts
757
+ function buildUrl(baseURL, path, params) {
758
+ const url = new URL(path.startsWith("/") ? path : `/${path}`, baseURL);
759
+ if (params) {
760
+ for (const [k, v] of Object.entries(params)) {
761
+ if (v === void 0) continue;
762
+ if (typeof v === "boolean") url.searchParams.set(k, v ? "1" : "0");
763
+ else url.searchParams.set(k, String(v));
279
764
  }
280
- return out;
281
- }
282
- parseHasNext(html) {
283
- const doc = this.dom.parse(html);
284
- const root = doc.documentElement ?? doc;
285
- if (this.dom.qs(root, 'a[rel="next"]')) return true;
286
- const pager = this.dom.qs(root, ".pager, .pagination, nav[role='navigation']");
287
- if (pager) {
288
- const next = this.dom.qs(
289
- pager,
290
- 'a[rel="next"], a.next, li.next a, a[title*="\u0421\u043B\u0435\u0434"], a[aria-label*="Next"]'
291
- );
292
- if (next) return true;
765
+ }
766
+ return url.pathname + (url.search ? url.search : "");
767
+ }
768
+ function normalizeCharactersPath(path) {
769
+ const clean = path.startsWith("/") ? path : `/${path}`;
770
+ if (/^\/alphabetical_order_characters\/?$/i.test(clean)) return "/characters";
771
+ return clean;
772
+ }
773
+ function sniffPagePrefixFromHtml(html) {
774
+ const m = html.match(
775
+ /<ul[^>]*class=["'][^"']*pager[^"']*["'][\s\S]*?\bhref=["'][^"']*?\bpage=([^"&]+)["'][\s\S]*?<\/ul>/i
776
+ ) || html.match(/\bpage=([^"&]+)/i);
777
+ if (!m) return null;
778
+ try {
779
+ const decoded = decodeURIComponent(m[1]);
780
+ if (decoded.includes(",")) {
781
+ const parts = decoded.split(",").map((s) => s.trim());
782
+ if (parts.length > 1) return parts.slice(0, -1).join(",") + ",";
293
783
  }
294
- return /\bpage=\d+\b/i.test(html);
784
+ } catch {
295
785
  }
296
- buildListURL(path, page = 0, letter) {
297
- if (!path) {
298
- const u2 = new URL(this.baseURL);
299
- if (page > 0) u2.searchParams.set("page", String(page));
300
- return u2.href;
786
+ return null;
787
+ }
788
+ function buildPageParam(htmlWithPager, page) {
789
+ const prefix = sniffPagePrefixFromHtml(htmlWithPager);
790
+ return prefix ? `${prefix}${page}` : String(page);
791
+ }
792
+ function getAppliedFromHtml(html, baseURL) {
793
+ const sorting = parseExposedSorting(html, baseURL);
794
+ return sorting?.appliedParams ?? {};
795
+ }
796
+ async function latest(http, baseURL, page = 0, params) {
797
+ const url0 = buildUrl(baseURL, "/new", { ...params ?? {}, page: 0 });
798
+ const html0 = await http.getHtml(url0);
799
+ if (page === 0) {
800
+ return parseHubListing(html0, baseURL, 0);
801
+ }
802
+ const applied = params ? {} : getAppliedFromHtml(html0, baseURL);
803
+ const pageParam = buildPageParam(html0, page);
804
+ const html = await http.getHtml(
805
+ buildUrl(baseURL, "/new", { ...applied, ...params ?? {}, page: pageParam })
806
+ );
807
+ return parseHubListing(html, baseURL, page);
808
+ }
809
+ async function listByPath(http, baseURL, path, page = 0, opts) {
810
+ const clean = path.startsWith("/") ? path : `/${path}`;
811
+ const commonParams = { ...opts ?? {} };
812
+ delete commonParams.letter;
813
+ if (opts?.letter) {
814
+ const entryHtml = await http.getHtml(buildUrl(baseURL, clean, commonParams));
815
+ const alphabet = parseAlphabetInline(entryHtml, baseURL);
816
+ const wanted = String(opts.letter).toUpperCase();
817
+ let letterUrl;
818
+ if (alphabet) {
819
+ const match = alphabet.letters.find((l) => (l.value || "").toUpperCase() === wanted) || alphabet.letters.find((l) => (l.label || "").toUpperCase() === wanted);
820
+ letterUrl = match?.href || `/${alphabet.section}/${encodeURIComponent(wanted)}`;
821
+ } else {
822
+ const section = guessAlphabetSectionFromPath(clean);
823
+ letterUrl = `/${section}/${encodeURIComponent(wanted)}`;
301
824
  }
302
- const u = new URL(path.startsWith("/") ? path : "/" + path, this.baseURL);
303
- if (page > 0) u.searchParams.set("page", String(page));
304
- if (letter) u.searchParams.set("letter", letter);
305
- return u.href;
825
+ const url0 = buildUrl(baseURL, letterUrl, { ...commonParams, page: 0 });
826
+ const html02 = await http.getHtml(url0);
827
+ const res0 = parseAlphabetListing(html02, baseURL, 0);
828
+ if (alphabet) res0.alphabet = alphabet;
829
+ if (page === 0) {
830
+ return res0;
831
+ }
832
+ const applied2 = Object.keys(commonParams).length ? {} : getAppliedFromHtml(html02, baseURL);
833
+ const pageParam2 = buildPageParam(html02, page);
834
+ const html2 = await http.getHtml(
835
+ buildUrl(baseURL, letterUrl, { ...applied2, ...commonParams, page: pageParam2 })
836
+ );
837
+ const res = parseAlphabetListing(html2, baseURL, page);
838
+ if (alphabet) res.alphabet = alphabet;
839
+ return res;
306
840
  }
307
- // -------- Listing
308
- async latest(page = 0, params) {
309
- return this.listByPath(void 0, page, params);
841
+ const effective = normalizeCharactersPath(clean);
842
+ const html0 = await http.getHtml(buildUrl(baseURL, effective, { ...commonParams, page: 0 }));
843
+ const parsed0 = parseHubListing(html0, baseURL, 0);
844
+ if (effective !== clean && !parsed0.alphabet) {
845
+ try {
846
+ const entryHtml = await http.getHtml(buildUrl(baseURL, clean, commonParams));
847
+ const alpha = parseAlphabetInline(entryHtml, baseURL);
848
+ if (alpha) parsed0.alphabet = alpha;
849
+ } catch {
850
+ }
310
851
  }
311
- async listByPath(path, page = 0, params) {
312
- const url = this.buildListURL(path, page, params?.letter);
313
- const html = await this.http.getHtml(url);
314
- const items = this.parseListing(html);
315
- const hasNext = this.parseHasNext(html);
316
- return { items, page, hasNext, totalPages: hasNext ? page + 2 : page + 1 };
852
+ if (page === 0) {
853
+ return parsed0;
317
854
  }
318
- // -------- Search
319
- async search(q, page = 0) {
320
- const u = new URL("/search", this.baseURL);
321
- u.searchParams.set("search", q);
322
- if (page > 0) u.searchParams.set("page", String(page));
323
- const html = await this.http.getHtml(u.href);
324
- const items = this.parseListing(html);
325
- const hasNext = this.parseHasNext(html);
326
- return { items, page, hasNext, totalPages: hasNext ? page + 2 : page + 1 };
855
+ const applied = Object.keys(commonParams).length ? {} : parsed0.sorting?.appliedParams ?? getAppliedFromHtml(html0, baseURL);
856
+ const pageParam = buildPageParam(html0, page);
857
+ const html = await http.getHtml(
858
+ buildUrl(baseURL, effective, { ...applied, ...commonParams, page: pageParam })
859
+ );
860
+ const parsed = parseHubListing(html, baseURL, page);
861
+ if (effective !== clean && !parsed.alphabet) {
862
+ try {
863
+ const entryHtml = await http.getHtml(buildUrl(baseURL, clean, commonParams));
864
+ const alpha = parseAlphabetInline(entryHtml, baseURL);
865
+ if (alpha) parsed.alphabet = alpha;
866
+ } catch {
867
+ }
327
868
  }
328
- // -------- Post
329
- parsePost(html, url) {
330
- const doc = this.dom.parse(html);
331
- const root = doc.documentElement ?? doc;
332
- const title = this.text(this.dom.qs(root, "h1")) || this.attr(this.dom.qs(root, 'meta[property="og:title"]'), "content") || "\u0411\u0435\u0437 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u044F";
333
- const imgEls = this.dom.qsa(root, "img");
334
- const imgSet = /* @__PURE__ */ new Set();
335
- for (const el of imgEls) {
336
- const src = absolutize(
337
- this.baseURL,
338
- this.attr(el, "data-src") || this.attr(el, "data-original") || this.attr(el, "src")
339
- );
340
- if (!src || /\b(logo|sprite|icon|favicon)\b/i.test(src)) continue;
341
- imgSet.add(src);
869
+ return parsed;
870
+ }
871
+
872
+ // src/api/posts.ts
873
+ var posts_exports = {};
874
+ __export(posts_exports, {
875
+ getPost: () => getPost
876
+ });
877
+
878
+ // src/parsers/post.ts
879
+ import * as cheerio4 from "cheerio/slim";
880
+ function parsePost(html, baseURL, url) {
881
+ const $ = cheerio4.load(html);
882
+ const title = $("h1").first().text().trim() || $(".page-title, .node-title, .title").first().text().trim() || url;
883
+ const container = $("#content, .content, article, .node, .field-items").first();
884
+ const imgs = [];
885
+ container.find("img").each((_, img) => {
886
+ const el = $(img);
887
+ const src = el.attr("data-src") || el.attr("src");
888
+ const abs = toAbsolute(baseURL, src || "");
889
+ if (abs) imgs.push(abs);
890
+ });
891
+ const images = uniq(imgs);
892
+ const tags = [];
893
+ $('.tags a, a[rel="tag"], .field-name-field-tags a').each((_, a) => {
894
+ const t = $(a).text().trim();
895
+ if (t) tags.push(t);
896
+ });
897
+ const author = $(".author a").first().text().trim() || $(".submitted .username").first().text().trim() || null;
898
+ return { title, url, images, tags: uniq(tags), author };
899
+ }
900
+
901
+ // src/api/posts.ts
902
+ async function getPost(http, baseURL, urlOrSlug) {
903
+ const html = await http.getHtml(urlOrSlug);
904
+ const absolute = (() => {
905
+ try {
906
+ return new URL(urlOrSlug).toString();
907
+ } catch {
908
+ return new URL(urlOrSlug.replace(/^\//, ""), baseURL + "/").toString();
342
909
  }
343
- const images = Array.from(imgSet);
344
- const tags = [];
345
- const tagEls = this.dom.qsa(root, 'a[href*="/tags/"], .tags a, .field-name-field-tags a');
346
- for (const t of tagEls) {
347
- const txt = this.text(t);
348
- if (txt) tags.push(txt);
910
+ })();
911
+ return parsePost(html, baseURL, absolute);
912
+ }
913
+
914
+ // src/api/search.ts
915
+ var search_exports = {};
916
+ __export(search_exports, {
917
+ search: () => search
918
+ });
919
+
920
+ // src/parsers/search.ts
921
+ import * as cheerio5 from "cheerio/slim";
922
+ function parseSearch(html, baseURL, page) {
923
+ const $ = cheerio5.load(html);
924
+ const items = [];
925
+ const view = $(".view").filter((_, el) => {
926
+ const cls = $(el).attr("class") || "";
927
+ return /view-id-search/.test(cls) && /view-display-id-page/.test(cls) && $(el).find(".view-content").length > 0;
928
+ }).first();
929
+ const rows = view.find(".view-content .views-row");
930
+ rows.each((_, el) => {
931
+ const row = $(el);
932
+ const a = row.find(".views-field-title a[href]").first().length ? row.find(".views-field-title a[href]").first() : row.find("a[href]").first();
933
+ const href = a.attr("href") || "";
934
+ const url = toAbsolute(baseURL, href);
935
+ const title = (a.text() || row.find(".views-field-title .field-content").text() || "").trim();
936
+ const pickImg = row.find(".views-field-field-preview img").first().length ? row.find(".views-field-field-preview img").first() : row.find(".views-field-field-image img").first().length ? row.find(".views-field-field-image img").first() : row.find(".views-field-field-fl-prev img").first().length ? row.find(".views-field-field-fl-prev img").first() : row.find(".views-field-field-album-preview img").first().length ? row.find(".views-field-field-album-preview img").first() : row.find(".views-field-field-vd-preciew img").first().length ? row.find(".views-field-field-vd-preciew img").first() : row.find(".views-field-field-gif-pre img").first().length ? row.find(".views-field-field-gif-pre img").first() : row.find(".views-field-field-avatar img").first().length ? row.find(".views-field-field-avatar img").first() : row.find("img").first();
937
+ let thumb = pickImg.attr("data-src") || pickImg.attr("src") || void 0;
938
+ thumb = toAbsolute(baseURL, thumb);
939
+ if (url && title) items.push({ title, url, thumb });
940
+ });
941
+ const totalPages = extractTotalPages(html);
942
+ const hasNext = page + 1 < totalPages;
943
+ if (items.length === 0) {
944
+ return { items: [], page, hasNext: false, totalPages: 1 };
945
+ }
946
+ return { items, page, hasNext, totalPages };
947
+ }
948
+
949
+ // src/parsers/ajax.ts
950
+ import * as cheerio6 from "cheerio/slim";
951
+ function extractViewsContextForSearch(html) {
952
+ const $ = cheerio6.load(html);
953
+ const view = $(".view").filter((_, el) => {
954
+ const cls2 = $(el).attr("class") || "";
955
+ return /view-id-search/.test(cls2) && /view-display-id-page/.test(cls2);
956
+ }).first();
957
+ const cls = view.attr("class") || "";
958
+ const view_name = cls.match(/view-id-([^\s]+)/)?.[1] || "search";
959
+ const view_display_id = cls.match(/view-display-id-([^\s]+)/)?.[1] || "page";
960
+ const domFromClass = cls.match(/view-dom-id-([^\s]+)/)?.[1] || "";
961
+ const domFromId = (view.attr("id") || "").replace(/^view-dom-id-/, "");
962
+ const view_dom_id = domFromClass || domFromId || "view-dom-id-1";
963
+ const ajax_html_id = $('[id^="views-exposed-form"]').attr("id") || view.attr("id") || void 0;
964
+ return { view_name, view_display_id, view_dom_id, ajax_html_id };
965
+ }
966
+ function extractHtmlFromDrupalAjax(payload, wantDomId) {
967
+ if (Array.isArray(payload)) {
968
+ for (const cmd of payload) {
969
+ const c = cmd;
970
+ const sel = String(c?.selector || "");
971
+ const data = c?.data;
972
+ if ((c?.command === "insert" || c?.command === "replaceWith") && typeof data === "string" && data.trim() && (!wantDomId || sel.includes(wantDomId) || sel.includes("view-content")))
973
+ return data;
974
+ }
975
+ const concat = payload.map((x) => typeof x?.data === "string" ? x.data : "").join("");
976
+ return concat.trim() ? concat : null;
977
+ }
978
+ const disp = payload?.display;
979
+ return typeof disp === "string" ? disp : null;
980
+ }
981
+
982
+ // src/api/search.ts
983
+ async function search(http, baseURL, query, page = 0) {
984
+ const q = encodeURIComponent(query);
985
+ const html1 = await http.getHtml(`/search?search_api_views_fulltext=${q}&page=${page}`);
986
+ const parsed1 = parseSearch(html1, baseURL, page);
987
+ if (parsed1.items.length > 0) return parsed1;
988
+ const firstHtml = await http.getHtml(`/search?search_api_views_fulltext=${q}`);
989
+ const ctx = extractViewsContextForSearch(firstHtml);
990
+ const ajaxUrl = `/views/ajax?search_api_views_fulltext=${q}&undefined=Search&_wrapper_format=drupal_ajax`;
991
+ const payload = {
992
+ view_name: ctx.view_name || "search",
993
+ view_display_id: ctx.view_display_id || "page",
994
+ view_args: "",
995
+ view_path: "search",
996
+ view_base_path: "search",
997
+ view_dom_id: ctx.view_dom_id,
998
+ pager_element: "0",
999
+ page: String(page)
1000
+ };
1001
+ if (ctx.ajax_html_id) payload["ajax_html_ids[]"] = [ctx.ajax_html_id];
1002
+ const json = await http.postForm(ajaxUrl, payload);
1003
+ const html2 = extractHtmlFromDrupalAjax(json, ctx.view_dom_id) || "";
1004
+ return parseSearch(html2, baseURL, page);
1005
+ }
1006
+
1007
+ // src/api/updates.ts
1008
+ var updates_exports = {};
1009
+ __export(updates_exports, {
1010
+ updates: () => updates,
1011
+ updatesShortcuts: () => updatesShortcuts
1012
+ });
1013
+
1014
+ // src/parsers/viewDisplay.ts
1015
+ import * as cheerio7 from "cheerio/slim";
1016
+ function parseViewDisplay(viewName, html, baseURL) {
1017
+ const $ = cheerio7.load(html);
1018
+ const items = [];
1019
+ const pickThumb2 = (scope) => {
1020
+ const img = scope.find(".views-field-field-preview img").first().length ? scope.find(".views-field-field-preview img").first() : scope.find(".views-field-field-image img").first().length ? scope.find(".views-field-field-image img").first() : scope.find(".views-field-field-avatar img").first().length ? scope.find(".views-field-field-avatar img").first() : scope.find("img").first();
1021
+ let thumb = img.attr("data-src") || img.attr("src") || void 0;
1022
+ return toAbsolute(baseURL, thumb);
1023
+ };
1024
+ const liList = $("ul.jcarousel li");
1025
+ liList.each((_, li) => {
1026
+ const scope = $(li);
1027
+ const a = scope.find(".views-field-title a[href]").first().length ? scope.find(".views-field-title a[href]").first() : scope.find(".views-field-name a[href]").first();
1028
+ const href = a.attr("href") || "";
1029
+ const url = toAbsolute(baseURL, href);
1030
+ const title = (a.text() || scope.find(".views-field-title .field-content").text() || scope.find(".views-field-name .field-content").text() || "").trim();
1031
+ const thumb = pickThumb2(scope);
1032
+ if (url && title) items.push({ title, url, thumb });
1033
+ });
1034
+ return items;
1035
+ }
1036
+
1037
+ // src/api/updates.ts
1038
+ var VIEW_PRESETS = {
1039
+ random_top_comics: { view_display_id: "block", jcarousel_dom_id: 7 },
1040
+ top_random_characters: { view_display_id: "block", jcarousel_dom_id: 8 }
1041
+ };
1042
+ function uniq2(arr) {
1043
+ return Array.from(new Set(arr));
1044
+ }
1045
+ async function updates(http, baseURL, params = {}) {
1046
+ const viewName = params.view_name ?? "new_mini";
1047
+ const preset = VIEW_PRESETS[viewName] || {};
1048
+ const first = Number(params.first ?? 0);
1049
+ const last = Number(params.last ?? 8);
1050
+ const basePayload = {
1051
+ js: "1",
1052
+ first: String(first),
1053
+ last: String(last),
1054
+ view_args: params.view_args ?? "",
1055
+ view_path: params.view_path ?? "node",
1056
+ view_base_path: params.view_base_path ?? "",
1057
+ view_name: viewName
1058
+ };
1059
+ const displayCandidates = uniq2([
1060
+ params.view_display_id ?? preset.view_display_id ?? "block_1",
1061
+ "block",
1062
+ "block_2",
1063
+ "block_3",
1064
+ "page",
1065
+ "default"
1066
+ ]).filter(Boolean);
1067
+ const origDom = Number(params.jcarousel_dom_id ?? preset.jcarousel_dom_id ?? 1);
1068
+ const domCandidates = uniq2([
1069
+ origDom,
1070
+ origDom - 1,
1071
+ origDom + 1,
1072
+ ...Array.from({ length: 10 }, (_, i) => i + 1)
1073
+ ]).filter((n) => Number.isFinite(n) && n > 0);
1074
+ let displayHtml = "";
1075
+ for (const view_display_id of displayCandidates) {
1076
+ for (const jcarousel_dom_id of domCandidates) {
1077
+ try {
1078
+ const qs = new URLSearchParams({
1079
+ ...basePayload,
1080
+ view_display_id: String(view_display_id),
1081
+ jcarousel_dom_id: String(jcarousel_dom_id)
1082
+ }).toString();
1083
+ const data = await http.getJson(`/jcarousel/ajax/views?${qs}`);
1084
+ const html = data?.display?.trim() ?? "";
1085
+ if (html) {
1086
+ displayHtml = html;
1087
+ displayCandidates.length = 0;
1088
+ break;
1089
+ }
1090
+ } catch {
1091
+ }
349
1092
  }
1093
+ }
1094
+ if (!displayHtml) {
1095
+ return { items: [], first, last, html: "", viewName };
1096
+ }
1097
+ const items = parseViewDisplay(viewName, displayHtml, baseURL);
1098
+ return { items, first, last, html: displayHtml, viewName };
1099
+ }
1100
+ var updatesShortcuts = {
1101
+ newMini: (http, baseURL, p) => updates(http, baseURL, { ...p ?? {}, view_name: "new_mini" }),
1102
+ userUploadFront: (http, baseURL, p) => updates(http, baseURL, { ...p ?? {}, view_name: "user_upload_front" }),
1103
+ updatedManga: (http, baseURL, p) => updates(http, baseURL, { ...p ?? {}, view_name: "updated_manga" }),
1104
+ updatedMangaPromoted: (http, baseURL, p) => updates(http, baseURL, { ...p ?? {}, view_name: "updated_manga_promoted" }),
1105
+ updatedGames: (http, baseURL, p) => updates(http, baseURL, { ...p ?? {}, view_name: "updated_games" }),
1106
+ randomTopComics: (http, baseURL, p) => updates(http, baseURL, { ...p ?? {}, view_name: "random_top_comics" }),
1107
+ topRandomCharacters: (http, baseURL, p) => updates(http, baseURL, { ...p ?? {}, view_name: "top_random_characters" })
1108
+ };
1109
+
1110
+ // src/parsers/viewer.ts
1111
+ var viewer_exports = {};
1112
+ __export(viewer_exports, {
1113
+ buildJuiceboxXmlUrl: () => buildJuiceboxXmlUrl,
1114
+ default: () => viewer_default,
1115
+ parseInlineJuiceboxFromHtml: () => parseInlineJuiceboxFromHtml,
1116
+ parseJuiceboxXml: () => parseJuiceboxXml,
1117
+ parseViewer: () => parseViewer,
1118
+ parseViewerMeta: () => parseViewerMeta
1119
+ });
1120
+ function decodeHtml(s) {
1121
+ return s.replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#039;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
1122
+ }
1123
+ function textBetween(html, openRe, close) {
1124
+ const m = openRe.exec(html);
1125
+ if (!m) return null;
1126
+ const i = m.index + m[0].length;
1127
+ const j = html.indexOf(close, i);
1128
+ if (j < 0) return null;
1129
+ return html.slice(i, j);
1130
+ }
1131
+ function stripTags(s) {
1132
+ return s.replace(/<[^>]*>/g, "");
1133
+ }
1134
+ function collectLinks(blockHtml, baseURL) {
1135
+ const out = [];
1136
+ const re = /<a\s+[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi;
1137
+ let m;
1138
+ while (m = re.exec(blockHtml)) {
1139
+ const url = absUrl(baseURL, m[1]) ?? "";
1140
+ const title = normSpace(decodeHtml(stripTags(m[2])));
1141
+ if (url && title) out.push({ url, title });
1142
+ }
1143
+ return out;
1144
+ }
1145
+ function findFieldNodeAndSys(html) {
1146
+ const re = /id="field--node--(\d+)--([a-z0-9_-]+)--full"/i;
1147
+ const m = re.exec(html);
1148
+ if (m) {
1149
+ const nodeId = parseInt(m[1], 10);
1150
+ const fieldSys = m[2].replace(/-/g, "_");
1151
+ if (Number.isFinite(nodeId)) return { nodeId, fieldSys };
1152
+ }
1153
+ const re2 = /\/juicebox\/xml\/field\/node\/(\d+)\/([a-z0-9_]+)\/full/gi;
1154
+ const m2 = re2.exec(html);
1155
+ if (m2) {
1156
+ const nodeId = parseInt(m2[1], 10);
1157
+ const fieldSys = m2[2];
1158
+ if (Number.isFinite(nodeId)) return { nodeId, fieldSys };
1159
+ }
1160
+ return null;
1161
+ }
1162
+ function buildJuiceboxXmlUrl(baseURL, nodeId, fieldSys) {
1163
+ const root = baseURL.replace(/\/+$/, "");
1164
+ return `${root}/juicebox/xml/field/node/${nodeId}/${fieldSys}/full`;
1165
+ }
1166
+ function parseJuiceboxXml(xml) {
1167
+ const images = [];
1168
+ const reImg = /<image\b([^>]+)>/gi;
1169
+ let m;
1170
+ while (m = reImg.exec(xml)) {
1171
+ const attrs = m[1];
1172
+ const map = {};
1173
+ let am;
1174
+ const reAttr = /([a-zA-Z0-9_-]+)\s*=\s*"([^"]*)"/g;
1175
+ while (am = reAttr.exec(attrs)) map[am[1]] = am[2];
1176
+ const original = map["linkURL"] || map["imageURL"] || map["largeImageURL"] || map["smallImageURL"] || "";
1177
+ if (!original) continue;
1178
+ images.push({
1179
+ original,
1180
+ large: map["largeImageURL"],
1181
+ medium: map["imageURL"] || map["smallImageURL"],
1182
+ small: map["smallImageURL"],
1183
+ thumb: map["thumbURL"]
1184
+ });
1185
+ }
1186
+ return images;
1187
+ }
1188
+ function parseInlineJuiceboxFromHtml(html) {
1189
+ const out = [];
1190
+ const reMed = /<img[^>]+src="([^"]+\/styles\/juicebox_(?:medium|small|large)\/[^"]+)"[^>]*>/gi;
1191
+ const seen = /* @__PURE__ */ new Set();
1192
+ let m;
1193
+ while (m = reMed.exec(html)) {
1194
+ const url = m[1];
1195
+ if (seen.has(url)) continue;
1196
+ seen.add(url);
1197
+ out.push({ original: url, medium: url });
1198
+ }
1199
+ return out;
1200
+ }
1201
+ function parseBreadcrumbs(html, baseURL) {
1202
+ const block = textBetween(html, /<div[^>]+class="breadcrumb"[^>]*>/i, "</div>");
1203
+ return block ? collectLinks(block, baseURL) : [];
1204
+ }
1205
+ function findLabeledFieldBlock(html, labelStartsWith) {
1206
+ const esc = labelStartsWith.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1207
+ const re = new RegExp(
1208
+ `<(?:h3|div)[^>]*class="[^"]*field-label[^"]*"[^>]*>\\s*${esc}\\s*:?\\s*<\\/[^>]+>`,
1209
+ "i"
1210
+ );
1211
+ const idx = html.search(re);
1212
+ if (idx < 0) return null;
1213
+ const open = html.lastIndexOf("<div", idx);
1214
+ let depth = 0;
1215
+ for (let i = open; i < html.length; i++) {
1216
+ if (html.startsWith("<div", i)) depth++;
1217
+ if (html.startsWith("</div>", i)) {
1218
+ depth--;
1219
+ if (depth === 0) {
1220
+ return html.slice(open, i + 6);
1221
+ }
1222
+ }
1223
+ }
1224
+ return null;
1225
+ }
1226
+ function parseLabeledField(html, labelStartsWith) {
1227
+ return findLabeledFieldBlock(html, labelStartsWith);
1228
+ }
1229
+ function parsePlainValuesFromLabeledField(html, label) {
1230
+ const block = findLabeledFieldBlock(html, label);
1231
+ if (!block) return [];
1232
+ const text = normSpace(decodeHtml(stripTags(block))).replace(new RegExp(`^${label}\\s*:?\\s*`, "i"), "").trim();
1233
+ if (!text) return [];
1234
+ return text.split(/\s*[,;]\s*/).filter(Boolean);
1235
+ }
1236
+ function parseTitle(html) {
1237
+ const h1 = textBetween(html, /<h1[^>]*id="page-title"[^>]*>/i, "</h1>");
1238
+ if (h1) return normSpace(decodeHtml(stripTags(h1)));
1239
+ const m = /<meta[^>]+property="og:title"[^>]+content="([^"]+)"/i.exec(html);
1240
+ if (m) return normSpace(decodeHtml(m[1]));
1241
+ return "";
1242
+ }
1243
+ function parseVotesAndRating(html) {
1244
+ const block = /<div[^>]*class="[^"]*\bfivestar-summary\b[^"]*"[^>]*>([\s\S]*?)<\/div>/i.exec(html)?.[1] || /<div[^>]*class="[^"]*\bfivestar-average[^"]*"[^>]*>([\s\S]*?)<\/div>/i.exec(html)?.[1] || "";
1245
+ if (block) {
1246
+ const mAvg = /class="average-rating"[^>]*>[\s\S]*?Average[^:]*:\s*(?:<span[^>]*>)?([\d.,]+)(?:<\/span>)?/i.exec(
1247
+ block
1248
+ );
1249
+ const mVotes = /class="total-votes"[^>]*>\s*\(\s*(?:<span[^>]*>)?(\d+)(?:<\/span>)?\s+votes?\s*\)/i.exec(
1250
+ block
1251
+ );
1252
+ const rating = mAvg ? parseNumberLike(mAvg[1]) : void 0;
1253
+ const votes = mVotes ? parseIntLike(mVotes[1]) : void 0;
1254
+ if (rating != null || votes != null) return { rating, votes };
1255
+ }
1256
+ const m1 = /Average\s*:\s*(?:<span[^>]*>)?([\d.,]+)(?:<\/span>)?[\s\S]*?\(\s*(?:<span[^>]*>)?(\d+)(?:<\/span>)?\s*votes?\s*\)/i.exec(
1257
+ html
1258
+ );
1259
+ if (m1) {
1260
+ return {
1261
+ rating: parseNumberLike(m1[1]),
1262
+ votes: parseIntLike(m1[2])
1263
+ };
1264
+ }
1265
+ const m2 = /Average[^<>\d]*([\d.,]+)/i.exec(html);
1266
+ const m3 = /\((\d+)\s+votes?\)/i.exec(html);
1267
+ if (m2 || m3) {
1268
+ const rating = m2 ? parseNumberLike(m2[1]) : void 0;
1269
+ const votes = m3 ? parseIntLike(m3[1]) : void 0;
1270
+ return { rating, votes };
1271
+ }
1272
+ return {};
1273
+ }
1274
+ function parseViews(html) {
1275
+ const patterns = [
1276
+ /<li[^>]*class="statistics_counter[^"]*"[^>]*>\s*<span>\s*([\d\s.,]+)\s+views\s*<\/span>/i,
1277
+ />\s*([\d\s.,]+)\s+views\s*<\/(?:span|div|li|h\d)>/i,
1278
+ />\s*Views\s*[:\-]?\s*<\/?(?:span|strong|b)?[^>]*>\s*([\d\s.,]+)\s*</i,
1279
+ /\bViews\s*[:\-]?\s*([\d\s.,]+)/i
1280
+ ];
1281
+ for (const rx of patterns) {
1282
+ const m = rx.exec(html);
1283
+ if (m && m[1]) return parseIntLike(m[1]);
1284
+ }
1285
+ return void 0;
1286
+ }
1287
+ function parseLinksFromLabeledField(html, baseURL, label) {
1288
+ const block = parseLabeledField(html, label);
1289
+ return block ? collectLinks(block, baseURL) : [];
1290
+ }
1291
+ function parseRelated(html, baseURL) {
1292
+ const pieces = [];
1293
+ const re = /<div[^>]+class="view[^"]*down[^"]*random[^"]*hentai[^"]*manga[^"]*"[^>]*>([\s\S]*?)<\/div>\s*<\/div>/gi;
1294
+ let m;
1295
+ while (m = re.exec(html)) pieces.push(m[1]);
1296
+ return uniq(pieces.flatMap((p) => collectLinks(p, baseURL)));
1297
+ }
1298
+ function parseUploader(html, baseURL) {
1299
+ const m = /<footer[^>]*class="[^"]*\bsubmitted\b[^"]*"[^>]*>([\s\S]*?)<\/footer>/i.exec(html);
1300
+ if (!m) return void 0;
1301
+ const block = m[1];
1302
+ const a = /Uploaded\s+by\s*<a[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>\s*on\s*([^<]+)/i.exec(
1303
+ block
1304
+ );
1305
+ const img = /<div[^>]*class="user-picture"[^>]*>[\s\S]*?<img[^>]*src="([^"]+)"/i.exec(block);
1306
+ const out = {};
1307
+ if (a) {
1308
+ out.url = absUrl(baseURL, a[1]) ?? "";
1309
+ out.name = normSpace(decodeHtml(stripTags(a[2])));
1310
+ out.dateText = normSpace(decodeHtml(a[3]));
1311
+ }
1312
+ if (img) out.avatar = absUrl(baseURL, img[1]) ?? "";
1313
+ return out;
1314
+ }
1315
+ function parseViewerMeta(html, baseURL, absoluteUrl) {
1316
+ const title = parseTitle(html);
1317
+ const breadcrumbs = parseBreadcrumbs(html, baseURL);
1318
+ let authors = parseLinksFromLabeledField(html, baseURL, "Author");
1319
+ if (authors.length === 0) {
1320
+ const altLinks = parseLinksFromLabeledField(html, baseURL, "Artist's name");
1321
+ if (altLinks.length) authors = altLinks;
1322
+ if (authors.length === 0) {
1323
+ const altPlain = parsePlainValuesFromLabeledField(html, "Artist's name");
1324
+ if (altPlain.length) {
1325
+ authors = altPlain.map((t) => ({ title: t, url: "" }));
1326
+ }
1327
+ }
1328
+ }
1329
+ let sections = parseLinksFromLabeledField(html, baseURL, "Section");
1330
+ if (sections.length === 0) {
1331
+ const sPlain = parsePlainValuesFromLabeledField(html, "Section");
1332
+ if (sPlain.length) sections = sPlain.map((t) => ({ title: t, url: "" }));
1333
+ }
1334
+ let tags = parseLinksFromLabeledField(html, baseURL, "Tags");
1335
+ if (tags.length === 0) {
1336
+ const block = /<div[^>]*class="[^"]*field-name-field-category[^"]*"[^>]*>([\s\S]*?)<\/div>/i.exec(html);
1337
+ if (block) tags = collectLinks(block[1], baseURL);
1338
+ }
1339
+ const characters = parseLinksFromLabeledField(html, baseURL, "Characters");
1340
+ const userTags = parseLinksFromLabeledField(html, baseURL, "User tags");
1341
+ const { rating, votes } = parseVotesAndRating(html);
1342
+ const views = parseViews(html);
1343
+ const kind = guessKindFromPath(absoluteUrl);
1344
+ const field = findFieldNodeAndSys(html);
1345
+ const uploader = parseUploader(html, baseURL);
1346
+ const meta = {
1347
+ nodeId: field?.nodeId ?? null,
1348
+ fieldSys: field?.fieldSys ?? null,
1349
+ title,
1350
+ kind,
1351
+ breadcrumbs,
1352
+ authors,
1353
+ sections,
1354
+ tags,
1355
+ characters,
1356
+ userTags,
1357
+ rating,
1358
+ votes,
1359
+ views,
1360
+ related: parseRelated(html, baseURL)
1361
+ };
1362
+ if (uploader) {
1363
+ meta.uploader = uploader;
1364
+ }
1365
+ return { meta, nodeId: meta.nodeId, fieldSys: meta.fieldSys };
1366
+ }
1367
+ function findCanonicalUrl(html, baseURL) {
1368
+ const m1 = /<link[^>]+rel=["']canonical["'][^>]+href=["']([^"']+)["']/i.exec(html);
1369
+ if (m1?.[1]) return absUrl(baseURL, m1[1]) ?? baseURL.replace(/\/+$/, "");
1370
+ const m2 = /<meta[^>]+property=["']og:url["'][^>]+content=["']([^"']+)["']/i.exec(html);
1371
+ if (m2?.[1]) return absUrl(baseURL, m2[1]) ?? baseURL.replace(/\/+$/, "");
1372
+ return baseURL.replace(/\/+$/, "");
1373
+ }
1374
+ var EXCLUDE_URL_PATTERNS = [
1375
+ /\/styles\/avatars\//i,
1376
+ /\/user_avatars\//i,
1377
+ /\/default_images\//i,
1378
+ /\/styles\/taxonomy_(?:comics|manga)\//i,
1379
+ /\/com_preview\//i,
1380
+ /\/promo\//i
1381
+ ];
1382
+ function isExcludedUrl(u) {
1383
+ const s = String(u);
1384
+ return EXCLUDE_URL_PATTERNS.some((re) => re.test(s));
1385
+ }
1386
+ function stripExcludedBlocks(html) {
1387
+ const patterns = [
1388
+ /<div[^>]+id="comments"[^>]*>[\s\S]*?<\/div>/gi,
1389
+ /<section[^>]+id="comments"[^>]*>[\s\S]*?<\/section>/gi,
1390
+ /<div[^>]+class="[^"]*\bcomments?\b[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
1391
+ /<div[^>]+class="[^"]*\bcomment\b[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
1392
+ /<ul[^>]+class="[^"]*\bcomment\b[^"]*"[^>]*>[\s\S]*?<\/ul>/gi,
1393
+ /<div[^>]+class="[^"]*\brelated\b[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
1394
+ /<div[^>]+class="[^"]*\bmore\b[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
1395
+ /<div[^>]+class="[^"]*\bmore-comics\b[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
1396
+ /<div[^>]+class="[^"]*\bpane-related\b[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
1397
+ /<aside[\s\S]*?<\/aside>/gi,
1398
+ /<div[^>]+class="[^"]*\bsidebar\b[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
1399
+ /<div[^>]+class="[^"]*\bnode-footer\b[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
1400
+ /<div[^>]+class="[^"]*\bpane-views\b[^"]*"[^>]*>[\s\S]*?<\/div>/gi,
1401
+ /<div[^>]+class="[^"]*\bpane-taxonomy\b[^"]*"[^>]*>[\s\S]*?<\/div>/gi
1402
+ ];
1403
+ let cleaned = html;
1404
+ for (const re of patterns) cleaned = cleaned.replace(re, "");
1405
+ return cleaned;
1406
+ }
1407
+ function collectImgSrcs(html) {
1408
+ const out = [];
1409
+ const re = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi;
1410
+ let m;
1411
+ while (m = re.exec(html)) out.push(m[1]);
1412
+ return out;
1413
+ }
1414
+ function collectContentImages(html) {
1415
+ const cleaned = stripExcludedBlocks(html);
1416
+ return collectImgSrcs(cleaned).filter((u) => !!u && !isExcludedUrl(u));
1417
+ }
1418
+ function parseViewer(html, baseURL) {
1419
+ const absoluteUrl = findCanonicalUrl(html, baseURL);
1420
+ const { meta } = parseViewerMeta(html, baseURL, absoluteUrl);
1421
+ const inline = parseInlineJuiceboxFromHtml(html).map((im) => {
1422
+ const original = toAbsolute(baseURL, im.original || "") || "";
350
1423
  return {
351
- url,
352
- title,
353
- images,
354
- tags,
355
- author: null
1424
+ original,
1425
+ large: im.large ? toAbsolute(baseURL, im.large) || void 0 : void 0,
1426
+ medium: im.medium ? toAbsolute(baseURL, im.medium) || void 0 : void 0,
1427
+ small: im.small ? toAbsolute(baseURL, im.small) || void 0 : void 0,
1428
+ thumb: im.thumb ? toAbsolute(baseURL, im.thumb) || void 0 : void 0
356
1429
  };
1430
+ }).filter((im) => !!im.original);
1431
+ let fallback = [];
1432
+ if (inline.length === 0) {
1433
+ const srcs = collectContentImages(html).map((u) => toAbsolute(baseURL, u) || "").filter((u) => !!u);
1434
+ const seen = /* @__PURE__ */ new Set();
1435
+ fallback = srcs.filter((u) => {
1436
+ if (!u || seen.has(u)) return false;
1437
+ seen.add(u);
1438
+ return true;
1439
+ }).map((u) => ({ original: u }));
1440
+ }
1441
+ const all = [...inline, ...fallback];
1442
+ const byOriginal = /* @__PURE__ */ new Map();
1443
+ for (const im of all) {
1444
+ const key = im.original || "";
1445
+ if (key && !byOriginal.has(key)) byOriginal.set(key, im);
357
1446
  }
358
- async getPost(urlOrSlug) {
359
- const url = absolutize(this.baseURL, urlOrSlug) ?? new URL(urlOrSlug, this.baseURL).href;
360
- const html = await this.http.getHtml(url);
361
- return this.parsePost(html, url);
362
- }
363
- // -------- Smart resolve
364
- async resolveSmart(urlOrSlug, _opts) {
365
- const url = absolutize(this.baseURL, urlOrSlug) ?? new URL(urlOrSlug, this.baseURL).href;
366
- const html = await this.http.getHtml(url);
367
- const doc = this.dom.parse(html);
368
- const articleImgs = this.dom.qsa(doc.documentElement ?? doc, "article img");
369
- if (articleImgs.length >= 2) {
370
- const post = this.parsePost(html, url);
1447
+ return { meta, images: Array.from(byOriginal.values()) };
1448
+ }
1449
+ var viewer_default = parseViewer;
1450
+
1451
+ // src/parsers/video.ts
1452
+ var ABS_URL = /^https?:\/\//i;
1453
+ function absolutize(u, base) {
1454
+ if (!u) return "";
1455
+ if (ABS_URL.test(u)) return u;
1456
+ if (u.startsWith("//")) return "https:" + u;
1457
+ if (u.startsWith("/")) return base.replace(/\/+$/, "") + u;
1458
+ return u;
1459
+ }
1460
+ function parseVideoFromHtml(html, baseURL) {
1461
+ if (!html || !/node-video|class=["']video-js|<video/i.test(html)) return null;
1462
+ const posterMatch = html.match(/<video[^>]*\sposter=["']([^"']+)["']/i) || html.match(/class=["']video-js[^"']*["'][^>]*\sposter=["']([^"']+)["']/i);
1463
+ const poster = posterMatch ? absolutize(posterMatch[1], baseURL) : void 0;
1464
+ const sources = [];
1465
+ const mainVideo = html.match(/<video[^>]*\ssrc=["']([^"']+)["'][^>]*>/i);
1466
+ if (mainVideo) sources.push({ url: absolutize(mainVideo[1], baseURL) });
1467
+ const re = /<source[^>]*\ssrc=["']([^"']+)["'][^>]*?(?:\stype=["']([^"']+)["'])?[^>]*>/gi;
1468
+ for (let m; m = re.exec(html); ) {
1469
+ sources.push({ url: absolutize(m[1], baseURL), type: m[2] });
1470
+ }
1471
+ if (!sources.length) return null;
1472
+ return { poster, sources };
1473
+ }
1474
+
1475
+ // src/api/viewer.ts
1476
+ var ABS_URL2 = /^https?:\/\//i;
1477
+ function absolutize2(u, base) {
1478
+ if (!u) return "";
1479
+ if (ABS_URL2.test(u)) return u;
1480
+ if (u.startsWith("//")) return "https:" + u;
1481
+ if (u.startsWith("/")) return base.replace(/\/+$/, "") + u;
1482
+ return base.replace(/\/+$/, "") + "/" + u.replace(/^\/+/, "");
1483
+ }
1484
+ function buildViewerUrl(base, urlOrSlug) {
1485
+ if (ABS_URL2.test(urlOrSlug)) return urlOrSlug;
1486
+ if (urlOrSlug.startsWith("/")) return base.replace(/\/+$/, "") + urlOrSlug;
1487
+ return base.replace(/\/+$/, "") + "/" + urlOrSlug.replace(/^\/+/, "");
1488
+ }
1489
+ async function fetchHtml(http, url) {
1490
+ const anyHttp = http;
1491
+ if (typeof anyHttp.getText === "function") return anyHttp.getText(url);
1492
+ if (typeof anyHttp.get === "function") return anyHttp.get(url);
1493
+ if (typeof anyHttp.text === "function") return anyHttp.text(url);
1494
+ if (typeof anyHttp.fetch === "function") {
1495
+ const r = await anyHttp.fetch(url);
1496
+ if (typeof r === "string") return r;
1497
+ if (r && typeof r.text === "function") return await r.text();
1498
+ }
1499
+ if (typeof fetch === "function") {
1500
+ const r = await fetch(url);
1501
+ return await r.text();
1502
+ }
1503
+ throw new Error("HttpClient: no getText/get/text/fetch available");
1504
+ }
1505
+ function proxyImgMaybe(u, opts) {
1506
+ if (!u) return "";
1507
+ return opts?.proxyImage ? opts.proxyImage(u) : u;
1508
+ }
1509
+ function proxyVidMaybe(u, opts) {
1510
+ if (!u) return "";
1511
+ const proxyVideo = opts?.proxyVideo;
1512
+ return proxyVideo ? proxyVideo(u) : proxyImgMaybe(u, opts);
1513
+ }
1514
+ function tryParseRichMeta(html, baseURL, absoluteUrl) {
1515
+ const anyParsers = viewer_exports;
1516
+ if (typeof anyParsers.parseViewerMeta === "function") {
1517
+ try {
1518
+ const { meta } = anyParsers.parseViewerMeta(html, baseURL, absoluteUrl);
1519
+ if (!meta.title) {
1520
+ const t = extractMeta(html, baseURL).title;
1521
+ if (t) meta.title = t;
1522
+ }
1523
+ return meta;
1524
+ } catch {
1525
+ }
1526
+ }
1527
+ return extractMeta(html, baseURL);
1528
+ }
1529
+ function parseImagesWithBackoff(html, baseURL) {
1530
+ const anyParsers = viewer_exports;
1531
+ const candidate = anyParsers.parseViewer ?? anyParsers.default;
1532
+ if (typeof candidate === "function") {
1533
+ return candidate(html, baseURL);
1534
+ }
1535
+ const images = [];
1536
+ const re = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi;
1537
+ let m;
1538
+ while (m = re.exec(html)) {
1539
+ const original = absolutize2(m[1], baseURL);
1540
+ if (!original) continue;
1541
+ images.push({ original, medium: original });
1542
+ }
1543
+ const meta = extractMeta(html, baseURL);
1544
+ return { meta, images };
1545
+ }
1546
+ function hasViewerClues(html) {
1547
+ const hasJuicebox = /juicebox/i.test(html) || /\/juicebox\/xml\/field\/node\/\d+\/[a-z0-9_]+\/full/i.test(html);
1548
+ const hasFieldNode = /id=["']field--node--\d+--[a-z0-9_-]+--full["']/i.test(html);
1549
+ const hasJbStyles = /styles\/juicebox_(?:large|medium|small)\//i.test(html);
1550
+ const hasNodeBody = /<body[^>]+class=["'][^"']*\bnode\b[^"']*["']/i.test(html);
1551
+ const hasGalleryField = /field-name-(?:field_)?(?:pictures|images|image|post_pictures)\b/i.test(
1552
+ html
1553
+ );
1554
+ return hasJuicebox || hasFieldNode || hasJbStyles || hasNodeBody || hasGalleryField;
1555
+ }
1556
+ var ViewerAPI = {
1557
+ async resolveViewer(http, baseURL, urlOrSlug, opts = {}) {
1558
+ const url = buildViewerUrl(baseURL, urlOrSlug);
1559
+ const html = await fetchHtml(http, url);
1560
+ const parsedVideo = parseVideoFromHtml(html, baseURL);
1561
+ if (parsedVideo && parsedVideo.sources?.length) {
1562
+ const meta = tryParseRichMeta(html, baseURL, url);
371
1563
  return {
372
- route: "viewer",
373
- data: {
374
- absoluteUrl: url,
375
- viewer: {
376
- kind: "images",
377
- meta: {
378
- nodeId: null,
379
- fieldSys: null,
380
- title: post.title,
381
- kind: "images",
382
- breadcrumbs: [],
383
- authors: [],
384
- sections: [],
385
- tags: [],
386
- characters: [],
387
- userTags: []
388
- },
389
- images: post.images.map((u) => ({ original: u }))
390
- }
1564
+ kind: "video",
1565
+ meta,
1566
+ video: {
1567
+ poster: parsedVideo.poster ? proxyImgMaybe(parsedVideo.poster, opts) : void 0,
1568
+ sources: parsedVideo.sources.map((s) => ({
1569
+ ...s,
1570
+ proxied: proxyVidMaybe(s.url, opts)
1571
+ }))
391
1572
  }
392
1573
  };
393
1574
  }
394
- const items = this.parseListing(html);
395
- const hasNext = this.parseHasNext(html);
396
- return {
397
- route: "listing",
398
- data: {
399
- page: 0,
400
- items,
401
- hasNext,
402
- absoluteUrl: url,
403
- path: new URL(url).pathname
1575
+ if (hasViewerClues(html)) {
1576
+ const imgRes = parseImagesWithBackoff(html, baseURL);
1577
+ const images = (imgRes.images || []).map((im) => {
1578
+ const preferred = im.original || im.large || im.medium || im.small || im.thumb || "";
1579
+ return { ...im, proxied: proxyImgMaybe(preferred, opts) };
1580
+ });
1581
+ return {
1582
+ kind: "images",
1583
+ meta: imgRes.meta,
1584
+ images
1585
+ };
1586
+ }
1587
+ return { kind: "other", meta: extractMeta(html, baseURL) };
1588
+ },
1589
+ async resolveSmart(http, baseURL, urlOrSlug, opts = {}) {
1590
+ const url = buildViewerUrl(baseURL, urlOrSlug);
1591
+ const u = new URL(url);
1592
+ const path = u.pathname;
1593
+ const html = await fetchHtml(http, url);
1594
+ const parsedVideo = parseVideoFromHtml(html, baseURL);
1595
+ if (parsedVideo && parsedVideo.sources?.length) {
1596
+ const meta = tryParseRichMeta(html, baseURL, url);
1597
+ const viewer = {
1598
+ kind: "video",
1599
+ meta,
1600
+ video: {
1601
+ poster: parsedVideo.poster ? proxyImgMaybe(parsedVideo.poster, opts) : void 0,
1602
+ sources: parsedVideo.sources.map((s) => ({
1603
+ ...s,
1604
+ proxied: proxyVidMaybe(s.url, opts)
1605
+ }))
1606
+ }
1607
+ };
1608
+ let recommendations;
1609
+ try {
1610
+ const recPage = parseHubListing(html, baseURL, 0);
1611
+ if (recPage?.items?.length) {
1612
+ recommendations = recPage.items.map((it) => ({
1613
+ ...it,
1614
+ proxiedThumb: it.thumb ? proxyImgMaybe(it.thumb, opts) : void 0
1615
+ }));
1616
+ }
1617
+ } catch {
404
1618
  }
405
- };
406
- }
407
- // -------- Alphabet (best effort)
408
- async alphabetLetters(section) {
409
- const path = section === "manga" ? "/munga" : `/${section}`;
410
- const html = await this.http.getHtml(path);
411
- const doc = this.dom.parse(html);
412
- const root = doc.documentElement ?? doc;
413
- const letters = [];
414
- const els = this.dom.qsa(
415
- root,
416
- ".alphabet a, .alphabet__item a, .letters a, a[href*='letter=']"
417
- );
418
- for (const a of els) {
419
- const label = this.text(a) || this.attr(a, "data-letter");
420
- if (!label) continue;
421
- const href = this.attr(a, "href");
422
- letters.push({ label, value: label, href });
1619
+ const data = { absoluteUrl: url, path, viewer };
1620
+ data.recommendations = recommendations;
1621
+ return { route: "viewer", data };
423
1622
  }
424
- if (!letters.length) {
425
- return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").map((c) => ({ label: c, value: c, href: "" }));
1623
+ if (hasViewerClues(html)) {
1624
+ const { meta, images } = parseImagesWithBackoff(html, baseURL);
1625
+ const mapped = (images || []).map((im) => {
1626
+ const preferred = im.original || im.large || im.medium || im.small || im.thumb || "";
1627
+ return { ...im, proxied: proxyImgMaybe(preferred, opts) };
1628
+ });
1629
+ const viewer = { kind: "images", meta, images: mapped };
1630
+ let recommendations;
1631
+ try {
1632
+ const recPage = parseHubListing(html, baseURL, 0);
1633
+ if (recPage?.items?.length) {
1634
+ recommendations = recPage.items.map((it) => ({
1635
+ ...it,
1636
+ proxiedThumb: it.thumb ? proxyImgMaybe(it.thumb, opts) : void 0
1637
+ }));
1638
+ }
1639
+ } catch {
1640
+ }
1641
+ const data = { absoluteUrl: url, path, viewer };
1642
+ data.recommendations = recommendations;
1643
+ return { route: "viewer", data };
426
1644
  }
427
- return letters;
428
- }
429
- async alphabet(section, letter, page = 0) {
430
- const path = section === "manga" ? "/munga" : `/${section}`;
431
- return this.listByPath(path, page, { letter });
432
- }
433
- // -------- Updates (views/ajax) best effort
434
- // ВАЖНО: чтобы не ловить TS2411, не используем индексную сигнатуру с строгим 'string|number'.
435
- // Вход — Partial (значит, значения могут быть undefined), а отправляем — отфильтрованный Record.
436
- async updates(params) {
437
- const filtered = Object.fromEntries(
438
- Object.entries(params ?? {}).filter(([, v]) => v !== void 0)
439
- );
440
- const p = { view_name: params?.view_name ?? "new_mini", ...params };
441
- const json = await this.http.postForm("/views/ajax", p);
442
- const raw = typeof json === "string" ? json : JSON.stringify(json);
443
- const items = this.parseListing(raw);
444
- return { items, first: 0, last: items.length, html: raw, viewName: String(p.view_name) };
1645
+ const page = await listings_exports.listByPath(http, baseURL, path, 0);
1646
+ return { route: "listing", data: { ...page, absoluteUrl: url, path } };
1647
+ }
1648
+ };
1649
+ function extractText(html, re) {
1650
+ const m = html.match(re);
1651
+ return m ? m[1].replace(/<[^>]*>/g, "").trim() : "";
1652
+ }
1653
+ function grabLinksByLabel(html, baseURL, label) {
1654
+ const esc = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1655
+ const reLbl = new RegExp(
1656
+ `<(?:h3|div)[^>]*class=["'][^"']*field-label[^"']*["'][^>]*>\\s*${esc}\\s*:?\\s*<\\/[^>]+>`,
1657
+ "i"
1658
+ );
1659
+ const idx = html.search(reLbl);
1660
+ if (idx < 0) return [];
1661
+ const open = html.lastIndexOf("<div", idx);
1662
+ const close = html.indexOf("</div>", idx);
1663
+ if (open < 0 || close < 0) return [];
1664
+ const block = html.slice(open, close + 6);
1665
+ const out = [];
1666
+ const reA = /<a[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi;
1667
+ for (let m; m = reA.exec(block); ) {
1668
+ out.push({
1669
+ title: m[2].replace(/<[^>]*>/g, "").trim(),
1670
+ url: absolutize2(m[1], baseURL)
1671
+ });
1672
+ }
1673
+ return out;
1674
+ }
1675
+ function grabLinks(html, blockRe, baseURL) {
1676
+ const alt = `(?:${blockRe.source})`;
1677
+ const reDiv = new RegExp(
1678
+ `<div[^>]*class=["'][^"']*\\bfield\\b[^"']*\\b${alt}\\b[^"']*["'][^>]*>([\\s\\S]*?)<\\/div>`,
1679
+ "i"
1680
+ );
1681
+ const m = reDiv.exec(html);
1682
+ if (!m) return [];
1683
+ const block = m[1];
1684
+ const arr = [];
1685
+ const reA = /<a[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi;
1686
+ for (let x; x = reA.exec(block); ) {
1687
+ arr.push({
1688
+ title: x[2].replace(/<[^>]*>/g, "").trim(),
1689
+ url: absolutize2(x[1], baseURL)
1690
+ });
1691
+ }
1692
+ return arr;
1693
+ }
1694
+ function extractMeta(html, baseURL) {
1695
+ const title = extractText(html, /<h1[^>]*id=["']page-title["'][^>]*>([\s\S]*?)<\/h1>/i) || extractText(html, /<title>([\s\S]*?)<\/title>/i);
1696
+ const breadcrumbs = [];
1697
+ const reCrumb = /<span[^>]*typeof=["']v:Breadcrumb["'][^>]*>[\s\S]*?<a[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>[\s\S]*?<\/span>/gi;
1698
+ for (let m; m = reCrumb.exec(html); ) {
1699
+ breadcrumbs.push({
1700
+ title: m[2].replace(/<[^>]*>/g, "").trim(),
1701
+ url: absolutize2(m[1], baseURL)
1702
+ });
1703
+ }
1704
+ let authors = grabLinks(
1705
+ html,
1706
+ /field-name-field-vd-authors|field-name-field-authors|field-name-field-au/i,
1707
+ baseURL
1708
+ ) || [];
1709
+ if (authors.length === 0) {
1710
+ authors = grabLinksByLabel(html, baseURL, "Author");
1711
+ }
1712
+ const sections = grabLinks(
1713
+ html,
1714
+ /field-name-field-vd-group|field-name-field-group|field-name-field-sections/i,
1715
+ baseURL
1716
+ );
1717
+ const tags = grabLinks(html, /field-name-field-(?:vd-)?tags|field-name-field-category/i, baseURL) || [];
1718
+ const meta = {
1719
+ title,
1720
+ breadcrumbs,
1721
+ authors,
1722
+ sections,
1723
+ tags,
1724
+ nodeId: "",
1725
+ fieldSys: {},
1726
+ kind: "viewer"
1727
+ };
1728
+ return meta;
1729
+ }
1730
+
1731
+ // src/client-core.ts
1732
+ var MultpornClient = class {
1733
+ http;
1734
+ baseURL;
1735
+ constructor(opts = {}) {
1736
+ this.baseURL = (opts.baseURL ?? "https://multporn.net").replace(/\/+$/, "");
1737
+ this.http = new HttpClient({ ...opts, baseURL: this.baseURL });
1738
+ }
1739
+ // -------- Listing
1740
+ latest(page = 0, params) {
1741
+ return listings_exports.latest(this.http, this.baseURL, page, params);
1742
+ }
1743
+ listByPath(path, page = 0, params) {
1744
+ return listings_exports.listByPath(this.http, this.baseURL, path, page, params);
1745
+ }
1746
+ // -------- Search
1747
+ search(query, page = 0) {
1748
+ return search_exports.search(this.http, this.baseURL, query, page);
1749
+ }
1750
+ // -------- Post
1751
+ getPost(urlOrSlug) {
1752
+ return posts_exports.getPost(this.http, this.baseURL, urlOrSlug);
1753
+ }
1754
+ // -------- Viewer / Resolver
1755
+ /**
1756
+ * Жёсткое разрешение ссылки в ViewerResult (images/video/other) без маршрутизации.
1757
+ */
1758
+ resolve(urlOrSlug, opts = {}) {
1759
+ return ViewerAPI.resolveViewer(this.http, this.baseURL, urlOrSlug, opts);
1760
+ }
1761
+ /**
1762
+ * Умный резолвер: возвращает либо listing-страницу (хаб), либо viewer-пейлоад (пост).
1763
+ */
1764
+ resolveSmart(urlOrSlug, opts = {}) {
1765
+ return ViewerAPI.resolveSmart(this.http, this.baseURL, urlOrSlug, opts);
1766
+ }
1767
+ // -------- Updates (Drupal / jcarousel/ajax/views)
1768
+ updates(params = {}) {
1769
+ return updates_exports.updates(this.http, this.baseURL, params);
1770
+ }
1771
+ viewUpdates(viewName, params) {
1772
+ return this.updates({ ...params ?? {}, view_name: viewName });
1773
+ }
1774
+ // Шорткаты для популярных view_name — выше остаётся общий метод updates()
1775
+ updatesNewMini(p) {
1776
+ return updates_exports.updates(this.http, this.baseURL, { ...p ?? {}, view_name: "new_mini" });
1777
+ }
1778
+ userUploadFront(p) {
1779
+ return updates_exports.updates(this.http, this.baseURL, {
1780
+ ...p ?? {},
1781
+ view_name: "user_upload_front"
1782
+ });
1783
+ }
1784
+ updatedManga(p) {
1785
+ return updates_exports.updates(this.http, this.baseURL, {
1786
+ ...p ?? {},
1787
+ view_name: "updated_manga"
1788
+ });
1789
+ }
1790
+ updatedMangaPromoted(p) {
1791
+ return updates_exports.updates(this.http, this.baseURL, {
1792
+ ...p ?? {},
1793
+ view_name: "updated_manga_promoted"
1794
+ });
1795
+ }
1796
+ updatedGames(p) {
1797
+ return updates_exports.updates(this.http, this.baseURL, {
1798
+ ...p ?? {},
1799
+ view_name: "updated_games"
1800
+ });
1801
+ }
1802
+ randomTopComics(p) {
1803
+ return updates_exports.updates(this.http, this.baseURL, {
1804
+ ...p ?? {},
1805
+ view_name: "random_top_comics"
1806
+ });
1807
+ }
1808
+ topRandomCharacters(p) {
1809
+ return updates_exports.updates(this.http, this.baseURL, {
1810
+ ...p ?? {},
1811
+ view_name: "top_random_characters"
1812
+ });
1813
+ }
1814
+ // -------- Alphabet
1815
+ alphabetLetters(section) {
1816
+ return alphabet_exports.alphabetLetters(this.http, this.baseURL, section);
445
1817
  }
446
- async viewUpdates(viewName, params) {
447
- return this.updates({ view_name: viewName, ...params || {} });
1818
+ alphabet(section, letter, page = 0) {
1819
+ return alphabet_exports.alphabetItems(this.http, this.baseURL, section, letter, page);
448
1820
  }
449
1821
  };
450
1822
  export {
451
- MultpornClientCore as MultpornClient
1823
+ MultpornClient
452
1824
  };