moqtail 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +153 -473
  2. package/dist/{client-BviQ20Lc.cjs → client-DQ5aGbLR.cjs} +1089 -1074
  3. package/dist/client-DUzLw_Y8.d.cts +1932 -0
  4. package/dist/{client-zi0lmuIL.mjs → client-DVi4Nh1J.mjs} +930 -921
  5. package/dist/client-epHqMdHm.d.mts +1932 -0
  6. package/dist/client.cjs +121 -4
  7. package/dist/client.d.cts +23 -1944
  8. package/dist/client.d.mts +23 -1944
  9. package/dist/client.mjs +117 -2
  10. package/dist/emitter-UbeRcbuf.mjs +109 -0
  11. package/dist/{logger-c2NoQqtx.cjs → emitter-qNJYD3yQ.cjs} +61 -2
  12. package/dist/index-B-BMK-b6.d.mts +2090 -0
  13. package/dist/index-BtemTtwe.d.cts +2090 -0
  14. package/dist/{index-BY6e1obL.d.cts → index-CNn9BgO6.d.mts} +119 -324
  15. package/dist/index.cjs +38 -34
  16. package/dist/index.d.cts +20 -4
  17. package/dist/index.d.mts +20 -4
  18. package/dist/index.mjs +5 -4
  19. package/dist/logger-B8IYkljn.d.cts +64 -0
  20. package/dist/logger-B8IYkljn.d.mts +64 -0
  21. package/dist/model.cjs +122 -340
  22. package/dist/model.d.cts +2896 -2
  23. package/dist/model.d.mts +17 -2
  24. package/dist/model.mjs +122 -340
  25. package/dist/player/component.cjs +317 -0
  26. package/dist/player/component.d.cts +50 -0
  27. package/dist/player/component.d.mts +50 -0
  28. package/dist/player/component.mjs +315 -0
  29. package/dist/player-CJayEzwt.cjs +6750 -0
  30. package/dist/player-DcctWhyM.mjs +6599 -0
  31. package/dist/player.cjs +27 -0
  32. package/dist/player.d.cts +17 -0
  33. package/dist/player.d.mts +17 -0
  34. package/dist/player.mjs +1 -0
  35. package/dist/rolldown-runtime-CmQyd0Gu.cjs +27 -0
  36. package/dist/util.cjs +9 -10
  37. package/dist/util.d.cts +20 -13
  38. package/dist/util.d.mts +20 -13
  39. package/dist/util.mjs +4 -6
  40. package/package.json +45 -5
  41. package/dist/index-BY6e1obL.d.mts +0 -3087
  42. package/dist/logger-ByDB8lYF.mjs +0 -56
  43. package/dist/logger-dEoueCj7.d.cts +0 -35
  44. package/dist/logger-dEoueCj7.d.mts +0 -35
@@ -1,8 +1,123 @@
1
- import { ByteBuffer, CombinedFilter, ControlMessage, ControlMessageType, Datagram, Fetch, FetchHeader, FetchObject, FetchOk, Forward, FrozenByteBuffer, FullTrackName, GoAway, GroupOrderParam, Header, InternalError, InvalidFilterError, LargestObject, Location, LocationFilter, MOQtailError, MaxFilterRanges, MessageParameter, MoqtObject, Namespace, NamespaceDone, NotEnoughBytesError, ProtocolViolationError, Publish, PublishDone, PublishNamespace, PublishSkipped, ReasonPhrase, RequestError, RequestIdMap, RequestOk, RequestUpdate, SUPPORTED_VERSIONS, Setup, SetupOptions, StreamResetCode, SubgroupHeader, SubgroupHeaderType, SubgroupObject, Subscribe, SubscribeNamespace, SubscribeOk, SubscribeTracks, SubscriberPriority, SwitchFrom, TerminationError, TimeoutError, Timestamp, TrackStatus, applyMessageParameterUpdate, assertNoAuthorityOverWebTransport, resolveTransportUrl } from "./model.mjs";
2
- import { a as setLogLevel, i as setLogEnabledModules, r as logger } from "./logger-ByDB8lYF.mjs";
3
- //#region src/client/control_stream.ts
1
+ import { ByteBuffer, CombinedFilter, ControlMessage, ControlMessageType, Datagram, Fetch, FetchHeader, FetchObject, FetchOk, Forward, FrozenByteBuffer, FullTrackName, GoAway, GroupOrderParam, Header, InternalError, InvalidFilterError, LargestObject, Location, LocationFilter, MOQtailError, MaxFilterRanges, MessageParameter, MoqtObject, Namespace, NamespaceDone, NotEnoughBytesError, ObjectDatagramType, PriorGroupIdGapProperty, PriorObjectIdGapProperty, ProtocolViolationError, Publish, PublishDone, PublishNamespace, PublishSkipped, ReasonPhrase, RequestError, RequestIdMap, RequestOk, RequestUpdate, SUPPORTED_VERSIONS, Setup, SetupOptions, StreamResetCode, SubgroupHeader, SubgroupHeaderType, SubgroupObject, Subscribe, SubscribeNamespace, SubscribeOk, SubscribeTracks, SubscriberPriority, SwitchFrom, TerminationError, TimeoutError, Timestamp, TrackStatus, applyMessageParameterUpdate, assertNoAuthorityOverWebTransport, findProperty, resolveTransportUrl } from "./model.mjs";
2
+ import { a as setLogEnabledModules, i as logger, o as setLogLevel, t as Emitter } from "./emitter-UbeRcbuf.mjs";
3
+ // src/util/error.ts
4
4
  /**
5
- * Copyright 2025 The MOQtail Authors
5
+ * Copyright 2026 The MOQtail Authors
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ function errorMessage(error) {
20
+ return error instanceof Error ? error.message : String(error);
21
+ }
22
+ // src/client/util/stream_reset.ts
23
+ /**
24
+ * Copyright 2026 The MOQtail Authors
25
+ *
26
+ * Licensed under the Apache License, Version 2.0 (the "License");
27
+ * you may not use this file except in compliance with the License.
28
+ * You may obtain a copy of the License at
29
+ *
30
+ * http://www.apache.org/licenses/LICENSE-2.0
31
+ *
32
+ * Unless required by applicable law or agreed to in writing, software
33
+ * distributed under the License is distributed on an "AS IS" BASIS,
34
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35
+ * See the License for the specific language governing permissions and
36
+ * limitations under the License.
37
+ */
38
+ /**
39
+ * @public
40
+ * The peer reset this stream, or told us to stop sending on it, with a code.
41
+ */
42
+ var PeerStreamResetError = class extends MOQtailError {
43
+ context;
44
+ code;
45
+ constructor(context, code) {
46
+ super(`[${context}] peer reset the stream with ${StreamResetCode[code]} (0x${code.toString(16)})`);
47
+ this.context = context;
48
+ this.code = code;
49
+ }
50
+ };
51
+ /**
52
+ * Stand-in for `WebTransportError` on runtimes that do not define it. Carries the
53
+ * same two fields so {@link streamResetCodeOf} reads either shape.
54
+ */
55
+ var StreamResetError = class extends Error {
56
+ streamErrorCode;
57
+ source = "stream";
58
+ constructor(streamErrorCode) {
59
+ super(`stream reset with code ${streamErrorCode}`);
60
+ this.streamErrorCode = streamErrorCode;
61
+ this.name = "StreamResetError";
62
+ }
63
+ };
64
+ /**
65
+ * @public
66
+ * The reason to hand `writer.abort()` or `reader.cancel()` so the stream is torn down
67
+ * with `code`.
68
+ *
69
+ * WebTransport carries a numeric RESET_STREAM / STOP_SENDING code only when the reason
70
+ * is a `WebTransportError` with `source: 'stream'`; any other value — a string, say —
71
+ * resets with 0, which the peer reads as INTERNAL_ERROR.
72
+ */
73
+ function streamResetReason(code) {
74
+ const ctor = globalThis.WebTransportError;
75
+ const message = `stream reset with code ${code}`;
76
+ if (typeof ctor === "function") {
77
+ const candidates = [() => new ctor({
78
+ streamErrorCode: code,
79
+ message
80
+ }), () => new ctor(message, {
81
+ source: "stream",
82
+ streamErrorCode: code
83
+ })];
84
+ for (const build of candidates) try {
85
+ const error = build();
86
+ if (streamResetCodeOf(error) === code) return error;
87
+ } catch {}
88
+ }
89
+ return new StreamResetError(code);
90
+ }
91
+ /**
92
+ * @public
93
+ * The code the peer reset a stream with, or `undefined` if `error` is not a stream
94
+ * reset or carries a code this draft does not define.
95
+ */
96
+ function streamResetCodeOf(error) {
97
+ const code = error?.streamErrorCode;
98
+ if (typeof code !== "number") return void 0;
99
+ try {
100
+ return StreamResetCode.tryFrom(code);
101
+ } catch {
102
+ return;
103
+ }
104
+ }
105
+ /** The WebTransport session closed under a read or write: expected during shutdown, not a failure. */
106
+ function isSessionClosed(error) {
107
+ return error?.source === "session";
108
+ }
109
+ /**
110
+ * @public
111
+ * Re-types a failed read: a peer reset becomes a {@link PeerStreamResetError} naming
112
+ * the code, anything else is passed through untouched.
113
+ */
114
+ function asStreamResetError(context, error) {
115
+ const code = streamResetCodeOf(error);
116
+ return code === void 0 ? error : new PeerStreamResetError(context, code);
117
+ }
118
+ // src/client/util/timeout.ts
119
+ /**
120
+ * Copyright 2026 The MOQtail Authors
6
121
  *
7
122
  * Licensed under the Apache License, Version 2.0 (the "License");
8
123
  * you may not use this file except in compliance with the License.
@@ -16,7 +131,8 @@ import { a as setLogLevel, i as setLogEnabledModules, r as logger } from "./logg
16
131
  * See the License for the specific language governing permissions and
17
132
  * limitations under the License.
18
133
  */
19
- function withTimeout$1(promise, ms, errorMsg) {
134
+ /** Rejects with `TimeoutError` when `promise` takes longer than `ms`; without `ms` it's `promise` itself. */
135
+ function withTimeout(promise, ms, errorMsg) {
20
136
  if (ms === void 0) return promise;
21
137
  let timeoutId;
22
138
  const timeoutPromise = new Promise((_, reject) => {
@@ -24,16 +140,33 @@ function withTimeout$1(promise, ms, errorMsg) {
24
140
  });
25
141
  return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timeoutId));
26
142
  }
143
+ // src/client/control_stream.ts
144
+ /**
145
+ * Copyright 2025 The MOQtail Authors
146
+ *
147
+ * Licensed under the Apache License, Version 2.0 (the "License");
148
+ * you may not use this file except in compliance with the License.
149
+ * You may obtain a copy of the License at
150
+ *
151
+ * http://www.apache.org/licenses/LICENSE-2.0
152
+ *
153
+ * Unless required by applicable law or agreed to in writing, software
154
+ * distributed under the License is distributed on an "AS IS" BASIS,
155
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
156
+ * See the License for the specific language governing permissions and
157
+ * limitations under the License.
158
+ */
27
159
  /**
28
160
  * Send half of the control plane: a unidirectional stream this endpoint opens and
29
161
  * whose first message must be SETUP.
30
162
  */
