@waku/core 0.0.21 → 0.0.23

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.
Files changed (62) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/bundle/base_protocol-84d9b670.js +1198 -0
  3. package/bundle/index.js +1163 -1281
  4. package/bundle/lib/base_protocol.js +2 -116
  5. package/bundle/lib/message/version_0.js +1 -1
  6. package/bundle/lib/predefined_bootstrap_nodes.js +6 -6
  7. package/bundle/{version_0-86411fdf.js → version_0-74b4b9db.js} +875 -794
  8. package/dist/.tsbuildinfo +1 -0
  9. package/dist/index.d.ts +6 -5
  10. package/dist/index.js +5 -4
  11. package/dist/index.js.map +1 -1
  12. package/dist/lib/base_protocol.d.ts +18 -5
  13. package/dist/lib/base_protocol.js +25 -8
  14. package/dist/lib/base_protocol.js.map +1 -1
  15. package/dist/lib/connection_manager.d.ts +3 -5
  16. package/dist/lib/connection_manager.js +53 -45
  17. package/dist/lib/connection_manager.js.map +1 -1
  18. package/dist/lib/filter/filter_rpc.js +4 -4
  19. package/dist/lib/filter/index.d.ts +4 -0
  20. package/dist/lib/filter/index.js +24 -27
  21. package/dist/lib/filter/index.js.map +1 -1
  22. package/dist/lib/filterPeers.d.ts +10 -0
  23. package/dist/lib/filterPeers.js +31 -0
  24. package/dist/lib/filterPeers.js.map +1 -0
  25. package/dist/lib/keep_alive_manager.d.ts +4 -6
  26. package/dist/lib/keep_alive_manager.js +27 -8
  27. package/dist/lib/keep_alive_manager.js.map +1 -1
  28. package/dist/lib/light_push/index.js +62 -33
  29. package/dist/lib/light_push/index.js.map +1 -1
  30. package/dist/lib/light_push/push_rpc.js +2 -2
  31. package/dist/lib/message/version_0.d.ts +1 -1
  32. package/dist/lib/message/version_0.js +3 -3
  33. package/dist/lib/message/version_0.js.map +1 -1
  34. package/dist/lib/predefined_bootstrap_nodes.js +6 -6
  35. package/dist/lib/store/history_rpc.js +3 -3
  36. package/dist/lib/store/index.d.ts +0 -5
  37. package/dist/lib/store/index.js +54 -37
  38. package/dist/lib/store/index.js.map +1 -1
  39. package/dist/lib/stream_manager.d.ts +15 -0
  40. package/dist/lib/stream_manager.js +53 -0
  41. package/dist/lib/stream_manager.js.map +1 -0
  42. package/dist/lib/to_proto_message.js +1 -1
  43. package/dist/lib/waku.d.ts +2 -2
  44. package/dist/lib/waku.js +1 -1
  45. package/package.json +16 -22
  46. package/src/index.ts +7 -13
  47. package/src/lib/base_protocol.ts +49 -18
  48. package/src/lib/connection_manager.ts +82 -66
  49. package/src/lib/filter/filter_rpc.ts +4 -4
  50. package/src/lib/filter/index.ts +32 -39
  51. package/src/lib/filterPeers.ts +43 -0
  52. package/src/lib/keep_alive_manager.ts +34 -14
  53. package/src/lib/light_push/index.ts +103 -47
  54. package/src/lib/light_push/push_rpc.ts +2 -2
  55. package/src/lib/message/version_0.ts +8 -5
  56. package/src/lib/predefined_bootstrap_nodes.ts +7 -7
  57. package/src/lib/store/history_rpc.ts +4 -4
  58. package/src/lib/store/index.ts +70 -51
  59. package/src/lib/stream_manager.ts +69 -0
  60. package/src/lib/to_proto_message.ts +1 -1
  61. package/src/lib/wait_for_remote_peer.ts +1 -1
  62. package/src/lib/waku.ts +3 -3
