@waku/core 0.0.33-c50088a.0 → 0.0.33-c9fdfb3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bundle/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { v as version_0, e as encodingLength, a as encode$1, d as decode$1, M as MessagePush, F as FilterSubscribeRequest, b as FilterSubscribeResponse$1, P as PushRpc$1, c as PushResponse, S as StoreQueryRequest$1, f as StoreQueryResponse$1, g as createEncoder, p as pubsubTopicToSingleShardInfo, s as shardInfoToPubsubTopics, W as WakuMetadataRequest, h as pubsubTopicsToShardInfo, i as WakuMetadataResponse } from './version_0-CnjebqQa.js';
2
- export { j as createDecoder } from './version_0-CnjebqQa.js';
3
- import { a as allocUnsafe, b as alloc, L as Logger, P as ProtocolError, c as Protocols, u as utf8ToBytes, T as Tags, E as EPeersByDiscoveryEvents, d as EConnectionStateEvents, H as HealthStatus } from './index-CpCu13gb.js';
4
- import { B as BaseProtocol } from './base_protocol-BUWwtk7E.js';
5
- export { S as StreamManager } from './base_protocol-BUWwtk7E.js';
1
+ import { v as version_0, e as encodingLength, a as encode$1, d as decode$1, M as MessagePush, F as FilterSubscribeRequest, b as FilterSubscribeResponse$1, P as PushRpc$1, c as PushResponse, S as StoreQueryRequest$1, f as StoreQueryResponse$1, g as createEncoder, p as pubsubTopicToSingleShardInfo, s as shardInfoToPubsubTopics, W as WakuMetadataRequest, h as pubsubTopicsToShardInfo, i as WakuMetadataResponse } from './version_0-BYg0O3M-.js';
2
+ export { j as createDecoder } from './version_0-BYg0O3M-.js';
3
+ import { a as allocUnsafe, b as alloc, L as Logger, P as ProtocolError, u as utf8ToBytes, T as Tags, E as EPeersByDiscoveryEvents, c as EConnectionStateEvents, H as HealthStatus, d as Protocols } from './index-CeEH6b9b.js';
4
+ import { B as BaseProtocol } from './base_protocol-BDjsZTsQ.js';
5
+ export { S as StreamManager } from './base_protocol-BDjsZTsQ.js';
6
6
 
7
7
  const MB = 1024 ** 2;
8
8
  const SIZE_CAP_IN_MB = 1;
