import type { Event, Filter } from 'nostr-tools' import { SimplePool } from 'nostr-tools' import { getPrimaryRelaySync } from './config' import { createSubscription } from '@/types/nostr-tools-extended' /** * Subscribe to events with timeout * Supports both sync and async parsers */ export function subscribeWithTimeout( pool: SimplePool, filters: Filter[], parser: (event: Event) => T | null | Promise, timeout: number = 5000 ): Promise { return new Promise((resolve) => { const resolved = { value: false } const relayUrl = getPrimaryRelaySync() const sub = createSubscription(pool, [relayUrl], filters) let timeoutId: NodeJS.Timeout | null = null const cleanup = () => { if (timeoutId) { clearTimeout(timeoutId) } sub.unsub() } const resolveOnce = (value: T | null) => { if (resolved.value) { return } resolved.value = true cleanup() resolve(value) } sub.on('event', async (event: Event) => { const result = await parser(event) resolveOnce(result) }) sub.on('eose', () => resolveOnce(null)) timeoutId = setTimeout(() => resolveOnce(null), timeout) }) }