moqtail 0.15.0 → 0.17.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 (43) hide show
  1. package/README.md +153 -473
  2. package/dist/client-CjdF7_cL.d.cts +1928 -0
  3. package/dist/{client-BviQ20Lc.cjs → client-FnSNJocV.cjs} +1102 -1192
  4. package/dist/client-I8mDg-Ls.d.mts +1928 -0
  5. package/dist/{client-zi0lmuIL.mjs → client-MXn-lkAA.mjs} +940 -1018
  6. package/dist/client.cjs +202 -7
  7. package/dist/client.d.cts +23 -1944
  8. package/dist/client.d.mts +23 -1944
  9. package/dist/client.mjs +195 -2
  10. package/dist/emitter-UbeRcbuf.mjs +109 -0
  11. package/dist/{logger-c2NoQqtx.cjs → emitter-qNJYD3yQ.cjs} +61 -2
  12. package/dist/{index-BY6e1obL.d.cts → index-BaZgHZ8D.d.mts} +124 -324
  13. package/dist/index-Bn8VlVoN.d.cts +2261 -0
  14. package/dist/index-Ch5QUygw.d.mts +2261 -0
  15. package/dist/index.cjs +18 -14
  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 +380 -572
  22. package/dist/model.d.cts +2901 -2
  23. package/dist/model.d.mts +17 -2
  24. package/dist/model.mjs +380 -572
  25. package/dist/player/component.cjs +364 -0
  26. package/dist/player/component.d.cts +59 -0
  27. package/dist/player/component.d.mts +59 -0
  28. package/dist/player/component.mjs +362 -0
  29. package/dist/player-C6y-qpHz.cjs +8488 -0
  30. package/dist/player-DfJB6vBH.mjs +8293 -0
  31. package/dist/player.cjs +31 -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/util.cjs +9 -10
  36. package/dist/util.d.cts +20 -13
  37. package/dist/util.d.mts +20 -13
  38. package/dist/util.mjs +4 -6
  39. package/package.json +46 -5
  40. package/dist/index-BY6e1obL.d.mts +0 -3087
  41. package/dist/logger-ByDB8lYF.mjs +0 -56
  42. package/dist/logger-dEoueCj7.d.cts +0 -35
  43. package/dist/logger-dEoueCj7.d.mts +0 -35
@@ -1,8 +1,123 @@
1
1
  const require_model = require("./model.cjs");
2
- const require_logger = require("./logger-c2NoQqtx.cjs");
3
- //#region src/client/control_stream.ts
2
+ const require_emitter = require("./emitter-qNJYD3yQ.cjs");
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 require_model.MOQtailError {
43
+ context;
44
+ code;
45
+ constructor(context, code) {
46
+ super(`[${context}] peer reset the stream with ${require_model.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 require_model.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 @@ const require_logger = require("./logger-c2NoQqtx.cjs");
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,36 +140,53 @@ 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;
40
173
  try {
41
174
  const serializedMessage = require_model.ControlMessage.serialize(message);
42
- require_logger.logger.debug("control_stream", `send: waiting for writer.ready — ${msgName} (${serializedMessage.length}B)`);
175
+ require_emitter.logger.debug("control_stream", `send: waiting for writer.ready — ${msgName} (${serializedMessage.length}B)`);
43
176
  await this.#writer.ready;
44
- require_logger.logger.debug("control_stream", `send: writer ready, writing — ${msgName}`);
177
+ require_emitter.logger.debug("control_stream", `send: writer ready, writing — ${msgName}`);
45
178
  await this.#writer.write(serializedMessage.toUint8Array());
46
- require_logger.logger.debug("control_stream", `send: write complete — ${msgName}`);
47
- if (this.onMessageSent) this.onMessageSent(message);
179
+ require_emitter.logger.debug("control_stream", `send: write complete — ${msgName}`);
180
+ this.#events?.emit("messagesent", message);
48
181
  } catch (error) {
49
- const errorMessage = error instanceof Error ? error.message : String(error);
50
- require_logger.logger.error("control_stream", `send: failed to write ${msgName} — ${errorMessage}`);
182
+ const reason = errorMessage(error);
183
+ require_emitter.logger.error("control_stream", `send: failed to write ${msgName} — ${reason}`);
51
184
  await this.close();
52
- throw new require_model.TerminationError(`ControlStream.send: Failed to write message: ${errorMessage}`, 1);
185
+ throw new require_model.TerminationError(`ControlStream.send: Failed to write message: ${reason}`, 1);
53
186
  }
54
187
  }
55
188
  async close() {
56
- require_logger.logger.debug("control_stream", "close: closing writer");
189
+ require_emitter.logger.debug("control_stream", "close: closing writer");
57
190
  await this.#writer.close().catch(() => {});
58
191
  }
59
192
  };
@@ -67,34 +200,35 @@ 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 require_model.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()
79
213
  });
80
214
  }
81
215
  async close() {
82
- require_logger.logger.debug("control_stream", "close: cancelling reader");
216
+ require_emitter.logger.debug("control_stream", "close: cancelling reader");
83
217
  await this.#reader.cancel().catch(() => {});
84
218
  }
85
219
  async #ingestLoop(controller) {
86
- require_logger.logger.debug("control_stream", "ingestLoop: started");
220
+ require_emitter.logger.debug("control_stream", "ingestLoop: started");
87
221
  try {
88
222
  while (true) {
89
223
  if (this.#receiveBuffer.length === 0) {
90
- require_logger.logger.debug("control_stream", "ingestLoop: buffer empty, awaiting reader.read()");
224
+ require_emitter.logger.debug("control_stream", "ingestLoop: buffer empty, awaiting reader.read()");
91
225
  const readResult = await this.#reader.read();
92
226
  this.#handleReadResult(readResult);
93
227
  if (readResult.done) {
94
- require_logger.logger.debug("control_stream", "ingestLoop: reader done (stream closed by peer)");
228
+ require_emitter.logger.debug("control_stream", "ingestLoop: reader done (stream closed by peer)");
95
229
  break;
96
230
  }
97
- require_logger.logger.debug("control_stream", `ingestLoop: received ${readResult.value?.byteLength ?? 0}B chunk`);
231
+ require_emitter.logger.debug("control_stream", `ingestLoop: received ${readResult.value?.byteLength ?? 0}B chunk`);
98
232
  continue;
99
233
  }
100
234
  try {
@@ -109,35 +243,35 @@ var ControlRecvStream = class {
109
243
  this.#receiveBuffer.commit();
110
244
  this.#expectedPayloadLength = null;
111
245
  const msg = require_model.ControlMessage.deserialize(new require_model.FrozenByteBuffer(messageBytes));
112
- require_logger.logger.debug("control_stream", `ingestLoop: deserialized ${msg.constructor.name} (${totalMessageSize}B)`);
246
+ require_emitter.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
- require_logger.logger.debug("control_stream", `ingestLoop: partial message — have ${this.#receiveBuffer.length}B, need ${totalMessageSize}B, awaiting more data`);
252
+ require_emitter.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) {
125
- require_logger.logger.debug("control_stream", "ingestLoop: reader done while waiting for partial message");
259
+ require_emitter.logger.debug("control_stream", "ingestLoop: reader done while waiting for partial message");
126
260
  break;
127
261
  }
128
262
  } catch (error) {
129
263
  if (error instanceof require_model.NotEnoughBytesError) {
130
- require_logger.logger.debug("control_stream", "ingestLoop: not enough bytes for header, awaiting more data");
264
+ require_emitter.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) {
136
- require_logger.logger.debug("control_stream", "ingestLoop: reader done while waiting for header");
270
+ require_emitter.logger.debug("control_stream", "ingestLoop: reader done while waiting for header");
137
271
  break;
138
272
  }
139
273
  } else {
140
- require_logger.logger.error("control_stream", `ingestLoop: deserialization error — ${error.message}`);
274
+ require_emitter.logger.error("control_stream", `ingestLoop: deserialization error — ${error.message}`);
141
275
  controller.error(new require_model.TerminationError(`ControlStream: Deserialization error: ${error.message}`, 3));
142
276
  await this.close();
143
277
  break;
@@ -145,11 +279,11 @@ var ControlRecvStream = class {
145
279
  }
146
280
  }
147
281
  } catch (error) {
148
- require_logger.logger.error("control_stream", `ingestLoop: unexpected error — ${error instanceof Error ? error.message : String(error)}`);
282
+ if (!isSessionClosed(error)) require_emitter.logger.error("control_stream", `ingestLoop: unexpected error — ${errorMessage(error)}`);
149
283
  controller.error(error);
150
284
  await this.close();
151
285
  } finally {
152
- require_logger.logger.debug("control_stream", "ingestLoop: ended, closing controller");
286
+ require_emitter.logger.debug("control_stream", "ingestLoop: ended, closing controller");
153
287
  controller.close();
154
288
  await this.close();
155
289
  }
@@ -157,14 +291,14 @@ var ControlRecvStream = class {
157
291
  #handleReadResult(readResult) {
158
292
  if (readResult.done) {
159
293
  if (this.#receiveBuffer.length > 0 || this.#expectedPayloadLength !== null) {
160
- require_logger.logger.error("control_stream", `handleReadResult: peer closed stream with incomplete data — bufferLen=${this.#receiveBuffer.length} expectedPayload=${this.#expectedPayloadLength}`);
294
+ require_emitter.logger.error("control_stream", `handleReadResult: peer closed stream with incomplete data — bufferLen=${this.#receiveBuffer.length} expectedPayload=${this.#expectedPayloadLength}`);
161
295
  throw new require_model.TerminationError("ControlStream: Stream closed by peer with incomplete message data.", 3);
162
296
  }
163
297
  return;
164
298
  }
165
299
  if (readResult.value) {
166
300
  this.#receiveBuffer.putBytes(readResult.value);
167
- require_logger.logger.debug("control_stream", `handleReadResult: appended ${readResult.value.byteLength}B — bufferLen=${this.#receiveBuffer.length}`);
301
+ require_emitter.logger.debug("control_stream", `handleReadResult: appended ${readResult.value.byteLength}B — bufferLen=${this.#receiveBuffer.length}`);
168
302
  }
169
303
  }
170
304
  };
