import type { Event } from 'nostr-tools' import { nostrService } from './nostr' import type { SimplePoolWithSub } from '@/types/nostr-tools-extended' import type { Article } from '@/types/nostr' import { parseArticleFromEvent } from './nostrEventParsing' import { buildTagFilter } from './nostrTagSystem' import { getPrimaryRelaySync } from './config' function createSeriesSubscription(poolWithSub: SimplePoolWithSub, seriesId: string, limit: number) { const filters = [ { ...buildTagFilter({ type: 'publication', seriesId, }), limit, }, ] const relayUrl = getPrimaryRelaySync() return poolWithSub.sub([relayUrl], filters) } export function getArticlesBySeries(seriesId: string, timeoutMs: number = 5000, limit: number = 100): Promise { const pool = nostrService.getPool() if (!pool) { throw new Error('Pool not initialized') } const poolWithSub = pool as SimplePoolWithSub const sub = createSeriesSubscription(poolWithSub, seriesId, limit) return new Promise((resolve) => { const results: Article[] = [] let finished = false const done = () => { if (finished) { return } finished = true sub.unsub() resolve(results) } sub.on('event', (event: Event) => { const parsed = parseArticleFromEvent(event) if (parsed) { results.push(parsed) } }) sub.on('eose', () => done()) setTimeout(() => done(), timeoutMs).unref?.() }) }