31
163
  var ControlSendStream = class {
32
164
  #writer;
33
- onMessageSent;
34
- constructor(writeStream, onMessageSent) {
165
+ #events;
166
+ /** @param events - Receives `messagesent` for every message written. */
167
+ constructor(writeStream, events) {
35
168
  this.#writer = writeStream.getWriter();
36
- if (onMessageSent) this.onMessageSent = onMessageSent;
169
+ this.#events = events;
37
170
  }
38
171
  async send(message) {
39
172
  const msgName = message.constructor.name;
@@ -44,12 +177,12 @@ var ControlSendStream = class {
44
177
  logger.debug("control_stream", `send: writer ready, writing — ${msgName}`);
45
178
  await this.#writer.write(serializedMessage.toUint8Array());
46
179
  logger.debug("control_stream", `send: write complete — ${msgName}`);
47
- if (this.onMessageSent) this.onMessageSent(message);
180
+ this.#events?.emit("messagesent", message);
48
181
  } catch (error) {
49
- const errorMessage = error instanceof Error ? error.message : String(error);
50
- logger.error("control_stream", `send: failed to write ${msgName} — ${errorMessage}`);
182
+ const reason = errorMessage(error);
183
+ logger.error("control_stream", `send: failed to write ${msgName} — ${reason}`);
51
184
  await this.close();
52
- throw new TerminationError(`ControlStream.send: Failed to write message: ${errorMessage}`, 1);
185
+ throw new TerminationError(`ControlStream.send: Failed to write message: ${reason}`, 1);
53
186
  }
54
187
  }
55
188
  async close() {
@@ -67,12 +200,13 @@ var ControlRecvStream = class {
67
200
  #expectedPayloadLength = null;
68
201
  #partialMessageTimeoutMs;
69
202
  #reader;
70
- onMessageReceived;
71
- constructor(readStream, partialMessageTimeoutMs, onMessageReceived) {
203
+ #events;
204
+ /** @param events - Receives `messagereceived` for every message decoded. */
205
+ constructor(readStream, partialMessageTimeoutMs, events) {
72
206
  this.#receiveBuffer = new ByteBuffer();
73
207
  this.#partialMessageTimeoutMs = partialMessageTimeoutMs;
74
208
  this.#reader = readStream.getReader();
75
- if (onMessageReceived) this.onMessageReceived = onMessageReceived;
209
+ this.#events = events;
76
210
  this.stream = new ReadableStream({
77
211
  start: (controller) => this.#ingestLoop(controller),
78
212
  cancel: () => this.close()
@@ -111,14 +245,14 @@ var ControlRecvStream = class {
111
245
  const msg = ControlMessage.deserialize(new FrozenByteBuffer(messageBytes));
112
246
  logger.debug("control_stream", `ingestLoop: deserialized ${msg.constructor.name} (${totalMessageSize}B)`);
113
247
  controller.enqueue(msg);
114
- if (this.onMessageReceived) this.onMessageReceived(msg);
248
+ this.#events?.emit("messagereceived", msg);
115
249
  continue;
116
250
  }
117
251
  this.#expectedPayloadLength = payloadLength;
118
252
  logger.debug("control_stream", `ingestLoop: partial message — have ${this.#receiveBuffer.length}B, need ${totalMessageSize}B, awaiting more data`);
119
253
  const timeoutMessage = `ControlStream: Timeout waiting for partial message data (expected ${payloadLength} bytes)`;
120
254
  let readResult;
121
- if (this.#partialMessageTimeoutMs !== void 0) readResult = await withTimeout$1(this.#reader.read(), this.#partialMessageTimeoutMs, timeoutMessage);
255
+ if (this.#partialMessageTimeoutMs !== void 0) readResult = await withTimeout(this.#reader.read(), this.#partialMessageTimeoutMs, timeoutMessage);
122
256
  else readResult = await this.#reader.read();
123
257
  this.#handleReadResult(readResult);
124
258
  if (readResult.done) {
@@ -129,7 +263,7 @@ var ControlRecvStream = class {
129
263
  if (error instanceof NotEnoughBytesError) {
130
264
  logger.debug("control_stream", "ingestLoop: not enough bytes for header, awaiting more data");
131
265
  let readResult;
132
- if (this.#partialMessageTimeoutMs !== void 0) readResult = await withTimeout$1(this.#reader.read(), this.#partialMessageTimeoutMs, "ControlStream: Timeout waiting for message header");
266
+ if (this.#partialMessageTimeoutMs !== void 0) readResult = await withTimeout(this.#reader.read(), this.#partialMessageTimeoutMs, "ControlStream: Timeout waiting for message header");
133
267
  else readResult = await this.#reader.read();
134
268
  this.#handleReadResult(readResult);
135
269
  if (readResult.done) {
@@ -145,7 +279,7 @@ var ControlRecvStream = class {
145
279
  }
146
280
  }
147
281
  } catch (error) {
148
- logger.error("control_stream", `ingestLoop: unexpected error — ${error instanceof Error ? error.message : String(error)}`);
282
+ if (!isSessionClosed(error)) logger.error("control_stream", `ingestLoop: unexpected error — ${errorMessage(error)}`);
149
283
  controller.error(error);
150
284
  await this.close();
151
285
  } finally {
@@ -193,101 +327,7 @@ var ControlStream = class {
193
327
  await Promise.allSettled([this.#sendHalf.close(), this.#recvHalf.close()]);
194
328
  }
195
329
  };
196
- //#endregion
197
- //#region src/client/util/stream_reset.ts
198
- /**
199
- * Copyright 2026 The MOQtail Authors
200
- *
201
- * Licensed under the Apache License, Version 2.0 (the "License");
202
- * you may not use this file except in compliance with the License.
203
- * You may obtain a copy of the License at
204
- *
205
- * http://www.apache.org/licenses/LICENSE-2.0
206
- *
207
- * Unless required by applicable law or agreed to in writing, software
208
- * distributed under the License is distributed on an "AS IS" BASIS,
209
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
210
- * See the License for the specific language governing permissions and
211
- * limitations under the License.
212
- */
213
- /**
214
- * @public
215
- * The peer reset this stream, or told us to stop sending on it, with a code.
216
- */
217
- var PeerStreamResetError = class extends MOQtailError {
218
- context;
219
- code;
220
- constructor(context, code) {
221
- super(`[${context}] peer reset the stream with ${StreamResetCode[code]} (0x${code.toString(16)})`);
222
- this.context = context;
223
- this.code = code;
224
- }
225
- };
226
- /**
227
- * Stand-in for `WebTransportError` on runtimes that do not define it. Carries the
228
- * same two fields so {@link streamResetCodeOf} reads either shape.
229
- */
230
- var StreamResetError = class extends Error {
231
- streamErrorCode;
232
- source = "stream";
233
- constructor(streamErrorCode) {
234
- super(`stream reset with code ${streamErrorCode}`);
235
- this.streamErrorCode = streamErrorCode;
236
- this.name = "StreamResetError";
237
- }
238
- };
239
- /**
240
- * @public
241
- * The reason to hand `writer.abort()` or `reader.cancel()` so the stream is torn down
242
- * with `code`.
243
- *
244
- * WebTransport carries a numeric RESET_STREAM / STOP_SENDING code only when the reason
245
- * is a `WebTransportError` with `source: 'stream'`; any other value — a string, say —
246
- * resets with 0, which the peer reads as INTERNAL_ERROR.
247
- */
248
- function streamResetReason(code) {
249
- const ctor = globalThis.WebTransportError;
250
- const message = `stream reset with code ${code}`;
251
- if (typeof ctor === "function") {
252
- const candidates = [() => new ctor({
253
- streamErrorCode: code,
254
- message
255
- }), () => new ctor(message, {
256
- source: "stream",
257
- streamErrorCode: code
258
- })];
259
- for (const build of candidates) try {
260
- const error = build();
261
- if (streamResetCodeOf(error) === code) return error;
262
- } catch {}
263
- }
264
- return new StreamResetError(code);
265
- }
266
- /**
267
- * @public
268
- * The code the peer reset a stream with, or `undefined` if `error` is not a stream
269
- * reset or carries a code this draft does not define.
270
- */
271
- function streamResetCodeOf(error) {
272
- const code = error?.streamErrorCode;
273
- if (typeof code !== "number") return void 0;
274
- try {
275
- return StreamResetCode.tryFrom(code);
276
- } catch {
277
- return;
278
- }
279
- }
280
- /**
281
- * @public
282
- * Re-types a failed read: a peer reset becomes a {@link PeerStreamResetError} naming
283
- * the code, anything else is passed through untouched.
284
- */
285
- function asStreamResetError(context, error) {
286
- const code = streamResetCodeOf(error);
287
- return code === void 0 ? error : new PeerStreamResetError(context, code);
288
- }
289
- //#endregion
290
- //#region src/client/request_stream.ts
330
+ // src/client/request_stream.ts
291
331
  /**
292
332
  * Copyright 2025 The MOQtail Authors
293
333
  *
@@ -329,9 +369,10 @@ var RequestStream = class RequestStream {
329
369
  #receiveBuffer;
330
370
  /** Held for the stream's lifetime once {@link next} is first called. */
331
371
  #messageReader;
332
- #hooks;
333
- constructor(biStream, hooks = {}) {
334
- this.#hooks = hooks;
372
+ #events;
373
+ /** @param events - Receives `messagesent` and `messagereceived` for every message on this stream. */
374
+ constructor(biStream, events) {
375
+ this.#events = events;
335
376
  this.#receiveBuffer = new ByteBuffer();
336
377
  this.#reader = biStream.readable.getReader();
337
378
  this.#writer = biStream.writable.getWriter();
@@ -347,10 +388,10 @@ var RequestStream = class RequestStream {
347
388
  * @throws :{@link ProtocolViolationError} If `first` is not one of the seven types
348
389
  * Table 5 marks `First`; those are the only ones allowed to open a request stream.
349
390
  */
350
- static async open(webTransport, first, hooks = {}) {
391
+ static async open(webTransport, first, events) {
351
392
  if (!ControlMessageType.isFirst(first.getType())) throw new ProtocolViolationError("RequestStream.open", `${first.constructor.name} may not open a request stream: only First-marked types can`);
352
393
  const biStream = await webTransport.createBidirectionalStream();
353
- const requestStream = new RequestStream(biStream, hooks);
394
+ const requestStream = new RequestStream(biStream, events);
354
395
  requestStream.first = first;
355
396
  requestStream.openingType = first.getType();
356
397
  await requestStream.send(first);
@@ -374,10 +415,10 @@ var RequestStream = class RequestStream {
374
415
  await this.#writer.ready;
375
416
  await this.#writer.write(serialized.toUint8Array());
376
417
  logger.debug("request_stream", `sent ${message.constructor.name}`);
377
- this.#hooks.onMessageSent?.(message);
418
+ this.#events?.emit("messagesent", message);
378
419
  } catch (error) {
379
420
  await this.close();
380
- const msg = error instanceof Error ? error.message : String(error);
421
+ const msg = errorMessage(error);
381
422
  logger.error("request_stream", `send failed: ${msg}`);
382
423
  throw new TerminationError(`RequestStream.send: Failed to write message: ${msg}`, 1);
383
424
  }
@@ -415,7 +456,7 @@ var RequestStream = class RequestStream {
415
456
  this.#receiveBuffer.commit();
416
457
  const msg = ControlMessage.deserialize(new FrozenByteBuffer(messageBytes));
417
458
  controller.enqueue(msg);
418
- this.#hooks.onMessageReceived?.(msg);
459
+ this.#events?.emit("messagereceived", msg);
419
460
  continue;
420
461
  }
421
462
  const readResult = await this.#reader.read();
@@ -435,7 +476,7 @@ var RequestStream = class RequestStream {
435
476
  }
436
477
  }
437
478
  } catch (error) {
438
- logger.error("request_stream", "ingest loop error", error);
479
+ if (!isSessionClosed(error)) logger.error("request_stream", "ingest loop error", error);
439
480
  controller.error(asStreamResetError("RequestStream", error));
440
481
  await this.close();
441
482
  } finally {
@@ -448,8 +489,7 @@ var RequestStream = class RequestStream {
448
489
  if (readResult.value) this.#receiveBuffer.putBytes(readResult.value);
449
490
  }
450
491
  };
451
- //#endregion
452
- //#region src/client/data_event.ts
492
+ // src/client/data_event.ts
453
493
  /**
454
494
  * Copyright 2026 The MOQtail Authors
455
495
  *
@@ -474,21 +514,24 @@ function locTimestampOf(properties) {
474
514
  }
475
515
  }
476
516
  /**
477
- * Turns one data stream's activity into {@link DataEvent}s. A throwing observer is
478
- * logged and otherwise ignored, so it can never break the stream it watches.
517
+ * Turns one data stream's activity into {@link DataEvent}s, emitted as `dataevent`.
518
+ * A throwing listener can't break the stream: `EventTarget` isolates it. Without an
519
+ * emitter no event is built, since this runs for every object.
479
520
  */
480
521
  var DataStreamReporter = class {
481
- direction;
482
- observer;
483
522
  streamId = ++lastStreamId;
523
+ #direction;
524
+ #events;
525
+ #fullTrackNameOf;
484
526
  #hasEnded = false;
485
- constructor(direction, observer) {
486
- this.direction = direction;
487
- this.observer = observer;
527
+ constructor(direction, events, fullTrackNameOf) {
528
+ this.#direction = direction;
529
+ this.#events = events;
530
+ this.#fullTrackNameOf = fullTrackNameOf;
488
531
  }
489
532
  header(header) {
490
- if (!this.observer) return;
491
- const fullTrackName = this.observer.fullTrackNameOf?.(header);
533
+ if (!this.#events) return;
534
+ const fullTrackName = this.#fullTrackNameOf?.(header);
492
535
  const event = Header.isFetch(header) ? {
493
536
  ...this.#base("header"),
494
537
  stream: "fetch",
@@ -505,7 +548,7 @@ var DataStreamReporter = class {
505
548
  }
506
549
  /** `header` is the stream's own: a subgroup object takes its group and subgroup from it. */
507
550
  object(header, object) {
508
- if (!this.observer) return;
551
+ if (!this.#events) return;
509
552
  let event;
510
553
  if (object instanceof FetchObject) {
511
554
  if (object.kind !== "object") return;
@@ -516,8 +559,6 @@ var DataStreamReporter = class {
516
559
  objectId: object.location.object,
517
560
  payloadLength: object.payload?.byteLength ?? 0
518
561
  };
519
- const locTimestamp = locTimestampOf(object.properties);
520
- if (locTimestamp !== void 0) event.locTimestamp = locTimestamp;
521
562
  } else {
522
563
  if (Header.isFetch(header)) return;
523
564
  event = {
@@ -528,16 +569,16 @@ var DataStreamReporter = class {
528
569
  ...header.subgroupId !== void 0 && { subgroupId: header.subgroupId },
529
570
  ...object.objectStatus !== null && { objectStatus: object.objectStatus }
530
571
  };
531
- const locTimestamp = locTimestampOf(object.properties);
532
- if (locTimestamp !== void 0) event.locTimestamp = locTimestamp;
533
572
  }
573
+ const locTimestamp = locTimestampOf(object.properties);
574
+ if (locTimestamp !== void 0) event.locTimestamp = locTimestamp;
534
575
  this.#emit(event);
535
576
  }
536
577
  /** Reports how the stream ended. Only the first call counts. */
537
578
  end(reason, resetCode) {
538
579
  if (this.#hasEnded) return;
539
580
  this.#hasEnded = true;
540
- if (!this.observer) return;
581
+ if (!this.#events) return;
541
582
  this.#emit({
542
583
  ...this.#base("end"),
543
584
  reason,
@@ -547,21 +588,16 @@ var DataStreamReporter = class {
547
588
  #base(kind) {
548
589
  return {
549
590
  kind,
550
- direction: this.direction,
591
+ direction: this.#direction,
551
592
  streamId: this.streamId,
552
593
  at: performance.now()
553
594
  };
554
595
  }
555
596
  #emit(event) {
556
- try {
557
- this.observer.onDataEvent(event);
558
- } catch (error) {
559
- logger.warn("data_event", "onDataEvent threw", error);
560
- }
597
+ this.#events?.emit("dataevent", event);
561
598
  }
562
599
  };
563
- //#endregion
564
- //#region src/client/data_stream.ts
600
+ // src/client/data_stream.ts
565
601
  /**
566
602
  * Copyright 2025 The MOQtail Authors
567
603
  *
@@ -584,24 +620,27 @@ var SendStream = class SendStream {
584
620
  #writer;
585
621
  #groupOrder;
586
622
  #reporter;
587
- onDataSent;
588
- constructor(header, writer, reporter, onDataSent, groupOrder = 0) {
623
+ #events;
624
+ constructor(header, writer, reporter, events, groupOrder = 0) {
589
625
  this.header = header;
590
- if (onDataSent) this.onDataSent = onDataSent;
626
+ this.#events = events;
591
627
  this.#writer = writer;
592
628
  this.#reporter = reporter;
593
629
  this.#groupOrder = groupOrder;
594
630
  }
595
- /** @param observer - Receives a {@link DataEvent} for the header, each object, and the stream's end. */
596
- static async new(writeStream, header, onDataSent, groupOrder = 0, observer) {
631
+ /**
632
+ * @param events - Receives `datasent` for the header and each object, and a `dataevent` for
633
+ * the header, each object, and the stream's end.
634
+ */
635
+ static async new(writeStream, header, events, groupOrder = 0, fullTrackNameOf) {
597
636
  const writer = writeStream.getWriter();
598
637
  const serializedHeader = header.serialize().toUint8Array();
599
638
  await writer.write(serializedHeader);
600
- if (onDataSent) onDataSent(header);
601
- const reporter = new DataStreamReporter("out", observer);
639
+ events?.emit("datasent", header);
640
+ const reporter = new DataStreamReporter("out", events, fullTrackNameOf);
602
641
  reporter.header(header);
603
642
  logger.debug("data_stream", `SendStream opened type=${header.type}`);
604
- return new SendStream(header, writer, reporter, onDataSent, groupOrder);
643
+ return new SendStream(header, writer, reporter, events, groupOrder);
605
644
  }
606
645
  async write(object) {
607
646
  let serializedObject;
@@ -622,7 +661,7 @@ var SendStream = class SendStream {
622
661
  this.#reporter.end("error");
623
662
  throw error;
624
663
  }
625
- if (this.onDataSent) this.onDataSent(object);
664
+ this.#events?.emit("datasent", object);
626
665
  this.#reporter.object(this.header, object);
627
666
  }
628
667
  async close() {
@@ -639,14 +678,6 @@ var SendStream = class SendStream {
639
678
  this.#reporter.end("reset", code);
640
679
  }
641
680
  };
642
- function withTimeout(promise, ms, errorMsg) {
643
- if (ms === void 0) return promise;
644
- let timeoutId;
645
- const timeoutPromise = new Promise((_, reject) => {
646
- timeoutId = setTimeout(() => reject(new TimeoutError(errorMsg ?? `Timeout after ${ms}ms`)), ms);
647
- });
648
- return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timeoutId));
649
- }
650
681
  var RecvStream = class RecvStream {
651
682
  header;
652
683
  stream;
@@ -655,15 +686,15 @@ var RecvStream = class RecvStream {
655
686
  #internalBuffer;
656
687
  #groupOrder;
657
688
  #reporter;
658
- onDataReceived;
659
- constructor(header, reader, internalBuffer, reporter, partialDataTimeout, onDataReceived, groupOrder = 0) {
689
+ #events;
690
+ constructor(header, reader, internalBuffer, reporter, partialDataTimeout, events, groupOrder = 0) {
660
691
  this.header = header;
661
692
  this.#reader = reader;
662
693
  this.#reporter = reporter;
663
694
  this.#internalBuffer = internalBuffer;
664
695
  this.#partialDataTimeout = partialDataTimeout;
665
696
  this.#groupOrder = groupOrder;
666
- if (onDataReceived) this.onDataReceived = onDataReceived;
697
+ this.#events = events;
667
698
  this.stream = new ReadableStream({
668
699
  start: (controller) => this.#ingestLoop(controller),
669
700
  cancel: (reason) => this.#reader.cancel(reason)
@@ -672,9 +703,10 @@ var RecvStream = class RecvStream {
672
703
  /**
673
704
  * @param resolveGroupOrder - Consulted once the FETCH header names its request, since
674
705
  * Group ID deltas on the stream are signed by the Group Order the request negotiated.
675
- * @param observer - Receives a {@link DataEvent} for the header, each object, and the stream's end.
706
+ * @param events - Receives `datareceived` for the header and each object, and a `dataevent`
707
+ * for the header, each object, and the stream's end.
676
708
  */
677
- static async new(readStream, partialDataTimeout, onDataReceived, resolveGroupOrder, observer) {
709
+ static async new(readStream, partialDataTimeout, events, resolveGroupOrder, fullTrackNameOf) {
678
710
  const reader = readStream.getReader();
679
711
  const internalBuffer = new ByteBuffer();
680
712
  let headerInstance;
@@ -703,12 +735,12 @@ var RecvStream = class RecvStream {
703
735
  reader.releaseLock();
704
736
  throw asStreamResetError("RecvStream.new", error);
705
737
  }
706
- if (onDataReceived) onDataReceived(headerInstance);
707
- const reporter = new DataStreamReporter("in", observer);
738
+ events?.emit("datareceived", headerInstance);
739
+ const reporter = new DataStreamReporter("in", events, fullTrackNameOf);
708
740
  reporter.header(headerInstance);
709
741
  logger.debug("data_stream", `RecvStream opened type=${headerInstance.type}`);
710
742
  const groupOrder = Header.isFetch(headerInstance) && resolveGroupOrder ? resolveGroupOrder(headerInstance) : 0;
711
- return new RecvStream(headerInstance, reader, internalBuffer, reporter, partialDataTimeout, onDataReceived, groupOrder);
743
+ return new RecvStream(headerInstance, reader, internalBuffer, reporter, partialDataTimeout, events, groupOrder);
712
744
  }
713
745
  async #ingestLoop(controller) {
714
746
  try {
@@ -728,7 +760,7 @@ var RecvStream = class RecvStream {
728
760
  }
729
761
  this.#internalBuffer.commit();
730
762
  controller.enqueue(object);
731
- if (this.onDataReceived) this.onDataReceived(object);
763
+ this.#events?.emit("datareceived", object);
732
764
  this.#reporter.object(this.header, object);
733
765
  continue;
734
766
  } catch (e) {
@@ -763,7 +795,7 @@ var RecvStream = class RecvStream {
763
795
  logger.debug("data_stream", `RecvStream reset by peer code=${StreamResetCode[peerReset]}`);
764
796
  this.#reporter.end("reset", peerReset);
765
797
  } else {
766
- logger.error("data_stream", "RecvStream ingest loop error", error);
798
+ if (!isSessionClosed(error)) logger.error("data_stream", "RecvStream ingest loop error", error);
767
799
  this.#reporter.end("error");
768
800
  await this.#reader.cancel(streamResetReason(0)).catch(() => {});
769
801
  }
@@ -776,8 +808,7 @@ var RecvStream = class RecvStream {
776
808
  await this.#reader.cancel(streamResetReason(code)).catch(() => {});
777
809
  }
778
810
  };
779
- //#endregion
780
- //#region src/client/track/content_source.ts
811
+ // src/client/track/content_source.ts
781
812
  var StaticTrackSource = class {
782
813
  cache;
783
814
  constructor(cache) {
@@ -790,6 +821,8 @@ var StaticTrackSource = class {
790
821
  var LiveTrackSource = class {
791
822
  stream;
792
823
  #listeners = /* @__PURE__ */ new Set();
824
+ /** Each listener's queue tail, so done waits for the objects still being delivered. */
825
+ #queues = /* @__PURE__ */ new Map();
793
826
  #doneListeners = /* @__PURE__ */ new Set();
794
827
  #largestLocation;
795
828
  #ingestActive = false;
@@ -817,7 +850,8 @@ var LiveTrackSource = class {
817
850
  } finally {
818
851
  this.#ingestActive = false;
819
852
  this.#reader?.releaseLock();
820
- for (const doneListener of this.#doneListeners) Promise.resolve().then(() => doneListener());
853
+ const drained = Promise.all([...this.#queues.values()].map((tail) => tail()));
854
+ for (const doneListener of this.#doneListeners) drained.then(() => doneListener());
821
855
  }
822
856
  }
823
857
  onNewObject(listener) {
@@ -828,7 +862,11 @@ var LiveTrackSource = class {
828
862
  });
829
863
  };
830
864
  this.#listeners.add(queuedListener);
831
- return () => this.#listeners.delete(queuedListener);
865
+ this.#queues.set(queuedListener, () => queue);
866
+ return () => {
867
+ this.#queues.delete(queuedListener);
868
+ return this.#listeners.delete(queuedListener);
869
+ };
832
870
  }
833
871
  onDone(listener) {
834
872
  this.#doneListeners.add(listener);
@@ -847,8 +885,7 @@ var HybridTrackSource = class {
847
885
  this.live = new LiveTrackSource(stream);
848
886
  }
849
887
  };
850
- //#endregion
851
- //#region src/client/request/publish_namespace.ts
888
+ // src/client/request/publish_namespace.ts
852
889
  /**
853
890
  * Copyright 2026 The MOQtail Authors
854
891
  *
@@ -885,7 +922,7 @@ var PublishNamespaceRequest = class {
885
922
  this._resolve(value);
886
923
  }
887
924
  reject(reason) {
888
- logger.error("request/publish_namespace", `rejected requestId=${this.requestId}`, reason);
925
+ if (!isSessionClosed(reason)) logger.error("request/publish_namespace", `rejected requestId=${this.requestId}`, reason);
889
926
  this._reject(reason);
890
927
  }
891
928
  then(onfulfilled, onrejected) {
@@ -898,25 +935,54 @@ var PublishNamespaceRequest = class {
898
935
  return this.promise.finally(onfinally);
899
936
  }
900
937
  };
901
- //#endregion
902
- //#region src/client/request/fetch.ts
938
+ // src/client/util/object_stream.ts
939
+ /**
940
+ * A request's consumer-facing object stream. The consumer may cancel it while objects are
941
+ * still in flight, so writes after that, or after it closed or errored, are dropped.
942
+ */
943
+ var ObjectStream = class {
944
+ readable;
945
+ #controller;
946
+ #open = true;
947
+ constructor() {
948
+ this.readable = new ReadableStream({
949
+ start: (controller) => {
950
+ this.#controller = controller;
951
+ },
952
+ cancel: () => {
953
+ this.#open = false;
954
+ }
955
+ });
956
+ }
957
+ /** False once closed, cancelled by the consumer, or errored: nothing written is read. */
958
+ get open() {
959
+ return this.#open && this.#controller.desiredSize !== null;
960
+ }
961
+ enqueue(object) {
962
+ if (this.open) this.#controller.enqueue(object);
963
+ }
964
+ close() {
965
+ if (!this.open) return;
966
+ this.#open = false;
967
+ this.#controller.close();
968
+ }
969
+ };
970
+ // src/client/request/fetch.ts
903
971
  var FetchRequest = class {
904
972
  requestId;
905
973
  message;
906
974
  _resolve;
907
975
  _reject;
908
976
  promise;
909
- controller;
910
- stream;
977
+ objects = new ObjectStream();
978
+ stream = this.objects.readable;
911
979
  onEndOfRange;
980
+ orderer;
912
981
  isActive = true;
913
982
  isResolved = false;
914
983
  constructor(message) {
915
984
  this.requestId = message.requestId;
916
985
  this.message = message;
917
- this.stream = new ReadableStream({ start: (controller) => {
918
- this.controller = controller;
919
- } });
920
986
  this.promise = new Promise((resolve, reject) => {
921
987
  this._resolve = resolve;
922
988
  this._reject = reject;
@@ -929,7 +995,7 @@ var FetchRequest = class {
929
995
  this._resolve(value);
930
996
  }
931
997
  reject(reason) {
932
- logger.error("request/fetch", `rejected requestId=${this.requestId}`, reason);
998
+ if (!isSessionClosed(reason)) logger.error("request/fetch", `rejected requestId=${this.requestId}`, reason);
933
999
  this._reject(reason);
934
1000
  }
935
1001
  then(onfulfilled, onrejected) {
@@ -942,8 +1008,7 @@ var FetchRequest = class {
942
1008
  return this.promise.finally(onfinally);
943
1009
  }
944
1010
  };
945
- //#endregion
946
- //#region src/client/types.ts
1011
+ // src/client/types.ts
947
1012
  /**
948
1013
  * Default for {@link MOQtailClientOptions.trackAliasResolutionTimeoutMs}: how long a
949
1014
  * data stream waits for the control message that establishes its track alias.
@@ -963,13 +1028,17 @@ const DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS = 2e3;
963
1028
  */
964
1029
  const DEFAULT_SWITCH_DRAIN_TIMEOUT_MS = 2e3;
965
1030
  /**
1031
+ * Default for {@link MOQtailClientOptions.fillOpenTimeoutMs}: how long after SUBSCRIBE_OK
1032
+ * a fill fetch stream may take to open before ordering stops waiting for it.
1033
+ */
1034
+ const DEFAULT_FILL_OPEN_TIMEOUT_MS = 1e3;
1035
+ /**
966
1036
  * @public
967
1037
  * The MAX_FILTER_RANGES a client advertises when its setup options set none: how
968
1038
  * many Range Filter ranges it applies, in total, for one subscription or fetch.
969
1039
  */
970
1040
  const DEFAULT_MAX_FILTER_RANGES = 32n;
971
- //#endregion
972
- //#region src/client/request/subscribe.ts
1041
+ // src/client/request/subscribe.ts
973
1042
  /**
974
1043
  * Represents an active subscription request in MOQT, implementing `PromiseLike`
975
1044
  * for convenient async resolution when subscription setup succeeds or fails.
@@ -991,14 +1060,24 @@ var SubscribeRequest = class {
991
1060
  * which is where a fill fetch stream stops.
992
1061
  */
993
1062
  fillBoundary;
1063
+ /** A fill fetch stream opened for this subscription. */
1064
+ fillOpened = false;
1065
+ /** Fill fetch streams still delivering. */
1066
+ openFills = 0;
994
1067
  /** EXPIRES from the last SUBSCRIBE_OK or REQUEST_UPDATE_OK, in milliseconds. */
995
1068
  expires;
996
1069
  streamsAccepted = 0n;
997
1070
  expectedStreams;
998
- /** The Subscription managing this request's output stream once switching is involved. */
1071
+ /** The last PUBLISH_DONE received for this request. */
1072
+ publishDone;
1073
+ #finished = Promise.withResolvers();
1074
+ /** Resolves once this request is over, with {@link SubscribeRequest.publishDone}. Never rejects. */
1075
+ done = this.#finished.promise;
1076
+ /** The Subscription that owns this request's consumer stream; it sets itself on construction. */
999
1077
  manager;
1000
- controller;
1001
- stream;
1078
+ objects = new ObjectStream();
1079
+ stream = this.objects.readable;
1080
+ orderer;
1002
1081
  #promise;
1003
1082
  #resolve;
1004
1083
  #reject;
@@ -1013,9 +1092,6 @@ var SubscribeRequest = class {
1013
1092
  const fwd = msg.parameters.find(MessageParameter.isForward);
1014
1093
  this.forward = fwd?.forward ?? true;
1015
1094
  this.subscribeParameters = msg.parameters;
1016
- this.stream = new ReadableStream({ start: (controller) => {
1017
- this.controller = controller;
1018
- } });
1019
1095
  this.#promise = new Promise((resolve, reject) => {
1020
1096
  this.#resolve = resolve;
1021
1097
  this.#reject = reject;
@@ -1036,6 +1112,22 @@ var SubscribeRequest = class {
1036
1112
  if (typeof applyMessageParameterUpdate === "function") applyMessageParameterUpdate(this.subscribeParameters, msg.parameters);
1037
1113
  }
1038
1114
  /**
1115
+ * Puts an object on the consumer stream, through {@link SubscribeRequest.orderer} when
1116
+ * there is one. `previous` is the object before it on the same fill fetch stream.
1117
+ */
1118
+ enqueue(obj, previous) {
1119
+ if (this.orderer) this.orderer.push(obj, previous);
1120
+ else this.output(obj);
1121
+ }
1122
+ /** Writes an object the orderer released, or an unordered one, through the manager. */
1123
+ output(obj) {
1124
+ this.manager.output(this, obj);
1125
+ }
1126
+ /** Ends the request: resolves {@link SubscribeRequest.done}. Later calls do nothing. */
1127
+ finish() {
1128
+ this.#finished.resolve(this.publishDone);
1129
+ }
1130
+ /**
1039
1131
  * Marks this subscription request as canceled.
1040
1132
  */
1041
1133
  unsubscribe() {
@@ -1053,7 +1145,7 @@ var SubscribeRequest = class {
1053
1145
  * Rejects the internal promise with an error/reason.
1054
1146
  */
1055
1147
  reject(reason) {
1056
- logger.error("request/subscribe", `rejected requestId=${this.requestId}`, reason);
1148
+ if (!isSessionClosed(reason)) logger.error("request/subscribe", `rejected requestId=${this.requestId}`, reason);
1057
1149
  this.#reject(reason);
1058
1150
  }
1059
1151
  then(onfulfilled, onrejected) {
@@ -1079,10 +1171,17 @@ var SubscribeRequest = class {
1079
1171
  * subscription is done, or until it has been quiet long enough to say so itself.
1080
1172
  */
1081
1173
  var Subscription = class {
1082
- controller;
1174
+ objects;
1083
1175
  stream;
1084
1176
  /** Oldest first; the last entry is the newest switch target still racing to produce data. */
1085
1177
  #requests;
1178
+ /** Requests {@link Subscription.done} has yet to wait for, oldest first. */
1179
+ #unwaited;
1180
+ /**
1181
+ * Resolves once every tracked request is over, with the newest one's PUBLISH_DONE, or
1182
+ * `undefined` if it ended without one. Never rejects.
1183
+ */
1184
+ done;
1086
1185
  /**
1087
1186
  * Requests a soft switch handed over from, still delivering the tail of what they
1088
1187
  * were told to finish, each with the timer that retires it if it goes quiet.
@@ -1090,6 +1189,8 @@ var Subscription = class {
1090
1189
  #draining = /* @__PURE__ */ new Map();
1091
1190
  /** Switch targets whose handover drains what it supersedes rather than cutting it. */
1092
1191
  #drainsSuperseded = /* @__PURE__ */ new WeakSet();
1192
+ /** The newest request's ordered objects, held while older requests still deliver. */
1193
+ #parked = [];
1093
1194
  /** Set once by `MOQtailClient.switch`; invoked with everything older on cutover. */
1094
1195
  onSuperseded;
1095
1196
  /** Set by the client to decide whether draining a request should continue. */
@@ -1102,9 +1203,19 @@ var Subscription = class {
1102
1203
  drainTimeoutMs = DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
1103
1204
  constructor(initial) {
1104
1205
  this.stream = initial.stream;
1105
- this.controller = initial.controller;
1206
+ this.objects = initial.objects;
1106
1207
  initial.manager = this;
1107
1208
  this.#requests = [initial];
1209
+ this.#unwaited = [initial];
1210
+ this.done = this.#allDone();
1211
+ }
1212
+ async #allDone() {
1213
+ let batch = [];
1214
+ while (this.#unwaited.length > 0) {
1215
+ batch = this.#unwaited.splice(0);
1216
+ await Promise.all(batch.map((request) => request.done));
1217
+ }
1218
+ return batch.at(-1)?.publishDone;
1108
1219
  }
1109
1220
  /** Requests still tracked, oldest first, draining ones last. */
1110
1221
  get requests() {
@@ -1114,6 +1225,10 @@ var Subscription = class {
1114
1225
  get newest() {
1115
1226
  return this.#requests[this.#requests.length - 1];
1116
1227
  }
1228
+ /** More than one request tracked, draining ones included. */
1229
+ get #switching() {
1230
+ return this.#requests.length + this.#draining.size > 1;
1231
+ }
1117
1232
  /**
1118
1233
  * Track a newly issued switch target alongside whatever is still delivering.
1119
1234
  *
@@ -1125,16 +1240,46 @@ var Subscription = class {
1125
1240
  request.manager = this;
1126
1241
  if (drainSuperseded) this.#drainsSuperseded.add(request);
1127
1242
  this.#requests.push(request);
1243
+ this.#unwaited.push(request);
1244
+ this.#updateSwitchState();
1245
+ }
1246
+ /**
1247
+ * Writes an object `request` released. While older requests still deliver, the newest
1248
+ * one's ordered objects wait, so the old track's tail comes first.
1249
+ */
1250
+ output(request, obj) {
1251
+ if (request.orderer && request === this.newest && this.#switching) this.#parked.push(obj);
1252
+ else this.objects.enqueue(obj);
1253
+ }
1254
+ /**
1255
+ * While a switch is in progress no ordering window expires, and once it's over the
1256
+ * parked objects go out first. `left` stopped being tracked.
1257
+ */
1258
+ #updateSwitchState(left = []) {
1259
+ const switching = this.#switching;
1260
+ if (!switching && this.#draining.size === 0) for (const obj of this.#parked.splice(0)) this.objects.enqueue(obj);
1261
+ for (const request of this.requests) if (switching) request.orderer?.suspendWindow("switch");
1262
+ else request.orderer?.resumeWindow("switch");
1263
+ for (const request of left) request.orderer?.resumeWindow("switch");
1264
+ }
1265
+ /** Hands `requests` to `onSuperseded`, which flushes what they still hold, then stops tracking them. */
1266
+ #retire(requests) {
1267
+ this.onSuperseded?.(requests);
1268
+ this.#updateSwitchState(requests);
1128
1269
  }
1129
1270
  /** Stop tracking `request` (e.g. it naturally completed without ever losing/winning a handover). */
1130
1271
  drop(request) {
1131
1272
  this.#clearDrain(request);
1132
1273
  this.#requests = this.#requests.filter((r) => r !== request);
1274
+ this.#updateSwitchState([request]);
1133
1275
  }
1134
1276
  /** Stop tracking everything (used when the whole switch chain is torn down at once). */
1135
1277
  clear() {
1278
+ const left = this.requests;
1136
1279
  for (const request of [...this.#draining.keys()]) this.#clearDrain(request);
1137
1280
  this.#requests = [];
1281
+ this.#parked = [];
1282
+ this.#updateSwitchState(left);
1138
1283
  }
1139
1284
  /** Starts, or on each further object restarts, the quiet period that ends a drain. */
1140
1285
  #keepDraining(request) {
@@ -1142,7 +1287,7 @@ var Subscription = class {
1142
1287
  this.#draining.set(request, setTimeout(() => {
1143
1288
  this.#draining.delete(request);
1144
1289
  logger.debug("Subscription", `drain of request ${request.requestId} ended on silence`);
1145
- this.onSuperseded?.([request]);
1290
+ this.#retire([request]);
1146
1291
  }, this.drainTimeoutMs));
1147
1292
  }
1148
1293
  #clearDrain(request) {
@@ -1159,13 +1304,15 @@ var Subscription = class {
1159
1304
  * Returns `true` if the object was delivered to the caller,
1160
1305
  * `false` if it was not consumed, and client should cancel the stream.
1161
1306
  */
1162
- deliver(request, obj) {
1307
+ deliver(request, obj, previous) {
1163
1308
  if (this.#draining.has(request)) {
1164
- if (this.onDrainDecision?.(request)) {
1309
+ if (this.onDrainDecision(request)) {
1165
1310
  this.#keepDraining(request);
1166
- this.controller.enqueue(obj);
1311
+ request.enqueue(obj, previous);
1167
1312
  return true;
1168
1313
  }
1314
+ this.#clearDrain(request);
1315
+ this.#retire([request]);
1169
1316
  return false;
1170
1317
  }
1171
1318
  if (!this.#requests.includes(request)) {
@@ -1176,14 +1323,13 @@ var Subscription = class {
1176
1323
  const superseded = this.#requests.slice(0, -1);
1177
1324
  this.#requests = [request];
1178
1325
  if (this.#drainsSuperseded.has(request)) for (const old of superseded) this.#keepDraining(old);
1179
- else this.onSuperseded?.(superseded);
1326
+ else this.#retire(superseded);
1180
1327
  }
1181
- this.controller.enqueue(obj);
1328
+ request.enqueue(obj, previous);
1182
1329
  return true;
1183
1330
  }
1184
1331
  };
1185
- //#endregion
1186
- //#region src/client/request/publish.ts
1332
+ // src/client/request/publish.ts
1187
1333
  /**
1188
1334
  * Copyright 2025 The MOQtail Authors
1189
1335
  *
@@ -1220,7 +1366,7 @@ var PublishRequest = class {
1220
1366
  this._resolve(value);
1221
1367
  }
1222
1368
  reject(reason) {
1223
- logger.error("request/publish", `rejected requestId=${this.requestId}`, reason);
1369
+ if (!isSessionClosed(reason)) logger.error("request/publish", `rejected requestId=${this.requestId}`, reason);
1224
1370
  this._reject(reason);
1225
1371
  }
1226
1372
  then(onfulfilled, onrejected) {
@@ -1233,8 +1379,7 @@ var PublishRequest = class {
1233
1379
  return this.promise.finally(onfinally);
1234
1380
  }
1235
1381
  };
1236
- //#endregion
1237
- //#region src/client/request/track_status.ts
1382
+ // src/client/request/track_status.ts
1238
1383
  /**
1239
1384
  * Copyright 2026 The MOQtail Authors
1240
1385
  *
@@ -1271,7 +1416,7 @@ var TrackStatusRequest = class {
1271
1416
  this._resolve(value);
1272
1417
  }
1273
1418
  reject(reason) {
1274
- logger.error("request/track_status", `rejected requestId=${this.requestId}`, reason);
1419
+ if (!isSessionClosed(reason)) logger.error("request/track_status", `rejected requestId=${this.requestId}`, reason);
1275
1420
  this._reject(reason);
1276
1421
  }
1277
1422
  then(onfulfilled, onrejected) {
@@ -1284,8 +1429,7 @@ var TrackStatusRequest = class {
1284
1429
  return this.promise.finally(onfinally);
1285
1430
  }
1286
1431
  };
1287
- //#endregion
1288
- //#region src/client/handler/publish.ts
1432
+ // src/client/handler/publish.ts
1289
1433
  /**
1290
1434
  * Copyright 2025 The MOQtail Authors
1291
1435
  *
@@ -1318,11 +1462,10 @@ const handlerPublish = async (client, msg, stream) => {
1318
1462
  controller: streamController
1319
1463
  };
1320
1464
  client.subscriptions.set(msg.trackAlias, receiver);
1321
- if (client.onPeerPublish) client.onPeerPublish(msg, objects);
1465
+ client.emit("peerpublish", msg, objects);
1322
1466
  await stream.send(new RequestOk());
1323
1467
  };
1324
- //#endregion
1325
- //#region src/client/handler/publish_namespace.ts
1468
+ // src/client/handler/publish_namespace.ts
1326
1469
  /**
1327
1470
  * Copyright 2025 The MOQtail Authors
1328
1471
  *
@@ -1340,11 +1483,10 @@ const handlerPublish = async (client, msg, stream) => {
1340
1483
  */
1341
1484
  const handlerPublishNamespace = async (client, msg, stream) => {
1342
1485
  logger.log("handler/publish_namespace", "namespace", msg.trackNamespace.toUtf8Path());
1343
- if (client.onNamespacePublished) client.onNamespacePublished(msg);
1486
+ client.emit("namespacepublished", msg);
1344
1487
  await stream.send(new RequestOk());
1345
1488
  };
1346
- //#endregion
1347
- //#region src/client/handler/publish_skipped.ts
1489
+ // src/client/handler/publish_skipped.ts
1348
1490
  /**
1349
1491
  * Copyright 2026 The MOQtail Authors
1350
1492
  *
@@ -1364,10 +1506,9 @@ const handlerPublishSkipped = async (client, msg, stream) => {
1364
1506
  const first = stream.first;
1365
1507
  if (!(first instanceof SubscribeTracks)) throw new ProtocolViolationError("handlerPublishSkipped", "PUBLISH_SKIPPED on a stream this side did not open with SUBSCRIBE_TRACKS");
1366
1508
  logger.log("handler/publish_skipped", "prefix", first.trackNamespacePrefix.toUtf8Path(), "suffix", msg.trackNamespaceSuffix.toUtf8Path());
1367
- client.onPeerPublishSkipped?.(first.trackNamespacePrefix, msg);
1509
+ client.emit("peerpublishskipped", first.trackNamespacePrefix, msg);
1368
1510
  };
1369
- //#endregion
1370
- //#region src/client/publication/subgroup.ts
1511
+ // src/client/publication/subgroup.ts
1371
1512
  /**
1372
1513
  * Copyright 2026 The MOQtail Authors
1373
1514
  *
@@ -1429,8 +1570,7 @@ function subgroupHeaderFor(obj, subgroupId, trackAlias, publisherPriority, first
1429
1570
  const explicit = SubgroupHeaderType.hasExplicitSubgroupId(headerType) ? subgroupId : void 0;
1430
1571
  return new SubgroupHeader(headerType, trackAlias, obj.location.group, explicit, publisherPriority);
1431
1572
  }
1432
- //#endregion
1433
- //#region src/client/publication/fetch.ts
1573
+ // src/client/publication/fetch.ts
1434
1574
  /**
1435
1575
  * Copyright 2025 The MOQtail Authors
1436
1576
  *
@@ -1493,7 +1633,7 @@ var FetchPublication = class {
1493
1633
  this.#objects = objects.filter((obj) => obj.location.compare(this.#endLocation) <= 0);
1494
1634
  const writeStream = await this.#client.webTransport.createUnidirectionalStream();
1495
1635
  const header = new FetchHeader(5, this.#requestId);
1496
- this.#sendStream = await SendStream.new(writeStream, header, this.#client.onDataSent, MessageParameter.groupOrderOf(this.#msg.parameters), this.#client.dataStreamObserver(() => this.#track.fullTrackName));
1636
+ this.#sendStream = await SendStream.new(writeStream, header, this.#client, MessageParameter.groupOrderOf(this.#msg.parameters), () => this.#track.fullTrackName);
1497
1637
  const subgroupIds = new SubgroupIds();
1498
1638
  let sent = 0;
1499
1639
  for (const obj of this.#objects) {
@@ -1514,14 +1654,13 @@ var FetchPublication = class {
1514
1654
  } catch (error) {
1515
1655
  if (this.#isCanceled) return;
1516
1656
  await this.#sendStream?.reset(0);
1517
- const message = error instanceof Error ? error.message : String(error);
1657
+ const message = errorMessage(error);
1518
1658
  logger.error("publication/fetch", `publish failed requestId=${this.#requestId}`, message);
1519
1659
  throw new InternalError("FetchPublication.publish", `Failed to publish: ${message}`);
1520
1660
  }
1521
1661
  }
1522
1662
  };
1523
- //#endregion
1524
- //#region src/client/util/validators.ts
1663
+ // src/client/util/validators.ts
1525
1664
  /**
1526
1665
  * Copyright 2026 The MOQtail Authors
1527
1666
  *
@@ -1579,8 +1718,7 @@ function assertWithinFilterRangeLimit(params, limit, context) {
1579
1718
  }
1580
1719
  for (const fill of params.filter(MessageParameter.isFillParameters)) assertWithinFilterRangeLimit(fill.parameters, limit, `${context} (FILL_PARAMETERS)`);
1581
1720
  }
1582
- //#endregion
1583
- //#region src/client/handler/fetch.ts
1721
+ // src/client/handler/fetch.ts
1584
1722
  /**
1585
1723
  * Copyright 2025 The MOQtail Authors
1586
1724
  *
@@ -1630,8 +1768,7 @@ const handlerFetch = async (client, msg, stream) => {
1630
1768
  const response = new FetchOk(false, range.end, [], trackProperties);
1631
1769
  await stream.send(response);
1632
1770
  };
1633
- //#endregion
1634
- //#region src/client/handler/fetch_ok.ts
1771
+ // src/client/handler/fetch_ok.ts
1635
1772
  /**
1636
1773
  * Copyright 2025 The MOQtail Authors
1637
1774
  *
@@ -1658,8 +1795,7 @@ const handlerFetchOk = async (client, msg, _stream, requestId) => {
1658
1795
  request.resolve(msg);
1659
1796
  } else throw new ProtocolViolationError("handlerFetchOk", `FETCH_OK on a stream with no pending fetch request (request id ${requestId})`);
1660
1797
  };
1661
- //#endregion
1662
- //#region src/client/handler/goaway.ts
1798
+ // src/client/handler/goaway.ts
1663
1799
  const handlerGoAway = async (client, msg) => {
1664
1800
  logger.log("handler/goaway", "newSessionUri", msg.newSessionUri, "timeout", msg.timeout);
1665
1801
  if (client.goawayReceived) {
@@ -1667,7 +1803,7 @@ const handlerGoAway = async (client, msg) => {
1667
1803
  return;
1668
1804
  }
1669
1805
  client.goawayReceived = true;
1670
- if (client.onGoaway) client.onGoaway(msg);
1806
+ client.emit("goaway", msg);
1671
1807
  };
1672
1808
  /**
1673
1809
  * GOAWAY on a request stream: the peer is migrating that one request (§10.4). The
@@ -1678,8 +1814,7 @@ const handlerGoAwayOnRequestStream = async (client, msg, _stream, requestId) =>
1678
1814
  logger.log("handler/goaway", `GOAWAY migrating request ${requestId}`, "timeout", msg.timeout);
1679
1815
  await client.migrateRequest(requestId, msg);
1680
1816
  };
1681
- //#endregion
1682
- //#region src/util/simple_lock.ts
1817
+ // src/util/simple_lock.ts
1683
1818
  var SimpleLock = class {
1684
1819
  acquiredLock = false;
1685
1820
  contQueue = [];
@@ -1707,8 +1842,7 @@ var SimpleLock = class {
1707
1842
  });
1708
1843
  }
1709
1844
  };
1710
- //#endregion
1711
- //#region src/client/util/priority.ts
1845
+ // src/client/util/priority.ts
1712
1846
  /**
1713
1847
  * Copyright 2025 The MOQtail Authors
1714
1848
  *
@@ -1730,8 +1864,7 @@ function getTransportPriority(priority) {
1730
1864
  if (priority === 255) return 0;
1731
1865
  return Math.round((255 - priority) * (Number.MAX_SAFE_INTEGER / 255));
1732
1866
  }
1733
- //#endregion
1734
- //#region src/client/publication/subscribe.ts
1867
+ // src/client/publication/subscribe.ts
1735
1868
  /**
1736
1869
  * Copyright 2025 The MOQtail Authors
1737
1870
  *
@@ -1964,7 +2097,7 @@ var SubscribePublication = class {
1964
2097
  const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
1965
2098
  const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
1966
2099
  const header = subgroupHeaderFor(obj, subgroupId ?? obj.location.object, this.#trackAlias, this.#publisherPriority, firstObject);
1967
- const sendStream = await SendStream.new(writeStream, header, this.client.onDataSent, void 0, this.client.dataStreamObserver(() => this.track.fullTrackName));
2100
+ const sendStream = await SendStream.new(writeStream, header, this.client, void 0, () => this.track.fullTrackName);
1968
2101
  this.#streams.set(obj.location.group, sendStream);
1969
2102
  this.#streamsOpened++;
1970
2103
  this.#markGroupSeen(obj.location.group);
@@ -1987,8 +2120,7 @@ var SubscribePublication = class {
1987
2120
  });
1988
2121
  }
1989
2122
  };
1990
- //#endregion
1991
- //#region src/client/handler/subscribe.ts
2123
+ // src/client/handler/subscribe.ts
1992
2124
  /**
1993
2125
  * Copyright 2025 The MOQtail Authors
1994
2126
  *
@@ -2036,8 +2168,7 @@ const handlerSubscribe = async (client, msg, stream) => {
2036
2168
  await stream.send(subscribeOk);
2037
2169
  logger.debug("handler/subscribe", `requestId=${msg.requestId} — SUBSCRIBE_OK sent, publication registered`);
2038
2170
  };
2039
- //#endregion
2040
- //#region src/client/handler/subscribe_namespace.ts
2171
+ // src/client/handler/subscribe_namespace.ts
2041
2172
  /**
2042
2173
  * Copyright 2025 The MOQtail Authors
2043
2174
  *
@@ -2055,11 +2186,10 @@ const handlerSubscribe = async (client, msg, stream) => {
2055
2186
  */
2056
2187
  const handlerSubscribeNamespace = async (client, msg, stream) => {
2057
2188
  logger.log("handler/subscribe_namespace", "namespace", msg.trackNamespacePrefix.toUtf8Path());
2058
- if (client.onPeerSubscribeNamespace) client.onPeerSubscribeNamespace(msg);
2189
+ client.emit("peersubscribenamespace", msg);
2059
2190
  await stream.send(new RequestOk());
2060
2191
  };
2061
- //#endregion
2062
- //#region src/client/handler/subscribe_tracks.ts
2192
+ // src/client/handler/subscribe_tracks.ts
2063
2193
  /**
2064
2194
  * Copyright 2026 The MOQtail Authors
2065
2195
  *
@@ -2091,11 +2221,10 @@ const handlerSubscribeTracks = async (client, msg, stream) => {
2091
2221
  await stream.send(new RequestError(code, 0n, new ReasonPhrase(reason)));
2092
2222
  return;
2093
2223
  }
2094
- if (client.onPeerSubscribeTracks) client.onPeerSubscribeTracks(msg);
2224
+ client.emit("peersubscribetracks", msg);
2095
2225
  await stream.send(new RequestOk());
2096
2226
  };
2097
- //#endregion
2098
- //#region src/client/request/subscribe_namespace.ts
2227
+ // src/client/request/subscribe_namespace.ts
2099
2228
  /**
2100
2229
  * Copyright 2026 The MOQtail Authors
2101
2230
  *
@@ -2132,7 +2261,7 @@ var SubscribeNamespaceRequest = class {
2132
2261
  this._resolve(value);
2133
2262
  }
2134
2263
  reject(reason) {
2135
- logger.error("request/subscribe_namespace", `rejected requestId=${this.requestId}`, reason);
2264
+ if (!isSessionClosed(reason)) logger.error("request/subscribe_namespace", `rejected requestId=${this.requestId}`, reason);
2136
2265
  this._reject(reason);
2137
2266
  }
2138
2267
  then(onfulfilled, onrejected) {
@@ -2145,8 +2274,7 @@ var SubscribeNamespaceRequest = class {
2145
2274
  return this.promise.finally(onfinally);
2146
2275
  }
2147
2276
  };
2148
- //#endregion
2149
- //#region src/client/publication/publish.ts
2277
+ // src/client/publication/publish.ts
2150
2278
  /**
2151
2279
  * @public
2152
2280
  * Manages the proactive publication of MOQT objects from a publisher to the relay.
@@ -2249,14 +2377,14 @@ var PublishPublication = class {
2249
2377
  }
2250
2378
  /**
2251
2379
  * Moves the Forward State: false parks the publication, true resumes it. The
2252
- * application hears about the move through {@link MOQtailClient.onForwardStateChange},
2380
+ * application hears about the move through the client's `forwardstatechange` event,
2253
2381
  * which is where a publisher starts or stops the work behind the track -- a camera
2254
2382
  * and an encoder cost the same whether or not anything is listening.
2255
2383
  */
2256
2384
  setForwardState(forward) {
2257
2385
  if (this.#forward === forward) return;
2258
2386
  this.#forward = forward;
2259
- this.client.onForwardStateChange?.(this.publishMsg.requestId, forward);
2387
+ this.client.emit("forwardstatechange", this.publishMsg.requestId, forward);
2260
2388
  }
2261
2389
  /**
2262
2390
  * Applies a REQUEST_UPDATE the peer sent on this publication's request stream. It
@@ -2330,7 +2458,7 @@ var PublishPublication = class {
2330
2458
  const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
2331
2459
  const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
2332
2460
  const header = subgroupHeaderFor(obj, subgroupId ?? obj.location.object, this.#trackAlias, this.#publisherPriority, firstObject);
2333
- const sendStream = await SendStream.new(writeStream, header, this.client.onDataSent, void 0, this.client.dataStreamObserver(() => this.track.fullTrackName));
2461
+ const sendStream = await SendStream.new(writeStream, header, this.client, void 0, () => this.track.fullTrackName);
2334
2462
  this.#streams.set(obj.location.group, sendStream);
2335
2463
  this.#streamsOpened++;
2336
2464
  this.#markGroupSeen(obj.location.group);
@@ -2339,8 +2467,13 @@ var PublishPublication = class {
2339
2467
  }
2340
2468
  const sendStream = this.#streams.get(obj.location.group);
2341
2469
  await this.#lock.acquire();
2342
- await sendStream.write(obj.tryIntoSubgroupObject());
2343
- await this.#lock.release();
2470
+ try {
2471
+ await sendStream.write(obj.tryIntoSubgroupObject());
2472
+ } catch (err) {
2473
+ logger.warn("publication/publish", "subgroup stream write failed, skipping rest of group", obj.location.group, err);
2474
+ } finally {
2475
+ await this.#lock.release();
2476
+ }
2344
2477
  if (this.latestLocation && this.latestLocation.group !== obj.location.group) {
2345
2478
  const prevGroup = this.latestLocation.group;
2346
2479
  try {
@@ -2369,8 +2502,7 @@ var PublishPublication = class {
2369
2502
  });
2370
2503
  }
2371
2504
  };
2372
- //#endregion
2373
- //#region src/client/handler/subscription_response.ts
2505
+ // src/client/handler/subscription_response.ts
2374
2506
  /**
2375
2507
  * Copyright 2026 The MOQtail Authors
2376
2508
  *
@@ -2407,8 +2539,7 @@ function applySubscriptionResponse(client, request, parameters, trackProperties)
2407
2539
  if (track !== void 0) track.trackProperties = trackProperties;
2408
2540
  }
2409
2541
  }
2410
- //#endregion
2411
- //#region src/client/handler/request_ok.ts
2542
+ // src/client/handler/request_ok.ts
2412
2543
  const handlerRequestOk = async (client, msg, _stream, requestId) => {
2413
2544
  logger.log("handler/request_ok", "received RequestOk for requestId:", requestId);
2414
2545
  const request = client.requests.get(requestId);
@@ -2441,8 +2572,7 @@ const handlerRequestOk = async (client, msg, _stream, requestId) => {
2441
2572
  client.requests.delete(requestId);
2442
2573
  } else throw new ProtocolViolationError("handlerRequestOk", `Request ID ${requestId} matched a pending request, but it does not expect a RequestOk response.`);
2443
2574
  };
2444
- //#endregion
2445
- //#region src/client/handler/request_error.ts
2575
+ // src/client/handler/request_error.ts
2446
2576
  const handlerRequestError = async (client, msg, _stream, requestId) => {
2447
2577
  logger.error("handler/request_error", `received requestId=${requestId} code=${msg.errorCode} reason="${msg.reasonPhrase.phrase}"`);
2448
2578
  const request = client.requests.get(requestId);
@@ -2456,18 +2586,32 @@ const handlerRequestError = async (client, msg, _stream, requestId) => {
2456
2586
  client.requests.delete(requestId);
2457
2587
  }
2458
2588
  };
2459
- //#endregion
2460
- //#region src/client/handler/publish_done.ts
2589
+ // src/client/handler/publish_done.ts
2590
+ /**
2591
+ * Copyright 2025 The MOQtail Authors
2592
+ *
2593
+ * Licensed under the Apache License, Version 2.0 (the "License");
2594
+ * you may not use this file except in compliance with the License.
2595
+ * You may obtain a copy of the License at
2596
+ *
2597
+ * http://www.apache.org/licenses/LICENSE-2.0
2598
+ *
2599
+ * Unless required by applicable law or agreed to in writing, software
2600
+ * distributed under the License is distributed on an "AS IS" BASIS,
2601
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2602
+ * See the License for the specific language governing permissions and
2603
+ * limitations under the License.
2604
+ */
2461
2605
  const handlerPublishDone = async (client, msg, _stream, openingRequestId) => {
2462
- if (client.onPeerPublishDone) client.onPeerPublishDone(msg, openingRequestId);
2606
+ client.emit("peerpublishdone", msg, openingRequestId);
2463
2607
  const request = client.requests.get(openingRequestId);
2464
2608
  if (request instanceof SubscribeRequest) {
2465
2609
  request.expectedStreams = msg.streamCount;
2610
+ request.publishDone = msg;
2466
2611
  client.completeSubscription(request);
2467
2612
  }
2468
2613
  };
2469
- //#endregion
2470
- //#region src/client/handler/subscribe_ok.ts
2614
+ // src/client/handler/subscribe_ok.ts
2471
2615
  /**
2472
2616
  * Copyright 2025 The MOQtail Authors
2473
2617
  *
@@ -2495,8 +2639,7 @@ const handlerSubscribeOk = async (client, msg, _stream, requestId) => {
2495
2639
  throw new ProtocolViolationError("handlerSubscribeOk", "SUBSCRIBE_OK on a stream with no pending subscribe request");
2496
2640
  }
2497
2641
  };
2498
- //#endregion
2499
- //#region src/client/handler/request_update.ts
2642
+ // src/client/handler/request_update.ts
2500
2643
  /**
2501
2644
  * Copyright 2025 The MOQtail Authors
2502
2645
  *
@@ -2586,13 +2729,10 @@ async function failUpdate(client, stream, requestId, errorCode, reason) {
2586
2729
  break;
2587
2730
  case 6:
2588
2731
  case 80:
2589
- case 81:
2590
- await stream.close();
2591
- break;
2732
+ case 81: await stream.close();
2592
2733
  }
2593
2734
  }
2594
- //#endregion
2595
- //#region src/client/handler/track_status.ts
2735
+ // src/client/handler/track_status.ts
2596
2736
  /**
2597
2737
  * Copyright 2025 The MOQtail Authors
2598
2738
  *
@@ -2612,8 +2752,7 @@ const handlerTrackStatus = async (_client, msg, stream) => {
2612
2752
  logger.debug("handler/track_status", `requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2613
2753
  await stream.send(new RequestOk());
2614
2754
  };
2615
- //#endregion
2616
- //#region src/client/handler/handler.ts
2755
+ // src/client/handler/handler.ts
2617
2756
  /**
2618
2757
  * Copyright 2025 The MOQtail Authors
2619
2758
  *
@@ -2631,7 +2770,7 @@ const handlerTrackStatus = async (_client, msg, stream) => {
2631
2770
  */
2632
2771
  /**
2633
2772
  * The control stream carries SETUP and GOAWAY, nothing else. SETUP is
2634
- * consumed by the handshake in {@link MOQtailClient.new}, so GOAWAY is all that reaches
2773
+ * consumed by the handshake in {@link MOQtailClient.init}, so GOAWAY is all that reaches
2635
2774
  * the read loop. Every request type has moved to its own bidi stream — see
2636
2775
  * {@link getHandlerForRequestStreamMessage}.
2637
2776
  */
@@ -2660,8 +2799,7 @@ function getHandlerForRequestStreamMessage(msg) {
2660
2799
  if (msg instanceof PublishDone) return handlerPublishDone;
2661
2800
  if (msg instanceof PublishSkipped) return handlerPublishSkipped;
2662
2801
  }
2663
- //#endregion
2664
- //#region src/client/util/random_id.ts
2802
+ // src/client/util/random_id.ts
2665
2803
  /**
2666
2804
  * Copyright 2025 The MOQtail Authors
2667
2805
  *
@@ -2685,53 +2823,37 @@ function random60bitId() {
2685
2823
  for (const b of buf) id = id << 8n | BigInt(b);
2686
2824
  return id;
2687
2825
  }
2688
- //#endregion
2689
- //#region src/client/datagram_stream.ts
2690
- /**
2691
- * Copyright 2025 The MOQtail Authors
2692
- *
2693
- * Licensed under the Apache License, Version 2.0 (the "License");
2694
- * you may not use this file except in compliance with the License.
2695
- * You may obtain a copy of the License at
2696
- *
2697
- * http://www.apache.org/licenses/LICENSE-2.0
2698
- *
2699
- * Unless required by applicable law or agreed to in writing, software
2700
- * distributed under the License is distributed on an "AS IS" BASIS,
2701
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2702
- * See the License for the specific language governing permissions and
2703
- * limitations under the License.
2704
- */
2826
+ // src/client/datagram_stream.ts
2705
2827
  /**
2706
2828
  * Sends MoqtObjects as WebTransport datagrams.
2707
2829
  * Parallel to SendStream but for datagram-based delivery.
2708
2830
  *
2709
2831
  * @example
2710
2832
  * ```ts
2711
- * const sender = new SendDatagramStream(client.webTransport.datagrams.writable, trackAlias);
2833
+ * const sender = await SendDatagramStream.new(client.webTransport.datagrams.writable, trackAlias);
2712
2834
  * await sender.write(moqtObject);
2713
2835
  * ```
2714
2836
  */
2715
2837
  var SendDatagramStream = class SendDatagramStream {
2716
2838
  #writer;
2717
2839
  #trackAlias;
2718
- onDataSent;
2719
- constructor(writer, trackAlias, onDataSent) {
2840
+ #events;
2841
+ constructor(writer, trackAlias, events) {
2720
2842
  this.#writer = writer;
2721
2843
  this.#trackAlias = trackAlias;
2722
- if (onDataSent) this.onDataSent = onDataSent;
2844
+ this.#events = events;
2723
2845
  }
2724
2846
  /**
2725
2847
  * Create a new datagram sender for a specific track.
2726
2848
  *
2727
2849
  * @param writeStream - WebTransport datagram writable stream
2728
2850
  * @param trackAlias - Track alias for this datagram stream
2729
- * @param onDataSent - Optional callback fired when datagram is sent
2851
+ * @param events - Receives `datagramsent` for each datagram written
2730
2852
  * @returns SendDatagramStream instance
2731
2853
  */
2732
- static async new(writeStream, trackAlias, onDataSent) {
2854
+ static async new(writeStream, trackAlias, events) {
2733
2855
  const writer = writeStream.getWriter();
2734
- return new SendDatagramStream(writer, trackAlias, onDataSent);
2856
+ return new SendDatagramStream(writer, trackAlias, events);
2735
2857
  }
2736
2858
  /**
2737
2859
  * Create a datagram sender using an existing shared writer.
@@ -2739,11 +2861,11 @@ var SendDatagramStream = class SendDatagramStream {
2739
2861
  *
2740
2862
  * @param writer - Existing WritableStreamDefaultWriter
2741
2863
  * @param trackAlias - Track alias for this datagram stream
2742
- * @param onDataSent - Optional callback fired when datagram is sent
2864
+ * @param events - Receives `datagramsent` for each datagram written
2743
2865
  * @returns SendDatagramStream instance
2744
2866
  */
2745
- static fromWriter(writer, trackAlias, onDataSent) {
2746
- return new SendDatagramStream(writer, trackAlias, onDataSent);
2867
+ static fromWriter(writer, trackAlias, events) {
2868
+ return new SendDatagramStream(writer, trackAlias, events);
2747
2869
  }
2748
2870
  /**
2749
2871
  * Write a MoqtObject as a datagram.
@@ -2755,7 +2877,7 @@ var SendDatagramStream = class SendDatagramStream {
2755
2877
  const datagram = object.tryIntoDatagram(this.#trackAlias);
2756
2878
  const serialized = datagram.serialize().toUint8Array();
2757
2879
  logger.log("datagram_stream", `Writing datagram: trackAlias=${this.#trackAlias}, group=${object.location?.group}, obj=${object.location?.object}, size=${serialized.byteLength}`);
2758
- if (this.onDataSent) this.onDataSent(datagram);
2880
+ this.#events?.emit("datagramsent", datagram);
2759
2881
  try {
2760
2882
  await this.#writer.write(serialized);
2761
2883
  logger.log("datagram_stream", `Successfully wrote ${serialized.byteLength} bytes to WebTransport datagram`);
@@ -2777,91 +2899,160 @@ var SendDatagramStream = class SendDatagramStream {
2777
2899
  this.#writer.releaseLock();
2778
2900
  }
2779
2901
  };
2902
+ // src/client/ordering.ts
2903
+ /** IDs before this object in its group that don't exist (moqt-22 Prior Object ID Gap). */
2904
+ const objectGap = (object) => findProperty(object.properties, PriorObjectIdGapProperty)?.gap ?? 0n;
2905
+ /** Group IDs before this object's group that don't exist (moqt-22 Prior Group ID Gap). */
2906
+ const groupGap = (object) => findProperty(object.properties, PriorGroupIdGapProperty)?.gap ?? 0n;
2780
2907
  /**
2781
- * Receives and parses WebTransport datagrams as MoqtObjects.
2782
- * Parallel to RecvStream but for datagram-based delivery.
2783
- *
2784
- * Automatically handles:
2785
- * - Datagram parsing (both payload and status datagrams)
2786
- * - Track alias to full track name resolution
2787
- *
2788
- * @example
2789
- * ```ts
2790
- * const receiver = new RecvDatagramStream(
2791
- * client.webTransport.datagrams.readable,
2792
- * (trackAlias) => client.requestIdMap.getNameByTrackAlias(trackAlias)
2793
- * );
2908
+ * @public
2909
+ * Releases one request's objects in location order, whatever streams or datagrams they
2910
+ * arrived on. An object goes out as soon as its predecessor has; one whose predecessor
2911
+ * is missing waits until the window is exceeded, then everything up to the oldest held
2912
+ * object goes out and the expected locations skipped are reported through `gap`.
2794
2913
  *
2795
- * for await (const object of receiver.stream) {
2796
- * console.log('Received:', object);
2797
- * }
2798
- * ```
2914
+ * Nothing is released yet, so the first object goes out at once only when it starts a
2915
+ * group: a mid-group first object waits for the start of its group, which a fill fetch
2916
+ * stream may still bring.
2799
2917
  */
2800
- var RecvDatagramStream = class RecvDatagramStream {
2801
- stream;
2802
- #reader;
2803
- #trackAliasResolver;
2804
- onDataReceived;
2805
- constructor(reader, trackAliasResolver, onDataReceived) {
2806
- this.#reader = reader;
2807
- this.#trackAliasResolver = trackAliasResolver;
2808
- if (onDataReceived) this.onDataReceived = onDataReceived;
2809
- this.stream = new ReadableStream({
2810
- start: (controller) => this.#ingestLoop(controller),
2811
- cancel: () => this.#reader.cancel()
2812
- });
2813
- }
2814
- /**
2815
- * Create a new datagram receiver.
2816
- *
2817
- * @param readStream - WebTransport datagram readable stream
2818
- * @param trackAliasResolver - Function to resolve track alias to full track name
2819
- * @param onDataReceived - Optional callback fired when datagram is received
2820
- * @returns RecvDatagramStream instance
2821
- */
2822
- static async new(readStream, trackAliasResolver, onDataReceived) {
2823
- const reader = readStream.getReader();
2824
- return new RecvDatagramStream(reader, trackAliasResolver, onDataReceived);
2825
- }
2826
- async #ingestLoop(controller) {
2827
- try {
2828
- while (true) {
2829
- const { done, value: datagramBytes } = await this.#reader.read();
2830
- if (done) {
2831
- controller.close();
2832
- break;
2833
- }
2834
- if (!datagramBytes || datagramBytes.length === 0) continue;
2835
- try {
2836
- const datagram = Datagram.deserialize(new FrozenByteBuffer(datagramBytes));
2837
- if (this.onDataReceived) this.onDataReceived(datagram);
2838
- const fullTrackName = this.#trackAliasResolver(datagram.trackAlias);
2839
- const moqtObject = MoqtObject.fromDatagram(datagram, fullTrackName);
2840
- controller.enqueue(moqtObject);
2841
- } catch (error) {
2842
- logger.warn("datagram_stream", "Failed to parse datagram:", error);
2843
- continue;
2844
- }
2918
+ var ObjectOrderer = class {
2919
+ #ordering;
2920
+ #onRelease;
2921
+ #onGap;
2922
+ #suspended = /* @__PURE__ */ new Set();
2923
+ #held = [];
2924
+ /** The location of the last object released in order. */
2925
+ #released;
2926
+ /** The last Object ID of each group known to be complete. */
2927
+ #ends = /* @__PURE__ */ new Map();
2928
+ #timer;
2929
+ #arrivals = 0;
2930
+ constructor(ordering, onRelease, onGap) {
2931
+ this.#ordering = ordering;
2932
+ this.#onRelease = onRelease;
2933
+ this.#onGap = onGap;
2934
+ }
2935
+ /** Takes an object; `previous` is the object before it on the same fetch stream. */
2936
+ push(object, previous) {
2937
+ if (this.#released && object.location.compare(this.#released) <= 0) {
2938
+ if (this.#ordering.onWindowExceeded !== "drop") this.#onRelease(object);
2939
+ return;
2940
+ }
2941
+ const index = this.#held.findIndex((held) => held.object.location.compare(object.location) >= 0);
2942
+ if (index >= 0 && this.#held[index].object.location.equals(object.location)) return;
2943
+ const entry = {
2944
+ object,
2945
+ previous,
2946
+ at: performance.now(),
2947
+ seq: this.#arrivals++
2948
+ };
2949
+ if (index < 0) this.#held.push(entry);
2950
+ else this.#held.splice(index, 0, entry);
2951
+ this.#drain();
2952
+ this.#expire();
2953
+ }
2954
+ /** While suspended for any reason nothing exceeds the window, so held objects wait for what's missing. */
2955
+ suspendWindow(reason) {
2956
+ if (this.#suspended.has(reason)) return;
2957
+ this.#suspended.add(reason);
2958
+ this.#expire();
2959
+ }
2960
+ /** Resuming the last reason releases at once what waited longer than the window. */
2961
+ resumeWindow(reason) {
2962
+ if (!this.#suspended.delete(reason)) return;
2963
+ this.#expire();
2964
+ }
2965
+ /** A stream carrying the End of Group for `group` ended cleanly with `lastObject`. */
2966
+ endGroup(group, lastObject) {
2967
+ this.#ends.set(group, lastObject);
2968
+ this.#drain();
2969
+ this.#schedule();
2970
+ }
2971
+ /** Releases everything held, in order, and stops the timer. Call before closing the stream. */
2972
+ flush() {
2973
+ this.#clearTimer();
2974
+ while (this.#held.length > 0) this.#force(this.#held.shift());
2975
+ }
2976
+ #drain() {
2977
+ while (this.#held.length > 0 && this.#isNext(this.#held[0])) this.#release(this.#held.shift().object);
2978
+ }
2979
+ #expire() {
2980
+ while (this.#exceeded()) {
2981
+ const oldest = this.#oldest().object.location;
2982
+ while (this.#held[0] && this.#held[0].object.location.compare(oldest) <= 0) this.#force(this.#held.shift());
2983
+ this.#drain();
2984
+ }
2985
+ this.#schedule();
2986
+ }
2987
+ #exceeded() {
2988
+ if (this.#suspended.size > 0 || this.#held.length === 0) return false;
2989
+ const { durationMs, objects } = this.#ordering.window;
2990
+ if (objects !== void 0 && this.#held.length > objects) return true;
2991
+ return durationMs !== void 0 && performance.now() - this.#oldest().at >= durationMs;
2992
+ }
2993
+ #oldest() {
2994
+ return this.#held.reduce((oldest, held) => held.seq < oldest.seq ? held : oldest);
2995
+ }
2996
+ /** One timer, armed only while objects are held, for when the oldest one exceeds the window. */
2997
+ #schedule() {
2998
+ this.#clearTimer();
2999
+ const { durationMs } = this.#ordering.window;
3000
+ if (this.#suspended.size > 0 || durationMs === void 0 || this.#held.length === 0) return;
3001
+ const wait = this.#oldest().at + durationMs - performance.now();
3002
+ this.#timer = setTimeout(() => {
3003
+ try {
3004
+ this.#expire();
3005
+ } catch (error) {
3006
+ logger.debug("ordering", "release after the stream closed", error);
3007
+ this.#held = [];
2845
3008
  }
2846
- } catch (error) {
2847
- controller.error(error);
3009
+ }, Math.max(0, wait));
3010
+ }
3011
+ #clearTimer() {
3012
+ clearTimeout(this.#timer);
3013
+ this.#timer = void 0;
3014
+ }
3015
+ #isNext({ object, previous }) {
3016
+ const last = this.#released;
3017
+ const { group, object: id } = object.location;
3018
+ const sparseObjects = this.#ordering.sparseObjectIds === true;
3019
+ const startsGroup = sparseObjects || id === objectGap(object);
3020
+ if (!last) return startsGroup;
3021
+ if (previous?.equals(last)) return true;
3022
+ if (group === last.group) return sparseObjects || id - 1n - objectGap(object) <= last.object;
3023
+ const followsGroup = this.#ordering.sparseGroupIds === true || group - 1n - groupGap(object) <= last.group;
3024
+ return startsGroup && followsGroup && this.#ends.get(last.group) === last.object;
3025
+ }
3026
+ /** Releases `held` out of turn, reporting the expected locations it skips. */
3027
+ #force(held) {
3028
+ const from = this.#skippedFrom(held);
3029
+ if (from) this.#onGap(from, held.object.location);
3030
+ this.#release(held.object);
3031
+ }
3032
+ /**
3033
+ * The first expected location skipped between the release point and `held`, if any.
3034
+ * A group's missing tail isn't counted: its last ID is unknown.
3035
+ */
3036
+ #skippedFrom({ object, previous }) {
3037
+ const last = this.#released;
3038
+ if (!last || previous?.equals(last)) return void 0;
3039
+ const { group, object: id } = object.location;
3040
+ const sparseObjects = this.#ordering.sparseObjectIds === true;
3041
+ if (group === last.group) return !sparseObjects && id - 1n - objectGap(object) > last.object ? new Location(group, last.object + 1n) : void 0;
3042
+ if (this.#ordering.sparseGroupIds !== true && group - 1n - groupGap(object) > last.group) return new Location(last.group + 1n, 0n);
3043
+ return !sparseObjects && id > objectGap(object) ? new Location(group, 0n) : void 0;
3044
+ }
3045
+ #release(object) {
3046
+ const { group, object: id } = object.location;
3047
+ if (this.#released?.group !== group) {
3048
+ for (const known of this.#ends.keys()) if (known < group) this.#ends.delete(known);
2848
3049
  }
2849
- }
2850
- /**
2851
- * Cancel the datagram reader.
2852
- */
2853
- async cancel() {
2854
- await this.#reader.cancel();
2855
- }
2856
- /**
2857
- * Release the reader lock without canceling.
2858
- */
2859
- releaseLock() {
2860
- this.#reader.releaseLock();
3050
+ this.#released = object.location;
3051
+ if (object.isEndOfGroup()) this.#ends.set(group, id);
3052
+ this.#onRelease(object);
2861
3053
  }
2862
3054
  };
2863
- //#endregion
2864
- //#region src/client/client.ts
3055
+ // src/client/client.ts
2865
3056
  /**
2866
3057
  * Copyright 2025 The MOQtail Authors
2867
3058
  *
@@ -2881,17 +3072,17 @@ var RecvDatagramStream = class RecvDatagramStream {
2881
3072
  * @public
2882
3073
  * Represents a Media Over QUIC Transport (MOQT) client session.
2883
3074
  *
2884
- * Use {@link MOQtailClient.new} to establish a connection and perform MOQT operations such as subscribing to tracks,
2885
- * fetching historical data, announcing tracks for publication, and managing session lifecycle.
2886
- *
2887
- * Once initialized, the client provides high-level methods for MOQT requests and publishing. If a protocol violation
2888
- * occurs, the client will terminate and must be re-initialized.
3075
+ * Construct it, attach listeners with `on()`, then call {@link MOQtailClient.init} to open the
3076
+ * session. Once initialized, the client provides high-level methods for MOQT requests and publishing. If a protocol
3077
+ * violation occurs, the client terminates; a new client is needed to reconnect.
2889
3078
  *
2890
3079
  * ## Usage
2891
3080
  *
2892
3081
  * ### Connect and Subscribe to a Track
2893
3082
  * ```ts
2894
- * const client = await MOQtailClient.new({ url });
3083
+ * const client = new MOQtailClient({ url });
3084
+ * client.on('sessionterminated', (reason) => console.warn('Session ended:', reason));
3085
+ * await client.init();
2895
3086
  * const result = await client.subscribe({
2896
3087
  * fullTrackName,
2897
3088
  * locationFilter: new LocationFilter(LocationFilterType.NextObject),
@@ -2908,7 +3099,8 @@ var RecvDatagramStream = class RecvDatagramStream {
2908
3099
  *
2909
3100
  * ### Publish a namespace for Publishing
2910
3101
  * ```ts
2911
- * const client = await MOQtailClient.new({ url });
3102
+ * const client = new MOQtailClient({ url });
3103
+ * await client.init();
2912
3104
  * const publishNamespaceResult = await client.publishNamespace(["camera", "main"]);
2913
3105
  * if (!(publishNamespaceResult instanceof RequestError)) {
2914
3106
  * // Ready to publish objects under this namespace
@@ -2920,7 +3112,7 @@ var RecvDatagramStream = class RecvDatagramStream {
2920
3112
  * await client.disconnect();
2921
3113
  * ```
2922
3114
  */
2923
- var MOQtailClient = class MOQtailClient {
3115
+ var MOQtailClient = class extends Emitter {
2924
3116
  /**
2925
3117
  * Namespace prefixes (tuples) the peer has requested announce notifications for via SUBSCRIBE_NAMESPACE.
2926
3118
  * Used to decide which locally issued ANNOUNCE messages should be forwarded (future optimization: prefix trie).
@@ -2988,10 +3180,12 @@ var MOQtailClient = class MOQtailClient {
2988
3180
  * stream to close.
2989
3181
  */
2990
3182
  #namespaceRequestIds = /* @__PURE__ */ new Map();
2991
- /** Underlying WebTransport session (set after successful construction in MOQtailClient.new). */
3183
+ /** Underlying WebTransport session (set by {@link MOQtailClient.init}). */
2992
3184
  webTransport;
2993
3185
  /** Validated Setup message the server sent back during handshake (protocol parameters negotiated). */
2994
3186
  #serverSetup;
3187
+ /** Setup message this client sent during handshake. */
3188
+ #clientSetup;
2995
3189
  /** How many filter ranges this client allows the server per request, as advertised in SETUP. */
2996
3190
  #maxFilterRanges = 0n;
2997
3191
  /** Outgoing / incoming control message stream pair. */
@@ -3012,6 +3206,8 @@ var MOQtailClient = class MOQtailClient {
3012
3206
  * retired anyway, if no PUBLISH_DONE ends its drain first.
3013
3207
  */
3014
3208
  switchDrainTimeoutMs = DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
3209
+ /** How long (ms) after SUBSCRIBE_OK a fill fetch stream may take to open before ordering stops waiting for it. */
3210
+ fillOpenTimeoutMs = DEFAULT_FILL_OPEN_TIMEOUT_MS;
3015
3211
  /**
3016
3212
  * Callbacks waiting for a track alias to be registered, keyed by alias. Each entry
3017
3213
  * belongs to a data stream that arrived before the control message naming its alias.
@@ -3019,129 +3215,19 @@ var MOQtailClient = class MOQtailClient {
3019
3215
  #aliasWaiters = /* @__PURE__ */ new Map();
3020
3216
  /** Flag indicating the client has been disconnected/destroyed and cannot accept further API calls. */
3021
3217
  #isDestroyed = false;
3218
+ /** Where {@link MOQtailClient.init} is: it runs once, and only a `ready` client takes requests. */
3219
+ #state = "idle";
3220
+ #options;
3022
3221
  /** Internal monotonically increasing client-assigned request id counter (even/odd parity scheme advances by 2). */
3023
3222
  #dontUseRequestId = 0n;
3024
3223
  /** Active early discard policy; undefined means no per-stream deadline is applied. */
3025
3224
  #earlyDiscardPolicy;
3026
3225
  /**
3027
- * TODO: onNamespaceAnnounced may be a better name
3028
- * Fired when an PUBLISH_NAMESPACE control message is processed for a track namespace.
3029
- * Use to update UI or trigger discovery logic.
3030
- * Discovery event.
3031
- */
3032
- onNamespacePublished;
3033
- /**
3034
- * Fired on GOAWAY reception signaling graceful session wind-down.
3035
- * Use to prepare for disconnect or cleanup.
3036
- * Lifecycle handler.
3037
- */
3038
- onGoaway;
3039
- /**
3040
3226
  * Whether the peer has sent a GOAWAY on the control stream. Once it has, this side
3041
3227
  * should not start new requests; a second one closes the session with
3042
3228
  * PROTOCOL_VIOLATION.
3043
3229
  */
3044
3230
  goawayReceived = false;
3045
- /**
3046
- * Fired if the underlying WebTransport session fails (ready -\> closed prematurely).
3047
- * Use to log or alert on transport errors.
3048
- * Lifecycle/error handler.
3049
- */
3050
- onWebTransportFail;
3051
- /**
3052
- * Fired exactly once when the client transitions to terminated (disconnect).
3053
- * Use to clean up resources or notify user.
3054
- * Lifecycle handler.
3055
- */
3056
- onSessionTerminated;
3057
- /**
3058
- * Invoked after each outbound control message is sent.
3059
- * Use for logging or analytics.
3060
- * Informational event.
3061
- */
3062
- onMessageSent;
3063
- /**
3064
- * Invoked upon receiving each inbound control message before handling.
3065
- * Use for logging or debugging.
3066
- * Informational event.
3067
- */
3068
- onMessageReceived;
3069
- /**
3070
- * Invoked for each decoded data object/header arriving on a uni stream (fetch or subgroup).
3071
- * Use to process or display incoming media/data.
3072
- * Informational event.
3073
- */
3074
- onDataReceived;
3075
- /**
3076
- * Invoked after enqueuing each outbound data object/header.
3077
- * Reserved for future use.
3078
- * Informational event.
3079
- */
3080
- onDataSent;
3081
- /**
3082
- * Invoked for every data stream this client opens or accepts: once for its header, once
3083
- * per object (identity and payload length only), and once when the stream ends.
3084
- * Use for counters and diagnostics.
3085
- * Informational event.
3086
- */
3087
- onDataEvent;
3088
- /**
3089
- * General-purpose error callback for surfaced exceptions not thrown to caller synchronously.
3090
- * Use to log or display errors.
3091
- * Error handler.
3092
- */
3093
- onError;
3094
- /** Invoked for each decoded datagram object/status arriving. */
3095
- onDatagramReceived;
3096
- /** Invoked after enqueuing each outbound datagram object/status. */
3097
- onDatagramSent;
3098
- /** Fired when an inbound PUBLISH control message is received. */
3099
- onPeerPublish;
3100
- /**
3101
- * Fired when an inbound PUBLISH_DONE control message is received. The message names
3102
- * no request of its own, so `requestId` is the request the stream it arrived on
3103
- * opened: for a track the peer pushed, the `requestId` of the {@link Publish} handed
3104
- * to {@link MOQtailClient.onPeerPublish}. It is what says which track just ended.
3105
- */
3106
- onPeerPublishDone;
3107
- /**
3108
- * Fired when the peer moves the Forward State of a track this side is publishing,
3109
- * either in its PUBLISH_OK or in a later REQUEST_UPDATE. `requestId` is the one
3110
- * {@link MOQtailClient.publish} returned.
3111
- *
3112
- * A publication that declared FORWARD=0 sends nothing until this reports `true`, so
3113
- * this is where the work behind the track starts and stops -- leaving a camera and
3114
- * an encoder running for a track nobody is taking costs the same as publishing it.
3115
- */
3116
- onForwardStateChange;
3117
- /** Fired when an inbound SUBSCRIBE_NAMESPACE control message is received. */
3118
- onPeerSubscribeNamespace;
3119
- /**
3120
- * Fired when an inbound SUBSCRIBE_TRACKS control message is received. The PUBLISH
3121
- * sent for each matching track:
3122
- * - states the request's settings as its parameters, from
3123
- * `MessageParameter.publishParametersFor(msg.parameters)`: FORWARD, GROUP_ORDER and
3124
- * the LOCATION_FILTER the subscription starts from, but never the request's
3125
- * AUTHORIZATION_TOKEN;
3126
- * - goes without Track Properties when
3127
- * `MessageParameter.includesProperties(msg.parameters)` is false.
3128
- *
3129
- * A request carrying FILL_PARAMETERS also asks for a fill of what each track has
3130
- * already published. This client cannot open a fill for a pushed track, so such a
3131
- * subscriber gets only the live Objects.
3132
- */
3133
- onPeerSubscribeTracks;
3134
- /**
3135
- * Fired when a PUBLISH_SKIPPED arrives on a {@link MOQtailClient.subscribeTracks}
3136
- * stream: the peer has a matching track but no bidi stream to send its PUBLISH on
3137
- * until its stream limit lifts (§10.20). `prefix` is the prefix this side subscribed
3138
- * with, which is what the message's suffix hangs off.
3139
- */
3140
- onPeerPublishSkipped;
3141
- /** Fired when a NAMESPACE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
3142
- onPeerNamespace;
3143
- /** Fired when a NAMESPACE_DONE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
3144
- onPeerNamespaceDone;
3145
3231
  /** Datagram writer for sending datagrams. */
3146
3232
  #datagramWriter;
3147
3233
  /** Datagram reader for receiving datagrams. */
@@ -3184,9 +3270,13 @@ var MOQtailClient = class MOQtailClient {
3184
3270
  return this.#serverSetup;
3185
3271
  }
3186
3272
  /**
3187
- * How many filter ranges the server allows in one request: its MAX_FILTER_RANGES,
3188
- * or 0 when it sent none, which allows no Range Filter at all.
3273
+ * Gets the setup this client sent during handshake.
3274
+ *
3275
+ * @returns The {@link Setup} instance written first on the control stream.
3189
3276
  */
3277
+ get clientSetup() {
3278
+ return this.#clientSetup;
3279
+ }
3190
3280
  /**
3191
3281
  * How many filter ranges this client allows the server in one request: the
3192
3282
  * MAX_FILTER_RANGES it advertised, {@link DEFAULT_MAX_FILTER_RANGES} unless the
@@ -3227,14 +3317,21 @@ var MOQtailClient = class MOQtailClient {
3227
3317
  setLogEnabledModules(modules);
3228
3318
  }
3229
3319
  /**
3230
- * Guard that throws if the client has been destroyed (disconnect already called). Used at start of public APIs
3231
- * to fail fast rather than perform partial operations on a torn-down session.
3232
- * @throws MOQtailError when #isDestroyed is true.
3320
+ * Guard that throws unless the client is initialized and not yet destroyed. Used at start of public APIs
3321
+ * to fail fast rather than perform partial operations on a session that is not open.
3322
+ * @throws MOQtailError when the client is destroyed or {@link MOQtailClient.init} has not completed.
3233
3323
  */
3234
3324
  #ensureActive() {
3235
3325
  if (this.#isDestroyed) throw new MOQtailError("MOQtailClient is destroyed and cannot be used.");
3326
+ if (this.#state !== "ready") throw new MOQtailError("MOQtailClient is not initialized. Await init() first.");
3236
3327
  }
3237
- constructor() {
3328
+ /**
3329
+ * Stores `options`; nothing happens on the network until {@link MOQtailClient.init}, so
3330
+ * listeners attached in between see everything, the handshake included.
3331
+ */
3332
+ constructor(options) {
3333
+ super();
3334
+ this.#options = options;
3238
3335
  this.receivedDatagramObjects = new ReadableStream({
3239
3336
  start: (controller) => {
3240
3337
  this.#receivedDatagramObjectController = controller;
@@ -3243,43 +3340,24 @@ var MOQtailClient = class MOQtailClient {
3243
3340
  });
3244
3341
  }
3245
3342
  /**
3246
- * Establishes a new {@link MOQtailClient} session over WebTransport and performs the MOQT setup handshake.
3247
- *
3248
- * @param args - {@link MOQtailClientOptions}
3249
- *
3250
- * @returns Promise resolving to a ready {@link MOQtailClient} instance.
3343
+ * Opens the WebTransport session and performs the MOQT setup handshake. Runs once: a
3344
+ * second call throws, and a failed one leaves the client unusable, so a retry needs a
3345
+ * new client.
3251
3346
  *
3347
+ * @throws :{@link MOQtailError} If called more than once, or after {@link MOQtailClient.disconnect}.
3252
3348
  * @throws :{@link ProtocolViolationError} If the server sends an unexpected or invalid message during setup.
3253
3349
  *
3254
- * @example Minimal connection
3255
- * ```ts
3256
- * const client = await MOQtailClient.new({
3257
- * url: 'https://relay.example.com/transport'
3258
- * });
3259
- * ```
3260
- *
3261
- * @example With callbacks and options
3350
+ * @example
3262
3351
  * ```ts
3263
- * const client = await MOQtailClient.new({
3264
- * url,
3265
- * setupOptions: new SetupOptions().addPath('/live'),
3266
- * transportOptions: { congestionControl: 'default' },
3267
- * dataStreamTimeoutMs: 5000,
3268
- * controlStreamTimeoutMs: 2000,
3269
- * trackAliasResolutionTimeoutMs: 2000,
3270
- * enableDatagrams: true,
3271
- * callbacks: {
3272
- * onMessageSent: msg => console.log('Sent:', msg),
3273
- * onMessageReceived: msg => console.log('Received:', msg),
3274
- * onSessionTerminated: reason => console.warn('Session ended:', reason),
3275
- * onDatagramReceived: data => console.log('Datagram:', data),
3276
- * }
3277
- * });
3352
+ * const client = new MOQtailClient({ url: 'https://relay.example.com/transport' })
3353
+ * client.on('messagesent', (msg) => console.log('Sent:', msg))
3354
+ * await client.init()
3278
3355
  * ```
3279
3356
  */
3280
- static async new(args) {
3281
- let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, trackAliasResolutionTimeoutMs, switchDrainTimeoutMs, enableDatagrams, callbacks } = args;
3282
- const client = new MOQtailClient();
3357
+ async init() {
3358
+ if (this.#state !== "idle" || this.#isDestroyed) throw new MOQtailError("MOQtailClient.init may only run once.");
3359
+ this.#state = "initializing";
3360
+ let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, trackAliasResolutionTimeoutMs, switchDrainTimeoutMs, fillOpenTimeoutMs, enableDatagrams } = this.#options;
3283
3361
  if (!transportOptions) transportOptions = { protocols: [] };
3284
3362
  if (!transportOptions.protocols) transportOptions = {
3285
3363
  ...transportOptions,
@@ -3287,51 +3365,48 @@ var MOQtailClient = class MOQtailClient {
3287
3365
  };
3288
3366
  else transportOptions.protocols.push(...SUPPORTED_VERSIONS);
3289
3367
  logger.log("MOQtailClient", "transportOptions", transportOptions);
3290
- const { transportUrl, moqtUrl } = resolveTransportUrl(url);
3291
- if (moqtUrl) {
3292
- logger.log("MOQtailClient", `moqt:// resolved to ${transportUrl}`);
3293
- if (moqtUrl.fragment) logger.log("MOQtailClient", `moqt:// fragment (local-only): ${moqtUrl.fragment.kind}:${moqtUrl.fragment.value}`);
3294
- }
3295
- client.webTransport = new WebTransport(transportUrl, transportOptions);
3296
- await client.webTransport.ready;
3297
3368
  try {
3298
- if (callbacks?.onMessageSent) client.onMessageSent = callbacks.onMessageSent;
3299
- if (callbacks?.onMessageReceived) client.onMessageReceived = callbacks.onMessageReceived;
3300
- if (callbacks?.onSessionTerminated) client.onSessionTerminated = callbacks.onSessionTerminated;
3301
- if (callbacks?.onDatagramReceived) client.onDatagramReceived = callbacks.onDatagramReceived;
3302
- if (callbacks?.onDatagramSent) client.onDatagramSent = callbacks.onDatagramSent;
3303
- if (callbacks?.onDataEvent) client.onDataEvent = callbacks.onDataEvent;
3304
- if (dataStreamTimeoutMs) client.dataStreamTimeoutMs = dataStreamTimeoutMs;
3305
- if (controlStreamTimeoutMs) client.controlStreamTimeoutMs = controlStreamTimeoutMs;
3306
- if (trackAliasResolutionTimeoutMs !== void 0) client.trackAliasResolutionTimeoutMs = trackAliasResolutionTimeoutMs;
3307
- if (switchDrainTimeoutMs !== void 0) client.switchDrainTimeoutMs = switchDrainTimeoutMs;
3308
- const sendHalf = new ControlSendStream(await client.webTransport.createUnidirectionalStream({ sendOrder: Number.MAX_SAFE_INTEGER }), client.onMessageSent);
3369
+ const { transportUrl, moqtUrl } = resolveTransportUrl(url);
3370
+ if (moqtUrl) {
3371
+ logger.log("MOQtailClient", `moqt:// resolved to ${transportUrl}`);
3372
+ if (moqtUrl.fragment) logger.log("MOQtailClient", `moqt:// fragment (local-only): ${moqtUrl.fragment.kind}:${moqtUrl.fragment.value}`);
3373
+ }
3374
+ this.webTransport = new WebTransport(transportUrl, transportOptions);
3375
+ await this.webTransport.ready;
3376
+ if (dataStreamTimeoutMs) this.dataStreamTimeoutMs = dataStreamTimeoutMs;
3377
+ if (controlStreamTimeoutMs) this.controlStreamTimeoutMs = controlStreamTimeoutMs;
3378
+ if (trackAliasResolutionTimeoutMs !== void 0) this.trackAliasResolutionTimeoutMs = trackAliasResolutionTimeoutMs;
3379
+ if (switchDrainTimeoutMs !== void 0) this.switchDrainTimeoutMs = switchDrainTimeoutMs;
3380
+ if (fillOpenTimeoutMs !== void 0) this.fillOpenTimeoutMs = fillOpenTimeoutMs;
3381
+ const sendHalf = new ControlSendStream(await this.webTransport.createUnidirectionalStream({ sendOrder: Number.MAX_SAFE_INTEGER }), this);
3309
3382
  const params = setupOptions ? setupOptions.build() : new SetupOptions().build();
3310
3383
  let maxFilterRanges = params.map((p) => MaxFilterRanges.fromKeyValuePair(p)).find((o) => o !== void 0);
3311
3384
  if (!maxFilterRanges) {
3312
3385
  maxFilterRanges = new MaxFilterRanges(DEFAULT_MAX_FILTER_RANGES);
3313
3386
  params.push(maxFilterRanges.toKeyValuePair());
3314
3387
  }
3315
- client.#maxFilterRanges = maxFilterRanges.value;
3388
+ this.#maxFilterRanges = maxFilterRanges.value;
3316
3389
  assertNoAuthorityOverWebTransport(params);
3317
- await sendHalf.send(new Setup(params));
3318
- client.#incomingUniStreams = client.webTransport.incomingUnidirectionalStreams.getReader();
3319
- const { value: recvStream, done: recvStreamDone } = await client.#incomingUniStreams.read();
3320
- if (recvStreamDone || !recvStream) throw new ProtocolViolationError("MOQtailClient.new", "Session closed before the server control stream");
3321
- client.controlStream = new ControlStream(sendHalf, new ControlRecvStream(recvStream, client.controlStreamTimeoutMs, client.onMessageReceived));
3322
- const reader = client.controlStream.stream.getReader();
3390
+ this.#clientSetup = new Setup(params);
3391
+ await sendHalf.send(this.#clientSetup);
3392
+ this.#incomingUniStreams = this.webTransport.incomingUnidirectionalStreams.getReader();
3393
+ const { value: recvStream, done: recvStreamDone } = await this.#incomingUniStreams.read();
3394
+ if (recvStreamDone || !recvStream) throw new ProtocolViolationError("MOQtailClient.init", "Session closed before the server control stream");
3395
+ const recvHalf = new ControlRecvStream(recvStream, this.controlStreamTimeoutMs, this);
3396
+ this.controlStream = new ControlStream(sendHalf, recvHalf);
3397
+ const reader = this.controlStream.stream.getReader();
3323
3398
  const { value: response, done } = await reader.read();
3324
- if (done) throw new ProtocolViolationError("MOQtailClient.new", "Stream closed after client setup");
3325
- if (!(response instanceof Setup)) throw new ProtocolViolationError("MOQtailClient.new", "Expected setup as the first control message");
3326
- client.#serverSetup = response;
3399
+ if (done) throw new ProtocolViolationError("MOQtailClient.init", "Stream closed after client setup");
3400
+ if (!(response instanceof Setup)) throw new ProtocolViolationError("MOQtailClient.init", "Expected setup as the first control message");
3401
+ this.#serverSetup = response;
3327
3402
  reader.releaseLock();
3328
- client.#handleIncomingControlMessages();
3329
- client.#acceptIncomingUniStreams();
3330
- client.#acceptIncomingBiStreams();
3331
- if (enableDatagrams) await client.startDatagrams();
3332
- return client;
3403
+ this.#state = "ready";
3404
+ this.#handleIncomingControlMessages();
3405
+ this.#acceptIncomingUniStreams();
3406
+ this.#acceptIncomingBiStreams();
3407
+ if (enableDatagrams) await this.startDatagrams();
3333
3408
  } catch (error) {
3334
- await client.disconnect(new InternalError("MOQtailClient.new", error instanceof Error ? error.message : String(error)));
3409
+ await this.disconnect(new InternalError("MOQtailClient.init", errorMessage(error)));
3335
3410
  throw error;
3336
3411
  }
3337
3412
  }
@@ -3349,7 +3424,8 @@ var MOQtailClient = class MOQtailClient {
3349
3424
  }
3350
3425
  logger.log("MOQtailClient", "Starting datagram support...");
3351
3426
  this.#datagramReader = this.webTransport.datagrams.readable.getReader();
3352
- this.#datagramWriter = this.webTransport.datagrams.writable.getWriter();
3427
+ const datagrams = this.webTransport.datagrams;
3428
+ this.#datagramWriter = (datagrams.writable ?? datagrams.createWritable()).getWriter();
3353
3429
  this.#isReceivingDatagrams = true;
3354
3430
  this.#acceptIncomingDatagrams();
3355
3431
  logger.log("MOQtailClient", "Datagram support started");
@@ -3427,7 +3503,7 @@ var MOQtailClient = class MOQtailClient {
3427
3503
  this.#ensureActive();
3428
3504
  if (!this.#datagramWriter) throw new MOQtailError("Datagrams not started. Call startDatagrams() first or set enableDatagrams: true in options.");
3429
3505
  logger.log("MOQtailClient", `Creating datagram sender for trackAlias=${trackAlias}`);
3430
- return SendDatagramStream.fromWriter(this.#datagramWriter, trackAlias, this.onDatagramSent);
3506
+ return SendDatagramStream.fromWriter(this.#datagramWriter, trackAlias, this);
3431
3507
  }
3432
3508
  /**
3433
3509
  * Send a single MoqtObject as a datagram.
@@ -3447,7 +3523,7 @@ var MOQtailClient = class MOQtailClient {
3447
3523
  if (!this.#datagramWriter) throw new MOQtailError("Datagrams not started. Call startDatagrams() first or set enableDatagrams: true in options.");
3448
3524
  const datagram = object.tryIntoDatagram(trackAlias);
3449
3525
  const serialized = datagram.serialize().toUint8Array();
3450
- if (this.onDatagramSent) this.onDatagramSent(datagram);
3526
+ this.emit("datagramsent", datagram);
3451
3527
  await this.#datagramWriter.write(serialized);
3452
3528
  }
3453
3529
  /**
@@ -3470,7 +3546,7 @@ var MOQtailClient = class MOQtailClient {
3470
3546
  try {
3471
3547
  const datagram = Datagram.deserialize(new FrozenByteBuffer(datagramBytes));
3472
3548
  const trackAlias = datagram.trackAlias;
3473
- if (this.onDatagramReceived) this.onDatagramReceived(datagram);
3549
+ this.emit("datagramreceived", datagram);
3474
3550
  const fullTrackName = this.#resolveTrackAlias(trackAlias);
3475
3551
  const moqtObject = MoqtObject.fromDatagram(datagram, fullTrackName);
3476
3552
  const trackKey = trackAlias.toString();
@@ -3480,6 +3556,11 @@ var MOQtailClient = class MOQtailClient {
3480
3556
  } catch (handlerError) {
3481
3557
  logger.warn("MOQtailClient", "Datagram track handler error:", handlerError);
3482
3558
  }
3559
+ const holder = this.subscriptions.get(trackAlias);
3560
+ if (holder instanceof SubscribeRequest && holder.orderer) {
3561
+ if (!holder.largestLocation || holder.largestLocation.compare(moqtObject.location) < 0) holder.largestLocation = moqtObject.location;
3562
+ if (holder.manager.deliver(holder, moqtObject) && ObjectDatagramType.isEndOfGroup(datagram.type)) holder.orderer.endGroup(moqtObject.location.group, moqtObject.location.object);
3563
+ }
3483
3564
  if (this.#receivedDatagramObjectController) try {
3484
3565
  this.#receivedDatagramObjectController.enqueue(moqtObject);
3485
3566
  } catch {}
@@ -3497,6 +3578,22 @@ var MOQtailClient = class MOQtailClient {
3497
3578
  }
3498
3579
  }
3499
3580
  /**
3581
+ * The track a data stream carries. A subgroup stream can open before the response
3582
+ * that names its alias, so its header event may lack `fullTrackName`: ask again on a
3583
+ * later event of the same stream.
3584
+ */
3585
+ trackNameOf(header) {
3586
+ if (header.fullTrackName || header.trackAlias === void 0) return header.fullTrackName;
3587
+ return this.aliasFullTrackNameMap.get(header.trackAlias);
3588
+ }
3589
+ /** A fetch stream is named by its FETCH, or by the SUBSCRIBE it fills. */
3590
+ #streamTrackName(header) {
3591
+ if (header instanceof SubgroupHeader) return this.aliasFullTrackNameMap.get(header.trackAlias);
3592
+ const request = this.requests.get(this.#clientRequestId(header.requestId));
3593
+ if (request instanceof FetchRequest) return request.message.fullTrackName;
3594
+ return request instanceof SubscribeRequest ? request.fullTrackName : void 0;
3595
+ }
3596
+ /**
3500
3597
  * Resolve track alias to the full track name it was claimed for.
3501
3598
  * Falls back to a placeholder if no request holds the alias.
3502
3599
  */
@@ -3529,7 +3626,7 @@ var MOQtailClient = class MOQtailClient {
3529
3626
  * Gracefully terminates this {@link MOQtailClient} session and releases underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} resources.
3530
3627
  *
3531
3628
  * @param reason - Optional application-level reason (string or error) recorded and wrapped in an {@link InternalError}
3532
- * passed to the {@link MOQtailClient.onSessionTerminated | onSessionTerminated} callback.
3629
+ * passed to `sessionterminated` listeners. Before {@link MOQtailClient.init} it only marks the client destroyed.
3533
3630
  *
3534
3631
  * @returns Promise that resolves once shutdown logic completes. Subsequent calls are safe no-ops.
3535
3632
  *
@@ -3560,13 +3657,15 @@ var MOQtailClient = class MOQtailClient {
3560
3657
  logger.log("MOQtailClient", "disconnect", reason);
3561
3658
  if (this.#isDestroyed) return;
3562
3659
  this.#isDestroyed = true;
3660
+ if (this.#state === "idle") return;
3563
3661
  await this.stopDatagrams();
3564
3662
  const openStreams = [...this.#requestStreams.values()];
3565
3663
  this.#requestStreams.clear();
3566
3664
  this.#namespaceRequestIds.clear();
3567
3665
  await Promise.allSettled(openStreams.map((requestStream) => requestStream.close()));
3568
- this.webTransport.close();
3569
- if (this.onSessionTerminated) this.onSessionTerminated(new InternalError("MOQtailClient.disconnect", reason instanceof Error ? reason.message : String(reason)));
3666
+ for (const request of this.requests.values()) if (request instanceof SubscribeRequest) request.finish();
3667
+ this.webTransport?.close();
3668
+ this.emit("sessionterminated", new InternalError("MOQtailClient.disconnect", errorMessage(reason)));
3570
3669
  }
3571
3670
  /**
3572
3671
  * Registers or updates a {@link Track} definition for local publishing or serving.
@@ -3597,7 +3696,7 @@ var MOQtailClient = class MOQtailClient {
3597
3696
  * });
3598
3697
  *
3599
3698
  * // For a hybrid track (live + past):
3600
- * import { MemoryObjectCache } from './track/object_cache';
3699
+ * import { MemoryObjectCache } from '@/client/track/object_cache';
3601
3700
  * const cache = new MemoryObjectCache(); // Caches are not yet fully supported
3602
3701
  * client.addOrUpdateTrack({
3603
3702
  * fullTrackName: { namespace: ["camera"], name: "main" },
@@ -3650,11 +3749,12 @@ var MOQtailClient = class MOQtailClient {
3650
3749
  * future waits for that object.
3651
3750
  * - A {@link FillParameters} in `parameters` also retrieves Objects already published, on a fill fetch stream.
3652
3751
  *
3653
- * The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId`, the `trackAlias` and a `ReadableStream` of {@link MoqtObject}s.
3752
+ * The method returns either a {@link RequestError} (on refusal) or a {@link SubscribeResult}: the subscription `requestId`, its
3753
+ * SUBSCRIBE_OK, a `ReadableStream` of {@link MoqtObject}s, and a `done` promise carrying the PUBLISH_DONE that ends it.
3654
3754
  * Use the `requestId` for {@link MOQtailClient.unsubscribe} or {@link MOQtailClient.subscribeUpdate}. Use the `stream` to decode and display objects.
3655
3755
  *
3656
3756
  * @param args - {@link SubscribeOptions} describing the subscription window and relay forwarding behavior.
3657
- * @returns Either a {@link RequestError} or `{ requestId, trackAlias, stream }` for consuming objects.
3757
+ * @returns Either a {@link RequestError} or `{ requestId, subscribeOk, stream, done }`.
3658
3758
  * @throws : {@link MOQtailError} If the client is destroyed.
3659
3759
  * @throws : {@link ProtocolViolationError} If required fields are missing or inconsistent.
3660
3760
  * @throws : {@link InvalidFilterError} If the Range Filters exceed the server's MAX_FILTER_RANGES; nothing is sent.
@@ -3701,9 +3801,12 @@ var MOQtailClient = class MOQtailClient {
3701
3801
  ...parameters ?? []
3702
3802
  ]);
3703
3803
  const request = new SubscribeRequest(msg);
3704
- request.manager = new Subscription(request);
3804
+ const subscription = new Subscription(request);
3705
3805
  request.earlyDiscardPolicy = args.earlyDiscardPolicy;
3706
3806
  request.onEndOfRange = args.onEndOfRange;
3807
+ request.orderer = this.#createOrderer(args.ordering, groupOrder, request.requestId, (obj) => request.output(obj));
3808
+ const fills = parameters?.some(MessageParameter.isFillParameters) ?? false;
3809
+ if (fills) request.orderer?.suspendWindow("fill");
3707
3810
  this.requests.set(request.requestId, request);
3708
3811
  this.requestIdMap.addMapping(request.requestId, request.fullTrackName);
3709
3812
  logger.debug("MOQtailClient", `subscribe: sending SUBSCRIBE requestId=${msg.requestId} ftn="${fullTrackName}"`);
@@ -3718,15 +3821,18 @@ var MOQtailClient = class MOQtailClient {
3718
3821
  } else {
3719
3822
  logger.debug("MOQtailClient", `subscribe: SUBSCRIBE_OK requestId=${request.requestId} trackAlias=${response.trackAlias}`);
3720
3823
  this.#claimTrackAlias(response.trackAlias, request);
3824
+ if (fills) this.#liftFillSuspension(request);
3721
3825
  return {
3722
3826
  requestId: msg.requestId,
3723
- trackAlias: response.trackAlias,
3724
- stream: request.stream
3827
+ subscribeOk: response,
3828
+ stream: request.stream,
3829
+ done: subscription.done
3725
3830
  };
3726
3831
  }
3727
3832
  } catch (error) {
3728
- logger.error("MOQtailClient", `subscribe: unexpected error — ${error instanceof Error ? error.message : String(error)}`);
3729
- await this.disconnect(new InternalError("MOQtailClient.subscribe", error instanceof Error ? error.message : String(error)));
3833
+ const reason = errorMessage(error);
3834
+ if (!this.#sessionClosing(error)) logger.error("MOQtailClient", `subscribe: unexpected error — ${reason}`);
3835
+ await this.disconnect(new InternalError("MOQtailClient.subscribe", reason));
3730
3836
  throw error;
3731
3837
  }
3732
3838
  }
@@ -3776,14 +3882,10 @@ var MOQtailClient = class MOQtailClient {
3776
3882
  target.unsubscribe();
3777
3883
  }
3778
3884
  } catch (error) {
3779
- await this.disconnect(new InternalError("MOQtailClient.unsubscribe", error instanceof Error ? error.message : String(error)));
3885
+ await this.disconnect(new InternalError("MOQtailClient.unsubscribe", errorMessage(error)));
3780
3886
  throw error;
3781
3887
  } finally {
3782
- for (const target of targets) {
3783
- this.requests.delete(target.requestId);
3784
- this.requestIdMap.removeMappingByRequestId(target.requestId);
3785
- this.#releaseTrackAlias(target);
3786
- }
3888
+ for (const target of targets) this.#forgetSubscription(target);
3787
3889
  owner?.clear();
3788
3890
  }
3789
3891
  }
@@ -3845,18 +3947,19 @@ var MOQtailClient = class MOQtailClient {
3845
3947
  const subscription = this.subscriptions.get(trackAlias);
3846
3948
  if (!subscription) throw new InternalError("MOQtailClient.subscribeUpdate", "Request exists but subscription does not");
3847
3949
  const requestId = this.#nextClientRequestId;
3848
- const msg = new RequestUpdate(requestId, [
3849
- new SubscriberPriority(priority),
3850
- new Forward(forward),
3950
+ const updateParams = [
3951
+ ...priority !== void 0 ? [new SubscriberPriority(priority)] : [],
3952
+ ...forward !== void 0 ? [new Forward(forward)] : [],
3851
3953
  ...locationFilter ? [locationFilter] : [],
3852
3954
  ...parameters ?? []
3853
- ]);
3955
+ ];
3956
+ const msg = new RequestUpdate(requestId, updateParams);
3854
3957
  subscription.update(msg);
3855
3958
  await this.#requestStreamFor(subscriptionRequestId, "MOQtailClient.subscribeUpdate").send(msg);
3856
3959
  }
3857
3960
  }
3858
3961
  } catch (error) {
3859
- await this.disconnect(new InternalError("MOQtailClient.subscribeUpdate", error instanceof Error ? error.message : String(error)));
3962
+ await this.disconnect(new InternalError("MOQtailClient.subscribeUpdate", errorMessage(error)));
3860
3963
  throw error;
3861
3964
  }
3862
3965
  }
@@ -3870,8 +3973,9 @@ var MOQtailClient = class MOQtailClient {
3870
3973
  * delivered by the newest switch target retires everything older.
3871
3974
  *
3872
3975
  * @param args - {@link SwitchOptions} referencing the subscription to switch from and the new subscription options.
3873
- * @returns Either a {@link RequestError} (refusal) or `{ requestId, stream }`, where `stream` is the
3874
- * same {@link https://developer.mozilla.org/docs/Web/API/ReadableStream | ReadableStream} object returned by the original `subscribe()` call.
3976
+ * @returns Either a {@link RequestError} (refusal) or the new request's {@link SubscribeResult}, where `stream`
3977
+ * is the same {@link https://developer.mozilla.org/docs/Web/API/ReadableStream | ReadableStream} object returned by the
3978
+ * original `subscribe()` call and `done` that subscription's, which resolves once the whole switched chain is over.
3875
3979
  * @throws :{@link MOQtailError} If the client is destroyed.
3876
3980
  * @throws :{@link ProtocolViolationError} If `switchFromRequestId` does not name an active subscription.
3877
3981
  * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
@@ -3881,7 +3985,7 @@ var MOQtailClient = class MOQtailClient {
3881
3985
  * await client.switch({
3882
3986
  * switchFromRequestId,
3883
3987
  * switchMode: SwitchMode.Soft,
3884
- * newSubscribeOptions: { fullTrackName: newTrackName, priority: 0, groupOrder: GroupOrder.Original, forward: true, locationFilter: new LocationFilter(LocationFilterType.NextObject) },
3988
+ * newSubscribeOptions: { fullTrackName: newTrackName, priority: 0, groupOrder: GroupOrder.Original, locationFilter: new LocationFilter(LocationFilterType.NextObject) },
3885
3989
  * onDrainDecision: (request) => true
3886
3990
  * });
3887
3991
  * ```
@@ -3910,15 +4014,25 @@ var MOQtailClient = class MOQtailClient {
3910
4014
  const newRequest = this.requests.get(result.requestId);
3911
4015
  subscription.addSwitchTarget(newRequest, drains);
3912
4016
  return {
3913
- requestId: result.requestId,
3914
- stream: subscription.stream
4017
+ ...result,
4018
+ stream: subscription.stream,
4019
+ done: subscription.done
3915
4020
  };
3916
4021
  } catch (error) {
3917
- await this.disconnect(new InternalError("MOQtailClient.switch", error instanceof Error ? error.message : String(error)));
4022
+ await this.disconnect(new InternalError("MOQtailClient.switch", errorMessage(error)));
3918
4023
  throw error;
3919
4024
  }
3920
4025
  }
3921
4026
  /**
4027
+ * The orderer for a request, unless its ordering, else the client's, is `'none'` or
4028
+ * unset. Descending group order is never ordered: every group after the first would be late.
4029
+ */
4030
+ #createOrderer(ordering, groupOrder, requestId, release) {
4031
+ const resolved = ordering ?? this.#options.ordering ?? "none";
4032
+ if (resolved === "none" || groupOrder === 2) return void 0;
4033
+ return new ObjectOrderer(resolved, release, (from, to) => this.emit("orderinggap", requestId, from, to));
4034
+ }
4035
+ /**
3922
4036
  * Ends a subscription whose publisher has said how many streams it opened and has
3923
4037
  * now delivered all of them, and reports whether that happened.
3924
4038
  *
@@ -3929,14 +4043,13 @@ var MOQtailClient = class MOQtailClient {
3929
4043
  */
3930
4044
  completeSubscription(request, force = false) {
3931
4045
  if (!force && (!request.expectedStreams || request.streamsAccepted < request.expectedStreams)) return false;
4046
+ request.orderer?.flush();
3932
4047
  const owner = request.manager;
3933
4048
  if (owner) {
3934
4049
  owner.drop(request);
3935
- if (owner.requests.length === 0) owner.controller.close();
3936
- } else request.controller?.close();
3937
- this.#releaseTrackAlias(request);
3938
- this.requests.delete(request.requestId);
3939
- this.requestIdMap.removeMappingByRequestId(request.requestId);
4050
+ if (owner.requests.length === 0) owner.objects.close();
4051
+ } else request.objects.close();
4052
+ this.#forgetSubscription(request);
3940
4053
  this.#closeRequestStream(request.requestId);
3941
4054
  logger.debug("MOQtailClient", `subscription for request ${request.requestId} completed`);
3942
4055
  return true;
@@ -4000,12 +4113,30 @@ var MOQtailClient = class MOQtailClient {
4000
4113
  this.subscriptions.delete(trackAlias);
4001
4114
  this.aliasFullTrackNameMap.delete(trackAlias);
4002
4115
  }
4116
+ /**
4117
+ * Lifts the fill's ordering suspension when no fill fetch stream will open: nothing was
4118
+ * published yet (no LARGEST_OBJECT), or none opened shortly after SUBSCRIBE_OK (an empty
4119
+ * fill range, moqt-22 3.4).
4120
+ */
4121
+ #liftFillSuspension(request) {
4122
+ const lift = () => {
4123
+ if (!request.fillOpened) request.orderer?.resumeWindow("fill");
4124
+ };
4125
+ if (!request.fillBoundary) lift();
4126
+ else setTimeout(lift, this.fillOpenTimeoutMs);
4127
+ }
4003
4128
  /** Tears down a switch target that lost the handover race to a newer one. */
4004
4129
  async #retireSwitchedRequest(request) {
4130
+ request.orderer?.flush();
4131
+ this.#forgetSubscription(request);
4132
+ await this.#resetRequestStream(request.requestId, 1);
4133
+ }
4134
+ /** Drops `request` from the request tables, frees its alias, and resolves its `done`. */
4135
+ #forgetSubscription(request) {
4005
4136
  this.requests.delete(request.requestId);
4006
4137
  this.requestIdMap.removeMappingByRequestId(request.requestId);
4007
4138
  this.#releaseTrackAlias(request);
4008
- await this.#resetRequestStream(request.requestId, 1);
4139
+ request.finish();
4009
4140
  }
4010
4141
  /**
4011
4142
  * One-shot retrieval of a bounded object span, optionally anchored to an existing subscription, returning a stream of {@link MoqtObject}s.
@@ -4021,7 +4152,7 @@ var MOQtailClient = class MOQtailClient {
4021
4152
  * - typeAndProps: Discriminated union carrying parameters specific to each fetch mode (see examples).
4022
4153
  * - parameters: Optional version-specific extension block.
4023
4154
  *
4024
- * Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, stream }` whose `stream`
4155
+ * Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, fetchOk, stream }` whose `stream`
4025
4156
  * ends naturally after the bounded range completes (no explicit cancel needed for normal completion).
4026
4157
  *
4027
4158
  * Use cases:
@@ -4080,6 +4211,7 @@ var MOQtailClient = class MOQtailClient {
4080
4211
  const msg = new Fetch(requestId, fullTrackName, params);
4081
4212
  const request = new FetchRequest(msg);
4082
4213
  request.onEndOfRange = args.onEndOfRange;
4214
+ request.orderer = this.#createOrderer(args.ordering, groupOrder, requestId, (obj) => request.objects.enqueue(obj));
4083
4215
  logger.log("MOQtailClient", "fetch: full fetch message:", {
4084
4216
  requestId: msg.requestId,
4085
4217
  fullTrackName: `${fullTrackName}`
@@ -4092,15 +4224,13 @@ var MOQtailClient = class MOQtailClient {
4092
4224
  if (response instanceof RequestError) {
4093
4225
  this.requests.delete(msg.requestId);
4094
4226
  return response;
4095
- } else {
4096
- const stream = request.stream;
4097
- return {
4098
- requestId: msg.requestId,
4099
- stream
4100
- };
4101
- }
4227
+ } else return {
4228
+ requestId: msg.requestId,
4229
+ fetchOk: response,
4230
+ stream: request.stream
4231
+ };
4102
4232
  } catch (error) {
4103
- await this.disconnect(new InternalError("MOQtailClient.fetch", error instanceof Error ? error.message : String(error)));
4233
+ await this.disconnect(new InternalError("MOQtailClient.fetch", errorMessage(error)));
4104
4234
  throw error;
4105
4235
  }
4106
4236
  }
@@ -4145,7 +4275,7 @@ var MOQtailClient = class MOQtailClient {
4145
4275
  if (typeof requestId === "number") requestId = BigInt(requestId);
4146
4276
  if (this.requests.get(requestId) instanceof FetchRequest) await this.#resetRequestStream(requestId, 1);
4147
4277
  } catch (error) {
4148
- await this.disconnect(new InternalError("MOQtailClient.fetchCancel", error instanceof Error ? error.message : String(error)));
4278
+ await this.disconnect(new InternalError("MOQtailClient.fetchCancel", errorMessage(error)));
4149
4279
  throw error;
4150
4280
  }
4151
4281
  }
@@ -4173,7 +4303,7 @@ var MOQtailClient = class MOQtailClient {
4173
4303
  trackAlias
4174
4304
  };
4175
4305
  } catch (error) {
4176
- await this.disconnect(new InternalError("MOQtailClient.publish", error instanceof Error ? error.message : String(error)));
4306
+ await this.disconnect(new InternalError("MOQtailClient.publish", errorMessage(error)));
4177
4307
  throw error;
4178
4308
  }
4179
4309
  }
@@ -4186,7 +4316,8 @@ var MOQtailClient = class MOQtailClient {
4186
4316
  try {
4187
4317
  if (typeof publishRequestId === "number") publishRequestId = BigInt(publishRequestId);
4188
4318
  const publication = this.publications.get(publishRequestId);
4189
- const msg = new PublishDone(statusCode, publication instanceof PublishPublication ? publication.streamsOpened : PublishDone.UNKNOWN_STREAM_COUNT, new ReasonPhrase(reasonPhrase));
4319
+ const streamCount = publication instanceof PublishPublication ? publication.streamsOpened : PublishDone.UNKNOWN_STREAM_COUNT;
4320
+ const msg = new PublishDone(statusCode, streamCount, new ReasonPhrase(reasonPhrase));
4190
4321
  const requestStream = this.#requestStreams.get(publishRequestId);
4191
4322
  if (requestStream) {
4192
4323
  await requestStream.send(msg);
@@ -4196,7 +4327,7 @@ var MOQtailClient = class MOQtailClient {
4196
4327
  this.requestIdMap.removeMappingByRequestId(publishRequestId);
4197
4328
  this.subscriptionAliasMap.delete(publishRequestId);
4198
4329
  } catch (error) {
4199
- await this.disconnect(new InternalError("MOQtailClient.publishDone", error instanceof Error ? error.message : String(error)));
4330
+ await this.disconnect(new InternalError("MOQtailClient.publishDone", errorMessage(error)));
4200
4331
  throw error;
4201
4332
  }
4202
4333
  }
@@ -4281,7 +4412,7 @@ var MOQtailClient = class MOQtailClient {
4281
4412
  this.requests.delete(msg.requestId);
4282
4413
  return response;
4283
4414
  } catch (error) {
4284
- await this.disconnect(new InternalError("MOQtailClient.publishNamespace", error instanceof Error ? error.message : String(error)));
4415
+ await this.disconnect(new InternalError("MOQtailClient.publishNamespace", errorMessage(error)));
4285
4416
  throw error;
4286
4417
  }
4287
4418
  }
@@ -4340,7 +4471,7 @@ var MOQtailClient = class MOQtailClient {
4340
4471
  try {
4341
4472
  const params = parameters ?? [];
4342
4473
  const msg = new SubscribeNamespace(this.#nextClientRequestId, trackNamespacePrefix, params);
4343
- const requestStream = await RequestStream.open(this.webTransport, msg, this.#requestStreamHooks);
4474
+ const requestStream = await RequestStream.open(this.webTransport, msg, this);
4344
4475
  this.#requestStreams.set(msg.requestId, requestStream);
4345
4476
  logger.log("MOQtailClient", "subscribeNamespace | sent msg", msg, msg.trackNamespacePrefix.toUtf8Path(), msg.requestId);
4346
4477
  const response = await requestStream.next();
@@ -4361,7 +4492,7 @@ var MOQtailClient = class MOQtailClient {
4361
4492
  }
4362
4493
  };
4363
4494
  } catch (error) {
4364
- await this.disconnect(new InternalError("MOQtailClient.subscribeNamespace", error instanceof Error ? error.message : String(error)));
4495
+ await this.disconnect(new InternalError("MOQtailClient.subscribeNamespace", errorMessage(error)));
4365
4496
  throw error;
4366
4497
  }
4367
4498
  }
@@ -4370,7 +4501,7 @@ var MOQtailClient = class MOQtailClient {
4370
4501
  assertWithinFilterRangeLimit(parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.subscribeTracks");
4371
4502
  try {
4372
4503
  const msg = new SubscribeTracks(this.#nextClientRequestId, trackNamespacePrefix, parameters ?? []);
4373
- const requestStream = await RequestStream.open(this.webTransport, msg, this.#requestStreamHooks);
4504
+ const requestStream = await RequestStream.open(this.webTransport, msg, this);
4374
4505
  this.#requestStreams.set(msg.requestId, requestStream);
4375
4506
  const response = await requestStream.next();
4376
4507
  if (!response) throw new InternalError("MOQtailClient.subscribeTracks", "Stream closed before response");
@@ -4387,7 +4518,7 @@ var MOQtailClient = class MOQtailClient {
4387
4518
  }
4388
4519
  };
4389
4520
  } catch (error) {
4390
- await this.disconnect(new InternalError("MOQtailClient.subscribeTracks", error instanceof Error ? error.message : String(error)));
4521
+ await this.disconnect(new InternalError("MOQtailClient.subscribeTracks", errorMessage(error)));
4391
4522
  throw error;
4392
4523
  }
4393
4524
  }
@@ -4396,8 +4527,8 @@ var MOQtailClient = class MOQtailClient {
4396
4527
  while (true) {
4397
4528
  const msg = await requestStream.next();
4398
4529
  if (!msg) break;
4399
- if (msg instanceof Namespace && this.onPeerNamespace) this.onPeerNamespace(prefix, msg.trackNamespaceSuffix);
4400
- else if (msg instanceof NamespaceDone && this.onPeerNamespaceDone) this.onPeerNamespaceDone(prefix, msg.trackNamespaceSuffix);
4530
+ if (msg instanceof Namespace) this.emit("peernamespace", prefix, msg.trackNamespaceSuffix);
4531
+ else if (msg instanceof NamespaceDone) this.emit("peernamespacedone", prefix, msg.trackNamespaceSuffix);
4401
4532
  }
4402
4533
  } finally {
4403
4534
  this.#requestStreams.delete(requestId);
@@ -4415,7 +4546,7 @@ var MOQtailClient = class MOQtailClient {
4415
4546
  this.subscribedNamespaces.delete(trackNamespacePrefix);
4416
4547
  await this.#closeNamespaceRequestStream(trackNamespacePrefix);
4417
4548
  } catch (error) {
4418
- await this.disconnect(new InternalError("MOQtailClient.unsubscribeNamespace", error instanceof Error ? error.message : String(error)));
4549
+ await this.disconnect(new InternalError("MOQtailClient.unsubscribeNamespace", errorMessage(error)));
4419
4550
  throw error;
4420
4551
  }
4421
4552
  }
@@ -4450,7 +4581,7 @@ var MOQtailClient = class MOQtailClient {
4450
4581
  this.requests.delete(msg.requestId);
4451
4582
  return response;
4452
4583
  } catch (error) {
4453
- await this.disconnect(new InternalError("MOQtailClient.trackStatus", error instanceof Error ? error.message : String(error)));
4584
+ await this.disconnect(new InternalError("MOQtailClient.trackStatus", errorMessage(error)));
4454
4585
  throw error;
4455
4586
  }
4456
4587
  }
@@ -4459,28 +4590,8 @@ var MOQtailClient = class MOQtailClient {
4459
4590
  *
4460
4591
  * @param requestId - The requestId carried by `first`; the key the stream is filed under.
4461
4592
  */
4462
- /**
4463
- * Hands a data stream {@link MOQtailClient.onDataEvent}, read at call time so an observer assigned
4464
- * after connecting still sees streams that are already open.
4465
- *
4466
- * @internal
4467
- */
4468
- dataStreamObserver(fullTrackNameOf) {
4469
- return {
4470
- onDataEvent: (event) => this.onDataEvent?.(event),
4471
- ...fullTrackNameOf && { fullTrackNameOf }
4472
- };
4473
- }
4474
- /**
4475
- * Forwards request-stream traffic to {@link onMessageSent} and {@link onMessageReceived},
4476
- * read at call time so callbacks assigned after connecting still see it.
4477
- */
4478
- #requestStreamHooks = {
4479
- onMessageSent: (msg) => this.onMessageSent?.(msg),
4480
- onMessageReceived: (msg) => this.onMessageReceived?.(msg)
4481
- };
4482
4593
  async #openRequestStream(requestId, first) {
4483
- const requestStream = await RequestStream.open(this.webTransport, first, this.#requestStreamHooks);
4594
+ const requestStream = await RequestStream.open(this.webTransport, first, this);
4484
4595
  this.#requestStreams.set(requestId, requestStream);
4485
4596
  this.#pumpRequestStream(requestId, requestStream);
4486
4597
  return requestStream;
@@ -4495,8 +4606,8 @@ var MOQtailClient = class MOQtailClient {
4495
4606
  * the wire changes.
4496
4607
  *
4497
4608
  * @returns True if the request was re-issued here. A GOAWAY naming a new session URI
4498
- * is not: opening a session is the application's call, so it is surfaced through
4499
- * {@link MOQtailClient.onGoaway} and the request stream is closed.
4609
+ * is not: opening a session is the application's call, so it is surfaced as a
4610
+ * `goaway` event and the request stream is closed.
4500
4611
  *
4501
4612
  * @internal
4502
4613
  */
@@ -4509,7 +4620,7 @@ var MOQtailClient = class MOQtailClient {
4509
4620
  }
4510
4621
  if (goAway.newSessionUri) {
4511
4622
  logger.log("MOQtailClient", `GOAWAY migrates request ${requestId} to ${goAway.newSessionUri}`);
4512
- this.onGoaway?.(goAway);
4623
+ this.emit("goaway", goAway);
4513
4624
  await this.#closeRequestStream(requestId);
4514
4625
  return false;
4515
4626
  }
@@ -4553,6 +4664,7 @@ var MOQtailClient = class MOQtailClient {
4553
4664
  */
4554
4665
  async #pumpRequestStream(requestId, requestStream) {
4555
4666
  let answered = false;
4667
+ let closedBy;
4556
4668
  try {
4557
4669
  while (true) {
4558
4670
  const msg = await requestStream.next();
@@ -4564,11 +4676,14 @@ var MOQtailClient = class MOQtailClient {
4564
4676
  }
4565
4677
  logger.debug("MOQtailClient", `request stream for requestId=${requestId} closed by peer`);
4566
4678
  } catch (error) {
4567
- logger.error("MOQtailClient", `request stream for requestId=${requestId} failed`, error);
4679
+ if (this.#sessionClosing(error)) closedBy = error;
4680
+ else logger.error("MOQtailClient", `request stream for requestId=${requestId} failed`, error);
4681
+ const request = this.requests.get(requestId);
4682
+ if (!requestStream.migrated && request instanceof SubscribeRequest) request.finish();
4568
4683
  } finally {
4569
4684
  if (!requestStream.migrated) {
4570
4685
  this.#requestStreams.delete(requestId);
4571
- if (!answered) this.requests.get(requestId)?.reject(new InternalError("MOQtailClient", `Request stream closed before answering request ${requestId}`));
4686
+ if (!answered) this.requests.get(requestId)?.reject(closedBy ?? new InternalError("MOQtailClient", `Request stream closed before answering request ${requestId}`));
4572
4687
  }
4573
4688
  }
4574
4689
  }
@@ -4600,7 +4715,6 @@ var MOQtailClient = class MOQtailClient {
4600
4715
  * Reads the shared control stream, every request type has its own bidi stream.
4601
4716
  */
4602
4717
  async #handleIncomingControlMessages() {
4603
- this.#ensureActive();
4604
4718
  try {
4605
4719
  const reader = this.controlStream.stream.getReader();
4606
4720
  while (true) {
@@ -4614,41 +4728,45 @@ var MOQtailClient = class MOQtailClient {
4614
4728
  await handler(this, msg);
4615
4729
  }
4616
4730
  } catch (error) {
4617
- this.disconnect();
4618
- throw error;
4731
+ if (!this.#sessionClosing(error)) logger.error("MOQtailClient", "control stream failed", error);
4732
+ await this.disconnect(error);
4619
4733
  }
4620
4734
  }
4621
4735
  async #acceptIncomingUniStreams() {
4622
- this.#ensureActive();
4623
4736
  const reader = this.#incomingUniStreams;
4624
- let isDone = false;
4625
- while (!isDone) try {
4626
- const { done, value: stream } = await reader.read();
4627
- if (done) {
4628
- isDone = true;
4629
- throw new MOQtailError("WebTransport session is terminated");
4737
+ try {
4738
+ while (true) {
4739
+ const { done, value: stream } = await reader.read();
4740
+ if (done) return;
4741
+ this.#handleRecvStreams(stream).catch((error) => {
4742
+ if (error instanceof PeerStreamResetError || this.#sessionClosing(error)) {
4743
+ logger.debug("MOQtailClient", `data stream ended: ${error.message}`);
4744
+ return;
4745
+ }
4746
+ logger.error("MOQtailClient", "handleRecvStreams error", error);
4747
+ });
4630
4748
  }
4631
- this.#handleRecvStreams(stream).catch((error) => {
4632
- if (error instanceof PeerStreamResetError) {
4633
- logger.debug("MOQtailClient", `data stream ended: ${error.message}`);
4634
- return;
4635
- }
4636
- logger.error("MOQtailClient", "handleRecvStreams error", error);
4637
- });
4638
4749
  } catch (error) {
4639
- logger.error("MOQtailClient", "acceptIncomingUniStreams error", error);
4640
- if (this.#isDestroyed) break;
4750
+ if (!this.#sessionClosing(error)) logger.error("MOQtailClient", "acceptIncomingUniStreams error", error);
4641
4751
  }
4642
4752
  }
4643
- #acceptIncomingBiStreams() {
4644
- (async () => {
4645
- const reader = this.webTransport.incomingBidirectionalStreams.getReader();
4753
+ async #acceptIncomingBiStreams() {
4754
+ const reader = this.webTransport.incomingBidirectionalStreams.getReader();
4755
+ try {
4646
4756
  while (true) {
4647
4757
  const { value: biStream, done } = await reader.read();
4648
- if (done) break;
4649
- this.#dispatchIncomingRequestStream(new RequestStream(biStream, this.#requestStreamHooks));
4758
+ if (done) return;
4759
+ this.#dispatchIncomingRequestStream(new RequestStream(biStream, this)).catch((error) => {
4760
+ if (!this.#sessionClosing(error)) logger.error("MOQtailClient", "incoming request stream failed", error);
4761
+ });
4650
4762
  }
4651
- })();
4763
+ } catch (error) {
4764
+ if (!this.#sessionClosing(error)) logger.error("MOQtailClient", "acceptIncomingBiStreams error", error);
4765
+ }
4766
+ }
4767
+ /** The session is going away, so a read or write failing is expected, not an error to log. */
4768
+ #sessionClosing(error) {
4769
+ return this.#isDestroyed || isSessionClosed(error);
4652
4770
  }
4653
4771
  /**
4654
4772
  * Serves one peer-opened request stream: the first message must be a `First`-marked
@@ -4675,7 +4793,7 @@ var MOQtailClient = class MOQtailClient {
4675
4793
  msg = await requestStream.next();
4676
4794
  }
4677
4795
  } catch (error) {
4678
- logger.error("MOQtailClient", "incoming request stream failed", error);
4796
+ if (!this.#sessionClosing(error)) logger.error("MOQtailClient", "incoming request stream failed", error);
4679
4797
  } finally {
4680
4798
  const requestId = "requestId" in first ? first.requestId : void 0;
4681
4799
  if (requestId !== void 0) {
@@ -4685,243 +4803,134 @@ var MOQtailClient = class MOQtailClient {
4685
4803
  await requestStream.close();
4686
4804
  }
4687
4805
  }
4806
+ /** The objects on a fetch data stream. End-of-range markers carry no Object, so they go to `onEndOfRange`. */
4807
+ async *#readFetchObjects(reader, fullTrackName, onEndOfRange) {
4808
+ while (true) {
4809
+ const { done, value } = await reader.read();
4810
+ if (done) return;
4811
+ if (!value) continue;
4812
+ if (!(value instanceof FetchObject)) throw new ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
4813
+ if (value.kind === "end_of_range") this.#notifyEndOfRange(onEndOfRange, value);
4814
+ else yield MoqtObject.fromFetchObject(value, fullTrackName);
4815
+ }
4816
+ }
4688
4817
  async #handleRecvStreams(incomingUniStream) {
4689
4818
  this.#ensureActive();
4690
- try {
4691
- const recvStream = await RecvStream.new(incomingUniStream, this.dataStreamTimeoutMs, this.onDataReceived, (header) => {
4692
- if (!(header instanceof FetchHeader)) return 0;
4693
- const request = this.requests.get(this.#clientRequestId(header.requestId));
4694
- if (!(request instanceof FetchRequest)) return 0;
4695
- return MessageParameter.groupOrderOf(request.message.parameters);
4696
- }, this.dataStreamObserver((header) => header instanceof SubgroupHeader ? this.aliasFullTrackNameMap.get(header.trackAlias) : void 0));
4697
- const header = recvStream.header;
4698
- const reader = recvStream.stream.getReader();
4699
- let forceComplete = false;
4700
- if (header instanceof FetchHeader) {
4701
- const request = this.requests.get(this.#clientRequestId(header.requestId));
4702
- if (request && request instanceof FetchRequest) {
4703
- const fullTrackName = request.message.fullTrackName;
4704
- try {
4705
- while (true) {
4706
- const { done, value: nextObject } = await reader.read();
4707
- if (done) {
4708
- request.controller?.close();
4709
- break;
4710
- }
4711
- if (nextObject) {
4712
- if (nextObject instanceof FetchObject) {
4713
- if (nextObject.kind === "end_of_range") {
4714
- this.#notifyEndOfRange(request.onEndOfRange, nextObject);
4715
- continue;
4716
- }
4717
- const moqtObject = MoqtObject.fromFetchObject(nextObject, fullTrackName);
4718
- request.controller?.enqueue(moqtObject);
4719
- continue;
4720
- }
4721
- throw new ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
4722
- }
4819
+ const recvStream = await RecvStream.new(incomingUniStream, this.dataStreamTimeoutMs, this, (header) => {
4820
+ if (!(header instanceof FetchHeader)) return 0;
4821
+ const request = this.requests.get(this.#clientRequestId(header.requestId));
4822
+ if (!(request instanceof FetchRequest)) return 0;
4823
+ return MessageParameter.groupOrderOf(request.message.parameters);
4824
+ }, (header) => this.#streamTrackName(header));
4825
+ const header = recvStream.header;
4826
+ const reader = recvStream.stream.getReader();
4827
+ let forceComplete = false;
4828
+ if (header instanceof FetchHeader) {
4829
+ const request = this.requests.get(this.#clientRequestId(header.requestId));
4830
+ if (request instanceof FetchRequest) {
4831
+ let previous;
4832
+ try {
4833
+ const objects = this.#readFetchObjects(reader, request.message.fullTrackName, request.onEndOfRange);
4834
+ for await (const moqtObject of objects) {
4835
+ if (!request.objects.open) {
4836
+ await recvStream.stopSending(1);
4837
+ break;
4723
4838
  }
4724
- } finally {
4725
- reader.releaseLock();
4839
+ if (request.orderer) request.orderer.push(moqtObject, previous);
4840
+ else request.objects.enqueue(moqtObject);
4841
+ previous = moqtObject.location;
4726
4842
  }
4727
- return;
4843
+ request.orderer?.flush();
4844
+ request.objects.close();
4845
+ } finally {
4846
+ reader.releaseLock();
4728
4847
  }
4729
- if (request instanceof SubscribeRequest) {
4730
- request.streamsAccepted++;
4731
- try {
4732
- while (true) {
4733
- const { done, value: nextObject } = await reader.read();
4734
- if (done) break;
4735
- if (!nextObject) continue;
4736
- if (!(nextObject instanceof FetchObject)) throw new ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
4737
- if (nextObject.kind === "end_of_range") {
4738
- this.#notifyEndOfRange(request.onEndOfRange, nextObject);
4739
- continue;
4740
- }
4741
- const moqtObject = MoqtObject.fromFetchObject(nextObject, request.fullTrackName);
4742
- if (request.manager) {
4743
- if (!request.manager.deliver(request, moqtObject)) {
4744
- await recvStream.stopSending(1);
4745
- forceComplete = true;
4746
- break;
4747
- }
4748
- } else request.controller?.enqueue(moqtObject);
4848
+ return;
4849
+ }
4850
+ if (request instanceof SubscribeRequest) {
4851
+ request.streamsAccepted++;
4852
+ request.fillOpened = true;
4853
+ request.openFills++;
4854
+ request.orderer?.suspendWindow("fill");
4855
+ let previous;
4856
+ try {
4857
+ for await (const moqtObject of this.#readFetchObjects(reader, request.fullTrackName, request.onEndOfRange)) {
4858
+ if (!request.manager.objects.open) {
4859
+ await recvStream.stopSending(1);
4860
+ break;
4861
+ }
4862
+ if (!request.manager.deliver(request, moqtObject, previous)) {
4863
+ await recvStream.stopSending(1);
4864
+ forceComplete = true;
4865
+ break;
4749
4866
  }
4750
- } finally {
4751
- reader.releaseLock();
4867
+ previous = moqtObject.location;
4752
4868
  }
4753
- this.completeSubscription(request, forceComplete);
4754
- return;
4755
- }
4756
- throw new ProtocolViolationError("MOQtailClient", "No request for received request id");
4757
- } else {
4758
- let subscription = this.subscriptions.get(header.trackAlias);
4759
- if (!subscription) {
4760
- await this.#waitForTrackAlias(header.trackAlias);
4761
- subscription = this.subscriptions.get(header.trackAlias);
4869
+ } finally {
4870
+ reader.releaseLock();
4871
+ request.openFills--;
4872
+ if (request.openFills === 0) request.orderer?.resumeWindow("fill");
4762
4873
  }
4763
- if (subscription) {
4764
- subscription.streamsAccepted++;
4765
- const fullTrackName = subscription.fullTrackName;
4766
- let firstObjectId = null;
4767
- let subgroupTimeoutId;
4768
- const effectiveDiscardPolicy = subscription.earlyDiscardPolicy ?? this.#earlyDiscardPolicy;
4769
- if (effectiveDiscardPolicy?.subgroupReceiveTimeout !== void 0) subgroupTimeoutId = setTimeout(() => {
4770
- reader.cancel(streamResetReason(2)).catch(() => {});
4771
- }, effectiveDiscardPolicy.subgroupReceiveTimeout);
4772
- try {
4773
- while (true) {
4774
- const { done, value: nextObject } = await reader.read();
4775
- if (done) break;
4776
- if (nextObject) {
4777
- if (nextObject instanceof SubgroupObject) {
4778
- if (!firstObjectId) firstObjectId = nextObject.objectId;
4779
- let subgroupId = null;
4780
- if (SubgroupHeaderType.isSubgroupIdZero(header.type)) subgroupId = 0n;
4781
- else if (SubgroupHeaderType.isSubgroupIdFirstObjectId(header.type)) subgroupId = firstObjectId ?? null;
4782
- else if (SubgroupHeaderType.hasExplicitSubgroupId(header.type)) subgroupId = header.subgroupId ?? null;
4783
- const moqtObject = MoqtObject.fromSubgroupObject(nextObject, header.groupId, header.publisherPriority, subgroupId, fullTrackName);
4784
- if (!subscription.largestLocation) subscription.largestLocation = moqtObject.location;
4785
- if (subscription.largestLocation.compare(moqtObject.location) == -1) subscription.largestLocation = moqtObject.location;
4786
- if (subscription.manager) {
4787
- if (!subscription.manager.deliver(subscription, moqtObject)) {
4788
- forceComplete = true;
4789
- await recvStream.stopSending(1);
4790
- break;
4791
- }
4792
- } else subscription.controller?.enqueue(moqtObject);
4793
- continue;
4874
+ this.completeSubscription(request, forceComplete);
4875
+ return;
4876
+ }
4877
+ throw new ProtocolViolationError("MOQtailClient", "No request for received request id");
4878
+ } else {
4879
+ let subscription = this.subscriptions.get(header.trackAlias);
4880
+ if (!subscription) {
4881
+ await this.#waitForTrackAlias(header.trackAlias);
4882
+ subscription = this.subscriptions.get(header.trackAlias);
4883
+ }
4884
+ if (subscription) {
4885
+ subscription.streamsAccepted++;
4886
+ const fullTrackName = subscription.fullTrackName;
4887
+ let firstObjectId = null;
4888
+ let lastObjectId;
4889
+ let subgroupTimeoutId;
4890
+ const effectiveDiscardPolicy = subscription.earlyDiscardPolicy ?? this.#earlyDiscardPolicy;
4891
+ if (effectiveDiscardPolicy?.subgroupReceiveTimeout !== void 0) subgroupTimeoutId = setTimeout(() => {
4892
+ reader.cancel(streamResetReason(2)).catch(() => {});
4893
+ }, effectiveDiscardPolicy.subgroupReceiveTimeout);
4894
+ try {
4895
+ while (true) {
4896
+ const { done, value: nextObject } = await reader.read();
4897
+ if (done) {
4898
+ if (lastObjectId !== void 0 && SubgroupHeaderType.containsEndOfGroup(header.type)) subscription.orderer?.endGroup(header.groupId, lastObjectId);
4899
+ break;
4900
+ }
4901
+ if (nextObject) {
4902
+ if (nextObject instanceof SubgroupObject) {
4903
+ lastObjectId = nextObject.objectId;
4904
+ if (firstObjectId === null) firstObjectId = nextObject.objectId;
4905
+ let subgroupId = null;
4906
+ if (SubgroupHeaderType.isSubgroupIdZero(header.type)) subgroupId = 0n;
4907
+ else if (SubgroupHeaderType.isSubgroupIdFirstObjectId(header.type)) subgroupId = firstObjectId ?? null;
4908
+ else if (SubgroupHeaderType.hasExplicitSubgroupId(header.type)) subgroupId = header.subgroupId ?? null;
4909
+ const moqtObject = MoqtObject.fromSubgroupObject(nextObject, header.groupId, header.publisherPriority, subgroupId, fullTrackName);
4910
+ if (!subscription.largestLocation) subscription.largestLocation = moqtObject.location;
4911
+ if (subscription.largestLocation.compare(moqtObject.location) == -1) subscription.largestLocation = moqtObject.location;
4912
+ if (!subscription.manager.objects.open) {
4913
+ await recvStream.stopSending(1);
4914
+ break;
4915
+ }
4916
+ if (!subscription.manager.deliver(subscription, moqtObject)) {
4917
+ forceComplete = true;
4918
+ await recvStream.stopSending(1);
4919
+ break;
4794
4920
  }
4795
- throw new ProtocolViolationError("MOQtailClient", "Received fetch object after subgroup header");
4921
+ continue;
4796
4922
  }
4923
+ throw new ProtocolViolationError("MOQtailClient", "Received fetch object after subgroup header");
4797
4924
  }
4798
- } finally {
4799
- if (subgroupTimeoutId !== void 0) clearTimeout(subgroupTimeoutId);
4800
4925
  }
4801
- this.completeSubscription(subscription, forceComplete);
4802
- return;
4926
+ } finally {
4927
+ if (subgroupTimeoutId !== void 0) clearTimeout(subgroupTimeoutId);
4803
4928
  }
4804
- throw new ProtocolViolationError("MOQtailClient", "No subscription for received track alias");
4929
+ this.completeSubscription(subscription, forceComplete);
4930
+ return;
4805
4931
  }
4806
- } catch (error) {
4807
- throw error;
4808
- }
4809
- }
4810
- };
4811
- //#endregion
4812
- //#region src/client/track/object_cache.ts
4813
- /**
4814
- * Copyright 2025 The MOQtail Authors
4815
- *
4816
- * Licensed under the Apache License, Version 2.0 (the "License");
4817
- * you may not use this file except in compliance with the License.
4818
- * You may obtain a copy of the License at
4819
- *
4820
- * http://www.apache.org/licenses/LICENSE-2.0
4821
- *
4822
- * Unless required by applicable law or agreed to in writing, software
4823
- * distributed under the License is distributed on an "AS IS" BASIS,
4824
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4825
- * See the License for the specific language governing permissions and
4826
- * limitations under the License.
4827
- */
4828
- var MemoryObjectCache = class {
4829
- objects = [];
4830
- add(obj) {
4831
- const idx = this._findInsertIndex(obj);
4832
- this.objects.splice(idx, 0, obj);
4833
- }
4834
- getRange(start, end) {
4835
- const startIdx = start ? this._findIndex(start, false) : 0;
4836
- const endIdx = end ? this._findIndex(end, true) : this.objects.length;
4837
- return this.objects.slice(startIdx, endIdx);
4838
- }
4839
- getByLocation(location) {
4840
- const idx = this._findIndex(location, false);
4841
- const obj = this.objects[idx];
4842
- if (obj && obj.groupId === location.group && obj.objectId === location.object) return obj;
4843
- }
4844
- size() {
4845
- return this.objects.length;
4846
- }
4847
- clear() {
4848
- this.objects = [];
4849
- }
4850
- _findInsertIndex(obj) {
4851
- let low = 0, high = this.objects.length;
4852
- while (low < high) {
4853
- const mid = low + high >> 1;
4854
- const midObj = this.objects[mid];
4855
- if (!midObj) break;
4856
- if (new Location(midObj.groupId, midObj.objectId).compare(new Location(obj.groupId, obj.objectId)) < 0) low = mid + 1;
4857
- else high = mid;
4858
- }
4859
- return low;
4860
- }
4861
- _findIndex(location, exclusive) {
4862
- let low = 0, high = this.objects.length;
4863
- while (low < high) {
4864
- const mid = low + high >> 1;
4865
- const midObj = this.objects[mid];
4866
- if (!midObj) break;
4867
- const cmp = new Location(midObj.groupId, midObj.objectId).compare(location);
4868
- if (cmp < 0 || exclusive && cmp === 0) low = mid + 1;
4869
- else high = mid;
4870
- }
4871
- return low;
4872
- }
4873
- };
4874
- var RingBufferObjectCache = class {
4875
- buffer;
4876
- maxSize;
4877
- constructor(maxSize = 100) {
4878
- this.buffer = [];
4879
- this.maxSize = maxSize;
4880
- }
4881
- add(obj) {
4882
- const idx = this._findInsertIndex(obj);
4883
- this.buffer.splice(idx, 0, obj);
4884
- if (this.buffer.length > this.maxSize) this.buffer.shift();
4885
- }
4886
- getRange(start, end) {
4887
- const startIdx = start ? this._findIndex(start, false) : 0;
4888
- const endIdx = end ? this._findIndex(end, true) : this.buffer.length;
4889
- return this.buffer.slice(startIdx, endIdx);
4890
- }
4891
- getByLocation(location) {
4892
- const idx = this._findIndex(location, false);
4893
- const obj = this.buffer[idx];
4894
- if (obj && obj.groupId === location.group && obj.objectId === location.object) return obj;
4895
- }
4896
- size() {
4897
- return this.buffer.length;
4898
- }
4899
- clear() {
4900
- this.buffer = [];
4901
- }
4902
- _findInsertIndex(obj) {
4903
- let low = 0, high = this.buffer.length;
4904
- while (low < high) {
4905
- const mid = low + high >> 1;
4906
- const midObj = this.buffer[mid];
4907
- if (!midObj) break;
4908
- if (new Location(midObj.groupId, midObj.objectId).compare(new Location(obj.groupId, obj.objectId)) < 0) low = mid + 1;
4909
- else high = mid;
4910
- }
4911
- return low;
4912
- }
4913
- _findIndex(location, exclusive) {
4914
- let low = 0, high = this.buffer.length;
4915
- while (low < high) {
4916
- const mid = low + high >> 1;
4917
- const midObj = this.buffer[mid];
4918
- if (!midObj) break;
4919
- const cmp = new Location(midObj.groupId, midObj.objectId).compare(location);
4920
- if (cmp < 0 || exclusive && cmp === 0) low = mid + 1;
4921
- else high = mid;
4932
+ throw new ProtocolViolationError("MOQtailClient", "No subscription for received track alias");
4922
4933
  }
4923
- return low;
4924
4934
  }
4925
4935
  };
4926
- //#endregion
4927
- export { SendStream as C, ControlSendStream as D, ControlRecvStream as E, ControlStream as O, RecvStream as S, RequestStream as T, FetchRequest as _, SendDatagramStream as a, LiveTrackSource as b, SubscribePublication as c, PublishRequest as d, SubscribeRequest as f, DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS as g, DEFAULT_SWITCH_DRAIN_TIMEOUT_MS as h, RecvDatagramStream as i, FetchPublication as l, DEFAULT_MAX_FILTER_RANGES as m, RingBufferObjectCache as n, PublishPublication as o, Subscription as p, MOQtailClient as r, SubscribeNamespaceRequest as s, MemoryObjectCache as t, TrackStatusRequest as u, PublishNamespaceRequest as v, DataStreamReporter as w, StaticTrackSource as x, HybridTrackSource as y };
4936
+ export { SendStream as C, ControlSendStream as D, ControlRecvStream as E, ControlStream as O, RecvStream as S, RequestStream as T, ObjectStream as _, SubscribeNamespaceRequest as a, LiveTrackSource as b, TrackStatusRequest as c, Subscription as d, DEFAULT_FILL_OPEN_TIMEOUT_MS as f, FetchRequest as g, DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS as h, PublishPublication as i, errorMessage as k, PublishRequest as l, DEFAULT_SWITCH_DRAIN_TIMEOUT_MS as m, ObjectOrderer as n, SubscribePublication as o, DEFAULT_MAX_FILTER_RANGES as p, SendDatagramStream as r, FetchPublication as s, MOQtailClient as t, SubscribeRequest as u, PublishNamespaceRequest as v, DataStreamReporter as w, StaticTrackSource as x, HybridTrackSource as y };