@@ -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 require_model.MOQtailError {
218
- context;
219
- code;
220
- constructor(context, code) {
221
- super(`[${context}] peer reset the stream with ${require_model.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 require_model.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 require_model.ByteBuffer();
336
377
  this.#reader = biStream.readable.getReader();
337
378
  this.#writer = biStream.writable.getWriter();
@@ -339,7 +380,7 @@ var RequestStream = class RequestStream {
339
380
  start: (controller) => this.#ingestLoop(controller),
340
381
  cancel: () => this.close()
341
382
  });
342
- require_logger.logger.debug("request_stream", "opened");
383
+ require_emitter.logger.debug("request_stream", "opened");
343
384
  }
344
385
  /**
345
386
  * Opens a new bidi stream and writes `first` on it.
@@ -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 (!require_model.ControlMessageType.isFirst(first.getType())) throw new require_model.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);
@@ -373,24 +414,24 @@ var RequestStream = class RequestStream {
373
414
  const serialized = require_model.ControlMessage.serialize(message);
374
415
  await this.#writer.ready;
375
416
  await this.#writer.write(serialized.toUint8Array());
376
- require_logger.logger.debug("request_stream", `sent ${message.constructor.name}`);
377
- this.#hooks.onMessageSent?.(message);
417
+ require_emitter.logger.debug("request_stream", `sent ${message.constructor.name}`);
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);
381
- require_logger.logger.error("request_stream", `send failed: ${msg}`);
421
+ const msg = errorMessage(error);
422
+ require_emitter.logger.error("request_stream", `send failed: ${msg}`);
382
423
  throw new require_model.TerminationError(`RequestStream.send: Failed to write message: ${msg}`, 1);
383
424
  }
384
425
  }
385
426
  async close() {
386
- require_logger.logger.debug("request_stream", "closed");
427
+ require_emitter.logger.debug("request_stream", "closed");
387
428
  await Promise.allSettled([this.#writer.close().catch(() => {}), this.#reader.cancel().catch(() => {})]);
388
429
  }
389
430
  /**
390
431
  * Cancels the request by resetting its stream with `code`.
391
432
  */
392
433
  async reset(code) {
393
- require_logger.logger.debug("request_stream", `reset code=${code}`);
434
+ require_emitter.logger.debug("request_stream", `reset code=${code}`);
394
435
  const reason = streamResetReason(code);
395
436
  await Promise.allSettled([this.#writer.abort(reason).catch(() => {}), this.#reader.cancel(reason).catch(() => {})]);
396
437
  }
@@ -415,7 +456,7 @@ var RequestStream = class RequestStream {
415
456
  this.#receiveBuffer.commit();
416
457
  const msg = require_model.ControlMessage.deserialize(new require_model.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();
@@ -427,7 +468,7 @@ var RequestStream = class RequestStream {
427
468
  this.#handleReadResult(readResult);
428
469
  if (readResult.done) break;
429
470
  } else {
430
- require_logger.logger.error("request_stream", `deserialization error: ${error.message}`);
471
+ require_emitter.logger.error("request_stream", `deserialization error: ${error.message}`);
431
472
  controller.error(new require_model.TerminationError(`RequestStream: Deserialization error: ${error.message}`, 3));
432
473
  await this.close();
433
474
  break;
@@ -435,7 +476,7 @@ var RequestStream = class RequestStream {
435
476
  }
436
477
  }
437
478
  } catch (error) {
438
- require_logger.logger.error("request_stream", "ingest loop error", error);
479
+ if (!isSessionClosed(error)) require_emitter.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 = require_model.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 require_model.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 (require_model.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
- require_logger.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
- require_logger.logger.debug("data_stream", `SendStream opened type=${header.type}`);
604
- return new SendStream(header, writer, reporter, onDataSent, groupOrder);
642
+ require_emitter.logger.debug("data_stream", `SendStream opened type=${header.type}`);
643
+ return new SendStream(header, writer, reporter, events, groupOrder);
605
644
  }
606
645
  async write(object) {
607
646
  let serializedObject;
@@ -610,7 +649,7 @@ var SendStream = class SendStream {
610
649
  this.#fetchPrevCtx = object.nextContext(this.#fetchPrevCtx);
611
650
  } else {
612
651
  if (this.#lastObjectId !== void 0 && object.objectId <= this.#lastObjectId) {
613
- require_logger.logger.error("data_stream", `SendStream out-of-order objectId=${object.objectId} lastObjectId=${this.#lastObjectId}`);
652
+ require_emitter.logger.error("data_stream", `SendStream out-of-order objectId=${object.objectId} lastObjectId=${this.#lastObjectId}`);
614
653
  throw new Error(`SendStream.write: Out-of-order object detected. Attempted to write objectId=${object.objectId}, but lastObjectId=${this.#lastObjectId}.`);
615
654
  }
616
655
  serializedObject = object.serialize(this.#lastObjectId).toUint8Array();
@@ -622,31 +661,23 @@ 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() {
629
668
  if (this.#writer) {
630
- require_logger.logger.debug("data_stream", `SendStream closed type=${this.header.type}`);
669
+ require_emitter.logger.debug("data_stream", `SendStream closed type=${this.header.type}`);
631
670
  await this.#writer.close();
632
671
  this.#reporter.end("fin");
633
672
  }
634
673
  }
635
674
  /** Abruptly tears the stream down, so the peer reads back `code` (§3.3.3). */
636
675
  async reset(code) {
637
- require_logger.logger.debug("data_stream", `SendStream reset type=${this.header.type} code=${code}`);
676
+ require_emitter.logger.debug("data_stream", `SendStream reset type=${this.header.type} code=${code}`);
638
677
  await this.#writer.abort(streamResetReason(code)).catch(() => {});
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 require_model.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 require_model.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
- require_logger.logger.debug("data_stream", `RecvStream opened type=${headerInstance.type}`);
741
+ require_emitter.logger.debug("data_stream", `RecvStream opened type=${headerInstance.type}`);
710
742
  const groupOrder = require_model.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) {
@@ -745,11 +777,11 @@ var RecvStream = class RecvStream {
745
777
  const { done, value } = readResult;
746
778
  if (done) {
747
779
  if (this.#internalBuffer.remaining > 0) {
748
- require_logger.logger.error("data_stream", `RecvStream closed with incomplete data remaining=${this.#internalBuffer.remaining}`);
780
+ require_emitter.logger.error("data_stream", `RecvStream closed with incomplete data remaining=${this.#internalBuffer.remaining}`);
749
781
  this.#reporter.end("error");
750
782
  controller.error(new require_model.ProtocolViolationError("RecvStream", `Stream closed with incomplete object data. Remaining: ${this.#internalBuffer.remaining} bytes.`));
751
783
  } else {
752
- require_logger.logger.debug("data_stream", `RecvStream closed type=${this.header.type}`);
784
+ require_emitter.logger.debug("data_stream", `RecvStream closed type=${this.header.type}`);
753
785
  this.#reporter.end("fin");
754
786
  controller.close();
755
787
  }
@@ -760,10 +792,10 @@ var RecvStream = class RecvStream {
760
792
  } catch (error) {
761
793
  const peerReset = streamResetCodeOf(error);
762
794
  if (peerReset !== void 0) {
763
- require_logger.logger.debug("data_stream", `RecvStream reset by peer code=${require_model.StreamResetCode[peerReset]}`);
795
+ require_emitter.logger.debug("data_stream", `RecvStream reset by peer code=${require_model.StreamResetCode[peerReset]}`);
764
796
  this.#reporter.end("reset", peerReset);
765
797
  } else {
766
- require_logger.logger.error("data_stream", "RecvStream ingest loop error", error);
798
+ if (!isSessionClosed(error)) require_emitter.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
  }
@@ -772,83 +804,11 @@ var RecvStream = class RecvStream {
772
804
  }
773
805
  /** Asks the peer to stop sending on this stream, reporting `code` (§3.3.3). */
774
806
  async stopSending(code) {
775
- require_logger.logger.debug("data_stream", `RecvStream stopSending type=${this.header.type} code=${code}`);
807
+ require_emitter.logger.debug("data_stream", `RecvStream stopSending type=${this.header.type} code=${code}`);
776
808
  await this.#reader.cancel(streamResetReason(code)).catch(() => {});
777
809
  }
778
810
  };
779
- //#endregion
780
- //#region src/client/track/content_source.ts
781
- var StaticTrackSource = class {
782
- cache;
783
- constructor(cache) {
784
- this.cache = cache;
785
- }
786
- async getRange(start, end) {
787
- return this.cache.getRange(start, end);
788
- }
789
- };
790
- var LiveTrackSource = class {
791
- stream;
792
- #listeners = /* @__PURE__ */ new Set();
793
- #doneListeners = /* @__PURE__ */ new Set();
794
- #largestLocation;
795
- #ingestActive = false;
796
- #reader;
797
- constructor(stream) {
798
- this.stream = stream;
799
- this.#startIngest();
800
- }
801
- get largestLocation() {
802
- return this.#largestLocation;
803
- }
804
- async #startIngest() {
805
- if (this.#ingestActive) return;
806
- this.#ingestActive = true;
807
- try {
808
- this.#reader = this.stream.getReader();
809
- while (this.#ingestActive) {
810
- const { value, done } = await this.#reader.read();
811
- if (done) break;
812
- this.#largestLocation = value.location;
813
- for (const listener of this.#listeners) listener(value);
814
- }
815
- } catch (error) {
816
- require_logger.logger.error("track/content_source", "Error during live object ingestion:", error);
817
- } finally {
818
- this.#ingestActive = false;
819
- this.#reader?.releaseLock();
820
- for (const doneListener of this.#doneListeners) Promise.resolve().then(() => doneListener());
821
- }
822
- }
823
- onNewObject(listener) {
824
- let queue = Promise.resolve();
825
- const queuedListener = (obj) => {
826
- queue = queue.then(() => listener(obj)).catch((err) => {
827
- require_logger.logger.error("track/content_source", "Error in subscriber listener:", err);
828
- });
829
- };
830
- this.#listeners.add(queuedListener);
831
- return () => this.#listeners.delete(queuedListener);
832
- }
833
- onDone(listener) {
834
- this.#doneListeners.add(listener);
835
- return () => this.#doneListeners.delete(listener);
836
- }
837
- stop() {
838
- this.#ingestActive = false;
839
- this.#reader?.cancel();
840
- }
841
- };
842
- var HybridTrackSource = class {
843
- past;
844
- live;
845
- constructor(cache, stream) {
846
- this.past = new StaticTrackSource(cache);
847
- this.live = new LiveTrackSource(stream);
848
- }
849
- };
850
- //#endregion
851
- //#region src/client/request/publish_namespace.ts
811
+ // src/client/request/publish_namespace.ts
852
812
  /**
853
813
  * Copyright 2026 The MOQtail Authors
854
814
  *
@@ -877,15 +837,15 @@ var PublishNamespaceRequest = class {
877
837
  this._resolve = resolve;
878
838
  this._reject = reject;
879
839
  });
880
- require_logger.logger.debug("request/publish_namespace", `created requestId=${this.requestId} namespace="${message.trackNamespace}"`);
840
+ require_emitter.logger.debug("request/publish_namespace", `created requestId=${this.requestId} namespace="${message.trackNamespace}"`);
881
841
  }
882
842
  resolve(value) {
883
- if (value instanceof require_model.RequestError) require_logger.logger.error("request/publish_namespace", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
884
- else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/publish_namespace", `resolved with OK requestId=${this.requestId}`);
843
+ if (value instanceof require_model.RequestError) require_emitter.logger.error("request/publish_namespace", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
844
+ else if (value instanceof require_model.RequestOk) require_emitter.logger.debug("request/publish_namespace", `resolved with OK requestId=${this.requestId}`);
885
845
  this._resolve(value);
886
846
  }
887
847
  reject(reason) {
888
- require_logger.logger.error("request/publish_namespace", `rejected requestId=${this.requestId}`, reason);
848
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/publish_namespace", `rejected requestId=${this.requestId}`, reason);
889
849
  this._reject(reason);
890
850
  }
891
851
  then(onfulfilled, onrejected) {
@@ -898,38 +858,67 @@ var PublishNamespaceRequest = class {
898
858
  return this.promise.finally(onfinally);
899
859
  }
900
860
  };
901
- //#endregion
902
- //#region src/client/request/fetch.ts
861
+ // src/client/util/object_stream.ts
862
+ /**
863
+ * A request's consumer-facing object stream. The consumer may cancel it while objects are
864
+ * still in flight, so writes after that, or after it closed or errored, are dropped.
865
+ */
866
+ var ObjectStream = class {
867
+ readable;
868
+ #controller;
869
+ #open = true;
870
+ constructor() {
871
+ this.readable = new ReadableStream({
872
+ start: (controller) => {
873
+ this.#controller = controller;
874
+ },
875
+ cancel: () => {
876
+ this.#open = false;
877
+ }
878
+ });
879
+ }
880
+ /** False once closed, cancelled by the consumer, or errored: nothing written is read. */
881
+ get open() {
882
+ return this.#open && this.#controller.desiredSize !== null;
883
+ }
884
+ enqueue(object) {
885
+ if (this.open) this.#controller.enqueue(object);
886
+ }
887
+ close() {
888
+ if (!this.open) return;
889
+ this.#open = false;
890
+ this.#controller.close();
891
+ }
892
+ };
893
+ // src/client/request/fetch.ts
903
894
  var FetchRequest = class {
904
895
  requestId;
905
896
  message;
906
897
  _resolve;
907
898
  _reject;
908
899
  promise;
909
- controller;
910
- stream;
900
+ objects = new ObjectStream();
901
+ stream = this.objects.readable;
911
902
  onEndOfRange;
903
+ orderer;
912
904
  isActive = true;
913
905
  isResolved = false;
914
906
  constructor(message) {
915
907
  this.requestId = message.requestId;
916
908
  this.message = message;
917
- this.stream = new ReadableStream({ start: (controller) => {
918
- this.controller = controller;
919
- } });
920
909
  this.promise = new Promise((resolve, reject) => {
921
910
  this._resolve = resolve;
922
911
  this._reject = reject;
923
912
  });
924
- require_logger.logger.debug("request/fetch", `created requestId=${this.requestId}`);
913
+ require_emitter.logger.debug("request/fetch", `created requestId=${this.requestId}`);
925
914
  }
926
915
  resolve(value) {
927
- if (value instanceof require_model.RequestError) require_logger.logger.error("request/fetch", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
928
- else if (value instanceof require_model.FetchOk) require_logger.logger.debug("request/fetch", `resolved with OK requestId=${this.requestId}`);
916
+ if (value instanceof require_model.RequestError) require_emitter.logger.error("request/fetch", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
917
+ else if (value instanceof require_model.FetchOk) require_emitter.logger.debug("request/fetch", `resolved with OK requestId=${this.requestId}`);
929
918
  this._resolve(value);
930
919
  }
931
920
  reject(reason) {
932
- require_logger.logger.error("request/fetch", `rejected requestId=${this.requestId}`, reason);
921
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/fetch", `rejected requestId=${this.requestId}`, reason);
933
922
  this._reject(reason);
934
923
  }
935
924
  then(onfulfilled, onrejected) {
@@ -942,8 +931,7 @@ var FetchRequest = class {
942
931
  return this.promise.finally(onfinally);
943
932
  }
944
933
  };
945
- //#endregion
946
- //#region src/client/types.ts
934
+ // src/client/types.ts
947
935
  /**
948
936
  * Default for {@link MOQtailClientOptions.trackAliasResolutionTimeoutMs}: how long a
949
937
  * data stream waits for the control message that establishes its track alias.
@@ -963,13 +951,17 @@ const DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS = 2e3;
963
951
  */
964
952
  const DEFAULT_SWITCH_DRAIN_TIMEOUT_MS = 2e3;
965
953
  /**
954
+ * Default for {@link MOQtailClientOptions.fillOpenTimeoutMs}: how long after SUBSCRIBE_OK
955
+ * a fill fetch stream may take to open before ordering stops waiting for it.
956
+ */
957
+ const DEFAULT_FILL_OPEN_TIMEOUT_MS = 1e3;
958
+ /**
966
959
  * @public
967
960
  * The MAX_FILTER_RANGES a client advertises when its setup options set none: how
968
961
  * many Range Filter ranges it applies, in total, for one subscription or fetch.
969
962
  */
970
963
  const DEFAULT_MAX_FILTER_RANGES = 32n;
971
- //#endregion
972
- //#region src/client/request/subscribe.ts
964
+ // src/client/request/subscribe.ts
973
965
  /**
974
966
  * Represents an active subscription request in MOQT, implementing `PromiseLike`
975
967
  * for convenient async resolution when subscription setup succeeds or fails.
@@ -991,14 +983,24 @@ var SubscribeRequest = class {
991
983
  * which is where a fill fetch stream stops.
992
984
  */
993
985
  fillBoundary;
986
+ /** A fill fetch stream opened for this subscription. */
987
+ fillOpened = false;
988
+ /** Fill fetch streams still delivering. */
989
+ openFills = 0;
994
990
  /** EXPIRES from the last SUBSCRIBE_OK or REQUEST_UPDATE_OK, in milliseconds. */
995
991
  expires;
996
992
  streamsAccepted = 0n;
997
993
  expectedStreams;
998
- /** The Subscription managing this request's output stream once switching is involved. */
994
+ /** The last PUBLISH_DONE received for this request. */
995
+ publishDone;
996
+ #finished = Promise.withResolvers();
997
+ /** Resolves once this request is over, with {@link SubscribeRequest.publishDone}. Never rejects. */
998
+ done = this.#finished.promise;
999
+ /** The Subscription that owns this request's consumer stream; it sets itself on construction. */
999
1000
  manager;
1000
- controller;
1001
- stream;
1001
+ objects = new ObjectStream();
1002
+ stream = this.objects.readable;
1003
+ orderer;
1002
1004
  #promise;
1003
1005
  #resolve;
1004
1006
  #reject;
@@ -1013,14 +1015,11 @@ var SubscribeRequest = class {
1013
1015
  const fwd = msg.parameters.find(require_model.MessageParameter.isForward);
1014
1016
  this.forward = fwd?.forward ?? true;
1015
1017
  this.subscribeParameters = msg.parameters;
1016
- this.stream = new ReadableStream({ start: (controller) => {
1017
- this.controller = controller;
1018
- } });
1019
1018
  this.#promise = new Promise((resolve, reject) => {
1020
1019
  this.#resolve = resolve;
1021
1020
  this.#reject = reject;
1022
1021
  });
1023
- require_logger.logger.debug("request/subscribe", `created requestId=${this.requestId} ftn="${this.fullTrackName}" priority=${this.priority} forward=${this.forward}`);
1022
+ require_emitter.logger.debug("request/subscribe", `created requestId=${this.requestId} ftn="${this.fullTrackName}" priority=${this.priority} forward=${this.forward}`);
1024
1023
  }
1025
1024
  /**
1026
1025
  * Updates subscription parameters in-place when a `RequestUpdate` message is received.
@@ -1036,6 +1035,22 @@ var SubscribeRequest = class {
1036
1035
  if (typeof require_model.applyMessageParameterUpdate === "function") require_model.applyMessageParameterUpdate(this.subscribeParameters, msg.parameters);
1037
1036
  }
1038
1037
  /**
1038
+ * Puts an object on the consumer stream, through {@link SubscribeRequest.orderer} when
1039
+ * there is one. `previous` is the object before it on the same fill fetch stream.
1040
+ */
1041
+ enqueue(obj, previous) {
1042
+ if (this.orderer) this.orderer.push(obj, previous);
1043
+ else this.output(obj);
1044
+ }
1045
+ /** Writes an object the orderer released, or an unordered one, through the manager. */
1046
+ output(obj) {
1047
+ this.manager.output(this, obj);
1048
+ }
1049
+ /** Ends the request: resolves {@link SubscribeRequest.done}. Later calls do nothing. */
1050
+ finish() {
1051
+ this.#finished.resolve(this.publishDone);
1052
+ }
1053
+ /**
1039
1054
  * Marks this subscription request as canceled.
1040
1055
  */
1041
1056
  unsubscribe() {
@@ -1045,15 +1060,15 @@ var SubscribeRequest = class {
1045
1060
  * Resolves the internal promise with a `SubscribeOk` or `RequestError`.
1046
1061
  */
1047
1062
  resolve(value) {
1048
- if (value instanceof require_model.RequestError) require_logger.logger.error("request/subscribe", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
1049
- else if (value instanceof require_model.SubscribeOk) require_logger.logger.debug("request/subscribe", `resolved with OK requestId=${this.requestId} trackAlias=${value.trackAlias}`);
1063
+ if (value instanceof require_model.RequestError) require_emitter.logger.error("request/subscribe", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
1064
+ else if (value instanceof require_model.SubscribeOk) require_emitter.logger.debug("request/subscribe", `resolved with OK requestId=${this.requestId} trackAlias=${value.trackAlias}`);
1050
1065
  this.#resolve(value);
1051
1066
  }
1052
1067
  /**
1053
1068
  * Rejects the internal promise with an error/reason.
1054
1069
  */
1055
1070
  reject(reason) {
1056
- require_logger.logger.error("request/subscribe", `rejected requestId=${this.requestId}`, reason);
1071
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/subscribe", `rejected requestId=${this.requestId}`, reason);
1057
1072
  this.#reject(reason);
1058
1073
  }
1059
1074
  then(onfulfilled, onrejected) {
@@ -1079,10 +1094,17 @@ var SubscribeRequest = class {
1079
1094
  * subscription is done, or until it has been quiet long enough to say so itself.
1080
1095
  */
1081
1096
  var Subscription = class {
1082
- controller;
1097
+ objects;
1083
1098
  stream;
1084
1099
  /** Oldest first; the last entry is the newest switch target still racing to produce data. */
1085
1100
  #requests;
1101
+ /** Requests {@link Subscription.done} has yet to wait for, oldest first. */
1102
+ #unwaited;
1103
+ /**
1104
+ * Resolves once every tracked request is over, with the newest one's PUBLISH_DONE, or
1105
+ * `undefined` if it ended without one. Never rejects.
1106
+ */
1107
+ done;
1086
1108
  /**
1087
1109
  * Requests a soft switch handed over from, still delivering the tail of what they
1088
1110
  * were told to finish, each with the timer that retires it if it goes quiet.
@@ -1090,6 +1112,8 @@ var Subscription = class {
1090
1112
  #draining = /* @__PURE__ */ new Map();
1091
1113
  /** Switch targets whose handover drains what it supersedes rather than cutting it. */
1092
1114
  #drainsSuperseded = /* @__PURE__ */ new WeakSet();
1115
+ /** The newest request's ordered objects, held while older requests still deliver. */
1116
+ #parked = [];
1093
1117
  /** Set once by `MOQtailClient.switch`; invoked with everything older on cutover. */
1094
1118
  onSuperseded;
1095
1119
  /** Set by the client to decide whether draining a request should continue. */
@@ -1102,9 +1126,19 @@ var Subscription = class {
1102
1126
  drainTimeoutMs = DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
1103
1127
  constructor(initial) {
1104
1128
  this.stream = initial.stream;
1105
- this.controller = initial.controller;
1129
+ this.objects = initial.objects;
1106
1130
  initial.manager = this;
1107
1131
  this.#requests = [initial];
1132
+ this.#unwaited = [initial];
1133
+ this.done = this.#allDone();
1134
+ }
1135
+ async #allDone() {
1136
+ let batch = [];
1137
+ while (this.#unwaited.length > 0) {
1138
+ batch = this.#unwaited.splice(0);
1139
+ await Promise.all(batch.map((request) => request.done));
1140
+ }
1141
+ return batch.at(-1)?.publishDone;
1108
1142
  }
1109
1143
  /** Requests still tracked, oldest first, draining ones last. */
1110
1144
  get requests() {
@@ -1114,6 +1148,10 @@ var Subscription = class {
1114
1148
  get newest() {
1115
1149
  return this.#requests[this.#requests.length - 1];
1116
1150
  }
1151
+ /** More than one request tracked, draining ones included. */
1152
+ get #switching() {
1153
+ return this.#requests.length + this.#draining.size > 1;
1154
+ }
1117
1155
  /**
1118
1156
  * Track a newly issued switch target alongside whatever is still delivering.
1119
1157
  *
@@ -1125,24 +1163,54 @@ var Subscription = class {
1125
1163
  request.manager = this;
1126
1164
  if (drainSuperseded) this.#drainsSuperseded.add(request);
1127
1165
  this.#requests.push(request);
1166
+ this.#unwaited.push(request);
1167
+ this.#updateSwitchState();
1168
+ }
1169
+ /**
1170
+ * Writes an object `request` released. While older requests still deliver, the newest
1171
+ * one's ordered objects wait, so the old track's tail comes first.
1172
+ */
1173
+ output(request, obj) {
1174
+ if (request.orderer && request === this.newest && this.#switching) this.#parked.push(obj);
1175
+ else this.objects.enqueue(obj);
1176
+ }
1177
+ /**
1178
+ * While a switch is in progress no ordering window expires, and once it's over the
1179
+ * parked objects go out first. `left` stopped being tracked.
1180
+ */
1181
+ #updateSwitchState(left = []) {
1182
+ const switching = this.#switching;
1183
+ if (!switching && this.#draining.size === 0) for (const obj of this.#parked.splice(0)) this.objects.enqueue(obj);
1184
+ for (const request of this.requests) if (switching) request.orderer?.suspendWindow("switch");
1185
+ else request.orderer?.resumeWindow("switch");
1186
+ for (const request of left) request.orderer?.resumeWindow("switch");
1187
+ }
1188
+ /** Hands `requests` to `onSuperseded`, which flushes what they still hold, then stops tracking them. */
1189
+ #retire(requests) {
1190
+ this.onSuperseded?.(requests);
1191
+ this.#updateSwitchState(requests);
1128
1192
  }
1129
1193
  /** Stop tracking `request` (e.g. it naturally completed without ever losing/winning a handover). */
1130
1194
  drop(request) {
1131
1195
  this.#clearDrain(request);
1132
1196
  this.#requests = this.#requests.filter((r) => r !== request);
1197
+ this.#updateSwitchState([request]);
1133
1198
  }
1134
1199
  /** Stop tracking everything (used when the whole switch chain is torn down at once). */
1135
1200
  clear() {
1201
+ const left = this.requests;
1136
1202
  for (const request of [...this.#draining.keys()]) this.#clearDrain(request);
1137
1203
  this.#requests = [];
1204
+ this.#parked = [];
1205
+ this.#updateSwitchState(left);
1138
1206
  }
1139
1207
  /** Starts, or on each further object restarts, the quiet period that ends a drain. */
1140
1208
  #keepDraining(request) {
1141
1209
  this.#clearDrain(request);
1142
1210
  this.#draining.set(request, setTimeout(() => {
1143
1211
  this.#draining.delete(request);
1144
- require_logger.logger.debug("Subscription", `drain of request ${request.requestId} ended on silence`);
1145
- this.onSuperseded?.([request]);
1212
+ require_emitter.logger.debug("Subscription", `drain of request ${request.requestId} ended on silence`);
1213
+ this.#retire([request]);
1146
1214
  }, this.drainTimeoutMs));
1147
1215
  }
1148
1216
  #clearDrain(request) {
@@ -1159,31 +1227,32 @@ var Subscription = class {
1159
1227
  * Returns `true` if the object was delivered to the caller,
1160
1228
  * `false` if it was not consumed, and client should cancel the stream.
1161
1229
  */
1162
- deliver(request, obj) {
1230
+ deliver(request, obj, previous) {
1163
1231
  if (this.#draining.has(request)) {
1164
- if (this.onDrainDecision?.(request)) {
1232
+ if (this.onDrainDecision(request)) {
1165
1233
  this.#keepDraining(request);
1166
- this.controller.enqueue(obj);
1234
+ request.enqueue(obj, previous);
1167
1235
  return true;
1168
1236
  }
1237
+ this.#clearDrain(request);
1238
+ this.#retire([request]);
1169
1239
  return false;
1170
1240
  }
1171
1241
  if (!this.#requests.includes(request)) {
1172
- require_logger.logger.warn("Subscription", `discarding object from superseded request ${request.requestId}`);
1242
+ require_emitter.logger.warn("Subscription", `discarding object from superseded request ${request.requestId}`);
1173
1243
  return false;
1174
1244
  }
1175
1245
  if (request === this.newest && this.#requests.length > 1) {
1176
1246
  const superseded = this.#requests.slice(0, -1);
1177
1247
  this.#requests = [request];
1178
1248
  if (this.#drainsSuperseded.has(request)) for (const old of superseded) this.#keepDraining(old);
1179
- else this.onSuperseded?.(superseded);
1249
+ else this.#retire(superseded);
1180
1250
  }
1181
- this.controller.enqueue(obj);
1251
+ request.enqueue(obj, previous);
1182
1252
  return true;
1183
1253
  }
1184
1254
  };
1185
- //#endregion
1186
- //#region src/client/request/publish.ts
1255
+ // src/client/request/publish.ts
1187
1256
  /**
1188
1257
  * Copyright 2025 The MOQtail Authors
1189
1258
  *
@@ -1212,15 +1281,15 @@ var PublishRequest = class {
1212
1281
  this._resolve = resolve;
1213
1282
  this._reject = reject;
1214
1283
  });
1215
- require_logger.logger.debug("request/publish", `created requestId=${this.requestId} ftn="${msg.fullTrackName}"`);
1284
+ require_emitter.logger.debug("request/publish", `created requestId=${this.requestId} ftn="${msg.fullTrackName}"`);
1216
1285
  }
1217
1286
  resolve(value) {
1218
- if (value instanceof require_model.RequestError) require_logger.logger.error("request/publish", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
1219
- else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/publish", `resolved with OK requestId=${this.requestId}`);
1287
+ if (value instanceof require_model.RequestError) require_emitter.logger.error("request/publish", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
1288
+ else if (value instanceof require_model.RequestOk) require_emitter.logger.debug("request/publish", `resolved with OK requestId=${this.requestId}`);
1220
1289
  this._resolve(value);
1221
1290
  }
1222
1291
  reject(reason) {
1223
- require_logger.logger.error("request/publish", `rejected requestId=${this.requestId}`, reason);
1292
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/publish", `rejected requestId=${this.requestId}`, reason);
1224
1293
  this._reject(reason);
1225
1294
  }
1226
1295
  then(onfulfilled, onrejected) {
@@ -1233,8 +1302,7 @@ var PublishRequest = class {
1233
1302
  return this.promise.finally(onfinally);
1234
1303
  }
1235
1304
  };
1236
- //#endregion
1237
- //#region src/client/request/track_status.ts
1305
+ // src/client/request/track_status.ts
1238
1306
  /**
1239
1307
  * Copyright 2026 The MOQtail Authors
1240
1308
  *
@@ -1263,15 +1331,15 @@ var TrackStatusRequest = class {
1263
1331
  this._resolve = resolve;
1264
1332
  this._reject = reject;
1265
1333
  });
1266
- require_logger.logger.debug("request/track_status", `created requestId=${this.requestId} ftn="${msg.fullTrackName}"`);
1334
+ require_emitter.logger.debug("request/track_status", `created requestId=${this.requestId} ftn="${msg.fullTrackName}"`);
1267
1335
  }
1268
1336
  resolve(value) {
1269
- if (value instanceof require_model.RequestError) require_logger.logger.error("request/track_status", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
1270
- else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/track_status", `resolved with OK requestId=${this.requestId}`);
1337
+ if (value instanceof require_model.RequestError) require_emitter.logger.error("request/track_status", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
1338
+ else if (value instanceof require_model.RequestOk) require_emitter.logger.debug("request/track_status", `resolved with OK requestId=${this.requestId}`);
1271
1339
  this._resolve(value);
1272
1340
  }
1273
1341
  reject(reason) {
1274
- require_logger.logger.error("request/track_status", `rejected requestId=${this.requestId}`, reason);
1342
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/track_status", `rejected requestId=${this.requestId}`, reason);
1275
1343
  this._reject(reason);
1276
1344
  }
1277
1345
  then(onfulfilled, onrejected) {
@@ -1284,8 +1352,7 @@ var TrackStatusRequest = class {
1284
1352
  return this.promise.finally(onfinally);
1285
1353
  }
1286
1354
  };
1287
- //#endregion
1288
- //#region src/client/handler/publish.ts
1355
+ // src/client/handler/publish.ts
1289
1356
  /**
1290
1357
  * Copyright 2025 The MOQtail Authors
1291
1358
  *
@@ -1302,27 +1369,12 @@ var TrackStatusRequest = class {
1302
1369
  * limitations under the License.
1303
1370
  */
1304
1371
  const handlerPublish = async (client, msg, stream) => {
1305
- require_logger.logger.log("handler/publish", "track: %s alias: %d", msg.fullTrackName.toString(), msg.trackAlias);
1306
- let streamController;
1307
- const objects = new ReadableStream({ start(c) {
1308
- streamController = c;
1309
- } });
1310
- const localPseudoRequestId = client.allocatePseudoRequestId();
1311
- client.requestIdMap.addMapping(localPseudoRequestId, msg.fullTrackName);
1312
- client.subscriptionAliasMap.set(localPseudoRequestId, msg.trackAlias);
1313
- client.aliasFullTrackNameMap.set(msg.trackAlias, msg.fullTrackName);
1314
- const receiver = {
1315
- requestId: localPseudoRequestId,
1316
- streamsAccepted: 0,
1317
- largestLocation: void 0,
1318
- controller: streamController
1319
- };
1320
- client.subscriptions.set(msg.trackAlias, receiver);
1321
- if (client.onPeerPublish) client.onPeerPublish(msg, objects);
1372
+ require_emitter.logger.log("handler/publish", "track: %s alias: %d", msg.fullTrackName.toString(), msg.trackAlias);
1373
+ const objects = client.acceptPushedTrack(msg);
1374
+ client.emit("peerpublish", msg, objects);
1322
1375
  await stream.send(new require_model.RequestOk());
1323
1376
  };
1324
- //#endregion
1325
- //#region src/client/handler/publish_namespace.ts
1377
+ // src/client/handler/publish_namespace.ts
1326
1378
  /**
1327
1379
  * Copyright 2025 The MOQtail Authors
1328
1380
  *
@@ -1339,12 +1391,11 @@ const handlerPublish = async (client, msg, stream) => {
1339
1391
  * limitations under the License.
1340
1392
  */
1341
1393
  const handlerPublishNamespace = async (client, msg, stream) => {
1342
- require_logger.logger.log("handler/publish_namespace", "namespace", msg.trackNamespace.toUtf8Path());
1343
- if (client.onNamespacePublished) client.onNamespacePublished(msg);
1394
+ require_emitter.logger.log("handler/publish_namespace", "namespace", msg.trackNamespace.toUtf8Path());
1395
+ client.emit("namespacepublished", msg);
1344
1396
  await stream.send(new require_model.RequestOk());
1345
1397
  };
1346
- //#endregion
1347
- //#region src/client/handler/publish_skipped.ts
1398
+ // src/client/handler/publish_skipped.ts
1348
1399
  /**
1349
1400
  * Copyright 2026 The MOQtail Authors
1350
1401
  *
@@ -1363,11 +1414,10 @@ const handlerPublishNamespace = async (client, msg, stream) => {
1363
1414
  const handlerPublishSkipped = async (client, msg, stream) => {
1364
1415
  const first = stream.first;
1365
1416
  if (!(first instanceof require_model.SubscribeTracks)) throw new require_model.ProtocolViolationError("handlerPublishSkipped", "PUBLISH_SKIPPED on a stream this side did not open with SUBSCRIBE_TRACKS");
1366
- require_logger.logger.log("handler/publish_skipped", "prefix", first.trackNamespacePrefix.toUtf8Path(), "suffix", msg.trackNamespaceSuffix.toUtf8Path());
1367
- client.onPeerPublishSkipped?.(first.trackNamespacePrefix, msg);
1417
+ require_emitter.logger.log("handler/publish_skipped", "prefix", first.trackNamespacePrefix.toUtf8Path(), "suffix", msg.trackNamespaceSuffix.toUtf8Path());
1418
+ client.emit("peerpublishskipped", first.trackNamespacePrefix, msg);
1368
1419
  };
1369
- //#endregion
1370
- //#region src/client/publication/subgroup.ts
1420
+ // src/client/publication/subgroup.ts
1371
1421
  /**
1372
1422
  * Copyright 2026 The MOQtail Authors
1373
1423
  *
@@ -1429,8 +1479,7 @@ function subgroupHeaderFor(obj, subgroupId, trackAlias, publisherPriority, first
1429
1479
  const explicit = require_model.SubgroupHeaderType.hasExplicitSubgroupId(headerType) ? subgroupId : void 0;
1430
1480
  return new require_model.SubgroupHeader(headerType, trackAlias, obj.location.group, explicit, publisherPriority);
1431
1481
  }
1432
- //#endregion
1433
- //#region src/client/publication/fetch.ts
1482
+ // src/client/publication/fetch.ts
1434
1483
  /**
1435
1484
  * Copyright 2025 The MOQtail Authors
1436
1485
  *
@@ -1468,11 +1517,11 @@ var FetchPublication = class {
1468
1517
  this.#startLocation = start;
1469
1518
  this.#endLocation = end;
1470
1519
  this.#filter = new require_model.CombinedFilter(fetchRequest.parameters);
1471
- require_logger.logger.debug("publication/fetch", `created requestId=${this.#requestId}`);
1520
+ require_emitter.logger.debug("publication/fetch", `created requestId=${this.#requestId}`);
1472
1521
  this.publish();
1473
1522
  }
1474
1523
  cancel() {
1475
- require_logger.logger.debug("publication/fetch", `canceled requestId=${this.#requestId}`);
1524
+ require_emitter.logger.debug("publication/fetch", `canceled requestId=${this.#requestId}`);
1476
1525
  this.#isCanceled = true;
1477
1526
  }
1478
1527
  /**
@@ -1480,27 +1529,27 @@ var FetchPublication = class {
1480
1529
  * a REQUEST_UPDATE for a FETCH fails.
1481
1530
  */
1482
1531
  async resetDataStream(code) {
1483
- require_logger.logger.debug("publication/fetch", `reset data stream requestId=${this.#requestId} code=${code}`);
1532
+ require_emitter.logger.debug("publication/fetch", `reset data stream requestId=${this.#requestId} code=${code}`);
1484
1533
  this.#isCanceled = true;
1485
1534
  await this.#sendStream?.reset(code);
1486
1535
  }
1487
1536
  async publish() {
1488
1537
  if (this.#isCanceled) return;
1489
1538
  if (!this.#track.trackSource.past) throw new require_model.MOQtailError("FetchPublication.publish, Track does not support fetch");
1490
- require_logger.logger.debug("publication/fetch", `publishing requestId=${this.#requestId} start=${this.#startLocation} end=${this.#endLocation}`);
1539
+ require_emitter.logger.debug("publication/fetch", `publishing requestId=${this.#requestId} start=${this.#startLocation} end=${this.#endLocation}`);
1491
1540
  try {
1492
1541
  const objects = await this.#track.trackSource.past.getRange(this.#startLocation);
1493
1542
  this.#objects = objects.filter((obj) => obj.location.compare(this.#endLocation) <= 0);
1494
1543
  const writeStream = await this.#client.webTransport.createUnidirectionalStream();
1495
1544
  const header = new require_model.FetchHeader(5, this.#requestId);
1496
- this.#sendStream = await SendStream.new(writeStream, header, this.#client.onDataSent, require_model.MessageParameter.groupOrderOf(this.#msg.parameters), this.#client.dataStreamObserver(() => this.#track.fullTrackName));
1545
+ this.#sendStream = await SendStream.new(writeStream, header, this.#client, require_model.MessageParameter.groupOrderOf(this.#msg.parameters), () => this.#track.fullTrackName);
1497
1546
  const subgroupIds = new SubgroupIds();
1498
1547
  let sent = 0;
1499
1548
  for (const obj of this.#objects) {
1500
1549
  subgroupIds.note(obj);
1501
1550
  if (!this.#filter.matches(obj, subgroupIds.of(obj))) continue;
1502
1551
  if (this.#isCanceled) {
1503
- require_logger.logger.debug("publication/fetch", `aborted during publish requestId=${this.#requestId}`);
1552
+ require_emitter.logger.debug("publication/fetch", `aborted during publish requestId=${this.#requestId}`);
1504
1553
  await this.#sendStream.reset(1);
1505
1554
  this.#client.publications.delete(this.#requestId);
1506
1555
  return;
@@ -1509,19 +1558,18 @@ var FetchPublication = class {
1509
1558
  sent++;
1510
1559
  }
1511
1560
  await this.#sendStream.close();
1512
- require_logger.logger.debug("publication/fetch", `published requestId=${this.#requestId} objects=${sent} of ${this.#objects.length}`);
1561
+ require_emitter.logger.debug("publication/fetch", `published requestId=${this.#requestId} objects=${sent} of ${this.#objects.length}`);
1513
1562
  this.#client.publications.delete(this.#requestId);
1514
1563
  } catch (error) {
1515
1564
  if (this.#isCanceled) return;
1516
1565
  await this.#sendStream?.reset(0);
1517
- const message = error instanceof Error ? error.message : String(error);
1518
- require_logger.logger.error("publication/fetch", `publish failed requestId=${this.#requestId}`, message);
1566
+ const message = errorMessage(error);
1567
+ require_emitter.logger.error("publication/fetch", `publish failed requestId=${this.#requestId}`, message);
1519
1568
  throw new require_model.InternalError("FetchPublication.publish", `Failed to publish: ${message}`);
1520
1569
  }
1521
1570
  }
1522
1571
  };
1523
- //#endregion
1524
- //#region src/client/util/validators.ts
1572
+ // src/client/util/validators.ts
1525
1573
  /**
1526
1574
  * Copyright 2026 The MOQtail Authors
1527
1575
  *
@@ -1579,8 +1627,7 @@ function assertWithinFilterRangeLimit(params, limit, context) {
1579
1627
  }
1580
1628
  for (const fill of params.filter(require_model.MessageParameter.isFillParameters)) assertWithinFilterRangeLimit(fill.parameters, limit, `${context} (FILL_PARAMETERS)`);
1581
1629
  }
1582
- //#endregion
1583
- //#region src/client/handler/fetch.ts
1630
+ // src/client/handler/fetch.ts
1584
1631
  /**
1585
1632
  * Copyright 2025 The MOQtail Authors
1586
1633
  *
@@ -1597,10 +1644,10 @@ function assertWithinFilterRangeLimit(params, limit, context) {
1597
1644
  * limitations under the License.
1598
1645
  */
1599
1646
  const handlerFetch = async (client, msg, stream) => {
1600
- require_logger.logger.log("handler/fetch", "requestId", msg.requestId);
1647
+ require_emitter.logger.log("handler/fetch", "requestId", msg.requestId);
1601
1648
  const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
1602
1649
  if (filterRejection) {
1603
- require_logger.logger.warn("handler/fetch", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
1650
+ require_emitter.logger.warn("handler/fetch", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
1604
1651
  await stream.send(filterRejection);
1605
1652
  return;
1606
1653
  }
@@ -1619,7 +1666,7 @@ const handlerFetch = async (client, msg, stream) => {
1619
1666
  const largest = track.trackSource.live?.largestLocation ?? (await track.trackSource.past.getRange()).at(-1)?.location;
1620
1667
  const range = msg.locationFilter.fetchRange(largest);
1621
1668
  if (!range) {
1622
- require_logger.logger.warn("handler/fetch", `requestId=${msg.requestId} selects nothing published (largest=${largest})`);
1669
+ require_emitter.logger.warn("handler/fetch", `requestId=${msg.requestId} selects nothing published (largest=${largest})`);
1623
1670
  const response = new require_model.RequestError(17, 0n, new require_model.ReasonPhrase("Nothing published in the requested range"));
1624
1671
  await stream.send(response);
1625
1672
  return;
@@ -1630,8 +1677,7 @@ const handlerFetch = async (client, msg, stream) => {
1630
1677
  const response = new require_model.FetchOk(false, range.end, [], trackProperties);
1631
1678
  await stream.send(response);
1632
1679
  };
1633
- //#endregion
1634
- //#region src/client/handler/fetch_ok.ts
1680
+ // src/client/handler/fetch_ok.ts
1635
1681
  /**
1636
1682
  * Copyright 2025 The MOQtail Authors
1637
1683
  *
@@ -1648,7 +1694,7 @@ const handlerFetch = async (client, msg, stream) => {
1648
1694
  * limitations under the License.
1649
1695
  */
1650
1696
  const handlerFetchOk = async (client, msg, _stream, requestId) => {
1651
- require_logger.logger.log("handler/fetch_ok", "requestId", requestId);
1697
+ require_emitter.logger.log("handler/fetch_ok", "requestId", requestId);
1652
1698
  const request = client.requests.get(requestId);
1653
1699
  if (request instanceof FetchRequest) {
1654
1700
  if (msg.trackProperties.length > 0) {
@@ -1658,16 +1704,15 @@ const handlerFetchOk = async (client, msg, _stream, requestId) => {
1658
1704
  request.resolve(msg);
1659
1705
  } else throw new require_model.ProtocolViolationError("handlerFetchOk", `FETCH_OK on a stream with no pending fetch request (request id ${requestId})`);
1660
1706
  };
1661
- //#endregion
1662
- //#region src/client/handler/goaway.ts
1707
+ // src/client/handler/goaway.ts
1663
1708
  const handlerGoAway = async (client, msg) => {
1664
- require_logger.logger.log("handler/goaway", "newSessionUri", msg.newSessionUri, "timeout", msg.timeout);
1709
+ require_emitter.logger.log("handler/goaway", "newSessionUri", msg.newSessionUri, "timeout", msg.timeout);
1665
1710
  if (client.goawayReceived) {
1666
1711
  await client.disconnect(new require_model.ProtocolViolationError("handler/goaway", "A second GOAWAY arrived on the control stream"));
1667
1712
  return;
1668
1713
  }
1669
1714
  client.goawayReceived = true;
1670
- if (client.onGoaway) client.onGoaway(msg);
1715
+ client.emit("goaway", msg);
1671
1716
  };
1672
1717
  /**
1673
1718
  * GOAWAY on a request stream: the peer is migrating that one request (§10.4). The
@@ -1675,11 +1720,10 @@ const handlerGoAway = async (client, msg) => {
1675
1720
  * on it, carries on.
1676
1721
  */
1677
1722
  const handlerGoAwayOnRequestStream = async (client, msg, _stream, requestId) => {
1678
- require_logger.logger.log("handler/goaway", `GOAWAY migrating request ${requestId}`, "timeout", msg.timeout);
1723
+ require_emitter.logger.log("handler/goaway", `GOAWAY migrating request ${requestId}`, "timeout", msg.timeout);
1679
1724
  await client.migrateRequest(requestId, msg);
1680
1725
  };
1681
- //#endregion
1682
- //#region src/util/simple_lock.ts
1726
+ // src/util/simple_lock.ts
1683
1727
  var SimpleLock = class {
1684
1728
  acquiredLock = false;
1685
1729
  contQueue = [];
@@ -1707,8 +1751,7 @@ var SimpleLock = class {
1707
1751
  });
1708
1752
  }
1709
1753
  };
1710
- //#endregion
1711
- //#region src/client/util/priority.ts
1754
+ // src/client/util/priority.ts
1712
1755
  /**
1713
1756
  * Copyright 2025 The MOQtail Authors
1714
1757
  *
@@ -1730,8 +1773,7 @@ function getTransportPriority(priority) {
1730
1773
  if (priority === 255) return 0;
1731
1774
  return Math.round((255 - priority) * (Number.MAX_SAFE_INTEGER / 255));
1732
1775
  }
1733
- //#endregion
1734
- //#region src/client/publication/subscribe.ts
1776
+ // src/client/publication/subscribe.ts
1735
1777
  /**
1736
1778
  * Copyright 2025 The MOQtail Authors
1737
1779
  *
@@ -1917,7 +1959,7 @@ var SubscribePublication = class {
1917
1959
  await stream.close();
1918
1960
  }
1919
1961
  } catch (err) {
1920
- require_logger.logger.warn("publication/subscribe", "error in closing stream: id, group, err", this.#id, group, err);
1962
+ require_emitter.logger.warn("publication/subscribe", "error in closing stream: id, group, err", this.#id, group, err);
1921
1963
  } finally {
1922
1964
  await this.#lock.release();
1923
1965
  }
@@ -1964,7 +2006,7 @@ var SubscribePublication = class {
1964
2006
  const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
1965
2007
  const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
1966
2008
  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));
2009
+ const sendStream = await SendStream.new(writeStream, header, this.client, void 0, () => this.track.fullTrackName);
1968
2010
  this.#streams.set(obj.location.group, sendStream);
1969
2011
  this.#streamsOpened++;
1970
2012
  this.#markGroupSeen(obj.location.group);
@@ -1987,8 +2029,7 @@ var SubscribePublication = class {
1987
2029
  });
1988
2030
  }
1989
2031
  };
1990
- //#endregion
1991
- //#region src/client/handler/subscribe.ts
2032
+ // src/client/handler/subscribe.ts
1992
2033
  /**
1993
2034
  * Copyright 2025 The MOQtail Authors
1994
2035
  *
@@ -2005,22 +2046,22 @@ var SubscribePublication = class {
2005
2046
  * limitations under the License.
2006
2047
  */
2007
2048
  const handlerSubscribe = async (client, msg, stream) => {
2008
- require_logger.logger.debug("handler/subscribe", `received requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2049
+ require_emitter.logger.debug("handler/subscribe", `received requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2009
2050
  const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
2010
2051
  if (filterRejection) {
2011
- require_logger.logger.warn("handler/subscribe", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
2052
+ require_emitter.logger.warn("handler/subscribe", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
2012
2053
  await stream.send(filterRejection);
2013
2054
  return;
2014
2055
  }
2015
2056
  const track = client.trackSources.get(msg.fullTrackName.toString());
2016
2057
  if (!track) {
2017
- require_logger.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track not found, sending REQUEST_ERROR`);
2058
+ require_emitter.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track not found, sending REQUEST_ERROR`);
2018
2059
  const subscribeError = new require_model.RequestError(16, 0n, new require_model.ReasonPhrase("Track does not exist"));
2019
2060
  await stream.send(subscribeError);
2020
2061
  return;
2021
2062
  }
2022
2063
  if (!track.trackSource.live) {
2023
- require_logger.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track has no live source, sending REQUEST_ERROR`);
2064
+ require_emitter.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track has no live source, sending REQUEST_ERROR`);
2024
2065
  const response = new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("Requested track does not support subscribe"));
2025
2066
  await stream.send(response);
2026
2067
  return;
@@ -2029,15 +2070,14 @@ const handlerSubscribe = async (client, msg, stream) => {
2029
2070
  const largestLocation = track.trackSource.live.largestLocation;
2030
2071
  const parameters = largestLocation ? [new require_model.LargestObject(largestLocation)] : [];
2031
2072
  const trackProperties = require_model.MessageParameter.includesProperties(msg.parameters) ? track.trackProperties ?? [] : [];
2032
- require_logger.logger.debug("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" trackAlias=${track.trackAlias} largestLocation=${largestLocation ? `${largestLocation.group}:${largestLocation.object}` : "none"} — sending SUBSCRIBE_OK`);
2073
+ require_emitter.logger.debug("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" trackAlias=${track.trackAlias} largestLocation=${largestLocation ? `${largestLocation.group}:${largestLocation.object}` : "none"} — sending SUBSCRIBE_OK`);
2033
2074
  const subscribeOk = require_model.SubscribeOk.create(track.trackAlias, parameters, trackProperties);
2034
2075
  const publication = new SubscribePublication(client, track, msg, stream, largestLocation);
2035
2076
  client.publications.set(msg.requestId, publication);
2036
2077
  await stream.send(subscribeOk);
2037
- require_logger.logger.debug("handler/subscribe", `requestId=${msg.requestId} — SUBSCRIBE_OK sent, publication registered`);
2078
+ require_emitter.logger.debug("handler/subscribe", `requestId=${msg.requestId} — SUBSCRIBE_OK sent, publication registered`);
2038
2079
  };
2039
- //#endregion
2040
- //#region src/client/handler/subscribe_namespace.ts
2080
+ // src/client/handler/subscribe_namespace.ts
2041
2081
  /**
2042
2082
  * Copyright 2025 The MOQtail Authors
2043
2083
  *
@@ -2054,12 +2094,11 @@ const handlerSubscribe = async (client, msg, stream) => {
2054
2094
  * limitations under the License.
2055
2095
  */
2056
2096
  const handlerSubscribeNamespace = async (client, msg, stream) => {
2057
- require_logger.logger.log("handler/subscribe_namespace", "namespace", msg.trackNamespacePrefix.toUtf8Path());
2058
- if (client.onPeerSubscribeNamespace) client.onPeerSubscribeNamespace(msg);
2097
+ require_emitter.logger.log("handler/subscribe_namespace", "namespace", msg.trackNamespacePrefix.toUtf8Path());
2098
+ client.emit("peersubscribenamespace", msg);
2059
2099
  await stream.send(new require_model.RequestOk());
2060
2100
  };
2061
- //#endregion
2062
- //#region src/client/handler/subscribe_tracks.ts
2101
+ // src/client/handler/subscribe_tracks.ts
2063
2102
  /**
2064
2103
  * Copyright 2026 The MOQtail Authors
2065
2104
  *
@@ -2076,7 +2115,7 @@ const handlerSubscribeNamespace = async (client, msg, stream) => {
2076
2115
  * limitations under the License.
2077
2116
  */
2078
2117
  const handlerSubscribeTracks = async (client, msg, stream) => {
2079
- require_logger.logger.log("handler/subscribe_tracks", "prefix", msg.trackNamespacePrefix.toUtf8Path());
2118
+ require_emitter.logger.log("handler/subscribe_tracks", "prefix", msg.trackNamespacePrefix.toUtf8Path());
2080
2119
  if (require_model.MessageParameter.carriesRangeFilter(msg.parameters)) {
2081
2120
  let code = 3;
2082
2121
  let reason = "Range filters on SUBSCRIBE_TRACKS are not supported";
@@ -2087,15 +2126,14 @@ const handlerSubscribeTracks = async (client, msg, stream) => {
2087
2126
  code = 54;
2088
2127
  reason = error.details;
2089
2128
  }
2090
- require_logger.logger.warn("handler/subscribe_tracks", `requestId=${msg.requestId} refused: ${reason}`);
2129
+ require_emitter.logger.warn("handler/subscribe_tracks", `requestId=${msg.requestId} refused: ${reason}`);
2091
2130
  await stream.send(new require_model.RequestError(code, 0n, new require_model.ReasonPhrase(reason)));
2092
2131
  return;
2093
2132
  }
2094
- if (client.onPeerSubscribeTracks) client.onPeerSubscribeTracks(msg);
2133
+ client.emit("peersubscribetracks", msg);
2095
2134
  await stream.send(new require_model.RequestOk());
2096
2135
  };
2097
- //#endregion
2098
- //#region src/client/request/subscribe_namespace.ts
2136
+ // src/client/request/subscribe_namespace.ts
2099
2137
  /**
2100
2138
  * Copyright 2026 The MOQtail Authors
2101
2139
  *
@@ -2124,15 +2162,15 @@ var SubscribeNamespaceRequest = class {
2124
2162
  this._resolve = resolve;
2125
2163
  this._reject = reject;
2126
2164
  });
2127
- require_logger.logger.debug("request/subscribe_namespace", `created requestId=${this.requestId} namespace="${msg.trackNamespacePrefix}"`);
2165
+ require_emitter.logger.debug("request/subscribe_namespace", `created requestId=${this.requestId} namespace="${msg.trackNamespacePrefix}"`);
2128
2166
  }
2129
2167
  resolve(value) {
2130
- if (value instanceof require_model.RequestError) require_logger.logger.error("request/subscribe_namespace", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
2131
- else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/subscribe_namespace", `resolved with OK requestId=${this.requestId}`);
2168
+ if (value instanceof require_model.RequestError) require_emitter.logger.error("request/subscribe_namespace", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
2169
+ else if (value instanceof require_model.RequestOk) require_emitter.logger.debug("request/subscribe_namespace", `resolved with OK requestId=${this.requestId}`);
2132
2170
  this._resolve(value);
2133
2171
  }
2134
2172
  reject(reason) {
2135
- require_logger.logger.error("request/subscribe_namespace", `rejected requestId=${this.requestId}`, reason);
2173
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/subscribe_namespace", `rejected requestId=${this.requestId}`, reason);
2136
2174
  this._reject(reason);
2137
2175
  }
2138
2176
  then(onfulfilled, onrejected) {
@@ -2145,8 +2183,7 @@ var SubscribeNamespaceRequest = class {
2145
2183
  return this.promise.finally(onfinally);
2146
2184
  }
2147
2185
  };
2148
- //#endregion
2149
- //#region src/client/publication/publish.ts
2186
+ // src/client/publication/publish.ts
2150
2187
  /**
2151
2188
  * @public
2152
2189
  * Manages the proactive publication of MOQT objects from a publisher to the relay.
@@ -2249,14 +2286,14 @@ var PublishPublication = class {
2249
2286
  }
2250
2287
  /**
2251
2288
  * Moves the Forward State: false parks the publication, true resumes it. The
2252
- * application hears about the move through {@link MOQtailClient.onForwardStateChange},
2289
+ * application hears about the move through the client's `forwardstatechange` event,
2253
2290
  * which is where a publisher starts or stops the work behind the track -- a camera
2254
2291
  * and an encoder cost the same whether or not anything is listening.
2255
2292
  */
2256
2293
  setForwardState(forward) {
2257
2294
  if (this.#forward === forward) return;
2258
2295
  this.#forward = forward;
2259
- this.client.onForwardStateChange?.(this.publishMsg.requestId, forward);
2296
+ this.client.emit("forwardstatechange", this.publishMsg.requestId, forward);
2260
2297
  }
2261
2298
  /**
2262
2299
  * Applies a REQUEST_UPDATE the peer sent on this publication's request stream. It
@@ -2292,7 +2329,7 @@ var PublishPublication = class {
2292
2329
  }
2293
2330
  this.#isCompleted = true;
2294
2331
  this.#lock.acquire().then(() => {
2295
- for (const [groupId, stream] of this.#streams.entries()) stream.close().catch((e) => require_logger.logger.warn("publication/publish", `Failed to close stream for group ${groupId}:`, e));
2332
+ for (const [groupId, stream] of this.#streams.entries()) stream.close().catch((e) => require_emitter.logger.warn("publication/publish", `Failed to close stream for group ${groupId}:`, e));
2296
2333
  this.#streams.clear();
2297
2334
  this.#lock.release();
2298
2335
  });
@@ -2330,7 +2367,7 @@ var PublishPublication = class {
2330
2367
  const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
2331
2368
  const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
2332
2369
  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));
2370
+ const sendStream = await SendStream.new(writeStream, header, this.client, void 0, () => this.track.fullTrackName);
2334
2371
  this.#streams.set(obj.location.group, sendStream);
2335
2372
  this.#streamsOpened++;
2336
2373
  this.#markGroupSeen(obj.location.group);
@@ -2339,8 +2376,13 @@ var PublishPublication = class {
2339
2376
  }
2340
2377
  const sendStream = this.#streams.get(obj.location.group);
2341
2378
  await this.#lock.acquire();
2342
- await sendStream.write(obj.tryIntoSubgroupObject());
2343
- await this.#lock.release();
2379
+ try {
2380
+ await sendStream.write(obj.tryIntoSubgroupObject());
2381
+ } catch (err) {
2382
+ require_emitter.logger.warn("publication/publish", "subgroup stream write failed, skipping rest of group", obj.location.group, err);
2383
+ } finally {
2384
+ await this.#lock.release();
2385
+ }
2344
2386
  if (this.latestLocation && this.latestLocation.group !== obj.location.group) {
2345
2387
  const prevGroup = this.latestLocation.group;
2346
2388
  try {
@@ -2350,13 +2392,13 @@ var PublishPublication = class {
2350
2392
  try {
2351
2393
  await prevStream.close();
2352
2394
  } catch (err) {
2353
- require_logger.logger.warn("publication/publish", "error in closing stream", prevGroup, err);
2395
+ require_emitter.logger.warn("publication/publish", "error in closing stream", prevGroup, err);
2354
2396
  }
2355
2397
  this.#streams.delete(prevGroup);
2356
2398
  }
2357
2399
  await this.#lock.release();
2358
2400
  } catch (err) {
2359
- require_logger.logger.warn("publication/publish", "error in closing stream: id, latestLocation.group, err", this.#id, this.latestLocation.group, err);
2401
+ require_emitter.logger.warn("publication/publish", "error in closing stream: id, latestLocation.group, err", this.#id, this.latestLocation.group, err);
2360
2402
  }
2361
2403
  }
2362
2404
  await this.#lock.acquire();
@@ -2369,8 +2411,7 @@ var PublishPublication = class {
2369
2411
  });
2370
2412
  }
2371
2413
  };
2372
- //#endregion
2373
- //#region src/client/handler/subscription_response.ts
2414
+ // src/client/handler/subscription_response.ts
2374
2415
  /**
2375
2416
  * Copyright 2026 The MOQtail Authors
2376
2417
  *
@@ -2402,18 +2443,17 @@ function applySubscriptionResponse(client, request, parameters, trackProperties)
2402
2443
  const expires = parameters.find(require_model.MessageParameter.isExpires);
2403
2444
  if (expires) request.expires = expires.expires;
2404
2445
  if (trackProperties.length > 0) {
2405
- require_logger.logger.debug("handler/subscription_response", `requestId=${request.requestId} — applying ${trackProperties.length} track propert(ies)`);
2446
+ require_emitter.logger.debug("handler/subscription_response", `requestId=${request.requestId} — applying ${trackProperties.length} track propert(ies)`);
2406
2447
  const track = client.trackSources.get(request.fullTrackName.toString());
2407
2448
  if (track !== void 0) track.trackProperties = trackProperties;
2408
2449
  }
2409
2450
  }
2410
- //#endregion
2411
- //#region src/client/handler/request_ok.ts
2451
+ // src/client/handler/request_ok.ts
2412
2452
  const handlerRequestOk = async (client, msg, _stream, requestId) => {
2413
- require_logger.logger.log("handler/request_ok", "received RequestOk for requestId:", requestId);
2453
+ require_emitter.logger.log("handler/request_ok", "received RequestOk for requestId:", requestId);
2414
2454
  const request = client.requests.get(requestId);
2415
2455
  if (!request) {
2416
- require_logger.logger.warn("handler/request_ok", `Received RequestOk for unknown or already-resolved request id: ${requestId}`);
2456
+ require_emitter.logger.warn("handler/request_ok", `Received RequestOk for unknown or already-resolved request id: ${requestId}`);
2417
2457
  return;
2418
2458
  }
2419
2459
  msg.validateTrackProperties(request instanceof TrackStatusRequest);
@@ -2421,12 +2461,12 @@ const handlerRequestOk = async (client, msg, _stream, requestId) => {
2421
2461
  request.resolve(msg);
2422
2462
  const fullTrackName = client.requestIdMap.getNameByRequestId(requestId);
2423
2463
  if (!fullTrackName) {
2424
- require_logger.logger.warn("handler/request_ok", `No track mapped for PublishRequest requestId: ${requestId}`);
2464
+ require_emitter.logger.warn("handler/request_ok", `No track mapped for PublishRequest requestId: ${requestId}`);
2425
2465
  return;
2426
2466
  }
2427
2467
  const track = client.trackSources.get(fullTrackName.toString());
2428
2468
  if (!track || !track.trackSource.live) {
2429
- require_logger.logger.warn("handler/request_ok", `Live track source not found for ${fullTrackName.toString()}`);
2469
+ require_emitter.logger.warn("handler/request_ok", `Live track source not found for ${fullTrackName.toString()}`);
2430
2470
  return;
2431
2471
  }
2432
2472
  client.publications.set(requestId, new PublishPublication(client, track, request.message));
@@ -2441,33 +2481,48 @@ const handlerRequestOk = async (client, msg, _stream, requestId) => {
2441
2481
  client.requests.delete(requestId);
2442
2482
  } else throw new require_model.ProtocolViolationError("handlerRequestOk", `Request ID ${requestId} matched a pending request, but it does not expect a RequestOk response.`);
2443
2483
  };
2444
- //#endregion
2445
- //#region src/client/handler/request_error.ts
2484
+ // src/client/handler/request_error.ts
2446
2485
  const handlerRequestError = async (client, msg, _stream, requestId) => {
2447
- require_logger.logger.error("handler/request_error", `received requestId=${requestId} code=${msg.errorCode} reason="${msg.reasonPhrase.phrase}"`);
2486
+ require_emitter.logger.error("handler/request_error", `received requestId=${requestId} code=${msg.errorCode} reason="${msg.reasonPhrase.phrase}"`);
2448
2487
  const request = client.requests.get(requestId);
2449
2488
  if (!request) {
2450
- require_logger.logger.warn("handler/request_error", `requestId=${requestId} — no pending request found (already resolved or unknown)`);
2489
+ require_emitter.logger.warn("handler/request_error", `requestId=${requestId} — no pending request found (already resolved or unknown)`);
2451
2490
  return;
2452
2491
  }
2453
- require_logger.logger.debug("handler/request_error", `requestId=${requestId} — resolving ${request.constructor.name} with error`);
2492
+ require_emitter.logger.debug("handler/request_error", `requestId=${requestId} — resolving ${request.constructor.name} with error`);
2454
2493
  if (request instanceof SubscribeRequest || request instanceof PublishRequest || request instanceof PublishNamespaceRequest || request instanceof SubscribeNamespaceRequest || request instanceof TrackStatusRequest || request instanceof FetchRequest) {
2455
2494
  request.resolve(msg);
2456
2495
  client.requests.delete(requestId);
2457
2496
  }
2458
2497
  };
2459
- //#endregion
2460
- //#region src/client/handler/publish_done.ts
2498
+ // src/client/handler/publish_done.ts
2499
+ /**
2500
+ * Copyright 2025 The MOQtail Authors
2501
+ *
2502
+ * Licensed under the Apache License, Version 2.0 (the "License");
2503
+ * you may not use this file except in compliance with the License.
2504
+ * You may obtain a copy of the License at
2505
+ *
2506
+ * http://www.apache.org/licenses/LICENSE-2.0
2507
+ *
2508
+ * Unless required by applicable law or agreed to in writing, software
2509
+ * distributed under the License is distributed on an "AS IS" BASIS,
2510
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2511
+ * See the License for the specific language governing permissions and
2512
+ * limitations under the License.
2513
+ */
2461
2514
  const handlerPublishDone = async (client, msg, _stream, openingRequestId) => {
2462
- if (client.onPeerPublishDone) client.onPeerPublishDone(msg, openingRequestId);
2463
- const request = client.requests.get(openingRequestId);
2464
- if (request instanceof SubscribeRequest) {
2515
+ client.emit("peerpublishdone", msg, openingRequestId);
2516
+ const alias = client.subscriptionAliasMap.get(openingRequestId);
2517
+ const found = client.requests.get(openingRequestId);
2518
+ const request = found instanceof SubscribeRequest ? found : found === void 0 && alias !== void 0 ? client.subscriptions.get(alias) : void 0;
2519
+ if (request) {
2465
2520
  request.expectedStreams = msg.streamCount;
2521
+ request.publishDone = msg;
2466
2522
  client.completeSubscription(request);
2467
2523
  }
2468
2524
  };
2469
- //#endregion
2470
- //#region src/client/handler/subscribe_ok.ts
2525
+ // src/client/handler/subscribe_ok.ts
2471
2526
  /**
2472
2527
  * Copyright 2025 The MOQtail Authors
2473
2528
  *
@@ -2484,19 +2539,18 @@ const handlerPublishDone = async (client, msg, _stream, openingRequestId) => {
2484
2539
  * limitations under the License.
2485
2540
  */
2486
2541
  const handlerSubscribeOk = async (client, msg, _stream, requestId) => {
2487
- require_logger.logger.debug("handler/subscribe_ok", `received requestId=${requestId} trackAlias=${msg.trackAlias}`);
2542
+ require_emitter.logger.debug("handler/subscribe_ok", `received requestId=${requestId} trackAlias=${msg.trackAlias}`);
2488
2543
  const request = client.requests.get(requestId);
2489
2544
  if (request instanceof SubscribeRequest) {
2490
2545
  applySubscriptionResponse(client, request, msg.parameters, msg.trackProperties);
2491
- require_logger.logger.debug("handler/subscribe_ok", `requestId=${requestId} — resolving SubscribeRequest ftn="${request.fullTrackName}"`);
2546
+ require_emitter.logger.debug("handler/subscribe_ok", `requestId=${requestId} — resolving SubscribeRequest ftn="${request.fullTrackName}"`);
2492
2547
  request.resolve(msg);
2493
2548
  } else {
2494
- require_logger.logger.error("handler/subscribe_ok", `requestId=${requestId} — no pending SubscribeRequest found (got ${request?.constructor.name ?? "undefined"})`);
2549
+ require_emitter.logger.error("handler/subscribe_ok", `requestId=${requestId} — no pending SubscribeRequest found (got ${request?.constructor.name ?? "undefined"})`);
2495
2550
  throw new require_model.ProtocolViolationError("handlerSubscribeOk", "SUBSCRIBE_OK on a stream with no pending subscribe request");
2496
2551
  }
2497
2552
  };
2498
- //#endregion
2499
- //#region src/client/handler/request_update.ts
2553
+ // src/client/handler/request_update.ts
2500
2554
  /**
2501
2555
  * Copyright 2025 The MOQtail Authors
2502
2556
  *
@@ -2519,7 +2573,7 @@ const handlerSubscribeOk = async (client, msg, _stream, requestId) => {
2519
2573
  * arriving anywhere else, a TRACK_STATUS among them, closes the session.
2520
2574
  */
2521
2575
  const handlerRequestUpdate = async (client, msg, stream, requestId) => {
2522
- require_logger.logger.log("handler/request_update", "requestId", requestId);
2576
+ require_emitter.logger.log("handler/request_update", "requestId", requestId);
2523
2577
  if (!isExpectedUpdate(stream)) {
2524
2578
  await client.disconnect(new require_model.ProtocolViolationError("handler/request_update", `Unexpected REQUEST_UPDATE on a ${stream.first ? "locally" : "peer"} opened ${describe(stream.openingType)} stream`));
2525
2579
  return;
@@ -2527,7 +2581,7 @@ const handlerRequestUpdate = async (client, msg, stream, requestId) => {
2527
2581
  const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
2528
2582
  if (filterRejection) {
2529
2583
  const reason = filterRejection.reasonPhrase.phrase;
2530
- require_logger.logger.warn("handler/request_update", `requestId=${requestId} has filters this client cannot take: ${reason}`);
2584
+ require_emitter.logger.warn("handler/request_update", `requestId=${requestId} has filters this client cannot take: ${reason}`);
2531
2585
  await failUpdate(client, stream, requestId, 54, reason);
2532
2586
  return;
2533
2587
  }
@@ -2537,14 +2591,14 @@ const handlerRequestUpdate = async (client, msg, stream, requestId) => {
2537
2591
  publication.update(msg);
2538
2592
  } catch (error) {
2539
2593
  const invalid = error instanceof require_model.InvalidFilterError;
2540
- require_logger.logger.error("handler/request_update", `update failed for requestId=${requestId}`, error);
2594
+ require_emitter.logger.error("handler/request_update", `update failed for requestId=${requestId}`, error);
2541
2595
  await failUpdate(client, stream, requestId, invalid ? 54 : 0, invalid ? error.details : "REQUEST_UPDATE failed");
2542
2596
  return;
2543
2597
  }
2544
2598
  await stream.send(new require_model.RequestOk());
2545
2599
  return;
2546
2600
  }
2547
- require_logger.logger.warn("handler/request_update", `no updatable request for requestId=${requestId}`);
2601
+ require_emitter.logger.warn("handler/request_update", `no updatable request for requestId=${requestId}`);
2548
2602
  await failUpdate(client, stream, requestId, 3, "REQUEST_UPDATE cannot be applied");
2549
2603
  };
2550
2604
  /**
@@ -2586,13 +2640,10 @@ async function failUpdate(client, stream, requestId, errorCode, reason) {
2586
2640
  break;
2587
2641
  case 6:
2588
2642
  case 80:
2589
- case 81:
2590
- await stream.close();
2591
- break;
2643
+ case 81: await stream.close();
2592
2644
  }
2593
2645
  }
2594
- //#endregion
2595
- //#region src/client/handler/track_status.ts
2646
+ // src/client/handler/track_status.ts
2596
2647
  /**
2597
2648
  * Copyright 2025 The MOQtail Authors
2598
2649
  *
@@ -2609,11 +2660,10 @@ async function failUpdate(client, stream, requestId, errorCode, reason) {
2609
2660
  * limitations under the License.
2610
2661
  */
2611
2662
  const handlerTrackStatus = async (_client, msg, stream) => {
2612
- require_logger.logger.debug("handler/track_status", `requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2663
+ require_emitter.logger.debug("handler/track_status", `requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2613
2664
  await stream.send(new require_model.RequestOk());
2614
2665
  };
2615
- //#endregion
2616
- //#region src/client/handler/handler.ts
2666
+ // src/client/handler/handler.ts
2617
2667
  /**
2618
2668
  * Copyright 2025 The MOQtail Authors
2619
2669
  *
@@ -2631,7 +2681,7 @@ const handlerTrackStatus = async (_client, msg, stream) => {
2631
2681
  */
2632
2682
  /**
2633
2683
  * 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
2684
+ * consumed by the handshake in {@link MOQtailClient.init}, so GOAWAY is all that reaches
2635
2685
  * the read loop. Every request type has moved to its own bidi stream — see
2636
2686
  * {@link getHandlerForRequestStreamMessage}.
2637
2687
  */
@@ -2660,8 +2710,7 @@ function getHandlerForRequestStreamMessage(msg) {
2660
2710
  if (msg instanceof require_model.PublishDone) return handlerPublishDone;
2661
2711
  if (msg instanceof require_model.PublishSkipped) return handlerPublishSkipped;
2662
2712
  }
2663
- //#endregion
2664
- //#region src/client/util/random_id.ts
2713
+ // src/client/util/random_id.ts
2665
2714
  /**
2666
2715
  * Copyright 2025 The MOQtail Authors
2667
2716
  *
@@ -2678,60 +2727,44 @@ function getHandlerForRequestStreamMessage(msg) {
2678
2727
  * limitations under the License.
2679
2728
  */
2680
2729
  function random60bitId() {
2681
- const buf = /* @__PURE__ */ new Uint8Array(8);
2682
- crypto.getRandomValues(buf);
2683
- buf[0] = buf[0] & 15;
2684
- let id = 0n;
2685
- for (const b of buf) id = id << 8n | BigInt(b);
2686
- return id;
2687
- }
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
- */
2730
+ const buf = /* @__PURE__ */ new Uint8Array(8);
2731
+ crypto.getRandomValues(buf);
2732
+ buf[0] = buf[0] & 15;
2733
+ let id = 0n;
2734
+ for (const b of buf) id = id << 8n | BigInt(b);
2735
+ return id;
2736
+ }
2737
+ // src/client/datagram_stream.ts
2705
2738
  /**
2706
2739
  * Sends MoqtObjects as WebTransport datagrams.
2707
2740
  * Parallel to SendStream but for datagram-based delivery.
2708
2741
  *
2709
2742
  * @example
2710
2743
  * ```ts
2711
- * const sender = new SendDatagramStream(client.webTransport.datagrams.writable, trackAlias);
2744
+ * const sender = await SendDatagramStream.new(client.webTransport.datagrams.writable, trackAlias);
2712
2745
  * await sender.write(moqtObject);
2713
2746
  * ```
2714
2747
  */
2715
2748
  var SendDatagramStream = class SendDatagramStream {
2716
2749
  #writer;
2717
2750
  #trackAlias;
2718
- onDataSent;
2719
- constructor(writer, trackAlias, onDataSent) {
2751
+ #events;
2752
+ constructor(writer, trackAlias, events) {
2720
2753
  this.#writer = writer;
2721
2754
  this.#trackAlias = trackAlias;
2722
- if (onDataSent) this.onDataSent = onDataSent;
2755
+ this.#events = events;
2723
2756
  }
2724
2757
  /**
2725
2758
  * Create a new datagram sender for a specific track.
2726
2759
  *
2727
2760
  * @param writeStream - WebTransport datagram writable stream
2728
2761
  * @param trackAlias - Track alias for this datagram stream
2729
- * @param onDataSent - Optional callback fired when datagram is sent
2762
+ * @param events - Receives `datagramsent` for each datagram written
2730
2763
  * @returns SendDatagramStream instance
2731
2764
  */
2732
- static async new(writeStream, trackAlias, onDataSent) {
2765
+ static async new(writeStream, trackAlias, events) {
2733
2766
  const writer = writeStream.getWriter();
2734
- return new SendDatagramStream(writer, trackAlias, onDataSent);
2767
+ return new SendDatagramStream(writer, trackAlias, events);
2735
2768
  }
2736
2769
  /**
2737
2770
  * Create a datagram sender using an existing shared writer.
@@ -2739,11 +2772,11 @@ var SendDatagramStream = class SendDatagramStream {
2739
2772
  *
2740
2773
  * @param writer - Existing WritableStreamDefaultWriter
2741
2774
  * @param trackAlias - Track alias for this datagram stream
2742
- * @param onDataSent - Optional callback fired when datagram is sent
2775
+ * @param events - Receives `datagramsent` for each datagram written
2743
2776
  * @returns SendDatagramStream instance
2744
2777
  */
2745
- static fromWriter(writer, trackAlias, onDataSent) {
2746
- return new SendDatagramStream(writer, trackAlias, onDataSent);
2778
+ static fromWriter(writer, trackAlias, events) {
2779
+ return new SendDatagramStream(writer, trackAlias, events);
2747
2780
  }
2748
2781
  /**
2749
2782
  * Write a MoqtObject as a datagram.
@@ -2754,13 +2787,13 @@ var SendDatagramStream = class SendDatagramStream {
2754
2787
  async write(object) {
2755
2788
  const datagram = object.tryIntoDatagram(this.#trackAlias);
2756
2789
  const serialized = datagram.serialize().toUint8Array();
2757
- require_logger.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);
2790
+ require_emitter.logger.log("datagram_stream", `Writing datagram: trackAlias=${this.#trackAlias}, group=${object.location?.group}, obj=${object.location?.object}, size=${serialized.byteLength}`);
2791
+ this.#events?.emit("datagramsent", datagram);
2759
2792
  try {
2760
2793
  await this.#writer.write(serialized);
2761
- require_logger.logger.log("datagram_stream", `Successfully wrote ${serialized.byteLength} bytes to WebTransport datagram`);
2794
+ require_emitter.logger.log("datagram_stream", `Successfully wrote ${serialized.byteLength} bytes to WebTransport datagram`);
2762
2795
  } catch (err) {
2763
- require_logger.logger.error("datagram_stream", `ERROR writing datagram:`, err);
2796
+ require_emitter.logger.error("datagram_stream", `ERROR writing datagram:`, err);
2764
2797
  throw err;
2765
2798
  }
2766
2799
  }
@@ -2777,91 +2810,160 @@ var SendDatagramStream = class SendDatagramStream {
2777
2810
  this.#writer.releaseLock();
2778
2811
  }
2779
2812
  };
2813
+ // src/client/ordering.ts
2814
+ /** IDs before this object in its group that don't exist (moqt-22 Prior Object ID Gap). */
2815
+ const objectGap = (object) => require_model.findProperty(object.properties, require_model.PriorObjectIdGapProperty)?.gap ?? 0n;
2816
+ /** Group IDs before this object's group that don't exist (moqt-22 Prior Group ID Gap). */
2817
+ const groupGap = (object) => require_model.findProperty(object.properties, require_model.PriorGroupIdGapProperty)?.gap ?? 0n;
2780
2818
  /**
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
- * );
2819
+ * @public
2820
+ * Releases one request's objects in location order, whatever streams or datagrams they
2821
+ * arrived on. An object goes out as soon as its predecessor has; one whose predecessor
2822
+ * is missing waits until the window is exceeded, then everything up to the oldest held
2823
+ * object goes out and the expected locations skipped are reported through `gap`.
2794
2824
  *
2795
- * for await (const object of receiver.stream) {
2796
- * console.log('Received:', object);
2797
- * }
2798
- * ```
2825
+ * Nothing is released yet, so the first object goes out at once only when it starts a
2826
+ * group: a mid-group first object waits for the start of its group, which a fill fetch
2827
+ * stream may still bring.
2799
2828
  */
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 = require_model.Datagram.deserialize(new require_model.FrozenByteBuffer(datagramBytes));
2837
- if (this.onDataReceived) this.onDataReceived(datagram);
2838
- const fullTrackName = this.#trackAliasResolver(datagram.trackAlias);
2839
- const moqtObject = require_model.MoqtObject.fromDatagram(datagram, fullTrackName);
2840
- controller.enqueue(moqtObject);
2841
- } catch (error) {
2842
- require_logger.logger.warn("datagram_stream", "Failed to parse datagram:", error);
2843
- continue;
2844
- }
2829
+ var ObjectOrderer = class {
2830
+ #ordering;
2831
+ #onRelease;
2832
+ #onGap;
2833
+ #suspended = /* @__PURE__ */ new Set();
2834
+ #held = [];
2835
+ /** The location of the last object released in order. */
2836
+ #released;
2837
+ /** The last Object ID of each group known to be complete. */
2838
+ #ends = /* @__PURE__ */ new Map();
2839
+ #timer;
2840
+ #arrivals = 0;
2841
+ constructor(ordering, onRelease, onGap) {
2842
+ this.#ordering = ordering;
2843
+ this.#onRelease = onRelease;
2844
+ this.#onGap = onGap;
2845
+ }
2846
+ /** Takes an object; `previous` is the object before it on the same fetch stream. */
2847
+ push(object, previous) {
2848
+ if (this.#released && object.location.compare(this.#released) <= 0) {
2849
+ if (this.#ordering.onWindowExceeded !== "drop") this.#onRelease(object);
2850
+ return;
2851
+ }
2852
+ const index = this.#held.findIndex((held) => held.object.location.compare(object.location) >= 0);
2853
+ if (index >= 0 && this.#held[index].object.location.equals(object.location)) return;
2854
+ const entry = {
2855
+ object,
2856
+ previous,
2857
+ at: performance.now(),
2858
+ seq: this.#arrivals++
2859
+ };
2860
+ if (index < 0) this.#held.push(entry);
2861
+ else this.#held.splice(index, 0, entry);
2862
+ this.#drain();
2863
+ this.#expire();
2864
+ }
2865
+ /** While suspended for any reason nothing exceeds the window, so held objects wait for what's missing. */
2866
+ suspendWindow(reason) {
2867
+ if (this.#suspended.has(reason)) return;
2868
+ this.#suspended.add(reason);
2869
+ this.#expire();
2870
+ }
2871
+ /** Resuming the last reason releases at once what waited longer than the window. */
2872
+ resumeWindow(reason) {
2873
+ if (!this.#suspended.delete(reason)) return;
2874
+ this.#expire();
2875
+ }
2876
+ /** A stream carrying the End of Group for `group` ended cleanly with `lastObject`. */
2877
+ endGroup(group, lastObject) {
2878
+ this.#ends.set(group, lastObject);
2879
+ this.#drain();
2880
+ this.#schedule();
2881
+ }
2882
+ /** Releases everything held, in order, and stops the timer. Call before closing the stream. */
2883
+ flush() {
2884
+ this.#clearTimer();
2885
+ while (this.#held.length > 0) this.#force(this.#held.shift());
2886
+ }
2887
+ #drain() {
2888
+ while (this.#held.length > 0 && this.#isNext(this.#held[0])) this.#release(this.#held.shift().object);
2889
+ }
2890
+ #expire() {
2891
+ while (this.#exceeded()) {
2892
+ const oldest = this.#oldest().object.location;
2893
+ while (this.#held[0] && this.#held[0].object.location.compare(oldest) <= 0) this.#force(this.#held.shift());
2894
+ this.#drain();
2895
+ }
2896
+ this.#schedule();
2897
+ }
2898
+ #exceeded() {
2899
+ if (this.#suspended.size > 0 || this.#held.length === 0) return false;
2900
+ const { durationMs, objects } = this.#ordering.window;
2901
+ if (objects !== void 0 && this.#held.length > objects) return true;
2902
+ return durationMs !== void 0 && performance.now() - this.#oldest().at >= durationMs;
2903
+ }
2904
+ #oldest() {
2905
+ return this.#held.reduce((oldest, held) => held.seq < oldest.seq ? held : oldest);
2906
+ }
2907
+ /** One timer, armed only while objects are held, for when the oldest one exceeds the window. */
2908
+ #schedule() {
2909
+ this.#clearTimer();
2910
+ const { durationMs } = this.#ordering.window;
2911
+ if (this.#suspended.size > 0 || durationMs === void 0 || this.#held.length === 0) return;
2912
+ const wait = this.#oldest().at + durationMs - performance.now();
2913
+ this.#timer = setTimeout(() => {
2914
+ try {
2915
+ this.#expire();
2916
+ } catch (error) {
2917
+ require_emitter.logger.debug("ordering", "release after the stream closed", error);
2918
+ this.#held = [];
2845
2919
  }
2846
- } catch (error) {
2847
- controller.error(error);
2920
+ }, Math.max(0, wait));
2921
+ }
2922
+ #clearTimer() {
2923
+ clearTimeout(this.#timer);
2924
+ this.#timer = void 0;
2925
+ }
2926
+ #isNext({ object, previous }) {
2927
+ const last = this.#released;
2928
+ const { group, object: id } = object.location;
2929
+ const sparseObjects = this.#ordering.sparseObjectIds === true;
2930
+ const startsGroup = sparseObjects || id === objectGap(object);
2931
+ if (!last) return startsGroup;
2932
+ if (previous?.equals(last)) return true;
2933
+ if (group === last.group) return sparseObjects || id - 1n - objectGap(object) <= last.object;
2934
+ const followsGroup = this.#ordering.sparseGroupIds === true || group - 1n - groupGap(object) <= last.group;
2935
+ return startsGroup && followsGroup && this.#ends.get(last.group) === last.object;
2936
+ }
2937
+ /** Releases `held` out of turn, reporting the expected locations it skips. */
2938
+ #force(held) {
2939
+ const from = this.#skippedFrom(held);
2940
+ if (from) this.#onGap(from, held.object.location);
2941
+ this.#release(held.object);
2942
+ }
2943
+ /**
2944
+ * The first expected location skipped between the release point and `held`, if any.
2945
+ * A group's missing tail isn't counted: its last ID is unknown.
2946
+ */
2947
+ #skippedFrom({ object, previous }) {
2948
+ const last = this.#released;
2949
+ if (!last || previous?.equals(last)) return void 0;
2950
+ const { group, object: id } = object.location;
2951
+ const sparseObjects = this.#ordering.sparseObjectIds === true;
2952
+ if (group === last.group) return !sparseObjects && id - 1n - objectGap(object) > last.object ? new require_model.Location(group, last.object + 1n) : void 0;
2953
+ if (this.#ordering.sparseGroupIds !== true && group - 1n - groupGap(object) > last.group) return new require_model.Location(last.group + 1n, 0n);
2954
+ return !sparseObjects && id > objectGap(object) ? new require_model.Location(group, 0n) : void 0;
2955
+ }
2956
+ #release(object) {
2957
+ const { group, object: id } = object.location;
2958
+ if (this.#released?.group !== group) {
2959
+ for (const known of this.#ends.keys()) if (known < group) this.#ends.delete(known);
2848
2960
  }
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();
2961
+ this.#released = object.location;
2962
+ if (object.isEndOfGroup()) this.#ends.set(group, id);
2963
+ this.#onRelease(object);
2861
2964
  }
2862
2965
  };
2863
- //#endregion
2864
- //#region src/client/client.ts
2966
+ // src/client/client.ts
2865
2967
  /**
2866
2968
  * Copyright 2025 The MOQtail Authors
2867
2969
  *
@@ -2881,17 +2983,17 @@ var RecvDatagramStream = class RecvDatagramStream {
2881
2983
  * @public
2882
2984
  * Represents a Media Over QUIC Transport (MOQT) client session.
2883
2985
  *
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.
2986
+ * Construct it, attach listeners with `on()`, then call {@link MOQtailClient.init} to open the
2987
+ * session. Once initialized, the client provides high-level methods for MOQT requests and publishing. If a protocol
2988
+ * violation occurs, the client terminates; a new client is needed to reconnect.
2889
2989
  *
2890
2990
  * ## Usage
2891
2991
  *
2892
2992
  * ### Connect and Subscribe to a Track
2893
2993
  * ```ts
2894
- * const client = await MOQtailClient.new({ url });
2994
+ * const client = new MOQtailClient({ url });
2995
+ * client.on('sessionterminated', (reason) => console.warn('Session ended:', reason));
2996
+ * await client.init();
2895
2997
  * const result = await client.subscribe({
2896
2998
  * fullTrackName,
2897
2999
  * locationFilter: new LocationFilter(LocationFilterType.NextObject),
@@ -2908,7 +3010,8 @@ var RecvDatagramStream = class RecvDatagramStream {
2908
3010
  *
2909
3011
  * ### Publish a namespace for Publishing
2910
3012
  * ```ts
2911
- * const client = await MOQtailClient.new({ url });
3013
+ * const client = new MOQtailClient({ url });
3014
+ * await client.init();
2912
3015
  * const publishNamespaceResult = await client.publishNamespace(["camera", "main"]);
2913
3016
  * if (!(publishNamespaceResult instanceof RequestError)) {
2914
3017
  * // Ready to publish objects under this namespace
@@ -2920,7 +3023,7 @@ var RecvDatagramStream = class RecvDatagramStream {
2920
3023
  * await client.disconnect();
2921
3024
  * ```
2922
3025
  */
2923
- var MOQtailClient = class MOQtailClient {
3026
+ var MOQtailClient = class extends require_emitter.Emitter {
2924
3027
  /**
2925
3028
  * Namespace prefixes (tuples) the peer has requested announce notifications for via SUBSCRIBE_NAMESPACE.
2926
3029
  * Used to decide which locally issued ANNOUNCE messages should be forwarded (future optimization: prefix trie).
@@ -2988,10 +3091,12 @@ var MOQtailClient = class MOQtailClient {
2988
3091
  * stream to close.
2989
3092
  */
2990
3093
  #namespaceRequestIds = /* @__PURE__ */ new Map();
2991
- /** Underlying WebTransport session (set after successful construction in MOQtailClient.new). */
3094
+ /** Underlying WebTransport session (set by {@link MOQtailClient.init}). */
2992
3095
  webTransport;
2993
3096
  /** Validated Setup message the server sent back during handshake (protocol parameters negotiated). */
2994
3097
  #serverSetup;
3098
+ /** Setup message this client sent during handshake. */
3099
+ #clientSetup;
2995
3100
  /** How many filter ranges this client allows the server per request, as advertised in SETUP. */
2996
3101
  #maxFilterRanges = 0n;
2997
3102
  /** Outgoing / incoming control message stream pair. */
@@ -3012,6 +3117,8 @@ var MOQtailClient = class MOQtailClient {
3012
3117
  * retired anyway, if no PUBLISH_DONE ends its drain first.
3013
3118
  */
3014
3119
  switchDrainTimeoutMs = DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
3120
+ /** How long (ms) after SUBSCRIBE_OK a fill fetch stream may take to open before ordering stops waiting for it. */
3121
+ fillOpenTimeoutMs = DEFAULT_FILL_OPEN_TIMEOUT_MS;
3015
3122
  /**
3016
3123
  * Callbacks waiting for a track alias to be registered, keyed by alias. Each entry
3017
3124
  * belongs to a data stream that arrived before the control message naming its alias.
@@ -3019,129 +3126,19 @@ var MOQtailClient = class MOQtailClient {
3019
3126
  #aliasWaiters = /* @__PURE__ */ new Map();
3020
3127
  /** Flag indicating the client has been disconnected/destroyed and cannot accept further API calls. */
3021
3128
  #isDestroyed = false;
3129
+ /** Where {@link MOQtailClient.init} is: it runs once, and only a `ready` client takes requests. */
3130
+ #state = "idle";
3131
+ #options;
3022
3132
  /** Internal monotonically increasing client-assigned request id counter (even/odd parity scheme advances by 2). */
3023
3133
  #dontUseRequestId = 0n;
3024
3134
  /** Active early discard policy; undefined means no per-stream deadline is applied. */
3025
3135
  #earlyDiscardPolicy;
3026
3136
  /**
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
3137
  * Whether the peer has sent a GOAWAY on the control stream. Once it has, this side
3041
3138
  * should not start new requests; a second one closes the session with
3042
3139
  * PROTOCOL_VIOLATION.
3043
3140
  */
3044
3141
  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
3142
  /** Datagram writer for sending datagrams. */
3146
3143
  #datagramWriter;
3147
3144
  /** Datagram reader for receiving datagrams. */
@@ -3170,12 +3167,6 @@ var MOQtailClient = class MOQtailClient {
3170
3167
  return id;
3171
3168
  }
3172
3169
  /**
3173
- * Generates a safe, sequential local request ID for tracking pushed/incoming tracks.
3174
- */
3175
- allocatePseudoRequestId() {
3176
- return this.#nextClientRequestId;
3177
- }
3178
- /**
3179
3170
  * Gets the current server setup configuration.
3180
3171
  *
3181
3172
  * @returns The {@link Setup} instance the server sent back during handshake.
@@ -3184,9 +3175,13 @@ var MOQtailClient = class MOQtailClient {
3184
3175
  return this.#serverSetup;
3185
3176
  }
3186
3177
  /**
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.
3178
+ * Gets the setup this client sent during handshake.
3179
+ *
3180
+ * @returns The {@link Setup} instance written first on the control stream.
3189
3181
  */
3182
+ get clientSetup() {
3183
+ return this.#clientSetup;
3184
+ }
3190
3185
  /**
3191
3186
  * How many filter ranges this client allows the server in one request: the
3192
3187
  * MAX_FILTER_RANGES it advertised, {@link DEFAULT_MAX_FILTER_RANGES} unless the
@@ -3217,24 +3212,31 @@ var MOQtailClient = class MOQtailClient {
3217
3212
  * @param level - The minimum {@link LogLevel} to output. Use `LogLevel.NONE` to silence all logs.
3218
3213
  */
3219
3214
  static setLogLevel(level) {
3220
- require_logger.setLogLevel(level);
3215
+ require_emitter.setLogLevel(level);
3221
3216
  }
3222
3217
  /**
3223
3218
  * Restricts log output to the specified module names. Pass `null` to allow all modules.
3224
3219
  * @param modules - Array of module name strings, or `null` to enable all modules.
3225
3220
  */
3226
3221
  static setLogEnabledModules(modules) {
3227
- require_logger.setLogEnabledModules(modules);
3222
+ require_emitter.setLogEnabledModules(modules);
3228
3223
  }
3229
3224
  /**
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.
3225
+ * Guard that throws unless the client is initialized and not yet destroyed. Used at start of public APIs
3226
+ * to fail fast rather than perform partial operations on a session that is not open.
3227
+ * @throws MOQtailError when the client is destroyed or {@link MOQtailClient.init} has not completed.
3233
3228
  */
3234
3229
  #ensureActive() {
3235
3230
  if (this.#isDestroyed) throw new require_model.MOQtailError("MOQtailClient is destroyed and cannot be used.");
3231
+ if (this.#state !== "ready") throw new require_model.MOQtailError("MOQtailClient is not initialized. Await init() first.");
3236
3232
  }
3237
- constructor() {
3233
+ /**
3234
+ * Stores `options`; nothing happens on the network until {@link MOQtailClient.init}, so
3235
+ * listeners attached in between see everything, the handshake included.
3236
+ */
3237
+ constructor(options) {
3238
+ super();
3239
+ this.#options = options;
3238
3240
  this.receivedDatagramObjects = new ReadableStream({
3239
3241
  start: (controller) => {
3240
3242
  this.#receivedDatagramObjectController = controller;
@@ -3243,95 +3245,73 @@ var MOQtailClient = class MOQtailClient {
3243
3245
  });
3244
3246
  }
3245
3247
  /**
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.
3248
+ * Opens the WebTransport session and performs the MOQT setup handshake. Runs once: a
3249
+ * second call throws, and a failed one leaves the client unusable, so a retry needs a
3250
+ * new client.
3251
3251
  *
3252
+ * @throws :{@link MOQtailError} If called more than once, or after {@link MOQtailClient.disconnect}.
3252
3253
  * @throws :{@link ProtocolViolationError} If the server sends an unexpected or invalid message during setup.
3253
3254
  *
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
3255
+ * @example
3262
3256
  * ```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
- * });
3257
+ * const client = new MOQtailClient({ url: 'https://relay.example.com/transport' })
3258
+ * client.on('messagesent', (msg) => console.log('Sent:', msg))
3259
+ * await client.init()
3278
3260
  * ```
3279
3261
  */
3280
- static async new(args) {
3281
- let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, trackAliasResolutionTimeoutMs, switchDrainTimeoutMs, enableDatagrams, callbacks } = args;
3282
- const client = new MOQtailClient();
3262
+ async init() {
3263
+ if (this.#state !== "idle" || this.#isDestroyed) throw new require_model.MOQtailError("MOQtailClient.init may only run once.");
3264
+ this.#state = "initializing";
3265
+ let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, trackAliasResolutionTimeoutMs, switchDrainTimeoutMs, fillOpenTimeoutMs, enableDatagrams } = this.#options;
3283
3266
  if (!transportOptions) transportOptions = { protocols: [] };
3284
3267
  if (!transportOptions.protocols) transportOptions = {
3285
3268
  ...transportOptions,
3286
3269
  protocols: [...require_model.SUPPORTED_VERSIONS]
3287
3270
  };
3288
3271
  else transportOptions.protocols.push(...require_model.SUPPORTED_VERSIONS);
3289
- require_logger.logger.log("MOQtailClient", "transportOptions", transportOptions);
3290
- const { transportUrl, moqtUrl } = require_model.resolveTransportUrl(url);
3291
- if (moqtUrl) {
3292
- require_logger.logger.log("MOQtailClient", `moqt:// resolved to ${transportUrl}`);
3293
- if (moqtUrl.fragment) require_logger.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;
3272
+ require_emitter.logger.log("MOQtailClient", "transportOptions", transportOptions);
3297
3273
  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);
3274
+ const { transportUrl, moqtUrl } = require_model.resolveTransportUrl(url);
3275
+ if (moqtUrl) {
3276
+ require_emitter.logger.log("MOQtailClient", `moqt:// resolved to ${transportUrl}`);
3277
+ if (moqtUrl.fragment) require_emitter.logger.log("MOQtailClient", `moqt:// fragment (local-only): ${moqtUrl.fragment.kind}:${moqtUrl.fragment.value}`);
3278
+ }
3279
+ this.webTransport = new WebTransport(transportUrl, transportOptions);
3280
+ await this.webTransport.ready;
3281
+ if (dataStreamTimeoutMs) this.dataStreamTimeoutMs = dataStreamTimeoutMs;
3282
+ if (controlStreamTimeoutMs) this.controlStreamTimeoutMs = controlStreamTimeoutMs;
3283
+ if (trackAliasResolutionTimeoutMs !== void 0) this.trackAliasResolutionTimeoutMs = trackAliasResolutionTimeoutMs;
3284
+ if (switchDrainTimeoutMs !== void 0) this.switchDrainTimeoutMs = switchDrainTimeoutMs;
3285
+ if (fillOpenTimeoutMs !== void 0) this.fillOpenTimeoutMs = fillOpenTimeoutMs;
3286
+ const sendHalf = new ControlSendStream(await this.webTransport.createUnidirectionalStream({ sendOrder: Number.MAX_SAFE_INTEGER }), this);
3309
3287
  const params = setupOptions ? setupOptions.build() : new require_model.SetupOptions().build();
3310
3288
  let maxFilterRanges = params.map((p) => require_model.MaxFilterRanges.fromKeyValuePair(p)).find((o) => o !== void 0);
3311
3289
  if (!maxFilterRanges) {
3312
3290
  maxFilterRanges = new require_model.MaxFilterRanges(DEFAULT_MAX_FILTER_RANGES);
3313
3291
  params.push(maxFilterRanges.toKeyValuePair());
3314
3292
  }
3315
- client.#maxFilterRanges = maxFilterRanges.value;
3293
+ this.#maxFilterRanges = maxFilterRanges.value;
3316
3294
  require_model.assertNoAuthorityOverWebTransport(params);
3317
- await sendHalf.send(new require_model.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 require_model.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();
3295
+ this.#clientSetup = new require_model.Setup(params);
3296
+ await sendHalf.send(this.#clientSetup);
3297
+ this.#incomingUniStreams = this.webTransport.incomingUnidirectionalStreams.getReader();
3298
+ const { value: recvStream, done: recvStreamDone } = await this.#incomingUniStreams.read();
3299
+ if (recvStreamDone || !recvStream) throw new require_model.ProtocolViolationError("MOQtailClient.init", "Session closed before the server control stream");
3300
+ const recvHalf = new ControlRecvStream(recvStream, this.controlStreamTimeoutMs, this);
3301
+ this.controlStream = new ControlStream(sendHalf, recvHalf);
3302
+ const reader = this.controlStream.stream.getReader();
3323
3303
  const { value: response, done } = await reader.read();
3324
- if (done) throw new require_model.ProtocolViolationError("MOQtailClient.new", "Stream closed after client setup");
3325
- if (!(response instanceof require_model.Setup)) throw new require_model.ProtocolViolationError("MOQtailClient.new", "Expected setup as the first control message");
3326
- client.#serverSetup = response;
3304
+ if (done) throw new require_model.ProtocolViolationError("MOQtailClient.init", "Stream closed after client setup");
3305
+ if (!(response instanceof require_model.Setup)) throw new require_model.ProtocolViolationError("MOQtailClient.init", "Expected setup as the first control message");
3306
+ this.#serverSetup = response;
3327
3307
  reader.releaseLock();
3328
- client.#handleIncomingControlMessages();
3329
- client.#acceptIncomingUniStreams();
3330
- client.#acceptIncomingBiStreams();
3331
- if (enableDatagrams) await client.startDatagrams();
3332
- return client;
3308
+ this.#state = "ready";
3309
+ this.#handleIncomingControlMessages();
3310
+ this.#acceptIncomingUniStreams();
3311
+ this.#acceptIncomingBiStreams();
3312
+ if (enableDatagrams) await this.startDatagrams();
3333
3313
  } catch (error) {
3334
- await client.disconnect(new require_model.InternalError("MOQtailClient.new", error instanceof Error ? error.message : String(error)));
3314
+ await this.disconnect(new require_model.InternalError("MOQtailClient.init", errorMessage(error)));
3335
3315
  throw error;
3336
3316
  }
3337
3317
  }
@@ -3344,15 +3324,16 @@ var MOQtailClient = class MOQtailClient {
3344
3324
  async startDatagrams() {
3345
3325
  this.#ensureActive();
3346
3326
  if (this.#isReceivingDatagrams) {
3347
- require_logger.logger.warn("MOQtailClient", "Datagrams already started");
3327
+ require_emitter.logger.warn("MOQtailClient", "Datagrams already started");
3348
3328
  return;
3349
3329
  }
3350
- require_logger.logger.log("MOQtailClient", "Starting datagram support...");
3330
+ require_emitter.logger.log("MOQtailClient", "Starting datagram support...");
3351
3331
  this.#datagramReader = this.webTransport.datagrams.readable.getReader();
3352
- this.#datagramWriter = this.webTransport.datagrams.writable.getWriter();
3332
+ const datagrams = this.webTransport.datagrams;
3333
+ this.#datagramWriter = (datagrams.writable ?? datagrams.createWritable()).getWriter();
3353
3334
  this.#isReceivingDatagrams = true;
3354
3335
  this.#acceptIncomingDatagrams();
3355
- require_logger.logger.log("MOQtailClient", "Datagram support started");
3336
+ require_emitter.logger.log("MOQtailClient", "Datagram support started");
3356
3337
  }
3357
3338
  /**
3358
3339
  * Stop receiving datagrams and release resources.
@@ -3360,7 +3341,7 @@ var MOQtailClient = class MOQtailClient {
3360
3341
  */
3361
3342
  async stopDatagrams() {
3362
3343
  if (!this.#isReceivingDatagrams) return;
3363
- require_logger.logger.log("MOQtailClient", "Stopping datagram support...");
3344
+ require_emitter.logger.log("MOQtailClient", "Stopping datagram support...");
3364
3345
  this.#isReceivingDatagrams = false;
3365
3346
  this.#datagramTrackHandlers.clear();
3366
3347
  if (this.#datagramReader) {
@@ -3394,10 +3375,10 @@ var MOQtailClient = class MOQtailClient {
3394
3375
  */
3395
3376
  subscribeToTrackDatagrams(trackAlias, handler) {
3396
3377
  const key = trackAlias.toString();
3397
- require_logger.logger.log("MOQtailClient", `Registering datagram handler for trackAlias=${trackAlias}`);
3378
+ require_emitter.logger.log("MOQtailClient", `Registering datagram handler for trackAlias=${trackAlias}`);
3398
3379
  this.#datagramTrackHandlers.set(key, handler);
3399
3380
  return () => {
3400
- require_logger.logger.log("MOQtailClient", `Unregistering datagram handler for trackAlias=${trackAlias}`);
3381
+ require_emitter.logger.log("MOQtailClient", `Unregistering datagram handler for trackAlias=${trackAlias}`);
3401
3382
  this.#datagramTrackHandlers.delete(key);
3402
3383
  };
3403
3384
  }
@@ -3426,8 +3407,8 @@ var MOQtailClient = class MOQtailClient {
3426
3407
  createDatagramSender(trackAlias) {
3427
3408
  this.#ensureActive();
3428
3409
  if (!this.#datagramWriter) throw new require_model.MOQtailError("Datagrams not started. Call startDatagrams() first or set enableDatagrams: true in options.");
3429
- require_logger.logger.log("MOQtailClient", `Creating datagram sender for trackAlias=${trackAlias}`);
3430
- return SendDatagramStream.fromWriter(this.#datagramWriter, trackAlias, this.onDatagramSent);
3410
+ require_emitter.logger.log("MOQtailClient", `Creating datagram sender for trackAlias=${trackAlias}`);
3411
+ return SendDatagramStream.fromWriter(this.#datagramWriter, trackAlias, this);
3431
3412
  }
3432
3413
  /**
3433
3414
  * Send a single MoqtObject as a datagram.
@@ -3447,19 +3428,19 @@ var MOQtailClient = class MOQtailClient {
3447
3428
  if (!this.#datagramWriter) throw new require_model.MOQtailError("Datagrams not started. Call startDatagrams() first or set enableDatagrams: true in options.");
3448
3429
  const datagram = object.tryIntoDatagram(trackAlias);
3449
3430
  const serialized = datagram.serialize().toUint8Array();
3450
- if (this.onDatagramSent) this.onDatagramSent(datagram);
3431
+ this.emit("datagramsent", datagram);
3451
3432
  await this.#datagramWriter.write(serialized);
3452
3433
  }
3453
3434
  /**
3454
3435
  * Background loop that receives and parses incoming datagrams.
3455
3436
  */
3456
3437
  async #acceptIncomingDatagrams() {
3457
- require_logger.logger.log("MOQtailClient", "Starting datagram reception loop...");
3438
+ require_emitter.logger.log("MOQtailClient", "Starting datagram reception loop...");
3458
3439
  try {
3459
3440
  while (this.#isReceivingDatagrams && this.#datagramReader) {
3460
3441
  const { done, value: datagramBytes } = await this.#datagramReader.read();
3461
3442
  if (done) {
3462
- require_logger.logger.log("MOQtailClient", "Datagram reader done, stopping reception");
3443
+ require_emitter.logger.log("MOQtailClient", "Datagram reader done, stopping reception");
3463
3444
  this.#isReceivingDatagrams = false;
3464
3445
  if (this.#receivedDatagramObjectController) try {
3465
3446
  this.#receivedDatagramObjectController.close();
@@ -3470,7 +3451,7 @@ var MOQtailClient = class MOQtailClient {
3470
3451
  try {
3471
3452
  const datagram = require_model.Datagram.deserialize(new require_model.FrozenByteBuffer(datagramBytes));
3472
3453
  const trackAlias = datagram.trackAlias;
3473
- if (this.onDatagramReceived) this.onDatagramReceived(datagram);
3454
+ this.emit("datagramreceived", datagram);
3474
3455
  const fullTrackName = this.#resolveTrackAlias(trackAlias);
3475
3456
  const moqtObject = require_model.MoqtObject.fromDatagram(datagram, fullTrackName);
3476
3457
  const trackKey = trackAlias.toString();
@@ -3478,18 +3459,23 @@ var MOQtailClient = class MOQtailClient {
3478
3459
  if (handler) try {
3479
3460
  handler(moqtObject);
3480
3461
  } catch (handlerError) {
3481
- require_logger.logger.warn("MOQtailClient", "Datagram track handler error:", handlerError);
3462
+ require_emitter.logger.warn("MOQtailClient", "Datagram track handler error:", handlerError);
3463
+ }
3464
+ const holder = this.subscriptions.get(trackAlias);
3465
+ if (holder instanceof SubscribeRequest && holder.orderer) {
3466
+ if (!holder.largestLocation || holder.largestLocation.compare(moqtObject.location) < 0) holder.largestLocation = moqtObject.location;
3467
+ if (holder.manager.deliver(holder, moqtObject) && require_model.ObjectDatagramType.isEndOfGroup(datagram.type)) holder.orderer.endGroup(moqtObject.location.group, moqtObject.location.object);
3482
3468
  }
3483
3469
  if (this.#receivedDatagramObjectController) try {
3484
3470
  this.#receivedDatagramObjectController.enqueue(moqtObject);
3485
3471
  } catch {}
3486
3472
  } catch (error) {
3487
- require_logger.logger.warn("MOQtailClient", "Failed to parse datagram:", error);
3473
+ require_emitter.logger.warn("MOQtailClient", "Failed to parse datagram:", error);
3488
3474
  continue;
3489
3475
  }
3490
3476
  }
3491
3477
  } catch (error) {
3492
- require_logger.logger.error("MOQtailClient", "Datagram reception error:", error);
3478
+ require_emitter.logger.error("MOQtailClient", "Datagram reception error:", error);
3493
3479
  if (this.#receivedDatagramObjectController) try {
3494
3480
  this.#receivedDatagramObjectController.error(error);
3495
3481
  } catch {}
@@ -3497,6 +3483,22 @@ var MOQtailClient = class MOQtailClient {
3497
3483
  }
3498
3484
  }
3499
3485
  /**
3486
+ * The track a data stream carries. A subgroup stream can open before the response
3487
+ * that names its alias, so its header event may lack `fullTrackName`: ask again on a
3488
+ * later event of the same stream.
3489
+ */
3490
+ trackNameOf(header) {
3491
+ if (header.fullTrackName || header.trackAlias === void 0) return header.fullTrackName;
3492
+ return this.aliasFullTrackNameMap.get(header.trackAlias);
3493
+ }
3494
+ /** A fetch stream is named by its FETCH, or by the SUBSCRIBE it fills. */
3495
+ #streamTrackName(header) {
3496
+ if (header instanceof require_model.SubgroupHeader) return this.aliasFullTrackNameMap.get(header.trackAlias);
3497
+ const request = this.requests.get(this.#clientRequestId(header.requestId));
3498
+ if (request instanceof FetchRequest) return request.message.fullTrackName;
3499
+ return request instanceof SubscribeRequest ? request.fullTrackName : void 0;
3500
+ }
3501
+ /**
3500
3502
  * Resolve track alias to the full track name it was claimed for.
3501
3503
  * Falls back to a placeholder if no request holds the alias.
3502
3504
  */
@@ -3529,7 +3531,7 @@ var MOQtailClient = class MOQtailClient {
3529
3531
  * Gracefully terminates this {@link MOQtailClient} session and releases underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} resources.
3530
3532
  *
3531
3533
  * @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.
3534
+ * passed to `sessionterminated` listeners. Before {@link MOQtailClient.init} it only marks the client destroyed.
3533
3535
  *
3534
3536
  * @returns Promise that resolves once shutdown logic completes. Subsequent calls are safe no-ops.
3535
3537
  *
@@ -3557,16 +3559,18 @@ var MOQtailClient = class MOQtailClient {
3557
3559
  * ```
3558
3560
  */
3559
3561
  async disconnect(reason) {
3560
- require_logger.logger.log("MOQtailClient", "disconnect", reason);
3562
+ require_emitter.logger.log("MOQtailClient", "disconnect", reason);
3561
3563
  if (this.#isDestroyed) return;
3562
3564
  this.#isDestroyed = true;
3565
+ if (this.#state === "idle") return;
3563
3566
  await this.stopDatagrams();
3564
3567
  const openStreams = [...this.#requestStreams.values()];
3565
3568
  this.#requestStreams.clear();
3566
3569
  this.#namespaceRequestIds.clear();
3567
3570
  await Promise.allSettled(openStreams.map((requestStream) => requestStream.close()));
3568
- this.webTransport.close();
3569
- if (this.onSessionTerminated) this.onSessionTerminated(new require_model.InternalError("MOQtailClient.disconnect", reason instanceof Error ? reason.message : String(reason)));
3571
+ for (const request of this.requests.values()) if (request instanceof SubscribeRequest) request.finish();
3572
+ this.webTransport?.close();
3573
+ this.emit("sessionterminated", new require_model.InternalError("MOQtailClient.disconnect", errorMessage(reason)));
3570
3574
  }
3571
3575
  /**
3572
3576
  * Registers or updates a {@link Track} definition for local publishing or serving.
@@ -3597,7 +3601,7 @@ var MOQtailClient = class MOQtailClient {
3597
3601
  * });
3598
3602
  *
3599
3603
  * // For a hybrid track (live + past):
3600
- * import { MemoryObjectCache } from './track/object_cache';
3604
+ * import { MemoryObjectCache } from '@/client/track/object_cache';
3601
3605
  * const cache = new MemoryObjectCache(); // Caches are not yet fully supported
3602
3606
  * client.addOrUpdateTrack({
3603
3607
  * fullTrackName: { namespace: ["camera"], name: "main" },
@@ -3650,11 +3654,12 @@ var MOQtailClient = class MOQtailClient {
3650
3654
  * future waits for that object.
3651
3655
  * - A {@link FillParameters} in `parameters` also retrieves Objects already published, on a fill fetch stream.
3652
3656
  *
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.
3657
+ * The method returns either a {@link RequestError} (on refusal) or a {@link SubscribeResult}: the subscription `requestId`, its
3658
+ * SUBSCRIBE_OK, a `ReadableStream` of {@link MoqtObject}s, and a `done` promise carrying the PUBLISH_DONE that ends it.
3654
3659
  * Use the `requestId` for {@link MOQtailClient.unsubscribe} or {@link MOQtailClient.subscribeUpdate}. Use the `stream` to decode and display objects.
3655
3660
  *
3656
3661
  * @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.
3662
+ * @returns Either a {@link RequestError} or `{ requestId, subscribeOk, stream, done }`.
3658
3663
  * @throws : {@link MOQtailError} If the client is destroyed.
3659
3664
  * @throws : {@link ProtocolViolationError} If required fields are missing or inconsistent.
3660
3665
  * @throws : {@link InvalidFilterError} If the Range Filters exceed the server's MAX_FILTER_RANGES; nothing is sent.
@@ -3692,7 +3697,7 @@ var MOQtailClient = class MOQtailClient {
3692
3697
  assertWithinFilterRangeLimit(args.parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.subscribe");
3693
3698
  try {
3694
3699
  const { fullTrackName, priority, groupOrder, forward, locationFilter, parameters } = args;
3695
- require_logger.logger.debug("MOQtailClient", `subscribe: ftn="${fullTrackName}" locationFilter=${locationFilter?.filterType} priority=${priority} forward=${forward} groupOrder=${groupOrder}`);
3700
+ require_emitter.logger.debug("MOQtailClient", `subscribe: ftn="${fullTrackName}" locationFilter=${locationFilter?.filterType} priority=${priority} forward=${forward} groupOrder=${groupOrder}`);
3696
3701
  const msg = new require_model.Subscribe(this.#nextClientRequestId, fullTrackName, [
3697
3702
  new require_model.SubscriberPriority(priority),
3698
3703
  ...forward !== void 0 ? [new require_model.Forward(forward)] : [],
@@ -3701,32 +3706,38 @@ var MOQtailClient = class MOQtailClient {
3701
3706
  ...parameters ?? []
3702
3707
  ]);
3703
3708
  const request = new SubscribeRequest(msg);
3704
- request.manager = new Subscription(request);
3709
+ const subscription = new Subscription(request);
3705
3710
  request.earlyDiscardPolicy = args.earlyDiscardPolicy;
3706
3711
  request.onEndOfRange = args.onEndOfRange;
3712
+ request.orderer = this.#createOrderer(args.ordering, groupOrder, request.requestId, (obj) => request.output(obj));
3713
+ const fills = parameters?.some(require_model.MessageParameter.isFillParameters) ?? false;
3714
+ if (fills) request.orderer?.suspendWindow("fill");
3707
3715
  this.requests.set(request.requestId, request);
3708
3716
  this.requestIdMap.addMapping(request.requestId, request.fullTrackName);
3709
- require_logger.logger.debug("MOQtailClient", `subscribe: sending SUBSCRIBE requestId=${msg.requestId} ftn="${fullTrackName}"`);
3717
+ require_emitter.logger.debug("MOQtailClient", `subscribe: sending SUBSCRIBE requestId=${msg.requestId} ftn="${fullTrackName}"`);
3710
3718
  await this.#openRequestStream(request.requestId, msg);
3711
- require_logger.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE sent, awaiting SUBSCRIBE_OK/REQUEST_ERROR requestId=${msg.requestId}`);
3719
+ require_emitter.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE sent, awaiting SUBSCRIBE_OK/REQUEST_ERROR requestId=${msg.requestId}`);
3712
3720
  const response = await request;
3713
3721
  if (response instanceof require_model.RequestError) {
3714
- require_logger.logger.error("MOQtailClient", `subscribe: SUBSCRIBE_ERROR requestId=${request.requestId} code=${response.errorCode} reason="${response.reasonPhrase.phrase}"`);
3722
+ require_emitter.logger.error("MOQtailClient", `subscribe: SUBSCRIBE_ERROR requestId=${request.requestId} code=${response.errorCode} reason="${response.reasonPhrase.phrase}"`);
3715
3723
  this.requests.delete(request.requestId);
3716
3724
  this.requestIdMap.removeMappingByRequestId(request.requestId);
3717
3725
  return response;
3718
3726
  } else {
3719
- require_logger.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE_OK requestId=${request.requestId} trackAlias=${response.trackAlias}`);
3727
+ require_emitter.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE_OK requestId=${request.requestId} trackAlias=${response.trackAlias}`);
3720
3728
  this.#claimTrackAlias(response.trackAlias, request);
3729
+ if (fills) this.#liftFillSuspension(request);
3721
3730
  return {
3722
3731
  requestId: msg.requestId,
3723
- trackAlias: response.trackAlias,
3724
- stream: request.stream
3732
+ subscribeOk: response,
3733
+ stream: request.stream,
3734
+ done: subscription.done
3725
3735
  };
3726
3736
  }
3727
3737
  } catch (error) {
3728
- require_logger.logger.error("MOQtailClient", `subscribe: unexpected error — ${error instanceof Error ? error.message : String(error)}`);
3729
- await this.disconnect(new require_model.InternalError("MOQtailClient.subscribe", error instanceof Error ? error.message : String(error)));
3738
+ const reason = errorMessage(error);
3739
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", `subscribe: unexpected error — ${reason}`);
3740
+ await this.disconnect(new require_model.InternalError("MOQtailClient.subscribe", reason));
3730
3741
  throw error;
3731
3742
  }
3732
3743
  }
@@ -3776,14 +3787,10 @@ var MOQtailClient = class MOQtailClient {
3776
3787
  target.unsubscribe();
3777
3788
  }
3778
3789
  } catch (error) {
3779
- await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribe", error instanceof Error ? error.message : String(error)));
3790
+ await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribe", errorMessage(error)));
3780
3791
  throw error;
3781
3792
  } finally {
3782
- for (const target of targets) {
3783
- this.requests.delete(target.requestId);
3784
- this.requestIdMap.removeMappingByRequestId(target.requestId);
3785
- this.#releaseTrackAlias(target);
3786
- }
3793
+ for (const target of targets) this.#forgetSubscription(target);
3787
3794
  owner?.clear();
3788
3795
  }
3789
3796
  }
@@ -3845,18 +3852,19 @@ var MOQtailClient = class MOQtailClient {
3845
3852
  const subscription = this.subscriptions.get(trackAlias);
3846
3853
  if (!subscription) throw new require_model.InternalError("MOQtailClient.subscribeUpdate", "Request exists but subscription does not");
3847
3854
  const requestId = this.#nextClientRequestId;
3848
- const msg = new require_model.RequestUpdate(requestId, [
3849
- new require_model.SubscriberPriority(priority),
3850
- new require_model.Forward(forward),
3855
+ const updateParams = [
3856
+ ...priority !== void 0 ? [new require_model.SubscriberPriority(priority)] : [],
3857
+ ...forward !== void 0 ? [new require_model.Forward(forward)] : [],
3851
3858
  ...locationFilter ? [locationFilter] : [],
3852
3859
  ...parameters ?? []
3853
- ]);
3860
+ ];
3861
+ const msg = new require_model.RequestUpdate(requestId, updateParams);
3854
3862
  subscription.update(msg);
3855
3863
  await this.#requestStreamFor(subscriptionRequestId, "MOQtailClient.subscribeUpdate").send(msg);
3856
3864
  }
3857
3865
  }
3858
3866
  } catch (error) {
3859
- await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeUpdate", error instanceof Error ? error.message : String(error)));
3867
+ await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeUpdate", errorMessage(error)));
3860
3868
  throw error;
3861
3869
  }
3862
3870
  }
@@ -3870,8 +3878,9 @@ var MOQtailClient = class MOQtailClient {
3870
3878
  * delivered by the newest switch target retires everything older.
3871
3879
  *
3872
3880
  * @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.
3881
+ * @returns Either a {@link RequestError} (refusal) or the new request's {@link SubscribeResult}, where `stream`
3882
+ * is the same {@link https://developer.mozilla.org/docs/Web/API/ReadableStream | ReadableStream} object returned by the
3883
+ * original `subscribe()` call and `done` that subscription's, which resolves once the whole switched chain is over.
3875
3884
  * @throws :{@link MOQtailError} If the client is destroyed.
3876
3885
  * @throws :{@link ProtocolViolationError} If `switchFromRequestId` does not name an active subscription.
3877
3886
  * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
@@ -3881,7 +3890,7 @@ var MOQtailClient = class MOQtailClient {
3881
3890
  * await client.switch({
3882
3891
  * switchFromRequestId,
3883
3892
  * switchMode: SwitchMode.Soft,
3884
- * newSubscribeOptions: { fullTrackName: newTrackName, priority: 0, groupOrder: GroupOrder.Original, forward: true, locationFilter: new LocationFilter(LocationFilterType.NextObject) },
3893
+ * newSubscribeOptions: { fullTrackName: newTrackName, priority: 0, groupOrder: GroupOrder.Original, locationFilter: new LocationFilter(LocationFilterType.NextObject) },
3885
3894
  * onDrainDecision: (request) => true
3886
3895
  * });
3887
3896
  * ```
@@ -3900,7 +3909,7 @@ var MOQtailClient = class MOQtailClient {
3900
3909
  subscription.drainTimeoutMs = this.switchDrainTimeoutMs;
3901
3910
  if (onDrainDecision) subscription.onDrainDecision = onDrainDecision;
3902
3911
  const drains = switchMode === 1;
3903
- if (newSubscribeOptions.parameters?.find(require_model.MessageParameter.isSwitchFrom)) require_logger.logger.warn("MOQtailClient", `switch: overwriting existing SwitchFrom parameter for requestId=${switchFromRequestId}`);
3912
+ if (newSubscribeOptions.parameters?.find(require_model.MessageParameter.isSwitchFrom)) require_emitter.logger.warn("MOQtailClient", `switch: overwriting existing SwitchFrom parameter for requestId=${switchFromRequestId}`);
3904
3913
  const parameters = [...newSubscribeOptions.parameters?.filter((p) => !require_model.MessageParameter.isSwitchFrom(p)) ?? [], new require_model.SwitchFrom(switchFromRequestId, switchMode, drains)];
3905
3914
  const result = await this.subscribe({
3906
3915
  ...newSubscribeOptions,
@@ -3910,15 +3919,25 @@ var MOQtailClient = class MOQtailClient {
3910
3919
  const newRequest = this.requests.get(result.requestId);
3911
3920
  subscription.addSwitchTarget(newRequest, drains);
3912
3921
  return {
3913
- requestId: result.requestId,
3914
- stream: subscription.stream
3922
+ ...result,
3923
+ stream: subscription.stream,
3924
+ done: subscription.done
3915
3925
  };
3916
3926
  } catch (error) {
3917
- await this.disconnect(new require_model.InternalError("MOQtailClient.switch", error instanceof Error ? error.message : String(error)));
3927
+ await this.disconnect(new require_model.InternalError("MOQtailClient.switch", errorMessage(error)));
3918
3928
  throw error;
3919
3929
  }
3920
3930
  }
3921
3931
  /**
3932
+ * The orderer for a request, unless its ordering, else the client's, is `'none'` or
3933
+ * unset. Descending group order is never ordered: every group after the first would be late.
3934
+ */
3935
+ #createOrderer(ordering, groupOrder, requestId, release) {
3936
+ const resolved = ordering ?? this.#options.ordering ?? "none";
3937
+ if (resolved === "none" || groupOrder === 2) return void 0;
3938
+ return new ObjectOrderer(resolved, release, (from, to) => this.emit("orderinggap", requestId, from, to));
3939
+ }
3940
+ /**
3922
3941
  * Ends a subscription whose publisher has said how many streams it opened and has
3923
3942
  * now delivered all of them, and reports whether that happened.
3924
3943
  *
@@ -3929,16 +3948,15 @@ var MOQtailClient = class MOQtailClient {
3929
3948
  */
3930
3949
  completeSubscription(request, force = false) {
3931
3950
  if (!force && (!request.expectedStreams || request.streamsAccepted < request.expectedStreams)) return false;
3951
+ request.orderer?.flush();
3932
3952
  const owner = request.manager;
3933
3953
  if (owner) {
3934
3954
  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);
3955
+ if (owner.requests.length === 0) owner.objects.close();
3956
+ } else request.objects.close();
3957
+ this.#forgetSubscription(request);
3940
3958
  this.#closeRequestStream(request.requestId);
3941
- require_logger.logger.debug("MOQtailClient", `subscription for request ${request.requestId} completed`);
3959
+ require_emitter.logger.debug("MOQtailClient", `subscription for request ${request.requestId} completed`);
3942
3960
  return true;
3943
3961
  }
3944
3962
  /**
@@ -3964,7 +3982,7 @@ var MOQtailClient = class MOQtailClient {
3964
3982
  * {@link MOQtailClient.trackAliasResolutionTimeoutMs} elapses with it still unclaimed.
3965
3983
  */
3966
3984
  async #waitForTrackAlias(trackAlias) {
3967
- require_logger.logger.debug("MOQtailClient", `data stream waiting for the track alias ${trackAlias} to be named`);
3985
+ require_emitter.logger.debug("MOQtailClient", `data stream waiting for the track alias ${trackAlias} to be named`);
3968
3986
  return new Promise((resolve) => {
3969
3987
  let waiters = this.#aliasWaiters.get(trackAlias);
3970
3988
  if (!waiters) {
@@ -4000,12 +4018,30 @@ var MOQtailClient = class MOQtailClient {
4000
4018
  this.subscriptions.delete(trackAlias);
4001
4019
  this.aliasFullTrackNameMap.delete(trackAlias);
4002
4020
  }
4021
+ /**
4022
+ * Lifts the fill's ordering suspension when no fill fetch stream will open: nothing was
4023
+ * published yet (no LARGEST_OBJECT), or none opened shortly after SUBSCRIBE_OK (an empty
4024
+ * fill range, moqt-22 3.4).
4025
+ */
4026
+ #liftFillSuspension(request) {
4027
+ const lift = () => {
4028
+ if (!request.fillOpened) request.orderer?.resumeWindow("fill");
4029
+ };
4030
+ if (!request.fillBoundary) lift();
4031
+ else setTimeout(lift, this.fillOpenTimeoutMs);
4032
+ }
4003
4033
  /** Tears down a switch target that lost the handover race to a newer one. */
4004
4034
  async #retireSwitchedRequest(request) {
4035
+ request.orderer?.flush();
4036
+ this.#forgetSubscription(request);
4037
+ await this.#resetRequestStream(request.requestId, 1);
4038
+ }
4039
+ /** Drops `request` from the request tables, frees its alias, and resolves its `done`. */
4040
+ #forgetSubscription(request) {
4005
4041
  this.requests.delete(request.requestId);
4006
4042
  this.requestIdMap.removeMappingByRequestId(request.requestId);
4007
4043
  this.#releaseTrackAlias(request);
4008
- await this.#resetRequestStream(request.requestId, 1);
4044
+ request.finish();
4009
4045
  }
4010
4046
  /**
4011
4047
  * One-shot retrieval of a bounded object span, optionally anchored to an existing subscription, returning a stream of {@link MoqtObject}s.
@@ -4021,7 +4057,7 @@ var MOQtailClient = class MOQtailClient {
4021
4057
  * - typeAndProps: Discriminated union carrying parameters specific to each fetch mode (see examples).
4022
4058
  * - parameters: Optional version-specific extension block.
4023
4059
  *
4024
- * Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, stream }` whose `stream`
4060
+ * Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, fetchOk, stream }` whose `stream`
4025
4061
  * ends naturally after the bounded range completes (no explicit cancel needed for normal completion).
4026
4062
  *
4027
4063
  * Use cases:
@@ -4076,31 +4112,30 @@ var MOQtailClient = class MOQtailClient {
4076
4112
  ...parameters ?? []
4077
4113
  ];
4078
4114
  const requestId = this.#nextClientRequestId;
4079
- require_logger.logger.log("MOQtailClient", "fetch: generated requestId:", requestId, "current #dontUseRequestId:", this.#dontUseRequestId);
4115
+ require_emitter.logger.log("MOQtailClient", "fetch: generated requestId:", requestId, "current #dontUseRequestId:", this.#dontUseRequestId);
4080
4116
  const msg = new require_model.Fetch(requestId, fullTrackName, params);
4081
4117
  const request = new FetchRequest(msg);
4082
4118
  request.onEndOfRange = args.onEndOfRange;
4083
- require_logger.logger.log("MOQtailClient", "fetch: full fetch message:", {
4119
+ request.orderer = this.#createOrderer(args.ordering, groupOrder, requestId, (obj) => request.objects.enqueue(obj));
4120
+ require_emitter.logger.log("MOQtailClient", "fetch: full fetch message:", {
4084
4121
  requestId: msg.requestId,
4085
4122
  fullTrackName: `${fullTrackName}`
4086
4123
  });
4087
4124
  this.requests.set(msg.requestId, request);
4088
- require_logger.logger.log("MOQtailClient", "fetch: about to send fetch message to server");
4125
+ require_emitter.logger.log("MOQtailClient", "fetch: about to send fetch message to server");
4089
4126
  await this.#openRequestStream(msg.requestId, msg);
4090
- require_logger.logger.log("MOQtailClient", "fetch: fetch message sent successfully, waiting for response");
4127
+ require_emitter.logger.log("MOQtailClient", "fetch: fetch message sent successfully, waiting for response");
4091
4128
  const response = await request;
4092
4129
  if (response instanceof require_model.RequestError) {
4093
4130
  this.requests.delete(msg.requestId);
4094
4131
  return response;
4095
- } else {
4096
- const stream = request.stream;
4097
- return {
4098
- requestId: msg.requestId,
4099
- stream
4100
- };
4101
- }
4132
+ } else return {
4133
+ requestId: msg.requestId,
4134
+ fetchOk: response,
4135
+ stream: request.stream
4136
+ };
4102
4137
  } catch (error) {
4103
- await this.disconnect(new require_model.InternalError("MOQtailClient.fetch", error instanceof Error ? error.message : String(error)));
4138
+ await this.disconnect(new require_model.InternalError("MOQtailClient.fetch", errorMessage(error)));
4104
4139
  throw error;
4105
4140
  }
4106
4141
  }
@@ -4145,7 +4180,7 @@ var MOQtailClient = class MOQtailClient {
4145
4180
  if (typeof requestId === "number") requestId = BigInt(requestId);
4146
4181
  if (this.requests.get(requestId) instanceof FetchRequest) await this.#resetRequestStream(requestId, 1);
4147
4182
  } catch (error) {
4148
- await this.disconnect(new require_model.InternalError("MOQtailClient.fetchCancel", error instanceof Error ? error.message : String(error)));
4183
+ await this.disconnect(new require_model.InternalError("MOQtailClient.fetchCancel", errorMessage(error)));
4149
4184
  throw error;
4150
4185
  }
4151
4186
  }
@@ -4173,7 +4208,7 @@ var MOQtailClient = class MOQtailClient {
4173
4208
  trackAlias
4174
4209
  };
4175
4210
  } catch (error) {
4176
- await this.disconnect(new require_model.InternalError("MOQtailClient.publish", error instanceof Error ? error.message : String(error)));
4211
+ await this.disconnect(new require_model.InternalError("MOQtailClient.publish", errorMessage(error)));
4177
4212
  throw error;
4178
4213
  }
4179
4214
  }
@@ -4186,17 +4221,18 @@ var MOQtailClient = class MOQtailClient {
4186
4221
  try {
4187
4222
  if (typeof publishRequestId === "number") publishRequestId = BigInt(publishRequestId);
4188
4223
  const publication = this.publications.get(publishRequestId);
4189
- const msg = new require_model.PublishDone(statusCode, publication instanceof PublishPublication ? publication.streamsOpened : require_model.PublishDone.UNKNOWN_STREAM_COUNT, new require_model.ReasonPhrase(reasonPhrase));
4224
+ const streamCount = publication instanceof PublishPublication ? publication.streamsOpened : require_model.PublishDone.UNKNOWN_STREAM_COUNT;
4225
+ const msg = new require_model.PublishDone(statusCode, streamCount, new require_model.ReasonPhrase(reasonPhrase));
4190
4226
  const requestStream = this.#requestStreams.get(publishRequestId);
4191
4227
  if (requestStream) {
4192
4228
  await requestStream.send(msg);
4193
4229
  await this.#closeRequestStream(publishRequestId);
4194
- } else require_logger.logger.warn("MOQtailClient", `publishDone: no request stream for requestId=${publishRequestId}`);
4230
+ } else require_emitter.logger.warn("MOQtailClient", `publishDone: no request stream for requestId=${publishRequestId}`);
4195
4231
  this.requests.delete(publishRequestId);
4196
4232
  this.requestIdMap.removeMappingByRequestId(publishRequestId);
4197
4233
  this.subscriptionAliasMap.delete(publishRequestId);
4198
4234
  } catch (error) {
4199
- await this.disconnect(new require_model.InternalError("MOQtailClient.publishDone", error instanceof Error ? error.message : String(error)));
4235
+ await this.disconnect(new require_model.InternalError("MOQtailClient.publishDone", errorMessage(error)));
4200
4236
  throw error;
4201
4237
  }
4202
4238
  }
@@ -4208,20 +4244,28 @@ var MOQtailClient = class MOQtailClient {
4208
4244
  */
4209
4245
  acceptPushedTrack(msg) {
4210
4246
  this.#ensureActive();
4211
- let streamController;
4212
- const stream = new ReadableStream({ start(c) {
4213
- streamController = c;
4214
- } });
4215
4247
  this.requestIdMap.addMapping(msg.requestId, msg.fullTrackName);
4248
+ const objects = new ObjectStream();
4216
4249
  const receiver = {
4217
4250
  requestId: msg.requestId,
4218
4251
  fullTrackName: msg.fullTrackName,
4219
- streamsAccepted: 0,
4252
+ streamsAccepted: 0n,
4253
+ expectedStreams: void 0,
4254
+ publishDone: void 0,
4220
4255
  largestLocation: void 0,
4221
- controller: streamController
4256
+ finish() {},
4257
+ manager: {
4258
+ objects,
4259
+ requests: [],
4260
+ drop() {},
4261
+ deliver(_request, obj) {
4262
+ objects.enqueue(obj);
4263
+ return true;
4264
+ }
4265
+ }
4222
4266
  };
4223
4267
  this.#claimTrackAlias(msg.trackAlias, receiver);
4224
- return stream;
4268
+ return objects.readable;
4225
4269
  }
4226
4270
  /**
4227
4271
  * Declare (publish) a track namespace to the peer so subscribers using matching prefixes (via {@link MOQtailClient.subscribeNamespace})
@@ -4281,7 +4325,7 @@ var MOQtailClient = class MOQtailClient {
4281
4325
  this.requests.delete(msg.requestId);
4282
4326
  return response;
4283
4327
  } catch (error) {
4284
- await this.disconnect(new require_model.InternalError("MOQtailClient.publishNamespace", error instanceof Error ? error.message : String(error)));
4328
+ await this.disconnect(new require_model.InternalError("MOQtailClient.publishNamespace", errorMessage(error)));
4285
4329
  throw error;
4286
4330
  }
4287
4331
  }
@@ -4340,13 +4384,13 @@ var MOQtailClient = class MOQtailClient {
4340
4384
  try {
4341
4385
  const params = parameters ?? [];
4342
4386
  const msg = new require_model.SubscribeNamespace(this.#nextClientRequestId, trackNamespacePrefix, params);
4343
- const requestStream = await RequestStream.open(this.webTransport, msg, this.#requestStreamHooks);
4387
+ const requestStream = await RequestStream.open(this.webTransport, msg, this);
4344
4388
  this.#requestStreams.set(msg.requestId, requestStream);
4345
- require_logger.logger.log("MOQtailClient", "subscribeNamespace | sent msg", msg, msg.trackNamespacePrefix.toUtf8Path(), msg.requestId);
4389
+ require_emitter.logger.log("MOQtailClient", "subscribeNamespace | sent msg", msg, msg.trackNamespacePrefix.toUtf8Path(), msg.requestId);
4346
4390
  const response = await requestStream.next();
4347
4391
  if (!response) throw new require_model.InternalError("MOQtailClient.subscribeNamespace", "Stream closed before response");
4348
4392
  if (!(response instanceof require_model.RequestOk || response instanceof require_model.RequestError)) throw new require_model.ProtocolViolationError("MOQtailClient.subscribeNamespace", "Unexpected response message type");
4349
- require_logger.logger.log("MOQtailClient", "subscribeNamespace | got response", response);
4393
+ require_emitter.logger.log("MOQtailClient", "subscribeNamespace | got response", response);
4350
4394
  if (response instanceof require_model.RequestOk) {
4351
4395
  this.subscribedNamespaces.add(trackNamespacePrefix);
4352
4396
  this.#namespaceRequestIds.set(trackNamespacePrefix.toUtf8Path(), msg.requestId);
@@ -4361,7 +4405,7 @@ var MOQtailClient = class MOQtailClient {
4361
4405
  }
4362
4406
  };
4363
4407
  } catch (error) {
4364
- await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeNamespace", error instanceof Error ? error.message : String(error)));
4408
+ await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeNamespace", errorMessage(error)));
4365
4409
  throw error;
4366
4410
  }
4367
4411
  }
@@ -4370,7 +4414,7 @@ var MOQtailClient = class MOQtailClient {
4370
4414
  assertWithinFilterRangeLimit(parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.subscribeTracks");
4371
4415
  try {
4372
4416
  const msg = new require_model.SubscribeTracks(this.#nextClientRequestId, trackNamespacePrefix, parameters ?? []);
4373
- const requestStream = await RequestStream.open(this.webTransport, msg, this.#requestStreamHooks);
4417
+ const requestStream = await RequestStream.open(this.webTransport, msg, this);
4374
4418
  this.#requestStreams.set(msg.requestId, requestStream);
4375
4419
  const response = await requestStream.next();
4376
4420
  if (!response) throw new require_model.InternalError("MOQtailClient.subscribeTracks", "Stream closed before response");
@@ -4387,7 +4431,7 @@ var MOQtailClient = class MOQtailClient {
4387
4431
  }
4388
4432
  };
4389
4433
  } catch (error) {
4390
- await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeTracks", error instanceof Error ? error.message : String(error)));
4434
+ await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeTracks", errorMessage(error)));
4391
4435
  throw error;
4392
4436
  }
4393
4437
  }
@@ -4396,8 +4440,8 @@ var MOQtailClient = class MOQtailClient {
4396
4440
  while (true) {
4397
4441
  const msg = await requestStream.next();
4398
4442
  if (!msg) break;
4399
- if (msg instanceof require_model.Namespace && this.onPeerNamespace) this.onPeerNamespace(prefix, msg.trackNamespaceSuffix);
4400
- else if (msg instanceof require_model.NamespaceDone && this.onPeerNamespaceDone) this.onPeerNamespaceDone(prefix, msg.trackNamespaceSuffix);
4443
+ if (msg instanceof require_model.Namespace) this.emit("peernamespace", prefix, msg.trackNamespaceSuffix);
4444
+ else if (msg instanceof require_model.NamespaceDone) this.emit("peernamespacedone", prefix, msg.trackNamespaceSuffix);
4401
4445
  }
4402
4446
  } finally {
4403
4447
  this.#requestStreams.delete(requestId);
@@ -4415,7 +4459,7 @@ var MOQtailClient = class MOQtailClient {
4415
4459
  this.subscribedNamespaces.delete(trackNamespacePrefix);
4416
4460
  await this.#closeNamespaceRequestStream(trackNamespacePrefix);
4417
4461
  } catch (error) {
4418
- await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribeNamespace", error instanceof Error ? error.message : String(error)));
4462
+ await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribeNamespace", errorMessage(error)));
4419
4463
  throw error;
4420
4464
  }
4421
4465
  }
@@ -4450,7 +4494,7 @@ var MOQtailClient = class MOQtailClient {
4450
4494
  this.requests.delete(msg.requestId);
4451
4495
  return response;
4452
4496
  } catch (error) {
4453
- await this.disconnect(new require_model.InternalError("MOQtailClient.trackStatus", error instanceof Error ? error.message : String(error)));
4497
+ await this.disconnect(new require_model.InternalError("MOQtailClient.trackStatus", errorMessage(error)));
4454
4498
  throw error;
4455
4499
  }
4456
4500
  }
@@ -4459,28 +4503,8 @@ var MOQtailClient = class MOQtailClient {
4459
4503
  *
4460
4504
  * @param requestId - The requestId carried by `first`; the key the stream is filed under.
4461
4505
  */
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
4506
  async #openRequestStream(requestId, first) {
4483
- const requestStream = await RequestStream.open(this.webTransport, first, this.#requestStreamHooks);
4507
+ const requestStream = await RequestStream.open(this.webTransport, first, this);
4484
4508
  this.#requestStreams.set(requestId, requestStream);
4485
4509
  this.#pumpRequestStream(requestId, requestStream);
4486
4510
  return requestStream;
@@ -4495,8 +4519,8 @@ var MOQtailClient = class MOQtailClient {
4495
4519
  * the wire changes.
4496
4520
  *
4497
4521
  * @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.
4522
+ * is not: opening a session is the application's call, so it is surfaced as a
4523
+ * `goaway` event and the request stream is closed.
4500
4524
  *
4501
4525
  * @internal
4502
4526
  */
@@ -4504,12 +4528,12 @@ var MOQtailClient = class MOQtailClient {
4504
4528
  const oldStream = this.#requestStreams.get(requestId);
4505
4529
  const first = oldStream?.first;
4506
4530
  if (!oldStream || !first) {
4507
- require_logger.logger.warn("MOQtailClient", `GOAWAY on a request stream this side did not open (request id ${requestId})`);
4531
+ require_emitter.logger.warn("MOQtailClient", `GOAWAY on a request stream this side did not open (request id ${requestId})`);
4508
4532
  return false;
4509
4533
  }
4510
4534
  if (goAway.newSessionUri) {
4511
- require_logger.logger.log("MOQtailClient", `GOAWAY migrates request ${requestId} to ${goAway.newSessionUri}`);
4512
- this.onGoaway?.(goAway);
4535
+ require_emitter.logger.log("MOQtailClient", `GOAWAY migrates request ${requestId} to ${goAway.newSessionUri}`);
4536
+ this.emit("goaway", goAway);
4513
4537
  await this.#closeRequestStream(requestId);
4514
4538
  return false;
4515
4539
  }
@@ -4520,7 +4544,7 @@ var MOQtailClient = class MOQtailClient {
4520
4544
  oldStream.migrated = true;
4521
4545
  await oldStream.close();
4522
4546
  await this.#openRequestStream(requestId, reissued);
4523
- require_logger.logger.log("MOQtailClient", `re-issued request ${requestId} as request id ${wireRequestId}`);
4547
+ require_emitter.logger.log("MOQtailClient", `re-issued request ${requestId} as request id ${wireRequestId}`);
4524
4548
  return true;
4525
4549
  }
4526
4550
  /** The request a peer-supplied Request ID belongs to, undoing any migration. */
@@ -4529,7 +4553,7 @@ var MOQtailClient = class MOQtailClient {
4529
4553
  try {
4530
4554
  handler?.(marker.endOfRange, marker.location);
4531
4555
  } catch (handlerError) {
4532
- require_logger.logger.warn("MOQtailClient", "End of Range handler error:", handlerError);
4556
+ require_emitter.logger.warn("MOQtailClient", "End of Range handler error:", handlerError);
4533
4557
  }
4534
4558
  }
4535
4559
  #clientRequestId(wireRequestId) {
@@ -4553,6 +4577,7 @@ var MOQtailClient = class MOQtailClient {
4553
4577
  */
4554
4578
  async #pumpRequestStream(requestId, requestStream) {
4555
4579
  let answered = false;
4580
+ let closedBy;
4556
4581
  try {
4557
4582
  while (true) {
4558
4583
  const msg = await requestStream.next();
@@ -4562,13 +4587,16 @@ var MOQtailClient = class MOQtailClient {
4562
4587
  await handler(this, msg, requestStream, requestId);
4563
4588
  answered = true;
4564
4589
  }
4565
- require_logger.logger.debug("MOQtailClient", `request stream for requestId=${requestId} closed by peer`);
4590
+ require_emitter.logger.debug("MOQtailClient", `request stream for requestId=${requestId} closed by peer`);
4566
4591
  } catch (error) {
4567
- require_logger.logger.error("MOQtailClient", `request stream for requestId=${requestId} failed`, error);
4592
+ if (this.#sessionClosing(error)) closedBy = error;
4593
+ else require_emitter.logger.error("MOQtailClient", `request stream for requestId=${requestId} failed`, error);
4594
+ const request = this.requests.get(requestId);
4595
+ if (!requestStream.migrated && request instanceof SubscribeRequest) request.finish();
4568
4596
  } finally {
4569
4597
  if (!requestStream.migrated) {
4570
4598
  this.#requestStreams.delete(requestId);
4571
- if (!answered) this.requests.get(requestId)?.reject(new require_model.InternalError("MOQtailClient", `Request stream closed before answering request ${requestId}`));
4599
+ if (!answered) this.requests.get(requestId)?.reject(closedBy ?? new require_model.InternalError("MOQtailClient", `Request stream closed before answering request ${requestId}`));
4572
4600
  }
4573
4601
  }
4574
4602
  }
@@ -4600,7 +4628,6 @@ var MOQtailClient = class MOQtailClient {
4600
4628
  * Reads the shared control stream, every request type has its own bidi stream.
4601
4629
  */
4602
4630
  async #handleIncomingControlMessages() {
4603
- this.#ensureActive();
4604
4631
  try {
4605
4632
  const reader = this.controlStream.stream.getReader();
4606
4633
  while (true) {
@@ -4608,47 +4635,51 @@ var MOQtailClient = class MOQtailClient {
4608
4635
  if (done) throw new require_model.MOQtailError("WebTransport session is terminated");
4609
4636
  const handler = getHandlerForControlMessage(msg);
4610
4637
  if (!handler) {
4611
- require_logger.logger.warn("MOQtailClient", `${msg.constructor.name} on the control stream`);
4638
+ require_emitter.logger.warn("MOQtailClient", `${msg.constructor.name} on the control stream`);
4612
4639
  continue;
4613
4640
  }
4614
4641
  await handler(this, msg);
4615
4642
  }
4616
4643
  } catch (error) {
4617
- this.disconnect();
4618
- throw error;
4644
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", "control stream failed", error);
4645
+ await this.disconnect(error);
4619
4646
  }
4620
4647
  }
4621
4648
  async #acceptIncomingUniStreams() {
4622
- this.#ensureActive();
4623
4649
  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 require_model.MOQtailError("WebTransport session is terminated");
4650
+ try {
4651
+ while (true) {
4652
+ const { done, value: stream } = await reader.read();
4653
+ if (done) return;
4654
+ this.#handleRecvStreams(stream).catch((error) => {
4655
+ if (error instanceof PeerStreamResetError || this.#sessionClosing(error)) {
4656
+ require_emitter.logger.debug("MOQtailClient", `data stream ended: ${error.message}`);
4657
+ return;
4658
+ }
4659
+ require_emitter.logger.error("MOQtailClient", "handleRecvStreams error", error);
4660
+ });
4630
4661
  }
4631
- this.#handleRecvStreams(stream).catch((error) => {
4632
- if (error instanceof PeerStreamResetError) {
4633
- require_logger.logger.debug("MOQtailClient", `data stream ended: ${error.message}`);
4634
- return;
4635
- }
4636
- require_logger.logger.error("MOQtailClient", "handleRecvStreams error", error);
4637
- });
4638
4662
  } catch (error) {
4639
- require_logger.logger.error("MOQtailClient", "acceptIncomingUniStreams error", error);
4640
- if (this.#isDestroyed) break;
4663
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", "acceptIncomingUniStreams error", error);
4641
4664
  }
4642
4665
  }
4643
- #acceptIncomingBiStreams() {
4644
- (async () => {
4645
- const reader = this.webTransport.incomingBidirectionalStreams.getReader();
4666
+ async #acceptIncomingBiStreams() {
4667
+ const reader = this.webTransport.incomingBidirectionalStreams.getReader();
4668
+ try {
4646
4669
  while (true) {
4647
4670
  const { value: biStream, done } = await reader.read();
4648
- if (done) break;
4649
- this.#dispatchIncomingRequestStream(new RequestStream(biStream, this.#requestStreamHooks));
4671
+ if (done) return;
4672
+ this.#dispatchIncomingRequestStream(new RequestStream(biStream, this)).catch((error) => {
4673
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", "incoming request stream failed", error);
4674
+ });
4650
4675
  }
4651
- })();
4676
+ } catch (error) {
4677
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", "acceptIncomingBiStreams error", error);
4678
+ }
4679
+ }
4680
+ /** The session is going away, so a read or write failing is expected, not an error to log. */
4681
+ #sessionClosing(error) {
4682
+ return this.#isDestroyed || isSessionClosed(error);
4652
4683
  }
4653
4684
  /**
4654
4685
  * Serves one peer-opened request stream: the first message must be a `First`-marked
@@ -4660,7 +4691,7 @@ var MOQtailClient = class MOQtailClient {
4660
4691
  const first = await requestStream.next();
4661
4692
  if (!first) return;
4662
4693
  if (!require_model.ControlMessageType.isFirst(first.getType())) {
4663
- require_logger.logger.warn("MOQtailClient", `${first.constructor.name} may not open a request stream; resetting it`);
4694
+ require_emitter.logger.warn("MOQtailClient", `${first.constructor.name} may not open a request stream; resetting it`);
4664
4695
  await requestStream.reset(0);
4665
4696
  return;
4666
4697
  }
@@ -4675,7 +4706,7 @@ var MOQtailClient = class MOQtailClient {
4675
4706
  msg = await requestStream.next();
4676
4707
  }
4677
4708
  } catch (error) {
4678
- require_logger.logger.error("MOQtailClient", "incoming request stream failed", error);
4709
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", "incoming request stream failed", error);
4679
4710
  } finally {
4680
4711
  const requestId = "requestId" in first ? first.requestId : void 0;
4681
4712
  if (requestId !== void 0) {
@@ -4685,245 +4716,136 @@ var MOQtailClient = class MOQtailClient {
4685
4716
  await requestStream.close();
4686
4717
  }
4687
4718
  }
4719
+ /** The objects on a fetch data stream. End-of-range markers carry no Object, so they go to `onEndOfRange`. */
4720
+ async *#readFetchObjects(reader, fullTrackName, onEndOfRange) {
4721
+ while (true) {
4722
+ const { done, value } = await reader.read();
4723
+ if (done) return;
4724
+ if (!value) continue;
4725
+ if (!(value instanceof require_model.FetchObject)) throw new require_model.ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
4726
+ if (value.kind === "end_of_range") this.#notifyEndOfRange(onEndOfRange, value);
4727
+ else yield require_model.MoqtObject.fromFetchObject(value, fullTrackName);
4728
+ }
4729
+ }
4688
4730
  async #handleRecvStreams(incomingUniStream) {
4689
4731
  this.#ensureActive();
4690
- try {
4691
- const recvStream = await RecvStream.new(incomingUniStream, this.dataStreamTimeoutMs, this.onDataReceived, (header) => {
4692
- if (!(header instanceof require_model.FetchHeader)) return 0;
4693
- const request = this.requests.get(this.#clientRequestId(header.requestId));
4694
- if (!(request instanceof FetchRequest)) return 0;
4695
- return require_model.MessageParameter.groupOrderOf(request.message.parameters);
4696
- }, this.dataStreamObserver((header) => header instanceof require_model.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 require_model.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 require_model.FetchObject) {
4713
- if (nextObject.kind === "end_of_range") {
4714
- this.#notifyEndOfRange(request.onEndOfRange, nextObject);
4715
- continue;
4716
- }
4717
- const moqtObject = require_model.MoqtObject.fromFetchObject(nextObject, fullTrackName);
4718
- request.controller?.enqueue(moqtObject);
4719
- continue;
4720
- }
4721
- throw new require_model.ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
4722
- }
4732
+ const recvStream = await RecvStream.new(incomingUniStream, this.dataStreamTimeoutMs, this, (header) => {
4733
+ if (!(header instanceof require_model.FetchHeader)) return 0;
4734
+ const request = this.requests.get(this.#clientRequestId(header.requestId));
4735
+ if (!(request instanceof FetchRequest)) return 0;
4736
+ return require_model.MessageParameter.groupOrderOf(request.message.parameters);
4737
+ }, (header) => this.#streamTrackName(header));
4738
+ const header = recvStream.header;
4739
+ const reader = recvStream.stream.getReader();
4740
+ let forceComplete = false;
4741
+ if (header instanceof require_model.FetchHeader) {
4742
+ const request = this.requests.get(this.#clientRequestId(header.requestId));
4743
+ if (request instanceof FetchRequest) {
4744
+ let previous;
4745
+ try {
4746
+ const objects = this.#readFetchObjects(reader, request.message.fullTrackName, request.onEndOfRange);
4747
+ for await (const moqtObject of objects) {
4748
+ if (!request.objects.open) {
4749
+ await recvStream.stopSending(1);
4750
+ break;
4723
4751
  }
4724
- } finally {
4725
- reader.releaseLock();
4752
+ if (request.orderer) request.orderer.push(moqtObject, previous);
4753
+ else request.objects.enqueue(moqtObject);
4754
+ previous = moqtObject.location;
4726
4755
  }
4727
- return;
4756
+ request.orderer?.flush();
4757
+ request.objects.close();
4758
+ } finally {
4759
+ reader.releaseLock();
4728
4760
  }
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 require_model.FetchObject)) throw new require_model.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 = require_model.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);
4761
+ return;
4762
+ }
4763
+ if (request instanceof SubscribeRequest) {
4764
+ request.streamsAccepted++;
4765
+ request.fillOpened = true;
4766
+ request.openFills++;
4767
+ request.orderer?.suspendWindow("fill");
4768
+ let previous;
4769
+ try {
4770
+ for await (const moqtObject of this.#readFetchObjects(reader, request.fullTrackName, request.onEndOfRange)) {
4771
+ if (!request.manager.objects.open) {
4772
+ await recvStream.stopSending(1);
4773
+ break;
4774
+ }
4775
+ if (!request.manager.deliver(request, moqtObject, previous)) {
4776
+ await recvStream.stopSending(1);
4777
+ forceComplete = true;
4778
+ break;
4749
4779
  }
4750
- } finally {
4751
- reader.releaseLock();
4780
+ previous = moqtObject.location;
4752
4781
  }
4753
- this.completeSubscription(request, forceComplete);
4754
- return;
4755
- }
4756
- throw new require_model.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);
4782
+ } finally {
4783
+ reader.releaseLock();
4784
+ request.openFills--;
4785
+ if (request.openFills === 0) request.orderer?.resumeWindow("fill");
4762
4786
  }
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 require_model.SubgroupObject) {
4778
- if (!firstObjectId) firstObjectId = nextObject.objectId;
4779
- let subgroupId = null;
4780
- if (require_model.SubgroupHeaderType.isSubgroupIdZero(header.type)) subgroupId = 0n;
4781
- else if (require_model.SubgroupHeaderType.isSubgroupIdFirstObjectId(header.type)) subgroupId = firstObjectId ?? null;
4782
- else if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(header.type)) subgroupId = header.subgroupId ?? null;
4783
- const moqtObject = require_model.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;
4787
+ this.completeSubscription(request, forceComplete);
4788
+ return;
4789
+ }
4790
+ throw new require_model.ProtocolViolationError("MOQtailClient", "No request for received request id");
4791
+ } else {
4792
+ let subscription = this.subscriptions.get(header.trackAlias);
4793
+ if (!subscription) {
4794
+ await this.#waitForTrackAlias(header.trackAlias);
4795
+ subscription = this.subscriptions.get(header.trackAlias);
4796
+ }
4797
+ if (subscription) {
4798
+ subscription.streamsAccepted++;
4799
+ const fullTrackName = subscription.fullTrackName;
4800
+ let firstObjectId = null;
4801
+ let lastObjectId;
4802
+ let subgroupTimeoutId;
4803
+ const effectiveDiscardPolicy = subscription.earlyDiscardPolicy ?? this.#earlyDiscardPolicy;
4804
+ if (effectiveDiscardPolicy?.subgroupReceiveTimeout !== void 0) subgroupTimeoutId = setTimeout(() => {
4805
+ reader.cancel(streamResetReason(2)).catch(() => {});
4806
+ }, effectiveDiscardPolicy.subgroupReceiveTimeout);
4807
+ try {
4808
+ while (true) {
4809
+ const { done, value: nextObject } = await reader.read();
4810
+ if (done) {
4811
+ if (lastObjectId !== void 0 && require_model.SubgroupHeaderType.containsEndOfGroup(header.type)) subscription.orderer?.endGroup(header.groupId, lastObjectId);
4812
+ break;
4813
+ }
4814
+ if (nextObject) {
4815
+ if (nextObject instanceof require_model.SubgroupObject) {
4816
+ lastObjectId = nextObject.objectId;
4817
+ if (firstObjectId === null) firstObjectId = nextObject.objectId;
4818
+ let subgroupId = null;
4819
+ if (require_model.SubgroupHeaderType.isSubgroupIdZero(header.type)) subgroupId = 0n;
4820
+ else if (require_model.SubgroupHeaderType.isSubgroupIdFirstObjectId(header.type)) subgroupId = firstObjectId ?? null;
4821
+ else if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(header.type)) subgroupId = header.subgroupId ?? null;
4822
+ const moqtObject = require_model.MoqtObject.fromSubgroupObject(nextObject, header.groupId, header.publisherPriority, subgroupId, fullTrackName);
4823
+ if (!subscription.largestLocation) subscription.largestLocation = moqtObject.location;
4824
+ if (subscription.largestLocation.compare(moqtObject.location) == -1) subscription.largestLocation = moqtObject.location;
4825
+ if (!subscription.manager.objects.open) {
4826
+ await recvStream.stopSending(1);
4827
+ break;
4828
+ }
4829
+ if (!subscription.manager.deliver(subscription, moqtObject)) {
4830
+ forceComplete = true;
4831
+ await recvStream.stopSending(1);
4832
+ break;
4794
4833
  }
4795
- throw new require_model.ProtocolViolationError("MOQtailClient", "Received fetch object after subgroup header");
4834
+ continue;
4796
4835
  }
4836
+ throw new require_model.ProtocolViolationError("MOQtailClient", "Received fetch object after subgroup header");
4797
4837
  }
4798
- } finally {
4799
- if (subgroupTimeoutId !== void 0) clearTimeout(subgroupTimeoutId);
4800
4838
  }
4801
- this.completeSubscription(subscription, forceComplete);
4802
- return;
4839
+ } finally {
4840
+ if (subgroupTimeoutId !== void 0) clearTimeout(subgroupTimeoutId);
4803
4841
  }
4804
- throw new require_model.ProtocolViolationError("MOQtailClient", "No subscription for received track alias");
4842
+ this.completeSubscription(subscription, forceComplete);
4843
+ return;
4805
4844
  }
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 require_model.Location(midObj.groupId, midObj.objectId).compare(new require_model.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 require_model.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 require_model.Location(midObj.groupId, midObj.objectId).compare(new require_model.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 require_model.Location(midObj.groupId, midObj.objectId).compare(location);
4920
- if (cmp < 0 || exclusive && cmp === 0) low = mid + 1;
4921
- else high = mid;
4845
+ throw new require_model.ProtocolViolationError("MOQtailClient", "No subscription for received track alias");
4922
4846
  }
4923
- return low;
4924
4847
  }
4925
4848
  };
4926
- //#endregion
4927
4849
  Object.defineProperty(exports, "ControlRecvStream", {
4928
4850
  enumerable: true,
4929
4851
  get: function() {
@@ -4942,6 +4864,12 @@ Object.defineProperty(exports, "ControlStream", {
4942
4864
  return ControlStream;
4943
4865
  }
4944
4866
  });
4867
+ Object.defineProperty(exports, "DEFAULT_FILL_OPEN_TIMEOUT_MS", {
4868
+ enumerable: true,
4869
+ get: function() {
4870
+ return DEFAULT_FILL_OPEN_TIMEOUT_MS;
4871
+ }
4872
+ });
4945
4873
  Object.defineProperty(exports, "DEFAULT_MAX_FILTER_RANGES", {
4946
4874
  enumerable: true,
4947
4875
  get: function() {
@@ -4978,28 +4906,22 @@ Object.defineProperty(exports, "FetchRequest", {
4978
4906
  return FetchRequest;
4979
4907
  }
4980
4908
  });
4981
- Object.defineProperty(exports, "HybridTrackSource", {
4982
- enumerable: true,
4983
- get: function() {
4984
- return HybridTrackSource;
4985
- }
4986
- });
4987
- Object.defineProperty(exports, "LiveTrackSource", {
4909
+ Object.defineProperty(exports, "MOQtailClient", {
4988
4910
  enumerable: true,
4989
4911
  get: function() {
4990
- return LiveTrackSource;
4912
+ return MOQtailClient;
4991
4913
  }
4992
4914
  });
4993
- Object.defineProperty(exports, "MOQtailClient", {
4915
+ Object.defineProperty(exports, "ObjectOrderer", {
4994
4916
  enumerable: true,
4995
4917
  get: function() {
4996
- return MOQtailClient;
4918
+ return ObjectOrderer;
4997
4919
  }
4998
4920
  });
4999
- Object.defineProperty(exports, "MemoryObjectCache", {
4921
+ Object.defineProperty(exports, "ObjectStream", {
5000
4922
  enumerable: true,
5001
4923
  get: function() {
5002
- return MemoryObjectCache;
4924
+ return ObjectStream;
5003
4925
  }
5004
4926
  });
5005
4927
  Object.defineProperty(exports, "PublishNamespaceRequest", {
@@ -5020,12 +4942,6 @@ Object.defineProperty(exports, "PublishRequest", {
5020
4942
  return PublishRequest;
5021
4943
  }
5022
4944
  });
5023
- Object.defineProperty(exports, "RecvDatagramStream", {
5024
- enumerable: true,
5025
- get: function() {
5026
- return RecvDatagramStream;
5027
- }
5028
- });
5029
4945
  Object.defineProperty(exports, "RecvStream", {
5030
4946
  enumerable: true,
5031
4947
  get: function() {
@@ -5038,12 +4954,6 @@ Object.defineProperty(exports, "RequestStream", {
5038
4954
  return RequestStream;
5039
4955
  }
5040
4956
  });
5041
- Object.defineProperty(exports, "RingBufferObjectCache", {
5042
- enumerable: true,
5043
- get: function() {
5044
- return RingBufferObjectCache;
5045
- }
5046
- });
5047
4957
  Object.defineProperty(exports, "SendDatagramStream", {
5048
4958
  enumerable: true,
5049
4959
  get: function() {
@@ -5056,12 +4966,6 @@ Object.defineProperty(exports, "SendStream", {
5056
4966
  return SendStream;
5057
4967
  }
5058
4968
  });
5059
- Object.defineProperty(exports, "StaticTrackSource", {
5060
- enumerable: true,
5061
- get: function() {
5062
- return StaticTrackSource;
5063
- }
5064
- });
5065
4969
  Object.defineProperty(exports, "SubscribeNamespaceRequest", {
5066
4970
  enumerable: true,
5067
4971
  get: function() {
@@ -5092,3 +4996,9 @@ Object.defineProperty(exports, "TrackStatusRequest", {
5092
4996
  return TrackStatusRequest;
5093
4997
  }
5094
4998
  });
4999
+ Object.defineProperty(exports, "errorMessage", {
5000
+ enumerable: true,
5001
+ get: function() {
5002
+ return errorMessage;
5003
+ }
5004
+ });