@minip2p/core 0.1.0 → 0.3.0

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/src/sdk.ts CHANGED
@@ -1,538 +1,991 @@
1
- /* oxlint-disable func-style, max-classes-per-file, no-use-before-define, promise/avoid-new, promise/prefer-await-to-then, unicorn/no-useless-spread -- The SDK uses a private queue class, hoisted helpers and Promise adapters, schedules same-tick events on a microtask, and snapshots observer sets before callbacks mutate them. */
1
+ /* oxlint-disable default-case, func-style, max-classes-per-file, no-empty-function, no-use-before-define, promise/avoid-new, promise/prefer-await-to-callbacks, promise/prefer-await-to-then, typescript/no-invalid-void-type, unicorn/consistent-function-scoping, unicorn/no-new-array, unicorn/no-useless-spread, unicorn/no-useless-undefined -- Promise adapters, void event payloads, snapshot fan-out, and bounded queues are deliberate SDK internals. */
2
2
 
3
- import type { MiniP2pBackend } from "./backend.js";
3
+ import type { Minip2pBackend } from "./backend.js";
4
4
  import {
5
+ AbortError,
5
6
  ClosedError,
7
+ ConnectFailedError,
8
+ ConnectResultUnavailableError,
6
9
  DriverFailedError,
10
+ EventQueueOverflowError,
11
+ OpenStreamError,
7
12
  PeerDisconnectedError,
13
+ StreamClosedError,
8
14
  TimeoutError,
9
15
  } from "./errors.js";
10
- import { P2pEvent_Tags } from "./types.js";
16
+ import { P2pEvent_Tags, PathKind_Tags } from "./types.js";
11
17
  import type {
12
18
  Bytes,
19
+ CloseReason,
20
+ ConnectResult,
13
21
  IdentifyInfo,
22
+ InboundStreamMeta,
14
23
  KnownPeerInfo,
15
- MiniP2pEvent,
24
+ Minip2pCatchAllEventMap,
25
+ Minip2pEvent,
26
+ Minip2pNamedEventMap,
27
+ OnceOptions,
28
+ OpOptions,
16
29
  P2pEvent,
17
- P2pEventByTag,
30
+ Path,
31
+ PathKind,
18
32
  Reachability,
19
33
  RelayReservationInfo,
20
34
  Unsubscribe,
35
+ WaitForOptions,
21
36
  } from "./types.js";
22
37
 
23
38
  declare const TextEncoder: new () => {
24
39
  encode: (input: string) => Uint8Array;
25
40
  };
26
41
 
