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