import { Worker } from 'node:worker_threads'; import { DEFAULT_LISTS, loadLists } from './subscriptions.mjs'; export class Filters { constructor() { this.worker = new Worker(new URL('./filter-worker.mjs', import.meta.url), { execArgv: [], resourceLimits: { maxOldGenerationSizeMb: 384 } }); this.next = 1; this.pending = new Map(); this.closed = false; this.worker.on('message', ({ id, result, error }) => { const pending = this.pending.get(id); if (!pending) return; clearTimeout(pending.timer); this.pending.delete(id); if (error) pending.reject(new Error(error)); else pending.resolve(result); }); const fail = () => { this.closed = true; for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error('The filter worker stopped.')); } this.pending.clear(); }; this.worker.on('error', fail); this.worker.on('exit', fail); } call(type, payload = {}, timeout = 3000) { if (this.closed || this.pending.size >= 512) return Promise.reject(new Error('Filters are unavailable.')); return new Promise((resolve, reject) => { const id = this.next++; const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('The filter operation timed out.')); }, timeout); this.pending.set(id, { resolve, reject, timer }); this.worker.postMessage({ id, type, ...payload }); }); } async load(extra = '', addresses = DEFAULT_LISTS, options = {}) { const files = await loadLists(addresses, options); this.status = await this.call('load', { text: [...files, extra].join('\n') }, 15_000); return this.status; } match(details) { return this.call('match', { details }); } cosmetics(details) { return this.call('cosmetics', { details }); } close() { return this.worker.terminate(); } }