mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-08 16:28:49 +00:00
Compare commits
7 Commits
node-webso
...
v2.16.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b076c34a2f | ||
|
|
4bb3eb2d40 | ||
|
|
87f2c74bb3 | ||
|
|
4b6cc19b9c | ||
|
|
b2f3a01439 | ||
|
|
6ec19b618c | ||
|
|
b3cc9f50e5 |
@@ -133,6 +133,14 @@ import WebSocket from 'ws'
|
||||
useWebSocketImplementation(WebSocket)
|
||||
```
|
||||
|
||||
You can enable regular pings of connected relays with the `enablePing` option. This will set up a heartbeat that closes the websocket if it doesn't receive a response in time. Some platforms don't report websocket disconnections due to network issues, and enabling this can increase reliability.
|
||||
|
||||
```js
|
||||
import { SimplePool } from 'nostr-tools/pool'
|
||||
|
||||
const pool = new SimplePool({ enablePing: true })
|
||||
```
|
||||
|
||||
### Parsing references (mentions) from a content based on NIP-27
|
||||
|
||||
```js
|
||||
|
||||
@@ -32,6 +32,7 @@ export class AbstractSimplePool {
|
||||
public trackRelays: boolean = false
|
||||
|
||||
public verifyEvent: Nostr['verifyEvent']
|
||||
public enablePing: boolean | undefined
|
||||
public trustedRelayURLs: Set<string> = new Set()
|
||||
|
||||
private _WebSocket?: typeof WebSocket
|
||||
@@ -39,6 +40,7 @@ export class AbstractSimplePool {
|
||||
constructor(opts: AbstractPoolConstructorOptions) {
|
||||
this.verifyEvent = opts.verifyEvent
|
||||
this._WebSocket = opts.websocketImplementation
|
||||
this.enablePing = opts.enablePing
|
||||
}
|
||||
|
||||
async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise<AbstractRelay> {
|
||||
@@ -49,6 +51,7 @@ export class AbstractSimplePool {
|
||||
relay = new AbstractRelay(url, {
|
||||
verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,
|
||||
websocketImplementation: this._WebSocket,
|
||||
enablePing: this.enablePing,
|
||||
})
|
||||
relay.onclose = () => {
|
||||
this.relays.delete(url)
|
||||
@@ -137,8 +140,6 @@ export class AbstractSimplePool {
|
||||
// open a subscription in all given relays
|
||||
const allOpened = Promise.all(
|
||||
requests.map(async ({ url, filter }, i) => {
|
||||
url = normalizeURL(url)
|
||||
|
||||
let relay: AbstractRelay
|
||||
try {
|
||||
relay = await this.ensureRelay(url, {
|
||||
|
||||
@@ -7,9 +7,15 @@ import { Queue, normalizeURL } from './utils.ts'
|
||||
import { makeAuthEvent } from './nip42.ts'
|
||||
import { yieldThread } from './helpers.ts'
|
||||
|
||||
type RelayWebSocket = WebSocket & {
|
||||
ping?(): void
|
||||
on?(event: 'pong', listener: () => void): any
|
||||
}
|
||||
|
||||
export type AbstractRelayConstructorOptions = {
|
||||
verifyEvent: Nostr['verifyEvent']
|
||||
websocketImplementation?: typeof WebSocket
|
||||
enablePing?: boolean
|
||||
}
|
||||
|
||||
export class SendingOnClosedConnection extends Error {
|
||||
@@ -29,13 +35,16 @@ export class AbstractRelay {
|
||||
public baseEoseTimeout: number = 4400
|
||||
public connectionTimeout: number = 4400
|
||||
public publishTimeout: number = 4400
|
||||
public pingFrequency: number = 20000
|
||||
public pingTimeout: number = 20000
|
||||
public openSubs: Map<string, Subscription> = new Map()
|
||||
public enablePing: boolean | undefined
|
||||
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
private connectionPromise: Promise<void> | undefined
|
||||
private openCountRequests = new Map<string, CountResolver>()
|
||||
private openEventPublishes = new Map<string, EventPublishResolver>()
|
||||
private ws: WebSocket | undefined
|
||||
private ws: RelayWebSocket | undefined
|
||||
private incomingMessageQueue = new Queue<string>()
|
||||
private queueRunning = false
|
||||
private challenge: string | undefined
|
||||
@@ -49,6 +58,7 @@ export class AbstractRelay {
|
||||
this.url = normalizeURL(url)
|
||||
this.verifyEvent = opts.verifyEvent
|
||||
this._WebSocket = opts.websocketImplementation || WebSocket
|
||||
this.enablePing = opts.enablePing
|
||||
}
|
||||
|
||||
static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise<AbstractRelay> {
|
||||
@@ -102,6 +112,9 @@ export class AbstractRelay {
|
||||
this.ws.onopen = () => {
|
||||
clearTimeout(this.connectionTimeoutHandle)
|
||||
this._connected = true
|
||||
if (this.enablePing) {
|
||||
this.pingpong()
|
||||
}
|
||||
resolve()
|
||||
}
|
||||
|
||||
@@ -133,6 +146,53 @@ export class AbstractRelay {
|
||||
return this.connectionPromise
|
||||
}
|
||||
|
||||
private async waitForPingPong() {
|
||||
return new Promise((res, err) => {
|
||||
// listen for pong
|
||||
;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err("ws can't listen for pong")
|
||||
// send a ping
|
||||
this.ws && this.ws.ping && this.ws.ping()
|
||||
})
|
||||
}
|
||||
|
||||
private async waitForDummyReq() {
|
||||
return new Promise((res, err) => {
|
||||
// make a dummy request with expected empty eose reply
|
||||
// ["REQ", "_", {"ids":["aaaa...aaaa"]}]
|
||||
const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {
|
||||
oneose: () => {
|
||||
sub.close()
|
||||
res(true)
|
||||
},
|
||||
eoseTimeout: this.pingTimeout + 1000,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// nodejs requires this magic here to ensure connections are closed when internet goes off and stuff
|
||||
// in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491
|
||||
private async pingpong() {
|
||||
// if the websocket is connected
|
||||
if (this.ws?.readyState === 1) {
|
||||
// wait for either a ping-pong reply or a timeout
|
||||
const result = await Promise.any([
|
||||
// browsers don't have ping so use a dummy req
|
||||
this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),
|
||||
new Promise(res => setTimeout(() => res(false), this.pingTimeout)),
|
||||
])
|
||||
if (result) {
|
||||
// schedule another pingpong
|
||||
setTimeout(() => this.pingpong(), this.pingFrequency)
|
||||
} else {
|
||||
// pingpong closing socket
|
||||
this.closeAllSubscriptions('pingpong timed out')
|
||||
this._connected = false
|
||||
this.ws?.close()
|
||||
this.onclose?.()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async runQueue() {
|
||||
this.queueRunning = true
|
||||
while (true) {
|
||||
|
||||
2
jsr.json
2
jsr.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@nostr/tools",
|
||||
"version": "2.15.1",
|
||||
"version": "2.16.0",
|
||||
"exports": {
|
||||
".": "./index.ts",
|
||||
"./core": "./core.ts",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
// prettier-ignore
|
||||
import {
|
||||
decode,
|
||||
naddrEncode,
|
||||
|
||||
2
nip29.ts
2
nip29.ts
@@ -2,7 +2,7 @@ import { AbstractSimplePool } from './abstract-pool.ts'
|
||||
import { Subscription } from './abstract-relay.ts'
|
||||
import type { Event, EventTemplate } from './core.ts'
|
||||
import { fetchRelayInformation, RelayInformation } from './nip11.ts'
|
||||
import { AddressPointer, decode, NostrTypeGuard } from './nip19.ts'
|
||||
import { decode, NostrTypeGuard } from './nip19.ts'
|
||||
import { normalizeURL } from './utils.ts'
|
||||
|
||||
/**
|
||||
|
||||
8
nip46.ts
8
nip46.ts
@@ -5,7 +5,6 @@ import { getConversationKey, decrypt, encrypt } from './nip44.ts'
|
||||
import { NIP05_REGEX } from './nip05.ts'
|
||||
import { SimplePool } from './pool.ts'
|
||||
import { Handlerinformation, NostrConnect } from './kinds.ts'
|
||||
import type { RelayRecord } from './relay.ts'
|
||||
import { Signer } from './signer.ts'
|
||||
|
||||
var _fetch: any
|
||||
@@ -238,13 +237,6 @@ export class BunkerSigner implements Signer {
|
||||
return this.cachedPubKey
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated removed from NIP
|
||||
*/
|
||||
async getRelays(): Promise<RelayRecord> {
|
||||
return JSON.parse(await this.sendRequest('get_relays', []))
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs an event using the remote private key.
|
||||
* @param event - The event to sign.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"type": "module",
|
||||
"name": "nostr-tools",
|
||||
"version": "2.15.0",
|
||||
"version": "2.16.0",
|
||||
"description": "Tools for making a Nostr client.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
4
pool.ts
4
pool.ts
@@ -14,8 +14,8 @@ export function useWebSocketImplementation(websocketImplementation: any) {
|
||||
}
|
||||
|
||||
export class SimplePool extends AbstractSimplePool {
|
||||
constructor() {
|
||||
super({ verifyEvent, websocketImplementation: _WebSocket })
|
||||
constructor(options?: { enablePing?: boolean }) {
|
||||
super({ verifyEvent, websocketImplementation: _WebSocket, ...options })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user