Skip to content

Commit

Permalink
update to the latest nostr-tools.
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed May 5, 2024
1 parent 4ba6274 commit 833ffec
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 80 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,6 @@
"markdown-it": "^13.0.1",
"markdown-it-plain-text": "^0.3.0",
"marked": "^7.0.5",
"nostr-tools": "^1.15.0"
"nostr-tools": "^2.5.2"
}
}
2 changes: 2 additions & 0 deletions src/app.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>

<script src="https://unpkg.com/window.nostr.js/dist/window.nostr.js"></script>
</html>
5 changes: 3 additions & 2 deletions src/cards/Welcome.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<script lang="ts">
import { parsePlainText } from '$lib/articleParser';
import { onMount } from 'svelte';
import { nip19, type Event } from 'nostr-tools';
import * as nip19 from 'nostr-tools/nip19';
import type { Event } from 'nostr-tools/pure';
import { cachingSub, signer, userPreferredRelays, getA, wikiKind, account } from '$lib/nostr';
import type { Tab } from '$lib/types';
Expand Down Expand Up @@ -49,7 +50,7 @@
<button
on:click={doLogin}
type="submit"
class="inline-flex items-center space-x-2 px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 text-white"
class="inline-flex items-center space-x-2 px-3 py-2 border border-gray-300 text-sm font-medium rounded-md bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 text-white"
>Login</button
>
{/if}
Expand Down
2 changes: 1 addition & 1 deletion src/components/UserLabel.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang="ts">
import { onMount } from 'svelte';
import { nip19 } from 'nostr-tools';
import * as nip19 from 'nostr-tools/nip19';
import { getMetadata, type Metadata } from '$lib/nostr';
Expand Down
117 changes: 42 additions & 75 deletions src/lib/nostr.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
import { debounce } from 'debounce';
import {
relayInit,
utils,
type EventTemplate,
type Sub,
type Relay,
type Event,
type Filter
} from 'nostr-tools';
import { readable } from 'svelte/store';
import type { EventTemplate, Event } from 'nostr-tools/pure';
import type { Filter } from 'nostr-tools/filter';
import { SimplePool } from 'nostr-tools/pool';
import { normalizeURL } from 'nostr-tools/utils';
import type { Relay, Subscription } from 'nostr-tools/relay';

