@nostrify/nostrify 0.48.2 → 0.48.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +2 -3
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +8 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/dist/BunkerURI.ts +0 -58
- package/dist/NBrowserSigner.ts +0 -100
- package/dist/NCache.ts +0 -73
- package/dist/NConnectSigner.ts +0 -188
- package/dist/NIP05.ts +0 -51
- package/dist/NIP50.ts +0 -24
- package/dist/NIP98.ts +0 -111
- package/dist/NIP98Client.ts +0 -36
- package/dist/NKinds.ts +0 -26
- package/dist/NPool.ts +0 -243
- package/dist/NRelay1.ts +0 -447
- package/dist/NSchema.ts +0 -291
- package/dist/NSecSigner.ts +0 -62
- package/dist/NSet.ts +0 -210
- package/dist/RelayError.ts +0 -22
- package/dist/ln/LNURL.ts +0 -146
- package/dist/ln/mod.ts +0 -4
- package/dist/ln/types/LNURLCallback.ts +0 -7
- package/dist/ln/types/LNURLDetails.ts +0 -19
- package/dist/mod.ts +0 -17
- package/dist/test/ErrorRelay.ts +0 -52
- package/dist/test/MockRelay.ts +0 -92
- package/dist/test/TestRelayServer.ts +0 -185
- package/dist/test/mod.ts +0 -28
- package/dist/uploaders/BlossomUploader.ts +0 -100
- package/dist/uploaders/NostrBuildUploader.ts +0 -89
- package/dist/uploaders/mod.ts +0 -2
- package/dist/utils/CircularSet.ts +0 -36
- package/dist/utils/Machina.ts +0 -66
- package/dist/utils/N64.ts +0 -23
- package/dist/utils/mod.ts +0 -2
package/dist/NPool.ts
DELETED
|
@@ -1,243 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
NostrEvent,
|
|
3
|
-
NostrFilter,
|
|
4
|
-
NostrRelayCLOSED,
|
|
5
|
-
NostrRelayEOSE,
|
|
6
|
-
NostrRelayEVENT,
|
|
7
|
-
NRelay,
|
|
8
|
-
} from '@nostrify/types';
|
|
9
|
-
import { getFilterLimit } from 'nostr-tools';
|
|
10
|
-
|
|
11
|
-
import { CircularSet } from './utils/CircularSet.ts';
|
|
12
|
-
import { Machina } from './utils/Machina.ts';
|
|
13
|
-
import { NSet } from './NSet.ts';
|
|
14
|
-
|
|
15
|
-
export interface NPoolOpts<T extends NRelay> {
|
|
16
|
-
/** Creates an `NRelay` instance for the given URL. */
|
|
17
|
-
open(url: string): T;
|
|
18
|
-
/** Determines the relays to use for making `REQ`s to the given filters. To support the Outbox model, it should analyze the `authors` field of the filters. */
|
|
19
|
-
reqRouter(
|
|
20
|
-
filters: NostrFilter[],
|
|
21
|
-
):
|
|
22
|
-
| ReadonlyMap<string, NostrFilter[]>
|
|
23
|
-
| Promise<ReadonlyMap<string, NostrFilter[]>>;
|
|
24
|
-
/** Determines the relays to use for publishing the given event. To support the Outbox model, it should analyze the `pubkey` field of the event. */
|
|
25
|
-
eventRouter(event: NostrEvent): string[] | Promise<string[]>;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* The `NPool` class is a `NRelay` implementation for connecting to multiple relays.
|
|
30
|
-
*
|
|
31
|
-
* ```ts
|
|
32
|
-
* const pool = new NPool({
|
|
33
|
-
* open: (url) => new NRelay1(url),
|
|
34
|
-
* reqRouter: async (filters) => new Map([
|
|
35
|
-
* ['wss://relay1.mostr.pub', filters],
|
|
36
|
-
* ['wss://relay2.mostr.pub', filters],
|
|
37
|
-
* ]),
|
|
38
|
-
* eventRouter: async (event) => ['wss://relay1.mostr.pub', 'wss://relay2.mostr.pub'],
|
|
39
|
-
* });
|
|
40
|
-
*
|
|
41
|
-
* // Now you can use the pool like a regular relay.
|
|
42
|
-
* for await (const msg of pool.req([{ kinds: [1] }])) {
|
|
43
|
-
* if (msg[0] === 'EVENT') console.log(msg[2]);
|
|
44
|
-
* if (msg[0] === 'EOSE') break;
|
|
45
|
-
* }
|
|
46
|
-
* ```
|
|
47
|
-
*
|
|
48
|
-
* This class is designed with the Outbox model in mind.
|
|
49
|
-
* Instead of passing relay URLs into each method, you pass functions into the contructor that statically-analyze filters and events to determine which relays to use for requesting and publishing events.
|
|
50
|
-
* If a relay wasn't already connected, it will be opened automatically.
|
|
51
|
-
* Defining `open` will also let you use any relay implementation, such as `NRelay1`.
|
|
52
|
-
*
|
|
53
|
-
* Note that `pool.req` may stream duplicate events, while `pool.query` will correctly process replaceable events and deletions within the event set before returning them.
|
|
54
|
-
*
|
|
55
|
-
* `pool.req` will only emit an `EOSE` when all relays in its set have emitted an `EOSE`, and likewise for `CLOSED`.
|
|
56
|
-
*/
|
|
57
|
-
export class NPool<T extends NRelay = NRelay> implements NRelay {
|
|
58
|
-
private _relays = new Map<string, T>();
|
|
59
|
-
private opts: NPoolOpts<T>;
|
|
60
|
-
|
|
61
|
-
constructor(opts: NPoolOpts<T>) {
|
|
62
|
-
this.opts = opts;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/** Get or create a relay instance for the given URL. */
|
|
66
|
-
public relay(url: string): T {
|
|
67
|
-
const relay = this._relays.get(url);
|
|
68
|
-
|
|
69
|
-
if (relay) {
|
|
70
|
-
return relay;
|
|
71
|
-
} else {
|
|
72
|
-
const relay = this.opts.open(url);
|
|
73
|
-
this._relays.set(url, relay);
|
|
74
|
-
return relay;
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** Returns a new pool instance that uses the given relays. Connections are shared with the original pool. */
|
|
79
|
-
public group(urls: string[]): NPool<T> {
|
|
80
|
-
return new NPool({
|
|
81
|
-
open: (url) => this.relay(url),
|
|
82
|
-
reqRouter: (filters) => new Map(urls.map((url) => [url, filters])),
|
|
83
|
-
eventRouter: () => urls,
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
public get relays(): ReadonlyMap<string, T> {
|
|
88
|
-
return this._relays;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Sends a `REQ` to relays based on the configured `reqRouter`.
|
|
93
|
-
*
|
|
94
|
-
* `EVENT` messages from the selected relays are yielded.
|
|
95
|
-
* `EOSE` and `CLOSE` messages are only yielded when all relays have emitted them.
|
|
96
|
-
*
|
|
97
|
-
* Deduplication of `EVENT` messages is attempted, so that each event is only yielded once.
|
|
98
|
-
* A circular set of 1000 is used to track seen event IDs, so it's possible that very
|
|
99
|
-
* long-running subscriptions (with over 1000 results) may yield duplicate events.
|
|
100
|
-
*/
|
|
101
|
-
async *req(
|
|
102
|
-
filters: NostrFilter[],
|
|
103
|
-
opts?: { signal?: AbortSignal; relays?: string[] },
|
|
104
|
-
): AsyncIterable<NostrRelayEVENT | NostrRelayEOSE | NostrRelayCLOSED> {
|
|
105
|
-
const controller = new AbortController();
|
|
106
|
-
const signal = opts?.signal ? AbortSignal.any([opts.signal, controller.signal]) : controller.signal;
|
|
107
|
-
|
|
108
|
-
const routes = opts?.relays
|
|
109
|
-
? new Map(opts.relays.map((url) => [url, filters]))
|
|
110
|
-
: await this.opts.reqRouter(filters);
|
|
111
|
-
|
|
112
|
-
if (routes.size < 1) {
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
const machina = new Machina<
|
|
117
|
-
NostrRelayEVENT | NostrRelayEOSE | NostrRelayCLOSED
|
|
118
|
-
>(signal);
|
|
119
|
-
|
|
120
|
-
const eoses = new Set<string>();
|
|
121
|
-
const closes = new Set<string>();
|
|
122
|
-
const events = new CircularSet<string>(1000);
|
|
123
|
-
|
|
124
|
-
const relayPromises: Promise<void>[] = [];
|
|
125
|
-
|
|
126
|
-
for (const [url, filters] of routes.entries()) {
|
|
127
|
-
const relay = this.relay(url);
|
|
128
|
-
const relayPromise = (async () => {
|
|
129
|
-
try {
|
|
130
|
-
for await (const msg of relay.req(filters, { signal })) {
|
|
131
|
-
if (msg[0] === 'EOSE') {
|
|
132
|
-
eoses.add(url);
|
|
133
|
-
if (eoses.size === routes.size) {
|
|
134
|
-
machina.push(msg);
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
if (msg[0] === 'CLOSED') {
|
|
138
|
-
closes.add(url);
|
|
139
|
-
if (closes.size === routes.size) {
|
|
140
|
-
machina.push(msg);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
if (msg[0] === 'EVENT') {
|
|
144
|
-
const [, , event] = msg;
|
|
145
|
-
if (!events.has(event.id)) {
|
|
146
|
-
events.add(event.id);
|
|
147
|
-
machina.push(msg);
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
} catch {
|
|
152
|
-
// Handle errors silently
|
|
153
|
-
}
|
|
154
|
-
})();
|
|
155
|
-
relayPromises.push(relayPromise);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
try {
|
|
159
|
-
for await (const msg of machina) {
|
|
160
|
-
yield msg;
|
|
161
|
-
}
|
|
162
|
-
} finally {
|
|
163
|
-
controller.abort();
|
|
164
|
-
// Wait for all relay promises to complete to prevent hanging promises
|
|
165
|
-
await Promise.allSettled(relayPromises);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* Events are sent to relays according to the `eventRouter`.
|
|
171
|
-
* Returns a fulfilled promise if ANY relay accepted the event,
|
|
172
|
-
* or a rejected promise if ALL relays rejected or failed to publish the event.
|
|
173
|
-
*/
|
|
174
|
-
async event(
|
|
175
|
-
event: NostrEvent,
|
|
176
|
-
opts?: { signal?: AbortSignal; relays?: string[] },
|
|
177
|
-
): Promise<void> {
|
|
178
|
-
const relayUrls = opts?.relays ?? await this.opts.eventRouter(event);
|
|
179
|
-
|
|
180
|
-
if (!relayUrls.length) {
|
|
181
|
-
return;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// @ts-ignore Promise.any exists for sure
|
|
185
|
-
await Promise.any(
|
|
186
|
-
relayUrls.map((url) => this.relay(url).event(event, opts)),
|
|
187
|
-
);
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/**
|
|
191
|
-
* This method calls `.req` internally and then post-processes the results.
|
|
192
|
-
* Please read the definition of `.req`.
|
|
193
|
-
*
|
|
194
|
-
* - The strategy is to seek regular events quickly, and to wait to find the latest versions of replaceable events.
|
|
195
|
-
* - Filters for replaceable events will wait for all relays to `EOSE` (or `CLOSE`, or for the signal to be aborted) to ensure the latest event versions are retrieved.
|
|
196
|
-
* - Filters for regular events will stop as soon as the filters are fulfilled.
|
|
197
|
-
* - Events are deduplicated, sorted, and only the latest version of replaceable events is kept.
|
|
198
|
-
* - If the signal is aborted, this method will return partial results instead of throwing.
|
|
199
|
-
*
|
|
200
|
-
* To implement a custom strategy, call `.req` directly.
|
|
201
|
-
*/
|
|
202
|
-
async query(
|
|
203
|
-
filters: NostrFilter[],
|
|
204
|
-
opts?: { signal?: AbortSignal; relays?: string[] },
|
|
205
|
-
): Promise<NostrEvent[]> {
|
|
206
|
-
const map = new Map<string, NostrEvent>();
|
|
207
|
-
const events = new NSet(map);
|
|
208
|
-
|
|
209
|
-
const limit = filters.reduce(
|
|
210
|
-
(result, filter) => result + getFilterLimit(filter),
|
|
211
|
-
0,
|
|
212
|
-
);
|
|
213
|
-
if (limit === 0) return [];
|
|
214
|
-
|
|
215
|
-
try {
|
|
216
|
-
for await (const msg of this.req(filters, opts)) {
|
|
217
|
-
if (msg[0] === 'EOSE') break;
|
|
218
|
-
if (msg[0] === 'EVENT') events.add(msg[2]);
|
|
219
|
-
if (msg[0] === 'CLOSED') break;
|
|
220
|
-
}
|
|
221
|
-
} catch {
|
|
222
|
-
// Skip errors, return partial results.
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
// Don't sort results of search filters.
|
|
226
|
-
if (filters.some((filter) => typeof filter.search === 'string')) {
|
|
227
|
-
return [...map.values()];
|
|
228
|
-
} else {
|
|
229
|
-
return [...events];
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
/** Close all the relays in the pool. */
|
|
234
|
-
async close(): Promise<void> {
|
|
235
|
-
await Promise.all(
|
|
236
|
-
[...this._relays.values()].map((relay) => relay.close()),
|
|
237
|
-
);
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
async [Symbol.asyncDispose](): Promise<void> {
|
|
241
|
-
await this.close();
|
|
242
|
-
}
|
|
243
|
-
}
|
package/dist/NRelay1.ts
DELETED
|
@@ -1,447 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
NostrClientMsg,
|
|
3
|
-
NostrClientREQ,
|
|
4
|
-
NostrEvent,
|
|
5
|
-
NostrFilter,
|
|
6
|
-
NostrRelayCLOSED,
|
|
7
|
-
NostrRelayCOUNT,
|
|
8
|
-
NostrRelayEOSE,
|
|
9
|
-
NostrRelayEVENT,
|
|
10
|
-
NostrRelayMsg,
|
|
11
|
-
NostrRelayNOTICE,
|
|
12
|
-
NostrRelayOK,
|
|
13
|
-
NRelay,
|
|
14
|
-
} from '@nostrify/types';
|
|
15
|
-
import { getFilterLimit, matchFilters, verifyEvent as _verifyEvent } from 'nostr-tools';
|
|
16
|
-
import { ArrayQueue, ExponentialBackoff, Websocket, WebsocketBuilder, WebsocketEvent } from 'websocket-ts';
|
|
17
|
-
import type { Backoff } from 'websocket-ts';
|
|
18
|
-
|
|
19
|
-
import { Machina } from './utils/Machina.ts';
|
|
20
|
-
import { NSchema as n } from './NSchema.ts';
|
|
21
|
-
import { NSet } from './NSet.ts';
|
|
22
|
-
|
|
23
|
-
/** Map of EventEmitter events. */
|
|
24
|
-
type EventMap = {
|
|
25
|
-
[k: `ok:${string}`]: NostrRelayOK;
|
|
26
|
-
[k: `sub:${string}`]: NostrRelayEVENT | NostrRelayEOSE | NostrRelayCLOSED;
|
|
27
|
-
[k: `count:${string}`]: NostrRelayCOUNT | NostrRelayCLOSED;
|
|
28
|
-
notice: NostrRelayNOTICE;
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
/** Options used for constructing an `NRelay1` instance. */
|
|
32
|
-
export interface NRelay1Opts {
|
|
33
|
-
/** Respond to `AUTH` challenges by producing a signed kind `22242` event. */
|
|
34
|
-
auth?(challenge: string): Promise<NostrEvent>;
|
|
35
|
-
/** Configure reconnection strategy, or set to `false` to disable. Default: `new ExponentialBackoff(1000)`. */
|
|
36
|
-
backoff?: Backoff | false;
|
|
37
|
-
/** How long to wait (in milliseconds) for the caller to create a subscription before closing the connection. Set to `false` to disable. Default: `30_000`. */
|
|
38
|
-
idleTimeout?: number | false;
|
|
39
|
-
/** Ensure the event is valid before returning it. Default: `nostrTools.verifyEvent`. */
|
|
40
|
-
verifyEvent?(event: NostrEvent): boolean;
|
|
41
|
-
/** Logger callback. */
|
|
42
|
-
log?(log: NRelay1Log): void;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export interface NRelay1Log {
|
|
46
|
-
level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'critical';
|
|
47
|
-
ns: string;
|
|
48
|
-
[k: string]: JsonValue | undefined | { toJSON(): JsonValue } | Error;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Single relay connection over WebSocket. */
|
|
52
|
-
export class NRelay1 implements NRelay {
|
|
53
|
-
socket: Websocket;
|
|
54
|
-
|
|
55
|
-
private subs = new Map<string, NostrClientREQ>();
|
|
56
|
-
private closedByUser = false;
|
|
57
|
-
private idleTimer?: ReturnType<typeof setTimeout>;
|
|
58
|
-
private controller = new AbortController();
|
|
59
|
-
private url: string;
|
|
60
|
-
private opts: NRelay1Opts;
|
|
61
|
-
|
|
62
|
-
private ee = new EventTarget();
|
|
63
|
-
|
|
64
|
-
get subscriptions(): readonly NostrClientREQ[] {
|
|
65
|
-
return [...this.subs.values()];
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
private log(log: NRelay1Log): void {
|
|
69
|
-
this.opts.log?.({ ...log, url: this.url });
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
constructor(url: string, opts: NRelay1Opts = {}) {
|
|
73
|
-
this.url = url;
|
|
74
|
-
this.opts = opts;
|
|
75
|
-
this.socket = this.createSocket();
|
|
76
|
-
this.maybeStartIdleTimer();
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** Create (and open) a WebSocket connection with automatic reconnect. */
|
|
80
|
-
private createSocket(): Websocket {
|
|
81
|
-
const { backoff = new ExponentialBackoff(1000) } = this.opts;
|
|
82
|
-
|
|
83
|
-
return new WebsocketBuilder(this.url)
|
|
84
|
-
.withBuffer(new ArrayQueue())
|
|
85
|
-
.withBackoff(backoff === false ? undefined : backoff)
|
|
86
|
-
.onOpen((socket) => {
|
|
87
|
-
this.log({
|
|
88
|
-
level: 'debug',
|
|
89
|
-
ns: 'relay.ws.state',
|
|
90
|
-
state: 'open',
|
|
91
|
-
readyState: socket.readyState,
|
|
92
|
-
});
|
|
93
|
-
for (const req of this.subs.values()) {
|
|
94
|
-
this.send(req);
|
|
95
|
-
}
|
|
96
|
-
})
|
|
97
|
-
.onClose((socket) => {
|
|
98
|
-
this.log({
|
|
99
|
-
level: 'debug',
|
|
100
|
-
ns: 'relay.ws.state',
|
|
101
|
-
state: 'close',
|
|
102
|
-
readyState: socket.readyState,
|
|
103
|
-
});
|
|
104
|
-
// If the connection closes on its own and there are no active subscriptions, let it stay closed.
|
|
105
|
-
if (!this.subs.size) {
|
|
106
|
-
this.socket.close();
|
|
107
|
-
}
|
|
108
|
-
})
|
|
109
|
-
.onReconnect((socket) => {
|
|
110
|
-
this.log({
|
|
111
|
-
level: 'debug',
|
|
112
|
-
ns: 'relay.ws.state',
|
|
113
|
-
state: 'reconnect',
|
|
114
|
-
readyState: socket.readyState,
|
|
115
|
-
});
|
|
116
|
-
})
|
|
117
|
-
.onRetry((socket, e) => {
|
|
118
|
-
this.log({
|
|
119
|
-
level: 'warn',
|
|
120
|
-
ns: 'relay.ws.retry',
|
|
121
|
-
readyState: socket.readyState,
|
|
122
|
-
backoff: e.detail.backoff,
|
|
123
|
-
});
|
|
124
|
-
})
|
|
125
|
-
.onError((socket) => {
|
|
126
|
-
this.log({
|
|
127
|
-
level: 'error',
|
|
128
|
-
ns: 'relay.ws.error',
|
|
129
|
-
readyState: socket.readyState,
|
|
130
|
-
});
|
|
131
|
-
})
|
|
132
|
-
.onMessage((_socket, e) => {
|
|
133
|
-
if (typeof e.data !== 'string') {
|
|
134
|
-
this.close();
|
|
135
|
-
return;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const result = n.json().pipe(n.relayMsg()).safeParse(e.data);
|
|
139
|
-
|
|
140
|
-
if (result.success) {
|
|
141
|
-
this.log({
|
|
142
|
-
level: 'trace',
|
|
143
|
-
ns: 'relay.ws.message',
|
|
144
|
-
data: result.data as JsonValue,
|
|
145
|
-
});
|
|
146
|
-
this.receive(result.data);
|
|
147
|
-
} else {
|
|
148
|
-
this.log({
|
|
149
|
-
level: 'warn',
|
|
150
|
-
ns: 'relay.ws.message',
|
|
151
|
-
error: result.error,
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
})
|
|
155
|
-
.build();
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** Handle a NIP-01 relay message. */
|
|
159
|
-
protected receive(msg: NostrRelayMsg): void {
|
|
160
|
-
const { auth, verifyEvent = _verifyEvent } = this.opts;
|
|
161
|
-
|
|
162
|
-
switch (msg[0]) {
|
|
163
|
-
case 'EVENT':
|
|
164
|
-
if (!verifyEvent(msg[2])) break;
|
|
165
|
-
this.ee.dispatchEvent(
|
|
166
|
-
new CustomEvent(`sub:${msg[1]}`, { detail: msg }),
|
|
167
|
-
);
|
|
168
|
-
break;
|
|
169
|
-
case 'EOSE':
|
|
170
|
-
this.ee.dispatchEvent(
|
|
171
|
-
new CustomEvent(`sub:${msg[1]}`, { detail: msg }),
|
|
172
|
-
);
|
|
173
|
-
break;
|
|
174
|
-
case 'CLOSED':
|
|
175
|
-
this.subs.delete(msg[1]);
|
|
176
|
-
this.maybeStartIdleTimer();
|
|
177
|
-
this.ee.dispatchEvent(
|
|
178
|
-
new CustomEvent(`sub:${msg[1]}`, { detail: msg }),
|
|
179
|
-
);
|
|
180
|
-
this.ee.dispatchEvent(
|
|
181
|
-
new CustomEvent(`count:${msg[1]}`, { detail: msg }),
|
|
182
|
-
);
|
|
183
|
-
break;
|
|
184
|
-
case 'OK':
|
|
185
|
-
this.ee.dispatchEvent(new CustomEvent(`ok:${msg[1]}`, { detail: msg }));
|
|
186
|
-
break;
|
|
187
|
-
case 'NOTICE':
|
|
188
|
-
this.ee.dispatchEvent(new CustomEvent('notice', { detail: msg }));
|
|
189
|
-
break;
|
|
190
|
-
case 'COUNT':
|
|
191
|
-
this.ee.dispatchEvent(
|
|
192
|
-
new CustomEvent(`count:${msg[1]}`, { detail: msg }),
|
|
193
|
-
);
|
|
194
|
-
break;
|
|
195
|
-
case 'AUTH':
|
|
196
|
-
auth?.(msg[1]).then((event) => this.send(['AUTH', event])).catch(
|
|
197
|
-
() => {},
|
|
198
|
-
);
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/** Send a NIP-01 client message to the relay. */
|
|
203
|
-
protected send(msg: NostrClientMsg): void {
|
|
204
|
-
this.log({ level: 'trace', ns: 'relay.ws.send', data: msg as JsonValue });
|
|
205
|
-
this.wake();
|
|
206
|
-
|
|
207
|
-
switch (msg[0]) {
|
|
208
|
-
case 'REQ':
|
|
209
|
-
this.subs.set(msg[1], msg);
|
|
210
|
-
break;
|
|
211
|
-
case 'CLOSE':
|
|
212
|
-
this.subs.delete(msg[1]);
|
|
213
|
-
this.maybeStartIdleTimer();
|
|
214
|
-
break;
|
|
215
|
-
case 'EVENT':
|
|
216
|
-
case 'COUNT':
|
|
217
|
-
return this.socket.send(JSON.stringify(msg));
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
if (this.socket.readyState === WebSocket.OPEN) {
|
|
221
|
-
this.socket.send(JSON.stringify(msg));
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
async *req(
|
|
226
|
-
filters: NostrFilter[],
|
|
227
|
-
opts: { signal?: AbortSignal } = {},
|
|
228
|
-
): AsyncGenerator<NostrRelayEVENT | NostrRelayEOSE | NostrRelayCLOSED> {
|
|
229
|
-
const { signal } = opts;
|
|
230
|
-
const subscriptionId = crypto.randomUUID();
|
|
231
|
-
|
|
232
|
-
const msgs = this.on(`sub:${subscriptionId}`, signal);
|
|
233
|
-
const req: NostrClientREQ = ['REQ', subscriptionId, ...filters];
|
|
234
|
-
|
|
235
|
-
this.send(req);
|
|
236
|
-
|
|
237
|
-
try {
|
|
238
|
-
for await (const msg of msgs) {
|
|
239
|
-
if (msg[0] === 'EOSE') yield msg;
|
|
240
|
-
if (msg[0] === 'CLOSED') break;
|
|
241
|
-
if (msg[0] === 'EVENT') {
|
|
242
|
-
if (matchFilters(filters, msg[2])) {
|
|
243
|
-
yield msg;
|
|
244
|
-
} else {
|
|
245
|
-
continue;
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
} finally {
|
|
250
|
-
this.send(['CLOSE', subscriptionId]);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
async query(
|
|
255
|
-
filters: NostrFilter[],
|
|
256
|
-
opts?: { signal?: AbortSignal },
|
|
257
|
-
): Promise<NostrEvent[]> {
|
|
258
|
-
const events = new NSet();
|
|
259
|
-
|
|
260
|
-
const limit = filters.reduce(
|
|
261
|
-
(result, filter) => result + getFilterLimit(filter),
|
|
262
|
-
0,
|
|
263
|
-
);
|
|
264
|
-
if (limit === 0) return [];
|
|
265
|
-
|
|
266
|
-
for await (const msg of this.req(filters, opts)) {
|
|
267
|
-
if (msg[0] === 'EOSE') break;
|
|
268
|
-
if (msg[0] === 'EVENT') events.add(msg[2]);
|
|
269
|
-
if (msg[0] === 'CLOSED') throw new Error('Subscription closed');
|
|
270
|
-
|
|
271
|
-
if (events.size >= limit) {
|
|
272
|
-
break;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
return [...events];
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
async event(
|
|
280
|
-
event: NostrEvent,
|
|
281
|
-
opts?: { signal?: AbortSignal },
|
|
282
|
-
): Promise<void> {
|
|
283
|
-
const result = this.once(`ok:${event.id}`, opts?.signal);
|
|
284
|
-
|
|
285
|
-
try {
|
|
286
|
-
this.send(['EVENT', event]);
|
|
287
|
-
} catch (e) {
|
|
288
|
-
result.catch(() => {});
|
|
289
|
-
throw e;
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
const [, , ok, reason] = await result;
|
|
293
|
-
|
|
294
|
-
if (!ok) {
|
|
295
|
-
throw new Error(reason);
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
async count(
|
|
300
|
-
filters: NostrFilter[],
|
|
301
|
-
opts?: { signal?: AbortSignal },
|
|
302
|
-
): Promise<{ count: number; approximate?: boolean }> {
|
|
303
|
-
const subscriptionId = crypto.randomUUID();
|
|
304
|
-
const result = this.once(`count:${subscriptionId}`, opts?.signal);
|
|
305
|
-
|
|
306
|
-
try {
|
|
307
|
-
this.send(['COUNT', subscriptionId, ...filters]);
|
|
308
|
-
} catch (e) {
|
|
309
|
-
result.catch(() => {});
|
|
310
|
-
throw e;
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
const msg = await result;
|
|
314
|
-
|
|
315
|
-
switch (msg[0]) {
|
|
316
|
-
case 'CLOSED':
|
|
317
|
-
throw new Error('Subscription closed');
|
|
318
|
-
case 'COUNT': {
|
|
319
|
-
const [, , count] = msg;
|
|
320
|
-
return count;
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
throw new Error('Count ended -- this should never happen');
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
/** Get a stream of EE events. */
|
|
328
|
-
private async *on<K extends keyof EventMap>(
|
|
329
|
-
key: K,
|
|
330
|
-
signal?: AbortSignal,
|
|
331
|
-
): AsyncIterable<EventMap[K]> {
|
|
332
|
-
const _signal = signal ? AbortSignal.any([this.controller.signal, signal]) : this.controller.signal;
|
|
333
|
-
|
|
334
|
-
if (_signal.aborted) throw this.abortError();
|
|
335
|
-
|
|
336
|
-
const machina = new Machina<EventMap[K]>(_signal);
|
|
337
|
-
const onMsg = (e: Event) => machina.push((e as CustomEvent<EventMap[K]>).detail);
|
|
338
|
-
|
|
339
|
-
this.ee.addEventListener(key, onMsg);
|
|
340
|
-
|
|
341
|
-
try {
|
|
342
|
-
for await (const msg of machina) {
|
|
343
|
-
yield msg;
|
|
344
|
-
}
|
|
345
|
-
} finally {
|
|
346
|
-
this.ee.removeEventListener(key, onMsg);
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
/** Wait for a single EE event. */
|
|
351
|
-
private async once<K extends keyof EventMap>(
|
|
352
|
-
key: K,
|
|
353
|
-
signal?: AbortSignal,
|
|
354
|
-
): Promise<EventMap[K]> {
|
|
355
|
-
for await (const msg of this.on(key, signal)) {
|
|
356
|
-
return msg;
|
|
357
|
-
}
|
|
358
|
-
throw new Error('Unreachable');
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
protected abortError(): DOMException {
|
|
362
|
-
return new DOMException('The signal has been aborted', 'AbortError');
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
/** Start the idle time if applicable. */
|
|
366
|
-
private maybeStartIdleTimer(): void {
|
|
367
|
-
const { idleTimeout = 30_000 } = this.opts;
|
|
368
|
-
|
|
369
|
-
// If the idle timeout is disabled, do nothing.
|
|
370
|
-
if (idleTimeout === false) return;
|
|
371
|
-
// If a timer is already running, let it continue without disruption.
|
|
372
|
-
if (this.idleTimer) return;
|
|
373
|
-
// If there are still subscriptions, the connection is not "idle".
|
|
374
|
-
if (this.subs.size) return;
|
|
375
|
-
// If the connection was manually closed, there's no need to start a timer.
|
|
376
|
-
if (this.closedByUser) return;
|
|
377
|
-
|
|
378
|
-
this.log({
|
|
379
|
-
level: 'debug',
|
|
380
|
-
ns: 'relay.idletimer',
|
|
381
|
-
state: 'running',
|
|
382
|
-
timeout: idleTimeout,
|
|
383
|
-
});
|
|
384
|
-
this.idleTimer = setTimeout(() => {
|
|
385
|
-
this.log({
|
|
386
|
-
level: 'debug',
|
|
387
|
-
ns: 'relay.idletimer',
|
|
388
|
-
state: 'aborted',
|
|
389
|
-
timeout: idleTimeout,
|
|
390
|
-
});
|
|
391
|
-
this.socket.close();
|
|
392
|
-
}, idleTimeout);
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
/** Stop the idle timer. */
|
|
396
|
-
private stopIdleTimer(): void {
|
|
397
|
-
this.log({ level: 'debug', ns: 'relay.idletimer', state: 'stopped' });
|
|
398
|
-
clearTimeout(this.idleTimer);
|
|
399
|
-
this.idleTimer = undefined;
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/** Make a new WebSocket, but only if it was closed by an idle timeout. */
|
|
403
|
-
private wake(): void {
|
|
404
|
-
this.stopIdleTimer();
|
|
405
|
-
|
|
406
|
-
if (!this.closedByUser && this.socket.closedByUser) {
|
|
407
|
-
this.log({ level: 'debug', ns: 'relay.wake', state: 'awoken' });
|
|
408
|
-
this.socket = this.createSocket();
|
|
409
|
-
} else if (this.closedByUser || this.socket.closedByUser) {
|
|
410
|
-
this.log({ level: 'debug', ns: 'relay.wake', state: 'closed' });
|
|
411
|
-
} else {
|
|
412
|
-
this.log({ level: 'debug', ns: 'relay.wake', state: 'awake' });
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
/**
|
|
417
|
-
* Close the relay connection and prevent it from reconnecting.
|
|
418
|
-
* After this you should dispose of the `NRelay1` instance and create a new one to connect again.
|
|
419
|
-
*/
|
|
420
|
-
async close(): Promise<void> {
|
|
421
|
-
this.closedByUser = true;
|
|
422
|
-
this.socket.close();
|
|
423
|
-
this.stopIdleTimer();
|
|
424
|
-
this.controller.abort();
|
|
425
|
-
|
|
426
|
-
if (this.socket.readyState !== WebSocket.CLOSED) {
|
|
427
|
-
await new Promise((resolve) => {
|
|
428
|
-
this.socket.addEventListener(WebsocketEvent.close, resolve, {
|
|
429
|
-
once: true,
|
|
430
|
-
});
|
|
431
|
-
});
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
async [Symbol.asyncDispose](): Promise<void> {
|
|
436
|
-
await this.close();
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
/** Native JSON primitive value, including objects and arrays. */
|
|
441
|
-
type JsonValue =
|
|
442
|
-
| { [key: string]: JsonValue | undefined }
|
|
443
|
-
| JsonValue[]
|
|
444
|
-
| string
|
|
445
|
-
| number
|
|
446
|
-
| boolean
|
|
447
|
-
| null;
|