feedkeeper 0.42.2 → 0.42.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feedkeeper",
3
- "version": "0.42.2",
3
+ "version": "0.42.3",
4
4
  "description": "A lightweight, self-hosted RSS reader and remote MCP server for your news, blogs, and AI workflows.",
5
5
  "keywords": [
6
6
  "rss",
@@ -15,7 +15,7 @@ export function articleText(html) {
15
15
  fragment.querySelectorAll("p, div, br, li, h1, h2, h3, h4, blockquote").forEach(node => node.append(" "));
16
16
  return (fragment.textContent ?? "").replace(/\s+/g, " ").trim();
17
17
  }
18
- const READER_CACHE_LIMIT = 300;
18
+ const READER_CACHE_LIMIT = 600;
19
19
  const readerCache = new Map();
20
20
  /**
21
21
  * Article HTML as a reader shows it, without breadcrumbs, repeated headline and similar page chrome. Computed when
@@ -1,117 +1,14 @@
1
- import { SCRIPT_IMAGE_SOURCE } from "./imageSources.js";
2
- import { Readability } from "@mozilla/readability";
3
- import { JSDOM } from "jsdom";
4
1
  import { fetch as undiciFetch } from "undici";
5
- import { cleanPage } from "./content/index.js";
6
2
  import { createPublicDispatcher, SsrfBlockedError } from "./ssrfGuard.js";
7
3
  import { assertPublicFeedUrl } from "./blockedHosts.js";
8
4
  import { articleWorkPool, ArticleHostBusyError, ArticleAccessDeniedError } from "./articleWorkPool.js";
9
5
  import { parseRetryAfter } from "./fetcher.js";
10
6
  import { sourceHost } from "./requestGate.js";
11
7
  import { APP_VERSION } from "../version.js";
8
+ import { isConsentContent, isCachedConsentSnippet } from "./extractorParser.js";
9
+ import { parseArticleInWorker } from "./extractorPool.js";
10
+ export { isConsentContent, isCachedConsentSnippet };
12
11
  const defaultFetch = undiciFetch;
13
- const CONSENT_SELECTORS = [
14
- "#onetrust-consent-sdk",
15
- "#cmpbox",
16
- "#usercentrics-root",
17
- "[id*='sp_message_container']",
18
- "[class*='cookie-banner']",
19
- "[class*='cookie-consent']",
20
- "[class*='consent-banner']",
21
- "[id*='cookie-notice']",
22
- "[id*='cookie-banner']",
23
- ".qc-cmp2-container",
24
- "#didomi-host",
25
- "dialog[open]",
26
- ".cookie-wall",
27
- ".consent-wall",
28
- "[data-nosnippet]",
29
- ];
30
- function cleanConsentDom(doc) {
31
- for (const sel of CONSENT_SELECTORS) {
32
- try {
33
- doc.querySelectorAll(sel).forEach((el) => el.remove());
34
- }
35
- catch {
36
- // ignore invalid selector in edge environments
37
- }
38
- }
39
- }
40
- function isSafeSource(value) {
41
- if (!value)
42
- return false;
43
- const trimmed = value.trim();
44
- if (trimmed.length === 0 || trimmed.length > 4000 || /^javascript:/i.test(trimmed))
45
- return false;
46
- return /^https?:\/\//i.test(trimmed) || /^data:image\//i.test(trimmed) || trimmed.startsWith("/");
47
- }
48
- function resolveLazyImages(doc) {
49
- const images = doc.querySelectorAll("img");
50
- for (const img of images) {
51
- const lazySrc = img.getAttribute("data-lazy-src") ||
52
- img.getAttribute("data-src") ||
53
- img.getAttribute("data-original") ||
54
- img.getAttribute("data-actualsrc");
55
- const src = img.getAttribute("src");
56
- if (isSafeSource(lazySrc) && (!src || src.startsWith("data:") || src.length < 10 || SCRIPT_IMAGE_SOURCE.test(src))) {
57
- img.setAttribute("src", encodeURI(lazySrc.trim()));
58
- }
59
- const lazySrcset = img.getAttribute("data-lazy-srcset") || img.getAttribute("data-srcset");
60
- const srcset = img.getAttribute("srcset");
61
- if (isSafeSource(lazySrcset) && (!srcset || srcset.startsWith("data:"))) {
62
- img.setAttribute("srcset", encodeURI(lazySrcset.trim()));
63
- }
64
- }
65
- const sources = doc.querySelectorAll("source");
66
- for (const source of sources) {
67
- const lazySrcset = source.getAttribute("data-lazy-srcset") || source.getAttribute("data-srcset");
68
- if (isSafeSource(lazySrcset)) {
69
- source.setAttribute("srcset", encodeURI(lazySrcset.trim()));
70
- }
71
- }
72
- }
73
- /**
74
- * Checks if a given URL or extracted HTML/text is a cookie / consent wall rather than article content.
75
- */
76
- export function isConsentContent(finalUrl, html, title, text) {
77
- if (/\/zustimmung[/?]/i.test(finalUrl) ||
78
- /\/consent[/?]/i.test(finalUrl) ||
79
- /\/cookie-wall/i.test(finalUrl) ||
80
- /\/pur-abo[/?]/i.test(finalUrl) ||
81
- /\/cmp[/?]/i.test(finalUrl) ||
82
- /\/privacy-wall/i.test(finalUrl)) {
83
- return true;
84
- }
85
- const combined = `${title || ""} ${text || ""} ${html}`.toLowerCase();
86
- const strongSignatures = [
87
- "cookies zustimmen",
88
- "nutzung aller cookies",
89
- "tracking zustimmen",
90
- "einwilligung verwalten",
91
- "werbung und tracking, indem sie",
92
- "zustimmen & weiter",
93
- "bevor sie fortfahren",
94
- "accept all cookies",
95
- "cookie-einstellungen",
96
- "alle cookies akzeptieren",
97
- "cookies akzeptieren",
98
- "we value your privacy",
99
- ];
100
- const headText = `${title || ""} ${text || ""}`.toLowerCase().slice(0, 600);
101
- const hits = strongSignatures.filter(sig => combined.includes(sig));
102
- if (hits.length === 0)
103
- return false;
104
- const heading = (title || "").toLowerCase();
105
- if (strongSignatures.some(sig => heading.includes(sig)))
106
- return true;
107
- return (text || "").length < 1200 && hits.length >= 2 && hits.some(sig => headText.includes(sig));
108
- }
109
- /**
110
- * Checks cached HTML to see if it was a saved consent banner instead of real article content.
111
- */
112
- export function isCachedConsentSnippet(html) {
113
- return isConsentContent("", html, "", html.replace(/<[^>]+>/g, " "));
114
- }
115
12
  // Browser-like so article pages render normally, but identifies FeedKeeper honestly.
116
13
  const FETCH_USER_AGENT = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 FeedKeeper/${APP_VERSION}`;
117
14
  const FETCH_TIMEOUT_MS = 12_000;
@@ -128,14 +25,6 @@ class ArticleHttpError extends Error {
128
25
  }
129
26
  }
130
27
  const MAX_HTML_BYTES = 2 * 1024 * 1024;
131
- /** From this many characters of text, a page that calls itself not free still holds the article, and its text is kept. */
132
- const PAYWALL_TEXT_MIN = 2500;
133
- /** The link at the end of an article whose publisher flags it as behind a paywall; clients show it as a card. */
134
- function paywallNotice(pageUrl) {
135
- const address = new URL(pageUrl);
136
- const escape = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
137
- return `<p><a href="${escape(address.href)}" data-media="paywall" data-source="${escape(address.hostname.replace(/^www\./, ""))}">${escape(address.hostname.replace(/^www\./, ""))}</a></p>`;
138
- }
139
28
  async function fetchArticleHtml(rawUrl, signal, dispatcher, fetchImpl, ownerSignal) {
140
29
  let currentUrl = rawUrl;
141
30
  for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
@@ -210,51 +99,18 @@ async function extractArticleContent(rawUrl, fetchImpl, signal) {
210
99
  const controller = new AbortController();
211
100
  const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
212
101
  try {
213
- const fetched = await fetchArticleHtml(rawUrl, AbortSignal.any([signal, controller.signal]), dispatcher, fetchImpl, signal);
102
+ const combinedSignal = AbortSignal.any([signal, controller.signal]);
103
+ const fetched = await fetchArticleHtml(rawUrl, combinedSignal, dispatcher, fetchImpl, signal);
214
104
  if (!fetched)
215
105
  return { status: "failed" };
216
- const dom = new JSDOM(fetched.html, { url: fetched.url });
217
- let parsed;
218
- let paywalled = false;
219
- try {
220
- // The content rules run first: players and consent plugins keep the address of an embed in the very tags removed next.
221
- cleanPage(dom.window.document);
222
- dom.window.document.querySelectorAll("script, style, svg, iframe, noscript").forEach(element => element.remove());
223
- const paywall = /"isAccessibleForFree"\s*:\s*(?:false|"false")/i.test(fetched.html);
224
- cleanConsentDom(dom.window.document);
225
- resolveLazyImages(dom.window.document);
226
- parsed = new Readability(dom.window.document, { charThreshold: 60 }).parse();
227
- paywalled = paywall;
228
- if (isConsentContent(fetched.url, parsed?.content ?? fetched.html, parsed?.title, parsed?.textContent)) {
229
- return { status: "consent_wall" };
230
- }
231
- // Publishers flag a whole article as not free although the page carries its text; enough of it is the article.
232
- if ((paywall && (parsed?.textContent?.length ?? 0) < PAYWALL_TEXT_MIN) || ((parsed?.textContent?.length ?? 0) < PAYWALL_TEXT_MIN && /(?:subscribe to (?:continue|read)|sign in to (?:continue|read)|abonnieren und weiterlesen|nur für abonnenten|jetzt abonnieren.{0,40}weiterlesen)/i.test(parsed?.textContent ?? "")))
233
- return { status: "paywall" };
234
- if (!parsed?.content)
235
- return { status: "failed" };
236
- }
237
- finally {
238
- dom.window.close();
239
- }
240
- return {
241
- status: (parsed.textContent?.trim().length ?? 0) < 200 ? "partial" : "ok",
242
- article: {
243
- title: parsed.title || null,
244
- byline: parsed.byline || null,
245
- contentHtml: paywalled ? `${parsed.content}${paywallNotice(fetched.url)}` : parsed.content,
246
- textContent: parsed.textContent || "",
247
- excerpt: parsed.excerpt || null,
248
- siteName: parsed.siteName || null,
249
- },
250
- };
106
+ return await parseArticleInWorker(fetched.html, fetched.url, combinedSignal);
251
107
  }
252
108
  catch (error) {
253
109
  if (error instanceof ArticleHostBusyError)
254
110
  return { status: "throttled", host: error.host, retryAt: error.retryAt, deferred: true };
255
111
  if (error instanceof SsrfBlockedError)
256
112
  throw error;
257
- if (signal.aborted || controller.signal.aborted)
113
+ if (signal.aborted || controller.signal.aborted || (error instanceof Error && ["TimeoutError", "AbortError"].includes(error.name)))
258
114
  return { status: "timeout" };
259
115
  if (error instanceof ArticleHttpError && [401, 402].includes(error.status))
260
116
  return { status: "paywall" };
@@ -0,0 +1,156 @@
1
+ import { Readability } from "@mozilla/readability";
2
+ import { JSDOM } from "jsdom";
3
+ import { cleanPage } from "./content/index.js";
4
+ import { SCRIPT_IMAGE_SOURCE } from "./imageSources.js";
5
+ const CONSENT_SELECTORS = [
6
+ "#onetrust-consent-sdk",
7
+ "#cmpbox",
8
+ "#usercentrics-root",
9
+ "[id*='sp_message_container']",
10
+ "[class*='cookie-banner']",
11
+ "[class*='cookie-consent']",
12
+ "[class*='consent-banner']",
13
+ "[id*='cookie-notice']",
14
+ "[id*='cookie-banner']",
15
+ ".qc-cmp2-container",
16
+ "#didomi-host",
17
+ "dialog[open]",
18
+ ".cookie-wall",
19
+ ".consent-wall",
20
+ "[data-nosnippet]",
21
+ ];
22
+ /** From this many characters of text, a page that calls itself not free still holds the article, and its text is kept. */
23
+ const PAYWALL_TEXT_MIN = 2500;
24
+ function cleanConsentDom(doc) {
25
+ for (const sel of CONSENT_SELECTORS) {
26
+ try {
27
+ doc.querySelectorAll(sel).forEach((el) => el.remove());
28
+ }
29
+ catch {
30
+ // ignore invalid selector in edge environments
31
+ }
32
+ }
33
+ }
34
+ function isSafeSource(value) {
35
+ if (!value)
36
+ return false;
37
+ const trimmed = value.trim();
38
+ if (trimmed.length === 0 || trimmed.length > 4000 || /^javascript:/i.test(trimmed))
39
+ return false;
40
+ return /^https?:\/\//i.test(trimmed) || /^data:image\//i.test(trimmed) || trimmed.startsWith("/");
41
+ }
42
+ function resolveLazyImages(doc) {
43
+ const images = doc.querySelectorAll("img");
44
+ for (const img of images) {
45
+ const lazySrc = img.getAttribute("data-lazy-src") ||
46
+ img.getAttribute("data-src") ||
47
+ img.getAttribute("data-original") ||
48
+ img.getAttribute("data-actualsrc");
49
+ const src = img.getAttribute("src");
50
+ if (isSafeSource(lazySrc) && (!src || src.startsWith("data:") || src.length < 10 || SCRIPT_IMAGE_SOURCE.test(src))) {
51
+ img.setAttribute("src", encodeURI(lazySrc.trim()));
52
+ }
53
+ const lazySrcset = img.getAttribute("data-lazy-srcset") || img.getAttribute("data-srcset");
54
+ const srcset = img.getAttribute("srcset");
55
+ if (isSafeSource(lazySrcset) && (!srcset || srcset.startsWith("data:"))) {
56
+ img.setAttribute("srcset", encodeURI(lazySrcset.trim()));
57
+ }
58
+ }
59
+ const sources = doc.querySelectorAll("source");
60
+ for (const source of sources) {
61
+ const lazySrcset = source.getAttribute("data-lazy-srcset") || source.getAttribute("data-srcset");
62
+ if (isSafeSource(lazySrcset)) {
63
+ source.setAttribute("srcset", encodeURI(lazySrcset.trim()));
64
+ }
65
+ }
66
+ }
67
+ /**
68
+ * Checks if a given URL or extracted HTML/text is a cookie / consent wall rather than article content.
69
+ */
70
+ export function isConsentContent(finalUrl, html, title, text) {
71
+ if (/\/zustimmung[/?]/i.test(finalUrl) ||
72
+ /\/consent[/?]/i.test(finalUrl) ||
73
+ /\/cookie-wall/i.test(finalUrl) ||
74
+ /\/pur-abo[/?]/i.test(finalUrl) ||
75
+ /\/cmp[/?]/i.test(finalUrl) ||
76
+ /\/privacy-wall/i.test(finalUrl)) {
77
+ return true;
78
+ }
79
+ const combined = `${title || ""} ${text || ""} ${html}`.toLowerCase();
80
+ const strongSignatures = [
81
+ "cookies zustimmen",
82
+ "nutzung aller cookies",
83
+ "tracking zustimmen",
84
+ "einwilligung verwalten",
85
+ "werbung und tracking, indem sie",
86
+ "zustimmen & weiter",
87
+ "bevor sie fortfahren",
88
+ "accept all cookies",
89
+ "cookie-einstellungen",
90
+ "alle cookies akzeptieren",
91
+ "cookies akzeptieren",
92
+ "we value your privacy",
93
+ ];
94
+ const headText = `${title || ""} ${text || ""}`.toLowerCase().slice(0, 600);
95
+ const hits = strongSignatures.filter(sig => combined.includes(sig));
96
+ if (hits.length === 0)
97
+ return false;
98
+ const heading = (title || "").toLowerCase();
99
+ if (strongSignatures.some(sig => heading.includes(sig)))
100
+ return true;
101
+ return (text || "").length < 1200 && hits.length >= 2 && hits.some(sig => headText.includes(sig));
102
+ }
103
+ /**
104
+ * Checks cached HTML to see if it was a saved consent banner instead of real article content.
105
+ */
106
+ export function isCachedConsentSnippet(html) {
107
+ return isConsentContent("", html, "", html.replace(/<[^>]+>/g, " "));
108
+ }
109
+ /** The link at the end of an article whose publisher flags it as behind a paywall; clients show it as a card. */
110
+ function paywallNotice(pageUrl) {
111
+ const address = new URL(pageUrl);
112
+ const escape = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
113
+ return `<p><a href="${escape(address.href)}" data-media="paywall" data-source="${escape(address.hostname.replace(/^www\./, ""))}">${escape(address.hostname.replace(/^www\./, ""))}</a></p>`;
114
+ }
115
+ /** Pure CPU-bound JSDOM + Readability extraction so worker threads can run it off the HTTP event loop. */
116
+ export function parseArticleHtml(html, url) {
117
+ const dom = new JSDOM(html, { url });
118
+ let parsed;
119
+ let paywalled = false;
120
+ try {
121
+ // The content rules run first: players and consent plugins keep the address of an embed in the very tags removed next.
122
+ cleanPage(dom.window.document);
123
+ dom.window.document.querySelectorAll("script, style, svg, iframe, noscript").forEach(element => element.remove());
124
+ const paywall = /"isAccessibleForFree"\s*:\s*(?:false|"false")/i.test(html);
125
+ cleanConsentDom(dom.window.document);
126
+ resolveLazyImages(dom.window.document);
127
+ parsed = new Readability(dom.window.document, { charThreshold: 60 }).parse();
128
+ paywalled = paywall;
129
+ if (isConsentContent(url, parsed?.content ?? html, parsed?.title, parsed?.textContent)) {
130
+ return { status: "consent_wall" };
131
+ }
132
+ // Publishers flag a whole article as not free although the page carries its text; enough of it is the article.
133
+ if ((paywall && (parsed?.textContent?.length ?? 0) < PAYWALL_TEXT_MIN) ||
134
+ ((parsed?.textContent?.length ?? 0) < PAYWALL_TEXT_MIN &&
135
+ /(?:subscribe to (?:continue|read)|sign in to (?:continue|read)|abonnieren und weiterlesen|nur für abonnenten|jetzt abonnieren.{0,40}weiterlesen)/i.test(parsed?.textContent ?? ""))) {
136
+ return { status: "paywall" };
137
+ }
138
+ if (!parsed?.content)
139
+ return { status: "failed" };
140
+ }
141
+ finally {
142
+ dom.window.close();
143
+ }
144
+ return {
145
+ status: (parsed.textContent?.trim().length ?? 0) < 200 ? "partial" : "ok",
146
+ article: {
147
+ title: parsed.title || null,
148
+ byline: parsed.byline || null,
149
+ contentHtml: paywalled ? `${parsed.content}${paywallNotice(url)}` : parsed.content,
150
+ textContent: parsed.textContent || "",
151
+ excerpt: parsed.excerpt || null,
152
+ siteName: parsed.siteName || null,
153
+ },
154
+ };
155
+ }
156
+ //# sourceMappingURL=extractorParser.js.map
@@ -0,0 +1,175 @@
1
+ import { Worker } from "node:worker_threads";
2
+ const PARSE_TIMEOUT_MS = 15_000;
3
+ function readWorkerCount() {
4
+ const raw = process.env.EXTRACTOR_WORKERS;
5
+ if (raw === undefined)
6
+ return 2;
7
+ const parsed = Number(raw);
8
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > 4)
9
+ return 2;
10
+ return parsed;
11
+ }
12
+ function createWorker() {
13
+ const isTs = import.meta.url.endsWith(".ts");
14
+ const url = new URL(isTs ? "./extractorWorker.ts" : "./extractorWorker.js", import.meta.url);
15
+ const worker = isTs ? new Worker(url, { execArgv: ["--import", "tsx"] }) : new Worker(url);
16
+ worker.unref();
17
+ return worker;
18
+ }
19
+ class ExtractorWorkerPool {
20
+ slots = [];
21
+ queue = [];
22
+ nextId = 1;
23
+ stopped = false;
24
+ ensureCapacity() {
25
+ const target = readWorkerCount();
26
+ while (!this.stopped && this.slots.length < target && this.slots.length < this.queue.length + this.activeCount()) {
27
+ this.slots.push(this.spawnSlot());
28
+ }
29
+ }
30
+ activeCount() {
31
+ return this.slots.filter(slot => slot.busy).length;
32
+ }
33
+ spawnSlot() {
34
+ const worker = createWorker();
35
+ const slot = { worker, busy: false, current: null, timer: null };
36
+ worker.on("message", (msg) => {
37
+ const task = slot.current;
38
+ if (!task || task.id !== msg.id)
39
+ return;
40
+ this.finishSlot(slot);
41
+ if (msg.error)
42
+ task.reject(new Error(msg.error));
43
+ else if (msg.result)
44
+ task.resolve(msg.result);
45
+ else
46
+ task.reject(new Error("worker_empty_response"));
47
+ this.pump();
48
+ });
49
+ const handleFailure = (reason) => {
50
+ const task = slot.current;
51
+ this.dropSlot(slot);
52
+ if (task)
53
+ task.reject(reason);
54
+ this.pump();
55
+ };
56
+ worker.on("error", err => handleFailure(err instanceof Error ? err : new Error(String(err))));
57
+ worker.on("exit", code => {
58
+ if (this.slots.includes(slot)) {
59
+ handleFailure(new Error(`extractor_worker_exited_${code}`));
60
+ }
61
+ });
62
+ return slot;
63
+ }
64
+ finishSlot(slot) {
65
+ if (slot.timer) {
66
+ clearTimeout(slot.timer);
67
+ slot.timer = null;
68
+ }
69
+ const task = slot.current;
70
+ if (task?.signal && task.abortListener) {
71
+ task.signal.removeEventListener("abort", task.abortListener);
72
+ }
73
+ slot.current = null;
74
+ slot.busy = false;
75
+ slot.worker.unref();
76
+ }
77
+ dropSlot(slot) {
78
+ if (slot.timer) {
79
+ clearTimeout(slot.timer);
80
+ slot.timer = null;
81
+ }
82
+ const task = slot.current;
83
+ if (task?.signal && task.abortListener) {
84
+ task.signal.removeEventListener("abort", task.abortListener);
85
+ }
86
+ slot.current = null;
87
+ slot.busy = false;
88
+ this.slots = this.slots.filter(entry => entry !== slot);
89
+ void slot.worker.terminate().catch(() => { });
90
+ }
91
+ run(html, url, signal) {
92
+ if (this.stopped)
93
+ return Promise.reject(new DOMException("Extractor pool stopped", "AbortError"));
94
+ if (signal?.aborted)
95
+ return Promise.reject(signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError"));
96
+ return new Promise((resolve, reject) => {
97
+ const task = { id: this.nextId++, html, url, signal, resolve, reject };
98
+ if (signal) {
99
+ task.abortListener = () => {
100
+ const idx = this.queue.indexOf(task);
101
+ if (idx !== -1) {
102
+ this.queue.splice(idx, 1);
103
+ reject(signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError"));
104
+ return;
105
+ }
106
+ const runningSlot = this.slots.find(s => s.current === task);
107
+ if (runningSlot) {
108
+ // Terminate a busy worker on abort/timeout so runaway DOM parsing cannot stall later tasks.
109
+ this.dropSlot(runningSlot);
110
+ reject(signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError"));
111
+ this.pump();
112
+ }
113
+ };
114
+ signal.addEventListener("abort", task.abortListener, { once: true });
115
+ }
116
+ this.queue.push(task);
117
+ this.pump();
118
+ });
119
+ }
120
+ pump() {
121
+ if (this.stopped || this.queue.length === 0)
122
+ return;
123
+ this.ensureCapacity();
124
+ for (const slot of this.slots) {
125
+ if (slot.busy)
126
+ continue;
127
+ const task = this.queue.shift();
128
+ if (!task)
129
+ break;
130
+ slot.busy = true;
131
+ slot.current = task;
132
+ slot.worker.ref();
133
+ slot.timer = setTimeout(() => {
134
+ if (slot.current !== task)
135
+ return;
136
+ this.dropSlot(slot);
137
+ task.reject(new DOMException("Worker parse deadline exceeded", "TimeoutError"));
138
+ this.pump();
139
+ }, PARSE_TIMEOUT_MS);
140
+ slot.worker.postMessage({ id: task.id, html: task.html, url: task.url });
141
+ }
142
+ }
143
+ async stop() {
144
+ this.stopped = true;
145
+ for (const task of this.queue.splice(0)) {
146
+ if (task.signal && task.abortListener)
147
+ task.signal.removeEventListener("abort", task.abortListener);
148
+ task.reject(new DOMException("Extractor pool stopped", "AbortError"));
149
+ }
150
+ const closing = this.slots.splice(0);
151
+ await Promise.all(closing.map(async (slot) => {
152
+ if (slot.timer)
153
+ clearTimeout(slot.timer);
154
+ const task = slot.current;
155
+ if (task?.signal && task.abortListener)
156
+ task.signal.removeEventListener("abort", task.abortListener);
157
+ if (task)
158
+ task.reject(new DOMException("Extractor pool stopped", "AbortError"));
159
+ await slot.worker.terminate().catch(() => { });
160
+ }));
161
+ }
162
+ }
163
+ let pool;
164
+ export function parseArticleInWorker(html, url, signal) {
165
+ pool ??= new ExtractorWorkerPool();
166
+ return pool.run(html, url, signal);
167
+ }
168
+ export async function stopExtractorPool() {
169
+ if (!pool)
170
+ return;
171
+ const active = pool;
172
+ pool = undefined;
173
+ await active.stop();
174
+ }
175
+ //# sourceMappingURL=extractorPool.js.map
@@ -0,0 +1,12 @@
1
+ import { parentPort } from "node:worker_threads";
2
+ import { parseArticleHtml } from "./extractorParser.js";
3
+ parentPort?.on("message", (task) => {
4
+ try {
5
+ const result = parseArticleHtml(task.html, task.url);
6
+ parentPort?.postMessage({ id: task.id, result });
7
+ }
8
+ catch (error) {
9
+ parentPort?.postMessage({ id: task.id, error: error instanceof Error ? error.message : "worker_parse_failed" });
10
+ }
11
+ });
12
+ //# sourceMappingURL=extractorWorker.js.map
@@ -148,7 +148,9 @@ export async function stopPollingScheduler() {
148
148
  scheduler = undefined;
149
149
  const { stopImageCache } = await import("./archive.js");
150
150
  const { stopFullTextScheduler } = await import("./fullTextQueue.js");
151
+ const { stopExtractorPool } = await import("./extractorPool.js");
151
152
  await stopFullTextScheduler();
153
+ await stopExtractorPool();
152
154
  await stopImageCache();
153
155
  await Promise.all([queue?.stop(), stopPushOutbox()]);
154
156
  feedRequests.stop();
@@ -45,6 +45,10 @@ async function resolveFeedUrl(inputUrl) {
45
45
  }
46
46
  return { url: targetUrl };
47
47
  }
48
+ function subscribePollWaitMs() {
49
+ const raw = Number(process.env.POLL_SUBSCRIBE_WAIT_MS);
50
+ return Number.isSafeInteger(raw) && raw >= 50 && raw <= 60_000 ? raw : 8_000;
51
+ }
48
52
  export async function subscribeToFeed(userId, inputUrl, label = null, folderId = null) {
49
53
  if (folderId !== null && !findFolderById(userId, folderId)) {
50
54
  throw new FeedError("folder_not_found");
@@ -58,12 +62,16 @@ export async function subscribeToFeed(userId, inputUrl, label = null, folderId =
58
62
  throw new FeedError("already_subscribed");
59
63
  }
60
64
  subscribe(userId, feed.id, label, folderId);
61
- // Fetch immediately so the user sees items right away instead of waiting
62
- // for the next scheduler tick.
63
- const pollResult = await pollFeed(feed);
65
+ // Fetch immediately up to a short response budget so slow publishers complete in background
66
+ // instead of tripping client request timeouts.
67
+ const pollResult = await new Promise((resolve, reject) => {
68
+ const timer = setTimeout(() => resolve(null), subscribePollWaitMs());
69
+ timer.unref?.();
70
+ pollFeed(feed).then(result => { clearTimeout(timer); resolve(result); }, error => { clearTimeout(timer); reject(error); });
71
+ });
64
72
  // A feed that has never been read successfully and fails right away is not a feed
65
73
  // (e.g. a homepage that announces itself as RSS); don't keep the subscription.
66
- if (pollResult.error && !pollResult.deferred && !findFeedById(feed.id)?.last_success_at) {
74
+ if (pollResult && pollResult.error && !pollResult.deferred && !findFeedById(feed.id)?.last_success_at) {
67
75
  unsubscribeRepo(userId, feed.id);
68
76
  if (pollResult.error === "feed_invalid_or_unavailable") {
69
77
  throw new NoFeedsFoundError();
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feedkeeper/server",
3
- "version": "0.42.2",
3
+ "version": "0.42.3",
4
4
  "private": true,
5
5
  "type": "module"
6
6
  }