type CancelFunc = () => void;
type HookFunc = (events: Event[]) => void;
type KeyFunc = (event: Event) => string;
type Subscription = {
type CachingSubscription = {
cache: Map<string, Event>;
hook: HookFunc;
cancel: CancelFunc;
Expand All @@ -31,8 +27,8 @@ export const reactionKind = 7;
export const labelKind = 1985;
export const wikiKind = 30818;

const _conn: Record<string, Relay> = {};
const _subscriptions: Record<string, Subscription> = {};
const _pool = new SimplePool();
const _subscriptions: Record<string, CachingSubscription> = {};
const _metadataCache = new Map<string, Metadata>();
const _seenOn = new WeakMap<Event, Set<string>>();

Expand Down Expand Up @@ -77,15 +73,15 @@ export const fallback = [
'wss://relay.nostr.band'
];

export const relayLists = ['wss://purplepag.es'];
export const relayLists = ['wss://purplepag.es', 'wss://relay.nos.social'];

export const profiles = ['wss://relay.damus.io', 'wss://relay.primal.net', 'wss://purplepag.es'];

export const safeRelays = [
'wss://nostr.mom',
'wss://nostr.wine',
'wss://relay.snort.social',
'wss://atlas.nostr.land'
'wss://nostr.land'
];

export const userPreferredRelays = readable(safeRelays, (set) => {
Expand All @@ -98,21 +94,6 @@ export const getA: KeyFunc = (event: Event) => {
return `${event.kind}:${event.pubkey}:${dTag}`;
};

async function ensureRelay(url: string): Promise<Relay> {
const nm = utils.normalizeURL(url);

if (!_conn[nm]) {
_conn[nm] = relayInit(nm, {
getTimeout: 3000,
listTimeout: 5000
});
}

const relay = _conn[nm];
await relay.connect();
return relay;
}

export function getRelaysForEvent(event: Event): Iterable<string> {
return _seenOn.get(event)?.keys() || [];
}
Expand All @@ -136,7 +117,7 @@ export async function broadcast(
await Promise.all(
relays.map(async (url) => {
try {
const r = await ensureRelay(url);
const r = await _pool.ensureRelay(url);
await r.publish(event);
successes.push(url);
} catch (err) {
Expand All @@ -159,11 +140,11 @@ export function cachingSub(
): CancelFunc {
const alreadyHaveEvent =
filter.kinds?.[0] === wikiKind || filter.ids
? (id: string, relay: string) => {
? (relay: Relay, id: string) => {
const event = cachedArticles.get(id);
if (event) {
// we already have this event, so no need to parse it again
cacheSeenOn(event, relay);
cacheSeenOn(event, relay.url);

// if we didn't have this in the cache yet we add it then trigger the hook
const k = keyfn(event);
Expand Down Expand Up @@ -191,10 +172,10 @@ export function cachingSub(
return _subscriptions[name].cancel;
}

const subs: Sub[] = [];
const subs: Subscription[] = [];
const cancel = () => {
subs.forEach((s) => {
s.unsub();
s.close();
});
delete _subscriptions[name];
};
Expand All @@ -203,25 +184,24 @@ export function cachingSub(
_subscriptions[name] = { cache, hook, cancel };

relays.forEach(async (url) => {
const r = await ensureRelay(url);
const subscription = r.sub([filter], {
const r = await _pool.ensureRelay(url);
const subscription = r.prepareSubscription([filter], {
id: name,
alreadyHaveEvent,
skipVerification: true
});
subs.push(subscription);

subscription.on('event', (event) => {
_subscriptions[name]?.cache?.set?.(keyfn(event), event);
if (event.kind === wikiKind) {
if (!cachedArticles.has(event.id)) {
// only set if not already set otherwise we lose the seenOn stuff
cachedArticles.set(event.id, event);
receivedEvent: alreadyHaveEvent,
onevent(event) {
_subscriptions[name]?.cache?.set?.(keyfn(event), event);
if (event.kind === wikiKind) {
if (!cachedArticles.has(event.id)) {
// only set if not already set otherwise we lose the seenOn stuff
cachedArticles.set(event.id, event);
}
cacheSeenOn(event, url);
}
cacheSeenOn(event, url);
invokeHook();
}
invokeHook();
});
subscription.fire();
subs.push(subscription);
});

return cancel;
Expand All @@ -230,37 +210,24 @@ export function cachingSub(
function cacheSeenOn(event: Event, relay: string) {
const relays = _seenOn.get(event) || new Set();
_seenOn.set(event, relays);
relays.add(utils.normalizeURL(relay));
relays.add(normalizeURL(relay));
}

export async function getMetadata(pubkey: string): Promise<Metadata> {
let metadata = _metadataCache.get(pubkey);
const metadata = _metadataCache.get(pubkey);
if (metadata) return metadata;

// TODO: use dexie as a second-level cache

metadata = await new Promise<Metadata>((resolve) => {
let ongoing = profiles.length;
profiles.forEach(async (url) => {
const r = await ensureRelay(url);
const event = await r.get({ kinds: [0], authors: [pubkey] });
if (event) {
try {
const metadata = JSON.parse(event.content);
metadata.pubkey = pubkey;
resolve(metadata);
} catch (err) {
ongoing--;
if (ongoing === 0) {
resolve({ pubkey, nip05valid: false });
}
}
}
});
});

const event = await _pool.get(profiles, { kinds: [0], authors: [pubkey] });
try {
const metadata = JSON.parse(event!.content);
metadata.pubkey = pubkey;
_metadataCache.set(pubkey, metadata);
return metadata;
} catch (err) {
const metadata = { pubkey, nip05valid: false };
_metadataCache.set(pubkey, metadata);
return metadata;
}
// TODO: validate nip05

_metadataCache.set(pubkey, metadata);
return metadata;
}
4 changes: 3 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
"strict": true,
"module": "esnext",
"moduleResolution": "bundler"
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
//
Expand Down

0 comments on commit 833ffec

Please sign in to comment.