@moq/net 0.4.1 → 0.4.3

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 (184) hide show
  1. package/broadcast.d.ts +21 -7
  2. package/broadcast.d.ts.map +1 -1
  3. package/broadcast.js +38 -16
  4. package/broadcast.js.map +1 -1
  5. package/connection/accept.js +6 -4
  6. package/connection/accept.js.map +1 -1
  7. package/connection/connect.d.ts.map +1 -1
  8. package/connection/connect.js +5 -4
  9. package/connection/connect.js.map +1 -1
  10. package/connection/forward.js +54 -47
  11. package/connection/forward.js.map +1 -1
  12. package/connection/goaway.d.ts +34 -0
  13. package/connection/goaway.d.ts.map +1 -0
  14. package/connection/goaway.js +176 -0
  15. package/connection/goaway.js.map +1 -0
  16. package/connection/handshake.d.ts +4 -2
  17. package/connection/handshake.d.ts.map +1 -1
  18. package/connection/handshake.js +42 -10
  19. package/connection/handshake.js.map +1 -1
  20. package/connection/pool.d.ts +16 -1
  21. package/connection/pool.d.ts.map +1 -1
  22. package/connection/pool.js +32 -10
  23. package/connection/pool.js.map +1 -1
  24. package/connection/reload.d.ts.map +1 -1
  25. package/connection/reload.js +184 -30
  26. package/connection/reload.js.map +1 -1
  27. package/error.d.ts +11 -0
  28. package/error.d.ts.map +1 -1
  29. package/error.js +14 -0
  30. package/error.js.map +1 -1
  31. package/errors.d.ts +1 -1
  32. package/errors.d.ts.map +1 -1
  33. package/errors.js +1 -1
  34. package/errors.js.map +1 -1
  35. package/group.d.ts.map +1 -1
  36. package/group.js +5 -4
  37. package/group.js.map +1 -1
  38. package/hop.d.ts +8 -0
  39. package/hop.d.ts.map +1 -1
  40. package/hop.js +16 -0
  41. package/hop.js.map +1 -1
  42. package/ietf/adapter.d.ts +4 -0
  43. package/ietf/adapter.d.ts.map +1 -1
  44. package/ietf/adapter.js +19 -8
  45. package/ietf/adapter.js.map +1 -1
  46. package/ietf/cluster.d.ts +3 -3
  47. package/ietf/cluster.js +3 -3
  48. package/ietf/cluster.js.map +1 -1
  49. package/ietf/connection.d.ts.map +1 -1
  50. package/ietf/connection.js +110 -37
  51. package/ietf/connection.js.map +1 -1
  52. package/ietf/fetch.d.ts +7 -20
  53. package/ietf/fetch.d.ts.map +1 -1
  54. package/ietf/fetch.js +52 -22
  55. package/ietf/fetch.js.map +1 -1
  56. package/ietf/filter.d.ts +20 -4
  57. package/ietf/filter.d.ts.map +1 -1
  58. package/ietf/filter.js +165 -17
  59. package/ietf/filter.js.map +1 -1
  60. package/ietf/goaway.d.ts +9 -1
  61. package/ietf/goaway.d.ts.map +1 -1
  62. package/ietf/goaway.js +20 -0
  63. package/ietf/goaway.js.map +1 -1
  64. package/ietf/hidden.js +1 -1
  65. package/ietf/hidden.js.map +1 -1
  66. package/ietf/index.d.ts +1 -1
  67. package/ietf/index.d.ts.map +1 -1
  68. package/ietf/index.js +1 -1
  69. package/ietf/index.js.map +1 -1
  70. package/ietf/object.d.ts +9 -6
  71. package/ietf/object.d.ts.map +1 -1
  72. package/ietf/object.js +47 -38
  73. package/ietf/object.js.map +1 -1
  74. package/ietf/parameters.d.ts +13 -8
  75. package/ietf/parameters.d.ts.map +1 -1
  76. package/ietf/parameters.js +177 -30
  77. package/ietf/parameters.js.map +1 -1
  78. package/ietf/publish.d.ts +1 -0
  79. package/ietf/publish.d.ts.map +1 -1
  80. package/ietf/publish.js +1 -0
  81. package/ietf/publish.js.map +1 -1
  82. package/ietf/publish_namespace.d.ts +2 -2
  83. package/ietf/publish_namespace.js +2 -2
  84. package/ietf/publish_namespace.js.map +1 -1
  85. package/ietf/publisher.js +404 -202
  86. package/ietf/publisher.js.map +1 -1
  87. package/ietf/request_stream.d.ts +7 -0
  88. package/ietf/request_stream.d.ts.map +1 -0
  89. package/ietf/request_stream.js +20 -0
  90. package/ietf/request_stream.js.map +1 -0
  91. package/ietf/subscribe.d.ts +7 -1
  92. package/ietf/subscribe.d.ts.map +1 -1
  93. package/ietf/subscribe.js +24 -17
  94. package/ietf/subscribe.js.map +1 -1
  95. package/ietf/subscribe_namespace.d.ts.map +1 -1
  96. package/ietf/subscribe_namespace.js +7 -3
  97. package/ietf/subscribe_namespace.js.map +1 -1
  98. package/ietf/subscriber.js +83 -56
  99. package/ietf/subscriber.js.map +1 -1
  100. package/ietf/token.d.ts +2 -0
  101. package/ietf/token.d.ts.map +1 -0
  102. package/ietf/token.js +99 -0
  103. package/ietf/token.js.map +1 -0
  104. package/ietf/track.d.ts +4 -0
  105. package/ietf/track.d.ts.map +1 -1
  106. package/ietf/track.js +6 -20
  107. package/ietf/track.js.map +1 -1
  108. package/index.d.ts +1 -1
  109. package/index.d.ts.map +1 -1
  110. package/index.js.map +1 -1
  111. package/internal.d.ts +12 -3
  112. package/internal.d.ts.map +1 -1
  113. package/internal.js +32 -0
  114. package/internal.js.map +1 -1
  115. package/lite/announce.d.ts.map +1 -1
  116. package/lite/announce.js +7 -4
  117. package/lite/announce.js.map +1 -1
  118. package/lite/connection.d.ts.map +1 -1
  119. package/lite/connection.js +22 -7
  120. package/lite/connection.js.map +1 -1
  121. package/lite/datagram.d.ts +3 -2
  122. package/lite/datagram.d.ts.map +1 -1
  123. package/lite/datagram.js +7 -8
  124. package/lite/datagram.js.map +1 -1
  125. package/lite/group.d.ts +12 -8
  126. package/lite/group.d.ts.map +1 -1
  127. package/lite/group.js +37 -16
  128. package/lite/group.js.map +1 -1
  129. package/lite/message.d.ts +2 -2
  130. package/lite/message.d.ts.map +1 -1
  131. package/lite/message.js +14 -5
  132. package/lite/message.js.map +1 -1
  133. package/lite/publisher.js +39 -45
  134. package/lite/publisher.js.map +1 -1
  135. package/lite/setup.d.ts +1 -1
  136. package/lite/setup.d.ts.map +1 -1
  137. package/lite/setup.js +22 -19
  138. package/lite/setup.js.map +1 -1
  139. package/lite/subscribe.d.ts.map +1 -1
  140. package/lite/subscribe.js +4 -5
  141. package/lite/subscribe.js.map +1 -1
  142. package/lite/subscriber.d.ts.map +1 -1
  143. package/lite/subscriber.js +210 -127
  144. package/lite/subscriber.js.map +1 -1
  145. package/origin.d.ts +9 -1
  146. package/origin.d.ts.map +1 -1
  147. package/origin.js +341 -146
  148. package/origin.js.map +1 -1
  149. package/package.json +2 -2
  150. package/stream.d.ts +77 -12
  151. package/stream.d.ts.map +1 -1
  152. package/stream.js +359 -122
  153. package/stream.js.map +1 -1
  154. package/tail.d.ts +7 -0
  155. package/tail.d.ts.map +1 -1
  156. package/tail.js +68 -22
  157. package/tail.js.map +1 -1
  158. package/track.d.ts +14 -3
  159. package/track.d.ts.map +1 -1
  160. package/track.js +170 -76
  161. package/track.js.map +1 -1
  162. package/util/abort.d.ts +2 -0
  163. package/util/abort.d.ts.map +1 -0
  164. package/util/abort.js +20 -0
  165. package/util/abort.js.map +1 -0
  166. package/util/u64.d.ts +39 -0
  167. package/util/u64.d.ts.map +1 -0
  168. package/util/u64.js +83 -0
  169. package/util/u64.js.map +1 -0
  170. package/util/varint.d.ts +29 -0
  171. package/util/varint.d.ts.map +1 -0
  172. package/util/varint.js +198 -0
  173. package/util/varint.js.map +1 -0
  174. package/varint.d.ts +10 -6
  175. package/varint.d.ts.map +1 -1
  176. package/varint.js +40 -237
  177. package/varint.js.map +1 -1
  178. package/wire.d.ts +17 -3
  179. package/wire.d.ts.map +1 -1
  180. package/wire.js.map +1 -1
  181. package/ietf/control.d.ts +0 -135
  182. package/ietf/control.d.ts.map +0 -1
  183. package/ietf/control.js +0 -242
  184. package/ietf/control.js.map +0 -1
