BlueGit

timfa hfy-novels

Files

hfy-novels / scripts / test-plugin.js

test-plugin.js

test-plugin.js 31.0 KiB Download Raw
1#!/usr/bin/env node
2"use strict";
3
4/**
5 * Laadt de plugin zoals LNReader dat doet: custom require-allowlist,
6 * `new Function`, en daarna popularNovels / searchNovels / parseNovel /
7 * parseChapter. De index komt van een lokale HTTP-server (testdata of
8 * public/). parseChapter, searchNovels, popularNovels en parseNovel
9 * gebruiken gemockte Reddit-JSON, vallen terug op Arctic Shift en daarna
10 * op de statische index; optioneel een live verzoek als HFY_LIVE=1.
11 */
12
13const fs = require("fs");
14const http = require("http");
15const path = require("path");
16const zlib = require("zlib");
17
18const ROOT = path.resolve(__dirname, "..");
19const PLUGIN = fs.readFileSync(path.join(ROOT, "plugin", "hfy-novels.js"), "utf8");
20
21const LIVE_COVER_REDDIT =
22 "https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/covers/reddit.png?rev=master";
23const LIVE_COVER_ARCTIC =
24 "https://git.timfalken.com/timfa/hfy-novels/-/raw/.dist/covers/arctic-shift.png?rev=master";
25
26const NovelStatus = {
27 Completed: "Completed",
28 Ongoing: "Ongoing",
29 OnHiatus: "On Hiatus",
30 Unknown: "Unknown",
31};
32const FilterTypes = { Picker: "Picker", Switch: "Switch", CheckboxGroup: "CheckboxGroup" };
33
34function mimeFor(file, asImg) {
35 if (file.endsWith(".svg")) return asImg ? "image/svg+xml" : "text/plain; charset=utf-8";
36 if (file.endsWith(".json")) return "text/plain; charset=utf-8"; // BlueGit serveert raw ook als text/plain
37 if (file.endsWith(".js")) return "text/plain; charset=utf-8";
38 if (file.endsWith(".png")) return "image/png";
39 return "application/octet-stream";
40}
41
42function startServer(rootDir, chapterHandler, redditHandler) {
43 return new Promise((resolve, reject) => {
44 const server = http.createServer((req, res) => {
45 const url = new URL(req.url, "http://127.0.0.1");
46 if (url.pathname.startsWith("/api/posts/ids") || url.pathname.startsWith("/api/posts/search") || url.pathname.startsWith("/api/subreddits/wikis")) {
47 return chapterHandler(url, res);
48 }
49 if (redditHandler && /\/r\/HFY\//i.test(url.pathname)) {
50 return redditHandler(url, res, req);
51 }
52 if (redditHandler && url.pathname.startsWith("/api/info")) {
53 return redditHandler(url, res, req);
54 }
55 // ?rev=master zoals BlueGit raw-URLs; voor het bestand negeren we de query.
56 let rel = decodeURIComponent(url.pathname).replace(/^\/+/, "");
57 const file = path.join(rootDir, rel);
58 if (!file.startsWith(path.resolve(rootDir))) {
59 res.writeHead(403);
60 res.end("forbidden");
61 return;
62 }
63 fs.readFile(file, (err, data) => {
64 if (err) {
65 res.writeHead(404, { "Content-Type": "text/plain" });
66 res.end("404 " + rel);
67 return;
68 }
69 const asImg = url.searchParams.get("as") === "img";
70 res.writeHead(200, { "Content-Type": mimeFor(file, asImg) });
71 res.end(data);
72 });
73 });
74 server.listen(0, "127.0.0.1", () => {
75 const { port } = server.address();
76 resolve({ server, port, url: "http://127.0.0.1:" + port });
77 });
78 server.on("error", reject);
79 });
80}
81
82function redditListingFor(id) {
83 return [
84 {
85 kind: "Listing",
86 data: {
87 children: [
88 {
89 kind: "t3",
90 data: {
91 id,
92 title: "The Last Terran - Part 1",
93 author: "WriterOne",
94 selftext: "It begins.\n\n[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)",
95 selftext_html: "<div class=\"md\"><p>It begins.</p></div>",
96 permalink: "/r/HFY/comments/" + id + "/",
97 },
98 },
99 ],
100 },
101 },
102 { kind: "Listing", data: { children: [] } },
103 ];
104}
105
106function loginHtml() {
107 return "<!DOCTYPE html><html><head><title>reddit.com: Log in</title></head><body>Log in to Reddit to continue. <a href=\"https://www.reddit.com/login\">log in</a></body></html>";
108}
109
110function blockHtml() {
111 return "<body class=theme-beta><div>Request blocked. reason=lor2</div></body>";
112}
113
114function defaultRedditHandler(mode) {
115 return function redditHandler(url, res) {
116 const m = url.pathname.match(/\/comments\/([0-9a-z]{4,10})\//i);
117 if (!m) {
118 res.writeHead(404, { "Content-Type": "text/plain" });
119 res.end("no default reddit mock for " + url.pathname);
120 return;
121 }
122 const id = m[1].toLowerCase();
123 if (mode === "ok") {
124 res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
125 res.end(JSON.stringify(redditListingFor(id)));
126 return;
127 }
128 if (mode === "403") {
129 res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
130 res.end(blockHtml());
131 return;
132 }
133 if (mode === "login-html") {
134 res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
135 res.end(loginHtml());
136 return;
137 }
138 res.writeHead(500, { "Content-Type": "text/plain" });
139 res.end("reddit mock error");
140 };
141}
142
143function defaultChapterHandler(url, res) {
144 if (!url.pathname.startsWith("/api/posts/ids")) {
145 res.writeHead(404, { "Content-Type": "text/plain" });
146 res.end("no default arctic mock for " + url.pathname);
147 return;
148 }
149 const ids = url.searchParams.get("ids") || "";
150 const id = ids.split(",")[0];
151 const fixture = {
152 data: [
153 {
154 id,
155 title: "The Last Terran - Part 1",
156 author: "WriterOne",
157 selftext: "It begins.\n\n[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)",
158 selftext_html: "<p>It begins.</p>",
159 permalink: "/r/HFY/comments/" + id + "/",
160 },
161 ],
162 };
163 res.writeHead(200, { "Content-Type": "application/json" });
164 res.end(JSON.stringify(fixture));
165}
166
167function wrapResponse(res) {
168 return {
169 ok: res.ok,
170 status: res.status,
171 headers: res.headers,
172 async text() {
173 return await res.text();
174 },
175 async json() {
176 const text = await res.text();
177 return JSON.parse(text);
178 },
179 url: res.url,
180 };
181}
182
183function makeFetchApi(origin) {
184 return async function fetchApi(url, init) {
185 let target = String(url);
186 // Stuur Reddit-JSON naar de lokale testhost, zodat we 200/403/login kunnen simuleren.
187 if (/^https?:\/\/(www\.|old\.)?reddit\.com\//i.test(target)) {
188 const parsed = new URL(target);
189 target = origin + parsed.pathname + parsed.search;
190 }
191 const res = await fetch(target, init);
192 return wrapResponse(res);
193 };
194}
195
196function loadPlugin(storageMap, fetchApi) {
197 const allow = {
198 "@libs/fetch": { fetchApi, fetchText: async (u, i) => (await fetchApi(u, i)).text() },
199 "@libs/filterInputs": { FilterTypes },
200 "@libs/defaultCover": { defaultCover: "https://example.invalid/cover.png" },
201 "@libs/novelStatus": { NovelStatus },
202 "@libs/storage": {
203 storage: {
204 get(key) {
205 return storageMap[key];
206 },
207 set(key, value, expires) {
208 storageMap[key] = value;
209 if (expires != null) {
210 storageMap[key + "__expires"] = expires;
211 }
212 },
213 },
214 },
215 };
216 const pluginModule = { exports: {} };
217 const fn = new Function("exports", "require", "module", PLUGIN);
218 fn(pluginModule.exports, (name) => {
219 if (!allow[name]) {
220 throw new Error("blocked require: " + name);
221 }
222 return allow[name];
223 }, pluginModule);
224 const plugin = pluginModule.exports.default;
225 if (!plugin) {
226 throw new Error("geen default export");
227 }
228 for (const method of ["popularNovels", "searchNovels", "parseNovel", "parseChapter"]) {
229 if (typeof plugin[method] !== "function") {
230 throw new Error("plugin mist " + method);
231 }
232 }
233 return plugin;
234}
235
236function assert(cond, msg) {
237 if (!cond) {
238 throw new Error("FAIL: " + msg);
239 }
240}
241
242function wikiIndexPayload(markdown) {
243 return { kind: "wikipage", data: { content_md: markdown, revision_date: 1700000000 } };
244}
245
246function listingOf(posts) {
247 return {
248 kind: "Listing",
249 data: {
250 children: posts.map((p) => ({ kind: "t3", data: p })),
251 after: null,
252 },
253 };
254}
255
256function samplePost(id, title, author, extras) {
257 const extra = extras || {};
258 return Object.assign(
259 {
260 id,
261 title,
262 author,
263 created_utc: extra.created_utc || 1700000000,
264 permalink: "/r/HFY/comments/" + id + "/",
265 selftext: extra.selftext || "",
266 selftext_html: extra.selftext_html || "",
267 link_flair_text: extra.flair || "OC-Series",
268 over_18: !!extra.over_18,
269 is_self: true,
270 },
271 extra.more || {},
272 );
273}
274
275async function testLiveCatalog(origin, fixtureRoot, fetchApi, assert) {
276 const wikiIndex = fs.readFileSync(path.join(ROOT, "testdata", "wiki", "index.md"), "utf8");
277 const wikiTerran = fs.readFileSync(path.join(ROOT, "testdata", "wiki", "pages", "the_last_terran.md"), "utf8");
278 const state = { redditMode: "ok", arcticMode: "ok", wikiHits: 0, searchHits: 0, arcticSearchHits: 0, arcticWikiHits: 0, infoHits: 0 };
279
280 function redditHandler(url, res) {
281 if (state.redditMode === "403") {
282 res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
283 res.end(blockHtml());
284 return;
285 }
286 if (state.redditMode === "error") {
287 res.writeHead(500, { "Content-Type": "text/plain" });
288 res.end("reddit mock error");
289 return;
290 }
291 if (/\/wiki\/series\/the_last_terran/i.test(url.pathname)) {
292 state.wikiHits += 1;
293 res.writeHead(200, { "Content-Type": "application/json" });
294 res.end(JSON.stringify(wikiIndexPayload(wikiTerran)));
295 return;
296 }
297 if (/\/wiki\/series/i.test(url.pathname)) {
298 state.wikiHits += 1;
299 res.writeHead(200, { "Content-Type": "application/json" });
300 res.end(JSON.stringify(wikiIndexPayload(wikiIndex)));
301 return;
302 }
303 if (/\/search\.json$/i.test(url.pathname)) {
304 state.searchHits += 1;
305 const q = (url.searchParams.get("q") || "").toLowerCase();
306 const posts = [];
307 if (q.indexOf("terran") !== -1 || q.indexOf("writerone") !== -1) {
308 posts.push(
309 samplePost("aaa111", "[OC] The Last Terran - Part 1", "WriterOne", {
310 flair: "OC-FirstOfSeries",
311 selftext: "[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)",
312 }),
313 );
314 }
315 if (q.indexOf("star") !== -1 || q.indexOf("boat") !== -1) {
316 posts.push(
317 samplePost("ddd001", "[OC] Star Boat - Part 1", "Skipper", {
318 flair: "OC-FirstOfSeries",
319 selftext: "[Next](https://www.reddit.com/r/HFY/comments/ddd002/x/)",
320 created_utc: 1700345600,
321 }),
322 );
323 posts.push(
324 samplePost("ddd002", "Star Boat - Part 2", "Skipper", {
325 flair: "OC-Series",
326 selftext: "[Prev](https://www.reddit.com/r/HFY/comments/ddd001/x/)",
327 created_utc: 1700432000,
328 }),
329 );
330 }
331 res.writeHead(200, { "Content-Type": "application/json" });
332 res.end(JSON.stringify(listingOf(posts)));
333 return;
334 }
335 if (/\/new\.json$/i.test(url.pathname)) {
336 state.searchHits += 1;
337 res.writeHead(200, { "Content-Type": "application/json" });
338 res.end(
339 JSON.stringify(
340 listingOf([
341 samplePost("ddd001", "[OC] Star Boat - Part 1", "Skipper", {
342 flair: "OC-FirstOfSeries",
343 created_utc: 1700345600,
344 }),
345 samplePost("meta999", "[META] Weekly thread", "ModAccount", { flair: "Meta", created_utc: 1700345700 }),
346 samplePost("aaa444", "The Last Terran - Part 4", "WriterOne", {
347 flair: "OC-Series",
348 created_utc: 1700259200,
349 }),
350 ]),
351 ),
352 );
353 return;
354 }
355 if (url.pathname.startsWith("/api/info") || /\/comments\/[0-9a-z]+\//i.test(url.pathname)) {
356 state.infoHits += 1;
357 const ids = [];
358 if (url.searchParams.get("id")) {
359 url.searchParams.get("id").split(",").forEach((raw) => ids.push(raw.replace(/^t3_/, "").toLowerCase()));
360 } else {
361 const m = url.pathname.match(/\/comments\/([0-9a-z]{4,10})\//i);
362 if (m) ids.push(m[1].toLowerCase());
363 }
364 const posts = ids.map((id) => {
365 if (id === "aaa222") {
366 return samplePost(id, "The Last Terran - Part 2", "WriterOne", {
367 selftext: "[Prev](https://www.reddit.com/r/HFY/comments/aaa111/x/) | [Next](https://www.reddit.com/r/HFY/comments/aaa333/x/)",
368 });
369 }
370 if (id === "aaa333") {
371 return samplePost(id, "The Last Terran Chapter 3", "WriterOne", {
372 selftext: "[Previous](/r/HFY/comments/aaa222/)",
373 });
374 }
375 return samplePost(id, "The Last Terran - Part 1", "WriterOne", {
376 flair: "OC-FirstOfSeries",
377 selftext: "[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)",
378 });
379 });
380 res.writeHead(200, { "Content-Type": "application/json" });
381 if (/\/comments\//i.test(url.pathname)) {
382 res.end(JSON.stringify(redditListingFor(ids[0] || "aaa111")));
383 } else {
384 res.end(JSON.stringify(listingOf(posts)));
385 }
386 return;
387 }
388 res.writeHead(404, { "Content-Type": "text/plain" });
389 res.end("no reddit mock for " + url.pathname);
390 }
391
392 function arcticHandler(url, res) {
393 if (url.pathname.startsWith("/api/subreddits/wikis")) {
394 state.arcticWikiHits += 1;
395 if (state.arcticMode === "fail") {
396 res.writeHead(500, { "Content-Type": "text/plain" });
397 res.end("arctic wiki fail");
398 return;
399 }
400 const paths = url.searchParams.get("paths") || "";
401 const content = /the_last_terran/.test(paths) ? wikiTerran : wikiIndex;
402 res.writeHead(200, { "Content-Type": "application/json" });
403 res.end(JSON.stringify({ data: [{ path: paths, content }] }));
404 return;
405 }
406 if (url.pathname.startsWith("/api/posts/search")) {
407 state.arcticSearchHits += 1;
408 if (state.arcticMode === "fail") {
409 res.writeHead(500, { "Content-Type": "text/plain" });
410 res.end("arctic search fail");
411 return;
412 }
413 const q = ((url.searchParams.get("query") || "") + " " + (url.searchParams.get("title") || "")).toLowerCase();
414 const posts = [];
415 if (!q.trim() || q.indexOf("star") !== -1 || q.indexOf("boat") !== -1) {
416 posts.push(
417 samplePost("ddd001", "[OC] Star Boat - Part 1", "Skipper", {
418 flair: "OC-FirstOfSeries",
419 created_utc: 1700345600,
420 }),
421 );
422 }
423 res.writeHead(200, { "Content-Type": "application/json" });
424 res.end(JSON.stringify({ data: posts }));
425 return;
426 }
427 if (url.pathname.startsWith("/api/posts/ids")) {
428 return defaultChapterHandler(url, res);
429 }
430 res.writeHead(404);
431 res.end("no arctic mock");
432 }
433
434 const started = await startServer(fixtureRoot, arcticHandler, redditHandler);
435 const liveFetch = makeFetchApi(started.url);
436 try {
437 const storageMap = {
438 indexBaseUrl: origin,
439 indexRev: "",
440 chapterSourceUrl: started.url,
441 chapterSource: "auto",
442 };
443 const plugin = loadPlugin(storageMap, liveFetch);
444
445 state.wikiHits = 0;
446 const popular = await plugin.popularNovels(1, { showLatestNovels: false, filters: {} });
447 assert(popular.some((n) => n.name === "The Last Terran"), "live wiki-index levert The Last Terran");
448 assert(popular.some((n) => n.path.indexOf("the_last_terran") !== -1 || n.path === "wiki/the_last_terran"), "wiki-pad zonder first-id");
449 const hitsAfterFirst = state.wikiHits;
450 assert(hitsAfterFirst >= 1, "wiki-index is bij Reddit opgehaald");
451 const popularAgain = await plugin.popularNovels(1, { filters: {} });
452 assert(popularAgain.some((n) => n.name === "The Last Terran"), "cache levert opnieuw de wiki-index");
453 assert(state.wikiHits === hitsAfterFirst, "tweede popularNovels gebruikt de wiki-cache");
454 const liveCover = popular.find((n) => n.name === "The Last Terran").cover;
455 assertLiveCover(liveCover, "reddit", "live wiki-cover");
456 assert(
457 popularAgain.find((n) => n.name === "The Last Terran").cover === liveCover,
458 "gecachte wiki-index houdt de Reddit-cover",
459 );
460
461 const latest = await plugin.popularNovels(1, { showLatestNovels: true, filters: {} });
462 assert(latest.some((n) => /Star Boat/i.test(n.name)), "Latest/Nieuw toont recente OC-reeks");
463 assertLiveCover(latest.find((n) => /Star Boat/i.test(n.name)).cover, "reddit", "Latest-cover");
464 assert(latest.every((n) => !/Weekly thread/i.test(n.name)), "Meta-posts blijven buiten Nieuw");
465 const viaFilter = await plugin.popularNovels(1, { filters: { catalog: { value: "new" } } });
466 assert(viaFilter.some((n) => /Star Boat/i.test(n.name)), "filter Nieuw toont recente OC-posts");
467
468 const search = await plugin.searchNovels("terran", 1);
469 assert(search.some((n) => /Last Terran/i.test(n.name)), "searchNovels groepeert wiki + Part 1");
470 const star = await plugin.searchNovels("Star Boat", 1);
471 assert(star.length === 1 && /Star Boat/i.test(star[0].name), "losse Part 1+2 worden één novel");
472 assert(star[0].path === "series/ddd001", "nieuwe reeks gebruikt het eerste deel als id");
473 assertLiveCover(star[0].cover, "reddit", "live zoek-cover zonder index-PNG");
474
475 const novel = await plugin.parseNovel("wiki/the_last_terran");
476 assert(novel.name === "The Last Terran", "parseNovel gebruikt de wiki-titel");
477 assert(novel.author === "WriterOne", "parseNovel leest de auteur uit de wiki");
478 assert(novel.chapters.length === 3, "parseNovel volgt de wiki-TOC");
479 assert(novel.chapters[0].path === "chapter/aaa111", "eerste hoofdstukpad");
480 assert(novel.chapters[2].path === "chapter/aaa333", "laatste TOC-hoofdstuk");
481 assertLiveCover(novel.cover, "reddit", "parseNovel live-cover (wiki, geen statische PNG)");
482 const indexed = await plugin.parseNovel("series/aaa111");
483 assert(indexed.cover && indexed.cover.indexOf("/covers/") !== -1, "parseNovel van een indexreeks houdt de statische cover");
484 assert(indexed.cover.indexOf("data:") === -1, "indexcover is geen data-URI");
485
486 delete storageMap.wikiSeriesIndex;
487 state.redditMode = "403";
488 state.arcticMode = "ok";
489 state.arcticWikiHits = 0;
490 const plugin403 = loadPlugin(storageMap, liveFetch);
491 const popular403 = await plugin403.popularNovels(1, { filters: {} });
492 assert(popular403.some((n) => n.name === "The Last Terran"), "403 valt terug op Arctic Shift-wiki");
493 assert(state.arcticWikiHits >= 1, "403 roept Arctic Shift-wiki aan");
494 assertLiveCover(
495 popular403.find((n) => n.name === "The Last Terran").cover,
496 "arctic",
497 "403-wiki-cover",
498 );
499
500 const search403 = await plugin403.searchNovels("Star Boat", 1);
501 assert(search403.some((n) => /Star Boat/i.test(n.name)), "zoeken valt bij 403 terug op Arctic Shift");
502 assertLiveCover(search403.find((n) => /Star Boat/i.test(n.name)).cover, "arctic", "403-zoek-cover");
503
504 const novel403 = await plugin403.parseNovel("wiki/the_last_terran");
505 assertLiveCover(novel403.cover, "arctic", "parseNovel 403-cover");
506
507 delete storageMap.wikiSeriesIndex;
508 state.redditMode = "403";
509 state.arcticMode = "fail";
510 const pluginStatic = loadPlugin(storageMap, liveFetch);
511 const popularStatic = await pluginStatic.popularNovels(1, { filters: {} });
512 assert(popularStatic.some((n) => n.path === "series/aaa111"), "na Reddit+Arctic Shift volgt de statische index");
513 const staticItem = popularStatic.find((n) => n.path === "series/aaa111");
514 assert(staticItem.cover && staticItem.cover.indexOf("/covers/") !== -1, "statische catalogus houdt eigen covers");
515 const searchStatic = await pluginStatic.searchNovels("terran", 1);
516 assert(searchStatic.length === 1 && searchStatic[0].path === "series/aaa111", "zoeken valt terug op de statische index");
517
518 console.log("✔️ live catalogus: wiki, Nieuw, zoeken, parseNovel, 403→Arctic Shift→index");
519 } finally {
520 started.server.close();
521 }
522}
523
524
525
526function assertLiveCover(uri, source, label) {
527 const expected = source === "arctic" ? LIVE_COVER_ARCTIC : LIVE_COVER_REDDIT;
528 assert(typeof uri === "string" && uri === expected, label + " is de vaste " + source + "-cover-URL");
529 assert(/^https:\/\//.test(uri), label + " is een https-URL");
530 assert(uri.indexOf("data:") === -1, label + " is geen data-URI");
531}
532
533function assertPngFile(file, label) {
534 const buf = fs.readFileSync(file);
535 assert(buf[0] === 0x89 && buf.toString("ascii", 1, 4) === "PNG", label + " heeft PNG-signatuur");
536 assert(buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a, label + " heeft geldige PNG-header");
537 const width = buf.readUInt32BE(16);
538 const height = buf.readUInt32BE(20);
539 assert(width === 240 && height === 360, label + " is 240x360");
540 assert(buf.length < 20 * 1024, label + " is een klein bestand");
541}
542
543function testLiveCoverFiles() {
544 for (const name of ["reddit.png", "arctic-shift.png"]) {
545 const src = path.join(ROOT, "plugin", "covers", name);
546 const dist = path.join(ROOT, ".dist", "covers", name);
547 assert(fs.existsSync(src), name + " staat in plugin/covers");
548 assert(fs.existsSync(dist), name + " staat in .dist/covers");
549 assertPngFile(src, "bron " + name);
550 assertPngFile(dist, "dist " + name);
551 assert(Buffer.compare(fs.readFileSync(src), fs.readFileSync(dist)) === 0, name + " is gelijk gekopieerd");
552 }
553 console.log("✔️ vaste broncovers: reddit.png en arctic-shift.png (240x360, klein PNG)");
554}
555
556
557async function main() {
558 const fixtureRoot = path.join(ROOT, "testdata", "index-fixture");
559 const redditState = { mode: "ok", redditHits: 0, arcticHits: 0 };
560 const chapterHandler = (reqUrl, res) => {
561 redditState.arcticHits += 1;
562 return defaultChapterHandler(reqUrl, res);
563 };
564 const redditHandler = (reqUrl, res) => {
565 redditState.redditHits += 1;
566 return defaultRedditHandler(redditState.mode)(reqUrl, res);
567 };
568 const { server, url } = await startServer(fixtureRoot, chapterHandler, redditHandler);
569 const fetchApi = makeFetchApi(url);
570 const failures = [];
571 try {
572 const storageMap = {
573 indexBaseUrl: url,
574 indexRev: "", // geen ?rev= nodig op de testhost
575 chapterSourceUrl: url,
576 chapterSource: "auto",
577 };
578 const plugin = loadPlugin(storageMap, fetchApi);
579
580 assert(plugin.id === "hfyNovels", "id");
581 assert(plugin.name === "HFY Novels", "name");
582 assert(plugin.version === "0.3.2", "version");
583 assert(plugin.site === "https://www.reddit.com/r/HFY/", "site");
584 assert(plugin.pluginSettings && plugin.pluginSettings.indexBaseUrl, "pluginSettings");
585 assert(plugin.filters && plugin.filters.catalog, "filter Nieuw/wiki");
586 assert(plugin.pluginSettings.chapterSource && plugin.pluginSettings.chapterSource.type === "Select", "bron-instelling is Select");
587 assert(typeof plugin.resolveUrl === "function", "resolveUrl");
588 assert(plugin.resolveUrl("chapter/aaa111") === "https://www.reddit.com/r/HFY/comments/aaa111/", "resolveUrl hoofdstuk");
589 assert(plugin.resolveUrl("series/aaa111", true) === "https://www.reddit.com/r/HFY/comments/aaa111/", "resolveUrl reeks");
590 assert(plugin.resolveUrl("wiki/the_last_terran", true) === "https://www.reddit.com/r/HFY/wiki/series/the_last_terran/", "resolveUrl wiki");
591
592 testLiveCoverFiles();
593
594 const popular = await plugin.popularNovels(1, { showLatestNovels: false, filters: {} });
595 assert(Array.isArray(popular) && popular.length >= 1, "popularNovels geeft items");
596 assert(popular[0].name && popular[0].path, "NovelItem heeft name+path");
597 assert(popular[0].cover && popular[0].cover.indexOf("/covers/") !== -1, "cover-URL wijst naar covers/");
598 const coverIsSvg = /\.svg(\?|$)/i.test(popular[0].cover);
599 if (coverIsSvg) {
600 assert(popular[0].cover.indexOf("as=img") !== -1, "SVG-cover heeft as=img");
601 }
602 const coverRes = await fetch(popular[0].cover);
603 assert(coverRes.ok, "cover is ophaalbaar");
604 const coverBuf = Buffer.from(await coverRes.arrayBuffer());
605 if (coverIsSvg) {
606 const coverBody = coverBuf.toString("utf8");
607 assert(coverBody.indexOf("<svg") === 0, "cover is een SVG");
608 assert(coverBody.indexOf(popular[0].name) !== -1, "cover toont de titel");
609 } else {
610 assert(coverBuf[0] === 0x89 && coverBuf.toString("ascii", 1, 4) === "PNG", "cover is een PNG");
611 }
612 const coverAgain = Buffer.from(await (await fetch(popular[0].cover)).arrayBuffer());
613 assert(Buffer.compare(coverBuf, coverAgain) === 0, "dezelfde titel geeft dezelfde cover");
614 assert(popular.every((n) => !n.path.includes("ccc001")), "NSFW standaard verborgen in catalogus");
615
616 const latest = await plugin.popularNovels(1, { showLatestNovels: true, filters: {} });
617 assert(latest.length >= 1, "showLatestNovels werkt via zoekindex");
618
619 const oneshots = await plugin.popularNovels(1, {
620 filters: { kind: { value: "oneshot" }, nsfw: { value: "hide" } },
621 });
622 assert(oneshots.length === 1 && oneshots[0].name === "A Short Hello", "filter oneshot");
623
624 const nsfw = await plugin.popularNovels(1, {
625 filters: { kind: { value: "all" }, nsfw: { value: "show" } },
626 });
627 assert(nsfw.some((n) => n.path.includes("ccc001")), "NSFW zichtbaar met filter");
628
629 const search = await plugin.searchNovels("terran", 1);
630 assert(search.length === 1 && search[0].path === "series/aaa111", "searchNovels op titel");
631 const byAuthor = await plugin.searchNovels("WriterTwo", 1);
632 assert(byAuthor.length === 1, "searchNovels op auteur");
633 assert((await plugin.searchNovels("", 1)).length === 0, "lege zoekterm");
634
635 const novel = await plugin.parseNovel("series/aaa111");
636 assert(novel.path === "series/aaa111", "SourceNovel.path gelijk aan input");
637 assert(novel.author === "WriterOne", "auteur");
638 assert(novel.cover && novel.cover.indexOf("/covers/") !== -1, "parseNovel heeft een cover-URL");
639 assert(novel.chapters.length === 3, "3 hoofdstukken");
640 assert(novel.chapters[0].path === "chapter/aaa111", "hoofdstukpad");
641 assert(novel.chapters[0].chapterNumber === 1, "hoofdstuknummer");
642 assert(novel.status === NovelStatus.Ongoing || novel.status === NovelStatus.OnHiatus || novel.status === NovelStatus.Unknown, "status enum");
643
644 redditState.mode = "ok";
645 redditState.redditHits = 0;
646 redditState.arcticHits = 0;
647 const html = await plugin.parseChapter("chapter/aaa111");
648 assert(/It begins/.test(html), "parseChapter bevat tekst");
649 assert(/<h1>/.test(html), "parseChapter heeft titel");
650 assert(!/<script/i.test(html), "geen script-tags");
651 assert(/Bron: Reddit/.test(html), "Reddit-ok toont Bron: Reddit");
652 assert(redditState.arcticHits === 0, "bij Reddit-ok geen Arctic Shift-aanroep");
653 assert(redditState.redditHits >= 1, "Reddit-JSON is aangeroepen");
654
655 redditState.mode = "403";
656 redditState.redditHits = 0;
657 redditState.arcticHits = 0;
658 const html403 = await plugin.parseChapter("chapter/aaa111");
659 assert(/It begins/.test(html403), "403 valt terug op Arctic Shift");
660 assert(/Bron: Arctic Shift \(fallback\)/.test(html403), "403 toont fallback-bron");
661 assert(redditState.arcticHits >= 1, "403 roept Arctic Shift aan");
662 assert(redditState.redditHits >= 1, "403 probeert eerst Reddit");
663
664 redditState.mode = "login-html";
665 redditState.redditHits = 0;
666 redditState.arcticHits = 0;
667 const htmlLogin = await plugin.parseChapter("chapter/aaa111");
668 assert(/It begins/.test(htmlLogin), "login-HTML valt terug op Arctic Shift");
669 assert(/Bron: Arctic Shift \(fallback\)/.test(htmlLogin), "login-HTML toont fallback-bron");
670 assert(redditState.arcticHits >= 1, "login-HTML roept Arctic Shift aan");
671
672 storageMap.chapterSource = "reddit";
673 redditState.mode = "403";
674 redditState.arcticHits = 0;
675 let redditOnlyThrew = false;
676 try {
677 await plugin.parseChapter("chapter/aaa111");
678 } catch (err) {
679 redditOnlyThrew = /Reddit/.test(String(err && err.message)) && /WebView/.test(String(err && err.message));
680 }
681 assert(redditOnlyThrew, "modus Reddit faalt zichtbaar bij 403");
682 assert(redditState.arcticHits === 0, "modus Reddit gebruikt geen fallback");
683
684 storageMap.chapterSource = "arctic";
685 redditState.mode = "ok";
686 redditState.redditHits = 0;
687 redditState.arcticHits = 0;
688 const htmlArctic = await plugin.parseChapter("chapter/aaa111");
689 assert(/Bron: Arctic Shift</.test(htmlArctic) && !/fallback/.test(htmlArctic), "modus Arctic Shift slaat Reddit over");
690 assert(redditState.redditHits === 0, "modus Arctic Shift roept Reddit niet aan");
691 assert(redditState.arcticHits >= 1, "modus Arctic Shift gebruikt Arctic Shift");
692 storageMap.chapterSource = "auto";
693
694 let threw = false;
695 try {
696 await plugin.parseChapter("chapter/../etc/passwd");
697 } catch (err) {
698 threw = true;
699 }
700 assert(threw, "ongeldig hoofdstuk-id wordt geweigerd");
701
702 // --- Live catalogus: wiki, zoeken, parseNovel, met fallbacks ---
703 await testLiveCatalog(url, fixtureRoot, fetchApi, assert);
704
705 // Manifest-vorm controleren.
706 const manifest = JSON.parse(fs.readFileSync(path.join(ROOT, ".dist", "plugins.json"), "utf8"));
707 const manifestMin = JSON.parse(fs.readFileSync(path.join(ROOT, ".dist", "plugins.min.json"), "utf8"));
708 assert(Array.isArray(manifest) && manifest.length === 1, "plugins.json is een array");
709 assert(manifestMin[0].version === manifest[0].version, "plugins.min.json heeft dezelfde versie");
710 const entry = manifest[0];
711 for (const key of ["id", "name", "site", "lang", "version", "url", "iconUrl"]) {
712 assert(entry[key], "manifest mist " + key);
713 }
714 assert(entry.id === plugin.id && entry.version === plugin.version, "manifest komt overeen met plugin");
715 assert(entry.lang === "English", "lang is de volle taalnaam");
716 assert(entry.hasSettings === true, "hasSettings");
717 assert(entry.url.includes("/-/raw/.dist/hfy-novels.js"), "raw URL voor de plugin-JS");
718 assert(entry.url.includes("rev=master"), "rev=master in de plugin-URL");
719
720 console.log("✔️ plugininterface: popularNovels, searchNovels, parseNovel, parseChapter");
721 console.log("✔️ plugins.json komt overeen met de plugin-export");
722
723 if (process.env.HFY_LIVE === "1") {
724 const liveStorage = {
725 indexBaseUrl: url,
726 indexRev: "",
727 chapterSourceUrl: "https://arctic-shift.photon-reddit.com",
728 };
729 const livePlugin = loadPlugin(liveStorage, async (reqUrl, init) => wrapResponse(await fetch(reqUrl, init)));
730 // Een recent, echt post-id uit de Arctic Shift-probe: willekeurig een
731 // bekend kort id heeft geen zin. We vragen een recente HFY-post op.
732 const listing = await fetch(
733 "https://arctic-shift.photon-reddit.com/api/posts/search?subreddit=HFY&limit=1&sort=desc",
734 { headers: { "User-Agent": "HFY-Novels/0.1 (plugin live test)" } },
735 );
736 if (!listing.ok) {
737 throw new Error("live listing HTTP " + listing.status);
738 }
739 const body = await listing.json();
740 const liveId = body.data[0].id;
741 const liveHtml = await livePlugin.parseChapter("chapter/" + liveId);
742 assert(liveHtml.length > 20, "live parseChapter gaf inhoud");
743 const liveSource = /Bron: ([^<]+)/.exec(liveHtml);
744 console.log("✔️ live parseChapter (" + liveId + ", " + liveHtml.length + " tekens, " + ((liveSource && liveSource[1]) || "bron onbekend") + ")");
745 }
746 } catch (err) {
747 failures.push(err);
748 } finally {
749 server.close();
750 }
751
752 if (failures.length) {
753 for (const err of failures) {
754 console.error(err);
755 }
756 process.exit(1);
757 }
758}
759
760main().catch((err) => {
761 console.error(err);
762 process.exit(1);
763});