@@ -1094,7 +1094,7 @@ class FIFO {
1094
1094
  * // [ [1, 2, 3] ]
1095
1095
  * ```
1096
1096
  */
1097
- let AbortError$1 = class AbortError extends Error {
1097
+ class AbortError extends Error {
1098
1098
  type;
1099
1099
  code;
1100
1100
  constructor(message, code) {
@@ -1102,7 +1102,7 @@ let AbortError$1 = class AbortError extends Error {
1102
1102
  this.type = 'aborted';
1103
1103
  this.code = code ?? 'ABORT_ERR';
1104
1104
  }
1105
- };
1105
+ }
1106
1106
  function pushable(options = {}) {
1107
1107
  const getNext = (buffer) => {
1108
1108
  const next = buffer.shift();
@@ -1222,7 +1222,7 @@ function _pushable(getNext, options) {
1222
1222
  if (signal != null) {
1223
1223
  cancel = new Promise((resolve, reject) => {
1224
1224
  listener = () => {
1225
- reject(new AbortError$1());
1225
+ reject(new AbortError());
1226
1226
  };
1227
1227
  signal.addEventListener('abort', listener);
1228
1228
  });
@@ -1611,26 +1611,24 @@ class FilterSubscribeResponse {
1611
1611
  }
1612
1612
  }
1613
1613
 
1614
- const log$6 = new Logger("filter:v2");
1614
+ const log$5 = new Logger("filter:v2");
1615
1615
  const FilterCodecs = {
1616
1616
  SUBSCRIBE: "/vac/waku/filter-subscribe/2.0.0-beta1",
1617
1617
  PUSH: "/vac/waku/filter-push/2.0.0-beta1"
1618
1618
  };
1619
1619
  class FilterCore extends BaseProtocol {
1620
1620
  handleIncomingMessage;
1621
- handleError;
1622
1621
  pubsubTopics;
1623
- constructor(handleIncomingMessage, handleError, pubsubTopics, libp2p) {
1624
- super(FilterCodecs.SUBSCRIBE, libp2p.components, log$6, pubsubTopics);
1622
+ constructor(handleIncomingMessage, pubsubTopics, libp2p) {
1623
+ super(FilterCodecs.SUBSCRIBE, libp2p.components, log$5, pubsubTopics);
1625
1624
  this.handleIncomingMessage = handleIncomingMessage;
1626
- this.handleError = handleError;
1627
1625
  this.pubsubTopics = pubsubTopics;
1628
1626
  libp2p
1629
1627
  .handle(FilterCodecs.PUSH, this.onRequest.bind(this), {
1630
1628
  maxInboundStreams: 100
1631
1629
  })
1632
1630
  .catch((e) => {
1633
- log$6.error("Failed to register ", FilterCodecs.PUSH, e);
1631
+ log$5.error("Failed to register ", FilterCodecs.PUSH, e);
1634
1632
  });
1635
1633
  }
1636
1634
  async subscribe(pubsubTopic, peer, contentTopics) {
@@ -1641,7 +1639,7 @@ class FilterCore extends BaseProtocol {
1641
1639
  res = await pipe([request.encode()], encode, stream, decode, async (source) => await all(source));
1642
1640
  }
1643
1641
  catch (error) {
1644
- log$6.error("Failed to send subscribe request", error);
1642
+ log$5.error("Failed to send subscribe request", error);
1645
1643
  return {
1646
1644
  success: null,
1647
1645
  failure: {
@@ -1652,7 +1650,7 @@ class FilterCore extends BaseProtocol {
1652
1650
  }
1653
1651
  const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());
1654
1652
  if (statusCode < 200 || statusCode >= 300) {
1655
- log$6.error(`Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1653
+ log$5.error(`Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1656
1654
  return {
1657
1655
  failure: {
1658
1656
  error: ProtocolError.REMOTE_PEER_REJECTED,
@@ -1672,7 +1670,7 @@ class FilterCore extends BaseProtocol {
1672
1670
  stream = await this.getStream(peer);
1673
1671
  }
1674
1672
  catch (error) {
1675
- log$6.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);
1673
+ log$5.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);
1676
1674
  return {
1677
1675
  success: null,
1678
1676
  failure: {
@@ -1686,7 +1684,7 @@ class FilterCore extends BaseProtocol {
1686
1684
  await pipe([unsubscribeRequest.encode()], encode, stream.sink);
1687
1685
  }
1688
1686
  catch (error) {
1689
- log$6.error("Failed to send unsubscribe request", error);
1687
+ log$5.error("Failed to send unsubscribe request", error);
1690
1688
  return {
1691
1689
  success: null,
1692
1690
  failure: {
@@ -1715,7 +1713,7 @@ class FilterCore extends BaseProtocol {
1715
1713
  }
1716
1714
  const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());
1717
1715
  if (statusCode < 200 || statusCode >= 300) {
1718
- log$6.error(`Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1716
+ log$5.error(`Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1719
1717
  return {
1720
1718
  failure: {
1721
1719
  error: ProtocolError.REMOTE_PEER_REJECTED,
@@ -1735,7 +1733,7 @@ class FilterCore extends BaseProtocol {
1735
1733
  stream = await this.getStream(peer);
1736
1734
  }
1737
1735
  catch (error) {
1738
- log$6.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);
1736
+ log$5.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);
1739
1737
  return {
1740
1738
  success: null,
1741
1739
  failure: {
@@ -1750,7 +1748,7 @@ class FilterCore extends BaseProtocol {
1750
1748
  res = await pipe([request.encode()], encode, stream, decode, async (source) => await all(source));
1751
1749
  }
1752
1750
  catch (error) {
1753
- log$6.error("Failed to send ping request", error);
1751
+ log$5.error("Failed to send ping request", error);
1754
1752
  return {
1755
1753
  success: null,
1756
1754
  failure: {
@@ -1770,7 +1768,7 @@ class FilterCore extends BaseProtocol {
1770
1768
  }
1771
1769
  const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());
1772
1770
  if (statusCode < 200 || statusCode >= 300) {
1773
- log$6.error(`Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1771
+ log$5.error(`Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1774
1772
  return {
1775
1773
  success: null,
1776
1774
  failure: {
@@ -1787,31 +1785,30 @@ class FilterCore extends BaseProtocol {
1787
1785
  onRequest(streamData) {
1788
1786
  const { connection, stream } = streamData;
1789
1787
  const { remotePeer } = connection;
1790
- log$6.info(`Received message from ${remotePeer.toString()}`);
1788
+ log$5.info(`Received message from ${remotePeer.toString()}`);
1791
1789
  try {
1792
1790
  pipe(stream, decode, async (source) => {
1793
1791
  for await (const bytes of source) {
1794
1792
  const response = FilterPushRpc.decode(bytes.slice());
1795
1793
  const { pubsubTopic, wakuMessage } = response;
1796
1794
  if (!wakuMessage) {
1797
- log$6.error("Received empty message");
1795
+ log$5.error("Received empty message");
1798
1796
  return;
1799
1797
  }
1800
1798
  if (!pubsubTopic) {
1801
- log$6.error("Pubsub topic missing from push message");
1799
+ log$5.error("Pubsub topic missing from push message");
1802
1800
  return;
1803
1801
  }
1804
1802
  await this.handleIncomingMessage(pubsubTopic, wakuMessage, connection.remotePeer.toString());
1805
1803
  }
1806
1804
  }).then(() => {
1807
- log$6.info("Receiving pipe closed.");
1805
+ log$5.info("Receiving pipe closed.");
1808
1806
  }, async (e) => {
1809
- log$6.error("Error with receiving pipe", e, " -- ", "on peer ", connection.remotePeer.toString(), " -- ", "stream ", stream);
1810
- await this.handleError(e);
1807
+ log$5.error("Error with receiving pipe", e, " -- ", "on peer ", connection.remotePeer.toString(), " -- ", "stream ", stream);
1811
1808
  });
1812
1809
  }
1813
1810
  catch (e) {
1814
- log$6.error("Error decoding message", e);
1811
+ log$5.error("Error decoding message", e);
1815
1812
  }
1816
1813
  }
1817
1814
  }
@@ -1877,7 +1874,7 @@ const matchRLNErrorMessage = (info) => {
1877
1874
  return ProtocolError.RLN_PROOF_GENERATION;
1878
1875
  };
1879
1876
 
1880
- const log$5 = new Logger("light-push");
1877
+ const log$4 = new Logger("light-push");
1881
1878
  const LightPushCodec = "/vac/waku/lightpush/2.0.0-beta1";
1882
1879
  /**
1883
1880
  * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).
@@ -1885,22 +1882,22 @@ const LightPushCodec = "/vac/waku/lightpush/2.0.0-beta1";
1885
1882
  class LightPushCore extends BaseProtocol {
1886
1883
  pubsubTopics;
1887
1884
  constructor(pubsubTopics, libp2p) {
1888
- super(LightPushCodec, libp2p.components, log$5, pubsubTopics);
1885
+ super(LightPushCodec, libp2p.components, log$4, pubsubTopics);
1889
1886
  this.pubsubTopics = pubsubTopics;
1890
1887
  }
1891
1888
  async preparePushMessage(encoder, message) {
1892
1889
  try {
1893
1890
  if (!message.payload || message.payload.length === 0) {
1894
- log$5.error("Failed to send waku light push: payload is empty");
1891
+ log$4.error("Failed to send waku light push: payload is empty");
1895
1892
  return { query: null, error: ProtocolError.EMPTY_PAYLOAD };
1896
1893
  }
1897
1894
  if (!(await isMessageSizeUnderCap(encoder, message))) {
1898
- log$5.error("Failed to send waku light push: message is bigger than 1MB");
1895
+ log$4.error("Failed to send waku light push: message is bigger than 1MB");
1899
1896
  return { query: null, error: ProtocolError.SIZE_TOO_BIG };
1900
1897
  }
1901
1898
  const protoMessage = await encoder.toProtoObj(message);
1902
1899
  if (!protoMessage) {
1903
- log$5.error("Failed to encode to protoMessage, aborting push");
1900
+ log$4.error("Failed to encode to protoMessage, aborting push");
1904
1901
  return {
1905
1902
  query: null,
1906
1903
  error: ProtocolError.ENCODE_FAILED
@@ -1910,7 +1907,7 @@ class LightPushCore extends BaseProtocol {
1910
1907
  return { query, error: null };
1911
1908
  }
1912
1909
  catch (error) {
1913
- log$5.error("Failed to prepare push message", error);
1910
+ log$4.error("Failed to prepare push message", error);
1914
1911
  return {
1915
1912
  query: null,
1916
1913
  error: ProtocolError.GENERIC_FAIL
@@ -1933,7 +1930,7 @@ class LightPushCore extends BaseProtocol {
1933
1930
  stream = await this.getStream(peer);
1934
1931
  }
1935
1932
  catch (error) {
1936
- log$5.error("Failed to get stream", error);
1933
+ log$4.error("Failed to get stream", error);
1937
1934
  return {
1938
1935
  success: null,
1939
1936
  failure: {
@@ -1947,7 +1944,7 @@ class LightPushCore extends BaseProtocol {
1947
1944
  res = await pipe([query.encode()], encode, stream, decode, async (source) => await all(source));
1948
1945
  }
1949
1946
  catch (err) {
1950
- log$5.error("Failed to send waku light push request", err);
1947
+ log$4.error("Failed to send waku light push request", err);
1951
1948
  return {
1952
1949
  success: null,
1953
1950
  failure: {
@@ -1965,7 +1962,7 @@ class LightPushCore extends BaseProtocol {
1965
1962
  response = PushRpc.decode(bytes).response;
1966
1963
  }
1967
1964
  catch (err) {
1968
- log$5.error("Failed to decode push reply", err);
1965
+ log$4.error("Failed to decode push reply", err);
1969
1966
  return {
1970
1967
  success: null,
1971
1968
  failure: {
@@ -1975,7 +1972,7 @@ class LightPushCore extends BaseProtocol {
1975
1972
  };
1976
1973
  }
1977
1974
  if (!response) {
1978
- log$5.error("Remote peer fault: No response in PushRPC");
1975
+ log$4.error("Remote peer fault: No response in PushRPC");
1979
1976
  return {
1980
1977
  success: null,
1981
1978
  failure: {
@@ -1986,7 +1983,7 @@ class LightPushCore extends BaseProtocol {
1986
1983
  }
1987
1984
  if (isRLNResponseError(response.info)) {
1988
1985
  const rlnErrorCase = matchRLNErrorMessage(response.info);
1989
- log$5.error("Remote peer rejected the message: ", rlnErrorCase);
1986
+ log$4.error("Remote peer rejected the message: ", rlnErrorCase);
1990
1987
  return {
1991
1988
  success: null,
1992
1989
  failure: {
@@ -1996,7 +1993,7 @@ class LightPushCore extends BaseProtocol {
1996
1993
  };
1997
1994
  }
1998
1995
  if (!response.isSuccess) {
1999
- log$5.error("Remote peer rejected the message: ", response.info);
1996
+ log$4.error("Remote peer rejected the message: ", response.info);
2000
1997
  return {
2001
1998
  success: null,
2002
1999
  failure: {
@@ -2101,12 +2098,12 @@ class StoreQueryResponse {
2101
2098
  }
2102
2099
  }
2103
2100
 
2104
- const log$4 = new Logger("store");
2101
+ const log$3 = new Logger("store");
2105
2102
  const StoreCodec = "/vac/waku/store-query/3.0.0";
2106
2103
  class StoreCore extends BaseProtocol {
2107
2104
  pubsubTopics;
2108
2105
  constructor(pubsubTopics, libp2p) {
2109
- super(StoreCodec, libp2p.components, log$4, pubsubTopics);
2106
+ super(StoreCodec, libp2p.components, log$3, pubsubTopics);
2110
2107
  this.pubsubTopics = pubsubTopics;
2111
2108
  }
2112
2109
  async *queryPerPage(queryOpts, decoders, peer) {
@@ -2125,7 +2122,7 @@ class StoreCore extends BaseProtocol {
2125
2122
  stream = await this.getStream(peer);
2126
2123
  }
2127
2124
  catch (e) {
2128
- log$4.error("Failed to get stream", e);
2125
+ log$3.error("Failed to get stream", e);
2129
2126
  break;
2130
2127
  }
2131
2128
  const res = await pipe([storeQueryRequest.encode()], encode, stream, decode, async (source) => await all(source));
@@ -2137,14 +2134,14 @@ class StoreCore extends BaseProtocol {
2137
2134
  if (!storeQueryResponse.statusCode ||
2138
2135
  storeQueryResponse.statusCode >= 300) {
2139
2136
  const errorMessage = `Store query failed with status code: ${storeQueryResponse.statusCode}, description: ${storeQueryResponse.statusDesc}`;
2140
- log$4.error(errorMessage);
2137
+ log$3.error(errorMessage);
2141
2138
  throw new Error(errorMessage);
2142
2139
  }
2143
2140
  if (!storeQueryResponse.messages || !storeQueryResponse.messages.length) {
2144
- log$4.warn("Stopping pagination due to empty messages in response");
2141
+ log$3.warn("Stopping pagination due to empty messages in response");
2145
2142
  break;
2146
2143
  }
2147
- log$4.info(`${storeQueryResponse.messages.length} messages retrieved from store`);
2144
+ log$3.info(`${storeQueryResponse.messages.length} messages retrieved from store`);
2148
2145
  const decodedMessages = storeQueryResponse.messages.map((protoMsg) => {
2149
2146
  if (!protoMsg.message) {
2150
2147
  return Promise.resolve(undefined);
@@ -2182,377 +2179,6 @@ var index = /*#__PURE__*/Object.freeze({
2182
2179
  StoreCore: StoreCore
2183
2180
  });
2184
2181
 
2185
- class TimeoutError extends Error {
2186
- constructor(message) {
2187
- super(message);
2188
- this.name = 'TimeoutError';
2189
- }
2190
- }
2191
-
2192
- /**
2193
- An error to be thrown when the request is aborted by AbortController.
2194
- DOMException is thrown instead of this Error when DOMException is available.
2195
- */
2196
- class AbortError extends Error {
2197
- constructor(message) {
2198
- super();
2199
- this.name = 'AbortError';
2200
- this.message = message;
2201
- }
2202
- }
2203
-
2204
- /**
2205
- TODO: Remove AbortError and just throw DOMException when targeting Node 18.
2206
- */
2207
- const getDOMException = errorMessage => globalThis.DOMException === undefined
2208
- ? new AbortError(errorMessage)
2209
- : new DOMException(errorMessage);
2210
-
2211
- /**
2212
- TODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.
2213
- */
2214
- const getAbortedReason = signal => {
2215
- const reason = signal.reason === undefined
2216
- ? getDOMException('This operation was aborted.')
2217
- : signal.reason;
2218
-
2219
- return reason instanceof Error ? reason : getDOMException(reason);
2220
- };
2221
-
2222
- function pTimeout(promise, options) {
2223
- const {
2224
- milliseconds,
2225
- fallback,
2226
- message,
2227
- customTimers = {setTimeout, clearTimeout},
2228
- } = options;
2229
-
2230
- let timer;
2231
-
2232
- const wrappedPromise = new Promise((resolve, reject) => {
2233
- if (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {
2234
- throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
2235
- }
2236
-
2237
- if (options.signal) {
2238
- const {signal} = options;
2239
- if (signal.aborted) {
2240
- reject(getAbortedReason(signal));
2241
- }
2242
-
2243
- signal.addEventListener('abort', () => {
2244
- reject(getAbortedReason(signal));
2245
- });
2246
- }
2247
-
2248
- if (milliseconds === Number.POSITIVE_INFINITY) {
2249
- promise.then(resolve, reject);
2250
- return;
2251
- }
2252
-
2253
- // We create the error outside of `setTimeout` to preserve the stack trace.
2254
- const timeoutError = new TimeoutError();
2255
-
2256
- timer = customTimers.setTimeout.call(undefined, () => {
2257
- if (fallback) {
2258
- try {
2259
- resolve(fallback());
2260
- } catch (error) {
2261
- reject(error);
2262
- }
2263
-
2264
- return;
2265
- }
2266
-
2267
- if (typeof promise.cancel === 'function') {
2268
- promise.cancel();
2269
- }
2270
-
2271
- if (message === false) {
2272
- resolve();
2273
- } else if (message instanceof Error) {
2274
- reject(message);
2275
- } else {
2276
- timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
2277
- reject(timeoutError);
2278
- }
2279
- }, milliseconds);
2280
-
2281
- (async () => {
2282
- try {
2283
- resolve(await promise);
2284
- } catch (error) {
2285
- reject(error);
2286
- }
2287
- })();
2288
- });
2289
-
2290
- const cancelablePromise = wrappedPromise.finally(() => {
2291
- cancelablePromise.clear();
2292
- });
2293
-
2294
- cancelablePromise.clear = () => {
2295
- customTimers.clearTimeout.call(undefined, timer);
2296
- timer = undefined;
2297
- };
2298
-
2299
- return cancelablePromise;
2300
- }
2301
-
2302
- const normalizeEmitter = emitter => {
2303
- const addListener = emitter.addEventListener || emitter.on || emitter.addListener;
2304
- const removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;
2305
-
2306
- if (!addListener || !removeListener) {
2307
- throw new TypeError('Emitter is not compatible');
2308
- }
2309
-
2310
- return {
2311
- addListener: addListener.bind(emitter),
2312
- removeListener: removeListener.bind(emitter),
2313
- };
2314
- };
2315
-
2316
- function pEventMultiple(emitter, event, options) {
2317
- let cancel;
2318
- const returnValue = new Promise((resolve, reject) => {
2319
- options = {
2320
- rejectionEvents: ['error'],
2321
- multiArgs: false,
2322
- resolveImmediately: false,
2323
- ...options,
2324
- };
2325
-
2326
- if (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {
2327
- throw new TypeError('The `count` option should be at least 0 or more');
2328
- }
2329
-
2330
- options.signal?.throwIfAborted();
2331
-
2332
- // Allow multiple events
2333
- const events = [event].flat();
2334
-
2335
- const items = [];
2336
- const {addListener, removeListener} = normalizeEmitter(emitter);
2337
-
2338
- const onItem = (...arguments_) => {
2339
- const value = options.multiArgs ? arguments_ : arguments_[0];
2340
-
2341
- // eslint-disable-next-line unicorn/no-array-callback-reference
2342
- if (options.filter && !options.filter(value)) {
2343
- return;
2344
- }
2345
-
2346
- items.push(value);
2347
-
2348
- if (options.count === items.length) {
2349
- cancel();
2350
- resolve(items);
2351
- }
2352
- };
2353
-
2354
- const rejectHandler = error => {
2355
- cancel();
2356
- reject(error);
2357
- };
2358
-
2359
- cancel = () => {
2360
- for (const event of events) {
2361
- removeListener(event, onItem);
2362
- }
2363
-
2364
- for (const rejectionEvent of options.rejectionEvents) {
2365
- removeListener(rejectionEvent, rejectHandler);
2366
- }
2367
- };
2368
-
2369
- for (const event of events) {
2370
- addListener(event, onItem);
2371
- }
2372
-
2373
- for (const rejectionEvent of options.rejectionEvents) {
2374
- addListener(rejectionEvent, rejectHandler);
2375
- }
2376
-
2377
- if (options.signal) {
2378
- options.signal.addEventListener('abort', () => {
2379
- rejectHandler(options.signal.reason);
2380
- }, {once: true});
2381
- }
2382
-
2383
- if (options.resolveImmediately) {
2384
- resolve(items);
2385
- }
2386
- });
2387
-
2388
- returnValue.cancel = cancel;
2389
-
2390
- if (typeof options.timeout === 'number') {
2391
- const timeout = pTimeout(returnValue, {milliseconds: options.timeout});
2392
- timeout.cancel = cancel;
2393
- return timeout;
2394
- }
2395
-
2396
- return returnValue;
2397
- }
2398
-
2399
- function pEvent(emitter, event, options) {
2400
- if (typeof options === 'function') {
2401
- options = {filter: options};
2402
- }
2403
-
2404
- options = {
2405
- ...options,
2406
- count: 1,
2407
- resolveImmediately: false,
2408
- };
2409
-
2410
- const arrayPromise = pEventMultiple(emitter, event, options);
2411
- const promise = arrayPromise.then(array => array[0]);
2412
- promise.cancel = arrayPromise.cancel;
2413
-
2414
- return promise;
2415
- }
2416
-
2417
- const log$3 = new Logger("wait-for-remote-peer");
2418
- //TODO: move this function within the Waku class: https://github.com/waku-org/js-waku/issues/1761
2419
- /**
2420
- * Wait for a remote peer to be ready given the passed protocols.
2421
- * Must be used after attempting to connect to nodes, using
2422
- * {@link @waku/sdk!WakuNode.dial} or a bootstrap method with
2423
- * {@link @waku/sdk!createLightNode}.
2424
- *
2425
- * If the passed protocols is a GossipSub protocol, then it resolves only once
2426
- * a peer is in a mesh, to help ensure that other peers will send and receive
2427
- * message to us.
2428
- *
2429
- * @param waku The Waku Node
2430
- * @param protocols The protocols that need to be enabled by remote peers.
2431
- * @param timeoutMs A timeout value in milliseconds..
2432
- *
2433
- * @returns A promise that **resolves** if all desired protocols are fulfilled by
2434
- * remote nodes, **rejects** if the timeoutMs is reached.
2435
- * @throws If passing a protocol that is not mounted
2436
- * @default Wait for remote peers with protocols enabled locally and no time out is applied.
2437
- */
2438
- async function waitForRemotePeer(waku, protocols, timeoutMs) {
2439
- protocols = protocols ?? getEnabledProtocols(waku);
2440
- if (!waku.isStarted())
2441
- return Promise.reject("Waku node is not started");
2442
- const promises = [];
2443
- if (protocols.includes(Protocols.Relay)) {
2444
- if (!waku.relay)
2445
- throw new Error("Cannot wait for Relay peer: protocol not mounted");
2446
- promises.push(waitForGossipSubPeerInMesh(waku.relay));
2447
- }
2448
- if (protocols.includes(Protocols.Store)) {
2449
- if (!waku.store)
2450
- throw new Error("Cannot wait for Store peer: protocol not mounted");
2451
- promises.push(waitForConnectedPeer(waku.store.protocol, waku.libp2p.services.metadata));
2452
- }
2453
- if (protocols.includes(Protocols.LightPush)) {
2454
- if (!waku.lightPush)
2455
- throw new Error("Cannot wait for LightPush peer: protocol not mounted");
2456
- promises.push(waitForConnectedPeer(waku.lightPush.protocol, waku.libp2p.services.metadata));
2457
- }
2458
- if (protocols.includes(Protocols.Filter)) {
2459
- if (!waku.filter)
2460
- throw new Error("Cannot wait for Filter peer: protocol not mounted");
2461
- promises.push(waitForConnectedPeer(waku.filter.protocol, waku.libp2p.services.metadata));
2462
- }
2463
- if (timeoutMs) {
2464
- await rejectOnTimeout(Promise.all(promises), timeoutMs, "Timed out waiting for a remote peer.");
2465
- }
2466
- else {
2467
- await Promise.all(promises);
2468
- }
2469
- }
2470
- //TODO: move this function within protocol SDK class: https://github.com/waku-org/js-waku/issues/1761
2471
- /**
2472
- * Wait for a peer with the given protocol to be connected.
2473
- * If sharding is enabled on the node, it will also wait for the peer to be confirmed by the metadata service.
2474
- */
2475
- async function waitForConnectedPeer(protocol, metadataService) {
2476
- const codec = protocol.multicodec;
2477
- const peers = await protocol.connectedPeers();
2478
- if (peers.length) {
2479
- if (!metadataService) {
2480
- log$3.info(`${codec} peer found: `, peers[0].id.toString());
2481
- return;
2482
- }
2483
- // once a peer is connected, we need to confirm the metadata handshake with at least one of those peers if sharding is enabled
2484
- try {
2485
- await Promise.any(peers.map((peer) => metadataService.confirmOrAttemptHandshake(peer.id)));
2486
- return;
2487
- }
2488
- catch (e) {
2489
- if (e.code === "ERR_CONNECTION_BEING_CLOSED")
2490
- log$3.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`);
2491
- log$3.error(`Error waiting for handshake confirmation: ${e}`);
2492
- }
2493
- }
2494
- log$3.info(`Waiting for ${codec} peer`);
2495
- // else we'll just wait for the next peer to connect
2496
- await new Promise((resolve) => {
2497
- const cb = (evt) => {
2498
- if (evt.detail?.protocols?.includes(codec)) {
2499
- if (metadataService) {
2500
- metadataService
2501
- .confirmOrAttemptHandshake(evt.detail.peerId)
2502
- .then(() => {
2503
- protocol.removeLibp2pEventListener("peer:identify", cb);
2504
- resolve();
2505
- })
2506
- .catch((e) => {
2507
- if (e.code === "ERR_CONNECTION_BEING_CLOSED")
2508
- log$3.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`);
2509
- log$3.error(`Error waiting for handshake confirmation: ${e}`);
2510
- });
2511
- }
2512
- else {
2513
- protocol.removeLibp2pEventListener("peer:identify", cb);
2514
- resolve();
2515
- }
2516
- }
2517
- };
2518
- protocol.addLibp2pEventListener("peer:identify", cb);
2519
- });
2520
- }
2521
- /**
2522
- * Wait for at least one peer with the given protocol to be connected and in the gossipsub
2523
- * mesh for all pubsubTopics.
2524
- */
2525
- async function waitForGossipSubPeerInMesh(waku) {
2526
- let peers = waku.getMeshPeers();
2527
- const pubsubTopics = waku.pubsubTopics;
2528
- for (const topic of pubsubTopics) {
2529
- while (peers.length == 0) {
2530
- await pEvent(waku.gossipSub, "gossipsub:heartbeat");
2531
- peers = waku.getMeshPeers(topic);
2532
- }
2533
- }
2534
- }
2535
- const awaitTimeout = (ms, rejectReason) => new Promise((_resolve, reject) => setTimeout(() => reject(rejectReason), ms));
2536
- async function rejectOnTimeout(promise, timeoutMs, rejectReason) {
2537
- await Promise.race([promise, awaitTimeout(timeoutMs, rejectReason)]);
2538
- }
2539
- function getEnabledProtocols(waku) {
2540
- const protocols = [];
2541
- if (waku.relay) {
2542
- protocols.push(Protocols.Relay);
2543
- }
2544
- if (waku.filter) {
2545
- protocols.push(Protocols.Filter);
2546
- }
2547
- if (waku.store) {
2548
- protocols.push(Protocols.Store);
2549
- }
2550
- if (waku.lightPush) {
2551
- protocols.push(Protocols.LightPush);
2552
- }
2553
- return protocols;
2554
- }
2555
-
2556
2182
  /** Noop for browser compatibility */
2557
2183
  function setMaxListeners$1() { }
2558
2184
 
@@ -3354,4 +2980,4 @@ function wakuMetadata(pubsubTopics) {
3354
2980
  return (components) => new Metadata(pubsubTopics, components);
3355
2981
  }
3356
2982
 
3357
- export { ConnectionManager, FilterCodecs, FilterCore, KeepAliveManager, LightPushCodec, LightPushCore, MetadataCodec, StoreCore, createEncoder, getHealthManager, index$3 as message, waitForRemotePeer, wakuMetadata, index$2 as waku_filter, index$1 as waku_light_push, index as waku_store };
2983
+ export { ConnectionManager, FilterCodecs, FilterCore, KeepAliveManager, LightPushCodec, LightPushCore, MetadataCodec, StoreCodec, StoreCore, createEncoder, getHealthManager, index$3 as message, wakuMetadata, index$2 as waku_filter, index$1 as waku_light_push, index as waku_store };