package/stream.js CHANGED
@@ -2,12 +2,15 @@
2
2
  import { race } from "@moq/signals";
3
3
  import { fromTransport, StreamCode, StreamError, toStreamCode, toTransport } from "./error.js";
4
4
  import { Version } from "./ietf/version.js";
5
+ import { Version as Lite } from "./lite/version.js";
5
6
  import { TimeoutError, withTimeout } from "./util/timeout.js";
7
+ import { POW32, toBigInt, toNumber, U64 } from "./util/u64.js";
6
8
  import { decodeUtf8 } from "./util/utf8.js";
7
- import * as Varint from "./varint.js";
9
+ import { lengthLeadingOnes, lengthQuic, parts, peekLeadingOnes, peekQuic, readLeadingOnes, readQuic, split, writeLeadingOnes, writeQuic, } from "./util/varint.js";
8
10
  // Decode raw transport errors before mapping so they cannot bypass the negotiated
9
11
  // registry. Ordinary errors already send 0 and retain their local identity.
10
- function withCode(reason, version) {
12
+ function withCode(reason, stream) {
13
+ const version = asIetf(stream);
11
14
  const decoded = fromTransport(reason, { version });
12
15
  const code = toStreamCode(decoded, { version });
13
16
  return code === StreamCode.Internal && decoded === reason ? reason : toTransport(code, decoded.message);
@@ -43,18 +46,56 @@ async function openWithin(opening, timeout, discard) {
43
46
  throw err;
44
47
  }
45
48
  }
49
+ const LITE = new Set(Object.values(Lite));
50
+ function isLite(version) {
51
+ return LITE.has(version);
52
+ }
53
+ /** The moq-transport draft a stream follows, or undefined on moq-lite, whose stream codes are the same on every draft. */
54
+ export function asIetf(version) {
55
+ return isLite(version) ? undefined : version;
56
+ }
57
+ // Every draft newer than these counts leading ones, so a new version falls forward.
46
58
  function isLeadingOnes(version) {
47
- return (version !== undefined &&
48
- version !== Version.DRAFT_14 &&
49
- version !== Version.DRAFT_15 &&
50
- version !== Version.DRAFT_16);
59
+ switch (version) {
60
+ case Version.DRAFT_14:
61
+ case Version.DRAFT_15:
62
+ case Version.DRAFT_16:
63
+ case Lite.DRAFT_01:
64
+ case Lite.DRAFT_02:
65
+ case Lite.DRAFT_03:
66
+ case Lite.DRAFT_04:
67
+ case Lite.DRAFT_05:
68
+ case Lite.DRAFT_06:
69
+ return false;
70
+ default:
71
+ return true;
72
+ }
73
+ }
74
+ // Encode `hi`/`lo` into `dst` in the varint form `version` uses: QUIC up to 2^62-1, leading-ones up to 2^64-1.
75
+ function encodeTo(dst, hi, lo, version) {
76
+ let buf;
77
+ if (isLeadingOnes(version)) {
78
+ buf = new Uint8Array(dst, 0, lengthLeadingOnes(hi, lo));
79
+ writeLeadingOnes(buf, hi, lo, buf.length);
80
+ }
81
+ else {
82
+ buf = new Uint8Array(dst, 0, lengthQuic(hi, lo));
83
+ writeQuic(buf, hi, lo, buf.length);
84
+ }
85
+ return buf;
86
+ }
87
+ /** Encode one varint in the form `version` uses, for a body written outside a {@link Writer}. */
88
+ export function encodeVarint(v, version) {
89
+ const lo = split(v);
90
+ return encodeTo(new ArrayBuffer(9), parts.hi, lo, version);
51
91
  }
52
92
  export class Stream {
53
93
  reader;
54
94
  writer;
55
95
  constructor(props) {
56
- const writer = props.writer ?? (props.writable && new Writer(props.writable, props.version));
57
- const reader = props.reader ?? (props.readable && new Reader(props.readable, undefined, props.version));
96
+ const version = props.version;
97
+ const writer = props.writer ?? (props.writable && version !== undefined && new Writer(props.writable, version));
98
+ const reader = props.reader ?? (props.readable && version !== undefined && new Reader(props.readable, undefined, version));
58
99
  if (!writer || !reader)
59
100
  throw new Error("stream needs both halves");
60
101
  this.writer = writer;
@@ -82,7 +123,7 @@ export class Stream {
82
123
  void stream.writable.abort().catch(() => void 0);
83
124
  void stream.readable.cancel().catch(() => void 0);
84
125
  });
85
- return new Stream({ readable, writable, version: options?.version });
126
+ return new Stream({ readable, writable, version: options.version });
86
127
  }
87
128
  close() {
88
129
  this.writer.close();
@@ -99,10 +140,16 @@ export class Stream {
99
140
  // Reader wraps a stream and provides convience methods for reading pieces from a stream
100
141
  // Unfortunately we can't use a BYOB reader because it's not supported with WebTransport+WebWorkers yet.
101
142
  export class Reader {
143
+ // Contiguous unread bytes, followed by chunks not yet joined onto it. Joining only once a
144
+ // read needs the bytes keeps a frame arriving in N chunks linear rather than quadratic.
102
145
  #buffer;
146
+ #chunks = [];
147
+ #chunked = 0; // bytes across #chunks
103
148
  #stream; // if undefined, the buffer is consumed then EOF
104
149
  #reader;
105
150
  #closed;
151
+ // The decode that last ran short and how far, so a retry can wait for those bytes.
152
+ #short;
106
153
  version;
107
154
  constructor(stream, buffer, version) {
108
155
  this.#buffer = buffer ?? new Uint8Array();
@@ -118,7 +165,7 @@ export class Reader {
118
165
  // Every read of this stream funnels through here, so decoding the peer's reset code
119
166
  // once is enough to keep the raw transport error out of every caller (and every app).
120
167
  const result = await this.#reader.read().catch((err) => {
121
- throw fromTransport(err, { version: this.version });
168
+ throw fromTransport(err, { version: asIetf(this.version) });
122
169
  });
123
170
  if (result.done) {
124
171
  return false;
@@ -126,16 +173,8 @@ export class Reader {
126
173
  if (result.value.byteLength === 0) {
127
174
  throw new Error("unexpected empty chunk");
128
175
  }
129
- const buffer = result.value;
130
- if (this.#buffer.byteLength === 0) {
131
- this.#buffer = new Uint8Array(buffer);
132
- }
133
- else {
134
- const temp = new Uint8Array(this.#buffer.byteLength + buffer.byteLength);
135
- temp.set(this.#buffer);
136
- temp.set(buffer, this.#buffer.byteLength);
137
- this.#buffer = temp;
138
- }
176
+ this.#chunks.push(result.value);
177
+ this.#chunked += result.value.byteLength;
139
178
  return true;
140
179
  }
141
180
  // Add more data to the buffer until it's at least size bytes.
@@ -143,11 +182,34 @@ export class Reader {
143
182
  if (size > MAX_READ_SIZE) {
144
183
  throw new Error(`read size ${size} exceeds max size ${MAX_READ_SIZE}`);
145
184
  }
146
- while (this.#buffer.byteLength < size) {
185
+ if (this.#buffer.byteLength >= size)
186
+ return;
187
+ while (this.#buffer.byteLength + this.#chunked < size) {
147
188
  if (!(await this.#fill())) {
148
- throw new Error("unexpected end of stream");
189
+ throw new UnexpectedEnd();
149
190
  }
150
191
  }
192
+ this.#join();
193
+ }
194
+ // Move every pending chunk into the buffer, copying only when there's more than one piece.
195
+ #join() {
196
+ if (this.#chunks.length === 0)
197
+ return;
198
+ if (this.#buffer.byteLength === 0 && this.#chunks.length === 1) {
199
+ this.#buffer = this.#chunks[0];
200
+ }
201
+ else {
202
+ const joined = new Uint8Array(this.#buffer.byteLength + this.#chunked);
203
+ joined.set(this.#buffer);
204
+ let offset = this.#buffer.byteLength;
205
+ for (const chunk of this.#chunks) {
206
+ joined.set(chunk, offset);
207
+ offset += chunk.byteLength;
208
+ }
209
+ this.#buffer = joined;
210
+ }
211
+ this.#chunks = [];
212
+ this.#chunked = 0;
151
213
  }
152
214
  // Consumes the first size bytes of the buffer.
153
215
  #slice(size) {
@@ -155,113 +217,118 @@ export class Reader {
155
217
  this.#buffer = new Uint8Array(this.#buffer.buffer, this.#buffer.byteOffset + size, this.#buffer.byteLength - size);
156
218
  return result;
157
219
  }
220
+ /**
221
+ * Run a synchronous decode over the buffered bytes and consume what it read.
222
+ *
223
+ * Returns undefined and consumes nothing when the decode ran past the buffered bytes, so a
224
+ * caller can drain every complete message already here without waiting on the stream.
225
+ */
226
+ tryDecode(decode) {
227
+ const result = this.#try(decode);
228
+ return result instanceof Short ? undefined : result;
229
+ }
230
+ /** Run a synchronous decode, filling from the stream until it has the bytes it needs. */
231
+ async decode(decode) {
232
+ for (;;) {
233
+ const result = this.#try(decode);
234
+ if (!(result instanceof Short))
235
+ return result;
236
+ await this.#fillTo(result.need);
237
+ }
238
+ }
239
+ // Like decode, but leaves the bytes buffered for the next read.
240
+ async #peek(decode) {
241
+ for (;;) {
242
+ const result = this.#try(decode, false);
243
+ if (!(result instanceof Short))
244
+ return result;
245
+ await this.#fillTo(result.need);
246
+ }
247
+ }
248
+ /** Like {@link decode}, but returns undefined if the stream ends cleanly first. */
249
+ async decodeMaybe(decode) {
250
+ if (await this.done())
251
+ return undefined;
252
+ return this.decode(decode);
253
+ }
254
+ #try(decode, consume = true) {
255
+ // A retry of the decode that last ran short, before the bytes it needs have arrived,
256
+ // would only throw again. Every decode reads at least a byte, so none can succeed on
257
+ // an empty buffer either.
258
+ const available = this.#buffer.byteLength + this.#chunked;
259
+ if (available === 0)
260
+ return EMPTY;
261
+ if (decode === this.#short?.decode && available < this.#short.err.need)
262
+ return this.#short.err;
263
+ this.#join();
264
+ const cursor = new Cursor(this.#buffer, this.version);
265
+ try {
266
+ const result = decode(cursor);
267
+ if (consume)
268
+ this.#slice(cursor.offset);
269
+ this.#short = undefined;
270
+ return result;
271
+ }
272
+ catch (err) {
273
+ if (!(err instanceof Short))
274
+ throw err;
275
+ // Filling could never satisfy it, so retrying would spin.
276
+ if (err.need <= this.#buffer.byteLength)
277
+ throw new Error("decode ran short of bytes it already had");
278
+ this.#short = { decode, err };
279
+ return err;
280
+ }
281
+ }
158
282
  async read(size) {
159
283
  if (size === 0)
160
284
  return new Uint8Array();
161
- await this.#fillTo(size);
162
- return this.#slice(size);
285
+ return this.decode((c) => c.read(size));
163
286
  }
164
287
  async readAll() {
165
288
  while (await this.#fill()) {
166
289
  // keep going
167
290
  }
291
+ this.#join();
168
292
  return this.#slice(this.#buffer.byteLength);
169
293
  }
294
+ // Reads to the end of the stream, dropping every byte instead of buffering it.
295
+ async discard() {
296
+ this.#buffer = new Uint8Array();
297
+ do {
298
+ this.#chunks = [];
299
+ this.#chunked = 0;
300
+ } while (await this.#fill());
301
+ }
170
302
  async string() {
171
- const length = await this.u53();
172
- const buffer = await this.read(length);
173
- return decodeUtf8(buffer);
303
+ return this.decode(STRING);
174
304
  }
175
305
  async bool() {
176
- const v = await this.u8();
177
- if (v === 0)
178
- return false;
179
- if (v === 1)
180
- return true;
181
- throw new Error("invalid bool value");
306
+ return this.decode(BOOL);
182
307
  }
183
308
  async u8() {
184
- await this.#fillTo(1);
185
- return this.#slice(1)[0];
309
+ return this.decode(U8);
186
310
  }
187
311
  async u16() {
188
- await this.#fillTo(2);
189
- const view = new DataView(this.#buffer.buffer, this.#buffer.byteOffset, 2);
190
- const result = view.getUint16(0);
191
- this.#slice(2);
192
- return result;
312
+ return this.decode(U16);
193
313
  }
194
314
  // Returns a Number using 53-bits, the max Javascript can use for integer math.
195
315
  async u53() {
196
- const v = await this.u62();
197
- if (v > Varint.MAX_U53) {
198
- throw new Error(`value larger than 53-bits: ${v.toString()}`);
199
- }
200
- return Number(v);
316
+ return this.decode(U53);
201
317
  }
202
318
  // NOTE: Returns a bigint instead of a number since it may be larger than 53-bits
203
319
  async u62() {
204
- if (isLeadingOnes(this.version)) {
205
- return this.#readLeadingOnes();
206
- }
207
- return this.#readQuicVarint();
208
- }
209
- async #readQuicVarint() {
210
- await this.#fillTo(1);
211
- const size = (this.#buffer[0] & 0xc0) >> 6;
212
- if (size === 0) {
213
- const first = this.#slice(1)[0];
214
- return BigInt(first) & 0x3fn;
215
- }
216
- if (size === 1) {
217
- await this.#fillTo(2);
218
- const slice = this.#slice(2);
219
- const view = new DataView(slice.buffer, slice.byteOffset, slice.byteLength);
220
- return BigInt(view.getUint16(0)) & 0x3fffn;
221
- }
222
- if (size === 2) {
223
- await this.#fillTo(4);
224
- const slice = this.#slice(4);
225
- const view = new DataView(slice.buffer, slice.byteOffset, slice.byteLength);
226
- return BigInt(view.getUint32(0)) & 0x3fffffffn;
227
- }
228
- await this.#fillTo(8);
229
- const slice = this.#slice(8);
230
- const view = new DataView(slice.buffer, slice.byteOffset, slice.byteLength);
231
- return view.getBigUint64(0) & 0x3fffffffffffffffn;
232
- }
233
- async #readLeadingOnes() {
234
- await this.#fillTo(1);
235
- const b = this.#buffer[0];
236
- // Count leading 1-bits
237
- let ones = 0;
238
- for (let bit = 7; bit >= 0; bit--) {
239
- if (b & (1 << bit))
240
- ones++;
241
- else
242
- break;
243
- }
244
- // 1111110x is a 7-byte form. Draft-17 rejects it; draft-18+ allows it per #1595.
245
- if (ones === 6 && this.version === Version.DRAFT_17) {
246
- throw new Error("invalid leading-ones varint: 1111110x prefix is reserved on draft-17");
247
- }
248
- let totalSize;
249
- if (ones <= 5)
250
- totalSize = ones + 1;
251
- else if (ones === 6)
252
- totalSize = 7;
253
- else if (ones === 7)
254
- totalSize = 8;
255
- else
256
- totalSize = 9; // ones === 8
257
- await this.#fillTo(totalSize);
258
- const slice = this.#slice(totalSize);
259
- const [value] = Varint.decodeLeadingOnes(slice);
260
- return value;
320
+ return this.decode(U62);
321
+ }
322
+ /** Like {@link u62}, but leaves the varint buffered, so a stream's type can be read twice. */
323
+ async peekU62() {
324
+ return this.#peek(U62);
325
+ }
326
+ async varint() {
327
+ return this.decode(VARINT);
261
328
  }
262
329
  // Returns false if there is more data to read, blocking if it hasn't been received yet.
263
330
  async done() {
264
- if (this.#buffer.byteLength > 0)
331
+ if (this.#buffer.byteLength > 0 || this.#chunked > 0)
265
332
  return false;
266
333
  return !(await this.#fill());
267
334
  }
@@ -272,18 +339,191 @@ export class Reader {
272
339
  // shape depending on which one won. Derived once, so racing it per frame doesn't allocate.
273
340
  get closed() {
274
341
  this.#closed ??= (this.#reader?.closed ?? Promise.resolve()).catch((err) => {
275
- throw fromTransport(err, { version: this.version });
342
+ throw fromTransport(err, { version: asIetf(this.version) });
276
343
  });
277
344
  return this.#closed;
278
345
  }
279
346
  }
347
+ /** The stream ended cleanly partway through a read. */
348
+ export class UnexpectedEnd extends Error {
349
+ constructor() {
350
+ super("unexpected end of stream");
351
+ }
352
+ }
353
+ // Thrown by a Cursor read that runs past the buffered bytes, carrying how many bytes from the
354
+ // start of the buffer the decode needs. Not an Error: it ends every chunk, so it must not
355
+ // capture a stack.
356
+ class Short {
357
+ need;
358
+ constructor(need) {
359
+ this.need = need;
360
+ }
361
+ }
362
+ const EMPTY = new Short(1);
363
+ /**
364
+ * A synchronous view over a {@link Reader}'s buffered bytes, handed to {@link Reader.decode}.
365
+ *
366
+ * A read past the buffered bytes throws an internal signal that the Reader catches: it consumes
367
+ * nothing, fills, and runs the decode again from the start. A decode must therefore not mutate
368
+ * anything before its last read, must not swallow what it throws, and must read at least a byte.
369
+ */
370
+ export class Cursor {
371
+ version;
372
+ #buffer;
373
+ #offset = 0;
374
+ // Resolved once, since every varint read branches on it.
375
+ #leadingOnes;
376
+ // First bytes below this are a whole 1-byte varint, and below this + 0x40 a 2-byte one whose
377
+ // value is the low 6 bits and the next byte. Both formats share that shape; only the bound moves.
378
+ #short;
379
+ // First bytes below this are a varint of at most 4 bytes: 0xc0 for QUIC, 0xf0 for leading-ones.
380
+ #word;
381
+ constructor(buffer, version) {
382
+ this.#buffer = buffer;
383
+ this.version = version;
384
+ this.#leadingOnes = isLeadingOnes(version);
385
+ this.#short = this.#leadingOnes ? 0x80 : 0x40;
386
+ this.#word = this.#leadingOnes ? 0xf0 : 0xc0;
387
+ }
388
+ /** How many bytes have been read. */
389
+ get offset() {
390
+ return this.#offset;
391
+ }
392
+ /** How many buffered bytes are left to read. */
393
+ get remaining() {
394
+ return this.#buffer.byteLength - this.#offset;
395
+ }
396
+ /**
397
+ * Decode the next `size` bytes on their own. Running past them, or leaving any unread, is
398
+ * malformed rather than a reason to wait for more.
399
+ */
400
+ exact(size, decode) {
401
+ const inner = new Cursor(this.read(size), this.version);
402
+ let result;
403
+ try {
404
+ result = decode(inner);
405
+ }
406
+ catch (err) {
407
+ if (err instanceof Short)
408
+ throw new Error(`message is shorter than its fields: ${size} bytes`);
409
+ throw err;
410
+ }
411
+ if (inner.remaining > 0)
412
+ throw new Error(`message has ${inner.remaining} unread bytes`);
413
+ return result;
414
+ }
415
+ #ensure(size) {
416
+ const need = this.#offset + size;
417
+ // Checked here too, and on the whole decode like the fill, since bytes that are already
418
+ // buffered never reach the fill.
419
+ if (need > MAX_READ_SIZE)
420
+ throw new Error(`read size ${need} exceeds max size ${MAX_READ_SIZE}`);
421
+ if (need > this.#buffer.byteLength)
422
+ throw new Short(need);
423
+ }
424
+ /** Read `size` bytes, as a view onto the buffer rather than a copy. */
425
+ read(size) {
426
+ this.#ensure(size);
427
+ const start = this.#offset;
428
+ this.#offset += size;
429
+ return this.#buffer.subarray(start, this.#offset);
430
+ }
431
+ string() {
432
+ return decodeUtf8(this.read(this.u53()));
433
+ }
434
+ bool() {
435
+ const v = this.u8();
436
+ if (v === 0)
437
+ return false;
438
+ if (v === 1)
439
+ return true;
440
+ throw new Error("invalid bool value");
441
+ }
442
+ u8() {
443
+ this.#ensure(1);
444
+ return this.#buffer[this.#offset++];
445
+ }
446
+ u16() {
447
+ this.#ensure(2);
448
+ const b = this.#buffer;
449
+ const o = this.#offset;
450
+ this.#offset += 2;
451
+ return (b[o] << 8) | b[o + 1];
452
+ }
453
+ /** Read a varint as a `number`, throwing if it is above `Number.MAX_SAFE_INTEGER`. */
454
+ u53() {
455
+ // Most varints are 1 or 2 bytes, which skip the general decode.
456
+ this.#ensure(1);
457
+ const b = this.#buffer;
458
+ const o = this.#offset;
459
+ const first = b[o];
460
+ if (first < this.#short) {
461
+ this.#offset = o + 1;
462
+ return first;
463
+ }
464
+ if (first < this.#short + 0x40) {
465
+ this.#ensure(2);
466
+ this.#offset = o + 2;
467
+ return ((first & 0x3f) << 8) | b[o + 1];
468
+ }
469
+ // Up to 4 bytes still fits 28 (leading-ones) or 30 (QUIC) bits, with no upper half.
470
+ if (first < this.#word) {
471
+ const size = this.#leadingOnes ? peekLeadingOnes(first) : 4;
472
+ this.#ensure(size);
473
+ this.#offset = o + size;
474
+ if (size === 3)
475
+ return ((first & 0x1f) << 16) | (b[o + 1] << 8) | b[o + 2];
476
+ return ((first & (this.#leadingOnes ? 0x0f : 0x3f)) << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3];
477
+ }
478
+ const lo = this.#varint();
479
+ return toNumber(parts.hi, lo);
480
+ }
481
+ /** Read a varint as a bigint. A leading-ones varint may exceed 62 bits. */
482
+ u62() {
483
+ const lo = this.#varint();
484
+ return toBigInt(parts.hi, lo);
485
+ }
486
+ /** Read a varint. */
487
+ varint() {
488
+ const lo = this.#varint();
489
+ return new U64(parts.hi, lo);
490
+ }
491
+ // Decode the next varint in the version's format, returning its lower half and leaving the upper in `parts`.
492
+ #varint() {
493
+ this.#ensure(1);
494
+ const b = this.#buffer;
495
+ const o = this.#offset;
496
+ let size;
497
+ if (this.#leadingOnes) {
498
+ size = peekLeadingOnes(b[o]);
499
+ // 1111110x is a 7-byte form. Draft-17 rejects it; draft-18+ allows it per #1595.
500
+ if (size === 7 && this.version === Version.DRAFT_17) {
501
+ throw new Error("invalid leading-ones varint: 1111110x prefix is reserved on draft-17");
502
+ }
503
+ this.#ensure(size);
504
+ this.#offset += size;
505
+ return readLeadingOnes(b, o, size);
506
+ }
507
+ size = peekQuic(b[o]);
508
+ this.#ensure(size);
509
+ this.#offset += size;
510
+ return readQuic(b, o, size);
511
+ }
512
+ }
513
+ // Shared decodes for the Reader's async primitives, so a read allocates no closure.
514
+ const STRING = (c) => c.string();
515
+ const BOOL = (c) => c.bool();
516
+ const U8 = (c) => c.u8();
517
+ const U16 = (c) => c.u16();
518
+ const U53 = (c) => c.u53();
519
+ const U62 = (c) => c.u62();
520
+ const VARINT = (c) => c.varint();
280
521
  // Writer wraps a stream and writes chunks of data
281
522
  export class Writer {
282
523
  #writer;
283
524
  #stream;
284
525
  #closed;
285
- // Scratch buffer for writing varints.
286
- // Fixed at 9 bytes (leading-ones max).
526
+ // Scratch buffer for each primitive write, sized for the longest (a 9-byte leading-ones varint).
287
527
  #scratch;
288
528
  version;
289
529
  constructor(stream, version) {
@@ -321,7 +561,7 @@ export class Writer {
321
561
  if (Math.abs(v) > MAX_U31) {
322
562
  throw new Error(`overflow, value larger than 32-bits: ${v.toString()}`);
323
563
  }
324
- // We don't use a VarInt, so it always takes 4 bytes.
564
+ // We don't use a varint, so it always takes 4 bytes.
325
565
  // This could be improved but nothing is standardized yet.
326
566
  await this.write(setInt32(this.#scratch, v));
327
567
  }
@@ -329,26 +569,23 @@ export class Writer {
329
569
  if (!Number.isSafeInteger(v) || v < 0) {
330
570
  throw new RangeError(`invalid u53: ${v}`);
331
571
  }
332
- if (isLeadingOnes(this.version)) {
333
- await this.write(Varint.encodeLeadingOnesTo(this.#scratch, v));
334
- }
335
- else {
336
- await this.write(Varint.encodeTo(this.#scratch, v));
337
- }
572
+ await this.#varint(Math.floor(v / POW32), v >>> 0);
338
573
  }
339
574
  async u62(v) {
340
- if (isLeadingOnes(this.version)) {
341
- await this.write(Varint.encodeLeadingOnesTo(this.#scratch, v));
342
- }
343
- else {
344
- await this.write(Varint.encodeTo(this.#scratch, v));
345
- }
575
+ const lo = split(v);
576
+ await this.#varint(parts.hi, lo);
577
+ }
578
+ async varint(v) {
579
+ await this.#varint(v.hi, v.lo);
580
+ }
581
+ #varint(hi, lo) {
582
+ return this.write(encodeTo(this.#scratch, hi, lo, this.version));
346
583
  }
347
584
  async write(v) {
348
585
  // Mirrors Reader.#fill: every write funnels through here, so a STOP_SENDING from the
349
586
  // peer surfaces as a typed code rather than the transport's own error shape.
350
587
  await this.#writer.write(v).catch((err) => {
351
- throw fromTransport(err, { version: this.version });
588
+ throw fromTransport(err, { version: asIetf(this.version) });
352
589
  });
353
590
  }
354
591
  async string(str) {
@@ -363,7 +600,7 @@ export class Writer {
363
600
  // typed code it would get from a write.
364
601
  get closed() {
365
602
  this.#closed ??= this.#writer.closed.catch((err) => {
366
- throw fromTransport(err, { version: this.version });
603
+ throw fromTransport(err, { version: asIetf(this.version) });
367
604
  });
368
605
  return this.#closed;
369
606
  }
@@ -378,7 +615,7 @@ export class Writer {
378
615
  */
379
616
  static async open(quic, options) {
380
617
  const writable = await openWithin(quic.createUnidirectionalStream(sendOptions(options)), options?.timeout ?? OPEN_TIMEOUT_MS, (stream) => void stream.abort().catch(() => void 0));
381
- return new Writer(writable, options?.version);
618
+ return new Writer(writable, options.version);
382
619
  }
383
620
  /**
384
621
  * Like {@link Writer.open}, but gives up when `cancel` settles or `timeout` elapses,