UNPKG

nostr-web-components

Version:

collection of web components that provide quick access to basic nostr things

72 lines (71 loc) 1.85 kB
import { SimplePool } from "nostr-tools/pool"; import { decode, npubEncode } from "nostr-tools/nip19"; import { queryProfile } from "nostr-tools/nip05"; import LRUCache from "mnemonist/lru-cache"; const pool = window.nostrSharedPool || new SimplePool(); const metadataCache = window.nostrMetadataCache || new LRUCache(2e3); function fetchMetadata(pubkey, hints) { let metadata = metadataCache.get(pubkey); if (metadata) return metadata; const relays = ["wss://purplepag.es", "wss://user.kindpag.es", "wss://relay.nos.social"]; relays.push(...hints); let promise = new Promise( (resolve, reject) => pool.subscribeManyEose( relays, [ { kinds: [0], authors: [pubkey] } ], { onevent(evt) { try { resolve(JSON.parse(evt.content)); } catch (err) { } }, onclose: reject } ) ); metadataCache.set(pubkey, promise); return promise; } async function inputToPubkey(input) { try { const { type, data } = decode(input); if (type === "nprofile") { return [data.pubkey, data.relays || []]; } else if (type === "npub") { return [data, []]; } } catch (err) { if (input.match(/[0-9a-f]{64}/)) { return [input, []]; } else if (input.match(".")) { let res = await queryProfile(input); if (!res) return [void 0]; return [res.pubkey, res.relays || []]; } } return [void 0]; } function getShortName(pubkey, metadata) { let name = metadata.name || metadata.display_name; if (name) return name; let npub = npubEncode(pubkey); return shortenNpub(npub); } function shortenNpub(npub) { return npub.substring(0, 7) + "\u2026" + npub.substring(57); } export { fetchMetadata, getShortName, inputToPubkey, shortenNpub };