@@ -0,0 +1,1198 @@
1
+ import { d as debug } from './browser-bde977a3.js';
2
+
3
+ // base-x encoding / decoding
4
+ // Copyright (c) 2018 base-x contributors
5
+ // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
6
+ // Distributed under the MIT software license, see the accompanying
7
+ // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
8
+ function base (ALPHABET, name) {
9
+ if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
10
+ var BASE_MAP = new Uint8Array(256);
11
+ for (var j = 0; j < BASE_MAP.length; j++) {
12
+ BASE_MAP[j] = 255;
13
+ }
14
+ for (var i = 0; i < ALPHABET.length; i++) {
15
+ var x = ALPHABET.charAt(i);
16
+ var xc = x.charCodeAt(0);
17
+ if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
18
+ BASE_MAP[xc] = i;
19
+ }
20
+ var BASE = ALPHABET.length;
21
+ var LEADER = ALPHABET.charAt(0);
22
+ var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
23
+ var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
24
+ function encode (source) {
25
+ if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
26
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
27
+ } else if (Array.isArray(source)) {
28
+ source = Uint8Array.from(source);
29
+ }
30
+ if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
31
+ if (source.length === 0) { return '' }
32
+ // Skip & count leading zeroes.
33
+ var zeroes = 0;
34
+ var length = 0;
35
+ var pbegin = 0;
36
+ var pend = source.length;
37
+ while (pbegin !== pend && source[pbegin] === 0) {
38
+ pbegin++;
39
+ zeroes++;
40
+ }
41
+ // Allocate enough space in big-endian base58 representation.
42
+ var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
43
+ var b58 = new Uint8Array(size);
44
+ // Process the bytes.
45
+ while (pbegin !== pend) {
46
+ var carry = source[pbegin];
47
+ // Apply "b58 = b58 * 256 + ch".
48
+ var i = 0;
49
+ for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
50
+ carry += (256 * b58[it1]) >>> 0;
51
+ b58[it1] = (carry % BASE) >>> 0;
52
+ carry = (carry / BASE) >>> 0;
53
+ }
54
+ if (carry !== 0) { throw new Error('Non-zero carry') }
55
+ length = i;
56
+ pbegin++;
57
+ }
58
+ // Skip leading zeroes in base58 result.
59
+ var it2 = size - length;
60
+ while (it2 !== size && b58[it2] === 0) {
61
+ it2++;
62
+ }
63
+ // Translate the result into a string.
64
+ var str = LEADER.repeat(zeroes);
65
+ for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
66
+ return str
67
+ }
68
+ function decodeUnsafe (source) {
69
+ if (typeof source !== 'string') { throw new TypeError('Expected String') }
70
+ if (source.length === 0) { return new Uint8Array() }
71
+ var psz = 0;
72
+ // Skip leading spaces.
73
+ if (source[psz] === ' ') { return }
74
+ // Skip and count leading '1's.
75
+ var zeroes = 0;
76
+ var length = 0;
77
+ while (source[psz] === LEADER) {
78
+ zeroes++;
79
+ psz++;
80
+ }
81
+ // Allocate enough space in big-endian base256 representation.
82
+ var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
83
+ var b256 = new Uint8Array(size);
84
+ // Process the characters.
85
+ while (source[psz]) {
86
+ // Decode character
87
+ var carry = BASE_MAP[source.charCodeAt(psz)];
88
+ // Invalid character
89
+ if (carry === 255) { return }
90
+ var i = 0;
91
+ for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
92
+ carry += (BASE * b256[it3]) >>> 0;
93
+ b256[it3] = (carry % 256) >>> 0;
94
+ carry = (carry / 256) >>> 0;
95
+ }
96
+ if (carry !== 0) { throw new Error('Non-zero carry') }
97
+ length = i;
98
+ psz++;
99
+ }
100
+ // Skip trailing spaces.
101
+ if (source[psz] === ' ') { return }
102
+ // Skip leading zeroes in b256.
103
+ var it4 = size - length;
104
+ while (it4 !== size && b256[it4] === 0) {
105
+ it4++;
106
+ }
107
+ var vch = new Uint8Array(zeroes + (size - it4));
108
+ var j = zeroes;
109
+ while (it4 !== size) {
110
+ vch[j++] = b256[it4++];
111
+ }
112
+ return vch
113
+ }
114
+ function decode (string) {
115
+ var buffer = decodeUnsafe(string);
116
+ if (buffer) { return buffer }
117
+ throw new Error(`Non-${name} character`)
118
+ }
119
+ return {
120
+ encode: encode,
121
+ decodeUnsafe: decodeUnsafe,
122
+ decode: decode
123
+ }
124
+ }
125
+ var src = base;
126
+
127
+ var _brrp__multiformats_scope_baseX = src;
128
+
129
+ /**
130
+ * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o
131
+ * @returns {Uint8Array}
132
+ */
133
+ const coerce = o => {
134
+ if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o
135
+ if (o instanceof ArrayBuffer) return new Uint8Array(o)
136
+ if (ArrayBuffer.isView(o)) {
137
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)
138
+ }
139
+ throw new Error('Unknown type, must be binary type')
140
+ };
141
+
142
+ /**
143
+ * @param {string} str
144
+ * @returns {Uint8Array}
145
+ */
146
+ const fromString$1 = str => (new TextEncoder()).encode(str);
147
+
148
+ /**
149
+ * @param {Uint8Array} b
150
+ * @returns {string}
151
+ */
152
+ const toString$1 = b => (new TextDecoder()).decode(b);
153
+
154
+ /**
155
+ * Class represents both BaseEncoder and MultibaseEncoder meaning it
156
+ * can be used to encode to multibase or base encode without multibase
157
+ * prefix.
158
+ *
159
+ * @class
160
+ * @template {string} Base
161
+ * @template {string} Prefix
162
+ * @implements {API.MultibaseEncoder<Prefix>}
163
+ * @implements {API.BaseEncoder}
164
+ */
165
+ class Encoder {
166
+ /**
167
+ * @param {Base} name
168
+ * @param {Prefix} prefix
169
+ * @param {(bytes:Uint8Array) => string} baseEncode
170
+ */
171
+ constructor (name, prefix, baseEncode) {
172
+ this.name = name;
173
+ this.prefix = prefix;
174
+ this.baseEncode = baseEncode;
175
+ }
176
+
177
+ /**
178
+ * @param {Uint8Array} bytes
179
+ * @returns {API.Multibase<Prefix>}
180
+ */
181
+ encode (bytes) {
182
+ if (bytes instanceof Uint8Array) {
183
+ return `${this.prefix}${this.baseEncode(bytes)}`
184
+ } else {
185
+ throw Error('Unknown type, must be binary type')
186
+ }
187
+ }
188
+ }
189
+
190
+ /**
191
+ * @template {string} Prefix
192
+ */
193
+ /**
194
+ * Class represents both BaseDecoder and MultibaseDecoder so it could be used
195
+ * to decode multibases (with matching prefix) or just base decode strings
196
+ * with corresponding base encoding.
197
+ *
198
+ * @class
199
+ * @template {string} Base
200
+ * @template {string} Prefix
201
+ * @implements {API.MultibaseDecoder<Prefix>}
202
+ * @implements {API.UnibaseDecoder<Prefix>}
203
+ * @implements {API.BaseDecoder}
204
+ */
205
+ class Decoder {
206
+ /**
207
+ * @param {Base} name
208
+ * @param {Prefix} prefix
209
+ * @param {(text:string) => Uint8Array} baseDecode
210
+ */
211
+ constructor (name, prefix, baseDecode) {
212
+ this.name = name;
213
+ this.prefix = prefix;
214
+ /* c8 ignore next 3 */
215
+ if (prefix.codePointAt(0) === undefined) {
216
+ throw new Error('Invalid prefix character')
217
+ }
218
+ /** @private */
219
+ this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0));
220
+ this.baseDecode = baseDecode;
221
+ }
222
+
223
+ /**
224
+ * @param {string} text
225
+ */
226
+ decode (text) {
227
+ if (typeof text === 'string') {
228
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
229
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)
230
+ }
231
+ return this.baseDecode(text.slice(this.prefix.length))
232
+ } else {
233
+ throw Error('Can only multibase decode strings')
234
+ }
235
+ }
236
+
237
+ /**
238
+ * @template {string} OtherPrefix
239
+ * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
240
+ * @returns {ComposedDecoder<Prefix|OtherPrefix>}
241
+ */
242
+ or (decoder) {
243
+ return or(this, decoder)
244
+ }
245
+ }
246
+
247
+ /**
248
+ * @template {string} Prefix
249
+ * @typedef {Record<Prefix, API.UnibaseDecoder<Prefix>>} Decoders
250
+ */
251
+
252
+ /**
253
+ * @template {string} Prefix
254
+ * @implements {API.MultibaseDecoder<Prefix>}
255
+ * @implements {API.CombobaseDecoder<Prefix>}
256
+ */
257
+ class ComposedDecoder {
258
+ /**
259
+ * @param {Decoders<Prefix>} decoders
260
+ */
261
+ constructor (decoders) {
262
+ this.decoders = decoders;
263
+ }
264
+
265
+ /**
266
+ * @template {string} OtherPrefix
267
+ * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
268
+ * @returns {ComposedDecoder<Prefix|OtherPrefix>}
269
+ */
270
+ or (decoder) {
271
+ return or(this, decoder)
272
+ }
273
+
274
+ /**
275
+ * @param {string} input
276
+ * @returns {Uint8Array}
277
+ */
278
+ decode (input) {
279
+ const prefix = /** @type {Prefix} */ (input[0]);
280
+ const decoder = this.decoders[prefix];
281
+ if (decoder) {
282
+ return decoder.decode(input)
283
+ } else {
284
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)
285
+ }
286
+ }
287
+ }
288
+
289
+ /**
290
+ * @template {string} L
291
+ * @template {string} R
292
+ * @param {API.UnibaseDecoder<L>|API.CombobaseDecoder<L>} left
293
+ * @param {API.UnibaseDecoder<R>|API.CombobaseDecoder<R>} right
294
+ * @returns {ComposedDecoder<L|R>}
295
+ */
296
+ const or = (left, right) => new ComposedDecoder(/** @type {Decoders<L|R>} */({
297
+ ...(left.decoders || { [/** @type API.UnibaseDecoder<L> */(left).prefix]: left }),
298
+ ...(right.decoders || { [/** @type API.UnibaseDecoder<R> */(right).prefix]: right })
299
+ }));
300
+
301
+ /**
302
+ * @class
303
+ * @template {string} Base
304
+ * @template {string} Prefix
305
+ * @implements {API.MultibaseCodec<Prefix>}
306
+ * @implements {API.MultibaseEncoder<Prefix>}
307
+ * @implements {API.MultibaseDecoder<Prefix>}
308
+ * @implements {API.BaseCodec}
309
+ * @implements {API.BaseEncoder}
310
+ * @implements {API.BaseDecoder}
311
+ */
312
+ class Codec {
313
+ /**
314
+ * @param {Base} name
315
+ * @param {Prefix} prefix
316
+ * @param {(bytes:Uint8Array) => string} baseEncode
317
+ * @param {(text:string) => Uint8Array} baseDecode
318
+ */
319
+ constructor (name, prefix, baseEncode, baseDecode) {
320
+ this.name = name;
321
+ this.prefix = prefix;
322
+ this.baseEncode = baseEncode;
323
+ this.baseDecode = baseDecode;
324
+ this.encoder = new Encoder(name, prefix, baseEncode);
325
+ this.decoder = new Decoder(name, prefix, baseDecode);
326
+ }
327
+
328
+ /**
329
+ * @param {Uint8Array} input
330
+ */
331
+ encode (input) {
332
+ return this.encoder.encode(input)
333
+ }
334
+
335
+ /**
336
+ * @param {string} input
337
+ */
338
+ decode (input) {
339
+ return this.decoder.decode(input)
340
+ }
341
+ }
342
+
343
+ /**
344
+ * @template {string} Base
345
+ * @template {string} Prefix
346
+ * @param {object} options
347
+ * @param {Base} options.name
348
+ * @param {Prefix} options.prefix
349
+ * @param {(bytes:Uint8Array) => string} options.encode
350
+ * @param {(input:string) => Uint8Array} options.decode
351
+ * @returns {Codec<Base, Prefix>}
352
+ */
353
+ const from = ({ name, prefix, encode, decode }) =>
354
+ new Codec(name, prefix, encode, decode);
355
+
356
+ /**
357
+ * @template {string} Base
358
+ * @template {string} Prefix
359
+ * @param {object} options
360
+ * @param {Base} options.name
361
+ * @param {Prefix} options.prefix
362
+ * @param {string} options.alphabet
363
+ * @returns {Codec<Base, Prefix>}
364
+ */
365
+ const baseX = ({ prefix, name, alphabet }) => {
366
+ const { encode, decode } = _brrp__multiformats_scope_baseX(alphabet, name);
367
+ return from({
368
+ prefix,
369
+ name,
370
+ encode,
371
+ /**
372
+ * @param {string} text
373
+ */
374
+ decode: text => coerce(decode(text))
375
+ })
376
+ };
377
+
378
+ /**
379
+ * @param {string} string
380
+ * @param {string} alphabet
381
+ * @param {number} bitsPerChar
382
+ * @param {string} name
383
+ * @returns {Uint8Array}
384
+ */
385
+ const decode$1 = (string, alphabet, bitsPerChar, name) => {
386
+ // Build the character lookup table:
387
+ /** @type {Record<string, number>} */
388
+ const codes = {};
389
+ for (let i = 0; i < alphabet.length; ++i) {
390
+ codes[alphabet[i]] = i;
391
+ }
392
+
393
+ // Count the padding bytes:
394
+ let end = string.length;
395
+ while (string[end - 1] === '=') {
396
+ --end;
397
+ }
398
+
399
+ // Allocate the output:
400
+ const out = new Uint8Array((end * bitsPerChar / 8) | 0);
401
+
402
+ // Parse the data:
403
+ let bits = 0; // Number of bits currently in the buffer
404
+ let buffer = 0; // Bits waiting to be written out, MSB first
405
+ let written = 0; // Next byte to write
406
+ for (let i = 0; i < end; ++i) {
407
+ // Read one character from the string:
408
+ const value = codes[string[i]];
409
+ if (value === undefined) {
410
+ throw new SyntaxError(`Non-${name} character`)
411
+ }
412
+
413
+ // Append the bits to the buffer:
414
+ buffer = (buffer << bitsPerChar) | value;
415
+ bits += bitsPerChar;
416
+
417
+ // Write out some bits if the buffer has a byte's worth:
418
+ if (bits >= 8) {
419
+ bits -= 8;
420
+ out[written++] = 0xff & (buffer >> bits);
421
+ }
422
+ }
423
+
424
+ // Verify that we have received just enough bits:
425
+ if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {
426
+ throw new SyntaxError('Unexpected end of data')
427
+ }
428
+
429
+ return out
430
+ };
431
+
432
+ /**
433
+ * @param {Uint8Array} data
434
+ * @param {string} alphabet
435
+ * @param {number} bitsPerChar
436
+ * @returns {string}
437
+ */
438
+ const encode$1 = (data, alphabet, bitsPerChar) => {
439
+ const pad = alphabet[alphabet.length - 1] === '=';
440
+ const mask = (1 << bitsPerChar) - 1;
441
+ let out = '';
442
+
443
+ let bits = 0; // Number of bits currently in the buffer
444
+ let buffer = 0; // Bits waiting to be written out, MSB first
445
+ for (let i = 0; i < data.length; ++i) {
446
+ // Slurp data into the buffer:
447
+ buffer = (buffer << 8) | data[i];
448
+ bits += 8;
449
+
450
+ // Write out as much as we can:
451
+ while (bits > bitsPerChar) {
452
+ bits -= bitsPerChar;
453
+ out += alphabet[mask & (buffer >> bits)];
454
+ }
455
+ }
456
+
457
+ // Partial character:
458
+ if (bits) {
459
+ out += alphabet[mask & (buffer << (bitsPerChar - bits))];
460
+ }
461
+
462
+ // Add padding characters until we hit a byte boundary:
463
+ if (pad) {
464
+ while ((out.length * bitsPerChar) & 7) {
465
+ out += '=';
466
+ }
467
+ }
468
+
469
+ return out
470
+ };
471
+
472
+ /**
473
+ * RFC4648 Factory
474
+ *
475
+ * @template {string} Base
476
+ * @template {string} Prefix
477
+ * @param {object} options
478
+ * @param {Base} options.name
479
+ * @param {Prefix} options.prefix
480
+ * @param {string} options.alphabet
481
+ * @param {number} options.bitsPerChar
482
+ */
483
+ const rfc4648 = ({ name, prefix, bitsPerChar, alphabet }) => {
484
+ return from({
485
+ prefix,
486
+ name,
487
+ encode (input) {
488
+ return encode$1(input, alphabet, bitsPerChar)
489
+ },
490
+ decode (input) {
491
+ return decode$1(input, alphabet, bitsPerChar, name)
492
+ }
493
+ })
494
+ };
495
+
496
+ // @ts-check
497
+
498
+
499
+ const identity = from({
500
+ prefix: '\x00',
501
+ name: 'identity',
502
+ encode: (buf) => toString$1(buf),
503
+ decode: (str) => fromString$1(str)
504
+ });
505
+
506
+ var identityBase = /*#__PURE__*/Object.freeze({
507
+ __proto__: null,
508
+ identity: identity
509
+ });
510
+
511
+ // @ts-check
512
+
513
+
514
+ const base2 = rfc4648({
515
+ prefix: '0',
516
+ name: 'base2',
517
+ alphabet: '01',
518
+ bitsPerChar: 1
519
+ });
520
+
521
+ var base2$1 = /*#__PURE__*/Object.freeze({
522
+ __proto__: null,
523
+ base2: base2
524
+ });
525
+
526
+ // @ts-check
527
+
528
+
529
+ const base8 = rfc4648({
530
+ prefix: '7',
531
+ name: 'base8',
532
+ alphabet: '01234567',
533
+ bitsPerChar: 3
534
+ });
535
+
536
+ var base8$1 = /*#__PURE__*/Object.freeze({
537
+ __proto__: null,
538
+ base8: base8
539
+ });
540
+
541
+ const base10 = baseX({
542
+ prefix: '9',
543
+ name: 'base10',
544
+ alphabet: '0123456789'
545
+ });
546
+
547
+ var base10$1 = /*#__PURE__*/Object.freeze({
548
+ __proto__: null,
549
+ base10: base10
550
+ });
551
+
552
+ // @ts-check
553
+
554
+
555
+ const base16 = rfc4648({
556
+ prefix: 'f',
557
+ name: 'base16',
558
+ alphabet: '0123456789abcdef',
559
+ bitsPerChar: 4
560
+ });
561
+
562
+ const base16upper = rfc4648({
563
+ prefix: 'F',
564
+ name: 'base16upper',
565
+ alphabet: '0123456789ABCDEF',
566
+ bitsPerChar: 4
567
+ });
568
+
569
+ var base16$1 = /*#__PURE__*/Object.freeze({
570
+ __proto__: null,
571
+ base16: base16,
572
+ base16upper: base16upper
573
+ });
574
+
575
+ const base32 = rfc4648({
576
+ prefix: 'b',
577
+ name: 'base32',
578
+ alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
579
+ bitsPerChar: 5
580
+ });
581
+
582
+ const base32upper = rfc4648({
583
+ prefix: 'B',
584
+ name: 'base32upper',
585
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
586
+ bitsPerChar: 5
587
+ });
588
+
589
+ const base32pad = rfc4648({
590
+ prefix: 'c',
591
+ name: 'base32pad',
592
+ alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
593
+ bitsPerChar: 5
594
+ });
595
+
596
+ const base32padupper = rfc4648({
597
+ prefix: 'C',
598
+ name: 'base32padupper',
599
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
600
+ bitsPerChar: 5
601
+ });
602
+
603
+ const base32hex = rfc4648({
604
+ prefix: 'v',
605
+ name: 'base32hex',
606
+ alphabet: '0123456789abcdefghijklmnopqrstuv',
607
+ bitsPerChar: 5
608
+ });
609
+
610
+ const base32hexupper = rfc4648({
611
+ prefix: 'V',
612
+ name: 'base32hexupper',
613
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
614
+ bitsPerChar: 5
615
+ });
616
+
617
+ const base32hexpad = rfc4648({
618
+ prefix: 't',
619
+ name: 'base32hexpad',
620
+ alphabet: '0123456789abcdefghijklmnopqrstuv=',
621
+ bitsPerChar: 5
622
+ });
623
+
624
+ const base32hexpadupper = rfc4648({
625
+ prefix: 'T',
626
+ name: 'base32hexpadupper',
627
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
628
+ bitsPerChar: 5
629
+ });
630
+
631
+ const base32z = rfc4648({
632
+ prefix: 'h',
633
+ name: 'base32z',
634
+ alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
635
+ bitsPerChar: 5
636
+ });
637
+
638
+ var base32$1 = /*#__PURE__*/Object.freeze({
639
+ __proto__: null,
640
+ base32: base32,
641
+ base32hex: base32hex,
642
+ base32hexpad: base32hexpad,
643
+ base32hexpadupper: base32hexpadupper,
644
+ base32hexupper: base32hexupper,
645
+ base32pad: base32pad,
646
+ base32padupper: base32padupper,
647
+ base32upper: base32upper,
648
+ base32z: base32z
649
+ });
650
+
651
+ const base36 = baseX({
652
+ prefix: 'k',
653
+ name: 'base36',
654
+ alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
655
+ });
656
+
657
+ const base36upper = baseX({
658
+ prefix: 'K',
659
+ name: 'base36upper',
660
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
661
+ });
662
+
663
+ var base36$1 = /*#__PURE__*/Object.freeze({
664
+ __proto__: null,
665
+ base36: base36,
666
+ base36upper: base36upper
667
+ });
668
+
669
+ const base58btc = baseX({
670
+ name: 'base58btc',
671
+ prefix: 'z',
672
+ alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
673
+ });
674
+
675
+ const base58flickr = baseX({
676
+ name: 'base58flickr',
677
+ prefix: 'Z',
678
+ alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
679
+ });
680
+
681
+ var base58 = /*#__PURE__*/Object.freeze({
682
+ __proto__: null,
683
+ base58btc: base58btc,
684
+ base58flickr: base58flickr
685
+ });
686
+
687
+ // @ts-check
688
+
689
+
690
+ const base64 = rfc4648({
691
+ prefix: 'm',
692
+ name: 'base64',
693
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
694
+ bitsPerChar: 6
695
+ });
696
+
697
+ const base64pad = rfc4648({
698
+ prefix: 'M',
699
+ name: 'base64pad',
700
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
701
+ bitsPerChar: 6
702
+ });
703
+
704
+ const base64url = rfc4648({
705
+ prefix: 'u',
706
+ name: 'base64url',
707
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
708
+ bitsPerChar: 6
709
+ });
710
+
711
+ const base64urlpad = rfc4648({
712
+ prefix: 'U',
713
+ name: 'base64urlpad',
714
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
715
+ bitsPerChar: 6
716
+ });
717
+
718
+ var base64$1 = /*#__PURE__*/Object.freeze({
719
+ __proto__: null,
720
+ base64: base64,
721
+ base64pad: base64pad,
722
+ base64url: base64url,
723
+ base64urlpad: base64urlpad
724
+ });
725
+
726
+ const alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');
727
+ const alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])));
728
+ const alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])));
729
+
730
+ /**
731
+ * @param {Uint8Array} data
732
+ * @returns {string}
733
+ */
734
+ function encode (data) {
735
+ return data.reduce((p, c) => {
736
+ p += alphabetBytesToChars[c];
737
+ return p
738
+ }, '')
739
+ }
740
+
741
+ /**
742
+ * @param {string} str
743
+ * @returns {Uint8Array}
744
+ */
745
+ function decode (str) {
746
+ const byts = [];
747
+ for (const char of str) {
748
+ const byt = alphabetCharsToBytes[/** @type {number} */ (char.codePointAt(0))];
749
+ if (byt === undefined) {
750
+ throw new Error(`Non-base256emoji character: ${char}`)
751
+ }
752
+ byts.push(byt);
753
+ }
754
+ return new Uint8Array(byts)
755
+ }
756
+
757
+ const base256emoji = from({
758
+ prefix: '🚀',
759
+ name: 'base256emoji',
760
+ encode,
761
+ decode
762
+ });
763
+
764
+ var base256emoji$1 = /*#__PURE__*/Object.freeze({
765
+ __proto__: null,
766
+ base256emoji: base256emoji
767
+ });
768
+
769
+ // @ts-check
770
+
771
+ /**
772
+ * @template T
773
+ * @typedef {import('./interface.js').ByteView<T>} ByteView
774
+ */
775
+
776
+ new TextEncoder();
777
+ new TextDecoder();
778
+
779
+ // @ts-check
780
+
781
+
782
+ const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$1, ...base256emoji$1 };
783
+
784
+ /**
785
+ * To guarantee Uint8Array semantics, convert nodejs Buffers
786
+ * into vanilla Uint8Arrays
787
+ */
788
+ function asUint8Array(buf) {
789
+ if (globalThis.Buffer != null) {
790
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
791
+ }
792
+ return buf;
793
+ }
794
+
795
+ /**
796
+ * Returns a `Uint8Array` of the requested size. Referenced memory will
797
+ * be initialized to 0.
798
+ */
799
+ function alloc(size = 0) {
800
+ if (globalThis.Buffer?.alloc != null) {
801
+ return asUint8Array(globalThis.Buffer.alloc(size));
802
+ }
803
+ return new Uint8Array(size);
804
+ }
805
+ /**
806
+ * Where possible returns a Uint8Array of the requested size that references
807
+ * uninitialized memory. Only use if you are certain you will immediately
808
+ * overwrite every value in the returned `Uint8Array`.
809
+ */
810
+ function allocUnsafe(size = 0) {
811
+ if (globalThis.Buffer?.allocUnsafe != null) {
812
+ return asUint8Array(globalThis.Buffer.allocUnsafe(size));
813
+ }
814
+ return new Uint8Array(size);
815
+ }
816
+
817
+ function createCodec(name, prefix, encode, decode) {
818
+ return {
819
+ name,
820
+ prefix,
821
+ encoder: {
822
+ name,
823
+ prefix,
824
+ encode
825
+ },
826
+ decoder: {
827
+ decode
828
+ }
829
+ };
830
+ }
831
+ const string = createCodec('utf8', 'u', (buf) => {
832
+ const decoder = new TextDecoder('utf8');
833
+ return 'u' + decoder.decode(buf);
834
+ }, (str) => {
835
+ const encoder = new TextEncoder();
836
+ return encoder.encode(str.substring(1));
837
+ });
838
+ const ascii = createCodec('ascii', 'a', (buf) => {
839
+ let string = 'a';
840
+ for (let i = 0; i < buf.length; i++) {
841
+ string += String.fromCharCode(buf[i]);
842
+ }
843
+ return string;
844
+ }, (str) => {
845
+ str = str.substring(1);
846
+ const buf = allocUnsafe(str.length);
847
+ for (let i = 0; i < str.length; i++) {
848
+ buf[i] = str.charCodeAt(i);
849
+ }
850
+ return buf;
851
+ });
852
+ const BASES = {
853
+ utf8: string,
854
+ 'utf-8': string,
855
+ hex: bases.base16,
856
+ latin1: ascii,
857
+ ascii,
858
+ binary: ascii,
859
+ ...bases
860
+ };
861
+
862
+ /**
863
+ * Turns a `Uint8Array` into a string.
864
+ *
865
+ * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.
866
+ *
867
+ * Also `ascii` which is similar to node's 'binary' encoding.
868
+ */
869
+ function toString(array, encoding = 'utf8') {
870
+ const base = BASES[encoding];
871
+ if (base == null) {
872
+ throw new Error(`Unsupported encoding "${encoding}"`);
873
+ }
874
+ if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
875
+ return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8');
876
+ }
877
+ // strip multibase prefix
878
+ return base.encoder.encode(array).substring(1);
879
+ }
880
+
881
+ /**
882
+ * Create a `Uint8Array` from the passed string
883
+ *
884
+ * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.
885
+ *
886
+ * Also `ascii` which is similar to node's 'binary' encoding.
887
+ */
888
+ function fromString(string, encoding = 'utf8') {
889
+ const base = BASES[encoding];
890
+ if (base == null) {
891
+ throw new Error(`Unsupported encoding "${encoding}"`);
892
+ }
893
+ if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
894
+ return asUint8Array(globalThis.Buffer.from(string, 'utf-8'));
895
+ }
896
+ // add multibase prefix
897
+ return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
898
+ }
899
+
900
+ var Protocols;
901
+ (function (Protocols) {
902
+ Protocols["Relay"] = "relay";
903
+ Protocols["Store"] = "store";
904
+ Protocols["LightPush"] = "lightpush";
905
+ Protocols["Filter"] = "filter";
906
+ })(Protocols || (Protocols = {}));
907
+ var SendError;
908
+ (function (SendError) {
909
+ SendError["GENERIC_FAIL"] = "Generic error";
910
+ SendError["ENCODE_FAILED"] = "Failed to encode";
911
+ SendError["DECODE_FAILED"] = "Failed to decode";
912
+ SendError["SIZE_TOO_BIG"] = "Size is too big";
913
+ SendError["NO_RPC_RESPONSE"] = "No RPC response";
914
+ })(SendError || (SendError = {}));
915
+
916
+ var PageDirection;
917
+ (function (PageDirection) {
918
+ PageDirection["BACKWARD"] = "backward";
919
+ PageDirection["FORWARD"] = "forward";
920
+ })(PageDirection || (PageDirection = {}));
921
+
922
+ var Tags;
923
+ (function (Tags) {
924
+ Tags["BOOTSTRAP"] = "bootstrap";
925
+ Tags["PEER_EXCHANGE"] = "peer-exchange";
926
+ })(Tags || (Tags = {}));
927
+ var EPeersByDiscoveryEvents;
928
+ (function (EPeersByDiscoveryEvents) {
929
+ EPeersByDiscoveryEvents["PEER_DISCOVERY_BOOTSTRAP"] = "peer:discovery:bootstrap";
930
+ EPeersByDiscoveryEvents["PEER_DISCOVERY_PEER_EXCHANGE"] = "peer:discovery:peer-exchange";
931
+ EPeersByDiscoveryEvents["PEER_CONNECT_BOOTSTRAP"] = "peer:connected:bootstrap";
932
+ EPeersByDiscoveryEvents["PEER_CONNECT_PEER_EXCHANGE"] = "peer:connected:peer-exchange";
933
+ })(EPeersByDiscoveryEvents || (EPeersByDiscoveryEvents = {}));
934
+
935
+ /**
936
+ * Decode byte array to utf-8 string.
937
+ */
938
+ const bytesToUtf8 = (b) => toString(b, "utf8");
939
+ /**
940
+ * Encode utf-8 string to byte array.
941
+ */
942
+ const utf8ToBytes = (s) => fromString(s, "utf8");
943
+ /**
944
+ * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`
945
+ */
946
+ function concat(byteArrays, totalLength) {
947
+ const len = totalLength ?? byteArrays.reduce((acc, curr) => acc + curr.length, 0);
948
+ const res = new Uint8Array(len);
949
+ let offset = 0;
950
+ for (const bytes of byteArrays) {
951
+ res.set(bytes, offset);
952
+ offset += bytes.length;
953
+ }
954
+ return res;
955
+ }
956
+
957
+ const log = debug("waku:libp2p-utils");
958
+ /**
959
+ * Returns a pseudo-random peer that supports the given protocol.
960
+ * Useful for protocols such as store and light push
961
+ */
962
+ function selectRandomPeer(peers) {
963
+ if (peers.length === 0)
964
+ return;
965
+ const index = Math.round(Math.random() * (peers.length - 1));
966
+ return peers[index];
967
+ }
968
+ /**
969
+ * Returns the peer with the lowest latency.
970
+ * @param peerStore - The Libp2p PeerStore
971
+ * @param peers - The list of peers to choose from
972
+ * @returns The peer with the lowest latency, or undefined if no peer could be reached
973
+ */
974
+ async function selectLowestLatencyPeer(peerStore, peers) {
975
+ if (peers.length === 0)
976
+ return;
977
+ const results = await Promise.all(peers.map(async (peer) => {
978
+ const pingBytes = (await peerStore.get(peer.id)).metadata.get("ping");
979
+ if (!pingBytes)
980
+ return { peer, ping: Infinity };
981
+ const ping = Number(bytesToUtf8(pingBytes)) ?? Infinity;
982
+ return { peer, ping };
983
+ }));
984
+ const lowestLatencyResult = results.sort((a, b) => a.ping - b.ping)[0];
985
+ if (!lowestLatencyResult) {
986
+ return undefined;
987
+ }
988
+ return lowestLatencyResult.ping !== Infinity
989
+ ? lowestLatencyResult.peer
990
+ : undefined;
991
+ }
992
+ /**
993
+ * Returns the list of peers that supports the given protocol.
994
+ */
995
+ async function getPeersForProtocol(peerStore, protocols) {
996
+ const peers = [];
997
+ await peerStore.forEach((peer) => {
998
+ for (let i = 0; i < protocols.length; i++) {
999
+ if (peer.protocols.includes(protocols[i])) {
1000
+ peers.push(peer);
1001
+ break;
1002
+ }
1003
+ }
1004
+ });
1005
+ return peers;
1006
+ }
1007
+ /**
1008
+ * Returns a peer that supports the given protocol.
1009
+ * If peerId is provided, the peer with that id is returned.
1010
+ * Otherwise, the peer with the lowest latency is returned.
1011
+ * If no peer is found from the above criteria, a random peer is returned.
1012
+ */
1013
+ async function selectPeerForProtocol(peerStore, protocols, peerId) {
1014
+ let peer;
1015
+ if (peerId) {
1016
+ peer = await peerStore.get(peerId);
1017
+ if (!peer) {
1018
+ throw new Error(`Failed to retrieve connection details for provided peer in peer store: ${peerId.toString()}`);
1019
+ }
1020
+ }
1021
+ else {
1022
+ const peers = await getPeersForProtocol(peerStore, protocols);
1023
+ peer = await selectLowestLatencyPeer(peerStore, peers);
1024
+ if (!peer) {
1025
+ peer = selectRandomPeer(peers);
1026
+ if (!peer)
1027
+ throw new Error(`Failed to find known peer that registers protocols: ${protocols}`);
1028
+ }
1029
+ }
1030
+ let protocol;
1031
+ for (const codec of protocols) {
1032
+ if (peer.protocols.includes(codec)) {
1033
+ protocol = codec;
1034
+ // Do not break as we want to keep the last value
1035
+ }
1036
+ }
1037
+ log(`Using codec ${protocol}`);
1038
+ if (!protocol) {
1039
+ throw new Error(`Peer does not register required protocols (${peer.id.toString()}): ${protocols}`);
1040
+ }
1041
+ return { peer, protocol };
1042
+ }
1043
+ function selectConnection(connections) {
1044
+ if (!connections.length)
1045
+ return;
1046
+ if (connections.length === 1)
1047
+ return connections[0];
1048
+ let latestConnection;
1049
+ connections.forEach((connection) => {
1050
+ if (connection.status === "open") {
1051
+ if (!latestConnection) {
1052
+ latestConnection = connection;
1053
+ }
1054
+ else if (connection.timeline.open > latestConnection.timeline.open) {
1055
+ latestConnection = connection;
1056
+ }
1057
+ }
1058
+ });
1059
+ return latestConnection;
1060
+ }
1061
+
1062
+ /**
1063
+ * Retrieves a list of peers based on the specified criteria.
1064
+ *
1065
+ * @param peers - The list of peers to filter from.
1066
+ * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
1067
+ * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
1068
+ * @returns A Promise that resolves to an array of peers based on the specified criteria.
1069
+ */
1070
+ async function filterPeers(peers, numPeers, maxBootstrapPeers) {
1071
+ // Collect the bootstrap peers up to the specified maximum
1072
+ const bootstrapPeers = peers
1073
+ .filter((peer) => peer.tags.has(Tags.BOOTSTRAP))
1074
+ .slice(0, maxBootstrapPeers);
1075
+ // Collect non-bootstrap peers
1076
+ const nonBootstrapPeers = peers.filter((peer) => !peer.tags.has(Tags.BOOTSTRAP));
1077
+ // If numPeers is 0, return all peers
1078
+ if (numPeers === 0) {
1079
+ return [...bootstrapPeers, ...nonBootstrapPeers];
1080
+ }
1081
+ // Initialize the list of selected peers with the bootstrap peers
1082
+ const selectedPeers = [...bootstrapPeers];
1083
+ // Fill up to numPeers with remaining random peers if needed
1084
+ while (selectedPeers.length < numPeers && nonBootstrapPeers.length > 0) {
1085
+ const randomIndex = Math.floor(Math.random() * nonBootstrapPeers.length);
1086
+ const randomPeer = nonBootstrapPeers.splice(randomIndex, 1)[0];
1087
+ selectedPeers.push(randomPeer);
1088
+ }
1089
+ return selectedPeers;
1090
+ }
1091
+
1092
+ class StreamManager {
1093
+ multicodec;
1094
+ getConnections;
1095
+ addEventListener;
1096
+ streamPool;
1097
+ log;
1098
+ constructor(multicodec, getConnections, addEventListener) {
1099
+ this.multicodec = multicodec;
1100
+ this.getConnections = getConnections;
1101
+ this.addEventListener = addEventListener;
1102
+ this.log = debug(`waku:stream-manager:${multicodec}`);
1103
+ this.addEventListener("peer:update", this.handlePeerUpdateStreamPool.bind(this));
1104
+ this.getStream = this.getStream.bind(this);
1105
+ this.streamPool = new Map();
1106
+ }
1107
+ async getStream(peer) {
1108
+ const peerIdStr = peer.id.toString();
1109
+ const streamPromise = this.streamPool.get(peerIdStr);
1110
+ if (!streamPromise) {
1111
+ return this.newStream(peer); // fallback by creating a new stream on the spot
1112
+ }
1113
+ // We have the stream, let's remove it from the map
1114
+ this.streamPool.delete(peerIdStr);
1115
+ this.prepareNewStream(peer);
1116
+ const stream = await streamPromise;
1117
+ if (stream.status === "closed") {
1118
+ return this.newStream(peer); // fallback by creating a new stream on the spot
1119
+ }
1120
+ return stream;
1121
+ }
1122
+ async newStream(peer) {
1123
+ const connections = this.getConnections(peer.id);
1124
+ const connection = selectConnection(connections);
1125
+ if (!connection) {
1126
+ throw new Error("Failed to get a connection to the peer");
1127
+ }
1128
+ return connection.newStream(this.multicodec);
1129
+ }
1130
+ prepareNewStream(peer) {
1131
+ const streamPromise = this.newStream(peer);
1132
+ this.streamPool.set(peer.id.toString(), streamPromise);
1133
+ }
1134
+ handlePeerUpdateStreamPool = (evt) => {
1135
+ const peer = evt.detail.peer;
1136
+ if (peer.protocols.includes(this.multicodec)) {
1137
+ this.log(`Preemptively opening a stream to ${peer.id.toString()}`);
1138
+ this.prepareNewStream(peer);
1139
+ }
1140
+ };
1141
+ }
1142
+
1143
+ /**
1144
+ * A class with predefined helpers, to be used as a base to implement Waku
1145
+ * Protocols.
1146
+ */
1147
+ class BaseProtocol {
1148
+ multicodec;
1149
+ components;
1150
+ addLibp2pEventListener;
1151
+ removeLibp2pEventListener;
1152
+ streamManager;
1153
+ constructor(multicodec, components) {
1154
+ this.multicodec = multicodec;
1155
+ this.components = components;
1156
+ this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);
1157
+ this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);
1158
+ this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);
1159
+ }
1160
+ async getStream(peer) {
1161
+ return this.streamManager.getStream(peer);
1162
+ }
1163
+ get peerStore() {
1164
+ return this.components.peerStore;
1165
+ }
1166
+ /**
1167
+ * Returns known peers from the address book (`libp2p.peerStore`) that support
1168
+ * the class protocol. Waku may or may not be currently connected to these
1169
+ * peers.
1170
+ */
1171
+ async peers() {
1172
+ return getPeersForProtocol(this.peerStore, [this.multicodec]);
1173
+ }
1174
+ async getPeer(peerId) {
1175
+ const { peer } = await selectPeerForProtocol(this.peerStore, [this.multicodec], peerId);
1176
+ return peer;
1177
+ }
1178
+ /**
1179
+ * Retrieves a list of peers based on the specified criteria.
1180
+ *
1181
+ * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
1182
+ * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
1183
+ * @returns A Promise that resolves to an array of peers based on the specified criteria.
1184
+ */
1185
+ async getPeers({ numPeers, maxBootstrapPeers } = {
1186
+ maxBootstrapPeers: 1,
1187
+ numPeers: 0
1188
+ }) {
1189
+ // Retrieve all peers that support the protocol
1190
+ const allPeersForProtocol = await getPeersForProtocol(this.peerStore, [
1191
+ this.multicodec
1192
+ ]);
1193
+ // Filter the peers based on the specified criteria
1194
+ return filterPeers(allPeersForProtocol, numPeers, maxBootstrapPeers);
1195
+ }
1196
+ }
1197
+
1198
+ export { BaseProtocol as B, EPeersByDiscoveryEvents as E, Protocols as P, SendError as S, Tags as T, allocUnsafe as a, asUint8Array as b, alloc as c, concat as d, StreamManager as e, fromString as f, toString as t, utf8ToBytes as u };