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