27
- const QUEUE_CAP = 4096;
28
- const FLUSH_BATCH = 256;
29
- const REPLACEABLE_EVENTS = new Set<P2pEvent_Tags>([
30
- P2pEvent_Tags.ReachabilityChanged,
31
- P2pEvent_Tags.PublicAddressesChanged,
32
- ]);
33
-
34
- type EventHandler = (event: MiniP2pEvent) => void;
35
- interface Waiter {
36
- predicate: (event: MiniP2pEvent) => boolean;
37
- resolve: (event: MiniP2pEvent) => void;
38
- reject: (error: Error) => void;
42
+ const DEFAULT_TIMEOUT_MS = 65_000;
43
+ const EVENT_QUEUE_CAP = 4096;
44
+ const EVENT_FLUSH_BATCH = 256;
45
+ const CONNECT_TERMINAL_CAP = 1024;
46
+ const STREAM_CHUNK_CAP = 64;
47
+ const STREAM_BYTE_CAP = 1024 * 1024;
48
+
49
+ type EventKind = keyof Minip2pNamedEventMap;
50
+ type AnyPayload = Minip2pNamedEventMap[EventKind];
51
+ type NamedHandler<Kind extends EventKind> = (
52
+ payload: Minip2pNamedEventMap[Kind]
53
+ ) => void;
54
+ type CatchAllHandler = (event: Minip2pEvent) => void;
55
+ type QueueItem =
56
+ | { readonly source: "native"; readonly event: P2pEvent }
57
+ | {
58
+ readonly source: "high";
59
+ readonly type: "handlerError";
60
+ readonly payload: Minip2pCatchAllEventMap["handlerError"];
61
+ };
62
+
63
+ interface EventWaiter {
64
+ readonly type: EventKind;
65
+ readonly predicate: (event: unknown) => boolean;
66
+ readonly resolve: (event: unknown) => void;
67
+ readonly reject: (error: unknown) => void;
39
68
  timer?: ReturnType<typeof setTimeout>;
69
+ removeAbort?: () => void;
40
70
  }
41
71
 
42
- interface EventNode {
43
- readonly event: P2pEvent;
44
- previous?: EventNode;
45
- next?: EventNode;
72
+ type ConnectTerminal =
73
+ | {
74
+ readonly ok: true;
75
+ readonly result: ConnectResult;
76
+ }
77
+ | {
78
+ readonly ok: false;
79
+ readonly error: ConnectFailedError;
80
+ };
81
+
82
+ interface ConnectAttempt {
83
+ terminal?: ConnectTerminal;
84
+ waiting: boolean;
85
+ resolve?: (result: ConnectResult) => void;
86
+ reject?: (error: unknown) => void;
46
87
  }
47
88
 
48
- /**
49
- * A bounded FIFO with constant-time front removal and payload eviction.
50
- *
51
- * Replaceable-event indexes let overflow compaction visit only candidates
52
- * that can actually be discarded rather than rebuilding the entire queue.
53
- */
54
- class EventQueue {
55
- readonly #payloads = new Set<EventNode>();
56
- readonly #replaceable = new Map<P2pEvent_Tags, Set<EventNode>>();
57
- #head?: EventNode;
58
- #tail?: EventNode;
89
+ interface PendingOpen {
90
+ readonly peerId: string;
91
+ readonly protocolId: string;
92
+ readonly connId: number;
93
+ readonly streamId: number;
94
+ readonly resolve: (stream: Stream) => void;
95
+ readonly reject: (error: unknown) => void;
96
+ timer?: ReturnType<typeof setTimeout>;
97
+ removeAbort?: () => void;
98
+ }
99
+
100
+ interface PendingRead {
101
+ readonly resolve: (data?: Uint8Array) => void;
102
+ readonly reject: (error: unknown) => void;
103
+ }
104
+
105
+ interface PingOperation {
106
+ readonly promise: Promise<number>;
107
+ readonly cancel: (error: unknown) => void;
108
+ callers: number;
109
+ }
110
+
111
+ class BoundedQueue<Item> {
112
+ readonly #items: (Item | undefined)[];
113
+ #head = 0;
59
114
  #size = 0;
60
115
 
61
- get size(): number {
116
+ constructor(capacity: number) {
117
+ this.#items = new Array<Item | undefined>(capacity);
118
+ }
119
+
120
+ get length(): number {
62
121
  return this.#size;
63
122
  }
64
123
 
124
+ push(item: Item): Item | undefined {
125
+ if (this.#size === this.#items.length) {
126
+ const dropped = this.#items[this.#head];
127
+ this.#items[this.#head] = item;
128
+ this.#head = (this.#head + 1) % this.#items.length;
129
+ return dropped;
130
+ }
131
+ const tail = (this.#head + this.#size) % this.#items.length;
132
+ this.#items[tail] = item;
133
+ this.#size += 1;
134
+ return undefined;
135
+ }
136
+
137
+ shift(): Item | undefined {
138
+ if (this.#size === 0) {
139
+ return undefined;
140
+ }
141
+ const item = this.#items[this.#head];
142
+ this.#items[this.#head] = undefined;
143
+ this.#head = (this.#head + 1) % this.#items.length;
144
+ this.#size -= 1;
145
+ return item;
146
+ }
147
+
65
148
  clear(): void {
66
- this.#head = undefined;
67
- this.#tail = undefined;
149
+ this.#items.fill(undefined);
150
+ this.#head = 0;
68
151
  this.#size = 0;
69
- this.#payloads.clear();
70
- this.#replaceable.clear();
152
+ }
153
+ }
154
+
155
+ /** A negotiated custom-protocol stream with exclusive pull or flowing reads. */
156
+ export class Stream {
157
+ /** Remote peer that owns the other end of this stream. */
158
+ readonly peerId: string;
159
+ /** Negotiated multistream protocol identifier. */
160
+ readonly protocolId: string;
161
+ /** Endpoint-local transport stream identifier. */
162
+ readonly streamId: number;
163
+ /** Endpoint-local connection carrying this stream. */
164
+ readonly connId: number;
165
+ /** Whether this endpoint initiated the stream. */
166
+ readonly initiatedLocally: boolean;
167
+ readonly #backend: Minip2pBackend;
168
+ readonly #onTerminal: () => void;
169
+ readonly #listeners = new Map<
170
+ keyof StreamEventMap,
171
+ Set<(payload: StreamEventMap[keyof StreamEventMap]) => void>
172
+ >();
173
+ readonly #fifo: Uint8Array[] = [];
174
+ readonly #reads: PendingRead[] = [];
175
+ #fifoBytes = 0;
176
+ #mode: "pull" | "flowing" | undefined;
177
+ #remoteWriteClosed = false;
178
+ #closed = false;
179
+
180
+ constructor(
181
+ backend: Minip2pBackend,
182
+ meta: InboundStreamMeta,
183
+ onTerminal: () => void
184
+ ) {
185
+ this.#backend = backend;
186
+ this.#onTerminal = onTerminal;
187
+ this.peerId = meta.peerId;
188
+ this.protocolId = meta.protocolId;
189
+ this.streamId = meta.streamId;
190
+ this.connId = meta.connId;
191
+ this.initiatedLocally = meta.initiatedLocally;
71
192
  }
72
193
 
73
- push(event: P2pEvent): number {
74
- let dropped = 0;
75
- if (this.#size >= QUEUE_CAP) {
76
- dropped += this.#compactReplaceable();
194
+ /** Subscribes to stream lifecycle or data events. */
195
+ on<Kind extends keyof StreamEventMap>(
196
+ type: Kind,
197
+ handler: (payload: StreamEventMap[Kind]) => void
198
+ ): Unsubscribe {
199
+ if (type === "data") {
200
+ if (this.#mode === "pull") {
201
+ throw new Error("Cannot use flowing data handlers after read()");
202
+ }
203
+ this.#mode = "flowing";
77
204
  }
78
- if (this.#size >= QUEUE_CAP) {
79
- const payload = this.#payloads.values().next().value;
80
- if (payload === undefined) {
81
- this.shift();
82
- } else {
83
- this.#remove(payload);
205
+ let listeners = this.#listeners.get(type);
206
+ if (listeners === undefined) {
207
+ listeners = new Set();
208
+ this.#listeners.set(type, listeners);
209
+ }
210
+ listeners.add(
211
+ handler as (payload: StreamEventMap[keyof StreamEventMap]) => void
212
+ );
213
+ if (type === "data") {
214
+ this.#flushFlowing();
215
+ }
216
+ let active = true;
217
+ return () => {
218
+ if (!active) {
219
+ return;
84
220
  }
85
- dropped += 1;
221
+ active = false;
222
+ listeners?.delete(
223
+ handler as (payload: StreamEventMap[keyof StreamEventMap]) => void
224
+ );
225
+ };
226
+ }
227
+
228
+ /**
229
+ * Reads the next buffered chunk, or `undefined` after the remote write side
230
+ * closes. Pull reads and flowing `data` handlers are mutually exclusive.
231
+ */
232
+ read(): Promise<Uint8Array | undefined> {
233
+ if (this.#mode === "flowing") {
234
+ return Promise.reject(
235
+ new Error('Cannot call read() after subscribing to "data"')
236
+ );
237
+ }
238
+ this.#mode = "pull";
239
+ const buffered = this.#shift();
240
+ if (buffered !== undefined) {
241
+ return Promise.resolve(buffered);
86
242
  }
243
+ if (this.#remoteWriteClosed) {
244
+ return Promise.resolve(this.#shift());
245
+ }
246
+ if (this.#closed) {
247
+ return Promise.reject(new ClosedError());
248
+ }
249
+ return new Promise((resolve, reject) => {
250
+ this.#reads.push({ reject, resolve });
251
+ });
252
+ }
87
253
 
88
- const node: EventNode = { event, previous: this.#tail };
89
- if (this.#tail === undefined) {
90
- this.#head = node;
91
- } else {
92
- this.#tail.next = node;
254
+ /** Writes UTF-8 text or bytes to the stream. */
255
+ write(data: string | Bytes): void {
256
+ if (this.#closed) {
257
+ throw new ClosedError();
93
258
  }
94
- this.#tail = node;
95
- this.#size += 1;
96
- this.#index(node);
97
- return dropped;
259
+ this.#backend.sendStream(this.peerId, this.streamId, toUint8Array(data));
98
260
  }
99
261
 
100
- shift(): P2pEvent | undefined {
101
- const node = this.#head;
102
- if (node === undefined) {
103
- return undefined;
262
+ /** Half-closes the local write side while keeping reads available. */
263
+ closeWrite(): void {
264
+ if (!this.#closed) {
265
+ this.#backend.closeStreamWrite(this.peerId, this.streamId);
104
266
  }
105
- this.#remove(node);
106
- return node.event;
107
267
  }
108
268
 
109
- #compactReplaceable(): number {
110
- let dropped = 0;
111
- for (const nodes of this.#replaceable.values()) {
112
- if (nodes.size < 2) {
113
- continue;
114
- }
115
- const latest = [...nodes].at(-1);
116
- for (const node of [...nodes]) {
117
- if (node !== latest) {
118
- this.#remove(node);
119
- dropped += 1;
120
- }
121
- }
269
+ /** Abruptly resets the stream and emits `closed`. */
270
+ reset(): void {
271
+ if (!this.#closed) {
272
+ this.#backend.resetStream(this.peerId, this.streamId);
273
+ this.terminal();
274
+ }
275
+ }
276
+
277
+ /** Resets and relinquishes the stream, suppressing later native events. */
278
+ abandon(): void {
279
+ if (!this.#closed) {
280
+ this.#backend.abandonStream(this.peerId, this.streamId);
281
+ this.terminal();
122
282
  }
123
- return dropped;
124
283
  }
125
284
 
126
- #index(node: EventNode): void {
285
+ [Symbol.dispose](): void {
286
+ this.abandon();
287
+ }
288
+
289
+ /** @internal */
290
+ receive(data: ArrayBuffer): void {
291
+ if (this.#closed) {
292
+ return;
293
+ }
294
+ const chunk = new Uint8Array(data);
295
+ const read = this.#reads.shift();
296
+ if (read !== undefined) {
297
+ read.resolve(chunk);
298
+ return;
299
+ }
300
+ if (this.#mode === "flowing") {
301
+ this.#emit("data", chunk);
302
+ return;
303
+ }
127
304
  if (
128
- node.event.tag === P2pEvent_Tags.Message ||
129
- node.event.tag === P2pEvent_Tags.StreamData
305
+ this.#fifo.length >= STREAM_CHUNK_CAP ||
306
+ this.#fifoBytes + chunk.byteLength > STREAM_BYTE_CAP
130
307
  ) {
131
- this.#payloads.add(node);
308
+ this.#emit("dataOverflow", {
309
+ droppedBytes: chunk.byteLength,
310
+ droppedChunks: 1,
311
+ });
312
+ return;
313
+ }
314
+ this.#fifo.push(chunk);
315
+ this.#fifoBytes += chunk.byteLength;
316
+ }
317
+
318
+ /** @internal */
319
+ remoteWriteClosed(): void {
320
+ if (this.#closed || this.#remoteWriteClosed) {
321
+ return;
132
322
  }
133
- if (REPLACEABLE_EVENTS.has(node.event.tag)) {
134
- let nodes = this.#replaceable.get(node.event.tag);
135
- if (nodes === undefined) {
136
- nodes = new Set();
137
- this.#replaceable.set(node.event.tag, nodes);
323
+ this.#remoteWriteClosed = true;
324
+ this.#emit("remoteWriteClosed");
325
+ if (this.#fifo.length === 0) {
326
+ for (const read of this.#reads.splice(0)) {
327
+ read.resolve();
138
328
  }
139
- nodes.add(node);
140
329
  }
141
330
  }
142
331
 
143
- #remove(node: EventNode): void {
144
- if (node.previous === undefined) {
145
- this.#head = node.next;
146
- } else {
147
- node.previous.next = node.next;
332
+ /** @internal */
333
+ terminal(error: unknown = new ClosedError()): void {
334
+ if (this.#closed) {
335
+ return;
148
336
  }
149
- if (node.next === undefined) {
150
- this.#tail = node.previous;
151
- } else {
152
- node.next.previous = node.previous;
337
+ this.#closed = true;
338
+ this.#fifo.length = 0;
339
+ this.#fifoBytes = 0;
340
+ for (const read of this.#reads.splice(0)) {
341
+ read.reject(error);
153
342
  }
343
+ this.#emit("closed");
344
+ this.#listeners.clear();
345
+ this.#onTerminal();
346
+ }
154
347
 
155
- this.#payloads.delete(node);
156
- const replaceable = this.#replaceable.get(node.event.tag);
157
- replaceable?.delete(node);
158
- if (replaceable?.size === 0) {
159
- this.#replaceable.delete(node.event.tag);
348
+ #flushFlowing(): void {
349
+ while (this.#fifo.length > 0 && !this.#closed) {
350
+ const chunk = this.#shift();
351
+ if (chunk !== undefined) {
352
+ this.#emit("data", chunk);
353
+ }
354
+ }
355
+ }
356
+
357
+ #shift(): Uint8Array | undefined {
358
+ const chunk = this.#fifo.shift();
359
+ if (chunk !== undefined) {
360
+ this.#fifoBytes -= chunk.byteLength;
361
+ }
362
+ return chunk;
363
+ }
364
+
365
+ #emit<Kind extends keyof StreamEventMap>(
366
+ type: Kind,
367
+ payload?: StreamEventMap[Kind]
368
+ ): void {
369
+ for (const handler of [...(this.#listeners.get(type) ?? [])]) {
370
+ try {
371
+ handler(payload as StreamEventMap[Kind]);
372
+ } catch {
373
+ // Stream handlers are isolated from native callbacks and one another.
374
+ }
160
375
  }
161
- this.#size -= 1;
162
376
  }
163
377
  }
164
378
 
379
+ /** Events emitted by a negotiated {@link Stream}. */
380
+ export interface StreamEventMap {
381
+ /** A received binary chunk. */
382
+ data: Uint8Array;
383
+ /** The remote peer half-closed its write side. */
384
+ remoteWriteClosed: void;
385
+ /** The stream reached a terminal state. */
386
+ closed: void;
387
+ /** Incoming data exceeded the bounded pull-read buffer. */
388
+ dataOverflow: {
389
+ readonly droppedChunks: number;
390
+ readonly droppedBytes: number;
391
+ };
392
+ }
393
+
165
394
  /**
166
- * Platform-neutral owner for one native minip2p endpoint.
395
+ * Promise-first, platform-neutral owner for one native minip2p endpoint.
167
396
  *
168
- * Platform packages extend this class and expose a zero-argument `create`
169
- * method backed by their native adapter.
397
+ * Platform packages subclass this and provide a native backend factory.
170
398
  */
171
- export class MiniP2pBase {
172
- readonly #backend: MiniP2pBackend;
399
+ export class Minip2pBase {
400
+ readonly #backend: Minip2pBackend;
173
401
  readonly #relayAddrs: readonly string[];
174
- readonly #handlers = new Set<EventHandler>();
175
- readonly #waiters = new Set<Waiter>();
176
- readonly #queue = new EventQueue();
177
- readonly #connectResults = new Map<
178
- number,
179
- | P2pEventByTag<P2pEvent_Tags.PathEstablished>
180
- | P2pEventByTag<P2pEvent_Tags.ConnectFailed>
181
- >();
182
- #overflowDropped = 0;
402
+ readonly #named = new Map<EventKind, Set<(payload: AnyPayload) => void>>();
403
+ readonly #catchAll = new Set<CatchAllHandler>();
404
+ readonly #closeHandlers = new Set<(reason: CloseReason) => void>();
405
+ readonly #waiters = new Set<EventWaiter>();
406
+ readonly #queue = new BoundedQueue<QueueItem>(EVENT_QUEUE_CAP);
407
+ readonly #connects = new Map<number, ConnectAttempt>();
408
+ readonly #terminalConnects = new Set<number>();
409
+ readonly #streams = new Map<string, Stream>();
410
+ readonly #pendingOpens = new Map<string, PendingOpen>();
411
+ readonly #pings = new Map<string, PingOperation>();
412
+ #dropped = 0;
183
413
  #flushScheduled = false;
184
414
  #closed = false;
185
415
 
186
416
  protected constructor(
187
- backend: MiniP2pBackend,
417
+ backend: Minip2pBackend,
188
418
  relayAddresses: readonly string[]
189
419
  ) {
190
420
  this.#backend = backend;
191
421
  this.#relayAddrs = relayAddresses;
192
422
  try {
193
- this.#backend.start((event) => {
194
- this.#enqueue(event);
423
+ backend.start((event) => {
424
+ this.#enqueueNative(event);
195
425
  });
196
426
  } catch (error) {
197
- this.#backend.close();
427
+ backend.close();
198
428
  throw error;
199
429
  }
200
430
  }
201
431
 
202
- /** Adds an event subscriber and returns an idempotent unsubscribe function. */
203
- on(handler: EventHandler): Unsubscribe {
432
+ /** Subscribes to one named event and returns an idempotent unsubscribe. */
433
+ on<Kind extends EventKind>(
434
+ type: Kind,
435
+ handler: NamedHandler<Kind>
436
+ ): Unsubscribe;
437
+ /** Subscribes to the catch-all metadata event stream. */
438
+ on(handler: CatchAllHandler): Unsubscribe;
439
+ on<Kind extends EventKind>(
440
+ typeOrHandler: Kind | CatchAllHandler,
441
+ maybeHandler?: NamedHandler<Kind>
442
+ ): Unsubscribe {
204
443
  this.#assertOpen();
205
- this.#handlers.add(handler);
206
- let subscribed = true;
207
- return () => {
208
- if (subscribed) {
209
- subscribed = false;
210
- this.#handlers.delete(handler);
211
- }
212
- };
444
+ if (typeof typeOrHandler === "function") {
445
+ return subscribe(this.#catchAll, typeOrHandler);
446
+ }
447
+ let handlers = this.#named.get(typeOrHandler);
448
+ if (handlers === undefined) {
449
+ handlers = new Set();
450
+ this.#named.set(typeOrHandler, handlers);
451
+ }
452
+ return subscribe(
453
+ handlers,
454
+ maybeHandler as unknown as (payload: AnyPayload) => void
455
+ );
213
456
  }
214
457
 
215
- /** Resolves with the first event matching `predicate`. */
216
- waitFor<EventType extends MiniP2pEvent>(
217
- predicate: (event: MiniP2pEvent) => event is EventType,
218
- timeoutMs?: number
219
- ): Promise<EventType>;
220
- waitFor(
221
- predicate: (event: MiniP2pEvent) => boolean,
222
- timeoutMs?: number
223
- ): Promise<MiniP2pEvent>;
224
- waitFor(
225
- predicate: (event: MiniP2pEvent) => boolean,
226
- timeoutMs = 65_000
227
- ): Promise<MiniP2pEvent> {
228
- this.#assertOpen();
229
- assertSafeUnsignedInteger(timeoutMs, "timeoutMs");
458
+ /** Resolves with the next event of `type`. */
459
+ once<Kind extends EventKind>(
460
+ type: Kind,
461
+ options?: OnceOptions
462
+ ): Promise<{ readonly type: Kind } & Minip2pNamedEventMap[Kind]> {
463
+ return this.waitFor(type, { ...options });
464
+ }
230
465
 
466
+ /** Resolves with the next event of `type` accepted by `predicate`. */
467
+ waitFor<Kind extends EventKind>(
468
+ type: Kind,
469
+ options: WaitForOptions<
470
+ { readonly type: Kind } & Minip2pNamedEventMap[Kind]
471
+ >
472
+ ): Promise<{ readonly type: Kind } & Minip2pNamedEventMap[Kind]> {
473
+ this.#assertOpen();
474
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
475
+ assertTimeout(timeoutMs);
476
+ if (options.signal?.aborted === true) {
477
+ return Promise.reject(new AbortError());
478
+ }
231
479
  return new Promise((resolve, reject) => {
232
- const waiter: Waiter = { predicate, reject, resolve };
480
+ const waiter: EventWaiter = {
481
+ predicate: (event) =>
482
+ options.predicate?.(
483
+ event as { readonly type: Kind } & Minip2pNamedEventMap[Kind]
484
+ ) ?? true,
485
+ reject,
486
+ resolve: (event) => {
487
+ resolve(
488
+ event as { readonly type: Kind } & Minip2pNamedEventMap[Kind]
489
+ );
490
+ },
491
+ type,
492
+ };
233
493
  if (timeoutMs > 0) {
234
494
  waiter.timer = setTimeout(() => {
235
495
  this.#waiters.delete(waiter);
496
+ waiter.removeAbort?.();
236
497
  reject(new TimeoutError(timeoutMs));
237
498
  }, timeoutMs);
238
499
  }
500
+ waiter.removeAbort = listenAbort(options.signal, () => {
501
+ this.#waiters.delete(waiter);
502
+ clearTimeout(waiter.timer);
503
+ reject(new AbortError());
504
+ });
239
505
  this.#waiters.add(waiter);
240
506
  });
241
507
  }
242
508
 
243
- /** Requests native shutdown and releases the platform backend. */
244
- close(): void {
509
+ /** Registers a one-shot endpoint shutdown observer. */
510
+ onClose(handler: (reason: CloseReason) => void): Unsubscribe {
245
511
  if (this.#closed) {
246
- return;
247
- }
248
- this.#closed = true;
249
- this.#queue.clear();
250
- this.#connectResults.clear();
251
- this.#overflowDropped = 0;
252
- this.#handlers.clear();
253
- for (const waiter of this.#waiters) {
254
- clearWaiterTimer(waiter);
255
- waiter.reject(new ClosedError());
512
+ return () => {};
256
513
  }
257
- this.#waiters.clear();
258
- this.#backend.close();
514
+ return subscribe(this.#closeHandlers, handler);
259
515
  }
260
516
 
261
- /** Returns the endpoint's base58 peer ID. */
517
+ /** Idempotently stops the endpoint and rejects outstanding operations. */
518
+ close(): void {
519
+ this.#teardown({ reason: "close" }, new ClosedError());
520
+ }
521
+
522
+ [Symbol.dispose](): void {
523
+ this.close();
524
+ }
525
+
526
+ /** Returns this endpoint's base58 peer ID. */
262
527
  peerId(): string {
263
528
  this.#assertOpen();
264
529
  return this.#backend.peerId();
265
530
  }
266
531
 
267
- /** Returns the endpoint's bound peer addresses. */
532
+ /** Returns the currently bound peer multiaddresses. */
268
533
  listenAddrs(): string[] {
269
534
  this.#assertOpen();
270
535
  return this.#backend.listenAddrs();
271
536
  }
272
537
 
273
- /** Returns currently connected peer IDs. */
538
+ /** Returns peer IDs with live transport connections. */
274
539
  connectedPeers(): string[] {
275
540
  this.#assertOpen();
276
541
  return this.#backend.connectedPeers();
277
542
  }
278
543
 
279
- /** Returns whether Identify has completed for a connected peer. */
544
+ /** Returns whether Identify completed for a connected peer. */
280
545
  isPeerReady(peerId: string): boolean {
281
546
  this.#assertOpen();
282
547
  return this.#backend.isPeerReady(peerId);
283
548
  }
284
549
 
285
- /** Returns the latest Identify snapshot for a connected peer. */
550
+ /** Returns the latest Identify snapshot for `peerId`. */
286
551
  peerInfo(peerId: string): IdentifyInfo | undefined {
287
552
  this.#assertOpen();
288
553
  return this.#backend.peerInfo(peerId);
289
554
  }
290
555
 
291
- /** Returns the normalized discovery address book. */
556
+ /** Returns the normalized multi-source discovery address book. */
292
557
  knownPeers(): KnownPeerInfo[] {
293
558
  this.#assertOpen();
294
559
  return this.#backend.knownPeers();
295
560
  }
296
561
 
297
- /** Returns the native discovery monotonic clock, when discovery is enabled. */
562
+ /** Returns the discovery monotonic clock when discovery is enabled. */
298
563
  discoveryNowMs(): number | undefined {
299
564
  this.#assertOpen();
300
565
  return this.#backend.discoveryNowMs();
301
566
  }
302
567
 
303
- /** Returns the active relay reservation, if one exists. */
568
+ /** Returns the active relay reservation, if any. */
304
569
  activeReservation(): RelayReservationInfo | undefined {
305
570
  this.#assertOpen();
306
571
  return this.#backend.activeReservation();
307
572
  }
308
573
 
309
- /** Returns this endpoint's currently usable circuit address, if known. */
574
+ /** Returns this endpoint's usable circuit address, if reserved. */
310
575
  get circuitAddress(): string | undefined {
311
576
  const reservation = this.activeReservation();
312
577
  if (reservation === undefined) {
313
578
  return undefined;
314
579
  }
315
- const suffix = `/p2p/${reservation.relayPeerId}`;
316
- const relayAddr = this.#relayAddrs.find((addr) => addr.endsWith(suffix));
317
- return relayAddr === undefined
580
+ const relay = this.#relayAddrs.find((address) =>
581
+ address.endsWith(`/p2p/${reservation.relayPeerId}`)
582
+ );
583
+ return relay === undefined
318
584
  ? undefined
319
- : this.#backend.circuitAddress(relayAddr, this.peerId());
585
+ : this.#backend.circuitAddress(relay, this.peerId());
320
586
  }
321
587
 
322
- /** Returns the current native reachability state. */
588
+ /** Returns the latest AutoNAT reachability verdict. */
323
589
  reachability(): Reachability {
324
590
  this.#assertOpen();
325
591
  return this.#backend.reachability();
326
592
  }
327
593
 
594
+ /** Returns the authoritative active path to `peerId`, if connected. */
595
+ path(peerId: string): Path | undefined {
596
+ this.#assertOpen();
597
+ const path = this.#backend.path(peerId);
598
+ return path === undefined ? undefined : normalizePath(path);
599
+ }
600
+
328
601
  /** Returns whether the native driver is accepting work. */
329
602
  isRunning(): boolean {
330
603
  return !this.#closed && this.#backend.isRunning();
331
604
  }
332
605
 
333
- /** Selects foreground or idle native polling. */
606
+ /** Selects foreground or idle native polling behavior. */
334
607
  setActive(active: boolean): void {
335
608
  this.#assertOpen();
336
609
  this.#backend.setActive(active);
337
610
  }
338
611
 
339
- /** Subscribes to a pubsub topic. */
612
+ /** Subscribes to a pubsub topic; returns whether the set changed. */
340
613
  subscribe(topic: string): boolean {
341
614
  this.#assertOpen();
342
615
  return this.#backend.subscribe(topic);
343
616
  }
344
617
 
345
- /** Withdraws a pubsub subscription. */
618
+ /** Unsubscribes from a pubsub topic; returns whether the set changed. */
346
619
  unsubscribe(topic: string): boolean {
347
620
  this.#assertOpen();
348
621
  return this.#backend.unsubscribe(topic);
349
622
  }
350
623
 
351
- /** Publishes UTF-8 text or bytes. */
624
+ /** Publishes UTF-8 text or bytes to a subscribed pubsub topic. */
352
625
  publish(topic: string, data: string | Bytes): void {
353
626
  this.#assertOpen();
354
627
  this.#backend.publish(topic, toUint8Array(data));
355
628
  }
356
629
 
357
- /** Sends an explicit ping; the result is emitted as a ping event. */
358
- ping(peerId: string): void {
630
+ /** Registers an application protocol for future inbound streams. */
631
+ addProtocol(protocolId: string): void {
359
632
  this.#assertOpen();
360
- this.#backend.ping(peerId);
633
+ this.#backend.addProtocol(protocolId);
361
634
  }
362
635
 
363
- /** Waits until Identify completes for `peerId`. */
636
+ /** Waits for Identify readiness or rejects if the peer disconnects. */
364
637
  waitPeerReady(
365
638
  peerId: string,
366
- timeoutMs = 65_000
367
- ): Promise<P2pEventByTag<P2pEvent_Tags.PeerReady>> {
368
- const info = this.peerInfo(peerId);
639
+ options: OpOptions = {}
640
+ ): Promise<{
641
+ readonly peerId: string;
642
+ readonly protocols: readonly string[];
643
+ }> {
644
+ const info = this.isPeerReady(peerId) ? this.peerInfo(peerId) : undefined;
369
645
  if (info !== undefined) {
370
- return Promise.resolve({
371
- inner: { peerId, protocols: info.protocols },
372
- tag: P2pEvent_Tags.PeerReady,
373
- });
646
+ return Promise.resolve({ peerId, protocols: info.protocols });
374
647
  }
375
- return this.waitFor(
376
- (
377
- event
378
- ): event is
379
- | P2pEventByTag<P2pEvent_Tags.PeerReady>
380
- | P2pEventByTag<P2pEvent_Tags.ConnectionClosed> =>
381
- "tag" in event &&
382
- (event.tag === P2pEvent_Tags.PeerReady ||
383
- event.tag === P2pEvent_Tags.ConnectionClosed) &&
384
- event.inner.peerId === peerId,
385
- timeoutMs
386
- ).then((event) => {
387
- if (event.tag === P2pEvent_Tags.ConnectionClosed) {
388
- throw new PeerDisconnectedError(peerId);
389
- }
390
- return event;
648
+ const controller = new AbortController();
649
+ if (options.signal?.aborted === true) {
650
+ controller.abort();
651
+ }
652
+ const removeExternalAbort = listenAbort(options.signal, () => {
653
+ controller.abort();
654
+ });
655
+ const ready = this.waitFor("peerReady", {
656
+ ...options,
657
+ predicate: (event) => event.peerId === peerId,
658
+ signal: controller.signal,
659
+ }).then(({ protocols }) => ({ peerId, protocols }));
660
+ const disconnected = this.waitFor("connectionClosed", {
661
+ ...options,
662
+ predicate: (event) =>
663
+ event.peerId === peerId &&
664
+ !this.#backend.connectedPeers().includes(peerId),
665
+ signal: controller.signal,
666
+ }).then(() => {
667
+ throw new PeerDisconnectedError(peerId, "waitPeerReady");
668
+ });
669
+ return Promise.race([ready, disconnected]).finally(() => {
670
+ removeExternalAbort?.();
671
+ controller.abort();
391
672
  });
392
673
  }
393
674
 
394
- /** Waits for the next explicit or keepalive ping RTT for `peerId`. */
395
- waitPingRtt(
396
- peerId: string,
397
- timeoutMs = 65_000
398
- ): Promise<P2pEventByTag<P2pEvent_Tags.PingRttMeasured>> {
399
- return this.waitFor(
400
- (event): event is P2pEventByTag<P2pEvent_Tags.PingRttMeasured> =>
401
- "tag" in event &&
402
- event.tag === P2pEvent_Tags.PingRttMeasured &&
403
- event.inner.peerId === peerId,
404
- timeoutMs
405
- );
406
- }
407
-
408
- /** Registers an application protocol at runtime. */
409
- addProtocol(protocolId: string): void {
675
+ /** Measures round-trip latency in milliseconds, coalescing concurrent calls. */
676
+ ping(peerId: string, options: OpOptions = {}): Promise<number> {
410
677
  this.#assertOpen();
411
- this.#backend.addProtocol(protocolId);
678
+ let operation = this.#pings.get(peerId);
679
+ if (operation === undefined) {
680
+ operation = this.#runPing(peerId);
681
+ this.#pings.set(peerId, operation);
682
+ const current = operation;
683
+ void operation.promise.then(
684
+ () => this.#removePing(peerId, current),
685
+ () => this.#removePing(peerId, current)
686
+ );
687
+ this.#backend.ping(peerId);
688
+ }
689
+ operation.callers += 1;
690
+ const current = operation;
691
+ return withOptions(operation.promise, options).finally(() => {
692
+ current.callers -= 1;
693
+ if (current.callers === 0 && this.#pings.get(peerId) === current) {
694
+ current.cancel(new AbortError("No ping callers remain"));
695
+ this.#pings.delete(peerId);
696
+ }
697
+ });
412
698
  }
413
699
 
414
- /** Opens a negotiated custom-protocol stream. */
415
- openStream(peerId: string, protocolId: string): number {
700
+ /** Opens and negotiates an application-protocol stream. */
701
+ openStream(
702
+ peerId: string,
703
+ protocolId: string,
704
+ options: OpOptions = {}
705
+ ): Promise<Stream> {
416
706
  this.#assertOpen();
417
- return this.#backend.openStream(peerId, protocolId);
707
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
708
+ assertTimeout(timeoutMs);
709
+ if (options.signal?.aborted === true) {
710
+ return Promise.reject(new AbortError());
711
+ }
712
+ let identity: { readonly connId: number; readonly streamId: number };
713
+ try {
714
+ identity = this.#backend.openStream(peerId, protocolId);
715
+ } catch (error) {
716
+ return Promise.reject(
717
+ new OpenStreamError({
718
+ detail: errorMessage(error),
719
+ kind: "synchronous",
720
+ peerId,
721
+ })
722
+ );
723
+ }
724
+ return new Promise((resolve, reject) => {
725
+ const pending: PendingOpen = {
726
+ connId: identity.connId,
727
+ peerId,
728
+ protocolId,
729
+ reject,
730
+ resolve,
731
+ streamId: identity.streamId,
732
+ };
733
+ if (timeoutMs > 0) {
734
+ pending.timer = setTimeout(() => {
735
+ this.#expireOpen(pending, new TimeoutError(timeoutMs));
736
+ }, timeoutMs);
737
+ }
738
+ pending.removeAbort = listenAbort(options.signal, () => {
739
+ this.#expireOpen(pending, new AbortError());
740
+ });
741
+ const key = pendingOpenKey(peerId, identity.connId, identity.streamId);
742
+ const overwritten = this.#pendingOpens.get(key);
743
+ if (overwritten !== undefined) {
744
+ clearPendingOpen(overwritten);
745
+ overwritten.reject(
746
+ new OpenStreamError({
747
+ connId: overwritten.connId,
748
+ detail: "The native backend reused an in-flight stream identity",
749
+ kind: "synchronous",
750
+ peerId: overwritten.peerId,
751
+ streamId: overwritten.streamId,
752
+ })
753
+ );
754
+ }
755
+ this.#pendingOpens.set(key, pending);
756
+ });
418
757
  }
419
758
 
420
- /** Sends UTF-8 text or bytes on a custom-protocol stream. */
421
- sendStream(peerId: string, streamId: number, data: string | Bytes): void {
759
+ /** Starts an advanced NAT-orchestrated connection attempt. */
760
+ startConnect(peerId: string): number {
422
761
  this.#assertOpen();
423
- assertSafeUnsignedInteger(streamId, "streamId");
424
- this.#backend.sendStream(peerId, streamId, toUint8Array(data));
762
+ return this.#rememberConnect(this.#backend.connect(peerId));
425
763
  }
426
764
 
427
- /** Half-closes the local write side of a stream. */
428
- closeStreamWrite(peerId: string, streamId: number): void {
765
+ /** Starts a connection attempt with an explicit ordered address set. */
766
+ startConnectWithAddrs(peerId: string, addresses: readonly string[]): number {
429
767
  this.#assertOpen();
430
- assertSafeUnsignedInteger(streamId, "streamId");
431
- this.#backend.closeStreamWrite(peerId, streamId);
768
+ return this.#rememberConnect(
769
+ this.#backend.connectWithAddrs(peerId, addresses)
770
+ );
432
771
  }
433
772
 
434
- /** Resets a stream while retaining later close events. */
435
- resetStream(peerId: string, streamId: number): void {
773
+ /** Starts a connection attempt from one full peer multiaddress. */
774
+ startConnectAddr(address: string): number {
436
775
  this.#assertOpen();
437
- assertSafeUnsignedInteger(streamId, "streamId");
438
- this.#backend.resetStream(peerId, streamId);
776
+ return this.#rememberConnect(this.#backend.connectAddr(address));
439
777
  }
440
778
 
441
- /** Resets and forgets a stream, suppressing later stream events. */
442
- abandonStream(peerId: string, streamId: number): void {
443
- this.#assertOpen();
444
- assertSafeUnsignedInteger(streamId, "streamId");
445
- this.#backend.abandonStream(peerId, streamId);
779
+ /** Connects to a known peer and resolves with its first usable path. */
780
+ connect(peerId: string, options: OpOptions = {}): Promise<ConnectResult> {
781
+ return this.#primaryConnect(this.startConnect(peerId), options);
446
782
  }
447
783
 
448
- /** Starts a connection attempt and returns its endpoint-local ID. */
449
- connect(peerId: string): number {
450
- this.#assertOpen();
451
- return this.#backend.connect(peerId);
784
+ /** Connects using an explicit ordered address set. */
785
+ connectWithAddrs(
786
+ peerId: string,
787
+ addresses: readonly string[],
788
+ options: OpOptions = {}
789
+ ): Promise<ConnectResult> {
790
+ return this.#primaryConnect(
791
+ this.startConnectWithAddrs(peerId, addresses),
792
+ options
793
+ );
452
794
  }
453
795
 
454
- /** Starts a NAT connection attempt using an explicit ordered address set. */
455
- connectWithAddrs(peerId: string, addresses: readonly string[]): number {
456
- this.#assertOpen();
457
- return this.#backend.connectWithAddrs(peerId, addresses);
796
+ /** Connects using one full peer multiaddress. */
797
+ connectAddr(
798
+ address: string,
799
+ options: OpOptions = {}
800
+ ): Promise<ConnectResult> {
801
+ return this.#primaryConnect(this.startConnectAddr(address), options);
458
802
  }
459
803
 
460
- /** Waits for a connection attempt's first usable path or terminal failure. */
804
+ /** Consumes the terminal result for a `startConnect*` attempt. */
461
805
  waitConnectResult(
462
806
  connectId: number,
463
- timeoutMs = 65_000
464
- ): Promise<
465
- | P2pEventByTag<P2pEvent_Tags.PathEstablished>
466
- | P2pEventByTag<P2pEvent_Tags.ConnectFailed>
467
- > {
468
- assertSafeUnsignedInteger(connectId, "connectId");
807
+ options: OpOptions = {}
808
+ ): Promise<ConnectResult> {
469
809
  this.#assertOpen();
470
- const result = this.#connectResults.get(connectId);
471
- if (result !== undefined) {
472
- return Promise.resolve(result);
473
- }
474
- return this.waitFor(
475
- (
476
- event
477
- ): event is
478
- | P2pEventByTag<P2pEvent_Tags.PathEstablished>
479
- | P2pEventByTag<P2pEvent_Tags.ConnectFailed> =>
480
- "tag" in event &&
481
- (event.tag === P2pEvent_Tags.PathEstablished ||
482
- event.tag === P2pEvent_Tags.ConnectFailed) &&
483
- event.inner.connectId === connectId,
484
- timeoutMs
485
- );
810
+ assertId(connectId, "connectId");
811
+ const attempt = this.#connects.get(connectId);
812
+ if (attempt === undefined || attempt.waiting) {
813
+ return Promise.reject(new ConnectResultUnavailableError(connectId));
814
+ }
815
+ if (attempt.terminal !== undefined) {
816
+ this.#connects.delete(connectId);
817
+ this.#terminalConnects.delete(connectId);
818
+ return attempt.terminal.ok
819
+ ? Promise.resolve(attempt.terminal.result)
820
+ : Promise.reject(attempt.terminal.error);
821
+ }
822
+ attempt.waiting = true;
823
+ const result = new Promise<ConnectResult>((resolve, reject) => {
824
+ attempt.resolve = resolve;
825
+ attempt.reject = reject;
826
+ });
827
+ return withOptions(result, options, () => {
828
+ this.cancelConnect(connectId);
829
+ }).finally(() => {
830
+ this.#connects.delete(connectId);
831
+ });
486
832
  }
487
833
 
488
- /** Starts a direct-address connection attempt. */
489
- connectAddr(address: string): number {
834
+ /** Cancels an in-flight advanced connection attempt. */
835
+ cancelConnect(connectId: number): void {
490
836
  this.#assertOpen();
491
- return this.#backend.connectAddr(address);
837
+ assertId(connectId, "connectId");
838
+ this.#backend.cancelConnect(connectId);
839
+ const attempt = this.#connects.get(connectId);
840
+ attempt?.reject?.(new AbortError("The connection attempt was cancelled"));
841
+ this.#connects.delete(connectId);
842
+ this.#terminalConnects.delete(connectId);
492
843
  }
493
844
 
494
- /** Dials a direct address on every applicable local address family. */
845
+ /** Starts direct transport dials for every applicable local address family. */
495
846
  dial(address: string): number[] {
496
847
  this.#assertOpen();
497
848
  return this.#backend.dial(address);
498
849
  }
499
850
 
500
- /** Dials a direct address using IPv4. */
851
+ /** Starts a direct IPv4 transport dial. */
501
852
  dialIp4(address: string): number {
502
853
  this.#assertOpen();
503
854
  return this.#backend.dialIp4(address);
504
855
  }
505
856
 
506
- /** Dials a direct address using IPv6. */
857
+ /** Starts a direct IPv6 transport dial. */
507
858
  dialIp6(address: string): number {
508
859
  this.#assertOpen();
509
860
  return this.#backend.dialIp6(address);
510
861
  }
511
862
 
512
- /** Suppresses future events for a known connection attempt. */
513
- cancelConnect(id: number): void {
514
- this.#assertOpen();
515
- assertSafeUnsignedInteger(id, "connectId");
516
- this.#backend.cancelConnect(id);
517
- }
518
-
519
- /** Closes an established connection to a peer. */
863
+ /** Closes the active connection to `peerId`. */
520
864
  disconnect(peerId: string): void {
521
865
  this.#assertOpen();
522
866
  this.#backend.disconnect(peerId);
523
867
  }
524
868
 
525
- #assertOpen(): void {
869
+ #rememberConnect(connectId: number): number {
870
+ this.#connects.set(connectId, { waiting: false });
871
+ return connectId;
872
+ }
873
+
874
+ #primaryConnect(
875
+ connectId: number,
876
+ options: OpOptions
877
+ ): Promise<ConnectResult> {
878
+ return this.waitConnectResult(connectId, options);
879
+ }
880
+
881
+ #runPing(peerId: string): PingOperation {
882
+ let settled = false;
883
+ let rejectOperation: (error: unknown) => void = () => {};
884
+ let cleanup: () => void = () => {};
885
+ const promise = new Promise<number>((resolve, reject) => {
886
+ rejectOperation = reject;
887
+ const offRtt = this.on("pingRttMeasured", (event) => {
888
+ if (event.peerId === peerId) {
889
+ finish();
890
+ resolve(event.rttMs);
891
+ }
892
+ });
893
+ const offTimeout = this.on("pingTimeout", (event) => {
894
+ if (event.peerId === peerId) {
895
+ finish();
896
+ reject(new TimeoutError());
897
+ }
898
+ });
899
+ const offClosed = this.on("connectionClosed", (event) => {
900
+ if (
901
+ event.peerId === peerId &&
902
+ !this.#backend.connectedPeers().includes(peerId)
903
+ ) {
904
+ finish();
905
+ reject(new PeerDisconnectedError(peerId, "ping"));
906
+ }
907
+ });
908
+ cleanup = () => {
909
+ offRtt();
910
+ offTimeout();
911
+ offClosed();
912
+ };
913
+ const finish = () => {
914
+ if (!settled) {
915
+ settled = true;
916
+ cleanup();
917
+ }
918
+ };
919
+ });
920
+ return {
921
+ callers: 0,
922
+ cancel: (error) => {
923
+ if (!settled) {
924
+ settled = true;
925
+ cleanup();
926
+ rejectOperation(error);
927
+ }
928
+ },
929
+ promise,
930
+ };
931
+ }
932
+
933
+ #removePing(peerId: string, operation: PingOperation): void {
934
+ if (this.#pings.get(peerId) === operation) {
935
+ this.#pings.delete(peerId);
936
+ }
937
+ }
938
+
939
+ #handleQueueOverflow(): void {
940
+ const error = new EventQueueOverflowError();
941
+ for (const waiter of [...this.#waiters]) {
942
+ this.#settleWaiter(waiter, error);
943
+ }
944
+ for (const ping of this.#pings.values()) {
945
+ ping.cancel(error);
946
+ }
947
+ this.#pings.clear();
948
+ for (const [connectId, attempt] of [...this.#connects]) {
949
+ if (attempt.terminal === undefined) {
950
+ attempt.reject?.(error);
951
+ this.#connects.delete(connectId);
952
+ this.#terminalConnects.delete(connectId);
953
+ }
954
+ }
955
+ for (const pending of this.#pendingOpens.values()) {
956
+ clearPendingOpen(pending);
957
+ pending.reject(error);
958
+ try {
959
+ this.#backend.abandonStream(pending.peerId, pending.streamId);
960
+ } catch {
961
+ // The operation is already failed; native cleanup is best effort.
962
+ }
963
+ }
964
+ this.#pendingOpens.clear();
965
+ }
966
+
967
+ #enqueueNative(event: P2pEvent): void {
526
968
  if (this.#closed) {
527
- throw new ClosedError();
969
+ return;
528
970
  }
971
+ if (this.#queue.push({ event, source: "native" }) !== undefined) {
972
+ this.#dropped += 1;
973
+ this.#handleQueueOverflow();
974
+ }
975
+ this.#scheduleFlush();
529
976
  }
530
977
 
531
- #enqueue(event: P2pEvent): void {
978
+ #enqueueHigh(
979
+ type: "handlerError",
980
+ payload: Minip2pCatchAllEventMap["handlerError"]
981
+ ): void {
532
982
  if (this.#closed) {
533
983
  return;
534
984
  }
535
- this.#overflowDropped += this.#queue.push(event);
985
+ if (this.#queue.push({ payload, source: "high", type }) !== undefined) {
986
+ this.#dropped += 1;
987
+ this.#handleQueueOverflow();
988
+ }
536
989
  this.#scheduleFlush();
537
990
  }
538
991
 
@@ -552,27 +1005,28 @@ export class MiniP2pBase {
552
1005
  }
553
1006
  this.#flushScheduled = false;
554
1007
  let delivered = 0;
555
-
556
- if (this.#overflowDropped > 0) {
557
- const dropped = this.#overflowDropped;
558
- this.#overflowDropped = 0;
559
- this.#dispatch({ dropped, type: "queueOverflow" });
1008
+ if (this.#dropped > 0) {
1009
+ const dropped = this.#dropped;
1010
+ this.#dropped = 0;
1011
+ this.#dispatch("queueOverflow", { dropped }, { dropped });
560
1012
  delivered += 1;
561
1013
  }
562
-
563
- while (delivered < FLUSH_BATCH) {
564
- const event = this.#queue.shift();
565
- if (event === undefined) {
1014
+ while (delivered < EVENT_FLUSH_BATCH) {
1015
+ const item = this.#queue.shift();
1016
+ if (item === undefined) {
566
1017
  break;
567
1018
  }
568
- this.#dispatch(event);
1019
+ if (item.source === "native") {
1020
+ this.#dispatchNative(item.event);
1021
+ } else {
1022
+ this.#dispatch(item.type, item.payload, item.payload);
1023
+ }
569
1024
  delivered += 1;
570
1025
  if (this.#closed) {
571
1026
  return;
572
1027
  }
573
1028
  }
574
-
575
- if (this.#queue.size > 0 || this.#overflowDropped > 0) {
1029
+ if (this.#queue.length > 0) {
576
1030
  this.#flushScheduled = true;
577
1031
  setTimeout(() => {
578
1032
  this.#flush();
@@ -580,71 +1034,606 @@ export class MiniP2pBase {
580
1034
  }
581
1035
  }
582
1036
 
583
- #dispatch(event: MiniP2pEvent): void {
1037
+ #dispatchNative(event: P2pEvent): void {
1038
+ if (event.tag === P2pEvent_Tags.DriverFailed) {
1039
+ const failure = new DriverFailedError(
1040
+ event.inner.kind,
1041
+ event.inner.detail
1042
+ );
1043
+ this.#dispatch("driverFailed", event.inner, event.inner);
1044
+ this.#teardown({ error: failure, reason: "driverFailed" }, failure);
1045
+ return;
1046
+ }
1047
+
1048
+ if (event.tag === P2pEvent_Tags.StreamReady) {
1049
+ this.#streamReady(event.inner);
1050
+ return;
1051
+ }
1052
+ if (
1053
+ event.tag === P2pEvent_Tags.StreamData ||
1054
+ event.tag === P2pEvent_Tags.StreamRemoteWriteClosed ||
1055
+ event.tag === P2pEvent_Tags.StreamClosed
1056
+ ) {
1057
+ this.#streamEvent(event);
1058
+ return;
1059
+ }
1060
+ if (event.tag === P2pEvent_Tags.EndpointError) {
1061
+ this.#correlateOpenError(event.inner);
1062
+ }
1063
+ if (event.tag === P2pEvent_Tags.ConnectionClosed) {
1064
+ this.#connectionClosed(event.inner.peerId, event.inner.connId);
1065
+ }
584
1066
  if (
585
- "tag" in event &&
586
- (event.tag === P2pEvent_Tags.PathEstablished ||
587
- event.tag === P2pEvent_Tags.ConnectFailed)
1067
+ event.tag === P2pEvent_Tags.PathEstablished ||
1068
+ event.tag === P2pEvent_Tags.ConnectFailed
588
1069
  ) {
589
- this.#connectResults.set(event.inner.connectId, event);
1070
+ this.#connectTerminal(event);
590
1071
  }
591
1072
 
592
- if ("tag" in event && event.tag === P2pEvent_Tags.DriverFailed) {
593
- this.#terminateDriver(event);
594
- return;
1073
+ const normalized = normalizeEvent(event);
1074
+ if (normalized !== undefined) {
1075
+ this.#dispatch(
1076
+ normalized.type as never,
1077
+ normalized.payload as never,
1078
+ normalized.payload as never
1079
+ );
595
1080
  }
1081
+ }
596
1082
 
1083
+ #dispatch<Kind extends EventKind>(
1084
+ type: Kind,
1085
+ payload: Minip2pNamedEventMap[Kind],
1086
+ catchPayload: Kind extends keyof Minip2pCatchAllEventMap
1087
+ ? Minip2pCatchAllEventMap[Kind]
1088
+ : never
1089
+ ): boolean {
1090
+ let claimed = false;
1091
+ const result = eventResult(type, payload);
597
1092
  for (const waiter of [...this.#waiters]) {
598
- let matched: boolean;
1093
+ if (waiter.type !== type) {
1094
+ continue;
1095
+ }
1096
+ let matched = false;
599
1097
  try {
600
- matched = waiter.predicate(event);
1098
+ matched = waiter.predicate(result as never);
601
1099
  } catch (error) {
602
- this.#waiters.delete(waiter);
603
- clearWaiterTimer(waiter);
604
- waiter.reject(asError(error));
1100
+ this.#settleWaiter(waiter, error);
605
1101
  continue;
606
1102
  }
607
1103
  if (matched) {
1104
+ claimed = true;
608
1105
  this.#waiters.delete(waiter);
609
- clearWaiterTimer(waiter);
610
- waiter.resolve(event);
1106
+ clearTimeout(waiter.timer);
1107
+ waiter.removeAbort?.();
1108
+ waiter.resolve(result as never);
611
1109
  }
612
1110
  }
613
1111
 
614
- for (const handler of [...this.#handlers]) {
1112
+ const handlers = [...(this.#named.get(type) ?? [])];
1113
+ for (const handler of handlers) {
615
1114
  try {
616
- handler(event);
617
- } catch {
618
- // One host handler cannot interrupt fan-out or unwind into Rust.
1115
+ handler(payload as AnyPayload);
1116
+ if (type === "stream") {
1117
+ claimed = true;
1118
+ }
1119
+ } catch (error) {
1120
+ this.#handlerFailed(type, payload, error);
1121
+ }
1122
+ }
1123
+ if (type !== "stream") {
1124
+ const catchEvent = eventResult(
1125
+ type as keyof Minip2pCatchAllEventMap,
1126
+ catchPayload as Minip2pCatchAllEventMap[keyof Minip2pCatchAllEventMap]
1127
+ ) as Minip2pEvent;
1128
+ for (const handler of [...this.#catchAll]) {
1129
+ try {
1130
+ handler(catchEvent);
1131
+ } catch (error) {
1132
+ this.#handlerFailed(type, payload, error);
1133
+ }
619
1134
  }
620
1135
  }
1136
+ return claimed;
621
1137
  }
622
1138
 
623
- #terminateDriver(event: P2pEventByTag<P2pEvent_Tags.DriverFailed>): void {
624
- this.#closed = true;
625
- this.#queue.clear();
626
- this.#connectResults.clear();
627
- this.#overflowDropped = 0;
628
- const handlers = [...this.#handlers];
629
- this.#handlers.clear();
630
- const failure = new DriverFailedError(event.inner.kind, event.inner.detail);
631
- for (const waiter of this.#waiters) {
632
- clearWaiterTimer(waiter);
633
- waiter.reject(failure);
1139
+ #handlerFailed(type: EventKind, payload: AnyPayload, error: unknown): void {
1140
+ if (type === "handlerError") {
1141
+ return;
634
1142
  }
635
- this.#waiters.clear();
1143
+ this.#enqueueHigh("handlerError", {
1144
+ error,
1145
+ eventType: type,
1146
+ metadata:
1147
+ type === "stream"
1148
+ ? { ...streamMeta(payload as Stream) }
1149
+ : safeMetadata(payload),
1150
+ });
1151
+ }
636
1152
 
637
- for (const handler of handlers) {
1153
+ #streamReady(meta: InboundStreamMeta): void {
1154
+ const key = streamKey(meta.peerId, meta.connId, meta.streamId);
1155
+ const stream = new Stream(this.#backend, meta, () => {
1156
+ this.#streams.delete(key);
1157
+ });
1158
+ this.#streams.set(key, stream);
1159
+ const pendingKey = pendingOpenKey(meta.peerId, meta.connId, meta.streamId);
1160
+ const pending = this.#pendingOpens.get(pendingKey);
1161
+ if (pending !== undefined && meta.initiatedLocally) {
1162
+ this.#pendingOpens.delete(pendingKey);
1163
+ clearPendingOpen(pending);
1164
+ pending.resolve(stream);
1165
+ return;
1166
+ }
1167
+ if (meta.initiatedLocally) {
1168
+ stream.abandon();
1169
+ return;
1170
+ }
1171
+ const claimed = this.#dispatch("stream", stream, undefined as never);
1172
+ const inbound = streamMeta(stream);
1173
+ this.#dispatchCatchOnly("inboundStream", inbound);
1174
+ if (!claimed) {
1175
+ stream.abandon();
1176
+ }
1177
+ }
1178
+
1179
+ #dispatchCatchOnly<Kind extends keyof Minip2pCatchAllEventMap>(
1180
+ type: Kind,
1181
+ payload: Minip2pCatchAllEventMap[Kind]
1182
+ ): void {
1183
+ const event = eventResult(type, payload) as unknown as Minip2pEvent;
1184
+ for (const handler of [...this.#catchAll]) {
638
1185
  try {
639
1186
  handler(event);
640
- } catch {
641
- // One host handler cannot interrupt fan-out or unwind into Rust.
1187
+ } catch (error) {
1188
+ this.#enqueueHigh("handlerError", {
1189
+ error,
1190
+ eventType: type,
1191
+ metadata: safeMetadata(payload),
1192
+ });
1193
+ }
1194
+ }
1195
+ }
1196
+
1197
+ #streamEvent(
1198
+ event: Extract<
1199
+ P2pEvent,
1200
+ {
1201
+ readonly tag:
1202
+ | typeof P2pEvent_Tags.StreamData
1203
+ | typeof P2pEvent_Tags.StreamRemoteWriteClosed
1204
+ | typeof P2pEvent_Tags.StreamClosed;
1205
+ }
1206
+ >
1207
+ ): void {
1208
+ const { peerId, connId, streamId } = event.inner;
1209
+ const stream = this.#streams.get(streamKey(peerId, connId, streamId));
1210
+ if (event.tag === P2pEvent_Tags.StreamClosed) {
1211
+ const pendingKey = pendingOpenKey(peerId, connId, streamId);
1212
+ const pending = this.#pendingOpens.get(pendingKey);
1213
+ if (pending !== undefined) {
1214
+ this.#pendingOpens.delete(pendingKey);
1215
+ clearPendingOpen(pending);
1216
+ pending.reject(new StreamClosedError());
1217
+ }
1218
+ stream?.terminal();
1219
+ } else if (event.tag === P2pEvent_Tags.StreamData) {
1220
+ stream?.receive(event.inner.data);
1221
+ } else {
1222
+ stream?.remoteWriteClosed();
1223
+ }
1224
+ }
1225
+
1226
+ #correlateOpenError(
1227
+ error: Extract<
1228
+ P2pEvent,
1229
+ { readonly tag: typeof P2pEvent_Tags.EndpointError }
1230
+ >["inner"]
1231
+ ): void {
1232
+ if (error.streamId === undefined) {
1233
+ return;
1234
+ }
1235
+ const candidates = [...this.#pendingOpens.values()].filter(
1236
+ (pending) =>
1237
+ pending.streamId === error.streamId &&
1238
+ (error.peerId === undefined || error.peerId === pending.peerId) &&
1239
+ (error.connId === undefined || error.connId === pending.connId)
1240
+ );
1241
+ if (candidates.length !== 1) {
1242
+ return;
1243
+ }
1244
+ const [pending] = candidates;
1245
+ if (pending === undefined) {
1246
+ return;
1247
+ }
1248
+ this.#pendingOpens.delete(
1249
+ pendingOpenKey(pending.peerId, pending.connId, pending.streamId)
1250
+ );
1251
+ clearPendingOpen(pending);
1252
+ pending.reject(
1253
+ new OpenStreamError({
1254
+ connId: error.connId,
1255
+ detail: error.detail,
1256
+ kind: error.kind,
1257
+ peerId: pending.peerId,
1258
+ streamId: error.streamId,
1259
+ })
1260
+ );
1261
+ }
1262
+
1263
+ #connectionClosed(peerId: string, connId: number): void {
1264
+ for (const [key, stream] of [...this.#streams]) {
1265
+ if (stream.peerId === peerId && stream.connId === connId) {
1266
+ stream.terminal(new PeerDisconnectedError(peerId, "stream"));
1267
+ this.#streams.delete(key);
1268
+ }
1269
+ }
1270
+ if (!this.#backend.connectedPeers().includes(peerId)) {
1271
+ for (const pending of [...this.#pendingOpens.values()]) {
1272
+ if (pending.peerId === peerId) {
1273
+ this.#pendingOpens.delete(
1274
+ pendingOpenKey(pending.peerId, pending.connId, pending.streamId)
1275
+ );
1276
+ clearPendingOpen(pending);
1277
+ pending.reject(new PeerDisconnectedError(peerId, "openStream"));
1278
+ }
1279
+ }
1280
+ }
1281
+ }
1282
+
1283
+ #connectTerminal(
1284
+ event: Extract<
1285
+ P2pEvent,
1286
+ {
1287
+ readonly tag:
1288
+ | typeof P2pEvent_Tags.PathEstablished
1289
+ | typeof P2pEvent_Tags.ConnectFailed;
1290
+ }
1291
+ >
1292
+ ): void {
1293
+ const attempt = this.#connects.get(event.inner.connectId);
1294
+ if (attempt === undefined) {
1295
+ return;
1296
+ }
1297
+ const terminal: ConnectTerminal =
1298
+ event.tag === P2pEvent_Tags.PathEstablished
1299
+ ? {
1300
+ ok: true,
1301
+ result: {
1302
+ connectId: event.inner.connectId,
1303
+ path: normalizePath(event.inner.path),
1304
+ peerId: event.inner.peerId,
1305
+ },
1306
+ }
1307
+ : {
1308
+ error: new ConnectFailedError(
1309
+ event.inner.connectId,
1310
+ event.inner.peerId,
1311
+ event.inner.kind,
1312
+ event.inner.detail
1313
+ ),
1314
+ ok: false,
1315
+ };
1316
+ if (attempt.waiting) {
1317
+ if (terminal.ok) {
1318
+ attempt.resolve?.(terminal.result);
1319
+ } else {
1320
+ attempt.reject?.(terminal.error);
1321
+ }
1322
+ } else {
1323
+ attempt.terminal = terminal;
1324
+ this.#terminalConnects.delete(event.inner.connectId);
1325
+ this.#terminalConnects.add(event.inner.connectId);
1326
+ while (this.#terminalConnects.size > CONNECT_TERMINAL_CAP) {
1327
+ const oldest = this.#terminalConnects.values().next().value;
1328
+ if (oldest === undefined) {
1329
+ break;
1330
+ }
1331
+ this.#terminalConnects.delete(oldest);
1332
+ this.#connects.delete(oldest);
642
1333
  }
643
1334
  }
644
- this.#backend.close();
1335
+ }
1336
+
1337
+ #expireOpen(pending: PendingOpen, error: unknown): void {
1338
+ const key = pendingOpenKey(
1339
+ pending.peerId,
1340
+ pending.connId,
1341
+ pending.streamId
1342
+ );
1343
+ if (this.#pendingOpens.get(key) !== pending) {
1344
+ return;
1345
+ }
1346
+ this.#pendingOpens.delete(key);
1347
+ clearPendingOpen(pending);
1348
+ pending.reject(error);
1349
+ try {
1350
+ this.#backend.abandonStream(pending.peerId, pending.streamId);
1351
+ } catch {
1352
+ // Cleanup failure must not replace the caller's timeout or abort.
1353
+ }
1354
+ }
1355
+
1356
+ #settleWaiter(waiter: EventWaiter, error: unknown): void {
1357
+ this.#waiters.delete(waiter);
1358
+ clearTimeout(waiter.timer);
1359
+ waiter.removeAbort?.();
1360
+ waiter.reject(error);
1361
+ }
1362
+
1363
+ #teardown(reason: CloseReason, error: Error): void {
1364
+ if (this.#closed) {
1365
+ return;
1366
+ }
1367
+ this.#closed = true;
1368
+ const closeHandlers = [...this.#closeHandlers];
1369
+ this.#closeHandlers.clear();
1370
+ this.#queue.clear();
1371
+ this.#dropped = 0;
1372
+ this.#named.clear();
1373
+ this.#catchAll.clear();
1374
+ for (const waiter of [...this.#waiters]) {
1375
+ this.#settleWaiter(waiter, error);
1376
+ }
1377
+ for (const attempt of this.#connects.values()) {
1378
+ attempt.reject?.(error);
1379
+ }
1380
+ this.#connects.clear();
1381
+ this.#terminalConnects.clear();
1382
+ for (const pending of this.#pendingOpens.values()) {
1383
+ clearPendingOpen(pending);
1384
+ pending.reject(error);
1385
+ }
1386
+ this.#pendingOpens.clear();
1387
+ for (const stream of this.#streams.values()) {
1388
+ stream.terminal(error);
1389
+ }
1390
+ this.#streams.clear();
1391
+ for (const ping of this.#pings.values()) {
1392
+ ping.cancel(error);
1393
+ }
1394
+ this.#pings.clear();
1395
+ try {
1396
+ this.#backend.close();
1397
+ } finally {
1398
+ for (const handler of closeHandlers) {
1399
+ try {
1400
+ handler(reason);
1401
+ } catch {
1402
+ // Close notification is outside the now-closed event queue.
1403
+ }
1404
+ }
1405
+ }
1406
+ }
1407
+
1408
+ #assertOpen(): void {
1409
+ if (this.#closed) {
1410
+ throw new ClosedError();
1411
+ }
645
1412
  }
646
1413
  }
647
1414
 
1415
+ function normalizeEvent(
1416
+ event: Exclude<
1417
+ P2pEvent,
1418
+ {
1419
+ readonly tag:
1420
+ | typeof P2pEvent_Tags.DriverFailed
1421
+ | typeof P2pEvent_Tags.StreamReady
1422
+ | typeof P2pEvent_Tags.StreamData
1423
+ | typeof P2pEvent_Tags.StreamRemoteWriteClosed
1424
+ | typeof P2pEvent_Tags.StreamClosed;
1425
+ }
1426
+ >
1427
+ ):
1428
+ | {
1429
+ type: Exclude<
1430
+ EventKind,
1431
+ "stream" | "queueOverflow" | "handlerError" | "driverFailed"
1432
+ >;
1433
+ payload: AnyPayload;
1434
+ }
1435
+ | undefined {
1436
+ const names: Partial<Record<string, EventKind>> = {
1437
+ [P2pEvent_Tags.EventsDropped]: "eventsDropped",
1438
+ [P2pEvent_Tags.ConnectionEstablished]: "connectionEstablished",
1439
+ [P2pEvent_Tags.ConnectionClosed]: "connectionClosed",
1440
+ [P2pEvent_Tags.PeerReady]: "peerReady",
1441
+ [P2pEvent_Tags.IdentifyReceived]: "identifyReceived",
1442
+ [P2pEvent_Tags.PingRttMeasured]: "pingRttMeasured",
1443
+ [P2pEvent_Tags.PingTimeout]: "pingTimeout",
1444
+ [P2pEvent_Tags.EndpointError]: "endpointError",
1445
+ [P2pEvent_Tags.ReachabilityChanged]: "reachabilityChanged",
1446
+ [P2pEvent_Tags.PublicAddressesChanged]: "publicAddressesChanged",
1447
+ [P2pEvent_Tags.RelayReserved]: "relayReserved",
1448
+ [P2pEvent_Tags.RelayReservationLost]: "relayReservationLost",
1449
+ [P2pEvent_Tags.PathEstablished]: "pathEstablished",
1450
+ [P2pEvent_Tags.PathUpgraded]: "pathUpgraded",
1451
+ [P2pEvent_Tags.HolePunchFailed]: "holePunchFailed",
1452
+ [P2pEvent_Tags.FellBackToRelay]: "fellBackToRelay",
1453
+ [P2pEvent_Tags.ConnectFailed]: "connectFailed",
1454
+ [P2pEvent_Tags.InboundDirectUpgrade]: "inboundDirectUpgrade",
1455
+ [P2pEvent_Tags.Message]: "message",
1456
+ [P2pEvent_Tags.PeerSubscribed]: "peerSubscribed",
1457
+ [P2pEvent_Tags.PeerUnsubscribed]: "peerUnsubscribed",
1458
+ [P2pEvent_Tags.PubsubOutboundFailure]: "pubsubOutboundFailure",
1459
+ [P2pEvent_Tags.PubsubProtocolViolation]: "pubsubProtocolViolation",
1460
+ [P2pEvent_Tags.PeerDiscovered]: "peerDiscovered",
1461
+ [P2pEvent_Tags.PeerUpdated]: "peerUpdated",
1462
+ [P2pEvent_Tags.PeerExpired]: "peerExpired",
1463
+ [P2pEvent_Tags.DiscoveryDialFailed]: "discoveryDialFailed",
1464
+ [P2pEvent_Tags.DiscoveryProtocolViolation]: "discoveryProtocolViolation",
1465
+ };
1466
+ const type = names[event.tag];
1467
+ if (type === undefined) {
1468
+ return undefined;
1469
+ }
1470
+ let payload: unknown = event.inner;
1471
+ if (event.tag === P2pEvent_Tags.PathEstablished) {
1472
+ payload = { ...event.inner, path: normalizePath(event.inner.path) };
1473
+ } else if (event.tag === P2pEvent_Tags.PathUpgraded) {
1474
+ payload = {
1475
+ ...event.inner,
1476
+ from: normalizePath(event.inner.from),
1477
+ to: normalizePath(event.inner.to),
1478
+ };
1479
+ }
1480
+ return { payload: payload as AnyPayload, type: type as never };
1481
+ }
1482
+
1483
+ function normalizePath(path: PathKind): Path {
1484
+ switch (path.tag) {
1485
+ case PathKind_Tags.DirectDialed: {
1486
+ return { kind: "directDialed" };
1487
+ }
1488
+ case PathKind_Tags.DirectPunched: {
1489
+ return { kind: "directPunched" };
1490
+ }
1491
+ case PathKind_Tags.Relayed: {
1492
+ return { kind: "relayed", relayPeerId: path.inner.relayPeerId };
1493
+ }
1494
+ }
1495
+ }
1496
+
1497
+ function streamKey(peerId: string, connId: number, streamId: number): string {
1498
+ return `${peerId}\u0000${connId}\u0000${streamId}`;
1499
+ }
1500
+
1501
+ function pendingOpenKey(
1502
+ peerId: string,
1503
+ connId: number,
1504
+ streamId: number
1505
+ ): string {
1506
+ return streamKey(peerId, connId, streamId);
1507
+ }
1508
+
1509
+ function streamMeta(stream: Stream): InboundStreamMeta {
1510
+ return {
1511
+ connId: stream.connId,
1512
+ initiatedLocally: stream.initiatedLocally,
1513
+ peerId: stream.peerId,
1514
+ protocolId: stream.protocolId,
1515
+ streamId: stream.streamId,
1516
+ };
1517
+ }
1518
+
1519
+ function safeMetadata(payload: unknown): Record<string, unknown> {
1520
+ if (payload === null || typeof payload !== "object") {
1521
+ return {};
1522
+ }
1523
+ const metadata: Record<string, unknown> = {};
1524
+ for (const [key, value] of Object.entries(payload)) {
1525
+ if (
1526
+ typeof value === "string" ||
1527
+ typeof value === "number" ||
1528
+ typeof value === "boolean" ||
1529
+ value === undefined
1530
+ ) {
1531
+ metadata[key] = value;
1532
+ } else if (
1533
+ Array.isArray(value) &&
1534
+ value.every((item) => typeof item === "string")
1535
+ ) {
1536
+ metadata[key] = [...value];
1537
+ }
1538
+ }
1539
+ return metadata;
1540
+ }
1541
+
1542
+ function eventResult<Kind extends string, Payload>(
1543
+ type: Kind,
1544
+ payload: Payload
1545
+ ): { readonly type: Kind } & Payload {
1546
+ if (payload instanceof Stream) {
1547
+ Object.defineProperty(payload, "type", {
1548
+ configurable: true,
1549
+ enumerable: false,
1550
+ value: type,
1551
+ });
1552
+ return payload as unknown as { readonly type: Kind } & Payload;
1553
+ }
1554
+ if (typeof payload === "object" && payload !== null) {
1555
+ return { type, ...payload };
1556
+ }
1557
+ return { type } as { readonly type: Kind } & Payload;
1558
+ }
1559
+
1560
+ function subscribe<Value>(set: Set<Value>, value: Value): Unsubscribe {
1561
+ set.add(value);
1562
+ let active = true;
1563
+ return () => {
1564
+ if (active) {
1565
+ active = false;
1566
+ set.delete(value);
1567
+ }
1568
+ };
1569
+ }
1570
+
1571
+ function listenAbort(
1572
+ signal: AbortSignal | undefined,
1573
+ handler: () => void
1574
+ ): (() => void) | undefined {
1575
+ if (signal === undefined) {
1576
+ return undefined;
1577
+ }
1578
+ signal.addEventListener("abort", handler, { once: true });
1579
+ return () => {
1580
+ signal.removeEventListener("abort", handler);
1581
+ };
1582
+ }
1583
+
1584
+ function withOptions<Value>(
1585
+ promise: Promise<Value>,
1586
+ options: OpOptions,
1587
+ onCancel?: () => void
1588
+ ): Promise<Value> {
1589
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1590
+ assertTimeout(timeoutMs);
1591
+ if (options.signal?.aborted === true) {
1592
+ onCancel?.();
1593
+ return Promise.reject(new AbortError());
1594
+ }
1595
+ return new Promise((resolve, reject) => {
1596
+ let settled = false;
1597
+ let timer: ReturnType<typeof setTimeout> | undefined;
1598
+ const finish = (callback: () => void) => {
1599
+ if (settled) {
1600
+ return;
1601
+ }
1602
+ settled = true;
1603
+ clearTimeout(timer);
1604
+ removeAbort?.();
1605
+ callback();
1606
+ };
1607
+ const removeAbort = listenAbort(options.signal, () => {
1608
+ finish(() => {
1609
+ onCancel?.();
1610
+ reject(new AbortError());
1611
+ });
1612
+ });
1613
+ if (timeoutMs > 0) {
1614
+ timer = setTimeout(() => {
1615
+ finish(() => {
1616
+ onCancel?.();
1617
+ reject(new TimeoutError(timeoutMs));
1618
+ });
1619
+ }, timeoutMs);
1620
+ }
1621
+ void promise.then(
1622
+ (value) => {
1623
+ finish(() => resolve(value));
1624
+ },
1625
+ (error: unknown) => {
1626
+ finish(() => reject(error));
1627
+ }
1628
+ );
1629
+ });
1630
+ }
1631
+
1632
+ function clearPendingOpen(pending: PendingOpen): void {
1633
+ clearTimeout(pending.timer);
1634
+ pending.removeAbort?.();
1635
+ }
1636
+
648
1637
  function toUint8Array(value: string | Bytes): Uint8Array {
649
1638
  if (typeof value === "string") {
650
1639
  return new TextEncoder().encode(value);
@@ -652,18 +1641,16 @@ function toUint8Array(value: string | Bytes): Uint8Array {
652
1641
  return value instanceof Uint8Array ? value : new Uint8Array(value);
653
1642
  }
654
1643
 
655
- function assertSafeUnsignedInteger(value: number, name: string): void {
1644
+ function assertId(value: number, name: string): void {
656
1645
  if (!Number.isSafeInteger(value) || value < 0) {
657
1646
  throw new RangeError(`${name} must be a non-negative safe integer`);
658
1647
  }
659
1648
  }
660
1649
 
661
- function clearWaiterTimer(waiter: Waiter): void {
662
- if (waiter.timer !== undefined) {
663
- clearTimeout(waiter.timer);
664
- }
1650
+ function assertTimeout(timeoutMs: number): void {
1651
+ assertId(timeoutMs, "timeoutMs");
665
1652
  }
666
1653
 
667
- function asError(error: unknown): Error {
668
- return error instanceof Error ? error : new Error(String(error));
1654
+ function errorMessage(error: unknown): string {
1655
+ return error instanceof Error ? error.message : String(error);
669
1656
  }