@libp2p/yamux 7.0.4
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/README.md +127 -0
- package/dist/index.min.js +4 -0
- package/dist/index.min.js.map +7 -0
- package/dist/src/config.d.ts +26 -0
- package/dist/src/config.d.ts.map +1 -0
- package/dist/src/config.js +37 -0
- package/dist/src/config.js.map +1 -0
- package/dist/src/constants.d.ts +12 -0
- package/dist/src/constants.d.ts.map +1 -0
- package/dist/src/constants.js +22 -0
- package/dist/src/constants.js.map +1 -0
- package/dist/src/decode.d.ts +34 -0
- package/dist/src/decode.d.ts.map +1 -0
- package/dist/src/decode.js +75 -0
- package/dist/src/decode.js.map +1 -0
- package/dist/src/encode.d.ts +3 -0
- package/dist/src/encode.d.ts.map +1 -0
- package/dist/src/encode.js +19 -0
- package/dist/src/encode.js.map +1 -0
- package/dist/src/errors.d.ts +40 -0
- package/dist/src/errors.d.ts.map +1 -0
- package/dist/src/errors.js +70 -0
- package/dist/src/errors.js.map +1 -0
- package/dist/src/frame.d.ts +54 -0
- package/dist/src/frame.d.ts.map +1 -0
- package/dist/src/frame.js +36 -0
- package/dist/src/frame.js.map +1 -0
- package/dist/src/index.d.ts +85 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +84 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/muxer.d.ts +91 -0
- package/dist/src/muxer.d.ts.map +1 -0
- package/dist/src/muxer.js +428 -0
- package/dist/src/muxer.js.map +1 -0
- package/dist/src/stream.d.ts +96 -0
- package/dist/src/stream.d.ts.map +1 -0
- package/dist/src/stream.js +240 -0
- package/dist/src/stream.js.map +1 -0
- package/package.json +188 -0
- package/src/config.ts +66 -0
- package/src/constants.ts +25 -0
- package/src/decode.ts +104 -0
- package/src/encode.ts +26 -0
- package/src/errors.ts +89 -0
- package/src/frame.ts +64 -0
- package/src/index.ts +90 -0
- package/src/muxer.ts +506 -0
- package/src/stream.ts +293 -0
package/README.md
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# @chainsafe/libp2p-yamux
|
|
2
|
+
|
|
3
|
+
[](https://codecov.io/gh/ChainSafe/js-libp2p-yamux)
|
|
4
|
+
[](https://github.com/ChainSafe/js-libp2p-yamux/actions/workflows/js-test-and-release.yml?query=branch%3Amaster)
|
|
5
|
+
|
|
6
|
+
> Yamux stream multiplexer for libp2p
|
|
7
|
+
|
|
8
|
+
# About
|
|
9
|
+
|
|
10
|
+
<!--
|
|
11
|
+
|
|
12
|
+
!IMPORTANT!
|
|
13
|
+
|
|
14
|
+
Everything in this README between "# About" and "# Install" is automatically
|
|
15
|
+
generated and will be overwritten the next time the doc generator is run.
|
|
16
|
+
|
|
17
|
+
To make changes to this section, please update the @packageDocumentation section
|
|
18
|
+
of src/index.js or src/index.ts
|
|
19
|
+
|
|
20
|
+
To experiment with formatting, please run "npm run docs" from the root of this
|
|
21
|
+
repo and examine the changes made.
|
|
22
|
+
|
|
23
|
+
-->
|
|
24
|
+
|
|
25
|
+
This module is a JavaScript implementation of [Yamux from Hashicorp](https://github.com/hashicorp/yamux/blob/master/spec.md) designed to be used with [js-libp2p](https://github.com/libp2p/js-libp2p).
|
|
26
|
+
|
|
27
|
+
## Example - Configure libp2p with Yamux
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
import { createLibp2p } from 'libp2p'
|
|
31
|
+
import { yamux } from '@chainsafe/libp2p-yamux'
|
|
32
|
+
|
|
33
|
+
const node = await createLibp2p({
|
|
34
|
+
// ... other options
|
|
35
|
+
streamMuxers: [
|
|
36
|
+
yamux()
|
|
37
|
+
]
|
|
38
|
+
})
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Example - Using the low-level API
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
import { yamux } from '@chainsafe/libp2p-yamux'
|
|
45
|
+
import { pipe } from 'it-pipe'
|
|
46
|
+
import { duplexPair } from 'it-pair/duplex'
|
|
47
|
+
import all from 'it-all'
|
|
48
|
+
|
|
49
|
+
// Connect two yamux muxers to demo basic stream multiplexing functionality
|
|
50
|
+
|
|
51
|
+
const clientMuxer = yamux({
|
|
52
|
+
client: true,
|
|
53
|
+
onIncomingStream: stream => {
|
|
54
|
+
// echo data on incoming streams
|
|
55
|
+
pipe(stream, stream)
|
|
56
|
+
},
|
|
57
|
+
onStreamEnd: stream => {
|
|
58
|
+
// do nothing
|
|
59
|
+
}
|
|
60
|
+
})()
|
|
61
|
+
|
|
62
|
+
const serverMuxer = yamux({
|
|
63
|
+
client: false,
|
|
64
|
+
onIncomingStream: stream => {
|
|
65
|
+
// echo data on incoming streams
|
|
66
|
+
pipe(stream, stream)
|
|
67
|
+
},
|
|
68
|
+
onStreamEnd: stream => {
|
|
69
|
+
// do nothing
|
|
70
|
+
}
|
|
71
|
+
})()
|
|
72
|
+
|
|
73
|
+
// `p` is our "connections", what we use to connect the two sides
|
|
74
|
+
// In a real application, a connection is usually to a remote computer
|
|
75
|
+
const p = duplexPair()
|
|
76
|
+
|
|
77
|
+
// connect the muxers together
|
|
78
|
+
pipe(p[0], clientMuxer, p[0])
|
|
79
|
+
pipe(p[1], serverMuxer, p[1])
|
|
80
|
+
|
|
81
|
+
// now either side can open streams
|
|
82
|
+
const stream0 = clientMuxer.newStream()
|
|
83
|
+
const stream1 = serverMuxer.newStream()
|
|
84
|
+
|
|
85
|
+
// Send some data to the other side
|
|
86
|
+
const encoder = new TextEncoder()
|
|
87
|
+
const data = [encoder.encode('hello'), encoder.encode('world')]
|
|
88
|
+
pipe(data, stream0)
|
|
89
|
+
|
|
90
|
+
// Receive data back
|
|
91
|
+
const result = await pipe(stream0, all)
|
|
92
|
+
|
|
93
|
+
// close a stream
|
|
94
|
+
stream1.close()
|
|
95
|
+
|
|
96
|
+
// close the muxer
|
|
97
|
+
clientMuxer.close()
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
# Install
|
|
101
|
+
|
|
102
|
+
```console
|
|
103
|
+
$ npm i @chainsafe/libp2p-yamux
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Browser `<script>` tag
|
|
107
|
+
|
|
108
|
+
Loading this module through a script tag will make its exports available as `ChainsafeLibp2pYamux` in the global namespace.
|
|
109
|
+
|
|
110
|
+
```html
|
|
111
|
+
<script src="https://unpkg.com/@chainsafe/libp2p-yamux/dist/index.min.js"></script>
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
# API Docs
|
|
115
|
+
|
|
116
|
+
- <https://ChainSafe.github.io/js-libp2p-yamux>
|
|
117
|
+
|
|
118
|
+
# License
|
|
119
|
+
|
|
120
|
+
Licensed under either of
|
|
121
|
+
|
|
122
|
+
- Apache 2.0, ([LICENSE-APACHE](https://github.com/ChainSafe/js-libp2p-yamux/LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
|
|
123
|
+
- MIT ([LICENSE-MIT](https://github.com/ChainSafe/js-libp2p-yamux/LICENSE-MIT) / <http://opensource.org/licenses/MIT>)
|
|
124
|
+
|
|
125
|
+
# Contribution
|
|
126
|
+
|
|
127
|
+
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PYamux = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
+
"use strict";var Libp2PYamux=(()=>{var ae=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var ke=(s,e)=>{for(var t in e)ae(s,t,{get:e[t],enumerable:!0})},_e=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Oe(e))!Fe.call(s,n)&&n!==t&&ae(s,n,{get:()=>e[n],enumerable:!(r=Me(e,n))||r.enumerable});return s};var ze=s=>_e(ae({},"__esModule",{value:!0}),s);var je={};ke(je,{GoAwayCode:()=>g,yamux:()=>He});var y=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var E=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}};var G=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var D=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},O=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Y=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}};var $=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},W=class extends Event{error;local;constructor(e,t,r){super("close",r),this.error=t,this.local=e}},q=class extends W{constructor(e,t){super(!0,e,t)}},K=class extends W{constructor(e,t){super(!1,e,t)}};var C=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);n==null&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(r!==!0&&r!==!1&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:i})=>i!==t),this.#e.set(e,n))}dispatchEvent(e){let t=super.dispatchEvent(e),r=this.#e.get(e.type);return r==null||(r=r.filter(({once:n})=>!n),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var pe=Symbol.for("@libp2p/service-capabilities"),tt=Symbol.for("@libp2p/service-dependencies");function ge(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function S(s=0){return new Uint8Array(s)}function F(s=0){return new Uint8Array(s)}function ue(s,e){e==null&&(e=s.reduce((n,i)=>n+i.length,0));let t=F(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var be=Symbol.for("@achingbrain/uint8arraylist");function we(s,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let r of s){let n=t+r.byteLength;if(e<n)return{buf:r,index:e-t};t=n}throw new RangeError("index is out of bounds")}function H(s){return!!s?.[be]}var v=class s{bufs;length;[be]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(H(r))t+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(H(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=we(this.bufs,e);return t.buf[t.index]}set(e,t){let r=we(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else if(H(e))for(let r=0;r<e.length;r++)this.set(t+r,e.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:r,length:n}=this._subList(e,t);return ue(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:ue(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),i=new s;return i.length=n,i.bufs=[...r],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let r=[],n=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],l=n,m=l+o.byteLength;if(n=m,e>=m)continue;let f=e>=l&&e<m,p=t>l&&t<=m;if(f&&p){if(e===l&&t===m){r.push(o);break}let u=e-l;r.push(o.subarray(u,u+(t-e)));break}if(f){if(e===0){r.push(o);continue}r.push(o.subarray(e-l));continue}if(p){if(t===m){r.push(o);break}r.push(o.subarray(0,t-l));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!H(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let n=r.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let u=0;u<i;u++)o[u]=-1;for(let u=0;u<n;u++)o[r[u]]=u;let l=o,m=this.byteLength-r.byteLength,f=r.byteLength-1,p;for(let u=t;u<=m;u+=p){p=0;for(let w=f;w>=0;w--){let h=this.get(u+w);if(r[w]!==h){p=Math.max(1,w-l[h]);break}}if(p===0)return u}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let r=F(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let n=S(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){let n=S(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){let n=S(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let r=F(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let n=S(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){let n=S(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){let n=S(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){let n=S(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){let n=S(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(e==null||!(e instanceof s)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ge(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new s;return r.bufs=e,t==null&&(t=e.reduce((n,i)=>n+i.byteLength,0)),r.length=t,r}};function j(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Q=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},B=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Q(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Q(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var le=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ye(s={}){return Ve(t=>{let r=t.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},s)}function Ve(s,e){e=e??{};let t=e.onEnd,r=new B,n,i,o,l=j(),m=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((c,T)=>{i=V=>{i=null,r.push(V);try{c(s(r))}catch(P){T(P)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{l.resolve(),l=j()})}},f=c=>i!=null?i(c):(r.push(c),n),p=c=>(r=new B,i!=null?i({error:c}):(r.push({error:c}),n)),u=c=>{if(o)return n;if(e?.objectMode!==!0&&c?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:c})},w=c=>o?n:(o=!0,c!=null?p(c):f({done:!0})),h=()=>(r=new B,w(),{done:!0}),z=c=>(w(c),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:m,return:h,throw:z,push:u,end:w,get readableLength(){return r.size},onEmpty:async c=>{let T=c?.signal;if(T?.throwIfAborted(),r.isEmpty())return;let V,P;T!=null&&(V=new Promise((Qe,Ue)=>{P=()=>{Ue(new le)},T.addEventListener("abort",P)}));try{await Promise.race([l.promise,V])}finally{P!=null&&T!=null&&T?.removeEventListener("abort",P)}}},t==null)return n;let R=n;return n={[Symbol.asyncIterator](){return this},next(){return R.next()},throw(c){return R.throw(c),t!=null&&(t(c),t=void 0),{done:!0}},return(){return R.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(c){return R.end(c),t!=null&&(t(c),t=void 0),n},get readableLength(){return R.readableLength},onEmpty:c=>R.onEmpty(c)},n}var he=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},ce=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},xe=s=>globalThis.DOMException===void 0?new ce(s):new DOMException(s),Ee=s=>{let e=s.reason===void 0?xe("This operation was aborted."):s.reason;return e instanceof Error?e:xe(e)};function de(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:i={setTimeout,clearTimeout}}=e,o,l,f=new Promise((p,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(Ee(h)),l=()=>{u(Ee(h))},h.addEventListener("abort",l,{once:!0})}if(t===Number.POSITIVE_INFINITY){s.then(p,u);return}let w=new he;o=i.setTimeout.call(void 0,()=>{if(r){try{p(r())}catch(h){u(h)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?p():n instanceof Error?u(n):(w.message=n??`Promise timed out after ${t} milliseconds`,u(w))},t),(async()=>{try{p(await s)}catch(h){u(h)}})()}).finally(()=>{f.clear(),l&&e.signal&&e.signal.removeEventListener("abort",l)});return f.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},f}var Ge=s=>{let e=s.addEventListener||s.on||s.addListener,t=s.removeEventListener||s.off||s.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(s),removeListener:t.bind(s)}};function Ye(s,e,t){let r,n=new Promise((i,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let l=[e].flat(),m=[],{addListener:f,removeListener:p}=Ge(s),u=(...h)=>{let z=t.multiArgs?h:h[0];t.filter&&!t.filter(z)||(m.push(z),t.count===m.length&&(r(),i(m)))},w=h=>{r(),o(h)};r=()=>{for(let h of l)p(h,u);for(let h of t.rejectionEvents)p(h,w)};for(let h of l)f(h,u);for(let h of t.rejectionEvents)f(h,w);t.signal&&t.signal.addEventListener("abort",()=>{w(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(m)});if(n.cancel=r,typeof t.timeout=="number"){let i=de(n,{milliseconds:t.timeout});return i.cancel=r,i}return n}function Se(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=Ye(s,e,t),n=r.then(i=>i[0]);return n.cancel=r.cancel,n}function ve(s,e){let t,r=function(){let n=function(){t=void 0,s()};clearTimeout(t),t=setTimeout(n,e)};return r.start=()=>{},r.stop=()=>{clearTimeout(t)},r}var X=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"};function $e(s){return s.reason}async function k(s,e,t){if(e==null)return s;let r=t?.translateError??$e;if(e.aborted)return s.catch(()=>{}),Promise.reject(r(e));let n;try{return await Promise.race([s,new Promise((i,o)=>{n=()=>{o(r(e))},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var qe=Math.pow(2,20)*4,J=class extends C{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;readBuffer;writeBuffer;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??qe,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new v,this.writeBuffer=new v,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this),this.addEventListener("drain",()=>{this.writeStatus==="paused"&&(this.writeStatus="writable"),this.processSendQueue()})}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=ye(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let r=i=>{e.end(i.error)};this.addEventListener("close",r);let n=()=>{e.end()};this.addEventListener("remoteCloseWrite",n);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",n)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new D(`Cannot write to a stream that is ${this.writeStatus}`);return this.writeStatus!=="writable"&&this.writeStatus!=="paused"?!0:(this.writeBuffer.append(e),this.writeStatus==="writable"?this.processSendQueue():!1)}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new q(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new D("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new D("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new D(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new G;this.dispatchEvent(new K(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new W))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writeBuffer.byteLength===0)return!0;if(this.writeStatus==="paused")return this.checkWriteBufferLength(),!1;let e=!0;for(;this.writeBuffer.byteLength>0;){let t=this.writeBuffer.sublist(0,Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength)),r=this.sendData(t);if(e=r.canSendMore,this.writeBuffer.consume(r.sentBytes),!e){this.log.trace("pausing sending because underlying stream is full"),this.writeStatus="paused",this.checkWriteBufferLength();break}}return this.writeBuffer.byteLength===0&&(this.log.trace("write queue became idle"),this.safeDispatchEvent("idle")),e}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new $(e))}finally{this.remoteWriteStatus==="closed"&&(this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new O(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new O(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}};function Ie(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var Z=class extends C{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let r=o=>{try{this.onData(o.data)}catch(l){this.abort(l),this.maConn.abort(l)}};this.maConn.addEventListener("message",r);let n=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(o=>{o.safeDispatchEvent("drain")})};this.maConn.addEventListener("drain",n);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){return this.maConn.send(e)}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await k(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new E;let t=this.onCreateStream({...this.streamOptions,...e});return Ie(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new X(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=r=>{let n=this.streams.findIndex(i=>i===e);n!==-1&&this.streams.splice(n,1),r.error!=null?r.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var ee=class extends J{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",this.writeBuffer.byteLength>0&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Se(this,"idle",{...e,rejectionEvents:["close"]})),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};function Le(s){let e=new globalThis.AbortController;function t(){e.abort();for(let i of s)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of s){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function r(){for(let i of s)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let n=e.signal;return n.clear=r,n}function Ae(s,e,t){let r,n,i=!1;function o(){let f={signal:n.signal};if(t?.timeout!=null){let p=Le([n.signal,AbortSignal.timeout(t.timeout)]);f.signal=p}i=!0,Promise.resolve().then(async()=>{await s(f)}).catch(()=>{}).finally(()=>{i=!1,!n.signal.aborted&&(r=setTimeout(o,e))})}let l=ve(o,t?.debounce??100),m=!1;return{setInterval:f=>{e!==f&&(e=f,r!=null&&(clearTimeout(r),r=setTimeout(o,e)))},setTimeout:f=>{t??={},t.timeout=f},run:()=>{i||(clearTimeout(r),l())},start:()=>{m||(m=!0,n=new AbortController,n.signal,t?.runImmediately===!0?queueMicrotask(()=>{o()}):r=setTimeout(o,e))},stop:()=>{clearTimeout(r),n?.abort(),m=!1}}}var d;(function(s){s[s.Data=0]="Data",s[s.WindowUpdate=1]="WindowUpdate",s[s.Ping=2]="Ping",s[s.GoAway=3]="GoAway"})(d||(d={}));var a;(function(s){s[s.SYN=1]="SYN",s[s.ACK=2]="ACK",s[s.FIN=4]="FIN",s[s.RST=8]="RST"})(a||(a={}));var fr=Object.values(a).filter(s=>typeof s!="string"),Te=0,g;(function(s){s[s.NormalTermination=0]="NormalTermination",s[s.ProtocolError=1]="ProtocolError",s[s.InternalError=2]="InternalError"})(g||(g={}));var I=12;var L=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function De(s){return s?.reason!==null}var x=class extends L{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,g.ProtocolError),this.name="InvalidFrameError"}},N=class extends L{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,g.ProtocolError),this.name="UnRequestedPingError"}},U=class extends L{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,g.ProtocolError),this.name="NotMatchingPingError"}};var te=class extends L{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,g.ProtocolError),this.name="StreamAlreadyExistsError"}},re=class extends L{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,g.ProtocolError),this.name="DecodeInvalidVersionError"}},se=class extends L{static name="BothClientsError";constructor(e="Both clients"){super(e,g.ProtocolError),this.name="BothClientsError"}},M=class extends L{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,g.ProtocolError),this.name="ReceiveWindowExceededError"}};var br=new Set([x.name,N.name,U.name,te.name,re.name,se.name,M.name]),_=256*1024,Re=16*1024*1024;var A={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:_,maxStreamWindowSize:Re,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{}};function Pe(s){if(s.keepAliveInterval!=null&&s.keepAliveInterval<=0)throw new y("keep-alive interval must be positive");if(s.maxInboundStreams!=null&&s.maxInboundStreams<0)throw new y("max inbound streams must be larger or equal 0");if(s.maxOutboundStreams!=null&&s.maxOutboundStreams<0)throw new y("max outbound streams must be larger or equal 0");if(s.initialStreamWindowSize!=null&&s.initialStreamWindowSize<_)throw new y("InitialStreamWindowSize must be larger or equal 256 kB");if(s.maxStreamWindowSize!=null&&s.initialStreamWindowSize!=null&&s.maxStreamWindowSize<s.initialStreamWindowSize)throw new y("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(s.maxStreamWindowSize!=null&&s.maxStreamWindowSize>2**32-1)throw new y("MaxStreamWindowSize must be less than equal MAX_UINT32");if(s.maxMessageSize!=null&&s.maxMessageSize<1024)throw new y("MaxMessageSize must be greater than a kilobyte")}function Ce(s){return s.header.type===d.Data&&s.data!==null}var We=2**24;function Ke(s){if(s[0]!==Te)throw new x("Invalid frame version");return{type:s[1],flag:(s[2]<<8)+s[3],streamID:s[4]*We+(s[5]<<16)+(s[6]<<8)+s[7],length:s[8]*We+(s[9]<<16)+(s[10]<<8)+s[11]}}var ne=class{buffer;constructor(){this.buffer=new v}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=I;if(this.buffer.byteLength<I)return;let t=Ke(this.buffer.subarray(0,I));if(t.type===d.Data){if(e+=t.length,this.buffer.byteLength<e)return;let r=this.buffer.sublist(I,e);return this.buffer.consume(e),{header:t,data:r}}return this.buffer.consume(e),{header:t}}};function fe(s){let e=new Uint8Array(I);return e[1]=s.type,e[2]=s.flag>>>8,e[3]=s.flag,e[4]=s.streamID>>>24,e[5]=s.streamID>>>16,e[6]=s.streamID>>>8,e[7]=s.streamID,e[8]=s.length>>>24,e[9]=s.length>>>16,e[10]=s.length>>>8,e[11]=s.length,e}var b;(function(s){s[s.Init=0]="Init",s[s.SYNSent=1]="SYNSent",s[s.SYNReceived=2]="SYNReceived",s[s.Established=3]="Established",s[s.Finished=4]="Finished",s[s.Paused=5]="Paused"})(b||(b={}));var ie=class extends ee{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??A.maxMessageSize)-I}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=_,this.recvWindow=e.initialStreamWindowSize??A.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??A.maxStreamWindowSize,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let t=()=>{this.state=b.Finished};this.addEventListener("close",t)}sendData(e){let t=e.byteLength,r=0,n=!0;for(;e.byteLength!==0;){if(this.sendWindowCapacity===0){n=!1,this.log?.trace("sent %d/%d bytes, wait for send window update, status %s",r,t,this.status);break}let i=Math.min(this.sendWindowCapacity,e.length),o=this.getSendFlags(),l=this.sendFrame({type:d.Data,flag:o,streamID:this.streamId,length:i},e.sublist(0,i));if(this.sendWindowCapacity-=i,r+=i,e.consume(i),!l){n=l,this.log("sent %d/%d bytes, wait for muxer to have more send capacity",r,t);break}}return{sentBytes:r,canSendMore:n}}async sendReset(){this.sendFrame({type:d.WindowUpdate,flag:a.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|a.FIN;this.sendFrame({type:d.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=b.Paused}sendResume(){this.state=b.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag);let t=this.sendWindowCapacity;this.sendWindowCapacity+=e.header.length,t===0&&e.header.length>0&&(this.log?.trace("window update of %d bytes allows more data to be sent",e.header.length),this.safeDispatchEvent("drain"))}handleData(e){if(!Ce(e))throw new x("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new M("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&a.ACK)===a.ACK&&this.state===b.SYNSent&&(this.state=b.Established),(e&a.FIN)===a.FIN&&this.onRemoteCloseWrite(),(e&a.RST)===a.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case b.Init:return this.state=b.SYNSent,a.SYN;case b.SYNReceived:return this.state=b.Established,a.ACK;default:return 0}}sendWindowUpdate(){let e=this.getSendFlags(),t=Date.now(),r=this.getRTT();if(e===0&&r>-1&&t-this.epochStart<r*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0||this.state===b.Paused)return;let n=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:d.WindowUpdate,flag:e,streamID:this.streamId,length:n})}};function Be(s){return{type:d[s.type],flags:[(s.flag&a.SYN)===a.SYN?"SYN":void 0,(s.flag&a.ACK)===a.ACK?"ACK":void 0,(s.flag&a.FIN)===a.FIN?"FIN":void 0,(s.flag&a.RST)===a.RST?"RST":void 0].filter(Boolean),streamID:s.streamID,length:s.length}}var Ne="/yamux/1.0.0",oe=class{protocol=Ne;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/yamux";[pe]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new me(e,{...this._init})}},me=class extends Z{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:Ne,name:"yamux"}),this.client=e.direction==="outbound",Pe(t),this.enableKeepAlive=t.enableKeepAlive??A.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??A.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??A.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??A.maxOutboundStreams,this.decoder=new ne,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=Ae(async r=>{try{await this.ping(r)}catch(n){this.log.error("ping error: %s",n)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new E("Muxer closed remotely");if(this.localGoAway!==void 0)throw new E("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Y("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,b.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new E("Muxer closed remotely");if(this.localGoAway!==void 0)throw new E("Muxer closed locally");if(this.activePing!=null)return k(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await k(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??g.NormalTermination;this.log.trace("muxer close reason=%s",g[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=g.InternalError;De(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,r){if(this.streams.find(i=>i.streamId===e)!=null)throw new y("Stream already exists with that id");let n=new ie({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:r,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${r}:${e}`),getRTT:this.getRTT.bind(this)});return n.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),n}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:r,length:n}=e.header;if(this.log.trace("received frame %o",Be(e.header)),t===0)switch(r){case d.Ping:{this.handlePing(e.header);return}case d.GoAway:{this.handleGoAway(n);return}default:throw new x("Invalid frame type")}else switch(e.header.type){case d.Data:case d.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new x("Invalid frame type")}}handlePing(e){if(e.flag===a.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,a.ACK);else if(e.flag===a.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new x("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new N("ping not requested");if(this.activePing.id!==e)throw new U("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",g[e]??"unknown"),this.remoteGoAway=e,e===g.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:r,type:n}=e.header;(r&a.SYN)===a.SYN&&this.incomingStream(t);let i=this.streams.find(o=>o.streamId===t);if(i===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(n){case d.WindowUpdate:{i.handleWindowUpdate(e);return}case d.Data:{i.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new y("Both endpoints are clients");if(this.streams.find(r=>r.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:d.WindowUpdate,flag:a.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:d.WindowUpdate,flag:a.RST,streamID:e,length:0});return}let t=this._newStream(e,b.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let r;if(e.type===d.Data){if(t===void 0)throw new x("Invalid frame");r=new v(fe(e),t)}else r=fe(e);return this.log.trace("sending frame %o",Be(e)),this.send(r)}sendPing(e,t=a.SYN){t===a.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:d.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=g.NormalTermination){this.log("sending GoAway reason=%s",g[e]),this.localGoAway=e,this.sendFrame({type:d.GoAway,flag:0,streamID:0,length:e})}};function He(s={}){return()=>new oe(s)}return ze(je);})();
|
|
3
|
+
return Libp2PYamux}));
|
|
4
|
+
//# sourceMappingURL=index.min.js.map
|