@libp2p/yamux 8.0.1 → 8.0.2

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 CHANGED
@@ -1,7 +1,9 @@
1
- # @chainsafe/libp2p-yamux
1
+ # @libp2p/yamux
2
2
 
3
- [![codecov](https://img.shields.io/codecov/c/github/ChainSafe/js-libp2p-yamux.svg?style=flat-square)](https://codecov.io/gh/ChainSafe/js-libp2p-yamux)
4
- [![CI](https://img.shields.io/github/actions/workflow/status/ChainSafe/js-libp2p-yamux/js-test-and-release.yml?branch=master\&style=flat-square)](https://github.com/ChainSafe/js-libp2p-yamux/actions/workflows/js-test-and-release.yml?query=branch%3Amaster)
3
+ [![libp2p.io](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](http://libp2p.io/)
4
+ [![Discuss](https://img.shields.io/discourse/https/discuss.libp2p.io/posts.svg?style=flat-square)](https://discuss.libp2p.io)
5
+ [![codecov](https://img.shields.io/codecov/c/github/libp2p/js-libp2p.svg?style=flat-square)](https://codecov.io/gh/libp2p/js-libp2p)
6
+ [![CI](https://img.shields.io/github/actions/workflow/status/libp2p/js-libp2p/main.yml?branch=main\&style=flat-square)](https://github.com/libp2p/js-libp2p/actions/workflows/main.yml?query=branch%3Amain)
5
7
 
6
8
  > Yamux stream multiplexer for libp2p
7
9
 
@@ -24,6 +26,8 @@ repo and examine the changes made.
24
26
 
25
27
  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
28
 
29
+ Formerly published as [`@chainsafe/libp2p-yamux`](https://www.npmjs.com/package/@chainsafe/libp2p-yamux).
30
+
27
31
  ## Example - Configure libp2p with Yamux
28
32
 
29
33
  ```typescript
@@ -40,87 +44,69 @@ const node = await createLibp2p({
40
44
 
41
45
  ## Example - Using the low-level API
42
46
 
43
- ```js
47
+ ```typescript
44
48
  import { yamux } from '@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()
49
+ import { multiaddrConnectionPair } from '@libp2p/utils'
50
+
51
+ // a pair of connected multiaddr connections - in a real application these
52
+ // would be the two ends of a network connection
53
+ const [outboundConnection, inboundConnection] = multiaddrConnectionPair()
54
+
55
+ const clientMuxer = yamux()().createStreamMuxer(outboundConnection)
56
+ const serverMuxer = yamux()().createStreamMuxer(inboundConnection)
57
+
58
+ // echo incoming data back on the server side
59
+ serverMuxer.addEventListener('stream', (evt) => {
60
+ const stream = evt.detail
61
+
62
+ stream.addEventListener('message', (msg) => {
63
+ stream.send(msg.data)
64
+ })
65
+ })
66
+
67
+ // open a stream from the client and send some data
68
+ const stream = await clientMuxer.createStream()
69
+
70
+ const received = new Promise<string>((resolve) => {
71
+ stream.addEventListener('message', (msg) => {
72
+ resolve(new TextDecoder().decode(msg.data.subarray()))
73
+ })
74
+ })
75
+
76
+ stream.send(new TextEncoder().encode('hello world'))
77
+
78
+ console.info(await received)
79
+ // -> hello world
80
+
81
+ await stream.close()
82
+ await clientMuxer.close()
83
+ await serverMuxer.close()
98
84
  ```
99
85
 
100
86
  # Install
101
87
 
102
88
  ```console
103
- $ npm i @chainsafe/libp2p-yamux
89
+ $ npm i @libp2p/yamux
104
90
  ```
105
91
 
106
92
  ## Browser `<script>` tag
107
93
 
108
- Loading this module through a script tag will make its exports available as `ChainsafeLibp2pYamux` in the global namespace.
94
+ Loading this module through a script tag will make its exports available as `Libp2pYamux` in the global namespace.
109
95
 
110
96
  ```html
111
- <script src="https://unpkg.com/@chainsafe/libp2p-yamux/dist/index.min.js"></script>
97
+ <script src="https://unpkg.com/@libp2p/yamux/dist/index.min.js"></script>
112
98
  ```
113
99
 
114
100
  # API Docs
115
101
 
116
- - <https://ChainSafe.github.io/js-libp2p-yamux>
102
+ - <https://libp2p.github.io/js-libp2p/modules/_libp2p_yamux.html>
117
103
 
118
104
  # License
119
105
 
120
106
  Licensed under either of
121
107
 
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>)
108
+ - Apache 2.0, ([LICENSE-APACHE](https://github.com/libp2p/js-libp2p/blob/main/packages/stream-multiplexer-yamux/LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
109
+ - MIT ([LICENSE-MIT](https://github.com/libp2p/js-libp2p/blob/main/packages/stream-multiplexer-yamux/LICENSE-MIT) / <http://opensource.org/licenses/MIT>)
124
110
 
125
111
  # Contribution
126
112
 
package/dist/index.min.js CHANGED
@@ -1,4 +1,4 @@
1
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 ue=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var ke=(s,e)=>{for(var t in e)ue(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&&ue(s,n,{get:()=>e[n],enumerable:!(r=Ue(e,n))||r.enumerable});return s};var ze=s=>_e(ue({},"__esModule",{value:!0}),s);var He={};ke(He,{GoAwayCode:()=>g,yamux:()=>Ke});var y=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var v=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},q=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var T=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},U=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var G=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}};var Y=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},R=class extends Event{error;local;constructor(e,t,r){super("close",r),this.error=t,this.local=e}},$=class extends R{constructor(e,t){super(!0,e,t)}},j=class extends R{constructor(e,t){super(!1,e,t)}};var W=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 we=Symbol.for("@libp2p/service-capabilities"),tt=Symbol.for("@libp2p/service-dependencies");function be(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 L(s=0){return new Uint8Array(s)}function O(s=0){return new Uint8Array(s)}function le(s,e){e==null&&(e=s.reduce((n,i)=>n+i.length,0));let t=O(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var xe=Symbol.for("@achingbrain/uint8arraylist");function ye(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 K(s){return!!s?.[xe]}var E=class s{bufs;length;[xe]=!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(K(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(K(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=ye(this.bufs,e);return t.buf[t.index]}set(e,t){let r=ye(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(K(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 le(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:le(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 a=this.bufs[i],o=n,d=o+a.byteLength;if(n=d,e>=d)continue;let m=e>=o&&e<d,p=t>o&&t<=d;if(m&&p){if(e===o&&t===d){r.push(a);break}let l=e-o;r.push(a.subarray(l,l+(t-e)));break}if(m){if(e===0){r.push(a);continue}r.push(a.subarray(e-o));continue}if(p){if(t===d){r.push(a);break}r.push(a.subarray(0,t-o));break}r.push(a)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!K(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,a=new Int32Array(i);for(let l=0;l<i;l++)a[l]=-1;for(let l=0;l<n;l++)a[r[l]]=l;let o=a,d=this.byteLength-r.byteLength,m=r.byteLength-1,p;for(let l=t;l<=d;l+=p){p=0;for(let w=m;w>=0;w--){let h=this.get(l+w);if(r[w]!==h){p=Math.max(1,w-o[h]);break}}if(p===0)return l}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=O(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=L(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=L(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=L(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=O(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=L(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=L(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=L(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=L(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=L(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(!be(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 H(){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}},P=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 he=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ee(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 P,n,i,a,o=H(),d=async()=>{try{return r.isEmpty()?a?{done:!0}:await new Promise((c,A)=>{i=V=>{i=null,r.push(V);try{c(s(r))}catch(B){A(B)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{o.resolve(),o=H()})}},m=c=>i!=null?i(c):(r.push(c),n),p=c=>(r=new P,i!=null?i({error:c}):(r.push({error:c}),n)),l=c=>{if(a)return n;if(e?.objectMode!==!0&&c?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return m({done:!1,value:c})},w=c=>a?n:(a=!0,c!=null?p(c):m({done:!0})),h=()=>(r=new P,w(),{done:!0}),z=c=>(w(c),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:d,return:h,throw:z,push:l,end:w,get readableLength(){return r.size},onEmpty:async c=>{let A=c?.signal;if(A?.throwIfAborted(),r.isEmpty())return;let V,B;A!=null&&(V=new Promise((Qe,Me)=>{B=()=>{Me(new he)},A.addEventListener("abort",B)}));try{await Promise.race([o.promise,V])}finally{B!=null&&A!=null&&A?.removeEventListener("abort",B)}}},t==null)return n;let D=n;return n={[Symbol.asyncIterator](){return this},next(){return D.next()},throw(c){return D.throw(c),t!=null&&(t(c),t=void 0),{done:!0}},return(){return D.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(c){return D.end(c),t!=null&&(t(c),t=void 0),n},get readableLength(){return D.readableLength},onEmpty:c=>D.onEmpty(c)},n}var ce=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},de=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Se=s=>globalThis.DOMException===void 0?new de(s):new DOMException(s),ve=s=>{let e=s.reason===void 0?Se("This operation was aborted."):s.reason;return e instanceof Error?e:Se(e)};function fe(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:i={setTimeout,clearTimeout}}=e,a,o,m=new Promise((p,l)=>{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&&l(ve(h)),o=()=>{l(ve(h))},h.addEventListener("abort",o,{once:!0})}if(t===Number.POSITIVE_INFINITY){s.then(p,l);return}let w=new ce;a=i.setTimeout.call(void 0,()=>{if(r){try{p(r())}catch(h){l(h)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?p():n instanceof Error?l(n):(w.message=n??`Promise timed out after ${t} milliseconds`,l(w))},t),(async()=>{try{p(await s)}catch(h){l(h)}})()}).finally(()=>{m.clear(),o&&e.signal&&e.signal.removeEventListener("abort",o)});return m.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},m}var qe=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 Ge(s,e,t){let r,n=new Promise((i,a)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!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 o=[e].flat(),d=[],{addListener:m,removeListener:p}=qe(s),l=async(...h)=>{let z=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(z))return}catch(D){r(),a(D);return}d.push(z),t.count===d.length&&(r(),i(d))},w=(...h)=>{r(),a(t.rejectionMultiArgs?h:h[0])};r=()=>{for(let h of o)p(h,l);for(let h of t.rejectionEvents)o.includes(h)||p(h,w)};for(let h of o)m(h,l);for(let h of t.rejectionEvents)o.includes(h)||m(h,w);t.signal&&t.signal.addEventListener("abort",()=>{w(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(d)});if(n.cancel=r,typeof t.timeout=="number"){let i=fe(n,{milliseconds:t.timeout});return i.cancel=()=>{r(),i.clear()},i}return n}function me(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=Ge(s,e,t),n=r.then(i=>i[0]);return n.cancel=r.cancel,n}function Le(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 Ye(s){return s.reason}async function F(s,e,t){if(e==null)return s;let r=t?.translateError??Ye;if(e.aborted)return s.catch(()=>{}),Promise.reject(r(e));let n;try{return await Promise.race([s,new Promise((i,a)=>{n=()=>{a(r(e))},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var $e=Math.pow(2,20)*4,J=class extends W{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??$e,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new E,this.writeBuffer=new E,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue())};this.addEventListener("drain",t)}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Ee(),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 T(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}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 $(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new T("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 T("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 T(`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 q;this.dispatchEvent(new j(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),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 R))}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.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,r=0;for(;this.writeBuffer.byteLength>0;){let n=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(n===0){e=!1;break}let i=this.writeBuffer.sublist(0,n),a=new E(i);this.writeBuffer.consume(i.byteLength);let o=this.sendData(i);if(e=o.canSendMore,r+=o.sentBytes,o.sentBytes!==a.byteLength&&(a.consume(o.sentBytes),this.writeBuffer.prepend(a)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",r,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}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 Y(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new U(`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 U(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};function Ie(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var Z=class extends W{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=a=>{try{this.onData(a.data)}catch(o){this.abort(o),this.maConn.abort(o)}};this.maConn.addEventListener("message",r);let n=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(a=>{a.onMuxerDrain()})};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){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(r=>{r.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await F(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 v;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.sendingData||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 me(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await me(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),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 De(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 a(){let m={signal:n.signal};if(t?.timeout!=null){let p=De([n.signal,AbortSignal.timeout(t.timeout)]);m.signal=p}i=!0,Promise.resolve().then(async()=>{await s(m)}).catch(()=>{}).finally(()=>{i=!1,!n.signal.aborted&&(r=setTimeout(a,e))})}let o=Le(a,t?.debounce??100),d=!1;return{setInterval:m=>{e!==m&&(e=m,r!=null&&(clearTimeout(r),r=setTimeout(a,e)))},setTimeout:m=>{t??={},t.timeout=m},run:()=>{i||(clearTimeout(r),o())},start:()=>{d||(d=!0,n=new AbortController,n.signal,t?.runImmediately===!0?queueMicrotask(()=>{a()}):r=setTimeout(a,e))},stop:()=>{clearTimeout(r),n?.abort(),d=!1}}}var f;(function(s){s[s.Data=0]="Data",s[s.WindowUpdate=1]="WindowUpdate",s[s.Ping=2]="Ping",s[s.GoAway=3]="GoAway"})(f||(f={}));var u;(function(s){s[s.SYN=1]="SYN",s[s.ACK=2]="ACK",s[s.FIN=4]="FIN",s[s.RST=8]="RST"})(u||(u={}));var dr=Object.values(u).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 S=12;var I=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function Be(s){return s?.reason!==null}var x=class extends I{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,g.ProtocolError),this.name="InvalidFrameError"}},N=class extends I{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,g.ProtocolError),this.name="UnRequestedPingError"}},C=class extends I{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,g.ProtocolError),this.name="NotMatchingPingError"}};var te=class extends I{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,g.ProtocolError),this.name="StreamAlreadyExistsError"}},re=class extends I{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,g.ProtocolError),this.name="DecodeInvalidVersionError"}},se=class extends I{static name="BothClientsError";constructor(e="Both clients"){super(e,g.ProtocolError),this.name="BothClientsError"}},M=class extends I{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,g.ProtocolError),this.name="ReceiveWindowExceededError"}};var wr=new Set([x.name,N.name,C.name,te.name,re.name,se.name,M.name]),k=256*1024,ne=16*1024*1024;var _={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:k,maxStreamWindowSize:ne,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function Re(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.maxMessageSize!=null&&s.maxMessageSize<1024)throw new y("MaxMessageSize must be greater than a kilobyte");if(s.streamOptions?.initialStreamWindowSize!=null&&s.streamOptions?.initialStreamWindowSize<k)throw new y("InitialStreamWindowSize must be larger or equal 256 kB");if(s.streamOptions?.maxStreamWindowSize!=null&&s.streamOptions?.initialStreamWindowSize!=null&&s.streamOptions?.maxStreamWindowSize<s.streamOptions?.initialStreamWindowSize)throw new y("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(s.streamOptions?.maxStreamWindowSize!=null&&s.streamOptions?.maxStreamWindowSize>2**32-1)throw new y("MaxStreamWindowSize must be less than equal MAX_UINT32")}function Pe(s){return s.header.type===f.Data&&s.data!==null}var We=2**24;function je(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 ie=class{buffer;constructor(){this.buffer=new E}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=S;if(this.buffer.byteLength<S)return;let t=je(this.buffer.subarray(0,S));if(t.type===f.Data){if(e+=t.length,this.buffer.byteLength<e)return;let r=this.buffer.sublist(S,e);return this.buffer.consume(e),{header:t,data:r}}return this.buffer.consume(e),{header:t}}};function pe(s){let e=new Uint8Array(S);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 ae=class extends ee{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??k;super({...e,maxMessageSize:t-S}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??ne,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let r=()=>{this.state=b.Finished};this.addEventListener("close",r)}sendData(e){let t=e.byteLength,r=0,n=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){n=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",r,t);break}let i=Math.min(this.sendWindowCapacity,e.byteLength),a=this.getSendFlags(),o=e.sublist(0,i);e.consume(i);let d=this.sendFrame({type:f.Data,flag:a,streamID:this.streamId,length:i},o);if(this.sendWindowCapacity-=i,r+=i,!d){n=d,this.log.trace("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:f.WindowUpdate,flag:u.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|u.FIN;this.sendFrame({type:f.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),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-S,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!Pe(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&u.ACK)===u.ACK&&this.state===b.SYNSent&&(this.state=b.Established),(e&u.FIN)===u.FIN&&this.onRemoteCloseWrite(),(e&u.RST)===u.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case b.Init:return this.state=b.SYNSent,u.SYN;case b.SYNReceived:return this.state=b.Established,u.ACK;default:return 0}}sendWindowUpdate(){if(this.state===b.Paused){this.epochStart=Date.now();return}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)return;let n=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:f.WindowUpdate,flag:e,streamID:this.streamId,length:n})}};function Ne(s){return{type:f[s.type],flags:[(s.flag&u.SYN)===u.SYN?"SYN":void 0,(s.flag&u.ACK)===u.ACK?"ACK":void 0,(s.flag&u.FIN)===u.FIN?"FIN":void 0,(s.flag&u.RST)===u.RST?"RST":void 0].filter(Boolean),streamID:s.streamID,length:s.length}}var Ce="/yamux/1.0.0",oe=class{protocol=Ce;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/yamux";[we]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new ge(e,{...this._init})}},ge=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:Ce,name:"yamux"}),this.client=e.direction==="outbound",Re(t),this.enableKeepAlive=t.enableKeepAlive??_.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??_.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??_.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??_.maxOutboundStreams,this.decoder=new ie,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 v("Muxer closed remotely");if(this.localGoAway!==void 0)throw new v("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new G("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 v("Muxer closed remotely");if(this.localGoAway!==void 0)throw new v("Muxer closed locally");if(this.activePing!=null)return F(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 F(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;Be(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 ae({...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",Ne(e.header)),t===0)switch(r){case f.Ping:{this.handlePing(e.header);return}case f.GoAway:{this.handleGoAway(n);return}default:throw new x("Invalid frame type")}else switch(e.header.type){case f.Data:case f.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new x("Invalid frame type")}}handlePing(e){if(e.flag===u.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,u.ACK);else if(e.flag===u.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 C("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&u.SYN)===u.SYN&&this.incomingStream(t);let i=this.streams.find(a=>a.streamId===t);if(i===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(n){case f.WindowUpdate:{i.handleWindowUpdate(e);return}case f.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:f.WindowUpdate,flag:u.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:f.WindowUpdate,flag:u.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===f.Data){if(t==null)throw new x("Invalid frame");r=new E(pe(e),t)}else r=pe(e);return this.log.trace("sending frame %o",Ne(e)),this.send(r)}sendPing(e,t=u.SYN){t===u.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:f.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:f.GoAway,flag:0,streamID:0,length:e})}};function Ke(s={}){return()=>new oe(s)}return ze(He);})();
2
+ "use strict";var Libp2PYamux=(()=>{var le=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var ze=(r,e)=>{for(var t in e)le(r,t,{get:e[t],enumerable:!0})},qe=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Fe(e))!_e.call(r,n)&&n!==t&&le(r,n,{get:()=>e[n],enumerable:!(s=ke(e,n))||s.enumerable});return r};var Ve=r=>qe(le({},"__esModule",{value:!0}),r);var tt={};ze(tt,{GoAwayCode:()=>w,yamux:()=>et});var y=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var S=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},V=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var A=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},k=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var G=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}};var Y=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},W=class extends Event{error;local;constructor(e,t,s){super("close",s),this.error=t,this.local=e}},j=class extends W{constructor(e,t){super(!0,e,t)}},$=class extends W{constructor(e,t){super(!1,e,t)}};function Ge(r){return typeof r?.handleEvent=="function"}function Ye(r){return r===!0||r===!1}function je(r){return Ye(r)?r:r?.capture??!1}function he(r){let e={capture:je(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function be(r,e){return he(r).capture===he(e).capture}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,s){let n=he(s);if(n?.signal?.aborted===!0)return;let i=c=>{n.once&&this.removeEventListener(e,t,n),Ge(t)?t.handleEvent(c):t(c)},a=this.#e.get(e);if(a==null&&(a=[],this.#e.set(e,a)),a.some(c=>c.callback!==t?!1:be(c.options,n)))return;super.addEventListener(e,i,n);let u=()=>{this.removeEventListener(e,t,n)};n.signal?.addEventListener("abort",u),a.push({callback:t,wrapper:i,options:n,onAbort:u})}removeEventListener(e,t,s){let n=this.#e.get(e);if(n==null){super.removeEventListener(e,t??null,s);return}this.#e.set(e,n.filter(i=>i.callback===t&&be(i.options,s)?(super.removeEventListener(e,i.wrapper,s),i.options?.signal?.removeEventListener("abort",i.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ye=Symbol.for("@libp2p/service-capabilities");function L(r=0){return new Uint8Array(r)}function F(r=0){return new Uint8Array(r)}function $e(r){return r?.buffer instanceof ArrayBuffer}function xe(r){if($e(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function ce(r,e){e==null&&(e=r.reduce((n,i)=>n+i.length,0));let t=F(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return xe(t)}function Ee(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Se=Symbol.for("@achingbrain/uint8arraylist");function ve(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let s of r){let n=t+s.byteLength;if(e<n)return{buf:s,index:e-t};t=n}throw new RangeError("index is out of bounds")}function K(r){return!!r?.[Se]}var E=class r{bufs;length;[Se]=!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 s of e)if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.push(s);else if(K(s)){t+=s.byteLength;for(let n of s.bufs)this.bufs.push(n)}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 s of e.reverse())if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.unshift(s);else if(K(s))t+=s.byteLength,this.bufs.unshift(...s.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=ve(this.bufs,e);return t.buf[t.index]}set(e,t){let s=ve(this.bufs,e);s.buf[s.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let s=0;s<e.length;s++)this.set(t+s,e[s]);else if(K(e))for(let s=0;s<e.length;s++)this.set(t+s,e.get(s));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:s,length:n}=this._subList(e,t);return ce(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:ce(s,n)}sublist(e,t){let{bufs:s,length:n}=this._subList(e,t),i=new r;return i.length=n,i.bufs=s,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 s=[],n=0;for(let i=0;i<this.bufs.length;i++){let a=this.bufs[i],o=n,u=o+a.byteLength;if(n=u,e>=u)continue;let c=e>=o&&e<u,d=t>o&&t<=u;if(c&&d){if(e===o&&t===u){s.push(a);break}let h=e-o;s.push(a.subarray(h,h+(t-e)));break}if(c){if(e===0){s.push(a);continue}s.push(a.subarray(e-o));continue}if(d){if(t===u){s.push(a);break}s.push(a.subarray(0,t-o));break}s.push(a)}return{bufs:s,length:t-e}}indexOf(e,t=0){if(!K(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let s=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=s.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,a=new Int32Array(i);for(let h=0;h<i;h++)a[h]=-1;for(let h=0;h<n;h++)a[s[h]]=h;let o=a,u=this.byteLength-s.byteLength,c=s.byteLength-1,d;for(let h=t;h<=u;h+=d){d=0;for(let g=c;g>=0;g--){let m=this.get(h+g);if(s[g]!==m){d=Math.max(1,g-o[m]);break}}if(d===0)return h}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 s=F(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt8(0,t),this.write(s,e)}getInt16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt16(0,t)}setInt16(e,t,s){let n=L(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,s),this.write(n,e)}getInt32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt32(0,t)}setInt32(e,t,s){let n=L(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,s),this.write(n,e)}getBigInt64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigInt64(0,t)}setBigInt64(e,t,s){let n=L(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,s),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 s=F(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint8(0,t),this.write(s,e)}getUint16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint16(0,t)}setUint16(e,t,s){let n=L(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,s),this.write(n,e)}getUint32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint32(0,t)}setUint32(e,t,s){let n=L(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,s),this.write(n,e)}getBigUint64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0,t)}setBigUint64(e,t,s){let n=L(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,s),this.write(n,e)}getFloat32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat32(0,t)}setFloat32(e,t,s){let n=L(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,s),this.write(n,e)}getFloat64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat64(0,t)}setFloat64(e,t,s){let n=L(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,s),this.write(n,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ee(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let s=new r;return s.bufs=e,t==null&&(t=e.reduce((n,i)=>n+i.byteLength,0)),s.length=t,s}};function H(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}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}},N=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 de=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Le(r={}){return Ke(t=>{let s=t.shift();if(s==null)return{done:!0};if(s.error!=null)throw s.error;return{done:s.done===!0,value:s.value}},r)}function Ke(r,e){e=e??{};let t=e.onEnd,s=new N,n,i,a,o=H(),u=async()=>{try{return s.isEmpty()?a?{done:!0}:await new Promise((f,T)=>{i=q=>{i=null,s.push(q);try{f(r(s))}catch(R){T(R)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{o.resolve(),o=H()})}},c=f=>i!=null?i(f):(s.push(f),n),d=f=>(s=new N,i!=null?i({error:f}):(s.push({error:f}),n)),h=f=>{if(a)return n;if(e?.objectMode!==!0&&f?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:f})},g=f=>a?n:(a=!0,f!=null?d(f):c({done:!0})),m=()=>(s=new N,g(),{done:!0}),P=f=>(g(f),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:u,return:m,throw:P,push:h,end:g,get readableLength(){return s.size},onEmpty:async f=>{let T=f?.signal;if(T?.throwIfAborted(),s.isEmpty())return;let q,R;T!=null&&(q=new Promise((rt,Oe)=>{R=()=>{Oe(new de)},T.addEventListener("abort",R)}));try{await Promise.race([o.promise,q])}finally{R!=null&&T!=null&&T?.removeEventListener("abort",R)}}},t==null)return n;let D=n;return n={[Symbol.asyncIterator](){return this},next(){return D.next()},throw(f){return D.throw(f),t!=null&&(t(f),t=void 0),{done:!0}},return(){return D.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(f){return D.end(f),t!=null&&(t(f),t=void 0),n},get readableLength(){return D.readableLength},onEmpty:f=>D.onEmpty(f)},n}var fe=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Ie=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function me(r,e){let{milliseconds:t,fallback:s,message:n,customTimers:i={setTimeout,clearTimeout},signal:a}=e,o,u,d=new Promise((h,g)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(a?.aborted){g(Ie(a));return}if(a&&(u=()=>{g(Ie(a))},a.addEventListener("abort",u,{once:!0})),r.then(h,g),t===Number.POSITIVE_INFINITY)return;let m=new fe;o=i.setTimeout.call(void 0,()=>{if(s){try{h(s())}catch(P){g(P)}return}typeof r.cancel=="function"&&r.cancel(),n===!1?h():n instanceof Error?g(n):(m.message=n??`Promise timed out after ${t} milliseconds`,g(m))},t)}).finally(()=>{d.clear(),u&&a&&a.removeEventListener("abort",u)});return d.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},d}var He=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Qe(r,e,t){let s,n=new Promise((i,a)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!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 o=[e].flat(),u=[],{addListener:c,removeListener:d}=He(r),h=async(...m)=>{let P=t.multiArgs?m:m[0];if(t.filter)try{if(!await t.filter(P))return}catch(D){s(),a(D);return}u.push(P),t.count===u.length&&(s(),i(u))},g=(...m)=>{s(),a(t.rejectionMultiArgs?m:m[0])};s=()=>{for(let m of o)d(m,h);for(let m of t.rejectionEvents)o.includes(m)||d(m,g)};for(let m of o)c(m,h);for(let m of t.rejectionEvents)o.includes(m)||c(m,g);t.signal&&t.signal.addEventListener("abort",()=>{g(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(u)});if(n.cancel=s,typeof t.timeout=="number"){let i=me(n,{milliseconds:t.timeout});return i.cancel=()=>{s(),i.clear()},i}return n}function pe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let s=Qe(r,e,t),n=s.then(i=>i[0]);return n.cancel=s.cancel,n}function De(r,e){let t,s=function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)};return s.start=()=>{},s.stop=()=>{clearTimeout(t)},s}var X=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},J=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Xe(r){return r.reason}function B(r,e,t){if(e==null||r==null)return r;let s=t?.translateError??Xe;if(e.aborted)return r.catch(()=>{}),Promise.reject(s(e));let n;return Promise.race([r,new Promise((i,a)=>{n=()=>{a(s(e))},e.addEventListener("abort",n)})]).finally(()=>{n!=null&&e.removeEventListener("abort",n)})}var Je=Math.pow(2,20)*4,Z=class extends C{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Je,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new E,this.writeBuffer=new E,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(n){this.log.error("processSendQueue threw - %e",n)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let s=n=>{this.onDrainPromise?.reject(n.error??new J)};this.addEventListener("close",s)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),B(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Le(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let s=i=>{e.end(i.error)};this.addEventListener("close",s);let n=()=>{e.end()};this.addEventListener("remoteCloseWrite",n);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",s),this.removeEventListener("remoteCloseWrite",n)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new A(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}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(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(t){this.log.error("failed to send reset to remote - %e",t)}this.dispatchEvent(new j(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new A("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 A("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 A(`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)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new A(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(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",this.maybeDispatchEnd()),this.dispatchEvent(new $(new V))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),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.maybeDispatchEnd(),this.dispatchEvent(new W))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),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.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,s=0;for(;this.writeBuffer.byteLength>0;){let n=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(n===0){e=!1;break}let i=this.writeBuffer.sublist(0,n),a=new E(i);this.writeBuffer.consume(i.byteLength);let o;try{o=this.sendData(i)}catch(u){throw this.writeBuffer.prepend(a),this.abort(u),u}if(e=o.canSendMore,s+=o.sentBytes,o.sentBytes!==a.byteLength&&(a.consume(o.sentBytes),this.writeBuffer.prepend(a)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",s,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}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 Y(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new k(`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 k(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};function Ae(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ee=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 s=a=>{try{this.onData(a.data)}catch(o){this.abort(o),this.maConn.abort(o)}};this.maConn.addEventListener("message",s);let n=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(a=>{a.onMuxerDrain()})};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){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await B(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 S;let t=this.onCreateStream({...this.streamOptions,...e});return Ae(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=s=>{let n=this.streams.findIndex(i=>i===e);n!==-1&&this.streams.splice(n,1),s.error!=null?s.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 te=class extends Z{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.sendingData||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 pe(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await pe(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),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.maybeDispatchEnd(),this.log("closed readable end gracefully"))}};function Te(r){let e=new globalThis.AbortController;function t(){let i=r.filter(a=>a?.aborted===!0).map(a=>a?.reason).pop();e.abort(i);for(let a of r)a?.removeEventListener!=null&&a.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function s(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let n=e.signal;return n.clear=s,n}function Be(r,e,t){let s,n,i=!1;function a(){let c={signal:n.signal},d;t?.timeout!=null&&(d=Te([n.signal,AbortSignal.timeout(t.timeout)]),c.signal=d),i=!0,Promise.resolve().then(async()=>{await r(c)}).catch(()=>{}).finally(()=>{d!=null&&(d.aborted?d.clear():d.addEventListener("abort",()=>{d.clear()},{once:!0})),i=!1,!n.signal.aborted&&(s=setTimeout(a,e))})}let o=De(a,t?.debounce??100),u=!1;return{setInterval:c=>{e!==c&&(e=c,s!=null&&(clearTimeout(s),s=setTimeout(a,e)))},setTimeout:c=>{t??={},t.timeout=c},run:()=>{i||(clearTimeout(s),o())},start:()=>{u||(u=!0,n=new AbortController,n.signal,t?.runImmediately===!0?queueMicrotask(()=>{a()}):s=setTimeout(a,e))},stop:()=>{clearTimeout(s),n?.abort(),u=!1}}}var p;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(p||(p={}));var l;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(l||(l={}));var br=Object.values(l).filter(r=>typeof r!="string"),Pe=0,w;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(w||(w={}));var v=12;var I=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function Re(r){return r?.reason!==null}var x=class extends I{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,w.ProtocolError),this.name="InvalidFrameError"}},M=class extends I{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,w.ProtocolError),this.name="UnRequestedPingError"}},U=class extends I{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,w.ProtocolError),this.name="NotMatchingPingError"}};var re=class extends I{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,w.ProtocolError),this.name="StreamAlreadyExistsError"}},se=class extends I{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,w.ProtocolError),this.name="DecodeInvalidVersionError"}},ne=class extends I{static name="BothClientsError";constructor(e="Both clients"){super(e,w.ProtocolError),this.name="BothClientsError"}},O=class extends I{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,w.ProtocolError),this.name="ReceiveWindowExceededError"}};var Sr=new Set([x.name,M.name,U.name,re.name,se.name,ne.name,O.name]),_=256*1024,ie=16*1024*1024;var z={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:_,maxStreamWindowSize:ie,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function We(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new y("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new y("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new y("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new y("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<_)throw new y("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new y("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new y("MaxStreamWindowSize must be less than equal MAX_UINT32")}function Ne(r){return r.header.type===p.Data&&r.data!==null}var Ce=2**24;function Ze(r){if(r[0]!==Pe)throw new x("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*Ce+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*Ce+(r[9]<<16)+(r[10]<<8)+r[11]}}var ae=class{buffer;constructor(){this.buffer=new E}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=v;if(this.buffer.byteLength<v)return;let t=Ze(this.buffer.subarray(0,v));if(t.type===p.Data){if(e+=t.length,this.buffer.byteLength<e)return;let s=this.buffer.sublist(v,e);return this.buffer.consume(e),{header:t,data:s}}return this.buffer.consume(e),{header:t}}};function ge(r){let e=new Uint8Array(v);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var b;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(b||(b={}));var oe=class extends te{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??_;super({...e,maxMessageSize:t-v}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??ie,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let s=()=>{this.state=b.Finished};this.addEventListener("close",s)}sendData(e){let t=e.byteLength,s=0,n=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){n=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",s,t);break}let i=Math.min(this.sendWindowCapacity,e.byteLength),a=this.getSendFlags(),o=e.sublist(0,i);e.consume(i);let u=this.sendFrame({type:p.Data,flag:a,streamID:this.streamId,length:i},o);if(this.sendWindowCapacity-=i,s+=i,!u){n=u,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",s,t);break}}return{sentBytes:s,canSendMore:n}}sendReset(){this.sendFrame({type:p.WindowUpdate,flag:l.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|l.FIN;this.sendFrame({type:p.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),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-v,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!Ne(e))throw new x("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new O("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&l.ACK)===l.ACK&&this.state===b.SYNSent&&(this.state=b.Established),(e&l.FIN)===l.FIN&&this.onRemoteCloseWrite(),(e&l.RST)===l.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case b.Init:return this.state=b.SYNSent,l.SYN;case b.SYNReceived:return this.state=b.Established,l.ACK;default:return 0}}sendWindowUpdate(){if(this.state===b.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),s=this.getRTT();if(e===0&&s>-1&&t-this.epochStart<=s*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let n=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:p.WindowUpdate,flag:e,streamID:this.streamId,length:n})}};function Me(r){return{type:p[r.type],flags:[(r.flag&l.SYN)===l.SYN?"SYN":void 0,(r.flag&l.ACK)===l.ACK?"ACK":void 0,(r.flag&l.FIN)===l.FIN?"FIN":void 0,(r.flag&l.RST)===l.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var Ue="/yamux/1.0.0",ue=class{protocol=Ue;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/yamux";[ye]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new we(e,{...this._init})}},we=class extends ee{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:Ue,name:"yamux"}),this.client=e.direction==="outbound",We(t),this.enableKeepAlive=t.enableKeepAlive??z.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??z.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??z.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??z.maxOutboundStreams,this.decoder=new ae,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=Be(async s=>{try{await this.ping(s)}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 S("Muxer closed remotely");if(this.localGoAway!==void 0)throw new S("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new G("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 S("Muxer closed remotely");if(this.localGoAway!==void 0)throw new S("Muxer closed locally");if(this.activePing!=null)return B(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 B(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??w.NormalTermination;this.log.trace("muxer close reason=%s",w[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=w.InternalError;Re(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,s){if(this.streams.find(i=>i.streamId===e)!=null)throw new y("Stream already exists with that id");let n=new oe({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:s,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${s}:${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:s,length:n}=e.header;if(this.log.trace("received frame %o",Me(e.header)),t===0)switch(s){case p.Ping:{this.handlePing(e.header);return}case p.GoAway:{this.handleGoAway(n);return}default:throw new x("Invalid frame type")}else switch(e.header.type){case p.Data:case p.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new x("Invalid frame type")}}handlePing(e){if(e.flag===l.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,l.ACK);else if(e.flag===l.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 M("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",w[e]??"unknown"),this.remoteGoAway=e,e===w.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:s,type:n}=e.header;(s&l.SYN)===l.SYN&&this.incomingStream(t);let i=this.streams.find(a=>a.streamId===t);if(i===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(n){case p.WindowUpdate:{i.handleWindowUpdate(e);return}case p.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(s=>s.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:p.WindowUpdate,flag:l.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:p.WindowUpdate,flag:l.RST,streamID:e,length:0});return}let t=this._newStream(e,b.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let s;if(e.type===p.Data){if(t==null)throw new x("Invalid frame");s=new E(ge(e),t)}else s=ge(e);return this.log.trace("sending frame %o",Me(e)),this.send(s)}sendPing(e,t=l.SYN){t===l.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:p.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=w.NormalTermination){this.log("sending GoAway reason=%s",w[e]),this.localGoAway=e,this.sendFrame({type:p.GoAway,flag:0,streamID:0,length:e})}};function et(r={}){return()=>new ue(r)}return Ve(tt);})();
3
3
  return Libp2PYamux}));
4
4
  //# sourceMappingURL=index.min.js.map