@highway1/core 0.1.48 → 0.1.53

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/dist/index.js CHANGED
@@ -1,58 +1,21 @@
1
- import 'path';
2
- import 'url';
3
1
  import * as ed25519 from '@noble/ed25519';
4
2
  import { base58btc } from 'multiformats/bases/base58';
5
- import { createLibp2p } from 'libp2p';
6
- import { tcp } from '@libp2p/tcp';
7
- import { setMaxListeners as setMaxListeners$1 } from 'events';
8
- import { CODE_IP6, CODE_IP4, CODE_P2P, CODE_QUIC_V1, CODE_QUIC, CODE_UDP, CODE_TCP, CODE_DNS4, CODE_DNS6, CODE_DNSADDR, CODE_DNS, CODE_IPCIDR, CODE_IP6ZONE, CODE_WS, CODE_SNI, CODE_TLS, CODE_WSS, CODE_CERTHASH, CODE_WEBRTC_DIRECT, CODE_WEBTRANSPORT, CODE_P2P_CIRCUIT, CODE_WEBRTC, CODE_HTTP, CODE_HTTPS, CODE_MEMORY, CODE_UNIX, multiaddr } from '@multiformats/multiaddr';
9
- import http from 'http';
10
- import https from 'https';
11
- import net, { isIPv4, isIPv6 } from 'net';
12
- import { allocUnsafe, alloc } from 'uint8arrays/alloc';
13
- import { concat } from 'uint8arrays/concat';
14
- import { equals } from 'uint8arrays/equals';
15
- import os from 'os';
16
- import * as ws from 'ws';
17
- import { fromString } from 'uint8arrays/from-string';
18
- import { noise } from '@chainsafe/libp2p-noise';
19
- import { mplex } from '@libp2p/mplex';
20
- import { kadDHT, passthroughMapper } from '@libp2p/kad-dht';
21
- import { bootstrap } from '@libp2p/bootstrap';
22
- import { identify } from '@libp2p/identify';
23
- import { ping } from '@libp2p/ping';
24
- import { circuitRelayTransport, circuitRelayServer } from '@libp2p/circuit-relay-v2';
25
- import Ajv from 'ajv';
3
+ import { WebSocket } from 'ws';
26
4
  import { encode, decode } from 'cbor-x';
27
- import { toString } from 'uint8arrays/to-string';
5
+ import Ajv from 'ajv';
28
6
  import lunr from 'lunr';
29
7
  import Fuse from 'fuse.js';
30
- import { peerIdFromString } from '@libp2p/peer-id';
31
8
  import { Level } from 'level';
32
9
  import { sha256 } from '@noble/hashes/sha256';
33
10
  import { bytesToHex } from '@noble/hashes/utils';
34
11
 
35
- var __getOwnPropNames = Object.getOwnPropertyNames;
36
- var __esm = (fn, res) => function __init() {
37
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
38
- };
39
- var init_esm_shims = __esm({
40
- "../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js"() {
41
- }
42
- });
43
-
44
- // src/index.ts
45
- init_esm_shims();
46
-
47
12
  // src/identity/keys.ts
48
- init_esm_shims();
49
13
 
50
14
  // src/utils/errors.ts
