@browsercore/quic 0.1.3 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +122 -0
  2. package/dist/connection.d.ts +33 -13
  3. package/dist/connection.d.ts.map +1 -1
  4. package/dist/connection.js +160 -77
  5. package/dist/connection.js.map +1 -1
  6. package/dist/errors.d.ts.map +1 -1
  7. package/dist/errors.js.map +1 -1
  8. package/dist/frame/frame.d.ts +1 -2
  9. package/dist/frame/frame.d.ts.map +1 -1
  10. package/dist/frame/frame.js +26 -8
  11. package/dist/frame/frame.js.map +1 -1
  12. package/dist/frame/varint.d.ts +10 -0
  13. package/dist/frame/varint.d.ts.map +1 -1
  14. package/dist/frame/varint.js +41 -14
  15. package/dist/frame/varint.js.map +1 -1
  16. package/dist/index.d.ts +5 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +3 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/packet/packet.d.ts +1 -2
  21. package/dist/packet/packet.d.ts.map +1 -1
  22. package/dist/packet/packet.js +19 -4
  23. package/dist/packet/packet.js.map +1 -1
  24. package/dist/stream/stream.d.ts +7 -1
  25. package/dist/stream/stream.d.ts.map +1 -1
  26. package/dist/stream/stream.js +127 -84
  27. package/dist/stream/stream.js.map +1 -1
  28. package/dist/transport-params.d.ts +38 -0
  29. package/dist/transport-params.d.ts.map +1 -0
  30. package/dist/transport-params.js +124 -0
  31. package/dist/transport-params.js.map +1 -0
  32. package/dist/types.d.ts.map +1 -1
  33. package/dist/utils.d.ts.map +1 -1
  34. package/dist/utils.js +2 -1
  35. package/dist/utils.js.map +1 -1
  36. package/package.json +51 -40
  37. package/.github/workflows/ci.yml +0 -17
  38. package/.github/workflows/publish.yml +0 -49
  39. package/CODING_STANDARDS.md +0 -205
  40. package/src/connection.ts +0 -374
  41. package/src/errors.ts +0 -153
  42. package/src/frame/frame.ts +0 -423
  43. package/src/frame/varint.ts +0 -124
  44. package/src/index.ts +0 -70
  45. package/src/packet/packet.ts +0 -210
  46. package/src/stream/stream.ts +0 -746
  47. package/src/types.ts +0 -441
  48. package/src/utils.ts +0 -38
  49. package/tests/connection.test.ts +0 -106
  50. package/tests/fake-transport.ts +0 -107
  51. package/tests/stream.test.ts +0 -152
  52. package/tests/wire.test.ts +0 -342
  53. package/tsconfig.json +0 -30
