import type { Event } from 'nostr-tools' import { nostrService } from './nostr' import type { SimplePoolWithSub } from '@/types/nostr-tools-extended' import type { Review } from '@/types/nostr' import { parseReviewFromEvent } from './nostrEventParsing' import { buildTagFilter } from './nostrTagSystem' const RELAY_URL = process.env.NEXT_PUBLIC_NOSTR_RELAY_URL ?? 'wss://relay.damus.io' export function getReviewsForArticle(articleId: string, timeoutMs: number = 5000): Promise { const pool = nostrService.getPool() if (!pool) { throw new Error('Pool not initialized') } const poolWithSub = pool as SimplePoolWithSub const tagFilter = buildTagFilter({ type: 'quote', articleId, }) const filterObj: { kinds: number[] '#quote'?: string[] '#article'?: string[] } = { kinds: Array.isArray(tagFilter.kinds) ? tagFilter.kinds as number[] : [1], } if (tagFilter['#quote']) { filterObj['#quote'] = tagFilter['#quote'] as string[] } if (tagFilter['#article']) { filterObj['#article'] = tagFilter['#article'] as string[] } const filters = [filterObj] return new Promise((resolve) => { const results: Review[] = [] const sub = poolWithSub.sub([RELAY_URL], filters) let finished = false const done = () => { if (finished) { return } finished = true sub.unsub() resolve(results) } sub.on('event', (event: Event) => { const parsed = parseReviewFromEvent(event) if (parsed) { results.push(parsed) } }) sub.on('eose', () => done()) setTimeout(() => done(), timeoutMs).unref?.() }) }