51
- init_esm_shims();
52
15
  var ClawiverseError = class extends Error {
53
- constructor(message, code2, details) {
16
+ constructor(message, code, details) {
54
17
  super(message);
55
- this.code = code2;
18
+ this.code = code;
56
19
  this.details = details;
57
20
  this.name = "ClawiverseError";
58
21
  }
@@ -121,9 +84,6 @@ function importKeyPair(exported) {
121
84
  privateKey: new Uint8Array(Buffer.from(exported.privateKey, "hex"))
122
85
  };
123
86
  }
124
-
125
- // src/identity/did.ts
126
- init_esm_shims();
127
87
  function deriveDID(publicKey) {
128
88
  try {
129
89
  const encoded = base58btc.encode(publicKey);
@@ -157,7 +117,6 @@ function validateDID(did) {
157
117
  }
158
118
 
159
119
  // src/identity/signer.ts
160
- init_esm_shims();
161
120
  async function signMessage(payload, privateKey, publicKey) {
162
121
  try {
163
122
  const signature = await sign(payload, privateKey);
@@ -187,2827 +146,360 @@ async function verifyMessage(signedMessage, expectedPublicKey) {
187
146
  }
188
147
  }
189
148
 
190
- // src/transport/node.ts
191
- init_esm_shims();
192
-
193
- // ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/index.js
194
- init_esm_shims();
195
-
196
- // ../../node_modules/.pnpm/@libp2p+interface@3.1.0/node_modules/@libp2p/interface/dist/src/index.js
197
- init_esm_shims();
198
-
199
- // ../../node_modules/.pnpm/@libp2p+interface@3.1.0/node_modules/@libp2p/interface/dist/src/errors.js
200
- init_esm_shims();
201
- var InvalidParametersError = class extends Error {
202
- static name = "InvalidParametersError";
203
- constructor(message = "Invalid parameters") {
204
- super(message);
205
- this.name = "InvalidParametersError";
206
- }
207
- };
208
- var ConnectionFailedError = class extends Error {
209
- static name = "ConnectionFailedError";
210
- constructor(message = "Connection failed") {
211
- super(message);
212
- this.name = "ConnectionFailedError";
213
- }
214
- };
215
- var StreamResetError = class extends Error {
216
- static name = "StreamResetError";
217
- constructor(message = "The stream has been reset") {
218
- super(message);
219
- this.name = "StreamResetError";
220
- }
221
- };
222
- var StreamStateError = class extends Error {
223
- static name = "StreamStateError";
224
- constructor(message = "The stream is in an invalid state") {
225
- super(message);
226
- this.name = "StreamStateError";
227
- }
228
- };
229
- var StreamBufferError = class extends Error {
230
- static name = "StreamBufferError";
231
- constructor(message = "The stream buffer was full") {
232
- super(message);
233
- this.name = "StreamBufferError";
234
- }
235
- };
236
-
237
- // ../../node_modules/.pnpm/@libp2p+interface@3.1.0/node_modules/@libp2p/interface/dist/src/events.js
238
- init_esm_shims();
239
- var StreamMessageEvent = class extends Event {
240
- data;
241
- constructor(data, eventInitDict) {
242
- super("message", eventInitDict);
243
- this.data = data;
244
- }
245
- };
246
- var StreamCloseEvent = class extends Event {
247
- error;
248
- local;
249
- constructor(local, error, eventInitDict) {
250
- super("close", eventInitDict);
251
- this.error = error;
252
- this.local = local;
253
- }
254
- };
255
- var StreamAbortEvent = class extends StreamCloseEvent {
256
- constructor(error, eventInitDict) {
257
- super(true, error, eventInitDict);
258
- }
259
- };
260
- var StreamResetEvent = class extends StreamCloseEvent {
261
- constructor(error, eventInitDict) {
262
- super(false, error, eventInitDict);
263
- }
264
- };
265
-
266
- // ../../node_modules/.pnpm/@libp2p+interface@3.1.0/node_modules/@libp2p/interface/dist/src/transport.js
267
- init_esm_shims();
268
- var transportSymbol = /* @__PURE__ */ Symbol.for("@libp2p/transport");
269
- var FaultTolerance;
270
- (function(FaultTolerance2) {
271
- FaultTolerance2[FaultTolerance2["FATAL_ALL"] = 0] = "FATAL_ALL";
272
- FaultTolerance2[FaultTolerance2["NO_FATAL"] = 1] = "NO_FATAL";
273
- })(FaultTolerance || (FaultTolerance = {}));
274
-
275
- // ../../node_modules/.pnpm/main-event@1.0.1/node_modules/main-event/dist/src/index.js
276
- init_esm_shims();
277
-
278
- // ../../node_modules/.pnpm/main-event@1.0.1/node_modules/main-event/dist/src/events.js
279
- init_esm_shims();
280
- var setMaxListeners = (n, ...eventTargets) => {
281
- try {
282
- setMaxListeners$1(n, ...eventTargets);
283
- } catch {
149
+ // src/utils/logger.ts
150
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
151
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
152
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
153
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
154
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
155
+ return LogLevel2;
156
+ })(LogLevel || {});
157
+ var Logger = class {
158
+ level;
159
+ prefix;
160
+ constructor(prefix, level = 1 /* INFO */) {
161
+ this.prefix = prefix;
162
+ this.level = level;
284
163
  }
285
- };
286
-
287
- // ../../node_modules/.pnpm/main-event@1.0.1/node_modules/main-event/dist/src/index.js
288
- var TypedEventEmitter = class extends EventTarget {
289
- #listeners = /* @__PURE__ */ new Map();
290
- constructor() {
291
- super();
292
- setMaxListeners(Infinity, this);
293
- }
294
- listenerCount(type) {
295
- const listeners = this.#listeners.get(type);
296
- if (listeners == null) {
297
- return 0;
298
- }
299
- return listeners.length;
300
- }
301
- addEventListener(type, listener, options) {
302
- super.addEventListener(type, listener, options);
303
- let list = this.#listeners.get(type);
304
- if (list == null) {
305
- list = [];
306
- this.#listeners.set(type, list);
307
- }
308
- list.push({
309
- callback: listener,
310
- once: (options !== true && options !== false && options?.once) ?? false
311
- });
164
+ setLevel(level) {
165
+ this.level = level;
312
166
  }
313
- removeEventListener(type, listener, options) {
314
- super.removeEventListener(type.toString(), listener ?? null, options);
315
- let list = this.#listeners.get(type);
316
- if (list == null) {
317
- return;
318
- }
319
- list = list.filter(({ callback }) => callback !== listener);
320
- this.#listeners.set(type, list);
321
- }
322
- dispatchEvent(event) {
323
- const result = super.dispatchEvent(event);
324
- let list = this.#listeners.get(event.type);
325
- if (list == null) {
326
- return result;
167
+ debug(message, ...args) {
168
+ if (this.level <= 0 /* DEBUG */) {
169
+ console.debug(`[${this.prefix}] DEBUG:`, message, ...args);
327
170
  }
328
- list = list.filter(({ once }) => !once);
329
- this.#listeners.set(event.type, list);
330
- return result;
331
- }
332
- safeDispatchEvent(type, detail = {}) {
333
- return this.dispatchEvent(new CustomEvent(type, detail));
334
171
  }
335
- };
336
-
337
- // ../../node_modules/.pnpm/@libp2p+interface@3.1.0/node_modules/@libp2p/interface/dist/src/index.js
338
- var serviceCapabilities = /* @__PURE__ */ Symbol.for("@libp2p/service-capabilities");
339
-
340
- // ../../node_modules/.pnpm/@multiformats+multiaddr-matcher@3.0.1/node_modules/@multiformats/multiaddr-matcher/dist/src/index.js
341
- init_esm_shims();
342
-
343
- // ../../node_modules/.pnpm/@multiformats+multiaddr-matcher@3.0.1/node_modules/@multiformats/multiaddr-matcher/dist/src/utils.js
344
- init_esm_shims();
345
- var code = (code2) => {
346
- return {
347
- match: (vals) => {
348
- const component = vals[0];
349
- if (component == null) {
350
- return false;
351
- }
352
- if (component.code !== code2) {
353
- return false;
354
- }
355
- if (component.value != null) {
356
- return false;
357
- }
358
- return vals.slice(1);
359
- }
360
- };
361
- };
362
- var value = (code2, value2) => {
363
- return {
364
- match: (vals) => {
365
- const component = vals[0];
366
- if (component?.code !== code2) {
367
- return false;
368
- }
369
- if (component.value == null) {
370
- return false;
371
- }
372
- if (value2 != null && component.value !== value2) {
373
- return false;
374
- }
375
- return vals.slice(1);
376
- }
377
- };
378
- };
379
- var not = (matcher) => {
380
- return {
381
- match: (vals) => {
382
- const result = matcher.match(vals);
383
- if (result === false) {
384
- return vals;
385
- }
386
- return false;
387
- }
388
- };
389
- };
390
- var optional = (matcher) => {
391
- return {
392
- match: (vals) => {
393
- const result = matcher.match(vals);
394
- if (result === false) {
395
- return vals;
396
- }
397
- return result;
398
- }
399
- };
400
- };
401
- var or = (...matchers) => {
402
- return {
403
- match: (vals) => {
404
- let matches;
405
- for (const matcher of matchers) {
406
- const result = matcher.match(vals);
407
- if (result === false) {
408
- continue;
409
- }
410
- if (matches == null || result.length < matches.length) {
411
- matches = result;
412
- }
413
- }
414
- if (matches == null) {
415
- return false;
416
- }
417
- return matches;
418
- }
419
- };
420
- };
421
- var and = (...matchers) => {
422
- return {
423
- match: (vals) => {
424
- for (const matcher of matchers) {
425
- const result = matcher.match(vals);
426
- if (result === false) {
427
- return false;
428
- }
429
- vals = result;
430
- }
431
- return vals;
432
- }
433
- };
434
- };
435
- function fmt(...matchers) {
436
- function match(ma) {
437
- if (ma == null) {
438
- return false;
439
- }
440
- let parts = ma.getComponents();
441
- for (const matcher of matchers) {
442
- const result = matcher.match(parts);
443
- if (result === false) {
444
- return false;
445
- }
446
- parts = result;
172
+ info(message, ...args) {
173
+ if (this.level <= 1 /* INFO */) {
174
+ console.info(`[${this.prefix}] INFO:`, message, ...args);
447
175
  }
448
- return parts;
449
176
  }
450
- function matches(ma) {
451
- const result = match(ma);
452
- return result !== false;
453
- }
454
- function exactMatch(ma) {
455
- const result = match(ma);
456
- if (result === false) {
457
- return false;
177
+ warn(message, ...args) {
178
+ if (this.level <= 2 /* WARN */) {
179
+ console.warn(`[${this.prefix}] WARN:`, message, ...args);
458
180
  }
459
- return result.length === 0;
460
- }
461
- return {
462
- matchers,
463
- matches,
464
- exactMatch
465
- };
466
- }
467
-
468
- // ../../node_modules/.pnpm/@multiformats+multiaddr-matcher@3.0.1/node_modules/@multiformats/multiaddr-matcher/dist/src/index.js
469
- var _PEER_ID = value(CODE_P2P);
470
- fmt(_PEER_ID);
471
- var _DNS4 = value(CODE_DNS4);
472
- var _DNS6 = value(CODE_DNS6);
473
- var _DNSADDR = value(CODE_DNSADDR);
474
- var _DNS = value(CODE_DNS);
475
- fmt(_DNS4, optional(value(CODE_P2P)));
476
- fmt(_DNS6, optional(value(CODE_P2P)));
477
- fmt(_DNSADDR, optional(value(CODE_P2P)));
478
- fmt(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(value(CODE_P2P)));
479
- var _IP4 = and(value(CODE_IP4), optional(value(CODE_IPCIDR)));
480
- var _IP6 = and(optional(value(CODE_IP6ZONE)), value(CODE_IP6), optional(value(CODE_IPCIDR)));
481
- var _IP = or(_IP4, _IP6);
482
- var _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR);
483
- fmt(or(_IP, and(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(value(CODE_P2P)))));
484
- fmt(_IP4);
485
- fmt(_IP6);
486
- fmt(_IP);
487
- var _TCP = and(_IP_OR_DOMAIN, value(CODE_TCP));
488
- var _UDP = and(_IP_OR_DOMAIN, value(CODE_UDP));
489
- fmt(and(_TCP, optional(value(CODE_P2P))));
490
- fmt(_UDP);
491
- var _QUIC = and(_UDP, code(CODE_QUIC), optional(value(CODE_P2P)));
492
- var _QUIC_V1 = and(_UDP, code(CODE_QUIC_V1), optional(value(CODE_P2P)));
493
- var QUIC_V0_OR_V1 = or(_QUIC, _QUIC_V1);
494
- fmt(_QUIC);
495
- fmt(_QUIC_V1);
496
- var _WEB = or(_IP_OR_DOMAIN, _TCP, _UDP, _QUIC, _QUIC_V1);
497
- var _WebSockets = or(and(_WEB, code(CODE_WS), optional(value(CODE_P2P))));
498
- var WebSockets = fmt(_WebSockets);
499
- var _WebSocketsSecure = or(and(_WEB, code(CODE_WSS), optional(value(CODE_P2P))), and(_WEB, code(CODE_TLS), optional(value(CODE_SNI)), code(CODE_WS), optional(value(CODE_P2P))));
500
- var WebSocketsSecure = fmt(_WebSocketsSecure);
501
- var _WebRTCDirect = and(_UDP, code(CODE_WEBRTC_DIRECT), optional(value(CODE_CERTHASH)), optional(value(CODE_CERTHASH)), optional(value(CODE_P2P)));
502
- fmt(_WebRTCDirect);
503
- var _WebTransport = and(_QUIC_V1, code(CODE_WEBTRANSPORT), optional(value(CODE_CERTHASH)), optional(value(CODE_CERTHASH)), optional(value(CODE_P2P)));
504
- fmt(_WebTransport);
505
- var _P2P = or(_WebSockets, _WebSocketsSecure, and(_TCP, optional(value(CODE_P2P))), and(QUIC_V0_OR_V1, optional(value(CODE_P2P))), and(_IP_OR_DOMAIN, optional(value(CODE_P2P))), _WebRTCDirect, _WebTransport, value(CODE_P2P));
506
- fmt(_P2P);
507
- var _Circuit = and(optional(_P2P), code(CODE_P2P_CIRCUIT), not(code(CODE_WEBRTC)), optional(value(CODE_P2P)));
508
- fmt(_Circuit);
509
- var _WebRTC = or(and(_P2P, code(CODE_P2P_CIRCUIT), code(CODE_WEBRTC), optional(value(CODE_P2P))), and(_P2P, code(CODE_WEBRTC), optional(value(CODE_P2P))), and(code(CODE_WEBRTC), optional(value(CODE_P2P))));
510
- fmt(_WebRTC);
511
- var _HTTP = or(and(_IP_OR_DOMAIN, value(CODE_TCP), code(CODE_HTTP), optional(value(CODE_P2P))), and(_IP_OR_DOMAIN, code(CODE_HTTP), optional(value(CODE_P2P))));
512
- fmt(_HTTP);
513
- var _HTTPS = and(_IP_OR_DOMAIN, or(and(value(CODE_TCP, "443"), code(CODE_HTTP)), and(value(CODE_TCP), code(CODE_HTTPS)), and(value(CODE_TCP), code(CODE_TLS), code(CODE_HTTP)), and(code(CODE_TLS), code(CODE_HTTP)), code(CODE_TLS), code(CODE_HTTPS)), optional(value(CODE_P2P)));
514
- fmt(_HTTPS);
515
- var _Memory = or(and(value(CODE_MEMORY), optional(value(CODE_P2P))));
516
- fmt(_Memory);
517
- var _Unix = or(and(value(CODE_UNIX), optional(value(CODE_P2P))));
518
- fmt(_Unix);
519
-
520
- // ../../node_modules/.pnpm/@multiformats+multiaddr-to-uri@12.0.0/node_modules/@multiformats/multiaddr-to-uri/dist/src/index.js
521
- init_esm_shims();
522
- var ASSUME_HTTP_CODES = [
523
- CODE_TCP,
524
- CODE_DNS,
525
- CODE_DNSADDR,
526
- CODE_DNS4,
527
- CODE_DNS6
528
- ];
529
- function extractSNI(ma) {
530
- return extractTuple("sni", ma)?.value;
531
- }
532
- function extractPort(ma) {
533
- const port = extractTuple("tcp", ma)?.value;
534
- if (port == null) {
535
- return "";
536
181
  }
537
- return `:${port}`;
538
- }
539
- function extractTuple(name, ma) {
540
- return ma.find((component) => component.name === name);
541
- }
542
- function hasTLS(ma) {
543
- return ma.some(({ code: code2 }) => code2 === CODE_TLS);
544
- }
545
- function interpretNext(head, rest) {
546
- const interpreter = interpreters[head.name];
547
- if (interpreter == null) {
548
- throw new Error(`Can't interpret protocol ${head.name}`);
549
- }
550
- const restVal = interpreter(head, rest);
551
- if (head.code === CODE_IP6) {
552
- return `[${restVal}]`;
553
- }
554
- return restVal;
555
- }
556
- var interpreters = {
557
- ip4: (head, rest) => head.value,
558
- ip6: (head, rest) => {
559
- if (rest.length === 0) {
560
- return head.value;
561
- }
562
- return `[${head.value}]`;
563
- },
564
- tcp: (head, rest) => {
565
- const tail = rest.pop();
566
- if (tail == null) {
567
- throw new Error("Unexpected end of multiaddr");
568
- }
569
- return `tcp://${interpretNext(tail, rest)}:${head.value}`;
570
- },
571
- udp: (head, rest) => {
572
- const tail = rest.pop();
573
- if (tail == null) {
574
- throw new Error("Unexpected end of multiaddr");
575
- }
576
- return `udp://${interpretNext(tail, rest)}:${head.value}`;
577
- },
578
- dnsaddr: (head, rest) => head.value,
579
- dns4: (head, rest) => head.value,
580
- dns6: (head, rest) => head.value,
581
- dns: (head, rest) => head.value,
582
- ipfs: (head, rest) => {
583
- const tail = rest.pop();
584
- if (tail == null) {
585
- throw new Error("Unexpected end of multiaddr");
586
- }
587
- return `${interpretNext(tail, rest)}`;
588
- },
589
- p2p: (head, rest) => {
590
- const tail = rest.pop();
591
- if (tail == null) {
592
- throw new Error("Unexpected end of multiaddr");
593
- }
594
- return `${interpretNext(tail, rest)}`;
595
- },
596
- http: (head, rest) => {
597
- const maHasTLS = hasTLS(rest);
598
- const sni = extractSNI(rest);
599
- const port = extractPort(rest);
600
- if (maHasTLS && sni != null) {
601
- return `https://${sni}${port}`;
602
- }
603
- const protocol = maHasTLS ? "https://" : "http://";
604
- const tail = rest.pop();
605
- if (tail == null) {
606
- throw new Error("Unexpected end of multiaddr");
607
- }
608
- let baseVal = interpretNext(tail, rest);
609
- baseVal = baseVal?.replace("tcp://", "");
610
- return `${protocol}${baseVal}`;
611
- },
612
- "http-path": (head, rest) => {
613
- const tail = rest.pop();
614
- if (tail == null) {
615
- throw new Error("Unexpected end of multiaddr");
616
- }
617
- const baseVal = interpretNext(tail, rest);
618
- const decodedValue = decodeURIComponent(head.value ?? "");
619
- return `${baseVal}${decodedValue}`;
620
- },
621
- tls: (head, rest) => {
622
- const tail = rest.pop();
623
- if (tail == null) {
624
- throw new Error("Unexpected end of multiaddr");
625
- }
626
- return interpretNext(tail, rest);
627
- },
628
- sni: (head, rest) => {
629
- const tail = rest.pop();
630
- if (tail == null) {
631
- throw new Error("Unexpected end of multiaddr");
632
- }
633
- return interpretNext(tail, rest);
634
- },
635
- https: (head, rest) => {
636
- const tail = rest.pop();
637
- if (tail == null) {
638
- throw new Error("Unexpected end of multiaddr");
639
- }
640
- let baseVal = interpretNext(tail, rest);
641
- baseVal = baseVal?.replace("tcp://", "");
642
- return `https://${baseVal}`;
643
- },
644
- ws: (head, rest) => {
645
- const maHasTLS = hasTLS(rest);
646
- const sni = extractSNI(rest);
647
- const port = extractPort(rest);
648
- if (maHasTLS && sni != null) {
649
- return `wss://${sni}${port}`;
650
- }
651
- const protocol = maHasTLS ? "wss://" : "ws://";
652
- const tail = rest.pop();
653
- if (tail == null) {
654
- throw new Error("Unexpected end of multiaddr");
655
- }
656
- let baseVal = interpretNext(tail, rest);
657
- baseVal = baseVal?.replace("tcp://", "");
658
- return `${protocol}${baseVal}`;
659
- },
660
- wss: (head, rest) => {
661
- const tail = rest.pop();
662
- if (tail == null) {
663
- throw new Error("Unexpected end of multiaddr");
182
+ error(message, ...args) {
183
+ if (this.level <= 3 /* ERROR */) {
184
+ console.error(`[${this.prefix}] ERROR:`, message, ...args);
664
185
  }
665
- let baseVal = interpretNext(tail, rest);
666
- baseVal = baseVal?.replace("tcp://", "");
667
- return `wss://${baseVal}`;
668
186
  }
669
187
  };
670
- function multiaddrToUri(input, opts) {
671
- const ma = multiaddr(input);
672
- const components = ma.getComponents();
673
- const head = components.pop();
674
- if (head == null) {
675
- throw new Error("Unexpected end of multiaddr");
676
- }
677
- const interpreter = interpreters[head.name];
678
- if (interpreter == null) {
679
- throw new Error(`No interpreter found for ${head.name}`);
680
- }
681
- let uri = interpreter(head, components) ?? "";
682
- if (ASSUME_HTTP_CODES.includes(head.code)) {
683
- uri = uri.replace(/^.*:\/\//, "");
684
- if (head.value === "443") {
685
- uri = `https://${uri}`;
686
- } else {
687
- uri = `http://${uri}`;
688
- }
689
- }
690
- if (uri.startsWith("http://") || uri.startsWith("https://") || uri.startsWith("ws://") || uri.startsWith("wss://")) {
691
- uri = new URL(uri).toString();
692
- if (uri.endsWith("/")) {
693
- uri = uri.substring(0, uri.length - 1);
694
- }
695
- }
696
- return uri;
697
- }
698
-
699
- // ../../node_modules/.pnpm/p-event@7.1.0/node_modules/p-event/index.js
700
- init_esm_shims();
188
+ var createLogger = (prefix, level) => {
189
+ return new Logger(prefix, level);
190
+ };
701
191
 
702
- // ../../node_modules/.pnpm/p-timeout@7.0.1/node_modules/p-timeout/index.js
703
- init_esm_shims();
704
- var TimeoutError = class _TimeoutError extends Error {
705
- name = "TimeoutError";
706
- constructor(message, options) {
707
- super(message, options);
708
- Error.captureStackTrace?.(this, _TimeoutError);
709
- }
192
+ // src/transport/relay-client.ts
193
+ var logger = createLogger("relay-client");
194
+ var DEFAULT_RECONNECT = {
195
+ baseMs: 1e3,
196
+ jitterMs: 2e3,
197
+ maxDelayMs: 3e4,
198
+ stableAfterMs: 6e4
710
199
  };
711
- var getAbortedReason = (signal) => signal.reason ?? new DOMException("This operation was aborted.", "AbortError");
712
- function pTimeout(promise, options) {
713
- const {
714
- milliseconds,
715
- fallback,
716
- message,
717
- customTimers = { setTimeout, clearTimeout },
718
- signal
719
- } = options;
720
- let timer;
721
- let abortHandler;
722
- const wrappedPromise = new Promise((resolve, reject) => {
723
- if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) {
724
- throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
725
- }
726
- if (signal?.aborted) {
727
- reject(getAbortedReason(signal));
728
- return;
729
- }
730
- if (signal) {
731
- abortHandler = () => {
732
- reject(getAbortedReason(signal));
733
- };
734
- signal.addEventListener("abort", abortHandler, { once: true });
735
- }
736
- promise.then(resolve, reject);
737
- if (milliseconds === Number.POSITIVE_INFINITY) {
738
- return;
739
- }
740
- const timeoutError = new TimeoutError();
741
- timer = customTimers.setTimeout.call(void 0, () => {
742
- if (fallback) {
200
+ function createRelayClient(config) {
201
+ const { relayUrls, did, keyPair, card } = config;
202
+ const reconnectConfig = { ...DEFAULT_RECONNECT, ...config.reconnect };
203
+ const connections = relayUrls.map((url) => ({
204
+ url,
205
+ ws: null,
206
+ connected: false,
207
+ reconnectAttempt: 0,
208
+ reconnectTimer: null,
209
+ stableTimer: null,
210
+ pingTimer: null,
211
+ peerCount: 0
212
+ }));
213
+ let deliveryHandler = null;
214
+ let deliveryReportHandler = null;
215
+ let stopped = false;
216
+ async function connectToRelay(conn) {
217
+ if (stopped) return;
218
+ try {
219
+ logger.info("Connecting to relay", { url: conn.url });
220
+ const ws = new WebSocket(conn.url);
221
+ conn.ws = ws;
222
+ await new Promise((resolve, reject) => {
223
+ const timeout = setTimeout(() => {
224
+ reject(new Error("Connection timeout"));
225
+ }, 1e4);
226
+ ws.on("open", async () => {
227
+ clearTimeout(timeout);
228
+ logger.info("WebSocket connected", { url: conn.url });
229
+ try {
230
+ const timestamp = Date.now();
231
+ const helloData = encode({ did, card, timestamp });
232
+ const signature = await sign(helloData, keyPair.privateKey);
233
+ const hello = {
234
+ type: "HELLO",
235
+ protocolVersion: 1,
236
+ did,
237
+ card,
238
+ timestamp,
239
+ signature
240
+ };
241
+ ws.send(encode(hello));
242
+ resolve();
243
+ } catch (err) {
244
+ reject(err);
245
+ }
246
+ });
247
+ ws.on("error", (err) => {
248
+ clearTimeout(timeout);
249
+ reject(err);
250
+ });
251
+ });
252
+ ws.on("message", async (data) => {
743
253
  try {
744
- resolve(fallback());
745
- } catch (error) {
746
- reject(error);
254
+ const msg = decode(data);
255
+ await handleRelayMessage(conn, msg);
256
+ } catch (err) {
257
+ logger.warn("Failed to parse relay message", { error: err.message });
747
258
  }
748
- return;
749
- }
750
- if (typeof promise.cancel === "function") {
751
- promise.cancel();
752
- }
753
- if (message === false) {
754
- resolve();
755
- } else if (message instanceof Error) {
756
- reject(message);
757
- } else {
758
- timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
759
- reject(timeoutError);
259
+ });
260
+ ws.on("close", () => {
261
+ logger.info("WebSocket closed", { url: conn.url });
262
+ conn.connected = false;
263
+ conn.ws = null;
264
+ if (conn.stableTimer) {
265
+ clearTimeout(conn.stableTimer);
266
+ conn.stableTimer = null;
267
+ }
268
+ if (conn.pingTimer) {
269
+ clearInterval(conn.pingTimer);
270
+ conn.pingTimer = null;
271
+ }
272
+ if (!stopped) {
273
+ scheduleReconnect(conn);
274
+ }
275
+ });
276
+ ws.on("error", (err) => {
277
+ logger.warn("WebSocket error", { url: conn.url, error: err.message });
278
+ });
279
+ } catch (err) {
280
+ logger.warn("Failed to connect to relay", { url: conn.url, error: err.message });
281
+ conn.ws = null;
282
+ conn.connected = false;
283
+ if (!stopped) {
284
+ scheduleReconnect(conn);
760
285
  }
761
- }, milliseconds);
762
- });
763
- const cancelablePromise = wrappedPromise.finally(() => {
764
- cancelablePromise.clear();
765
- if (abortHandler && signal) {
766
- signal.removeEventListener("abort", abortHandler);
767
286
  }
768
- });
769
- cancelablePromise.clear = () => {
770
- customTimers.clearTimeout.call(void 0, timer);
771
- timer = void 0;
772
- };
773
- return cancelablePromise;
774
- }
775
-
776
- // ../../node_modules/.pnpm/p-event@7.1.0/node_modules/p-event/index.js
777
- var normalizeEmitter = (emitter) => {
778
- const addListener = emitter.addEventListener || emitter.on || emitter.addListener;
779
- const removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;
780
- if (!addListener || !removeListener) {
781
- throw new TypeError("Emitter is not compatible");
782
287
  }
783
- return {
784
- addListener: addListener.bind(emitter),
785
- removeListener: removeListener.bind(emitter)
786
- };
787
- };
788
- function pEventMultiple(emitter, event, options) {
789
- let cancel;
790
- const returnValue = new Promise((resolve, reject) => {
791
- options = {
792
- rejectionEvents: ["error"],
793
- multiArgs: false,
794
- rejectionMultiArgs: false,
795
- resolveImmediately: false,
796
- ...options
797
- };
798
- if (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {
799
- throw new TypeError("The `count` option should be at least 0 or more");
800
- }
801
- options.signal?.throwIfAborted();
802
- const events = [event].flat();
803
- const items = [];
804
- const { addListener, removeListener } = normalizeEmitter(emitter);
805
- const onItem = async (...arguments_) => {
806
- const value2 = options.multiArgs ? arguments_ : arguments_[0];
807
- if (options.filter) {
808
- try {
809
- if (!await options.filter(value2)) {
810
- return;
288
+ function scheduleReconnect(conn) {
289
+ if (conn.reconnectTimer) return;
290
+ const delay = Math.min(
291
+ reconnectConfig.baseMs * Math.pow(2, conn.reconnectAttempt) + Math.random() * reconnectConfig.jitterMs,
292
+ reconnectConfig.maxDelayMs
293
+ );
294
+ conn.reconnectAttempt++;
295
+ logger.debug("Scheduling reconnect", { url: conn.url, attempt: conn.reconnectAttempt, delayMs: delay });
296
+ conn.reconnectTimer = setTimeout(() => {
297
+ conn.reconnectTimer = null;
298
+ connectToRelay(conn);
299
+ }, delay);
300
+ }
301
+ async function handleRelayMessage(conn, msg) {
302
+ switch (msg.type) {
303
+ case "WELCOME": {
304
+ const welcome = msg;
305
+ logger.info("Received WELCOME", { relayId: welcome.relayId, peers: welcome.peers });
306
+ conn.connected = true;
307
+ conn.peerCount = welcome.peers;
308
+ conn.reconnectAttempt = 0;
309
+ if (conn.stableTimer) clearTimeout(conn.stableTimer);
310
+ conn.stableTimer = setTimeout(() => {
311
+ conn.reconnectAttempt = 0;
312
+ logger.debug("Connection stable", { url: conn.url });
313
+ }, reconnectConfig.stableAfterMs);
314
+ if (conn.pingTimer) clearInterval(conn.pingTimer);
315
+ conn.pingTimer = setInterval(() => {
316
+ if (conn.ws && conn.connected) {
317
+ conn.ws.send(encode({ type: "PING" }));
318
+ logger.debug("Sent PING", { url: conn.url });
811
319
  }
812
- } catch (error) {
813
- cancel();
814
- reject(error);
815
- return;
816
- }
817
- }
818
- items.push(value2);
819
- if (options.count === items.length) {
820
- cancel();
821
- resolve(items);
822
- }
823
- };
824
- const rejectHandler = (...arguments_) => {
825
- cancel();
826
- reject(options.rejectionMultiArgs ? arguments_ : arguments_[0]);
827
- };
828
- cancel = () => {
829
- for (const event2 of events) {
830
- removeListener(event2, onItem);
320
+ }, 3e4);
321
+ break;
831
322
  }
832
- for (const rejectionEvent of options.rejectionEvents) {
833
- if (!events.includes(rejectionEvent)) {
834
- removeListener(rejectionEvent, rejectHandler);
323
+ case "DELIVER": {
324
+ const deliver = msg;
325
+ logger.info("Received DELIVER", { messageId: deliver.messageId, from: deliver.from });
326
+ if (deliveryHandler) {
327
+ await deliveryHandler(deliver);
835
328
  }
329
+ if (conn.ws && conn.connected) {
330
+ conn.ws.send(encode({ type: "ACK", messageId: deliver.messageId }));
331
+ logger.debug("Sent ACK", { messageId: deliver.messageId });
332
+ }
333
+ break;
836
334
  }
837
- };
838
- for (const event2 of events) {
839
- addListener(event2, onItem);
840
- }
841
- for (const rejectionEvent of options.rejectionEvents) {
842
- if (!events.includes(rejectionEvent)) {
843
- addListener(rejectionEvent, rejectHandler);
844
- }
845
- }
846
- if (options.signal) {
847
- options.signal.addEventListener("abort", () => {
848
- rejectHandler(options.signal.reason);
849
- }, { once: true });
850
- }
851
- if (options.resolveImmediately) {
852
- resolve(items);
853
- }
854
- });
855
- returnValue.cancel = cancel;
856
- if (typeof options.timeout === "number") {
857
- const timeout = pTimeout(returnValue, { milliseconds: options.timeout });
858
- timeout.cancel = () => {
859
- cancel();
860
- timeout.clear();
861
- };
862
- return timeout;
863
- }
864
- return returnValue;
865
- }
866
- function pEvent(emitter, event, options) {
867
- if (typeof options === "function") {
868
- options = { filter: options };
869
- }
870
- options = {
871
- ...options,
872
- count: 1,
873
- resolveImmediately: false
874
- };
875
- const arrayPromise = pEventMultiple(emitter, event, options);
876
- const promise = arrayPromise.then((array) => array[0]);
877
- promise.cancel = arrayPromise.cancel;
878
- return promise;
879
- }
880
-
881
- // ../../node_modules/.pnpm/progress-events@1.0.1/node_modules/progress-events/dist/src/index.js
882
- init_esm_shims();
883
- var CustomProgressEvent = class extends Event {
884
- type;
885
- detail;
886
- constructor(type, detail) {
887
- super(type);
888
- this.type = type;
889
- this.detail = detail;
890
- }
891
- };
892
-
893
- // ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/listener.js
894
- init_esm_shims();
895
-
896
- // ../../node_modules/.pnpm/uint8arraylist@2.4.8/node_modules/uint8arraylist/dist/src/index.js
897
- init_esm_shims();
898
- var symbol = /* @__PURE__ */ Symbol.for("@achingbrain/uint8arraylist");
899
- function findBufAndOffset(bufs, index) {
900
- if (index == null || index < 0) {
901
- throw new RangeError("index is out of bounds");
902
- }
903
- let offset = 0;
904
- for (const buf of bufs) {
905
- const bufEnd = offset + buf.byteLength;
906
- if (index < bufEnd) {
907
- return {
908
- buf,
909
- index: index - offset
910
- };
911
- }
912
- offset = bufEnd;
913
- }
914
- throw new RangeError("index is out of bounds");
915
- }
916
- function isUint8ArrayList(value2) {
917
- return Boolean(value2?.[symbol]);
918
- }
919
- var Uint8ArrayList = class _Uint8ArrayList {
920
- bufs;
921
- length;
922
- [symbol] = true;
923
- constructor(...data) {
924
- this.bufs = [];
925
- this.length = 0;
926
- if (data.length > 0) {
927
- this.appendAll(data);
928
- }
929
- }
930
- *[Symbol.iterator]() {
931
- yield* this.bufs;
932
- }
933
- get byteLength() {
934
- return this.length;
935
- }
936
- /**
937
- * Add one or more `bufs` to the end of this Uint8ArrayList
938
- */
939
- append(...bufs) {
940
- this.appendAll(bufs);
941
- }
942
- /**
943
- * Add all `bufs` to the end of this Uint8ArrayList
944
- */
945
- appendAll(bufs) {
946
- let length = 0;
947
- for (const buf of bufs) {
948
- if (buf instanceof Uint8Array) {
949
- length += buf.byteLength;
950
- this.bufs.push(buf);
951
- } else if (isUint8ArrayList(buf)) {
952
- length += buf.byteLength;
953
- this.bufs.push(...buf.bufs);
954
- } else {
955
- throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");
956
- }
957
- }
958
- this.length += length;
959
- }
960
- /**
961
- * Add one or more `bufs` to the start of this Uint8ArrayList
962
- */
963
- prepend(...bufs) {
964
- this.prependAll(bufs);
965
- }
966
- /**
967
- * Add all `bufs` to the start of this Uint8ArrayList
968
- */
969
- prependAll(bufs) {
970
- let length = 0;
971
- for (const buf of bufs.reverse()) {
972
- if (buf instanceof Uint8Array) {
973
- length += buf.byteLength;
974
- this.bufs.unshift(buf);
975
- } else if (isUint8ArrayList(buf)) {
976
- length += buf.byteLength;
977
- this.bufs.unshift(...buf.bufs);
978
- } else {
979
- throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");
980
- }
981
- }
982
- this.length += length;
983
- }
984
- /**
985
- * Read the value at `index`
986
- */
987
- get(index) {
988
- const res = findBufAndOffset(this.bufs, index);
989
- return res.buf[res.index];
990
- }
991
- /**
992
- * Set the value at `index` to `value`
993
- */
994
- set(index, value2) {
995
- const res = findBufAndOffset(this.bufs, index);
996
- res.buf[res.index] = value2;
997
- }
998
- /**
999
- * Copy bytes from `buf` to the index specified by `offset`
1000
- */
1001
- write(buf, offset = 0) {
1002
- if (buf instanceof Uint8Array) {
1003
- for (let i = 0; i < buf.length; i++) {
1004
- this.set(offset + i, buf[i]);
1005
- }
1006
- } else if (isUint8ArrayList(buf)) {
1007
- for (let i = 0; i < buf.length; i++) {
1008
- this.set(offset + i, buf.get(i));
1009
- }
1010
- } else {
1011
- throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");
1012
- }
1013
- }
1014
- /**
1015
- * Remove bytes from the front of the pool
1016
- */
1017
- consume(bytes) {
1018
- bytes = Math.trunc(bytes);
1019
- if (Number.isNaN(bytes) || bytes <= 0) {
1020
- return;
1021
- }
1022
- if (bytes === this.byteLength) {
1023
- this.bufs = [];
1024
- this.length = 0;
1025
- return;
1026
- }
1027
- while (this.bufs.length > 0) {
1028
- if (bytes >= this.bufs[0].byteLength) {
1029
- bytes -= this.bufs[0].byteLength;
1030
- this.length -= this.bufs[0].byteLength;
1031
- this.bufs.shift();
1032
- } else {
1033
- this.bufs[0] = this.bufs[0].subarray(bytes);
1034
- this.length -= bytes;
1035
- break;
1036
- }
1037
- }
1038
- }
1039
- /**
1040
- * Extracts a section of an array and returns a new array.
1041
- *
1042
- * This is a copy operation as it is with Uint8Arrays and Arrays
1043
- * - note this is different to the behaviour of Node Buffers.
1044
- */
1045
- slice(beginInclusive, endExclusive) {
1046
- const { bufs, length } = this._subList(beginInclusive, endExclusive);
1047
- return concat(bufs, length);
1048
- }
1049
- /**
1050
- * Returns a alloc from the given start and end element index.
1051
- *
1052
- * In the best case where the data extracted comes from a single Uint8Array
1053
- * internally this is a no-copy operation otherwise it is a copy operation.
1054
- */
1055
- subarray(beginInclusive, endExclusive) {
1056
- const { bufs, length } = this._subList(beginInclusive, endExclusive);
1057
- if (bufs.length === 1) {
1058
- return bufs[0];
1059
- }
1060
- return concat(bufs, length);
1061
- }
1062
- /**
1063
- * Returns a allocList from the given start and end element index.
1064
- *
1065
- * This is a no-copy operation.
1066
- */
1067
- sublist(beginInclusive, endExclusive) {
1068
- const { bufs, length } = this._subList(beginInclusive, endExclusive);
1069
- const list = new _Uint8ArrayList();
1070
- list.length = length;
1071
- list.bufs = [...bufs];
1072
- return list;
1073
- }
1074
- _subList(beginInclusive, endExclusive) {
1075
- beginInclusive = beginInclusive ?? 0;
1076
- endExclusive = endExclusive ?? this.length;
1077
- if (beginInclusive < 0) {
1078
- beginInclusive = this.length + beginInclusive;
1079
- }
1080
- if (endExclusive < 0) {
1081
- endExclusive = this.length + endExclusive;
1082
- }
1083
- if (beginInclusive < 0 || endExclusive > this.length) {
1084
- throw new RangeError("index is out of bounds");
1085
- }
1086
- if (beginInclusive === endExclusive) {
1087
- return { bufs: [], length: 0 };
1088
- }
1089
- if (beginInclusive === 0 && endExclusive === this.length) {
1090
- return { bufs: this.bufs, length: this.length };
1091
- }
1092
- const bufs = [];
1093
- let offset = 0;
1094
- for (let i = 0; i < this.bufs.length; i++) {
1095
- const buf = this.bufs[i];
1096
- const bufStart = offset;
1097
- const bufEnd = bufStart + buf.byteLength;
1098
- offset = bufEnd;
1099
- if (beginInclusive >= bufEnd) {
1100
- continue;
1101
- }
1102
- const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd;
1103
- const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd;
1104
- if (sliceStartInBuf && sliceEndsInBuf) {
1105
- if (beginInclusive === bufStart && endExclusive === bufEnd) {
1106
- bufs.push(buf);
1107
- break;
1108
- }
1109
- const start = beginInclusive - bufStart;
1110
- bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)));
1111
- break;
1112
- }
1113
- if (sliceStartInBuf) {
1114
- if (beginInclusive === 0) {
1115
- bufs.push(buf);
1116
- continue;
1117
- }
1118
- bufs.push(buf.subarray(beginInclusive - bufStart));
1119
- continue;
1120
- }
1121
- if (sliceEndsInBuf) {
1122
- if (endExclusive === bufEnd) {
1123
- bufs.push(buf);
1124
- break;
335
+ case "DELIVERY_REPORT": {
336
+ const report = msg;
337
+ logger.info("Received DELIVERY_REPORT", { messageId: report.messageId, status: report.status });
338
+ if (deliveryReportHandler) {
339
+ deliveryReportHandler(report);
1125
340
  }
1126
- bufs.push(buf.subarray(0, endExclusive - bufStart));
1127
341
  break;
1128
- }
1129
- bufs.push(buf);
1130
- }
1131
- return { bufs, length: endExclusive - beginInclusive };
1132
- }
1133
- indexOf(search, offset = 0) {
1134
- if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {
1135
- throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');
1136
- }
1137
- const needle = search instanceof Uint8Array ? search : search.subarray();
1138
- offset = Number(offset ?? 0);
1139
- if (isNaN(offset)) {
1140
- offset = 0;
1141
- }
1142
- if (offset < 0) {
1143
- offset = this.length + offset;
1144
- }
1145
- if (offset < 0) {
1146
- offset = 0;
1147
- }
1148
- if (search.length === 0) {
1149
- return offset > this.length ? this.length : offset;
1150
- }
1151
- const M = needle.byteLength;
1152
- if (M === 0) {
1153
- throw new TypeError("search must be at least 1 byte long");
1154
- }
1155
- const radix = 256;
1156
- const rightmostPositions = new Int32Array(radix);
1157
- for (let c = 0; c < radix; c++) {
1158
- rightmostPositions[c] = -1;
1159
- }
1160
- for (let j = 0; j < M; j++) {
1161
- rightmostPositions[needle[j]] = j;
1162
- }
1163
- const right = rightmostPositions;
1164
- const lastIndex = this.byteLength - needle.byteLength;
1165
- const lastPatIndex = needle.byteLength - 1;
1166
- let skip;
1167
- for (let i = offset; i <= lastIndex; i += skip) {
1168
- skip = 0;
1169
- for (let j = lastPatIndex; j >= 0; j--) {
1170
- const char = this.get(i + j);
1171
- if (needle[j] !== char) {
1172
- skip = Math.max(1, j - right[char]);
1173
- break;
1174
- }
1175
- }
1176
- if (skip === 0) {
1177
- return i;
1178
- }
1179
- }
1180
- return -1;
1181
- }
1182
- getInt8(byteOffset) {
1183
- const buf = this.subarray(byteOffset, byteOffset + 1);
1184
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1185
- return view.getInt8(0);
1186
- }
1187
- setInt8(byteOffset, value2) {
1188
- const buf = allocUnsafe(1);
1189
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1190
- view.setInt8(0, value2);
1191
- this.write(buf, byteOffset);
1192
- }
1193
- getInt16(byteOffset, littleEndian) {
1194
- const buf = this.subarray(byteOffset, byteOffset + 2);
1195
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1196
- return view.getInt16(0, littleEndian);
1197
- }
1198
- setInt16(byteOffset, value2, littleEndian) {
1199
- const buf = alloc(2);
1200
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1201
- view.setInt16(0, value2, littleEndian);
1202
- this.write(buf, byteOffset);
1203
- }
1204
- getInt32(byteOffset, littleEndian) {
1205
- const buf = this.subarray(byteOffset, byteOffset + 4);
1206
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1207
- return view.getInt32(0, littleEndian);
1208
- }
1209
- setInt32(byteOffset, value2, littleEndian) {
1210
- const buf = alloc(4);
1211
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1212
- view.setInt32(0, value2, littleEndian);
1213
- this.write(buf, byteOffset);
1214
- }
1215
- getBigInt64(byteOffset, littleEndian) {
1216
- const buf = this.subarray(byteOffset, byteOffset + 8);
1217
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1218
- return view.getBigInt64(0, littleEndian);
1219
- }
1220
- setBigInt64(byteOffset, value2, littleEndian) {
1221
- const buf = alloc(8);
1222
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1223
- view.setBigInt64(0, value2, littleEndian);
1224
- this.write(buf, byteOffset);
1225
- }
1226
- getUint8(byteOffset) {
1227
- const buf = this.subarray(byteOffset, byteOffset + 1);
1228
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1229
- return view.getUint8(0);
1230
- }
1231
- setUint8(byteOffset, value2) {
1232
- const buf = allocUnsafe(1);
1233
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1234
- view.setUint8(0, value2);
1235
- this.write(buf, byteOffset);
1236
- }
1237
- getUint16(byteOffset, littleEndian) {
1238
- const buf = this.subarray(byteOffset, byteOffset + 2);
1239
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1240
- return view.getUint16(0, littleEndian);
1241
- }
1242
- setUint16(byteOffset, value2, littleEndian) {
1243
- const buf = alloc(2);
1244
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1245
- view.setUint16(0, value2, littleEndian);
1246
- this.write(buf, byteOffset);
1247
- }
1248
- getUint32(byteOffset, littleEndian) {
1249
- const buf = this.subarray(byteOffset, byteOffset + 4);
1250
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1251
- return view.getUint32(0, littleEndian);
1252
- }
1253
- setUint32(byteOffset, value2, littleEndian) {
1254
- const buf = alloc(4);
1255
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1256
- view.setUint32(0, value2, littleEndian);
1257
- this.write(buf, byteOffset);
1258
- }
1259
- getBigUint64(byteOffset, littleEndian) {
1260
- const buf = this.subarray(byteOffset, byteOffset + 8);
1261
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1262
- return view.getBigUint64(0, littleEndian);
1263
- }
1264
- setBigUint64(byteOffset, value2, littleEndian) {
1265
- const buf = alloc(8);
1266
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1267
- view.setBigUint64(0, value2, littleEndian);
1268
- this.write(buf, byteOffset);
1269
- }
1270
- getFloat32(byteOffset, littleEndian) {
1271
- const buf = this.subarray(byteOffset, byteOffset + 4);
1272
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1273
- return view.getFloat32(0, littleEndian);
1274
- }
1275
- setFloat32(byteOffset, value2, littleEndian) {
1276
- const buf = alloc(4);
1277
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1278
- view.setFloat32(0, value2, littleEndian);
1279
- this.write(buf, byteOffset);
1280
- }
1281
- getFloat64(byteOffset, littleEndian) {
1282
- const buf = this.subarray(byteOffset, byteOffset + 8);
1283
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1284
- return view.getFloat64(0, littleEndian);
1285
- }
1286
- setFloat64(byteOffset, value2, littleEndian) {
1287
- const buf = alloc(8);
1288
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1289
- view.setFloat64(0, value2, littleEndian);
1290
- this.write(buf, byteOffset);
1291
- }
1292
- equals(other) {
1293
- if (other == null) {
1294
- return false;
1295
- }
1296
- if (!(other instanceof _Uint8ArrayList)) {
1297
- return false;
1298
- }
1299
- if (other.bufs.length !== this.bufs.length) {
1300
- return false;
1301
- }
1302
- for (let i = 0; i < this.bufs.length; i++) {
1303
- if (!equals(this.bufs[i], other.bufs[i])) {
1304
- return false;
1305
- }
1306
- }
1307
- return true;
1308
- }
1309
- /**
1310
- * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this
1311
- * method if you know the total size of all the Uint8Arrays ahead of time.
1312
- */
1313
- static fromUint8Arrays(bufs, length) {
1314
- const list = new _Uint8ArrayList();
1315
- list.bufs = bufs;
1316
- if (length == null) {
1317
- length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0);
1318
- }
1319
- list.length = length;
1320
- return list;
1321
- }
1322
- };
1323
-
1324
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/multiaddr/get-net-config.js
1325
- init_esm_shims();
1326
- function getNetConfig(ma) {
1327
- const components = ma.getComponents();
1328
- const config = {};
1329
- let index = 0;
1330
- if (components[index]?.name === "ip6zone") {
1331
- config.zone = `${components[index].value}`;
1332
- index++;
1333
- }
1334
- if (components[index].name === "ip4" || components[index].name === "ip6") {
1335
- config.type = components[index].name;
1336
- config.host = components[index].value;
1337
- index++;
1338
- } else if (components[index].name === "dns" || components[index].name === "dns4" || components[index].name === "dns6") {
1339
- config.type = components[index].name;
1340
- config.host = components[index].value;
1341
- index++;
1342
- } else if (components[index].name === "dnsaddr") {
1343
- config.type = components[index].name;
1344
- config.host = `_dnsaddr.${components[index].value}`;
1345
- index++;
1346
- }
1347
- if (components[index]?.name === "tcp" || components[index]?.name === "udp") {
1348
- config.protocol = components[index].name === "tcp" ? "tcp" : "udp";
1349
- config.port = parseInt(`${components[index].value}`);
1350
- index++;
1351
- }
1352
- if (components[index]?.name === "ipcidr") {
1353
- if (config.type === "ip4") {
1354
- config.cidr = parseInt(`${components[index].value}`);
1355
- } else if (config.type === "ip6") {
1356
- config.cidr = `${components[index].value}`;
1357
- }
1358
- index++;
1359
- }
1360
- if (config.type == null || config.host == null) {
1361
- throw new InvalidParametersError(`Multiaddr ${ma} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);
1362
- }
1363
- if (components[index]?.name === "tls" && components[index + 1]?.name === "sni") {
1364
- config.sni = components[index + 1].value;
1365
- index += 2;
1366
- }
1367
- return config;
1368
- }
1369
-
1370
- // ../../node_modules/.pnpm/@chainsafe+is-ip@2.1.0/node_modules/@chainsafe/is-ip/lib/is-ip.node.js
1371
- init_esm_shims();
1372
-
1373
- // ../../node_modules/.pnpm/it-pushable@3.2.3/node_modules/it-pushable/dist/src/index.js
1374
- init_esm_shims();
1375
-
1376
- // ../../node_modules/.pnpm/p-defer@4.0.1/node_modules/p-defer/index.js
1377
- init_esm_shims();
1378
- function pDefer() {
1379
- const deferred = {};
1380
- deferred.promise = new Promise((resolve, reject) => {
1381
- deferred.resolve = resolve;
1382
- deferred.reject = reject;
1383
- });
1384
- return deferred;
1385
- }
1386
-
1387
- // ../../node_modules/.pnpm/it-pushable@3.2.3/node_modules/it-pushable/dist/src/fifo.js
1388
- init_esm_shims();
1389
- var FixedFIFO = class {
1390
- buffer;
1391
- mask;
1392
- top;
1393
- btm;
1394
- next;
1395
- constructor(hwm) {
1396
- if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) {
1397
- throw new Error("Max size for a FixedFIFO should be a power of two");
1398
- }
1399
- this.buffer = new Array(hwm);
1400
- this.mask = hwm - 1;
1401
- this.top = 0;
1402
- this.btm = 0;
1403
- this.next = null;
1404
- }
1405
- push(data) {
1406
- if (this.buffer[this.top] !== void 0) {
1407
- return false;
1408
- }
1409
- this.buffer[this.top] = data;
1410
- this.top = this.top + 1 & this.mask;
1411
- return true;
1412
- }
1413
- shift() {
1414
- const last = this.buffer[this.btm];
1415
- if (last === void 0) {
1416
- return void 0;
1417
- }
1418
- this.buffer[this.btm] = void 0;
1419
- this.btm = this.btm + 1 & this.mask;
1420
- return last;
1421
- }
1422
- isEmpty() {
1423
- return this.buffer[this.btm] === void 0;
1424
- }
1425
- };
1426
- var FIFO = class {
1427
- size;
1428
- hwm;
1429
- head;
1430
- tail;
1431
- constructor(options = {}) {
1432
- this.hwm = options.splitLimit ?? 16;
1433
- this.head = new FixedFIFO(this.hwm);
1434
- this.tail = this.head;
1435
- this.size = 0;
1436
- }
1437
- calculateSize(obj) {
1438
- if (obj?.byteLength != null) {
1439
- return obj.byteLength;
1440
- }
1441
- return 1;
1442
- }
1443
- push(val) {
1444
- if (val?.value != null) {
1445
- this.size += this.calculateSize(val.value);
1446
- }
1447
- if (!this.head.push(val)) {
1448
- const prev = this.head;
1449
- this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
1450
- this.head.push(val);
1451
- }
1452
- }
1453
- shift() {
1454
- let val = this.tail.shift();
1455
- if (val === void 0 && this.tail.next != null) {
1456
- const next = this.tail.next;
1457
- this.tail.next = null;
1458
- this.tail = next;
1459
- val = this.tail.shift();
1460
- }
1461
- if (val?.value != null) {
1462
- this.size -= this.calculateSize(val.value);
1463
- }
1464
- return val;
1465
- }
1466
- isEmpty() {
1467
- return this.head.isEmpty();
1468
- }
1469
- };
1470
-
1471
- // ../../node_modules/.pnpm/it-pushable@3.2.3/node_modules/it-pushable/dist/src/index.js
1472
- var AbortError = class extends Error {
1473
- type;
1474
- code;
1475
- constructor(message, code2) {
1476
- super(message ?? "The operation was aborted");
1477
- this.type = "aborted";
1478
- this.code = code2 ?? "ABORT_ERR";
1479
- }
1480
- };
1481
- function pushable(options = {}) {
1482
- const getNext = (buffer) => {
1483
- const next = buffer.shift();
1484
- if (next == null) {
1485
- return { done: true };
1486
- }
1487
- if (next.error != null) {
1488
- throw next.error;
1489
- }
1490
- return {
1491
- done: next.done === true,
1492
- // @ts-expect-error if done is false, value will be present
1493
- value: next.value
1494
- };
1495
- };
1496
- return _pushable(getNext, options);
1497
- }
1498
- function _pushable(getNext, options) {
1499
- options = options ?? {};
1500
- let onEnd = options.onEnd;
1501
- let buffer = new FIFO();
1502
- let pushable2;
1503
- let onNext;
1504
- let ended;
1505
- let drain = pDefer();
1506
- const waitNext = async () => {
1507
- try {
1508
- if (!buffer.isEmpty()) {
1509
- return getNext(buffer);
1510
- }
1511
- if (ended) {
1512
- return { done: true };
1513
- }
1514
- return await new Promise((resolve, reject) => {
1515
- onNext = (next) => {
1516
- onNext = null;
1517
- buffer.push(next);
1518
- try {
1519
- resolve(getNext(buffer));
1520
- } catch (err) {
1521
- reject(err);
1522
- }
1523
- return pushable2;
1524
- };
1525
- });
1526
- } finally {
1527
- if (buffer.isEmpty()) {
1528
- queueMicrotask(() => {
1529
- drain.resolve();
1530
- drain = pDefer();
1531
- });
1532
- }
1533
- }
1534
- };
1535
- const bufferNext = (next) => {
1536
- if (onNext != null) {
1537
- return onNext(next);
1538
- }
1539
- buffer.push(next);
1540
- return pushable2;
1541
- };
1542
- const bufferError = (err) => {
1543
- buffer = new FIFO();
1544
- if (onNext != null) {
1545
- return onNext({ error: err });
1546
- }
1547
- buffer.push({ error: err });
1548
- return pushable2;
1549
- };
1550
- const push = (value2) => {
1551
- if (ended) {
1552
- return pushable2;
1553
- }
1554
- if (options?.objectMode !== true && value2?.byteLength == null) {
1555
- throw new Error("objectMode was not true but tried to push non-Uint8Array value");
1556
- }
1557
- return bufferNext({ done: false, value: value2 });
1558
- };
1559
- const end = (err) => {
1560
- if (ended)
1561
- return pushable2;
1562
- ended = true;
1563
- return err != null ? bufferError(err) : bufferNext({ done: true });
1564
- };
1565
- const _return = () => {
1566
- buffer = new FIFO();
1567
- end();
1568
- return { done: true };
1569
- };
1570
- const _throw = (err) => {
1571
- end(err);
1572
- return { done: true };
1573
- };
1574
- pushable2 = {
1575
- [Symbol.asyncIterator]() {
1576
- return this;
1577
- },
1578
- next: waitNext,
1579
- return: _return,
1580
- throw: _throw,
1581
- push,
1582
- end,
1583
- get readableLength() {
1584
- return buffer.size;
1585
- },
1586
- onEmpty: async (options2) => {
1587
- const signal = options2?.signal;
1588
- signal?.throwIfAborted();
1589
- if (buffer.isEmpty()) {
1590
- return;
1591
- }
1592
- let cancel;
1593
- let listener;
1594
- if (signal != null) {
1595
- cancel = new Promise((resolve, reject) => {
1596
- listener = () => {
1597
- reject(new AbortError());
1598
- };
1599
- signal.addEventListener("abort", listener);
1600
- });
1601
- }
1602
- try {
1603
- await Promise.race([
1604
- drain.promise,
1605
- cancel
1606
- ]);
1607
- } finally {
1608
- if (listener != null && signal != null) {
1609
- signal?.removeEventListener("abort", listener);
1610
- }
1611
- }
1612
- }
1613
- };
1614
- if (onEnd == null) {
1615
- return pushable2;
1616
- }
1617
- const _pushable2 = pushable2;
1618
- pushable2 = {
1619
- [Symbol.asyncIterator]() {
1620
- return this;
1621
- },
1622
- next() {
1623
- return _pushable2.next();
1624
- },
1625
- throw(err) {
1626
- _pushable2.throw(err);
1627
- if (onEnd != null) {
1628
- onEnd(err);
1629
- onEnd = void 0;
1630
- }
1631
- return { done: true };
1632
- },
1633
- return() {
1634
- _pushable2.return();
1635
- if (onEnd != null) {
1636
- onEnd();
1637
- onEnd = void 0;
1638
- }
1639
- return { done: true };
1640
- },
1641
- push,
1642
- end(err) {
1643
- _pushable2.end(err);
1644
- if (onEnd != null) {
1645
- onEnd(err);
1646
- onEnd = void 0;
1647
- }
1648
- return pushable2;
1649
- },
1650
- get readableLength() {
1651
- return _pushable2.readableLength;
1652
- },
1653
- onEmpty: (opts) => {
1654
- return _pushable2.onEmpty(opts);
1655
- }
1656
- };
1657
- return pushable2;
1658
- }
1659
-
1660
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/debounce.js
1661
- init_esm_shims();
1662
- function debounce(func, wait) {
1663
- let timeout;
1664
- const output = function() {
1665
- const later = function() {
1666
- timeout = void 0;
1667
- void func();
1668
- };
1669
- clearTimeout(timeout);
1670
- timeout = setTimeout(later, wait);
1671
- };
1672
- output.start = () => {
1673
- };
1674
- output.stop = () => {
1675
- clearTimeout(timeout);
1676
- };
1677
- return output;
1678
- }
1679
-
1680
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/errors.js
1681
- init_esm_shims();
1682
- var StreamClosedError = class extends Error {
1683
- static name = "StreamClosedError";
1684
- name = "StreamClosedError";
1685
- };
1686
-
1687
- // ../../node_modules/.pnpm/race-signal@2.0.0/node_modules/race-signal/dist/src/index.js
1688
- init_esm_shims();
1689
- function defaultTranslate(signal) {
1690
- return signal.reason;
1691
- }
1692
- async function raceSignal(promise, signal, opts) {
1693
- if (signal == null) {
1694
- return promise;
1695
- }
1696
- const translateError = defaultTranslate;
1697
- if (signal.aborted) {
1698
- promise.catch(() => {
1699
- });
1700
- return Promise.reject(translateError(signal));
1701
- }
1702
- let listener;
1703
- try {
1704
- return await Promise.race([
1705
- promise,
1706
- new Promise((resolve, reject) => {
1707
- listener = () => {
1708
- reject(translateError(signal));
1709
- };
1710
- signal.addEventListener("abort", listener);
1711
- })
1712
- ]);
1713
- } finally {
1714
- if (listener != null) {
1715
- signal.removeEventListener("abort", listener);
1716
- }
1717
- }
1718
- }
1719
-
1720
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/abstract-message-stream.js
1721
- init_esm_shims();
1722
- var DEFAULT_MAX_READ_BUFFER_LENGTH = Math.pow(2, 20) * 4;
1723
- var AbstractMessageStream = class extends TypedEventEmitter {
1724
- status;
1725
- timeline;
1726
- inactivityTimeout;
1727
- maxReadBufferLength;
1728
- maxWriteBufferLength;
1729
- log;
1730
- direction;
1731
- maxMessageSize;
1732
- readStatus;
1733
- writeStatus;
1734
- remoteReadStatus;
1735
- remoteWriteStatus;
1736
- writableNeedsDrain;
1737
- /**
1738
- * Any data stored here is emitted before any new incoming data.
1739
- *
1740
- * This is used when the stream is paused or if data is pushed onto the stream
1741
- */
1742
- readBuffer;
1743
- writeBuffer;
1744
- sendingData;
1745
- onDrainPromise;
1746
- constructor(init) {
1747
- super();
1748
- this.status = "open";
1749
- this.log = init.log;
1750
- this.direction = init.direction ?? "outbound";
1751
- this.inactivityTimeout = init.inactivityTimeout ?? 12e4;
1752
- this.maxReadBufferLength = init.maxReadBufferLength ?? DEFAULT_MAX_READ_BUFFER_LENGTH;
1753
- this.maxWriteBufferLength = init.maxWriteBufferLength;
1754
- this.maxMessageSize = init.maxMessageSize;
1755
- this.readBuffer = new Uint8ArrayList();
1756
- this.writeBuffer = new Uint8ArrayList();
1757
- this.readStatus = "readable";
1758
- this.remoteReadStatus = "readable";
1759
- this.writeStatus = "writable";
1760
- this.remoteWriteStatus = "writable";
1761
- this.sendingData = false;
1762
- this.writableNeedsDrain = false;
1763
- this.timeline = {
1764
- open: Date.now()
1765
- };
1766
- this.processSendQueue = this.processSendQueue.bind(this);
1767
- const continueSendingOnDrain = () => {
1768
- if (this.writableNeedsDrain) {
1769
- this.log.trace("drain event received, continue sending data");
1770
- this.writableNeedsDrain = false;
1771
- this.processSendQueue();
1772
- }
1773
- this.onDrainPromise?.resolve();
1774
- };
1775
- this.addEventListener("drain", continueSendingOnDrain);
1776
- const rejectOnDrainOnClose = (evt) => {
1777
- this.onDrainPromise?.reject(evt.error ?? new StreamClosedError());
1778
- };
1779
- this.addEventListener("close", rejectOnDrainOnClose);
1780
- }
1781
- get readBufferLength() {
1782
- return this.readBuffer.byteLength;
1783
- }
1784
- get writeBufferLength() {
1785
- return this.writeBuffer.byteLength;
1786
- }
1787
- async onDrain(options) {
1788
- if (this.writableNeedsDrain !== true) {
1789
- return Promise.resolve();
1790
- }
1791
- if (this.onDrainPromise == null) {
1792
- this.onDrainPromise = Promise.withResolvers();
1793
- }
1794
- return raceSignal(this.onDrainPromise.promise, options?.signal);
1795
- }
1796
- async *[Symbol.asyncIterator]() {
1797
- if (this.readStatus !== "readable" && this.readStatus !== "paused") {
1798
- return;
1799
- }
1800
- const output = pushable();
1801
- const streamAsyncIterableOnMessageListener = (evt) => {
1802
- output.push(evt.data);
1803
- };
1804
- this.addEventListener("message", streamAsyncIterableOnMessageListener);
1805
- const streamAsyncIterableOnCloseListener = (evt) => {
1806
- output.end(evt.error);
1807
- };
1808
- this.addEventListener("close", streamAsyncIterableOnCloseListener);
1809
- const streamAsyncIterableOnRemoteCloseWriteListener = () => {
1810
- output.end();
1811
- };
1812
- this.addEventListener("remoteCloseWrite", streamAsyncIterableOnRemoteCloseWriteListener);
1813
- try {
1814
- yield* output;
1815
- } finally {
1816
- this.removeEventListener("message", streamAsyncIterableOnMessageListener);
1817
- this.removeEventListener("close", streamAsyncIterableOnCloseListener);
1818
- this.removeEventListener("remoteCloseWrite", streamAsyncIterableOnRemoteCloseWriteListener);
1819
- }
1820
- }
1821
- isReadable() {
1822
- return this.status === "open";
1823
- }
1824
- send(data) {
1825
- if (this.writeStatus === "closed" || this.writeStatus === "closing") {
1826
- throw new StreamStateError(`Cannot write to a stream that is ${this.writeStatus}`);
1827
- }
1828
- this.log.trace("append %d bytes to write buffer", data.byteLength);
1829
- this.writeBuffer.append(data);
1830
- return this.processSendQueue();
1831
- }
1832
- /**
1833
- * Close immediately for reading and writing and send a reset message (local
1834
- * error)
1835
- */
1836
- abort(err) {
1837
- if (this.status === "aborted" || this.status === "reset" || this.status === "closed") {
1838
- return;
1839
- }
1840
- this.log.error("abort with error - %e", err);
1841
- this.status = "aborted";
1842
- if (this.readBuffer.byteLength > 0) {
1843
- this.readBuffer.consume(this.readBuffer.byteLength);
1844
- }
1845
- if (this.writeBuffer.byteLength > 0) {
1846
- this.writeBuffer.consume(this.writeBuffer.byteLength);
1847
- this.safeDispatchEvent("idle");
1848
- }
1849
- this.writeStatus = "closed";
1850
- this.remoteWriteStatus = "closed";
1851
- this.readStatus = "closed";
1852
- this.remoteReadStatus = "closed";
1853
- this.timeline.close = Date.now();
1854
- try {
1855
- this.sendReset(err);
1856
- } catch (err2) {
1857
- this.log("failed to send reset to remote - %e", err2);
1858
- }
1859
- this.dispatchEvent(new StreamAbortEvent(err));
1860
- }
1861
- pause() {
1862
- if (this.readStatus === "closed" || this.readStatus === "closing") {
1863
- throw new StreamStateError("Cannot pause a stream that is closing/closed");
1864
- }
1865
- if (this.readStatus === "paused") {
1866
- return;
1867
- }
1868
- this.readStatus = "paused";
1869
- this.sendPause();
1870
- }
1871
- resume() {
1872
- if (this.readStatus === "closed" || this.readStatus === "closing") {
1873
- throw new StreamStateError("Cannot resume a stream that is closing/closed");
1874
- }
1875
- if (this.readStatus === "readable") {
1876
- return;
1877
- }
1878
- this.readStatus = "readable";
1879
- this.dispatchReadBuffer();
1880
- this.sendResume();
1881
- }
1882
- push(data) {
1883
- if (this.readStatus === "closed" || this.readStatus === "closing") {
1884
- throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`);
1885
- }
1886
- if (data.byteLength === 0) {
1887
- return;
1888
- }
1889
- this.readBuffer.append(data);
1890
- if (this.readStatus === "paused" || this.listenerCount("message") === 0) {
1891
- this.checkReadBufferLength();
1892
- return;
1893
- }
1894
- setTimeout(() => {
1895
- this.dispatchReadBuffer();
1896
- }, 0);
1897
- }
1898
- unshift(data) {
1899
- if (this.readStatus === "closed" || this.readStatus === "closing") {
1900
- throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`);
1901
- }
1902
- if (data.byteLength === 0) {
1903
- return;
1904
- }
1905
- this.readBuffer.prepend(data);
1906
- if (this.readStatus === "paused" || this.listenerCount("message") === 0) {
1907
- this.checkReadBufferLength();
1908
- return;
1909
- }
1910
- setTimeout(() => {
1911
- this.dispatchReadBuffer();
1912
- }, 0);
1913
- }
1914
- /**
1915
- * When an extending class reads data from it's implementation-specific source,
1916
- * call this method to allow the stream consumer to read the data.
1917
- */
1918
- onData(data) {
1919
- if (data.byteLength === 0) {
1920
- return;
1921
- }
1922
- if (this.readStatus === "closing" || this.readStatus === "closed") {
1923
- this.log("ignoring data - read status %s", this.readStatus);
1924
- return;
1925
- }
1926
- this.readBuffer.append(data);
1927
- this.dispatchReadBuffer();
1928
- }
1929
- addEventListener(...args) {
1930
- super.addEventListener.apply(this, args);
1931
- if (args[0] === "message" && this.readBuffer.byteLength > 0) {
1932
- queueMicrotask(() => {
1933
- this.dispatchReadBuffer();
1934
- });
1935
- }
1936
- }
1937
- /**
1938
- * Receive a reset message - close immediately for reading and writing (remote
1939
- * error)
1940
- */
1941
- onRemoteReset() {
1942
- this.log("remote reset");
1943
- this.status = "reset";
1944
- this.writeStatus = "closed";
1945
- this.remoteWriteStatus = "closed";
1946
- this.remoteReadStatus = "closed";
1947
- this.timeline.close = Date.now();
1948
- if (this.readBuffer.byteLength === 0) {
1949
- this.readStatus = "closed";
1950
- }
1951
- const err = new StreamResetError();
1952
- this.dispatchEvent(new StreamResetEvent(err));
1953
- }
1954
- /**
1955
- * The underlying resource or transport this stream uses has closed - it is
1956
- * not possible to send any more messages though any data still in the read
1957
- * buffer may still be read
1958
- */
1959
- onTransportClosed(err) {
1960
- this.log("transport closed");
1961
- if (this.readStatus === "readable" && this.readBuffer.byteLength === 0) {
1962
- this.log("close readable end after transport closed and read buffer is empty");
1963
- this.readStatus = "closed";
1964
- }
1965
- if (this.remoteReadStatus !== "closed") {
1966
- this.remoteReadStatus = "closed";
1967
- }
1968
- if (this.remoteWriteStatus !== "closed") {
1969
- this.remoteWriteStatus = "closed";
1970
- }
1971
- if (this.writeStatus !== "closed") {
1972
- this.writeStatus = "closed";
1973
- }
1974
- if (err != null) {
1975
- this.abort(err);
1976
- } else {
1977
- if (this.status === "open" || this.status === "closing") {
1978
- this.timeline.close = Date.now();
1979
- this.status = "closed";
1980
- this.writeStatus = "closed";
1981
- this.remoteWriteStatus = "closed";
1982
- this.remoteReadStatus = "closed";
1983
- this.dispatchEvent(new StreamCloseEvent());
1984
- }
1985
- }
1986
- }
1987
- /**
1988
- * Called by extending classes when the remote closes its writable end
1989
- */
1990
- onRemoteCloseWrite() {
1991
- if (this.remoteWriteStatus === "closed") {
1992
- return;
1993
- }
1994
- this.log.trace("on remote close write");
1995
- this.remoteWriteStatus = "closed";
1996
- this.safeDispatchEvent("remoteCloseWrite");
1997
- if (this.writeStatus === "closed") {
1998
- this.onTransportClosed();
1999
- }
2000
- }
2001
- /**
2002
- * Called by extending classes when the remote closes its readable end
2003
- */
2004
- onRemoteCloseRead() {
2005
- this.log.trace("on remote close read");
2006
- this.remoteReadStatus = "closed";
2007
- if (this.writeBuffer.byteLength > 0) {
2008
- this.writeBuffer.consume(this.writeBuffer.byteLength);
2009
- this.safeDispatchEvent("idle");
2010
- }
2011
- }
2012
- processSendQueue() {
2013
- if (this.writableNeedsDrain) {
2014
- this.log.trace("not processing send queue as drain is required");
2015
- this.checkWriteBufferLength();
2016
- return false;
2017
- }
2018
- if (this.writeBuffer.byteLength === 0) {
2019
- this.log.trace("not processing send queue as no bytes to send");
2020
- return true;
2021
- }
2022
- if (this.sendingData) {
2023
- this.log.trace("not processing send queue as already sending data");
2024
- return true;
2025
- }
2026
- this.sendingData = true;
2027
- this.log.trace("processing send queue with %d queued bytes", this.writeBuffer.byteLength);
2028
- try {
2029
- let canSendMore = true;
2030
- const totalBytes = this.writeBuffer.byteLength;
2031
- let sentBytes = 0;
2032
- while (this.writeBuffer.byteLength > 0) {
2033
- const end = Math.min(this.maxMessageSize ?? this.writeBuffer.byteLength, this.writeBuffer.byteLength);
2034
- if (end === 0) {
2035
- canSendMore = false;
2036
- break;
2037
- }
2038
- const toSend = this.writeBuffer.sublist(0, end);
2039
- const willSend = new Uint8ArrayList(toSend);
2040
- this.writeBuffer.consume(toSend.byteLength);
2041
- const sendResult = this.sendData(toSend);
2042
- canSendMore = sendResult.canSendMore;
2043
- sentBytes += sendResult.sentBytes;
2044
- if (sendResult.sentBytes !== willSend.byteLength) {
2045
- willSend.consume(sendResult.sentBytes);
2046
- this.writeBuffer.prepend(willSend);
2047
- }
2048
- if (!canSendMore) {
2049
- break;
2050
- }
2051
- }
2052
- if (!canSendMore) {
2053
- this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer", sentBytes, totalBytes, this.writeBuffer.byteLength);
2054
- this.writableNeedsDrain = true;
2055
- this.checkWriteBufferLength();
2056
- }
2057
- if (this.writeBuffer.byteLength === 0) {
2058
- this.safeDispatchEvent("idle");
2059
- }
2060
- return canSendMore;
2061
- } finally {
2062
- this.sendingData = false;
2063
- }
2064
- }
2065
- dispatchReadBuffer() {
2066
- try {
2067
- if (this.listenerCount("message") === 0) {
2068
- this.log.trace("not dispatching pause buffer as there are no listeners for the message event");
2069
- return;
2070
- }
2071
- if (this.readBuffer.byteLength === 0) {
2072
- this.log.trace("not dispatching pause buffer as there is no data to dispatch");
2073
- return;
2074
- }
2075
- if (this.readStatus === "paused") {
2076
- this.log.trace("not dispatching pause buffer we are paused");
2077
- return;
2078
- }
2079
- if (this.readStatus === "closing" || this.readStatus === "closed") {
2080
- this.log("dropping %d bytes because the readable end is %s", this.readBuffer.byteLength, this.readStatus);
2081
- this.readBuffer.consume(this.readBuffer.byteLength);
2082
- return;
2083
- }
2084
- const buf = this.readBuffer.sublist();
2085
- this.readBuffer.consume(buf.byteLength);
2086
- this.dispatchEvent(new StreamMessageEvent(buf));
2087
- } finally {
2088
- if (this.readBuffer.byteLength === 0 && this.remoteWriteStatus === "closed") {
2089
- this.log("close readable end after dispatching read buffer and remote writable end is closed");
2090
- this.readStatus = "closed";
2091
- }
2092
- this.checkReadBufferLength();
2093
- }
2094
- }
2095
- checkReadBufferLength() {
2096
- if (this.readBuffer.byteLength > this.maxReadBufferLength) {
2097
- this.abort(new StreamBufferError(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`));
2098
- }
2099
- }
2100
- checkWriteBufferLength() {
2101
- if (this.maxWriteBufferLength == null) {
2102
- return;
2103
- }
2104
- if (this.writeBuffer.byteLength > this.maxWriteBufferLength) {
2105
- this.abort(new StreamBufferError(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`));
2106
- }
2107
- }
2108
- onMuxerNeedsDrain() {
2109
- this.writableNeedsDrain = true;
2110
- }
2111
- onMuxerDrain() {
2112
- this.safeDispatchEvent("drain");
2113
- }
2114
- };
2115
-
2116
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/abstract-multiaddr-connection.js
2117
- init_esm_shims();
2118
- var AbstractMultiaddrConnection = class extends AbstractMessageStream {
2119
- remoteAddr;
2120
- metricPrefix;
2121
- metrics;
2122
- constructor(init) {
2123
- super(init);
2124
- this.metricPrefix = init.metricPrefix ?? "";
2125
- this.metrics = init.metrics;
2126
- this.remoteAddr = init.remoteAddr;
2127
- this.addEventListener("close", (evt) => {
2128
- this.metrics?.increment({ [`${this.metricPrefix}end`]: true });
2129
- if (evt.error != null) {
2130
- if (evt.local) {
2131
- this.metrics?.increment({ [`${this.metricPrefix}abort`]: true });
2132
- } else {
2133
- this.metrics?.increment({ [`${this.metricPrefix}reset`]: true });
2134
- }
2135
- } else {
2136
- if (evt.local) {
2137
- this.metrics?.increment({ [`${this.metricPrefix}_local_close`]: true });
2138
- } else {
2139
- this.metrics?.increment({ [`${this.metricPrefix}_remote_close`]: true });
2140
- }
2141
- }
2142
- });
2143
- }
2144
- async close(options) {
2145
- if (this.status !== "open") {
2146
- return;
2147
- }
2148
- this.status = "closing";
2149
- this.writeStatus = "closing";
2150
- this.remoteWriteStatus = "closing";
2151
- this.remoteReadStatus = "closing";
2152
- if (this.sendingData || this.writeBuffer.byteLength > 0) {
2153
- this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes", this.writeBuffer.byteLength);
2154
- await pEvent(this, "idle", {
2155
- ...options,
2156
- rejectionEvents: [
2157
- "close"
2158
- ]
2159
- });
2160
- }
2161
- if (this.writableNeedsDrain) {
2162
- this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes", this.writeBuffer.byteLength);
2163
- await pEvent(this, "drain", {
2164
- ...options,
2165
- rejectionEvents: [
2166
- "close"
2167
- ]
2168
- });
2169
- }
2170
- await this.sendClose(options);
2171
- this.onTransportClosed();
2172
- }
2173
- };
2174
-
2175
- // ../../node_modules/.pnpm/any-signal@4.2.0/node_modules/any-signal/dist/src/index.js
2176
- init_esm_shims();
2177
- function anySignal(signals) {
2178
- const controller = new globalThis.AbortController();
2179
- function onAbort() {
2180
- const reason = signals.filter((s) => s?.aborted === true).map((s) => s?.reason).pop();
2181
- controller.abort(reason);
2182
- for (const signal2 of signals) {
2183
- if (signal2?.removeEventListener != null) {
2184
- signal2.removeEventListener("abort", onAbort);
2185
- }
2186
- }
2187
- }
2188
- for (const signal2 of signals) {
2189
- if (signal2?.aborted === true) {
2190
- onAbort();
2191
- break;
2192
- }
2193
- if (signal2?.addEventListener != null) {
2194
- signal2.addEventListener("abort", onAbort);
2195
- }
2196
- }
2197
- function clear() {
2198
- for (const signal2 of signals) {
2199
- if (signal2?.removeEventListener != null) {
2200
- signal2.removeEventListener("abort", onAbort);
2201
- }
2202
- }
2203
- }
2204
- const signal = controller.signal;
2205
- signal.clear = clear;
2206
- return signal;
2207
- }
2208
-
2209
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/get-thin-waist-addresses.js
2210
- init_esm_shims();
2211
-
2212
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/link-local-ip.js
2213
- init_esm_shims();
2214
- function isLinkLocalIp(ip) {
2215
- if (ip.startsWith("169.254.")) {
2216
- return true;
2217
- }
2218
- if (ip.toLowerCase().startsWith("fe80")) {
2219
- return true;
2220
- }
2221
- return false;
2222
- }
2223
-
2224
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/multiaddr/utils.js
2225
- init_esm_shims();
2226
- function netConfigToMultiaddr(config, port, host) {
2227
- const parts = [
2228
- config.type,
2229
- host ?? config.host
2230
- ];
2231
- if (config.protocol != null) {
2232
- const p = port ?? config.port;
2233
- if (p != null) {
2234
- parts.push(config.protocol, p);
2235
- }
2236
- }
2237
- if (config.type === "ip6" && config.zone != null) {
2238
- parts.unshift("ip6zone", config.zone);
2239
- }
2240
- if (config.cidr != null) {
2241
- parts.push("ipcidr", config.cidr);
2242
- }
2243
- return multiaddr(`/${parts.join("/")}`);
2244
- }
2245
-
2246
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/get-thin-waist-addresses.js
2247
- var FAMILIES = { 4: "IPv4", 6: "IPv6" };
2248
- function isWildcard(ip) {
2249
- return ["0.0.0.0", "::"].includes(ip);
2250
- }
2251
- function getNetworkAddrs(family) {
2252
- const addresses = [];
2253
- const networks = os.networkInterfaces();
2254
- for (const [, netAddrs] of Object.entries(networks)) {
2255
- if (netAddrs != null) {
2256
- for (const netAddr of netAddrs) {
2257
- if (isLinkLocalIp(netAddr.address)) {
2258
- continue;
2259
- }
2260
- if (netAddr.family === FAMILIES[family]) {
2261
- addresses.push(netAddr.address);
2262
- }
2263
- }
2264
- }
2265
- }
2266
- return addresses;
2267
- }
2268
- function getThinWaistAddresses(ma, port) {
2269
- if (ma == null) {
2270
- return [];
2271
- }
2272
- const config = getNetConfig(ma);
2273
- if ((config.type === "ip4" || config.type === "ip6") && isWildcard(config.host)) {
2274
- return getNetworkAddrs(config.type === "ip4" ? 4 : 6).map((host) => netConfigToMultiaddr(config, port, host));
2275
- }
2276
- return [
2277
- netConfigToMultiaddr(config, port)
2278
- ];
2279
- }
2280
-
2281
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/ip-port-to-multiaddr.js
2282
- init_esm_shims();
2283
- function ipPortToMultiaddr(ip, port) {
2284
- if (typeof ip !== "string") {
2285
- throw new InvalidParametersError(`invalid ip provided: ${ip}`);
2286
- }
2287
- if (typeof port === "string") {
2288
- port = parseInt(port);
2289
- }
2290
- if (isNaN(port)) {
2291
- throw new InvalidParametersError(`invalid port provided: ${port}`);
2292
- }
2293
- if (isIPv4(ip)) {
2294
- return multiaddr(`/ip4/${ip}/tcp/${port}`);
2295
- }
2296
- if (isIPv6(ip)) {
2297
- return multiaddr(`/ip6/${ip}/tcp/${port}`);
2298
- }
2299
- throw new InvalidParametersError(`invalid ip:port for creating a multiaddr: ${ip}:${port}`);
2300
- }
2301
-
2302
- // ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/repeating-task.js
2303
- init_esm_shims();
2304
- function repeatingTask(fn, interval, options) {
2305
- let timeout;
2306
- let shutdownController;
2307
- let running = false;
2308
- function runTask() {
2309
- const opts = {
2310
- signal: shutdownController.signal
2311
- };
2312
- if (options?.timeout != null) {
2313
- const signal = anySignal([shutdownController.signal, AbortSignal.timeout(options.timeout)]);
2314
- setMaxListeners(Infinity, signal);
2315
- opts.signal = signal;
2316
- }
2317
- running = true;
2318
- Promise.resolve().then(async () => {
2319
- await fn(opts);
2320
- }).catch(() => {
2321
- }).finally(() => {
2322
- running = false;
2323
- if (shutdownController.signal.aborted) {
2324
- return;
2325
- }
2326
- timeout = setTimeout(runTask, interval);
2327
- });
2328
- }
2329
- const runTaskDebounced = debounce(runTask, options?.debounce ?? 100);
2330
- let started = false;
2331
- return {
2332
- setInterval: (ms) => {
2333
- if (interval === ms) {
2334
- return;
2335
- }
2336
- interval = ms;
2337
- if (timeout != null) {
2338
- clearTimeout(timeout);
2339
- timeout = setTimeout(runTask, interval);
2340
- }
2341
- },
2342
- setTimeout: (ms) => {
2343
- options ??= {};
2344
- options.timeout = ms;
2345
- },
2346
- run: () => {
2347
- if (running) {
2348
- return;
2349
- }
2350
- clearTimeout(timeout);
2351
- runTaskDebounced();
2352
- },
2353
- start: () => {
2354
- if (started) {
2355
- return;
2356
- }
2357
- started = true;
2358
- shutdownController = new AbortController();
2359
- setMaxListeners(Infinity, shutdownController.signal);
2360
- if (options?.runImmediately === true) {
2361
- queueMicrotask(() => {
2362
- runTask();
2363
- });
2364
- } else {
2365
- timeout = setTimeout(runTask, interval);
2366
- }
2367
- },
2368
- stop: () => {
2369
- clearTimeout(timeout);
2370
- shutdownController?.abort();
2371
- started = false;
2372
- }
2373
- };
2374
- }
2375
-
2376
- // ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/utils.js
2377
- init_esm_shims();
2378
- function toWebSocket(ws2) {
2379
- Object.defineProperty(ws2, "url", {
2380
- value: "",
2381
- writable: false
2382
- });
2383
- ws2.dispatchEvent = (evt) => {
2384
- if (evt.type === "close") {
2385
- ws2.emit("close");
2386
- }
2387
- if (evt.type === "open") {
2388
- ws2.emit("open");
2389
- }
2390
- if (evt.type === "message") {
2391
- const m = evt;
2392
- ws2.emit("data", m.data);
2393
- }
2394
- if (evt.type === "error") {
2395
- ws2.emit("error", new Error("An error occurred"));
2396
- }
2397
- ws2.emit(evt.type, evt);
2398
- };
2399
- return ws2;
2400
- }
2401
-
2402
- // ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/websocket-to-conn.js
2403
- init_esm_shims();
2404
- var DEFAULT_MAX_BUFFERED_AMOUNT = 1024 * 1024 * 4;
2405
- var DEFAULT_BUFFERED_AMOUNT_POLL_INTERVAL = 10;
2406
- var WebSocketMultiaddrConnection = class extends AbstractMultiaddrConnection {
2407
- websocket;
2408
- maxBufferedAmount;
2409
- checkBufferedAmountTask;
2410
- constructor(init) {
2411
- super(init);
2412
- this.websocket = init.websocket;
2413
- this.maxBufferedAmount = init.maxBufferedAmount ?? DEFAULT_MAX_BUFFERED_AMOUNT;
2414
- this.checkBufferedAmountTask = repeatingTask(this.checkBufferedAmount.bind(this), init.bufferedAmountPollInterval ?? DEFAULT_BUFFERED_AMOUNT_POLL_INTERVAL);
2415
- this.websocket.addEventListener("close", (evt) => {
2416
- this.log('closed - code %d, reason "%s", wasClean %s', evt.code, evt.reason, evt.wasClean);
2417
- this.checkBufferedAmountTask.stop();
2418
- if (!evt.wasClean) {
2419
- this.onRemoteReset();
2420
- return;
2421
- }
2422
- this.onTransportClosed();
2423
- }, { once: true });
2424
- this.websocket.addEventListener("message", (evt) => {
2425
- try {
2426
- let buf;
2427
- if (typeof evt.data === "string") {
2428
- buf = fromString(evt.data);
2429
- } else if (evt.data instanceof ArrayBuffer) {
2430
- buf = new Uint8Array(evt.data, 0, evt.data.byteLength);
2431
- } else {
2432
- this.abort(new Error("Incorrect binary type"));
2433
- return;
2434
- }
2435
- this.onData(buf);
2436
- } catch (err) {
2437
- this.log.error("error receiving data - %e", err);
2438
- }
2439
- });
2440
- }
2441
- sendData(data) {
2442
- for (const buf of data) {
2443
- this.websocket.send(buf);
2444
- }
2445
- const canSendMore = this.websocket.bufferedAmount < this.maxBufferedAmount;
2446
- if (!canSendMore) {
2447
- this.checkBufferedAmountTask.start();
2448
- }
2449
- return {
2450
- sentBytes: data.byteLength,
2451
- canSendMore
2452
- };
2453
- }
2454
- sendReset() {
2455
- this.websocket.close(1006);
2456
- }
2457
- async sendClose(options) {
2458
- this.websocket.close();
2459
- options?.signal?.throwIfAborted();
2460
- }
2461
- sendPause() {
2462
- }
2463
- sendResume() {
2464
- }
2465
- checkBufferedAmount() {
2466
- this.log("buffered amount now %d", this.websocket.bufferedAmount);
2467
- if (this.websocket.bufferedAmount === 0) {
2468
- this.checkBufferedAmountTask.stop();
2469
- this.safeDispatchEvent("drain");
2470
- }
2471
- }
2472
- };
2473
- function webSocketToMaConn(init) {
2474
- return new WebSocketMultiaddrConnection(init);
2475
- }
2476
-
2477
- // ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/listener.js
2478
- var WebSocketListener = class extends TypedEventEmitter {
2479
- components;
2480
- log;
2481
- server;
2482
- wsServer;
2483
- metrics;
2484
- sockets;
2485
- upgrader;
2486
- httpOptions;
2487
- httpsOptions;
2488
- shutdownController;
2489
- http;
2490
- https;
2491
- addr;
2492
- listeningMultiaddr;
2493
- maxBufferedAmount;
2494
- bufferedAmountPollInterval;
2495
- constructor(components, init) {
2496
- super();
2497
- this.components = components;
2498
- this.log = components.logger.forComponent("libp2p:websockets:listener");
2499
- this.upgrader = init.upgrader;
2500
- this.httpOptions = init.http;
2501
- this.httpsOptions = init.https ?? init.http;
2502
- this.maxBufferedAmount = init.maxBufferedAmount;
2503
- this.bufferedAmountPollInterval = init.bufferedAmountPollInterval;
2504
- this.sockets = /* @__PURE__ */ new Set();
2505
- this.shutdownController = new AbortController();
2506
- setMaxListeners(Infinity, this.shutdownController.signal);
2507
- this.wsServer = new ws.WebSocketServer({
2508
- noServer: true
2509
- });
2510
- this.wsServer.addListener("connection", this.onWsServerConnection.bind(this));
2511
- components.metrics?.registerMetricGroup("libp2p_websockets_inbound_connections_total", {
2512
- label: "address",
2513
- help: "Current active connections in WebSocket listener",
2514
- calculate: () => {
2515
- if (this.addr == null) {
2516
- return {};
2517
- }
2518
- return {
2519
- [this.addr]: this.sockets.size
2520
- };
2521
- }
2522
- });
2523
- this.metrics = {
2524
- status: components.metrics?.registerMetricGroup("libp2p_websockets_listener_status_info", {
2525
- label: "address",
2526
- help: "Current status of the WebSocket listener socket"
2527
- }),
2528
- errors: components.metrics?.registerMetricGroup("libp2p_websockets_listener_errors_total", {
2529
- label: "address",
2530
- help: "Total count of WebSocket listener errors by type"
2531
- }),
2532
- events: components.metrics?.registerMetricGroup("libp2p_websockets_listener_events_total", {
2533
- label: "address",
2534
- help: "Total count of WebSocket listener events by type"
2535
- })
2536
- };
2537
- this.server = net.createServer({
2538
- pauseOnConnect: true
2539
- }, (socket) => {
2540
- this.onSocketConnection(socket).catch((err) => {
2541
- this.log.error("error handling socket - %e", err);
2542
- socket.destroy();
2543
- });
2544
- });
2545
- components.events.addEventListener("certificate:provision", this.onCertificateProvision.bind(this));
2546
- components.events.addEventListener("certificate:renew", this.onCertificateRenew.bind(this));
2547
- }
2548
- async onSocketConnection(socket) {
2549
- this.metrics.events?.increment({ [`${this.addr} connection`]: true });
2550
- let buffer = socket.read(1);
2551
- if (buffer == null) {
2552
- await pEvent(socket, "readable");
2553
- buffer = socket.read(1);
2554
- }
2555
- const byte = buffer[0];
2556
- let server = this.http;
2557
- if (byte < 32 || byte >= 127) {
2558
- server = this.https;
2559
- }
2560
- if (server == null) {
2561
- this.log.error("no appropriate listener configured for byte %d", byte);
2562
- socket.destroy();
2563
- return;
2564
- }
2565
- this.sockets.add(socket);
2566
- socket.on("close", () => {
2567
- this.metrics.events?.increment({ [`${this.addr} close`]: true });
2568
- this.sockets.delete(socket);
2569
- });
2570
- socket.on("error", (err) => {
2571
- this.log.error("socket error - %e", err);
2572
- this.metrics.events?.increment({ [`${this.addr} error`]: true });
2573
- socket.destroy();
2574
- });
2575
- socket.once("timeout", () => {
2576
- this.metrics.events?.increment({ [`${this.addr} timeout`]: true });
2577
- });
2578
- socket.once("end", () => {
2579
- this.metrics.events?.increment({ [`${this.addr} end`]: true });
2580
- });
2581
- socket.unshift(buffer);
2582
- server.emit("connection", socket);
2583
- }
2584
- onWsServerConnection(socket, req) {
2585
- let addr;
2586
- socket.binaryType = "arraybuffer";
2587
- try {
2588
- addr = this.server.address();
2589
- if (typeof addr === "string") {
2590
- throw new Error("Cannot listen on unix sockets");
2591
- }
2592
- if (addr == null) {
2593
- throw new Error("Server was closing or not running");
2594
- }
2595
- } catch (err) {
2596
- this.log.error("error obtaining remote socket address - %e", err);
2597
- req.destroy(err);
2598
- socket.close();
2599
- return;
2600
- }
2601
- let maConn;
2602
- try {
2603
- maConn = webSocketToMaConn({
2604
- websocket: toWebSocket(socket),
2605
- remoteAddr: ipPortToMultiaddr(req.socket.remoteAddress ?? "0.0.0.0", req.socket.remotePort ?? 0).encapsulate("/ws"),
2606
- metrics: this.metrics?.events,
2607
- metricPrefix: `${this.addr} `,
2608
- direction: "inbound",
2609
- log: this.components.logger.forComponent("libp2p:websockets:connection"),
2610
- maxBufferedAmount: this.maxBufferedAmount,
2611
- bufferedAmountPollInterval: this.bufferedAmountPollInterval
2612
- });
2613
- } catch (err) {
2614
- this.log.error("inbound connection failed - %e", err);
2615
- this.metrics.errors?.increment({ [`${this.addr} inbound_to_connection`]: true });
2616
- socket.close();
2617
- return;
2618
- }
2619
- this.log("new inbound connection %s", maConn.remoteAddr);
2620
- this.upgrader.upgradeInbound(maConn, {
2621
- signal: this.shutdownController.signal
2622
- }).catch(async (err) => {
2623
- this.log.error("inbound connection failed to upgrade - %e", err);
2624
- this.metrics.errors?.increment({ [`${this.addr} inbound_upgrade`]: true });
2625
- maConn.close();
2626
- });
2627
- }
2628
- onUpgrade(req, socket, head) {
2629
- this.wsServer.handleUpgrade(req, socket, head, this.onWsServerConnection.bind(this));
2630
- }
2631
- onTLSClientError(err, socket) {
2632
- this.log.error("TLS client error - %e", err);
2633
- socket.destroy();
2634
- }
2635
- async listen(ma) {
2636
- if (WebSockets.exactMatch(ma)) {
2637
- this.http = http.createServer(this.httpOptions ?? {}, this.httpRequestHandler.bind(this));
2638
- this.http.addListener("upgrade", this.onUpgrade.bind(this));
2639
- } else if (WebSocketsSecure.exactMatch(ma)) {
2640
- this.https = https.createServer(this.httpsOptions ?? {}, this.httpRequestHandler.bind(this));
2641
- this.https.addListener("upgrade", this.onUpgrade.bind(this));
2642
- this.https.addListener("tlsClientError", this.onTLSClientError.bind(this));
2643
- }
2644
- const config = getNetConfig(ma);
2645
- this.addr = `${config.host}:${config.port}`;
2646
- this.server.listen({
2647
- ...config,
2648
- ipv6Only: config.type === "ip6"
2649
- });
2650
- await new Promise((resolve, reject) => {
2651
- const onListening = () => {
2652
- removeListeners();
2653
- resolve();
2654
- };
2655
- const onError = (err) => {
2656
- this.metrics.errors?.increment({ [`${this.addr} listen_error`]: true });
2657
- removeListeners();
2658
- reject(err);
2659
- };
2660
- const onDrop = () => {
2661
- this.metrics.events?.increment({ [`${this.addr} drop`]: true });
2662
- };
2663
- const removeListeners = () => {
2664
- this.server.removeListener("listening", onListening);
2665
- this.server.removeListener("error", onError);
2666
- this.server.removeListener("drop", onDrop);
2667
- };
2668
- this.server.addListener("listening", onListening);
2669
- this.server.addListener("error", onError);
2670
- this.server.addListener("drop", onDrop);
2671
- });
2672
- this.listeningMultiaddr = ma;
2673
- this.safeDispatchEvent("listening");
2674
- }
2675
- onCertificateProvision(event) {
2676
- if (this.https != null) {
2677
- this.log("auto-tls certificate found but already listening on https");
2678
- return;
2679
- }
2680
- this.log("auto-tls certificate found, starting https server");
2681
- this.https = https.createServer({
2682
- ...this.httpsOptions,
2683
- ...event.detail
2684
- }, this.httpRequestHandler.bind(this));
2685
- this.https.addListener("upgrade", this.onUpgrade.bind(this));
2686
- this.https.addListener("tlsClientError", this.onTLSClientError.bind(this));
2687
- this.safeDispatchEvent("listening");
2688
- }
2689
- onCertificateRenew(event) {
2690
- this.https?.close();
2691
- this.log("auto-tls certificate renewed, restarting https server");
2692
- this.https = https.createServer({
2693
- ...this.httpsOptions,
2694
- ...event.detail
2695
- }, this.httpRequestHandler.bind(this));
2696
- this.https.addListener("upgrade", this.onUpgrade.bind(this));
2697
- this.https.addListener("tlsClientError", this.onTLSClientError.bind(this));
2698
- }
2699
- async close() {
2700
- this.server.close();
2701
- this.http?.close();
2702
- this.https?.close();
2703
- this.wsServer.close();
2704
- this.http?.closeAllConnections();
2705
- this.https?.closeAllConnections();
2706
- [...this.sockets].forEach((socket) => {
2707
- socket.destroy();
2708
- });
2709
- this.shutdownController.abort();
2710
- const events = [
2711
- pEvent(this.server, "close"),
2712
- pEvent(this.wsServer, "close")
2713
- ];
2714
- if (this.http != null) {
2715
- events.push(pEvent(this.http, "close"));
2716
- }
2717
- if (this.https != null) {
2718
- events.push(pEvent(this.https, "close"));
2719
- }
2720
- await Promise.all(events);
2721
- this.safeDispatchEvent("close");
2722
- }
2723
- getAddrs() {
2724
- const address = this.server.address();
2725
- if (address == null) {
2726
- return [];
2727
- }
2728
- if (typeof address === "string") {
2729
- return [multiaddr(`/unix/${encodeURIComponent(address)}/ws`)];
2730
- }
2731
- const multiaddrs = getThinWaistAddresses(this.listeningMultiaddr, address.port);
2732
- const insecureMultiaddrs = [];
2733
- if (this.http != null) {
2734
- multiaddrs.forEach((ma) => {
2735
- insecureMultiaddrs.push(ma.encapsulate("/ws"));
2736
- });
2737
- }
2738
- const secureMultiaddrs = [];
2739
- if (this.https != null) {
2740
- multiaddrs.forEach((ma) => {
2741
- secureMultiaddrs.push(ma.encapsulate("/tls/ws"));
2742
- });
2743
- }
2744
- return [
2745
- ...insecureMultiaddrs,
2746
- ...secureMultiaddrs
2747
- ];
2748
- }
2749
- updateAnnounceAddrs() {
2750
- }
2751
- httpRequestHandler(req, res) {
2752
- res.writeHead(400);
2753
- res.write("Only WebSocket connections are supported");
2754
- res.end();
2755
- }
2756
- };
2757
- function createListener(components, init) {
2758
- return new WebSocketListener(components, init);
2759
- }
2760
-
2761
- // ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/index.js
2762
- var WebSockets2 = class {
2763
- log;
2764
- init;
2765
- logger;
2766
- metrics;
2767
- components;
2768
- constructor(components, init = {}) {
2769
- this.log = components.logger.forComponent("libp2p:websockets");
2770
- this.logger = components.logger;
2771
- this.components = components;
2772
- this.init = init;
2773
- if (components.metrics != null) {
2774
- this.metrics = {
2775
- dialerEvents: components.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total", {
2776
- label: "event",
2777
- help: "Total count of WebSockets dialer events by type"
2778
- })
2779
- };
2780
- }
2781
- }
2782
- [transportSymbol] = true;
2783
- [Symbol.toStringTag] = "@libp2p/websockets";
2784
- [serviceCapabilities] = [
2785
- "@libp2p/transport"
2786
- ];
2787
- async dial(ma, options) {
2788
- this.log("dialing %s", ma);
2789
- options = options ?? {};
2790
- const maConn = webSocketToMaConn({
2791
- websocket: await this._connect(ma, options),
2792
- remoteAddr: ma,
2793
- metrics: this.metrics?.dialerEvents,
2794
- direction: "outbound",
2795
- log: this.components.logger.forComponent("libp2p:websockets:connection"),
2796
- maxBufferedAmount: this.init.maxBufferedAmount,
2797
- bufferedAmountPollInterval: this.init.bufferedAmountPollInterval
2798
- });
2799
- this.log("new outbound connection %s", maConn.remoteAddr);
2800
- const conn = await options.upgrader.upgradeOutbound(maConn, options);
2801
- this.log("outbound connection %s upgraded", maConn.remoteAddr);
2802
- return conn;
2803
- }
2804
- async _connect(ma, options) {
2805
- options?.signal?.throwIfAborted();
2806
- const uri = multiaddrToUri(ma);
2807
- this.log("create websocket connection to %s", uri);
2808
- const websocket = new WebSocket(uri);
2809
- websocket.binaryType = "arraybuffer";
2810
- try {
2811
- options.onProgress?.(new CustomProgressEvent("websockets:open-connection"));
2812
- await pEvent(websocket, "open", options);
2813
- } catch (err) {
2814
- if (options.signal?.aborted) {
2815
- this.metrics?.dialerEvents.increment({ abort: true });
2816
- throw new ConnectionFailedError(`Could not connect to ${uri}`);
2817
- } else {
2818
- this.metrics?.dialerEvents.increment({ error: true });
2819
- }
2820
- try {
2821
- websocket.close();
2822
- } catch {
2823
- }
2824
- throw err;
2825
- }
2826
- this.log("connected %s", ma);
2827
- this.metrics?.dialerEvents.increment({ connect: true });
2828
- return websocket;
2829
- }
2830
- /**
2831
- * Creates a WebSockets listener. The provided `handler` function will be called
2832
- * anytime a new incoming Connection has been successfully upgraded via
2833
- * `upgrader.upgradeInbound`
2834
- */
2835
- createListener(options) {
2836
- return createListener({
2837
- logger: this.logger,
2838
- events: this.components.events,
2839
- metrics: this.components.metrics
2840
- }, {
2841
- ...this.init,
2842
- ...options
2843
- });
2844
- }
2845
- listenFilter(multiaddrs) {
2846
- return multiaddrs.filter((ma) => WebSockets.exactMatch(ma) || WebSocketsSecure.exactMatch(ma));
2847
- }
2848
- dialFilter(multiaddrs) {
2849
- return this.listenFilter(multiaddrs);
2850
- }
2851
- };
2852
- function webSockets(init = {}) {
2853
- return (components) => {
2854
- return new WebSockets2(components, init);
2855
- };
2856
- }
2857
-
2858
- // src/utils/logger.ts
2859
- init_esm_shims();
2860
- var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
2861
- LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
2862
- LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
2863
- LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
2864
- LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
2865
- return LogLevel2;
2866
- })(LogLevel || {});
2867
- var Logger = class {
2868
- level;
2869
- prefix;
2870
- constructor(prefix, level = 1 /* INFO */) {
2871
- this.prefix = prefix;
2872
- this.level = level;
2873
- }
2874
- setLevel(level) {
2875
- this.level = level;
2876
- }
2877
- debug(message, ...args) {
2878
- if (this.level <= 0 /* DEBUG */) {
2879
- console.debug(`[${this.prefix}] DEBUG:`, message, ...args);
2880
- }
2881
- }
2882
- info(message, ...args) {
2883
- if (this.level <= 1 /* INFO */) {
2884
- console.info(`[${this.prefix}] INFO:`, message, ...args);
342
+ }
343
+ case "PONG": {
344
+ conn.peerCount = msg.peers;
345
+ logger.debug("Received PONG", { peers: msg.peers });
346
+ break;
347
+ }
348
+ case "GOODBYE": {
349
+ const goodbye = msg;
350
+ const reconnectAfter = goodbye.reconnectAfter || 5e3;
351
+ logger.info("Received GOODBYE", { url: conn.url, reconnectAfter });
352
+ if (conn.ws) {
353
+ conn.ws.close();
354
+ }
355
+ setTimeout(() => {
356
+ if (!stopped) {
357
+ connectToRelay(conn);
358
+ }
359
+ }, reconnectAfter);
360
+ break;
361
+ }
362
+ default:
363
+ logger.debug("Received relay message", { type: msg.type });
2885
364
  }
2886
365
  }
2887
- warn(message, ...args) {
2888
- if (this.level <= 2 /* WARN */) {
2889
- console.warn(`[${this.prefix}] WARN:`, message, ...args);
2890
- }
366
+ function getConnectedConnection() {
367
+ return connections.find((c) => c.connected && c.ws) || null;
2891
368
  }
2892
- error(message, ...args) {
2893
- if (this.level <= 3 /* ERROR */) {
2894
- console.error(`[${this.prefix}] ERROR:`, message, ...args);
369
+ async function sendToRelay(msg) {
370
+ const conn = getConnectedConnection();
371
+ if (!conn || !conn.ws) {
372
+ throw new TransportError("No connected relay");
2895
373
  }
374
+ conn.ws.send(encode(msg));
2896
375
  }
2897
- };
2898
- var createLogger = (prefix, level) => {
2899
- return new Logger(prefix, level);
2900
- };
2901
-
2902
- // src/transport/node.ts
2903
- var logger = createLogger("transport");
2904
- async function createNode(config) {
2905
- try {
2906
- const {
2907
- listenAddresses = ["/ip4/0.0.0.0/tcp/0", "/ip4/0.0.0.0/tcp/0/ws"],
2908
- // CVP-0010 §5: Add WebSocket listener
2909
- bootstrapPeers = [],
2910
- enableDHT = true,
2911
- enableRelay = false,
2912
- reserveRelaySlot = false,
2913
- enableMDNS = false,
2914
- privateKey
2915
- } = config;
2916
- const relayListenAddrs = reserveRelaySlot ? bootstrapPeers.map((peer) => `${peer}/p2p-circuit`) : [];
2917
- const libp2pConfig = {
2918
- addresses: {
2919
- listen: [...listenAddresses, ...relayListenAddrs]
2920
- },
2921
- ...privateKey ? { privateKey } : {},
2922
- transports: [
2923
- tcp(),
2924
- webSockets(),
2925
- // CVP-0010 §5: WebSocket for firewall traversal
2926
- circuitRelayTransport()
2927
- ],
2928
- connectionEncrypters: [noise()],
2929
- streamMuxers: [mplex()],
2930
- connectionManager: {
2931
- minConnections: bootstrapPeers.length > 0 ? 1 : 0,
2932
- maxConnections: 50
2933
- },
2934
- services: {
2935
- identify: identify(),
2936
- ping: ping()
376
+ return {
377
+ async start() {
378
+ stopped = false;
379
+ logger.info("Starting relay client", { relays: relayUrls.length });
380
+ for (let i = 0; i < connections.length; i++) {
381
+ const conn = connections[i];
382
+ setTimeout(() => {
383
+ connectToRelay(conn);
384
+ }, Math.random() * 2e3);
385
+ }
386
+ const maxWait = 15e3;
387
+ const start = Date.now();
388
+ while (Date.now() - start < maxWait) {
389
+ if (getConnectedConnection()) {
390
+ logger.info("Relay client started");
391
+ return;
392
+ }
393
+ await new Promise((resolve) => setTimeout(resolve, 100));
2937
394
  }
2938
- };
2939
- if (enableRelay) {
2940
- libp2pConfig.services.relay = circuitRelayServer({
2941
- reservations: {
2942
- maxReservations: 100
2943
- // Allow up to 100 concurrent relay reservations
395
+ throw new TransportError("Failed to connect to any relay");
396
+ },
397
+ async stop() {
398
+ stopped = true;
399
+ logger.info("Stopping relay client");
400
+ for (const conn of connections) {
401
+ if (conn.reconnectTimer) {
402
+ clearTimeout(conn.reconnectTimer);
403
+ conn.reconnectTimer = null;
404
+ }
405
+ if (conn.stableTimer) {
406
+ clearTimeout(conn.stableTimer);
407
+ conn.stableTimer = null;
2944
408
  }
409
+ if (conn.pingTimer) {
410
+ clearInterval(conn.pingTimer);
411
+ conn.pingTimer = null;
412
+ }
413
+ if (conn.ws) {
414
+ conn.ws.close();
415
+ conn.ws = null;
416
+ }
417
+ conn.connected = false;
418
+ }
419
+ logger.info("Relay client stopped");
420
+ },
421
+ async sendEnvelope(toDid, envelopeBytes) {
422
+ const msg = {
423
+ type: "SEND",
424
+ to: toDid,
425
+ envelope: envelopeBytes
426
+ };
427
+ await sendToRelay(msg);
428
+ logger.debug("Sent envelope", { to: toDid, size: envelopeBytes.length });
429
+ },
430
+ async discover(query, minTrust, limit) {
431
+ const conn = getConnectedConnection();
432
+ const ws = conn?.ws;
433
+ if (!conn || !ws) {
434
+ throw new TransportError("No connected relay");
435
+ }
436
+ return new Promise((resolve, reject) => {
437
+ const timeout = setTimeout(() => {
438
+ reject(new TransportError("Discover timeout"));
439
+ }, 1e4);
440
+ const handler = (data) => {
441
+ try {
442
+ const msg = decode(data);
443
+ if (msg.type === "DISCOVERED") {
444
+ clearTimeout(timeout);
445
+ ws.off("message", handler);
446
+ resolve(msg.agents);
447
+ }
448
+ } catch (err) {
449
+ }
450
+ };
451
+ ws.on("message", handler);
452
+ ws.send(encode({ type: "DISCOVER", query, minTrust, limit }));
2945
453
  });
2946
- }
2947
- if (enableDHT) {
2948
- libp2pConfig.services.dht = kadDHT({
2949
- clientMode: false,
2950
- peerInfoMapper: passthroughMapper,
2951
- validators: {
2952
- clawiverse: async () => {
454
+ },
455
+ async fetchCard(did2) {
456
+ const conn = getConnectedConnection();
457
+ const ws = conn?.ws;
458
+ if (!conn || !ws) {
459
+ throw new TransportError("No connected relay");
460
+ }
461
+ return new Promise((resolve, reject) => {
462
+ const timeout = setTimeout(() => {
463
+ reject(new TransportError("Fetch card timeout"));
464
+ }, 5e3);
465
+ const handler = (data) => {
466
+ try {
467
+ const msg = decode(data);
468
+ if (msg.type === "CARD" && msg.did === did2) {
469
+ clearTimeout(timeout);
470
+ ws.off("message", handler);
471
+ resolve(msg.card);
472
+ }
473
+ } catch (err) {
2953
474
  }
2954
- },
2955
- selectors: {
2956
- clawiverse: () => 0
2957
- },
2958
- // Optimize for small networks: reduce replication factor and query timeout
2959
- kBucketSize: 20,
2960
- // Default K=20, keep for compatibility
2961
- querySelfInterval: 3e4,
2962
- // Self-query every 30 seconds (libp2p default)
2963
- // Allow queries to complete faster in small networks
2964
- allowQueryWithZeroPeers: true
475
+ };
476
+ ws.on("message", handler);
477
+ ws.send(encode({ type: "FETCH_CARD", did: did2 }));
2965
478
  });
479
+ },
480
+ onDeliver(handler) {
481
+ deliveryHandler = handler;
482
+ },
483
+ onDeliveryReport(handler) {
484
+ deliveryReportHandler = handler;
485
+ },
486
+ isConnected() {
487
+ return getConnectedConnection() !== null;
488
+ },
489
+ getConnectedRelays() {
490
+ return connections.filter((c) => c.connected).map((c) => c.url);
491
+ },
492
+ getPeerCount() {
493
+ const conn = getConnectedConnection();
494
+ return conn ? conn.peerCount : 0;
2966
495
  }
2967
- const peerDiscovery = [];
2968
- if (bootstrapPeers.length > 0) peerDiscovery.push(bootstrap({ list: bootstrapPeers }));
2969
- if (enableMDNS) {
2970
- const { mdns } = await import('@libp2p/mdns');
2971
- peerDiscovery.push(mdns());
2972
- }
2973
- if (peerDiscovery.length > 0) libp2pConfig.peerDiscovery = peerDiscovery;
2974
- const libp2p = await createLibp2p(libp2pConfig);
2975
- logger.info("Libp2p node created", {
2976
- listenAddresses: libp2pConfig.addresses.listen,
2977
- reserveRelaySlot
2978
- });
2979
- return {
2980
- libp2p,
2981
- start: async () => {
2982
- await libp2p.start();
2983
- logger.info("Node started", {
2984
- peerId: libp2p.peerId.toString(),
2985
- addresses: libp2p.getMultiaddrs().map((ma) => ma.toString()),
2986
- relay: enableRelay,
2987
- reserveRelaySlot
2988
- });
2989
- },
2990
- stop: async () => {
2991
- await libp2p.stop();
2992
- logger.info("Node stopped");
2993
- },
2994
- getMultiaddrs: () => {
2995
- return libp2p.getMultiaddrs().map((ma) => ma.toString());
2996
- },
2997
- getPeerId: () => {
2998
- return libp2p.peerId.toString();
2999
- }
3000
- };
3001
- } catch (error) {
3002
- throw new TransportError("Failed to create transport node", error);
3003
- }
496
+ };
3004
497
  }
3005
498
 
3006
- // src/discovery/agent-card.ts
3007
- init_esm_shims();
499
+ // src/transport/relay-types.ts
500
+ var RELAY_PROTOCOL_VERSION = 1;
3008
501
 
3009
502
  // src/discovery/agent-card-types.ts
3010
- init_esm_shims();
3011
503
  function isLegacyCard(card) {
3012
504
  return Array.isArray(card.capabilities) && card.capabilities.length > 0 && typeof card.capabilities[0] === "string";
3013
505
  }
@@ -3137,7 +629,6 @@ function matchesCapability(card, capability) {
3137
629
  }
3138
630
 
3139
631
  // src/discovery/agent-card-schema.ts
3140
- init_esm_shims();
3141
632
  var CLAWIVERSE_CONTEXT = "https://clawiverse.org/context/v1";
3142
633
  var SCHEMA_ORG_CONTEXT = "https://schema.org";
3143
634
  var clawiverseContext = {
@@ -3196,9 +687,6 @@ function isValidContext(context) {
3196
687
  if (!Array.isArray(context)) return false;
3197
688
  return context.every((c) => typeof c === "string");
3198
689
  }
3199
-
3200
- // src/discovery/agent-card-encoder.ts
3201
- init_esm_shims();
3202
690
  function encodeForDHT(card) {
3203
691
  try {
3204
692
  const { "@context": _, ...cardWithoutContext } = card;
@@ -3267,15 +755,70 @@ function getEncodedSize(card) {
3267
755
  };
3268
756
  }
3269
757
 
3270
- // src/discovery/dht.ts
3271
- init_esm_shims();
3272
-
3273
- // src/discovery/semantic-search.ts
3274
- init_esm_shims();
3275
-
3276
- // src/discovery/search-index.ts
3277
- init_esm_shims();
3278
- var logger2 = createLogger("search-index");
758
+ // src/discovery/relay-index.ts
759
+ var logger2 = createLogger("relay-index");
760
+ function createRelayIndexOperations(client) {
761
+ return {
762
+ publishAgentCard: async (card) => {
763
+ logger2.debug("Agent Card published via HELLO", { did: card.did });
764
+ },
765
+ queryAgentCard: async (did) => {
766
+ try {
767
+ const card = await client.fetchCard(did);
768
+ if (card) {
769
+ logger2.debug("Found Agent Card via relay", { did });
770
+ } else {
771
+ logger2.debug("Agent Card not found via relay", { did });
772
+ }
773
+ return card;
774
+ } catch (error) {
775
+ logger2.warn("Failed to query Agent Card", { did, error });
776
+ return null;
777
+ }
778
+ },
779
+ queryByCapability: async (capability) => {
780
+ try {
781
+ const results = await client.discover(capability);
782
+ const cards = results.map((r) => r.card);
783
+ logger2.debug("Query by capability", { capability, count: cards.length });
784
+ return cards;
785
+ } catch (error) {
786
+ throw new DiscoveryError("Failed to query by capability", error);
787
+ }
788
+ },
789
+ searchSemantic: async (query) => {
790
+ try {
791
+ const queryText = query.text || query.capability || "";
792
+ const minTrust = query.filters?.minTrustScore;
793
+ const limit = query.limit || 10;
794
+ const results = await client.discover(queryText, minTrust, limit);
795
+ const cards = results.map((r) => r.card);
796
+ logger2.debug("Semantic search", { query: queryText, count: cards.length });
797
+ return cards;
798
+ } catch (error) {
799
+ throw new DiscoveryError("Failed to perform semantic search", error);
800
+ }
801
+ },
802
+ resolveDID: async (did) => {
803
+ try {
804
+ const relays = client.getConnectedRelays();
805
+ if (relays.length === 0) {
806
+ logger2.debug("DID resolution failed: no connected relays", { did });
807
+ return null;
808
+ }
809
+ logger2.debug("Resolved DID to relay", { did, relay: relays[0] });
810
+ return { relayUrl: relays[0] };
811
+ } catch (error) {
812
+ logger2.warn("Failed to resolve DID", { did, error });
813
+ return null;
814
+ }
815
+ },
816
+ queryRelayPeers: async () => {
817
+ return client.getConnectedRelays();
818
+ }
819
+ };
820
+ }
821
+ var logger3 = createLogger("search-index");
3279
822
  var SearchIndex = class {
3280
823
  cards = /* @__PURE__ */ new Map();
3281
824
  lunrIndex;
@@ -3287,7 +830,7 @@ var SearchIndex = class {
3287
830
  indexAgentCard(card) {
3288
831
  this.cards.set(card.did, card);
3289
832
  this.needsRebuild = true;
3290
- logger2.debug("Indexed Agent Card", { did: card.did, capabilities: card.capabilities.length });
833
+ logger3.debug("Indexed Agent Card", { did: card.did, capabilities: card.capabilities.length });
3291
834
  }
3292
835
  /**
3293
836
  * Remove an Agent Card from the index
@@ -3295,7 +838,7 @@ var SearchIndex = class {
3295
838
  removeAgentCard(did) {
3296
839
  this.cards.delete(did);
3297
840
  this.needsRebuild = true;
3298
- logger2.debug("Removed Agent Card from index", { did });
841
+ logger3.debug("Removed Agent Card from index", { did });
3299
842
  }
3300
843
  /**
3301
844
  * Search for agents matching a query
@@ -3322,7 +865,7 @@ var SearchIndex = class {
3322
865
  if (query.limit) {
3323
866
  results = results.slice(0, query.limit);
3324
867
  }
3325
- logger2.debug("Search completed", { query, results: results.length });
868
+ logger3.debug("Search completed", { query, results: results.length });
3326
869
  return results;
3327
870
  }
3328
871
  /**
@@ -3339,7 +882,7 @@ var SearchIndex = class {
3339
882
  this.lunrIndex = void 0;
3340
883
  this.fuse = void 0;
3341
884
  this.needsRebuild = false;
3342
- logger2.info("Search index cleared");
885
+ logger3.info("Search index cleared");
3343
886
  }
3344
887
  /**
3345
888
  * Get index size
@@ -3351,7 +894,7 @@ var SearchIndex = class {
3351
894
  * Rebuild search indexes
3352
895
  */
3353
896
  rebuild() {
3354
- logger2.info("Rebuilding search indexes", { cards: this.cards.size });
897
+ logger3.info("Rebuilding search indexes", { cards: this.cards.size });
3355
898
  const cards = Array.from(this.cards.values());
3356
899
  this.lunrIndex = lunr(function() {
3357
900
  this.ref("did");
@@ -3378,7 +921,7 @@ var SearchIndex = class {
3378
921
  includeScore: true
3379
922
  });
3380
923
  this.needsRebuild = false;
3381
- logger2.info("Search indexes rebuilt");
924
+ logger3.info("Search indexes rebuilt");
3382
925
  }
3383
926
  /**
3384
927
  * Search by text using Lunr
@@ -3436,7 +979,6 @@ var SearchIndex = class {
3436
979
  };
3437
980
 
3438
981
  // src/discovery/capability-matcher.ts
3439
- init_esm_shims();
3440
982
  var CapabilityMatcher = class {
3441
983
  /**
3442
984
  * Match a query against a capability
@@ -3590,7 +1132,7 @@ var CapabilityMatcher = class {
3590
1132
  };
3591
1133
 
3592
1134
  // src/discovery/semantic-search.ts
3593
- var logger3 = createLogger("semantic-search");
1135
+ var logger4 = createLogger("semantic-search");
3594
1136
  var SemanticSearchEngine = class {
3595
1137
  constructor(dht) {
3596
1138
  this.dht = dht;
@@ -3604,12 +1146,12 @@ var SemanticSearchEngine = class {
3604
1146
  * Local-first with network fallback
3605
1147
  */
3606
1148
  async search(query) {
3607
- logger3.info("Searching for agents", { query });
1149
+ logger4.info("Searching for agents", { query });
3608
1150
  const localResults = this.index.search(query);
3609
- logger3.debug("Local search results", { count: localResults.length });
1151
+ logger4.debug("Local search results", { count: localResults.length });
3610
1152
  const limit = query.limit || 10;
3611
1153
  if (localResults.length < limit && this.dht) {
3612
- logger3.debug("Insufficient local results, querying network");
1154
+ logger4.debug("Insufficient local results, querying network");
3613
1155
  const networkResults = await this.searchNetwork(query);
3614
1156
  return this.mergeResults(localResults, networkResults, limit);
3615
1157
  }
@@ -3655,17 +1197,17 @@ var SemanticSearchEngine = class {
3655
1197
  try {
3656
1198
  const capability = query.capability || this.extractPrimaryCapability(query.text);
3657
1199
  if (!capability) {
3658
- logger3.debug("No capability extracted from query, skipping network search");
1200
+ logger4.debug("No capability extracted from query, skipping network search");
3659
1201
  return [];
3660
1202
  }
3661
1203
  const cards = await this.dht.queryByCapability(capability);
3662
- logger3.debug("Network search results", { count: cards.length });
1204
+ logger4.debug("Network search results", { count: cards.length });
3663
1205
  return cards.map((card) => {
3664
1206
  const score = this.scoreCard(card, query);
3665
1207
  return { card, score };
3666
1208
  });
3667
1209
  } catch (error) {
3668
- logger3.error("Network search failed", { error });
1210
+ logger4.error("Network search failed", { error });
3669
1211
  return [];
3670
1212
  }
3671
1213
  }
@@ -3749,238 +1291,7 @@ function createSemanticSearch(dht) {
3749
1291
  return new SemanticSearchEngine(dht);
3750
1292
  }
3751
1293
 
3752
- // src/discovery/dht.ts
3753
- var logger4 = createLogger("dht");
3754
- var peerCache = /* @__PURE__ */ new Map();
3755
- var CACHE_TTL = 5 * 60 * 1e3;
3756
- function extractValue(event) {
3757
- if (event.name === "VALUE" && event.value) return event.value;
3758
- if (event.name === "PEER_RESPONSE" && event.value) return event.value;
3759
- return null;
3760
- }
3761
- function capKey(cap) {
3762
- return cap.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
3763
- }
3764
- async function readDIDList(dht, key) {
3765
- try {
3766
- for await (const event of dht.get(key, { signal: AbortSignal.timeout(3e4) })) {
3767
- const raw = extractValue(event);
3768
- if (raw) {
3769
- const text = toString(raw);
3770
- return text.split("\n").filter(Boolean);
3771
- }
3772
- }
3773
- } catch {
3774
- }
3775
- return [];
3776
- }
3777
- async function writeDIDList(dht, key, dids) {
3778
- const value2 = fromString([...new Set(dids)].join("\n"));
3779
- for (let attempt = 1; attempt <= 3; attempt++) {
3780
- try {
3781
- for await (const _ of dht.put(key, value2, { signal: AbortSignal.timeout(3e4) })) {
3782
- }
3783
- return;
3784
- } catch (e) {
3785
- if (e?.name === "AbortError" && attempt < 3) {
3786
- logger4.debug(`DHT put timeout, retrying (${attempt}/3)...`);
3787
- continue;
3788
- }
3789
- if (e?.name !== "AbortError") throw e;
3790
- }
3791
- }
3792
- }
3793
- function createDHTOperations(libp2p) {
3794
- const operations = {};
3795
- const searchEngine = createSemanticSearch(operations);
3796
- return Object.assign(operations, {
3797
- publishAgentCard: async (card) => {
3798
- try {
3799
- const dht = libp2p.services?.dht;
3800
- if (!dht) throw new DiscoveryError("DHT service not available");
3801
- const agentKey = fromString(`/clawiverse/agent/${card.did}`);
3802
- for (let attempt = 1; attempt <= 3; attempt++) {
3803
- try {
3804
- for await (const _ of dht.put(agentKey, encodeForDHT(card), { signal: AbortSignal.timeout(3e4) })) {
3805
- }
3806
- break;
3807
- } catch (e) {
3808
- if (e?.name === "AbortError" && attempt < 3) {
3809
- logger4.debug(`DHT put agent card timeout, retrying (${attempt}/3)...`);
3810
- continue;
3811
- }
3812
- logger4.warn("DHT put agent card failed (non-fatal)", { error: e.message });
3813
- break;
3814
- }
3815
- }
3816
- const caps = (card.capabilities ?? []).flatMap((c) => {
3817
- if (typeof c === "string") return [c];
3818
- return [c.name, c.id].filter((v) => typeof v === "string" && v.length > 0);
3819
- });
3820
- caps.push("__all__");
3821
- const importantCaps = ["__all__"];
3822
- if (caps.some((cap) => capKey(cap) === "relay")) {
3823
- importantCaps.push("relay");
3824
- }
3825
- await Promise.all(importantCaps.map(async (cap) => {
3826
- const capKeyStr = `/clawiverse/cap/${capKey(cap)}`;
3827
- const capDHTKey = fromString(capKeyStr);
3828
- try {
3829
- const existing = await readDIDList(dht, capDHTKey);
3830
- if (!existing.includes(card.did)) {
3831
- await writeDIDList(dht, capDHTKey, [...existing, card.did]);
3832
- logger4.debug("Indexed capability in DHT", { cap: capKey(cap), did: card.did });
3833
- }
3834
- } catch (e) {
3835
- logger4.warn("Failed to index capability (non-fatal)", { cap: capKey(cap), error: e.message });
3836
- }
3837
- }));
3838
- searchEngine.indexAgentCard(card);
3839
- logger4.info("Published Agent Card to DHT", { did: card.did });
3840
- } catch (error) {
3841
- logger4.warn("Failed to publish Agent Card to DHT (non-fatal)", { error: error.message });
3842
- searchEngine.indexAgentCard(card);
3843
- }
3844
- },
3845
- queryAgentCard: async (did) => {
3846
- try {
3847
- const dht = libp2p.services?.dht;
3848
- if (!dht) throw new DiscoveryError("DHT service not available");
3849
- const key = fromString(`/clawiverse/agent/${did}`);
3850
- for await (const event of dht.get(key)) {
3851
- const raw = extractValue(event);
3852
- if (raw) {
3853
- const card = decodeFromCBOR(raw);
3854
- searchEngine.indexAgentCard(card);
3855
- logger4.debug("Found Agent Card in DHT", { did });
3856
- return card;
3857
- }
3858
- }
3859
- logger4.debug("Agent Card not found in DHT", { did });
3860
- return null;
3861
- } catch (error) {
3862
- logger4.warn("Failed to query Agent Card", { did, error });
3863
- return null;
3864
- }
3865
- },
3866
- queryByCapability: async (capability) => {
3867
- try {
3868
- const dht = libp2p.services?.dht;
3869
- const local = searchEngine.getAllIndexedCards().filter(
3870
- (card) => card.capabilities.some((cap) => {
3871
- const name = typeof cap === "string" ? cap : cap.name;
3872
- return name?.toLowerCase().includes(capability.toLowerCase());
3873
- })
3874
- );
3875
- if (local.length > 0) return local;
3876
- if (!dht) return [];
3877
- const capDHTKey = fromString(`/clawiverse/cap/${capKey(capability)}`);
3878
- const dids = await readDIDList(dht, capDHTKey);
3879
- logger4.debug("DHT capability index", { capability, dids });
3880
- const cards = await Promise.all(
3881
- dids.map(async (did) => {
3882
- const key = fromString(`/clawiverse/agent/${did}`);
3883
- try {
3884
- for await (const event of dht.get(key)) {
3885
- const raw = extractValue(event);
3886
- if (raw) {
3887
- const card = decodeFromCBOR(raw);
3888
- searchEngine.indexAgentCard(card);
3889
- return card;
3890
- }
3891
- }
3892
- } catch {
3893
- }
3894
- return null;
3895
- })
3896
- );
3897
- return cards.filter((c) => c !== null);
3898
- } catch (error) {
3899
- throw new DiscoveryError("Failed to query by capability", error);
3900
- }
3901
- },
3902
- searchSemantic: async (query) => {
3903
- try {
3904
- const dht = libp2p.services?.dht;
3905
- if (dht) {
3906
- const allKey = fromString("/clawiverse/cap/__all__");
3907
- const dids = await readDIDList(dht, allKey);
3908
- logger4.debug("DHT __all__ index", { count: dids.length });
3909
- await Promise.all(
3910
- dids.map(async (did) => {
3911
- const key = fromString(`/clawiverse/agent/${did}`);
3912
- try {
3913
- for await (const event of dht.get(key)) {
3914
- const raw = extractValue(event);
3915
- if (raw) {
3916
- searchEngine.indexAgentCard(decodeFromCBOR(raw));
3917
- break;
3918
- }
3919
- }
3920
- } catch {
3921
- }
3922
- })
3923
- );
3924
- }
3925
- return searchEngine.search(query);
3926
- } catch (error) {
3927
- throw new DiscoveryError("Failed to perform semantic search", error);
3928
- }
3929
- },
3930
- queryRelayPeers: async () => {
3931
- const dht = libp2p.services?.dht;
3932
- if (!dht) return [];
3933
- const capDHTKey = fromString("/clawiverse/cap/relay");
3934
- const dids = await readDIDList(dht, capDHTKey);
3935
- const addrs = [];
3936
- await Promise.all(dids.map(async (did) => {
3937
- const card = await operations.queryAgentCard(did);
3938
- if (card?.endpoints) {
3939
- addrs.push(...card.endpoints.filter((e) => !e.includes("/p2p-circuit/")));
3940
- }
3941
- }));
3942
- return addrs;
3943
- },
3944
- resolveDID: async (did) => {
3945
- try {
3946
- const cached = peerCache.get(did);
3947
- if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
3948
- logger4.debug("Using cached peer info", { did });
3949
- return { peerId: cached.peerId, multiaddrs: cached.multiaddrs };
3950
- }
3951
- const dht = libp2p.services?.dht;
3952
- if (!dht) throw new DiscoveryError("DHT service not available");
3953
- const key = fromString(`/clawiverse/agent/${did}`);
3954
- for await (const event of dht.get(key)) {
3955
- const raw = extractValue(event);
3956
- if (raw) {
3957
- const card = decodeFromCBOR(raw);
3958
- if (card.peerId) {
3959
- logger4.debug("Resolved DID to peer", { did, peerId: card.peerId });
3960
- const result = { peerId: card.peerId, multiaddrs: card.endpoints || [] };
3961
- peerCache.set(did, {
3962
- peerId: result.peerId,
3963
- multiaddrs: result.multiaddrs,
3964
- timestamp: Date.now()
3965
- });
3966
- return result;
3967
- }
3968
- logger4.warn("Agent Card found but has no peerId", { did });
3969
- return null;
3970
- }
3971
- }
3972
- logger4.debug("DID not found in DHT", { did });
3973
- return null;
3974
- } catch (error) {
3975
- logger4.warn("Failed to resolve DID", { did, error });
3976
- return null;
3977
- }
3978
- }
3979
- });
3980
- }
3981
-
3982
1294
  // src/messaging/envelope.ts
3983
- init_esm_shims();
3984
1295
  function createEnvelope(from, to, type, protocol, payload, replyTo) {
3985
1296
  return {
3986
1297
  id: generateMessageId(),
@@ -4027,9 +1338,6 @@ function validateEnvelope(msg) {
4027
1338
  function generateMessageId() {
4028
1339
  return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
4029
1340
  }
4030
-
4031
- // src/messaging/codec.ts
4032
- init_esm_shims();
4033
1341
  function encodeMessage(envelope) {
4034
1342
  try {
4035
1343
  return encode(envelope);
@@ -4060,24 +1368,11 @@ function decodeMessageJSON(json) {
4060
1368
  }
4061
1369
 
4062
1370
  // src/messaging/router.ts
4063
- init_esm_shims();
4064
1371
  var logger5 = createLogger("router");
4065
- function concatUint8Arrays(arrays) {
4066
- if (arrays.length === 0) return new Uint8Array(0);
4067
- if (arrays.length === 1) return arrays[0];
4068
- const totalLength = arrays.reduce((acc, arr) => acc + arr.length, 0);
4069
- const result = new Uint8Array(totalLength);
4070
- let offset = 0;
4071
- for (const arr of arrays) {
4072
- result.set(arr, offset);
4073
- offset += arr.length;
4074
- }
4075
- return result;
4076
- }
4077
- function createMessageRouter(libp2p, verifyFn, dht, relayPeers) {
1372
+ function createMessageRouter(relayClient, verifyFn) {
4078
1373
  const handlers = /* @__PURE__ */ new Map();
4079
1374
  let catchAllHandler;
4080
- const PROTOCOL_PREFIX = "/clawiverse/msg/1.0.0";
1375
+ const pendingRequests = /* @__PURE__ */ new Map();
4081
1376
  return {
4082
1377
  registerHandler: (protocol, handler) => {
4083
1378
  handlers.set(protocol, handler);
@@ -4091,134 +1386,14 @@ function createMessageRouter(libp2p, verifyFn, dht, relayPeers) {
4091
1386
  catchAllHandler = handler;
4092
1387
  logger5.info("Registered catch-all message handler");
4093
1388
  },
4094
- sendMessage: async (envelope, peerHint) => {
1389
+ sendMessage: async (envelope) => {
4095
1390
  try {
4096
1391
  if (!validateEnvelope(envelope)) {
4097
1392
  throw new MessagingError("Invalid message envelope");
4098
1393
  }
4099
- let targetPeerIdStr;
4100
- let targetMultiaddrs = [];
4101
- if (peerHint) {
4102
- targetPeerIdStr = peerHint.peerId;
4103
- targetMultiaddrs = peerHint.multiaddrs;
4104
- logger5.info("Using peer hint for direct addressing", { peerId: targetPeerIdStr });
4105
- } else if (dht) {
4106
- const resolved = await dht.resolveDID(envelope.to);
4107
- if (resolved) {
4108
- targetPeerIdStr = resolved.peerId;
4109
- targetMultiaddrs = resolved.multiaddrs;
4110
- }
4111
- }
4112
- if (!targetPeerIdStr) {
4113
- throw new MessagingError(
4114
- `Cannot resolve recipient: ${envelope.to} \u2014 provide peerHint or ensure agent is in DHT`
4115
- );
4116
- }
4117
- const targetPeerId = peerIdFromString(targetPeerIdStr);
4118
- if (targetMultiaddrs.length > 0) {
4119
- const mas = targetMultiaddrs.map((a) => multiaddr(a));
4120
- await libp2p.peerStore.merge(targetPeerId, { multiaddrs: mas });
4121
- }
4122
- logger5.info("Dialing peer for message delivery", {
4123
- peerId: targetPeerIdStr,
4124
- multiaddrs: targetMultiaddrs
4125
- });
4126
- let stream;
4127
- const DIAL_TIMEOUT = 3e3;
4128
- const relayMultiaddrs = targetMultiaddrs.filter((a) => a.includes("/p2p-circuit/"));
4129
- const directMultiaddrs = targetMultiaddrs.filter((a) => !a.includes("/p2p-circuit/"));
4130
- if (directMultiaddrs.length > 0) {
4131
- const directDialPromises = directMultiaddrs.map(async (addr) => {
4132
- try {
4133
- const conn = await libp2p.dial(multiaddr(addr), {
4134
- signal: AbortSignal.timeout(DIAL_TIMEOUT)
4135
- });
4136
- const s = await conn.newStream(PROTOCOL_PREFIX, { runOnLimitedConnection: true });
4137
- logger5.info("Direct dial succeeded", { addr });
4138
- return { conn, stream: s };
4139
- } catch {
4140
- return null;
4141
- }
4142
- });
4143
- const winner = await Promise.race(
4144
- directDialPromises.map((p) => p.then((r) => r || Promise.reject()))
4145
- ).catch(() => void 0);
4146
- if (winner) {
4147
- stream = winner.stream;
4148
- Promise.allSettled(directDialPromises).then((results) => {
4149
- for (const result of results) {
4150
- if (result.status === "fulfilled" && result.value && result.value.stream !== stream) {
4151
- result.value.conn.close().catch(() => {
4152
- });
4153
- }
4154
- }
4155
- });
4156
- }
4157
- }
4158
- let lastError;
4159
- if (!stream) {
4160
- const allRelayAddrs = [
4161
- ...relayMultiaddrs,
4162
- ...(relayPeers ?? []).map((r) => buildCircuitRelayAddr(r, targetPeerIdStr))
4163
- ];
4164
- const uniqueRelayAddrs = [...new Set(allRelayAddrs)];
4165
- if (uniqueRelayAddrs.length > 0) {
4166
- const relayDialPromises = uniqueRelayAddrs.map(async (addr) => {
4167
- try {
4168
- const conn = await libp2p.dial(multiaddr(addr), {
4169
- signal: AbortSignal.timeout(DIAL_TIMEOUT)
4170
- });
4171
- logger5.info("Relay connection established", { addr });
4172
- const s = await conn.newStream(PROTOCOL_PREFIX, { runOnLimitedConnection: true });
4173
- logger5.info("Relay stream opened", { addr });
4174
- return { conn, stream: s };
4175
- } catch (relayErr) {
4176
- logger5.warn("Relay dial failed", { addr, error: relayErr.message });
4177
- lastError = relayErr;
4178
- return null;
4179
- }
4180
- });
4181
- const winner = await Promise.race(
4182
- relayDialPromises.map((p) => p.then((r) => r || Promise.reject()))
4183
- ).catch(() => void 0);
4184
- if (winner) {
4185
- stream = winner.stream;
4186
- Promise.allSettled(relayDialPromises).then((results) => {
4187
- for (const result of results) {
4188
- if (result.status === "fulfilled" && result.value && result.value.stream !== stream) {
4189
- result.value.conn.close().catch(() => {
4190
- });
4191
- }
4192
- }
4193
- });
4194
- }
4195
- }
4196
- }
4197
- if (!stream && dht && "queryRelayPeers" in dht) {
4198
- const discoveredRelays = await dht.queryRelayPeers();
4199
- for (const relayAddr of discoveredRelays) {
4200
- const circuitAddr = buildCircuitRelayAddr(relayAddr, targetPeerIdStr);
4201
- try {
4202
- const conn = await libp2p.dial(multiaddr(circuitAddr));
4203
- stream = await conn.newStream(PROTOCOL_PREFIX, { runOnLimitedConnection: true });
4204
- logger5.info("DHT-discovered relay succeeded", { relayAddr });
4205
- break;
4206
- } catch (e) {
4207
- logger5.warn("DHT relay failed", { relayAddr, error: e.message });
4208
- lastError = e;
4209
- }
4210
- }
4211
- }
4212
- if (!stream) {
4213
- throw lastError ?? new MessagingError("All dial attempts failed (including DHT-discovered relays)");
4214
- }
4215
1394
  const encoded = encodeMessage(envelope);
4216
- await stream.sink(
4217
- (async function* () {
4218
- yield encoded;
4219
- })()
4220
- );
4221
- logger5.info("Message sent over libp2p stream", {
1395
+ await relayClient.sendEnvelope(envelope.to, encoded);
1396
+ logger5.info("Message sent via relay", {
4222
1397
  id: envelope.id,
4223
1398
  from: envelope.from,
4224
1399
  to: envelope.to,
@@ -4226,38 +1401,15 @@ function createMessageRouter(libp2p, verifyFn, dht, relayPeers) {
4226
1401
  });
4227
1402
  if (envelope.type === "request") {
4228
1403
  logger5.debug("Waiting for response to request", { id: envelope.id });
4229
- try {
4230
- const RESPONSE_TIMEOUT = 3e4;
4231
- const responsePromise = (async () => {
4232
- const responseChunks = [];
4233
- for await (const chunk of stream.source) {
4234
- responseChunks.push(chunk.subarray());
4235
- }
4236
- if (responseChunks.length > 0) {
4237
- const responseData = concatUint8Arrays(responseChunks);
4238
- const responseEnvelope = decodeMessage(responseData);
4239
- logger5.info("Received response", {
4240
- id: responseEnvelope.id,
4241
- replyTo: responseEnvelope.replyTo
4242
- });
4243
- return responseEnvelope;
4244
- } else {
4245
- logger5.warn("No response received for request", { id: envelope.id });
4246
- return void 0;
4247
- }
4248
- })();
4249
- const timeoutPromise = new Promise((resolve) => {
4250
- setTimeout(() => {
4251
- logger5.warn("Response timeout", { id: envelope.id, timeout: RESPONSE_TIMEOUT });
4252
- resolve(void 0);
4253
- }, RESPONSE_TIMEOUT);
4254
- });
4255
- const response = await Promise.race([responsePromise, timeoutPromise]);
4256
- return response;
4257
- } catch (error) {
4258
- logger5.warn("Error reading response", { error });
4259
- return void 0;
4260
- }
1404
+ const RESPONSE_TIMEOUT = 3e4;
1405
+ return new Promise((resolve) => {
1406
+ const timeout = setTimeout(() => {
1407
+ pendingRequests.delete(envelope.id);
1408
+ logger5.warn("Response timeout", { id: envelope.id, timeout: RESPONSE_TIMEOUT });
1409
+ resolve(void 0);
1410
+ }, RESPONSE_TIMEOUT);
1411
+ pendingRequests.set(envelope.id, { resolve, timeout });
1412
+ });
4261
1413
  }
4262
1414
  return void 0;
4263
1415
  } catch (error) {
@@ -4266,113 +1418,100 @@ function createMessageRouter(libp2p, verifyFn, dht, relayPeers) {
4266
1418
  }
4267
1419
  },
4268
1420
  start: async () => {
4269
- await libp2p.handle(PROTOCOL_PREFIX, async ({ stream }) => {
1421
+ relayClient.onDeliver(async (deliverMsg) => {
4270
1422
  try {
4271
- await handleIncomingStream(stream, handlers, catchAllHandler, verifyFn);
1423
+ const envelope = decodeMessage(deliverMsg.envelope);
1424
+ if (!validateEnvelope(envelope)) {
1425
+ logger5.warn("Received invalid message envelope");
1426
+ return;
1427
+ }
1428
+ const isValidSignature = await verifyEnvelope(envelope, async (signature, data) => {
1429
+ const senderPublicKey = extractPublicKey(envelope.from);
1430
+ return verify(signature, data, senderPublicKey);
1431
+ });
1432
+ if (!isValidSignature) {
1433
+ logger5.warn("Received message with invalid signature", {
1434
+ id: envelope.id,
1435
+ from: envelope.from
1436
+ });
1437
+ return;
1438
+ }
1439
+ try {
1440
+ const { signature, ...envelopeWithoutSig } = envelope;
1441
+ const dataBytes = new TextEncoder().encode(JSON.stringify(envelopeWithoutSig));
1442
+ const signatureBytes = Buffer.from(signature, "hex");
1443
+ const hookValid = await verifyFn(signatureBytes, dataBytes);
1444
+ if (!hookValid) {
1445
+ logger5.warn("Message rejected by custom verifier", {
1446
+ id: envelope.id,
1447
+ from: envelope.from
1448
+ });
1449
+ return;
1450
+ }
1451
+ } catch (error) {
1452
+ logger5.warn("Custom verification hook failed", {
1453
+ id: envelope.id,
1454
+ from: envelope.from,
1455
+ error: error.message
1456
+ });
1457
+ return;
1458
+ }
1459
+ logger5.info("Received message", {
1460
+ id: envelope.id,
1461
+ from: envelope.from,
1462
+ to: envelope.to,
1463
+ protocol: envelope.protocol,
1464
+ type: envelope.type
1465
+ });
1466
+ if (envelope.type === "response" && envelope.replyTo) {
1467
+ const pending = pendingRequests.get(envelope.replyTo);
1468
+ if (pending) {
1469
+ clearTimeout(pending.timeout);
1470
+ pendingRequests.delete(envelope.replyTo);
1471
+ pending.resolve(envelope);
1472
+ logger5.info("Matched response to pending request", {
1473
+ requestId: envelope.replyTo,
1474
+ responseId: envelope.id
1475
+ });
1476
+ return;
1477
+ }
1478
+ }
1479
+ const handler = handlers.get(envelope.protocol);
1480
+ let response = void 0;
1481
+ if (handler) {
1482
+ response = await handler(envelope);
1483
+ } else if (catchAllHandler) {
1484
+ logger5.debug("Using catch-all handler for protocol", { protocol: envelope.protocol });
1485
+ response = await catchAllHandler(envelope);
1486
+ } else {
1487
+ logger5.warn("No handler for protocol", { protocol: envelope.protocol });
1488
+ }
1489
+ if (response) {
1490
+ const encoded = encodeMessage(response);
1491
+ await relayClient.sendEnvelope(response.to, encoded);
1492
+ logger5.info("Sent response back to sender", {
1493
+ responseId: response.id,
1494
+ replyTo: response.replyTo
1495
+ });
1496
+ }
4272
1497
  } catch (error) {
4273
- logger5.error("Error handling incoming stream", error);
1498
+ logger5.error("Error handling incoming message", error);
4274
1499
  }
4275
- }, { runOnLimitedConnection: true });
1500
+ });
4276
1501
  logger5.info("Message router started");
4277
1502
  },
4278
1503
  stop: async () => {
4279
- await libp2p.unhandle(PROTOCOL_PREFIX);
1504
+ for (const [, pending] of pendingRequests.entries()) {
1505
+ clearTimeout(pending.timeout);
1506
+ pending.resolve(void 0);
1507
+ }
1508
+ pendingRequests.clear();
4280
1509
  handlers.clear();
4281
1510
  catchAllHandler = void 0;
4282
1511
  logger5.info("Message router stopped");
4283
1512
  }
4284
1513
  };
4285
1514
  }
4286
- function buildCircuitRelayAddr(relayAddr, targetPeerId) {
4287
- return `${relayAddr}/p2p-circuit/p2p/${targetPeerId}`;
4288
- }
4289
- async function handleIncomingStream(stream, handlers, catchAllHandler, verifyFn) {
4290
- try {
4291
- const chunks = [];
4292
- for await (const chunk of stream.source) {
4293
- chunks.push(chunk.subarray());
4294
- }
4295
- const data = concatUint8Arrays(chunks);
4296
- if (data.length === 0) {
4297
- logger5.debug("Received empty stream, ignoring");
4298
- return;
4299
- }
4300
- const envelope = decodeMessage(data);
4301
- if (!validateEnvelope(envelope)) {
4302
- logger5.warn("Received invalid message envelope");
4303
- return;
4304
- }
4305
- const isValidSignature = await verifyEnvelope(envelope, async (signature, data2) => {
4306
- const senderPublicKey = extractPublicKey(envelope.from);
4307
- return verify(signature, data2, senderPublicKey);
4308
- });
4309
- if (!isValidSignature) {
4310
- logger5.warn("Received message with invalid signature", {
4311
- id: envelope.id,
4312
- from: envelope.from
4313
- });
4314
- return;
4315
- }
4316
- try {
4317
- const { signature, ...envelopeWithoutSig } = envelope;
4318
- const dataBytes = new TextEncoder().encode(JSON.stringify(envelopeWithoutSig));
4319
- const signatureBytes = Buffer.from(signature, "hex");
4320
- const hookValid = await verifyFn(signatureBytes, dataBytes);
4321
- if (!hookValid) {
4322
- logger5.warn("Message rejected by custom verifier", {
4323
- id: envelope.id,
4324
- from: envelope.from
4325
- });
4326
- return;
4327
- }
4328
- } catch (error) {
4329
- logger5.warn("Custom verification hook failed", {
4330
- id: envelope.id,
4331
- from: envelope.from,
4332
- error: error.message
4333
- });
4334
- return;
4335
- }
4336
- logger5.info("Received message", {
4337
- id: envelope.id,
4338
- from: envelope.from,
4339
- to: envelope.to,
4340
- protocol: envelope.protocol,
4341
- payload: envelope.payload
4342
- });
4343
- const handler = handlers.get(envelope.protocol);
4344
- let response = void 0;
4345
- if (handler) {
4346
- response = await handler(envelope);
4347
- } else if (catchAllHandler) {
4348
- logger5.debug("Using catch-all handler for protocol", { protocol: envelope.protocol });
4349
- response = await catchAllHandler(envelope);
4350
- } else {
4351
- logger5.warn("No handler for protocol", { protocol: envelope.protocol });
4352
- }
4353
- if (response) {
4354
- const encoded = encodeMessage(response);
4355
- logger5.info("Sending response back to sender", {
4356
- responseId: response.id,
4357
- replyTo: response.replyTo,
4358
- size: encoded.length
4359
- });
4360
- await stream.sink(
4361
- (async function* () {
4362
- yield encoded;
4363
- })()
4364
- );
4365
- }
4366
- } catch (error) {
4367
- logger5.error("Error handling incoming message", error);
4368
- }
4369
- }
4370
-
4371
- // src/messaging/types.ts
4372
- init_esm_shims();
4373
-
4374
- // src/messaging/storage.ts
4375
- init_esm_shims();
4376
1515
  var logger6 = createLogger("message-storage");
4377
1516
  var MessageStorage = class {
4378
1517
  db;
@@ -4403,12 +1542,12 @@ var MessageStorage = class {
4403
1542
  async getMessage(id) {
4404
1543
  for (const direction of ["inbound", "outbound"]) {
4405
1544
  const prefix = `msg:${direction}:`;
4406
- for await (const [, value2] of this.db.iterator({
1545
+ for await (const [, value] of this.db.iterator({
4407
1546
  gte: prefix,
4408
1547
  lte: prefix + "\xFF",
4409
1548
  valueEncoding: "json"
4410
1549
  })) {
4411
- if (value2.envelope.id === id) return value2;
1550
+ if (value.envelope.id === id) return value;
4412
1551
  }
4413
1552
  }
4414
1553
  return null;
@@ -4437,20 +1576,20 @@ var MessageStorage = class {
4437
1576
  const results = [];
4438
1577
  let total = 0;
4439
1578
  let skipped = 0;
4440
- for await (const [, value2] of this.db.iterator({
1579
+ for await (const [, value] of this.db.iterator({
4441
1580
  gte: prefix,
4442
1581
  lte: prefix + "\xFF",
4443
1582
  reverse: true,
4444
1583
  // newest first
4445
1584
  valueEncoding: "json"
4446
1585
  })) {
4447
- if (!this.matchesFilter(value2, filter)) continue;
1586
+ if (!this.matchesFilter(value, filter)) continue;
4448
1587
  total++;
4449
1588
  if (skipped < offset) {
4450
1589
  skipped++;
4451
1590
  continue;
4452
1591
  }
4453
- if (results.length < limit) results.push(value2);
1592
+ if (results.length < limit) results.push(value);
4454
1593
  }
4455
1594
  return {
4456
1595
  messages: results,
@@ -4487,12 +1626,12 @@ var MessageStorage = class {
4487
1626
  async countMessages(direction, filter = {}) {
4488
1627
  const prefix = `msg:${direction}:`;
4489
1628
  let count = 0;
4490
- for await (const [, value2] of this.db.iterator({
1629
+ for await (const [, value] of this.db.iterator({
4491
1630
  gte: prefix,
4492
1631
  lte: prefix + "\xFF",
4493
1632
  valueEncoding: "json"
4494
1633
  })) {
4495
- if (this.matchesFilter(value2, filter)) count++;
1634
+ if (this.matchesFilter(value, filter)) count++;
4496
1635
  }
4497
1636
  return count;
4498
1637
  }
@@ -4515,12 +1654,12 @@ var MessageStorage = class {
4515
1654
  }
4516
1655
  async listBlocked() {
4517
1656
  const results = [];
4518
- for await (const [, value2] of this.db.iterator({
1657
+ for await (const [, value] of this.db.iterator({
4519
1658
  gte: "block:",
4520
1659
  lte: "block:\xFF",
4521
1660
  valueEncoding: "json"
4522
1661
  })) {
4523
- results.push(value2);
1662
+ results.push(value);
4524
1663
  }
4525
1664
  return results;
4526
1665
  }
@@ -4543,12 +1682,12 @@ var MessageStorage = class {
4543
1682
  }
4544
1683
  async listAllowed() {
4545
1684
  const results = [];
4546
- for await (const [, value2] of this.db.iterator({
1685
+ for await (const [, value] of this.db.iterator({
4547
1686
  gte: "allow:",
4548
1687
  lte: "allow:\xFF",
4549
1688
  valueEncoding: "json"
4550
1689
  })) {
4551
- results.push(value2);
1690
+ results.push(value);
4552
1691
  }
4553
1692
  return results;
4554
1693
  }
@@ -4566,12 +1705,12 @@ var MessageStorage = class {
4566
1705
  async cleanupSeen(maxAgeMs) {
4567
1706
  const cutoff = Date.now() - maxAgeMs;
4568
1707
  const toDelete = [];
4569
- for await (const [key, value2] of this.db.iterator({
1708
+ for await (const [key, value] of this.db.iterator({
4570
1709
  gte: "seen:",
4571
1710
  lte: "seen:\xFF",
4572
1711
  valueEncoding: "json"
4573
1712
  })) {
4574
- if (value2.seenAt < cutoff) toDelete.push(key);
1713
+ if (value.seenAt < cutoff) toDelete.push(key);
4575
1714
  }
4576
1715
  await this.db.batch(toDelete.map((key) => ({ type: "del", key })));
4577
1716
  }
@@ -4589,19 +1728,18 @@ var MessageStorage = class {
4589
1728
  async cleanupRateLimits(maxAgeMs) {
4590
1729
  const cutoff = Date.now() - maxAgeMs;
4591
1730
  const toDelete = [];
4592
- for await (const [key, value2] of this.db.iterator({
1731
+ for await (const [key, value] of this.db.iterator({
4593
1732
  gte: "rate:",
4594
1733
  lte: "rate:\xFF",
4595
1734
  valueEncoding: "json"
4596
1735
  })) {
4597
- if (value2.lastRefill < cutoff) toDelete.push(key);
1736
+ if (value.lastRefill < cutoff) toDelete.push(key);
4598
1737
  }
4599
1738
  await this.db.batch(toDelete.map((key) => ({ type: "del", key })));
4600
1739
  }
4601
1740
  };
4602
1741
 
4603
1742
  // src/messaging/queue.ts
4604
- init_esm_shims();
4605
1743
  var logger7 = createLogger("message-queue");
4606
1744
  var MessageQueue = class {
4607
1745
  storage;
@@ -4727,11 +1865,7 @@ var MessageQueue = class {
4727
1865
  }
4728
1866
  };
4729
1867
 
4730
- // src/messaging/defense.ts
4731
- init_esm_shims();
4732
-
4733
1868
  // src/messaging/rate-limiter.ts
4734
- init_esm_shims();
4735
1869
  var TokenBucket = class {
4736
1870
  tokens;
4737
1871
  lastRefill;
@@ -4950,11 +2084,7 @@ var DefenseMiddleware = class {
4950
2084
  }
4951
2085
  };
4952
2086
 
4953
- // src/trust/index.ts
4954
- init_esm_shims();
4955
-
4956
2087
  // src/trust/trust-score.ts
4957
- init_esm_shims();
4958
2088
  var TrustMetrics = class {
4959
2089
  /**
4960
2090
  * Calculate trust score from interaction history
@@ -5022,9 +2152,6 @@ function createDefaultTrustScore() {
5022
2152
  lastUpdated: Date.now()
5023
2153
  };
5024
2154
  }
5025
-
5026
- // src/trust/interaction-history.ts
5027
- init_esm_shims();
5028
2155
  var logger9 = createLogger("interaction-history");
5029
2156
  var InteractionHistory = class {
5030
2157
  db;
@@ -5060,14 +2187,14 @@ var InteractionHistory = class {
5060
2187
  const interactions = [];
5061
2188
  const prefix = `interaction:${agentDid}:`;
5062
2189
  try {
5063
- for await (const [_, value2] of this.db.iterator({
2190
+ for await (const [_, value] of this.db.iterator({
5064
2191
  gte: prefix,
5065
2192
  lte: prefix + "\xFF",
5066
2193
  limit,
5067
2194
  reverse: true
5068
2195
  // Most recent first
5069
2196
  })) {
5070
- interactions.push(value2);
2197
+ interactions.push(value);
5071
2198
  }
5072
2199
  } catch (error) {
5073
2200
  logger9.error("Failed to get interaction history", { agentDid, error });
@@ -5134,8 +2261,8 @@ var InteractionHistory = class {
5134
2261
  async cleanup(maxAge = 90 * 24 * 60 * 60 * 1e3) {
5135
2262
  const cutoff = Date.now() - maxAge;
5136
2263
  const keysToDelete = [];
5137
- for await (const [key, value2] of this.db.iterator()) {
5138
- if (value2.timestamp < cutoff) {
2264
+ for await (const [key, value] of this.db.iterator()) {
2265
+ if (value.timestamp < cutoff) {
5139
2266
  keysToDelete.push(key);
5140
2267
  }
5141
2268
  }
@@ -5148,7 +2275,6 @@ var InteractionHistory = class {
5148
2275
  };
5149
2276
 
5150
2277
  // src/trust/endorsement.ts
5151
- init_esm_shims();
5152
2278
  var logger10 = createLogger("endorsement");
5153
2279
  var EndorsementManager = class {
5154
2280
  constructor(db, getPublicKey) {
@@ -5209,11 +2335,11 @@ var EndorsementManager = class {
5209
2335
  const endorsements = [];
5210
2336
  const prefix = `endorsement:${agentDid}:`;
5211
2337
  try {
5212
- for await (const [_, value2] of this.db.iterator({
2338
+ for await (const [_, value] of this.db.iterator({
5213
2339
  gte: prefix,
5214
2340
  lte: prefix + "\xFF"
5215
2341
  })) {
5216
- endorsements.push(value2);
2342
+ endorsements.push(value);
5217
2343
  }
5218
2344
  } catch (error) {
5219
2345
  logger10.error("Failed to get endorsements", { agentDid, error });
@@ -5226,9 +2352,9 @@ var EndorsementManager = class {
5226
2352
  async getEndorsementsBy(fromDid) {
5227
2353
  const endorsements = [];
5228
2354
  try {
5229
- for await (const [_, value2] of this.db.iterator()) {
5230
- if (value2.from === fromDid) {
5231
- endorsements.push(value2);
2355
+ for await (const [_, value] of this.db.iterator()) {
2356
+ if (value.from === fromDid) {
2357
+ endorsements.push(value);
5232
2358
  }
5233
2359
  }
5234
2360
  } catch (error) {
@@ -5256,9 +2382,6 @@ var EndorsementManager = class {
5256
2382
  logger10.info("Deleted endorsement", { from: fromDid, to: toDid });
5257
2383
  }
5258
2384
  };
5259
-
5260
- // src/trust/sybil-defense.ts
5261
- init_esm_shims();
5262
2385
  var logger11 = createLogger("sybil-defense");
5263
2386
  var SybilDefense = class {
5264
2387
  rateLimits = /* @__PURE__ */ new Map();
@@ -5537,6 +2660,6 @@ function createTrustSystem(config) {
5537
2660
  return new TrustSystem(config);
5538
2661
  }
5539
2662
 
5540
- export { CLAWIVERSE_CONTEXT, CapabilityMatcher, CapabilityTypes, ClawiverseError, DEFAULT_RATE_LIMIT_TIERS, DefenseMiddleware, DiscoveryError, EndorsementManager, IdentityError, InteractionHistory, LogLevel, Logger, MessageQueue, MessageStorage, MessagingError, ParameterTypes, SCHEMA_ORG_CONTEXT, SearchIndex, SemanticSearchEngine, SybilDefense, TokenBucket, TransportError, TrustMetrics, TrustSystem, clawiverseContext, createAgentCard, createDHTOperations, createDefaultTrustScore, createEnvelope, createLegacyAgentCard, createLogger, createMessageRouter, createNode, createSemanticSearch, createTrustSystem, decodeAgentCard, decodeFromCBOR, decodeFromJSON, decodeMessage, decodeMessageJSON, deriveDID, downgradeToLegacyCard, encodeForDHT, encodeForWeb, encodeMessage, encodeMessageJSON, exportKeyPair, extractPublicKey, generateKeyPair, getAgentCardContext, getEncodedSize, getTierConfig, importKeyPair, isLegacyCard, isValidContext, matchesCapability, sign, signAgentCard, signEnvelope, signMessage, upgradeLegacyCard, validateAgentCard, validateDID, validateEnvelope, verify, verifyAgentCard, verifyEnvelope, verifyMessage };
2663
+ export { CLAWIVERSE_CONTEXT, CapabilityMatcher, CapabilityTypes, ClawiverseError, DEFAULT_RATE_LIMIT_TIERS, DefenseMiddleware, DiscoveryError, EndorsementManager, IdentityError, InteractionHistory, LogLevel, Logger, MessageQueue, MessageStorage, MessagingError, ParameterTypes, RELAY_PROTOCOL_VERSION, SCHEMA_ORG_CONTEXT, SearchIndex, SemanticSearchEngine, SybilDefense, TokenBucket, TransportError, TrustMetrics, TrustSystem, clawiverseContext, createAgentCard, createDefaultTrustScore, createEnvelope, createLegacyAgentCard, createLogger, createMessageRouter, createRelayClient, createRelayIndexOperations, createSemanticSearch, createTrustSystem, decodeAgentCard, decodeFromCBOR, decodeFromJSON, decodeMessage, decodeMessageJSON, deriveDID, downgradeToLegacyCard, encodeForDHT, encodeForWeb, encodeMessage, encodeMessageJSON, exportKeyPair, extractPublicKey, generateKeyPair, getAgentCardContext, getEncodedSize, getTierConfig, importKeyPair, isLegacyCard, isValidContext, matchesCapability, sign, signAgentCard, signEnvelope, signMessage, upgradeLegacyCard, validateAgentCard, validateDID, validateEnvelope, verify, verifyAgentCard, verifyEnvelope, verifyMessage };
5541
2664
  //# sourceMappingURL=index.js.map
5542
2665
  //# sourceMappingURL=index.js.map