package/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # @browsercore/quic
2
+
3
+
4
+ [![npm version](https://img.shields.io/npm/v/@browsercore/quic)](https://www.npmjs.com/package/@browsercore/quic)
5
+ [![coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/jverneuer/browsercore-quic/coverage/coverage/badge.json)](https://github.com/jverneuer/browsercore-quic/blob/main/COVERAGE.md)
6
+ [![lint](https://img.shields.io/github/actions/workflow/status/jverneuer/browsercore-quic/ci.yml?label=lint)](https://github.com/jverneuer/browsercore-quic/actions/workflows/ci.yml)
7
+
8
+ QUIC transport (RFC 9000) — packet headers, frames, packet protection, streams,
9
+ and connection lifecycle over a datagram (UDP) transport.
10
+
11
+ ## Responsibility
12
+
13
+ Packet header parse/serialization (long + short headers), the full QUIC frame
14
+ set (RFC 9000 §12), variable-length integer encoding (RFC 9000 §16), per-stream
15
+ state machines, receive reassembly, and flow control (connection + stream
16
+ level). The package knows nothing about HTTP/3, TLS, or sockets — it composes
17
+ exclusively over an injected `DatagramTransport` and `@browsercore/crypto`.
18
+
19
+ ## What it does NOT know about
20
+
21
+ - HTTP/3, QPACK, or any application protocol
22
+ - TLS 1.3 / the QUIC handshake (key derivation lives in `@browsercore/crypto`)
23
+ - UDP, DNS, or sockets
24
+ - Browser fingerprints
25
+
26
+ Higher layers compose exclusively through the `QuicConnection` interface. A
27
+ future `@browsercore/http3` opens bidirectional + unidirectional QUIC streams
28
+ and never touches QUIC internals. The production UDP transport **never** calls
29
+ `node:dgram` directly — it implements `DatagramTransport`, so the backend is
30
+ replaceable (a test double, a `node:dgram` adapter, a mock).
31
+
32
+ ## Public API
33
+
34
+ ```ts
35
+ import { connectQuic, ConnectionClosedError } from "@browsercore/quic";
36
+
37
+ const conn = await connectQuic({
38
+ transport, // an injected DatagramTransport (UDP)
39
+ peer: { address: "93.184.216.34", port: 443, family: 6 },
40
+ serverName: "example.com",
41
+ initialDcid: new Uint8Array([1, 2, 3, 4]),
42
+ initialScid: new Uint8Array([5, 6, 7, 8]),
43
+ });
44
+
45
+ // Open a bidirectional stream (request/response in HTTP/3).
46
+ const stream = await conn.openBidirectionalStream();
47
+ await stream.write(new TextEncoder().encode("hello"));
48
+ await stream.close();
49
+ const chunk = await stream.read();
50
+
51
+ // Accept a peer-opened unidirectional stream (control / QPACK / push).
52
+ const control = await conn.acceptUnidirectionalStream();
53
+
54
+ await conn.close(0x00n, "graceful shutdown");
55
+ ```
56
+
57
+ ## Types
58
+
59
+ | Export | Kind | Purpose |
60
+ | --- | --- | --- |
61
+ | `connectQuic` | function | Establish a QUIC connection over a datagram transport |
62
+ | `QuicConnectionImpl` | class | Concrete connection; implements `QuicConnection` |
63
+ | `QuicConnection` | interface | Public contract HTTP/3 depends on |
64
+ | `QuicStream` | interface | A reliable, ordered byte stream |
65
+ | `QuicOptions` | interface | Options for `connectQuic` |
66
+ | `DatagramTransport` | interface | Injected UDP abstraction |
67
+ | `QuicFrame` | type | Every QUIC frame variant (exhaustive union) |
68
+ | `QuicFrameType` | const | Frame type identifiers |
69
+ | `StreamId` | type | Branded 62-bit stream id |
70
+ | `ConnectionId` | type | QUIC connection id (0–255 bytes) |
71
+ | `LongPacketType` | const | Long-header packet types (Initial/Handshake/0-RTT/Retry) |
72
+ | `TransportParameter` | const | Transport-parameter identifiers |
73
+ | `QuicTransportParameters` | interface | Locally-advertised transport parameters |
74
+ | `QuicError` | class | Base class for all QUIC errors |
75
+ | `ConnectionClosedError` | class | Peer closed the connection |
76
+ | `ResetStreamError` | class | Peer reset a stream |
77
+ | `StopSendingError` | class | Peer asked us to stop sending |
78
+ | `FlowControlError` | class | Flow-control window violated |
79
+ | `PacketParseError` | class | Malformed packet |
80
+ | `FrameParseError` | class | Malformed frame |
81
+ | `TransportParameterError` | class | Peer violated transport parameters |
82
+ | `HandshakeTimeoutError` | class | Handshake did not complete in time |
83
+ | `createStreamManager` | function | Create the stream state machine + flow control |
84
+ | `serializeFrame` / `readFrames` | functions | Frame serialization + incremental parsing |
85
+ | `encodeVarint` / `decodeVarint` | functions | QUIC varint encoding |
86
+ | `parsePacketHeader` / `serializeShortHeader` / `serializeLongHeader` | functions | Packet header parse/serialize |
87
+ | `decodePacketNumber` / `encodePacketNumber` | functions | Truncated packet-number coding |
88
+
89
+ ## Architecture
90
+
91
+ ```
92
+ DatagramTransport (injected UDP)
93
+ │
94
+ ▼
95
+ ┌─────────────────────────────────────────────┐
96
+ │ connection.ts — read loop, packet I/O │
97
+ │ packet.ts — header parse/serialize │
98
+ │ frame.ts — frame parse/serialize │
99
+ │ varint.ts — QUIC varint (RFC 9000 §16) │
100
+ └──────────────┬──────────────────────────────┘
101
+ │ dispatch
102
+ ▼
103
+ ┌─────────────────────────────────────────────┐
104
+ │ stream.ts — stream state machine, │
105
+ │ reassembly, flow control │
106
+ └─────────────────────────────────────────────┘
107
+ ```
108
+
109
+ Frames flow up from the transport into the stream manager; the manager emits
110
+ control frames (MAX_DATA, MAX_STREAM_DATA, CONNECTION_CLOSE, …) back down to
111
+ the connection's packetizer. The connection owns the read loop and packs
112
+ outbound frames into short-header (1-RTT) packets.
113
+
114
+ ## Known limitations
115
+
116
+ - The TLS 1.3 handshake and packet protection (header protection + AEAD
117
+ payload encryption) are out of scope. `connectQuic()` returns a connection
118
+ that moves *unprotected* frames over the transport — the data plane is fully
119
+ functional and unit-tested, but it is not wire-ready without a protection +
120
+ handshake layer on top.
121
+ - No congestion controller, no connection migration, no PATH_CHALLENGE /
122
+ PATH_RESPONSE beyond frame relay, and no liveness PING.
@@ -20,8 +20,9 @@
20
20
  * manager and packed into packets; writes resolve once bytes are buffered.
21
21
  */
22
22
  import type { EventEmitter } from "node:events";
23
- import type { ConnectionId, QuicConnection, QuicFrame, QuicOptions, QuicStream } from "./types.js";
23
+ import { type ConnectionId, type QuicConnection, type QuicFrame, type QuicOptions, type QuicStream, type QuicTransportParameters } from "./types.js";
24
24
  import { type StreamManager } from "./stream/stream.js";
25
+ import { type TransportParameters } from "./transport-params.js";
25
26
  /**
26
27
  * Concrete QUIC connection. The public surface matches the fixed
27
28
  * `QuicConnection` interface; internal state is kept on the instance.
@@ -36,6 +37,11 @@ export declare class QuicConnectionImpl implements QuicConnection {
36
37
  private readonly manager;
37
38
  /** Our current destination connection id (the one we put on outbound packets). */
38
39
  private readonly dcid;
40
+ /**
41
+ * Our transport parameters encoded for the wire. Produced at handshake
42
+ * time so a TLS layer can carry them to the peer in the QUIC extension.
43
+ */
44
+ private readonly encodedLocalParameters;
39
45
  /** Set once the connection begins graceful shutdown. */
40
46
  private closing;
41
47
  /** Set once the connection is fully torn down. */
@@ -54,43 +60,57 @@ export declare class QuicConnectionImpl implements QuicConnection {
54
60
  * connection's packetizer.
55
61
  */
56
62
  sendFrame(frame: QuicFrame): void;
63
+ /**
64
+ * Our transport parameters, encoded for the wire. A TLS handshake layer
65
+ * reads these once and carries them to the peer in the QUIC extension.
66
+ */
67
+ getEncodedLocalParameters(): Uint8Array;
68
+ /**
69
+ * Ingest the peer's transport parameters from their wire encoding. Decodes
70
+ * them and feeds them to the stream manager so its send windows match what
71
+ * the peer advertised. Called by the handshake layer once the peer's
72
+ * parameters are available.
73
+ */
74
+ receivePeerParameters(peerWireParameters: Uint8Array): void;
75
+ /** Expose the wire-form peer parameters for inspection (tests, debugging). */
76
+ toWireParameters(params: QuicTransportParameters): TransportParameters;
57
77
  /**
58
78
  * Pack all buffered outbound frames into a short-header packet and send it.
59
79
  * Splits into multiple datagrams if the payload exceeds MAX_DATAGRAM_PAYLOAD.
60
80
  */
61
- private _flush;
81
+ private flush;
62
82
  /** Serialize frames into a single byte buffer (no packet header). */
63
- private _packFrames;
83
+ private packFrames;
64
84
  /** Wrap a serialized payload in a short (1-RTT) header + packet number. */
65
- private _wrapPacket;
85
+ private wrapPacket;
66
86
  /**
67
87
  * Start the datagram read loop. Must be called once after construction.
68
88
  * Runs until the transport closes or the connection tears down.
69
89
  */
70
90
  startReadLoop(): void;
71
- private _onPeerClose;
91
+ private onPeerClose;
72
92
  /** Parse a single datagram into frames and dispatch them. */
73
- private _dispatchDatagram;
93
+ private dispatchDatagram;
74
94
  /** Pull the DCID / version from a parsed header into connection state. */
75
- private _applyHeader;
95
+ private applyHeader;
76
96
  /**
77
97
  * Build a pull-based byte reader over a fixed buffer. `readFrames` consumes
78
98
  * bytes incrementally; this yields slices until the buffer is exhausted.
79
99
  */
80
- private _byteStreamReader;
100
+ private byteStreamReader;
81
101
  /** Route a decoded frame: data-plane frames to the manager, the rest here. */
82
- private _handleFrame;
102
+ private handleFrame;
83
103
  /** Run `fn`, then flush any outbound frames it produced to the peer. */
84
- private _withOutbound;
104
+ private withOutbound;
85
105
  /** Main read loop: pull datagrams, dispatch, drain sends. */
86
- private _readLoop;
106
+ private readLoop;
87
107
  /** Emit STREAM frames for streams with queued data, then flush. */
88
- private _drainSends;
108
+ private drainSends;
89
109
  /** Tear down the connection on a fatal transport / parse error. */
90
110
  private _handleFatal;
91
111
  /** Mark closed and release the transport. */
92
112
  private _teardown;
93
- private _ensureOpen;
113
+ private ensureOpen;
94
114
  }
95
115
  /**
96
116
  * Establish a QUIC connection over an existing datagram transport.
@@ -1 +1 @@
1
- {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../src/connection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EACR,YAAY,EACZ,cAAc,EACd,SAAS,EACT,WAAW,EACX,UAAU,EAGb,MAAM,YAAY,CAAC;AAMpB,OAAO,EAAuB,KAAK,aAA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C;YAC/B,SAAS;IAavB,OAAO,CAAC,UAAU;CAKrB;AA4CD;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,cAAc,CAAC,CA0BzE"}
@@ -19,12 +19,13 @@
19
19
  * the transport. Outbound frames are produced synchronously by the stream
20
20
  * manager and packed into packets; writes resolve once bytes are buffered.
21
21
  */
22
- import { QuicFrameType } from "./types.js";
22
+ import { QuicFrameType, } from "./types.js";
23
23
  import { parsePacketHeader, serializeShortHeader } from "./packet/packet.js";
24
24
  import { readFrames, serializeFrame } from "./frame/frame.js";
25
25
  import { ConnectionClosedError } from "./errors.js";
26
26
  import { createStreamManager } from "./stream/stream.js";
27
27
  import { concatAll } from "./utils.js";
28
+ import { decodeTransportParameters, encodeTransportParameters, fromWireParameters, toWireParameters, } from "./transport-params.js";
28
29
  /** Largest UDP payload we will pack into a single datagram (RFC 9000 §14). */
29
30
  const MAX_DATAGRAM_PAYLOAD = 1200;
30
31
  /**
@@ -41,6 +42,11 @@ export class QuicConnectionImpl {
41
42
  manager;
42
43
  /** Our current destination connection id (the one we put on outbound packets). */
43
44
  dcid;
45
+ /**
46
+ * Our transport parameters encoded for the wire. Produced at handshake
47
+ * time so a TLS layer can carry them to the peer in the QUIC extension.
48
+ */
49
+ encodedLocalParameters;
44
50
  /** Set once the connection begins graceful shutdown. */
45
51
  closing = false;
46
52
  /** Set once the connection is fully torn down. */
@@ -53,31 +59,44 @@ export class QuicConnectionImpl {
53
59
  this.peer = options.peer;
54
60
  this.manager = manager;
55
61
  this.dcid = dcid;
62
+ // Encode our transport parameters for the wire at construction. A real
63
+ // TLS handshake would carry these to the peer in the QUIC extension;
64
+ // here we surface them so the handshake layer can read them.
65
+ this.encodedLocalParameters = encodeTransportParameters(toWireParameters(resolveLocalParameters(options)));
56
66
  }
57
67
  // --- public QuicConnection surface ------------------------------------------
58
- async openBidirectionalStream() {
59
- this._ensureOpen();
60
- return this.manager.openStream(true);
68
+ openBidirectionalStream() {
69
+ return Promise.resolve().then(() => {
70
+ this.ensureOpen();
71
+ return this.manager.openStream(true);
72
+ });
61
73
  }
62
- async acceptBidirectionalStream() {
63
- this._ensureOpen();
64
- return this.manager.acceptStream(true);
74
+ acceptBidirectionalStream() {
75
+ return Promise.resolve().then(() => {
76
+ this.ensureOpen();
77
+ return this.manager.acceptStream(true);
78
+ });
65
79
  }
66
- async openUnidirectionalStream() {
67
- this._ensureOpen();
68
- return this.manager.openStream(false);
80
+ openUnidirectionalStream() {
81
+ return Promise.resolve().then(() => {
82
+ this.ensureOpen();
83
+ return this.manager.openStream(false);
84
+ });
69
85
  }
70
- async acceptUnidirectionalStream() {
71
- this._ensureOpen();
72
- return this.manager.acceptStream(false);
86
+ acceptUnidirectionalStream() {
87
+ return Promise.resolve().then(() => {
88
+ this.ensureOpen();
89
+ return this.manager.acceptStream(false);
90
+ });
73
91
  }
74
92
  async close(errorCode, reason) {
75
- if (this.closed)
93
+ if (this.closed) {
76
94
  return;
95
+ }
77
96
  this.closing = true;
78
97
  this.manager.close(errorCode, reason);
79
98
  // Pack + flush the CONNECTION_CLOSE frame, then tear down.
80
- await this._flush();
99
+ await this.flush();
81
100
  await this._teardown({ kind: "client_close" });
82
101
  }
83
102
  // --- frame I/O -------------------------------------------------------------
@@ -89,29 +108,53 @@ export class QuicConnectionImpl {
89
108
  sendFrame(frame) {
90
109
  this.outboundFrames.push(frame);
91
110
  }
111
+ /**
112
+ * Our transport parameters, encoded for the wire. A TLS handshake layer
113
+ * reads these once and carries them to the peer in the QUIC extension.
114
+ */
115
+ getEncodedLocalParameters() {
116
+ return this.encodedLocalParameters;
117
+ }
118
+ /**
119
+ * Ingest the peer's transport parameters from their wire encoding. Decodes
120
+ * them and feeds them to the stream manager so its send windows match what
121
+ * the peer advertised. Called by the handshake layer once the peer's
122
+ * parameters are available.
123
+ */
124
+ receivePeerParameters(peerWireParameters) {
125
+ const wire = decodeTransportParameters(peerWireParameters);
126
+ this.manager.updatePeerParameters(fromWireParameters(wire));
127
+ }
128
+ /** Expose the wire-form peer parameters for inspection (tests, debugging). */
129
+ toWireParameters(params) {
130
+ return toWireParameters(params);
131
+ }
92
132
  /**
93
133
  * Pack all buffered outbound frames into a short-header packet and send it.
94
134
  * Splits into multiple datagrams if the payload exceeds MAX_DATAGRAM_PAYLOAD.
95
135
  */
96
- async _flush() {
97
- if (this.outboundFrames.length === 0)
136
+ async flush() {
137
+ if (this.outboundFrames.length === 0) {
98
138
  return;
99
- const frames = this.outboundFrames.splice(0, this.outboundFrames.length);
100
- const payload = this._packFrames(frames);
101
- let offset = 0;
102
- while (offset < payload.length) {
139
+ }
140
+ const frames = this.outboundFrames.splice(0);
141
+ const payload = this.packFrames(frames);
142
+ // Each fragment is an independent datagram (own slice, own packet); build
143
+ // them all, then send concurrently rather than serializing independent sends.
144
+ const sends = [];
145
+ for (let offset = 0; offset < payload.length; offset += MAX_DATAGRAM_PAYLOAD) {
103
146
  const slice = payload.subarray(offset, offset + MAX_DATAGRAM_PAYLOAD);
104
- const packet = this._wrapPacket(slice);
105
- await this.transport.send(packet, this.peer);
106
- offset += MAX_DATAGRAM_PAYLOAD;
147
+ const packet = this.wrapPacket(slice);
148
+ sends.push(this.transport.send(packet, this.peer));
107
149
  }
150
+ await Promise.all(sends);
108
151
  }
109
152
  /** Serialize frames into a single byte buffer (no packet header). */
110
- _packFrames(frames) {
153
+ packFrames(frames) {
111
154
  return concatAll(frames.map((f) => serializeFrame(f)));
112
155
  }
113
156
  /** Wrap a serialized payload in a short (1-RTT) header + packet number. */
114
- _wrapPacket(payload) {
157
+ wrapPacket(payload) {
115
158
  const header = serializeShortHeader(this.dcid, 1, false, false);
116
159
  // 1-byte packet number (relative offset 0) — placeholder for the
117
160
  // protection layer, which assigns real packet numbers.
@@ -126,26 +169,26 @@ export class QuicConnectionImpl {
126
169
  startReadLoop() {
127
170
  // React to connection-level signals from the stream manager.
128
171
  this.manager.on("connectionClose", ({ errorCode, reason }) => {
129
- void errorCode;
130
- void reason;
131
- void this._onPeerClose(errorCode, reason);
172
+ void this.onPeerClose(errorCode, reason);
132
173
  });
133
- void this._readLoop();
174
+ void this.readLoop();
134
175
  }
135
- async _onPeerClose(errorCode, reason) {
136
- if (this.closed)
176
+ async onPeerClose(errorCode, reason) {
177
+ if (this.closed) {
137
178
  return;
179
+ }
138
180
  this.closing = true;
139
181
  this.manager.abortAll(new ConnectionClosedError(errorCode, reason));
140
182
  await this._teardown({ kind: "remote_close" });
141
183
  }
142
184
  /** Parse a single datagram into frames and dispatch them. */
143
- async _dispatchDatagram(data) {
144
- if (data.length === 0)
185
+ async dispatchDatagram(data) {
186
+ if (data.length === 0) {
145
187
  return;
188
+ }
146
189
  try {
147
190
  const header = parsePacketHeader(data);
148
- this._applyHeader(header);
191
+ this.applyHeader(header);
149
192
  // Skip the header + packet number to reach the frame payload. The
150
193
  // protection layer would decrypt first in a full implementation.
151
194
  const pnLength = header.packetNumberLength;
@@ -155,11 +198,12 @@ export class QuicConnectionImpl {
155
198
  const dcidLength = header.form === 0 ? this.dcid.length : 0;
156
199
  const payloadStart = header.headerLength + dcidLength + pnLength;
157
200
  const payload = data.subarray(payloadStart);
158
- if (payload.length === 0)
201
+ if (payload.length === 0) {
159
202
  return;
160
- const read = this._byteStreamReader(payload);
203
+ }
204
+ const read = this.byteStreamReader(payload);
161
205
  for await (const frame of readFrames(read)) {
162
- this._handleFrame(frame);
206
+ this.handleFrame(frame);
163
207
  }
164
208
  }
165
209
  catch (err) {
@@ -169,7 +213,7 @@ export class QuicConnectionImpl {
169
213
  }
170
214
  }
171
215
  /** Pull the DCID / version from a parsed header into connection state. */
172
- _applyHeader(header) {
216
+ applyHeader(header) {
173
217
  if (header.form === 1) {
174
218
  // Long header: could carry a version negotiation. We ignore for now.
175
219
  return;
@@ -181,22 +225,47 @@ export class QuicConnectionImpl {
181
225
  * Build a pull-based byte reader over a fixed buffer. `readFrames` consumes
182
226
  * bytes incrementally; this yields slices until the buffer is exhausted.
183
227
  */
184
- _byteStreamReader(buf) {
228
+ byteStreamReader(buf) {
185
229
  let offset = 0;
186
- return async () => {
187
- if (offset >= buf.length)
188
- return null;
230
+ return () => {
231
+ if (offset >= buf.length) {
232
+ return Promise.resolve(null);
233
+ }
189
234
  const chunk = buf.subarray(offset);
190
235
  offset = buf.length;
191
- return chunk;
236
+ return Promise.resolve(chunk);
192
237
  };
193
238
  }
194
239
  /** Route a decoded frame: data-plane frames to the manager, the rest here. */
195
- _handleFrame(frame) {
240
+ handleFrame(frame) {
241
+ // Connection / handshake layer concerns (PADDING, PING, ACK, CRYPTO,
242
+ // NEW_TOKEN, NEW_CONNECTION_ID, RETIRE_CONNECTION_ID, PATH_CHALLENGE,
243
+ // PATH_RESPONSE, HANDSHAKE_DONE) — relay only. Data-plane frames are
244
+ // dispatched to the stream manager, which may emit outbound control
245
+ // frames (MAX_DATA, MAX_STREAM_DATA, ...).
196
246
  switch (frame.type) {
247
+ case QuicFrameType.RESET_STREAM:
248
+ case QuicFrameType.STOP_SENDING:
249
+ case QuicFrameType.STREAM:
250
+ case QuicFrameType.MAX_DATA:
251
+ case QuicFrameType.MAX_STREAM_DATA:
252
+ case QuicFrameType.MAX_STREAMS_BIDI:
253
+ case QuicFrameType.MAX_STREAMS_UNI:
254
+ case QuicFrameType.DATA_BLOCKED:
255
+ case QuicFrameType.STREAM_DATA_BLOCKED:
256
+ case QuicFrameType.STREAMS_BLOCKED_BIDI:
257
+ case QuicFrameType.STREAMS_BLOCKED_UNI:
258
+ case QuicFrameType.CONNECTION_CLOSE:
259
+ case QuicFrameType.CONNECTION_CLOSE_APP:
260
+ this.withOutbound(() => {
261
+ this.manager.dispatch(frame);
262
+ });
263
+ break;
264
+ // Connection / handshake layer concerns — relay only. The data plane
265
+ // does not act on these; a full implementation would pace ACKs and
266
+ // handle the handshake, which is out of scope here.
197
267
  case QuicFrameType.PADDING:
198
268
  case QuicFrameType.PING:
199
- return;
200
269
  case QuicFrameType.ACK:
201
270
  case QuicFrameType.ACK_ECN:
202
271
  case QuicFrameType.CRYPTO:
@@ -206,31 +275,29 @@ export class QuicConnectionImpl {
206
275
  case QuicFrameType.PATH_CHALLENGE:
207
276
  case QuicFrameType.PATH_RESPONSE:
208
277
  case QuicFrameType.HANDSHAKE_DONE:
209
- // Connection / handshake layer concerns — relay only.
210
- return;
211
- default:
212
- // Data-plane frame: dispatch to the stream manager, which may
213
- // emit outbound control frames (MAX_DATA, MAX_STREAM_DATA, ...).
214
- this._withOutbound(() => this.manager.dispatch(frame));
215
- return;
278
+ break;
216
279
  }
217
280
  }
218
281
  /** Run `fn`, then flush any outbound frames it produced to the peer. */
219
- _withOutbound(fn) {
282
+ withOutbound(fn) {
220
283
  const before = this.outboundFrames.length;
221
284
  fn();
222
285
  if (this.outboundFrames.length > before) {
223
- void this._flush();
286
+ void this.flush();
224
287
  }
225
288
  }
226
289
  /** Main read loop: pull datagrams, dispatch, drain sends. */
227
- async _readLoop() {
290
+ async readLoop() {
228
291
  try {
229
292
  while (!this.closed) {
293
+ // The read loop pulls one datagram at a time and must process it
294
+ // before pulling the next (ordered, in-order frame dispatch).
295
+ // eslint-disable-next-line no-await-in-loop -- sequential datagram consumption is required
230
296
  const { data } = await this.transport.recv();
231
- await this._dispatchDatagram(data);
297
+ // eslint-disable-next-line no-await-in-loop -- dispatch must complete before the next datagram
298
+ await this.dispatchDatagram(data);
232
299
  // Drain any pending stream sends after handling each datagram.
233
- this._drainSends();
300
+ this.drainSends();
234
301
  }
235
302
  }
236
303
  catch (err) {
@@ -240,24 +307,29 @@ export class QuicConnectionImpl {
240
307
  }
241
308
  }
242
309
  /** Emit STREAM frames for streams with queued data, then flush. */
243
- _drainSends() {
244
- if (!this.manager.hasPendingSends)
310
+ drainSends() {
311
+ if (!this.manager.hasPendingSends) {
245
312
  return;
246
- this.manager.flushSends(MAX_DATAGRAM_PAYLOAD, (frame) => this.sendFrame(frame));
247
- void this._flush();
313
+ }
314
+ this.manager.flushSends(MAX_DATAGRAM_PAYLOAD, (frame) => {
315
+ this.sendFrame(frame);
316
+ });
317
+ void this.flush();
248
318
  }
249
319
  /** Tear down the connection on a fatal transport / parse error. */
250
320
  _handleFatal(err) {
251
- if (this.closed)
321
+ if (this.closed) {
252
322
  return;
323
+ }
253
324
  this.closing = true;
254
325
  this.manager.abortAll(err);
255
- this._teardown({ kind: "error", error: err });
326
+ void this._teardown({ kind: "error", error: err });
256
327
  }
257
328
  /** Mark closed and release the transport. */
258
329
  async _teardown(reason) {
259
- if (this.closed)
330
+ if (this.closed) {
260
331
  return;
332
+ }
261
333
  this.closed = true;
262
334
  this.closing = true;
263
335
  try {
@@ -267,7 +339,7 @@ export class QuicConnectionImpl {
267
339
  // best-effort
268
340
  }
269
341
  }
270
- _ensureOpen() {
342
+ ensureOpen() {
271
343
  if (this.closing || this.closed) {
272
344
  throw new Error("connection is closing");
273
345
  }
@@ -280,26 +352,33 @@ export class QuicConnectionImpl {
280
352
  function resolveLocalParameters(options) {
281
353
  const src = options.transportParameters;
282
354
  const out = {};
283
- if (src?.initialMaxData !== undefined)
355
+ if (src?.initialMaxData !== undefined) {
284
356
  out.initialMaxData = src.initialMaxData;
357
+ }
285
358
  if (src?.initialMaxStreamDataBidiLocal !== undefined) {
286
359
  out.initialMaxStreamDataBidiLocal = src.initialMaxStreamDataBidiLocal;
287
360
  }
288
361
  if (src?.initialMaxStreamDataBidiRemote !== undefined) {
289
362
  out.initialMaxStreamDataBidiRemote = src.initialMaxStreamDataBidiRemote;
290
363
  }
291
- if (src?.initialMaxStreamDataUni !== undefined)
364
+ if (src?.initialMaxStreamDataUni !== undefined) {
292
365
  out.initialMaxStreamDataUni = src.initialMaxStreamDataUni;
293
- if (src?.initialMaxStreamsBidi !== undefined)
366
+ }
367
+ if (src?.initialMaxStreamsBidi !== undefined) {
294
368
  out.initialMaxStreamsBidi = src.initialMaxStreamsBidi;
295
- if (src?.initialMaxStreamsUni !== undefined)
369
+ }
370
+ if (src?.initialMaxStreamsUni !== undefined) {
296
371
  out.initialMaxStreamsUni = src.initialMaxStreamsUni;
297
- if (src?.maxIdleTimeoutMs !== undefined)
372
+ }
373
+ if (src?.maxIdleTimeoutMs !== undefined) {
298
374
  out.maxIdleTimeoutMs = src.maxIdleTimeoutMs;
299
- if (src?.maxUdpPayloadSize !== undefined)
375
+ }
376
+ if (src?.maxUdpPayloadSize !== undefined) {
300
377
  out.maxUdpPayloadSize = src.maxUdpPayloadSize;
301
- if (src?.activeConnectionIdLimit !== undefined)
378
+ }
379
+ if (src?.activeConnectionIdLimit !== undefined) {
302
380
  out.activeConnectionIdLimit = src.activeConnectionIdLimit;
381
+ }
303
382
  return out;
304
383
  }
305
384
  // ---------------------------------------------------------------------------
@@ -313,22 +392,26 @@ function resolveLocalParameters(options) {
313
392
  * unprotected frames — the data plane is fully functional and testable with a
314
393
  * fake datagram transport.
315
394
  */
316
- export async function connectQuic(options) {
395
+ export function connectQuic(options) {
317
396
  const id = `quic_${Date.now().toString(36)}`;
318
397
  // The stream manager is constructed before the connection, but its frames
319
398
  // must reach the connection's packetizer. We bridge the two with a mutable
320
399
  // router that we point at the connection once it exists.
321
400
  const frameRouter = { send: () => { } };
322
401
  const manager = createStreamManager({
323
- sendFrame: (frame) => frameRouter.send(frame),
402
+ sendFrame: (frame) => {
403
+ frameRouter.send(frame);
404
+ },
324
405
  localParameters: resolveLocalParameters(options),
325
406
  peerParameters: options.transportParameters ?? {},
326
407
  });
327
408
  const conn = new QuicConnectionImpl(id, options, manager, options.initialDcid);
328
- frameRouter.send = (frame) => conn.sendFrame(frame);
409
+ frameRouter.send = (frame) => {
410
+ conn.sendFrame(frame);
411
+ };
329
412
  // A larger send window may have queued stream data — the read loop drains it.
330
413
  manager.on("maxData", () => { });
331
414
  conn.startReadLoop();
332
- return conn;
415
+ return Promise.resolve(conn);
333
416
  }
334
417
  //# sourceMappingURL=connection.js.map