moqtail 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +153 -473
  2. package/dist/{client-Z7egUKTO.cjs → client-DQ5aGbLR.cjs} +1100 -1099
  3. package/dist/client-DUzLw_Y8.d.cts +1932 -0
  4. package/dist/{client-BW1agDFV.mjs → client-DVi4Nh1J.mjs} +942 -947
  5. package/dist/client-epHqMdHm.d.mts +1932 -0
  6. package/dist/client.cjs +121 -4
  7. package/dist/client.d.cts +23 -1933
  8. package/dist/client.d.mts +23 -1933
  9. package/dist/client.mjs +117 -2
  10. package/dist/emitter-UbeRcbuf.mjs +109 -0
  11. package/dist/{logger-c2NoQqtx.cjs → emitter-qNJYD3yQ.cjs} +61 -2
  12. package/dist/index-B-BMK-b6.d.mts +2090 -0
  13. package/dist/index-BtemTtwe.d.cts +2090 -0
  14. package/dist/{index-DBbxKcc1.d.cts → index-CNn9BgO6.d.mts} +168 -337
  15. package/dist/index.cjs +39 -34
  16. package/dist/index.d.cts +20 -4
  17. package/dist/index.d.mts +20 -4
  18. package/dist/index.mjs +5 -4
  19. package/dist/logger-B8IYkljn.d.cts +64 -0
  20. package/dist/logger-B8IYkljn.d.mts +64 -0
  21. package/dist/model.cjs +208 -359
  22. package/dist/model.d.cts +2896 -2
  23. package/dist/model.d.mts +17 -2
  24. package/dist/model.mjs +207 -359
  25. package/dist/player/component.cjs +317 -0
  26. package/dist/player/component.d.cts +50 -0
  27. package/dist/player/component.d.mts +50 -0
  28. package/dist/player/component.mjs +315 -0
  29. package/dist/player-CJayEzwt.cjs +6750 -0
  30. package/dist/player-DcctWhyM.mjs +6599 -0
  31. package/dist/player.cjs +27 -0
  32. package/dist/player.d.cts +17 -0
  33. package/dist/player.d.mts +17 -0
  34. package/dist/player.mjs +1 -0
  35. package/dist/rolldown-runtime-CmQyd0Gu.cjs +27 -0
  36. package/dist/util.cjs +9 -10
  37. package/dist/util.d.cts +20 -13
  38. package/dist/util.d.mts +20 -13
  39. package/dist/util.mjs +4 -6
  40. package/package.json +45 -5
  41. package/dist/index-DBbxKcc1.d.mts +0 -3051
  42. package/dist/logger-ByDB8lYF.mjs +0 -56
  43. package/dist/logger-dEoueCj7.d.cts +0 -35
  44. package/dist/logger-dEoueCj7.d.mts +0 -35
@@ -1,8 +1,27 @@
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
6
25
  *
7
26
  * Licensed under the Apache License, Version 2.0 (the "License");
8
27
  * you may not use this file except in compliance with the License.
@@ -16,7 +35,104 @@ const require_logger = require("./logger-c2NoQqtx.cjs");
16
35
  * See the License for the specific language governing permissions and
17
36
  * limitations under the License.
18
37
  */
19
- function withTimeout$1(promise, ms, errorMsg) {
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
121
+ *
122
+ * Licensed under the Apache License, Version 2.0 (the "License");
123
+ * you may not use this file except in compliance with the License.
124
+ * You may obtain a copy of the License at
125
+ *
126
+ * http://www.apache.org/licenses/LICENSE-2.0
127
+ *
128
+ * Unless required by applicable law or agreed to in writing, software
129
+ * distributed under the License is distributed on an "AS IS" BASIS,
130
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
131
+ * See the License for the specific language governing permissions and
132
+ * limitations under the License.
133
+ */
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,34 +620,36 @@ 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;
608
647
  if (object instanceof require_model.FetchObject) {
609
648
  serializedObject = object.serialize(this.#fetchPrevCtx, this.#groupOrder).toUint8Array();
610
- const newCtx = object.toContext();
611
- if (newCtx) this.#fetchPrevCtx = newCtx;
649
+ this.#fetchPrevCtx = object.nextContext(this.#fetchPrevCtx);
612
650
  } else {
613
651
  if (this.#lastObjectId !== void 0 && object.objectId <= this.#lastObjectId) {
614
- 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}`);
615
653
  throw new Error(`SendStream.write: Out-of-order object detected. Attempted to write objectId=${object.objectId}, but lastObjectId=${this.#lastObjectId}.`);
616
654
  }
617
655
  serializedObject = object.serialize(this.#lastObjectId).toUint8Array();
@@ -623,31 +661,23 @@ var SendStream = class SendStream {
623
661
  this.#reporter.end("error");
624
662
  throw error;
625
663
  }
626
- if (this.onDataSent) this.onDataSent(object);
664
+ this.#events?.emit("datasent", object);
627
665
  this.#reporter.object(this.header, object);
628
666
  }
629
667
  async close() {
630
668
  if (this.#writer) {
631
- 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}`);
632
670
  await this.#writer.close();
633
671
  this.#reporter.end("fin");
634
672
  }
635
673
  }
636
674
  /** Abruptly tears the stream down, so the peer reads back `code` (§3.3.3). */
637
675
  async reset(code) {
638
- 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}`);
639
677
  await this.#writer.abort(streamResetReason(code)).catch(() => {});
640
678
  this.#reporter.end("reset", code);
641
679
  }
642
680
  };
643
- function withTimeout(promise, ms, errorMsg) {
644
- if (ms === void 0) return promise;
645
- let timeoutId;
646
- const timeoutPromise = new Promise((_, reject) => {
647
- timeoutId = setTimeout(() => reject(new require_model.TimeoutError(errorMsg ?? `Timeout after ${ms}ms`)), ms);
648
- });
649
- return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timeoutId));
650
- }
651
681
  var RecvStream = class RecvStream {
652
682
  header;
653
683
  stream;
@@ -656,15 +686,15 @@ var RecvStream = class RecvStream {
656
686
  #internalBuffer;
657
687
  #groupOrder;
658
688
  #reporter;
659
- onDataReceived;
660
- constructor(header, reader, internalBuffer, reporter, partialDataTimeout, onDataReceived, groupOrder = 0) {
689
+ #events;
690
+ constructor(header, reader, internalBuffer, reporter, partialDataTimeout, events, groupOrder = 0) {
661
691
  this.header = header;
662
692
  this.#reader = reader;
663
693
  this.#reporter = reporter;
664
694
  this.#internalBuffer = internalBuffer;
665
695
  this.#partialDataTimeout = partialDataTimeout;
666
696
  this.#groupOrder = groupOrder;
667
- if (onDataReceived) this.onDataReceived = onDataReceived;
697
+ this.#events = events;
668
698
  this.stream = new ReadableStream({
669
699
  start: (controller) => this.#ingestLoop(controller),
670
700
  cancel: (reason) => this.#reader.cancel(reason)
@@ -673,9 +703,10 @@ var RecvStream = class RecvStream {
673
703
  /**
674
704
  * @param resolveGroupOrder - Consulted once the FETCH header names its request, since
675
705
  * Group ID deltas on the stream are signed by the Group Order the request negotiated.
676
- * @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.
677
708
  */
678
- static async new(readStream, partialDataTimeout, onDataReceived, resolveGroupOrder, observer) {
709
+ static async new(readStream, partialDataTimeout, events, resolveGroupOrder, fullTrackNameOf) {
679
710
  const reader = readStream.getReader();
680
711
  const internalBuffer = new require_model.ByteBuffer();
681
712
  let headerInstance;
@@ -704,12 +735,12 @@ var RecvStream = class RecvStream {
704
735
  reader.releaseLock();
705
736
  throw asStreamResetError("RecvStream.new", error);
706
737
  }
707
- if (onDataReceived) onDataReceived(headerInstance);
708
- const reporter = new DataStreamReporter("in", observer);
738
+ events?.emit("datareceived", headerInstance);
739
+ const reporter = new DataStreamReporter("in", events, fullTrackNameOf);
709
740
  reporter.header(headerInstance);
710
- require_logger.logger.debug("data_stream", `RecvStream opened type=${headerInstance.type}`);
741
+ require_emitter.logger.debug("data_stream", `RecvStream opened type=${headerInstance.type}`);
711
742
  const groupOrder = require_model.Header.isFetch(headerInstance) && resolveGroupOrder ? resolveGroupOrder(headerInstance) : 0;
712
- return new RecvStream(headerInstance, reader, internalBuffer, reporter, partialDataTimeout, onDataReceived, groupOrder);
743
+ return new RecvStream(headerInstance, reader, internalBuffer, reporter, partialDataTimeout, events, groupOrder);
713
744
  }
714
745
  async #ingestLoop(controller) {
715
746
  try {
@@ -721,8 +752,7 @@ var RecvStream = class RecvStream {
721
752
  let object;
722
753
  if (require_model.Header.isFetch(this.header)) {
723
754
  object = require_model.FetchObject.deserialize(this.#internalBuffer, fetchPrevCtx, this.#groupOrder);
724
- const newCtx = object.toContext();
725
- if (newCtx) fetchPrevCtx = newCtx;
755
+ fetchPrevCtx = object.nextContext(fetchPrevCtx);
726
756
  } else {
727
757
  object = require_model.SubgroupObject.deserialize(this.#internalBuffer, require_model.SubgroupHeaderType.hasProperties(this.header.type), previousObjectId);
728
758
  this.header.resolveSubgroupId(object.objectId);
@@ -730,7 +760,7 @@ var RecvStream = class RecvStream {
730
760
  }
731
761
  this.#internalBuffer.commit();
732
762
  controller.enqueue(object);
733
- if (this.onDataReceived) this.onDataReceived(object);
763
+ this.#events?.emit("datareceived", object);
734
764
  this.#reporter.object(this.header, object);
735
765
  continue;
736
766
  } catch (e) {
@@ -747,11 +777,11 @@ var RecvStream = class RecvStream {
747
777
  const { done, value } = readResult;
748
778
  if (done) {
749
779
  if (this.#internalBuffer.remaining > 0) {
750
- 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}`);
751
781
  this.#reporter.end("error");
752
782
  controller.error(new require_model.ProtocolViolationError("RecvStream", `Stream closed with incomplete object data. Remaining: ${this.#internalBuffer.remaining} bytes.`));
753
783
  } else {
754
- 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}`);
755
785
  this.#reporter.end("fin");
756
786
  controller.close();
757
787
  }
@@ -762,10 +792,10 @@ var RecvStream = class RecvStream {
762
792
  } catch (error) {
763
793
  const peerReset = streamResetCodeOf(error);
764
794
  if (peerReset !== void 0) {
765
- 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]}`);
766
796
  this.#reporter.end("reset", peerReset);
767
797
  } else {
768
- 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);
769
799
  this.#reporter.end("error");
770
800
  await this.#reader.cancel(streamResetReason(0)).catch(() => {});
771
801
  }
@@ -774,12 +804,11 @@ var RecvStream = class RecvStream {
774
804
  }
775
805
  /** Asks the peer to stop sending on this stream, reporting `code` (§3.3.3). */
776
806
  async stopSending(code) {
777
- 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}`);
778
808
  await this.#reader.cancel(streamResetReason(code)).catch(() => {});
779
809
  }
780
810
  };
781
- //#endregion
782
- //#region src/client/track/content_source.ts
811
+ // src/client/track/content_source.ts
783
812
  var StaticTrackSource = class {
784
813
  cache;
785
814
  constructor(cache) {
@@ -792,6 +821,8 @@ var StaticTrackSource = class {
792
821
  var LiveTrackSource = class {
793
822
  stream;
794
823
  #listeners = /* @__PURE__ */ new Set();
824
+ /** Each listener's queue tail, so done waits for the objects still being delivered. */
825
+ #queues = /* @__PURE__ */ new Map();
795
826
  #doneListeners = /* @__PURE__ */ new Set();
796
827
  #largestLocation;
797
828
  #ingestActive = false;
@@ -815,22 +846,27 @@ var LiveTrackSource = class {
815
846
  for (const listener of this.#listeners) listener(value);
816
847
  }
817
848
  } catch (error) {
818
- require_logger.logger.error("track/content_source", "Error during live object ingestion:", error);
849
+ require_emitter.logger.error("track/content_source", "Error during live object ingestion:", error);
819
850
  } finally {
820
851
  this.#ingestActive = false;
821
852
  this.#reader?.releaseLock();
822
- for (const doneListener of this.#doneListeners) Promise.resolve().then(() => doneListener());
853
+ const drained = Promise.all([...this.#queues.values()].map((tail) => tail()));
854
+ for (const doneListener of this.#doneListeners) drained.then(() => doneListener());
823
855
  }
824
856
  }
825
857
  onNewObject(listener) {
826
858
  let queue = Promise.resolve();
827
859
  const queuedListener = (obj) => {
828
860
  queue = queue.then(() => listener(obj)).catch((err) => {
829
- require_logger.logger.error("track/content_source", "Error in subscriber listener:", err);
861
+ require_emitter.logger.error("track/content_source", "Error in subscriber listener:", err);
830
862
  });
831
863
  };
832
864
  this.#listeners.add(queuedListener);
833
- return () => this.#listeners.delete(queuedListener);
865
+ this.#queues.set(queuedListener, () => queue);
866
+ return () => {
867
+ this.#queues.delete(queuedListener);
868
+ return this.#listeners.delete(queuedListener);
869
+ };
834
870
  }
835
871
  onDone(listener) {
836
872
  this.#doneListeners.add(listener);
@@ -849,8 +885,7 @@ var HybridTrackSource = class {
849
885
  this.live = new LiveTrackSource(stream);
850
886
  }
851
887
  };
852
- //#endregion
853
- //#region src/client/request/publish_namespace.ts
888
+ // src/client/request/publish_namespace.ts
854
889
  /**
855
890
  * Copyright 2026 The MOQtail Authors
856
891
  *
@@ -879,15 +914,15 @@ var PublishNamespaceRequest = class {
879
914
  this._resolve = resolve;
880
915
  this._reject = reject;
881
916
  });
882
- require_logger.logger.debug("request/publish_namespace", `created requestId=${this.requestId} namespace="${message.trackNamespace}"`);
917
+ require_emitter.logger.debug("request/publish_namespace", `created requestId=${this.requestId} namespace="${message.trackNamespace}"`);
883
918
  }
884
919
  resolve(value) {
885
- 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}"`);
886
- else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/publish_namespace", `resolved with OK requestId=${this.requestId}`);
920
+ 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}"`);
921
+ else if (value instanceof require_model.RequestOk) require_emitter.logger.debug("request/publish_namespace", `resolved with OK requestId=${this.requestId}`);
887
922
  this._resolve(value);
888
923
  }
889
924
  reject(reason) {
890
- require_logger.logger.error("request/publish_namespace", `rejected requestId=${this.requestId}`, reason);
925
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/publish_namespace", `rejected requestId=${this.requestId}`, reason);
891
926
  this._reject(reason);
892
927
  }
893
928
  then(onfulfilled, onrejected) {
@@ -900,52 +935,67 @@ var PublishNamespaceRequest = class {
900
935
  return this.promise.finally(onfinally);
901
936
  }
902
937
  };
903
- //#endregion
904
- //#region src/client/request/fetch.ts
938
+ // src/client/util/object_stream.ts
905
939
  /**
906
- * Copyright 2025 The MOQtail Authors
907
- *
908
- * Licensed under the Apache License, Version 2.0 (the "License");
909
- * you may not use this file except in compliance with the License.
910
- * You may obtain a copy of the License at
911
- *
912
- * http://www.apache.org/licenses/LICENSE-2.0
913
- *
914
- * Unless required by applicable law or agreed to in writing, software
915
- * distributed under the License is distributed on an "AS IS" BASIS,
916
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
917
- * See the License for the specific language governing permissions and
918
- * limitations under the License.
940
+ * A request's consumer-facing object stream. The consumer may cancel it while objects are
941
+ * still in flight, so writes after that, or after it closed or errored, are dropped.
919
942
  */
943
+ var ObjectStream = class {
944
+ readable;
945
+ #controller;
946
+ #open = true;
947
+ constructor() {
948
+ this.readable = new ReadableStream({
949
+ start: (controller) => {
950
+ this.#controller = controller;
951
+ },
952
+ cancel: () => {
953
+ this.#open = false;
954
+ }
955
+ });
956
+ }
957
+ /** False once closed, cancelled by the consumer, or errored: nothing written is read. */
958
+ get open() {
959
+ return this.#open && this.#controller.desiredSize !== null;
960
+ }
961
+ enqueue(object) {
962
+ if (this.open) this.#controller.enqueue(object);
963
+ }
964
+ close() {
965
+ if (!this.open) return;
966
+ this.#open = false;
967
+ this.#controller.close();
968
+ }
969
+ };
970
+ // src/client/request/fetch.ts
920
971
  var FetchRequest = class {
921
972
  requestId;
922
973
  message;
923
974
  _resolve;
924
975
  _reject;
925
976
  promise;
926
- controller;
927
- stream;
977
+ objects = new ObjectStream();
978
+ stream = this.objects.readable;
979
+ onEndOfRange;
980
+ orderer;
928
981
  isActive = true;
929
982
  isResolved = false;
930
983
  constructor(message) {
931
984
  this.requestId = message.requestId;
932
985
  this.message = message;
933
- this.stream = new ReadableStream({ start: (controller) => {
934
- this.controller = controller;
935
- } });
936
986
  this.promise = new Promise((resolve, reject) => {
937
987
  this._resolve = resolve;
938
988
  this._reject = reject;
939
989
  });
940
- require_logger.logger.debug("request/fetch", `created requestId=${this.requestId}`);
990
+ require_emitter.logger.debug("request/fetch", `created requestId=${this.requestId}`);
941
991
  }
942
992
  resolve(value) {
943
- 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}"`);
944
- else if (value instanceof require_model.FetchOk) require_logger.logger.debug("request/fetch", `resolved with OK requestId=${this.requestId}`);
993
+ 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}"`);
994
+ else if (value instanceof require_model.FetchOk) require_emitter.logger.debug("request/fetch", `resolved with OK requestId=${this.requestId}`);
945
995
  this._resolve(value);
946
996
  }
947
997
  reject(reason) {
948
- require_logger.logger.error("request/fetch", `rejected requestId=${this.requestId}`, reason);
998
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/fetch", `rejected requestId=${this.requestId}`, reason);
949
999
  this._reject(reason);
950
1000
  }
951
1001
  then(onfulfilled, onrejected) {
@@ -958,8 +1008,7 @@ var FetchRequest = class {
958
1008
  return this.promise.finally(onfinally);
959
1009
  }
960
1010
  };
961
- //#endregion
962
- //#region src/client/types.ts
1011
+ // src/client/types.ts
963
1012
  /**
964
1013
  * Default for {@link MOQtailClientOptions.trackAliasResolutionTimeoutMs}: how long a
965
1014
  * data stream waits for the control message that establishes its track alias.
@@ -979,28 +1028,17 @@ const DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS = 2e3;
979
1028
  */
980
1029
  const DEFAULT_SWITCH_DRAIN_TIMEOUT_MS = 2e3;
981
1030
  /**
1031
+ * Default for {@link MOQtailClientOptions.fillOpenTimeoutMs}: how long after SUBSCRIBE_OK
1032
+ * a fill fetch stream may take to open before ordering stops waiting for it.
1033
+ */
1034
+ const DEFAULT_FILL_OPEN_TIMEOUT_MS = 1e3;
1035
+ /**
982
1036
  * @public
983
1037
  * The MAX_FILTER_RANGES a client advertises when its setup options set none: how
984
1038
  * many Range Filter ranges it applies, in total, for one subscription or fetch.
985
1039
  */
986
1040
  const DEFAULT_MAX_FILTER_RANGES = 32n;
987
- //#endregion
988
- //#region src/client/request/subscribe.ts
989
- /**
990
- * Copyright 2026 The MOQtail Authors
991
- *
992
- * Licensed under the Apache License, Version 2.0 (the "License");
993
- * you may not use this file except in compliance with the License.
994
- * You may obtain a copy of the License at
995
- *
996
- * http://www.apache.org/licenses/LICENSE-2.0
997
- *
998
- * Unless required by applicable law or agreed to in writing, software
999
- * distributed under the License is distributed on an "AS IS" BASIS,
1000
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1001
- * See the License for the specific language governing permissions and
1002
- * limitations under the License.
1003
- */
1041
+ // src/client/request/subscribe.ts
1004
1042
  /**
1005
1043
  * Represents an active subscription request in MOQT, implementing `PromiseLike`
1006
1044
  * for convenient async resolution when subscription setup succeeds or fails.
@@ -1015,20 +1053,31 @@ var SubscribeRequest = class {
1015
1053
  forward;
1016
1054
  subscribeParameters;
1017
1055
  earlyDiscardPolicy;
1056
+ onEndOfRange;
1018
1057
  largestLocation;
1019
1058
  /**
1020
1059
  * The publisher's Largest Object as of the last SUBSCRIBE_OK or REQUEST_UPDATE_OK,
1021
1060
  * which is where a fill fetch stream stops.
1022
1061
  */
1023
1062
  fillBoundary;
1063
+ /** A fill fetch stream opened for this subscription. */
1064
+ fillOpened = false;
1065
+ /** Fill fetch streams still delivering. */
1066
+ openFills = 0;
1024
1067
  /** EXPIRES from the last SUBSCRIBE_OK or REQUEST_UPDATE_OK, in milliseconds. */
1025
1068
  expires;
1026
1069
  streamsAccepted = 0n;
1027
1070
  expectedStreams;
1028
- /** The Subscription managing this request's output stream once switching is involved. */
1071
+ /** The last PUBLISH_DONE received for this request. */
1072
+ publishDone;
1073
+ #finished = Promise.withResolvers();
1074
+ /** Resolves once this request is over, with {@link SubscribeRequest.publishDone}. Never rejects. */
1075
+ done = this.#finished.promise;
1076
+ /** The Subscription that owns this request's consumer stream; it sets itself on construction. */
1029
1077
  manager;
1030
- controller;
1031
- stream;
1078
+ objects = new ObjectStream();
1079
+ stream = this.objects.readable;
1080
+ orderer;
1032
1081
  #promise;
1033
1082
  #resolve;
1034
1083
  #reject;
@@ -1043,14 +1092,11 @@ var SubscribeRequest = class {
1043
1092
  const fwd = msg.parameters.find(require_model.MessageParameter.isForward);
1044
1093
  this.forward = fwd?.forward ?? true;
1045
1094
  this.subscribeParameters = msg.parameters;
1046
- this.stream = new ReadableStream({ start: (controller) => {
1047
- this.controller = controller;
1048
- } });
1049
1095
  this.#promise = new Promise((resolve, reject) => {
1050
1096
  this.#resolve = resolve;
1051
1097
  this.#reject = reject;
1052
1098
  });
1053
- require_logger.logger.debug("request/subscribe", `created requestId=${this.requestId} ftn="${this.fullTrackName}" priority=${this.priority} forward=${this.forward}`);
1099
+ require_emitter.logger.debug("request/subscribe", `created requestId=${this.requestId} ftn="${this.fullTrackName}" priority=${this.priority} forward=${this.forward}`);
1054
1100
  }
1055
1101
  /**
1056
1102
  * Updates subscription parameters in-place when a `RequestUpdate` message is received.
@@ -1066,6 +1112,22 @@ var SubscribeRequest = class {
1066
1112
  if (typeof require_model.applyMessageParameterUpdate === "function") require_model.applyMessageParameterUpdate(this.subscribeParameters, msg.parameters);
1067
1113
  }
1068
1114
  /**
1115
+ * Puts an object on the consumer stream, through {@link SubscribeRequest.orderer} when
1116
+ * there is one. `previous` is the object before it on the same fill fetch stream.
1117
+ */
1118
+ enqueue(obj, previous) {
1119
+ if (this.orderer) this.orderer.push(obj, previous);
1120
+ else this.output(obj);
1121
+ }
1122
+ /** Writes an object the orderer released, or an unordered one, through the manager. */
1123
+ output(obj) {
1124
+ this.manager.output(this, obj);
1125
+ }
1126
+ /** Ends the request: resolves {@link SubscribeRequest.done}. Later calls do nothing. */
1127
+ finish() {
1128
+ this.#finished.resolve(this.publishDone);
1129
+ }
1130
+ /**
1069
1131
  * Marks this subscription request as canceled.
1070
1132
  */
1071
1133
  unsubscribe() {
@@ -1075,15 +1137,15 @@ var SubscribeRequest = class {
1075
1137
  * Resolves the internal promise with a `SubscribeOk` or `RequestError`.
1076
1138
  */
1077
1139
  resolve(value) {
1078
- 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}"`);
1079
- else if (value instanceof require_model.SubscribeOk) require_logger.logger.debug("request/subscribe", `resolved with OK requestId=${this.requestId} trackAlias=${value.trackAlias}`);
1140
+ 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}"`);
1141
+ else if (value instanceof require_model.SubscribeOk) require_emitter.logger.debug("request/subscribe", `resolved with OK requestId=${this.requestId} trackAlias=${value.trackAlias}`);
1080
1142
  this.#resolve(value);
1081
1143
  }
1082
1144
  /**
1083
1145
  * Rejects the internal promise with an error/reason.
1084
1146
  */
1085
1147
  reject(reason) {
1086
- require_logger.logger.error("request/subscribe", `rejected requestId=${this.requestId}`, reason);
1148
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/subscribe", `rejected requestId=${this.requestId}`, reason);
1087
1149
  this.#reject(reason);
1088
1150
  }
1089
1151
  then(onfulfilled, onrejected) {
@@ -1109,10 +1171,17 @@ var SubscribeRequest = class {
1109
1171
  * subscription is done, or until it has been quiet long enough to say so itself.
1110
1172
  */
1111
1173
  var Subscription = class {
1112
- controller;
1174
+ objects;
1113
1175
  stream;
1114
1176
  /** Oldest first; the last entry is the newest switch target still racing to produce data. */
1115
1177
  #requests;
1178
+ /** Requests {@link Subscription.done} has yet to wait for, oldest first. */
1179
+ #unwaited;
1180
+ /**
1181
+ * Resolves once every tracked request is over, with the newest one's PUBLISH_DONE, or
1182
+ * `undefined` if it ended without one. Never rejects.
1183
+ */
1184
+ done;
1116
1185
  /**
1117
1186
  * Requests a soft switch handed over from, still delivering the tail of what they
1118
1187
  * were told to finish, each with the timer that retires it if it goes quiet.
@@ -1120,6 +1189,8 @@ var Subscription = class {
1120
1189
  #draining = /* @__PURE__ */ new Map();
1121
1190
  /** Switch targets whose handover drains what it supersedes rather than cutting it. */
1122
1191
  #drainsSuperseded = /* @__PURE__ */ new WeakSet();
1192
+ /** The newest request's ordered objects, held while older requests still deliver. */
1193
+ #parked = [];
1123
1194
  /** Set once by `MOQtailClient.switch`; invoked with everything older on cutover. */
1124
1195
  onSuperseded;
1125
1196
  /** Set by the client to decide whether draining a request should continue. */
@@ -1132,9 +1203,19 @@ var Subscription = class {
1132
1203
  drainTimeoutMs = DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
1133
1204
  constructor(initial) {
1134
1205
  this.stream = initial.stream;
1135
- this.controller = initial.controller;
1206
+ this.objects = initial.objects;
1136
1207
  initial.manager = this;
1137
1208
  this.#requests = [initial];
1209
+ this.#unwaited = [initial];
1210
+ this.done = this.#allDone();
1211
+ }
1212
+ async #allDone() {
1213
+ let batch = [];
1214
+ while (this.#unwaited.length > 0) {
1215
+ batch = this.#unwaited.splice(0);
1216
+ await Promise.all(batch.map((request) => request.done));
1217
+ }
1218
+ return batch.at(-1)?.publishDone;
1138
1219
  }
1139
1220
  /** Requests still tracked, oldest first, draining ones last. */
1140
1221
  get requests() {
@@ -1144,6 +1225,10 @@ var Subscription = class {
1144
1225
  get newest() {
1145
1226
  return this.#requests[this.#requests.length - 1];
1146
1227
  }
1228
+ /** More than one request tracked, draining ones included. */
1229
+ get #switching() {
1230
+ return this.#requests.length + this.#draining.size > 1;
1231
+ }
1147
1232
  /**
1148
1233
  * Track a newly issued switch target alongside whatever is still delivering.
1149
1234
  *
@@ -1155,24 +1240,54 @@ var Subscription = class {
1155
1240
  request.manager = this;
1156
1241
  if (drainSuperseded) this.#drainsSuperseded.add(request);
1157
1242
  this.#requests.push(request);
1243
+ this.#unwaited.push(request);
1244
+ this.#updateSwitchState();
1245
+ }
1246
+ /**
1247
+ * Writes an object `request` released. While older requests still deliver, the newest
1248
+ * one's ordered objects wait, so the old track's tail comes first.
1249
+ */
1250
+ output(request, obj) {
1251
+ if (request.orderer && request === this.newest && this.#switching) this.#parked.push(obj);
1252
+ else this.objects.enqueue(obj);
1253
+ }
1254
+ /**
1255
+ * While a switch is in progress no ordering window expires, and once it's over the
1256
+ * parked objects go out first. `left` stopped being tracked.
1257
+ */
1258
+ #updateSwitchState(left = []) {
1259
+ const switching = this.#switching;
1260
+ if (!switching && this.#draining.size === 0) for (const obj of this.#parked.splice(0)) this.objects.enqueue(obj);
1261
+ for (const request of this.requests) if (switching) request.orderer?.suspendWindow("switch");
1262
+ else request.orderer?.resumeWindow("switch");
1263
+ for (const request of left) request.orderer?.resumeWindow("switch");
1264
+ }
1265
+ /** Hands `requests` to `onSuperseded`, which flushes what they still hold, then stops tracking them. */
1266
+ #retire(requests) {
1267
+ this.onSuperseded?.(requests);
1268
+ this.#updateSwitchState(requests);
1158
1269
  }
1159
1270
  /** Stop tracking `request` (e.g. it naturally completed without ever losing/winning a handover). */
1160
1271
  drop(request) {
1161
1272
  this.#clearDrain(request);
1162
1273
  this.#requests = this.#requests.filter((r) => r !== request);
1274
+ this.#updateSwitchState([request]);
1163
1275
  }
1164
1276
  /** Stop tracking everything (used when the whole switch chain is torn down at once). */
1165
1277
  clear() {
1278
+ const left = this.requests;
1166
1279
  for (const request of [...this.#draining.keys()]) this.#clearDrain(request);
1167
1280
  this.#requests = [];
1281
+ this.#parked = [];
1282
+ this.#updateSwitchState(left);
1168
1283
  }
1169
1284
  /** Starts, or on each further object restarts, the quiet period that ends a drain. */
1170
1285
  #keepDraining(request) {
1171
1286
  this.#clearDrain(request);
1172
1287
  this.#draining.set(request, setTimeout(() => {
1173
1288
  this.#draining.delete(request);
1174
- require_logger.logger.debug("Subscription", `drain of request ${request.requestId} ended on silence`);
1175
- this.onSuperseded?.([request]);
1289
+ require_emitter.logger.debug("Subscription", `drain of request ${request.requestId} ended on silence`);
1290
+ this.#retire([request]);
1176
1291
  }, this.drainTimeoutMs));
1177
1292
  }
1178
1293
  #clearDrain(request) {
@@ -1189,31 +1304,32 @@ var Subscription = class {
1189
1304
  * Returns `true` if the object was delivered to the caller,
1190
1305
  * `false` if it was not consumed, and client should cancel the stream.
1191
1306
  */
1192
- deliver(request, obj) {
1307
+ deliver(request, obj, previous) {
1193
1308
  if (this.#draining.has(request)) {
1194
- if (this.onDrainDecision?.(request)) {
1309
+ if (this.onDrainDecision(request)) {
1195
1310
  this.#keepDraining(request);
1196
- this.controller.enqueue(obj);
1311
+ request.enqueue(obj, previous);
1197
1312
  return true;
1198
1313
  }
1314
+ this.#clearDrain(request);
1315
+ this.#retire([request]);
1199
1316
  return false;
1200
1317
  }
1201
1318
  if (!this.#requests.includes(request)) {
1202
- require_logger.logger.warn("Subscription", `discarding object from superseded request ${request.requestId}`);
1319
+ require_emitter.logger.warn("Subscription", `discarding object from superseded request ${request.requestId}`);
1203
1320
  return false;
1204
1321
  }
1205
1322
  if (request === this.newest && this.#requests.length > 1) {
1206
1323
  const superseded = this.#requests.slice(0, -1);
1207
1324
  this.#requests = [request];
1208
1325
  if (this.#drainsSuperseded.has(request)) for (const old of superseded) this.#keepDraining(old);
1209
- else this.onSuperseded?.(superseded);
1326
+ else this.#retire(superseded);
1210
1327
  }
1211
- this.controller.enqueue(obj);
1328
+ request.enqueue(obj, previous);
1212
1329
  return true;
1213
1330
  }
1214
1331
  };
1215
- //#endregion
1216
- //#region src/client/request/publish.ts
1332
+ // src/client/request/publish.ts
1217
1333
  /**
1218
1334
  * Copyright 2025 The MOQtail Authors
1219
1335
  *
@@ -1242,15 +1358,15 @@ var PublishRequest = class {
1242
1358
  this._resolve = resolve;
1243
1359
  this._reject = reject;
1244
1360
  });
1245
- require_logger.logger.debug("request/publish", `created requestId=${this.requestId} ftn="${msg.fullTrackName}"`);
1361
+ require_emitter.logger.debug("request/publish", `created requestId=${this.requestId} ftn="${msg.fullTrackName}"`);
1246
1362
  }
1247
1363
  resolve(value) {
1248
- 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}"`);
1249
- else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/publish", `resolved with OK requestId=${this.requestId}`);
1364
+ 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}"`);
1365
+ else if (value instanceof require_model.RequestOk) require_emitter.logger.debug("request/publish", `resolved with OK requestId=${this.requestId}`);
1250
1366
  this._resolve(value);
1251
1367
  }
1252
1368
  reject(reason) {
1253
- require_logger.logger.error("request/publish", `rejected requestId=${this.requestId}`, reason);
1369
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/publish", `rejected requestId=${this.requestId}`, reason);
1254
1370
  this._reject(reason);
1255
1371
  }
1256
1372
  then(onfulfilled, onrejected) {
@@ -1263,8 +1379,7 @@ var PublishRequest = class {
1263
1379
  return this.promise.finally(onfinally);
1264
1380
  }
1265
1381
  };
1266
- //#endregion
1267
- //#region src/client/request/track_status.ts
1382
+ // src/client/request/track_status.ts
1268
1383
  /**
1269
1384
  * Copyright 2026 The MOQtail Authors
1270
1385
  *
@@ -1293,15 +1408,15 @@ var TrackStatusRequest = class {
1293
1408
  this._resolve = resolve;
1294
1409
  this._reject = reject;
1295
1410
  });
1296
- require_logger.logger.debug("request/track_status", `created requestId=${this.requestId} ftn="${msg.fullTrackName}"`);
1411
+ require_emitter.logger.debug("request/track_status", `created requestId=${this.requestId} ftn="${msg.fullTrackName}"`);
1297
1412
  }
1298
1413
  resolve(value) {
1299
- 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}"`);
1300
- else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/track_status", `resolved with OK requestId=${this.requestId}`);
1414
+ 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}"`);
1415
+ else if (value instanceof require_model.RequestOk) require_emitter.logger.debug("request/track_status", `resolved with OK requestId=${this.requestId}`);
1301
1416
  this._resolve(value);
1302
1417
  }
1303
1418
  reject(reason) {
1304
- require_logger.logger.error("request/track_status", `rejected requestId=${this.requestId}`, reason);
1419
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/track_status", `rejected requestId=${this.requestId}`, reason);
1305
1420
  this._reject(reason);
1306
1421
  }
1307
1422
  then(onfulfilled, onrejected) {
@@ -1314,8 +1429,7 @@ var TrackStatusRequest = class {
1314
1429
  return this.promise.finally(onfinally);
1315
1430
  }
1316
1431
  };
1317
- //#endregion
1318
- //#region src/client/handler/publish.ts
1432
+ // src/client/handler/publish.ts
1319
1433
  /**
1320
1434
  * Copyright 2025 The MOQtail Authors
1321
1435
  *
@@ -1332,7 +1446,7 @@ var TrackStatusRequest = class {
1332
1446
  * limitations under the License.
1333
1447
  */
1334
1448
  const handlerPublish = async (client, msg, stream) => {
1335
- require_logger.logger.log("handler/publish", "track: %s alias: %d", msg.fullTrackName.toString(), msg.trackAlias);
1449
+ require_emitter.logger.log("handler/publish", "track: %s alias: %d", msg.fullTrackName.toString(), msg.trackAlias);
1336
1450
  let streamController;
1337
1451
  const objects = new ReadableStream({ start(c) {
1338
1452
  streamController = c;
@@ -1348,11 +1462,10 @@ const handlerPublish = async (client, msg, stream) => {
1348
1462
  controller: streamController
1349
1463
  };
1350
1464
  client.subscriptions.set(msg.trackAlias, receiver);
1351
- if (client.onPeerPublish) client.onPeerPublish(msg, objects);
1465
+ client.emit("peerpublish", msg, objects);
1352
1466
  await stream.send(new require_model.RequestOk());
1353
1467
  };
1354
- //#endregion
1355
- //#region src/client/handler/publish_namespace.ts
1468
+ // src/client/handler/publish_namespace.ts
1356
1469
  /**
1357
1470
  * Copyright 2025 The MOQtail Authors
1358
1471
  *
@@ -1369,12 +1482,11 @@ const handlerPublish = async (client, msg, stream) => {
1369
1482
  * limitations under the License.
1370
1483
  */
1371
1484
  const handlerPublishNamespace = async (client, msg, stream) => {
1372
- require_logger.logger.log("handler/publish_namespace", "namespace", msg.trackNamespace.toUtf8Path());
1373
- if (client.onNamespacePublished) client.onNamespacePublished(msg);
1485
+ require_emitter.logger.log("handler/publish_namespace", "namespace", msg.trackNamespace.toUtf8Path());
1486
+ client.emit("namespacepublished", msg);
1374
1487
  await stream.send(new require_model.RequestOk());
1375
1488
  };
1376
- //#endregion
1377
- //#region src/client/handler/publish_skipped.ts
1489
+ // src/client/handler/publish_skipped.ts
1378
1490
  /**
1379
1491
  * Copyright 2026 The MOQtail Authors
1380
1492
  *
@@ -1393,11 +1505,10 @@ const handlerPublishNamespace = async (client, msg, stream) => {
1393
1505
  const handlerPublishSkipped = async (client, msg, stream) => {
1394
1506
  const first = stream.first;
1395
1507
  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");
1396
- require_logger.logger.log("handler/publish_skipped", "prefix", first.trackNamespacePrefix.toUtf8Path(), "suffix", msg.trackNamespaceSuffix.toUtf8Path());
1397
- client.onPeerPublishSkipped?.(first.trackNamespacePrefix, msg);
1508
+ require_emitter.logger.log("handler/publish_skipped", "prefix", first.trackNamespacePrefix.toUtf8Path(), "suffix", msg.trackNamespaceSuffix.toUtf8Path());
1509
+ client.emit("peerpublishskipped", first.trackNamespacePrefix, msg);
1398
1510
  };
1399
- //#endregion
1400
- //#region src/client/publication/subgroup.ts
1511
+ // src/client/publication/subgroup.ts
1401
1512
  /**
1402
1513
  * Copyright 2026 The MOQtail Authors
1403
1514
  *
@@ -1459,8 +1570,7 @@ function subgroupHeaderFor(obj, subgroupId, trackAlias, publisherPriority, first
1459
1570
  const explicit = require_model.SubgroupHeaderType.hasExplicitSubgroupId(headerType) ? subgroupId : void 0;
1460
1571
  return new require_model.SubgroupHeader(headerType, trackAlias, obj.location.group, explicit, publisherPriority);
1461
1572
  }
1462
- //#endregion
1463
- //#region src/client/publication/fetch.ts
1573
+ // src/client/publication/fetch.ts
1464
1574
  /**
1465
1575
  * Copyright 2025 The MOQtail Authors
1466
1576
  *
@@ -1498,11 +1608,11 @@ var FetchPublication = class {
1498
1608
  this.#startLocation = start;
1499
1609
  this.#endLocation = end;
1500
1610
  this.#filter = new require_model.CombinedFilter(fetchRequest.parameters);
1501
- require_logger.logger.debug("publication/fetch", `created requestId=${this.#requestId}`);
1611
+ require_emitter.logger.debug("publication/fetch", `created requestId=${this.#requestId}`);
1502
1612
  this.publish();
1503
1613
  }
1504
1614
  cancel() {
1505
- require_logger.logger.debug("publication/fetch", `canceled requestId=${this.#requestId}`);
1615
+ require_emitter.logger.debug("publication/fetch", `canceled requestId=${this.#requestId}`);
1506
1616
  this.#isCanceled = true;
1507
1617
  }
1508
1618
  /**
@@ -1510,27 +1620,27 @@ var FetchPublication = class {
1510
1620
  * a REQUEST_UPDATE for a FETCH fails.
1511
1621
  */
1512
1622
  async resetDataStream(code) {
1513
- require_logger.logger.debug("publication/fetch", `reset data stream requestId=${this.#requestId} code=${code}`);
1623
+ require_emitter.logger.debug("publication/fetch", `reset data stream requestId=${this.#requestId} code=${code}`);
1514
1624
  this.#isCanceled = true;
1515
1625
  await this.#sendStream?.reset(code);
1516
1626
  }
1517
1627
  async publish() {
1518
1628
  if (this.#isCanceled) return;
1519
1629
  if (!this.#track.trackSource.past) throw new require_model.MOQtailError("FetchPublication.publish, Track does not support fetch");
1520
- require_logger.logger.debug("publication/fetch", `publishing requestId=${this.#requestId} start=${this.#startLocation} end=${this.#endLocation}`);
1630
+ require_emitter.logger.debug("publication/fetch", `publishing requestId=${this.#requestId} start=${this.#startLocation} end=${this.#endLocation}`);
1521
1631
  try {
1522
1632
  const objects = await this.#track.trackSource.past.getRange(this.#startLocation);
1523
1633
  this.#objects = objects.filter((obj) => obj.location.compare(this.#endLocation) <= 0);
1524
1634
  const writeStream = await this.#client.webTransport.createUnidirectionalStream();
1525
1635
  const header = new require_model.FetchHeader(5, this.#requestId);
1526
- this.#sendStream = await SendStream.new(writeStream, header, this.#client.onDataSent, require_model.MessageParameter.groupOrderOf(this.#msg.parameters), this.#client.dataStreamObserver(() => this.#track.fullTrackName));
1636
+ this.#sendStream = await SendStream.new(writeStream, header, this.#client, require_model.MessageParameter.groupOrderOf(this.#msg.parameters), () => this.#track.fullTrackName);
1527
1637
  const subgroupIds = new SubgroupIds();
1528
1638
  let sent = 0;
1529
1639
  for (const obj of this.#objects) {
1530
1640
  subgroupIds.note(obj);
1531
1641
  if (!this.#filter.matches(obj, subgroupIds.of(obj))) continue;
1532
1642
  if (this.#isCanceled) {
1533
- require_logger.logger.debug("publication/fetch", `aborted during publish requestId=${this.#requestId}`);
1643
+ require_emitter.logger.debug("publication/fetch", `aborted during publish requestId=${this.#requestId}`);
1534
1644
  await this.#sendStream.reset(1);
1535
1645
  this.#client.publications.delete(this.#requestId);
1536
1646
  return;
@@ -1539,19 +1649,18 @@ var FetchPublication = class {
1539
1649
  sent++;
1540
1650
  }
1541
1651
  await this.#sendStream.close();
1542
- require_logger.logger.debug("publication/fetch", `published requestId=${this.#requestId} objects=${sent} of ${this.#objects.length}`);
1652
+ require_emitter.logger.debug("publication/fetch", `published requestId=${this.#requestId} objects=${sent} of ${this.#objects.length}`);
1543
1653
  this.#client.publications.delete(this.#requestId);
1544
1654
  } catch (error) {
1545
1655
  if (this.#isCanceled) return;
1546
1656
  await this.#sendStream?.reset(0);
1547
- const message = error instanceof Error ? error.message : String(error);
1548
- require_logger.logger.error("publication/fetch", `publish failed requestId=${this.#requestId}`, message);
1657
+ const message = errorMessage(error);
1658
+ require_emitter.logger.error("publication/fetch", `publish failed requestId=${this.#requestId}`, message);
1549
1659
  throw new require_model.InternalError("FetchPublication.publish", `Failed to publish: ${message}`);
1550
1660
  }
1551
1661
  }
1552
1662
  };
1553
- //#endregion
1554
- //#region src/client/util/validators.ts
1663
+ // src/client/util/validators.ts
1555
1664
  /**
1556
1665
  * Copyright 2026 The MOQtail Authors
1557
1666
  *
@@ -1609,8 +1718,7 @@ function assertWithinFilterRangeLimit(params, limit, context) {
1609
1718
  }
1610
1719
  for (const fill of params.filter(require_model.MessageParameter.isFillParameters)) assertWithinFilterRangeLimit(fill.parameters, limit, `${context} (FILL_PARAMETERS)`);
1611
1720
  }
1612
- //#endregion
1613
- //#region src/client/handler/fetch.ts
1721
+ // src/client/handler/fetch.ts
1614
1722
  /**
1615
1723
  * Copyright 2025 The MOQtail Authors
1616
1724
  *
@@ -1627,10 +1735,10 @@ function assertWithinFilterRangeLimit(params, limit, context) {
1627
1735
  * limitations under the License.
1628
1736
  */
1629
1737
  const handlerFetch = async (client, msg, stream) => {
1630
- require_logger.logger.log("handler/fetch", "requestId", msg.requestId);
1738
+ require_emitter.logger.log("handler/fetch", "requestId", msg.requestId);
1631
1739
  const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
1632
1740
  if (filterRejection) {
1633
- require_logger.logger.warn("handler/fetch", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
1741
+ require_emitter.logger.warn("handler/fetch", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
1634
1742
  await stream.send(filterRejection);
1635
1743
  return;
1636
1744
  }
@@ -1649,7 +1757,7 @@ const handlerFetch = async (client, msg, stream) => {
1649
1757
  const largest = track.trackSource.live?.largestLocation ?? (await track.trackSource.past.getRange()).at(-1)?.location;
1650
1758
  const range = msg.locationFilter.fetchRange(largest);
1651
1759
  if (!range) {
1652
- require_logger.logger.warn("handler/fetch", `requestId=${msg.requestId} selects nothing published (largest=${largest})`);
1760
+ require_emitter.logger.warn("handler/fetch", `requestId=${msg.requestId} selects nothing published (largest=${largest})`);
1653
1761
  const response = new require_model.RequestError(17, 0n, new require_model.ReasonPhrase("Nothing published in the requested range"));
1654
1762
  await stream.send(response);
1655
1763
  return;
@@ -1660,8 +1768,7 @@ const handlerFetch = async (client, msg, stream) => {
1660
1768
  const response = new require_model.FetchOk(false, range.end, [], trackProperties);
1661
1769
  await stream.send(response);
1662
1770
  };
1663
- //#endregion
1664
- //#region src/client/handler/fetch_ok.ts
1771
+ // src/client/handler/fetch_ok.ts
1665
1772
  /**
1666
1773
  * Copyright 2025 The MOQtail Authors
1667
1774
  *
@@ -1678,7 +1785,7 @@ const handlerFetch = async (client, msg, stream) => {
1678
1785
  * limitations under the License.
1679
1786
  */
1680
1787
  const handlerFetchOk = async (client, msg, _stream, requestId) => {
1681
- require_logger.logger.log("handler/fetch_ok", "requestId", requestId);
1788
+ require_emitter.logger.log("handler/fetch_ok", "requestId", requestId);
1682
1789
  const request = client.requests.get(requestId);
1683
1790
  if (request instanceof FetchRequest) {
1684
1791
  if (msg.trackProperties.length > 0) {
@@ -1688,16 +1795,15 @@ const handlerFetchOk = async (client, msg, _stream, requestId) => {
1688
1795
  request.resolve(msg);
1689
1796
  } else throw new require_model.ProtocolViolationError("handlerFetchOk", `FETCH_OK on a stream with no pending fetch request (request id ${requestId})`);
1690
1797
  };
1691
- //#endregion
1692
- //#region src/client/handler/goaway.ts
1798
+ // src/client/handler/goaway.ts
1693
1799
  const handlerGoAway = async (client, msg) => {
1694
- require_logger.logger.log("handler/goaway", "newSessionUri", msg.newSessionUri, "timeout", msg.timeout);
1800
+ require_emitter.logger.log("handler/goaway", "newSessionUri", msg.newSessionUri, "timeout", msg.timeout);
1695
1801
  if (client.goawayReceived) {
1696
1802
  await client.disconnect(new require_model.ProtocolViolationError("handler/goaway", "A second GOAWAY arrived on the control stream"));
1697
1803
  return;
1698
1804
  }
1699
1805
  client.goawayReceived = true;
1700
- if (client.onGoaway) client.onGoaway(msg);
1806
+ client.emit("goaway", msg);
1701
1807
  };
1702
1808
  /**
1703
1809
  * GOAWAY on a request stream: the peer is migrating that one request (§10.4). The
@@ -1705,11 +1811,10 @@ const handlerGoAway = async (client, msg) => {
1705
1811
  * on it, carries on.
1706
1812
  */
1707
1813
  const handlerGoAwayOnRequestStream = async (client, msg, _stream, requestId) => {
1708
- require_logger.logger.log("handler/goaway", `GOAWAY migrating request ${requestId}`, "timeout", msg.timeout);
1814
+ require_emitter.logger.log("handler/goaway", `GOAWAY migrating request ${requestId}`, "timeout", msg.timeout);
1709
1815
  await client.migrateRequest(requestId, msg);
1710
1816
  };
1711
- //#endregion
1712
- //#region src/util/simple_lock.ts
1817
+ // src/util/simple_lock.ts
1713
1818
  var SimpleLock = class {
1714
1819
  acquiredLock = false;
1715
1820
  contQueue = [];
@@ -1737,8 +1842,7 @@ var SimpleLock = class {
1737
1842
  });
1738
1843
  }
1739
1844
  };
1740
- //#endregion
1741
- //#region src/client/util/priority.ts
1845
+ // src/client/util/priority.ts
1742
1846
  /**
1743
1847
  * Copyright 2025 The MOQtail Authors
1744
1848
  *
@@ -1760,8 +1864,7 @@ function getTransportPriority(priority) {
1760
1864
  if (priority === 255) return 0;
1761
1865
  return Math.round((255 - priority) * (Number.MAX_SAFE_INTEGER / 255));
1762
1866
  }
1763
- //#endregion
1764
- //#region src/client/publication/subscribe.ts
1867
+ // src/client/publication/subscribe.ts
1765
1868
  /**
1766
1869
  * Copyright 2025 The MOQtail Authors
1767
1870
  *
@@ -1947,7 +2050,7 @@ var SubscribePublication = class {
1947
2050
  await stream.close();
1948
2051
  }
1949
2052
  } catch (err) {
1950
- require_logger.logger.warn("publication/subscribe", "error in closing stream: id, group, err", this.#id, group, err);
2053
+ require_emitter.logger.warn("publication/subscribe", "error in closing stream: id, group, err", this.#id, group, err);
1951
2054
  } finally {
1952
2055
  await this.#lock.release();
1953
2056
  }
@@ -1994,7 +2097,7 @@ var SubscribePublication = class {
1994
2097
  const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
1995
2098
  const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
1996
2099
  const header = subgroupHeaderFor(obj, subgroupId ?? obj.location.object, this.#trackAlias, this.#publisherPriority, firstObject);
1997
- const sendStream = await SendStream.new(writeStream, header, this.client.onDataSent, void 0, this.client.dataStreamObserver(() => this.track.fullTrackName));
2100
+ const sendStream = await SendStream.new(writeStream, header, this.client, void 0, () => this.track.fullTrackName);
1998
2101
  this.#streams.set(obj.location.group, sendStream);
1999
2102
  this.#streamsOpened++;
2000
2103
  this.#markGroupSeen(obj.location.group);
@@ -2017,8 +2120,7 @@ var SubscribePublication = class {
2017
2120
  });
2018
2121
  }
2019
2122
  };
2020
- //#endregion
2021
- //#region src/client/handler/subscribe.ts
2123
+ // src/client/handler/subscribe.ts
2022
2124
  /**
2023
2125
  * Copyright 2025 The MOQtail Authors
2024
2126
  *
@@ -2035,22 +2137,22 @@ var SubscribePublication = class {
2035
2137
  * limitations under the License.
2036
2138
  */
2037
2139
  const handlerSubscribe = async (client, msg, stream) => {
2038
- require_logger.logger.debug("handler/subscribe", `received requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2140
+ require_emitter.logger.debug("handler/subscribe", `received requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2039
2141
  const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
2040
2142
  if (filterRejection) {
2041
- require_logger.logger.warn("handler/subscribe", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
2143
+ require_emitter.logger.warn("handler/subscribe", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
2042
2144
  await stream.send(filterRejection);
2043
2145
  return;
2044
2146
  }
2045
2147
  const track = client.trackSources.get(msg.fullTrackName.toString());
2046
2148
  if (!track) {
2047
- require_logger.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track not found, sending REQUEST_ERROR`);
2149
+ require_emitter.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track not found, sending REQUEST_ERROR`);
2048
2150
  const subscribeError = new require_model.RequestError(16, 0n, new require_model.ReasonPhrase("Track does not exist"));
2049
2151
  await stream.send(subscribeError);
2050
2152
  return;
2051
2153
  }
2052
2154
  if (!track.trackSource.live) {
2053
- require_logger.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track has no live source, sending REQUEST_ERROR`);
2155
+ require_emitter.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track has no live source, sending REQUEST_ERROR`);
2054
2156
  const response = new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("Requested track does not support subscribe"));
2055
2157
  await stream.send(response);
2056
2158
  return;
@@ -2059,15 +2161,14 @@ const handlerSubscribe = async (client, msg, stream) => {
2059
2161
  const largestLocation = track.trackSource.live.largestLocation;
2060
2162
  const parameters = largestLocation ? [new require_model.LargestObject(largestLocation)] : [];
2061
2163
  const trackProperties = require_model.MessageParameter.includesProperties(msg.parameters) ? track.trackProperties ?? [] : [];
2062
- 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`);
2164
+ 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`);
2063
2165
  const subscribeOk = require_model.SubscribeOk.create(track.trackAlias, parameters, trackProperties);
2064
2166
  const publication = new SubscribePublication(client, track, msg, stream, largestLocation);
2065
2167
  client.publications.set(msg.requestId, publication);
2066
2168
  await stream.send(subscribeOk);
2067
- require_logger.logger.debug("handler/subscribe", `requestId=${msg.requestId} — SUBSCRIBE_OK sent, publication registered`);
2169
+ require_emitter.logger.debug("handler/subscribe", `requestId=${msg.requestId} — SUBSCRIBE_OK sent, publication registered`);
2068
2170
  };
2069
- //#endregion
2070
- //#region src/client/handler/subscribe_namespace.ts
2171
+ // src/client/handler/subscribe_namespace.ts
2071
2172
  /**
2072
2173
  * Copyright 2025 The MOQtail Authors
2073
2174
  *
@@ -2084,12 +2185,11 @@ const handlerSubscribe = async (client, msg, stream) => {
2084
2185
  * limitations under the License.
2085
2186
  */
2086
2187
  const handlerSubscribeNamespace = async (client, msg, stream) => {
2087
- require_logger.logger.log("handler/subscribe_namespace", "namespace", msg.trackNamespacePrefix.toUtf8Path());
2088
- if (client.onPeerSubscribeNamespace) client.onPeerSubscribeNamespace(msg);
2188
+ require_emitter.logger.log("handler/subscribe_namespace", "namespace", msg.trackNamespacePrefix.toUtf8Path());
2189
+ client.emit("peersubscribenamespace", msg);
2089
2190
  await stream.send(new require_model.RequestOk());
2090
2191
  };
2091
- //#endregion
2092
- //#region src/client/handler/subscribe_tracks.ts
2192
+ // src/client/handler/subscribe_tracks.ts
2093
2193
  /**
2094
2194
  * Copyright 2026 The MOQtail Authors
2095
2195
  *
@@ -2106,7 +2206,7 @@ const handlerSubscribeNamespace = async (client, msg, stream) => {
2106
2206
  * limitations under the License.
2107
2207
  */
2108
2208
  const handlerSubscribeTracks = async (client, msg, stream) => {
2109
- require_logger.logger.log("handler/subscribe_tracks", "prefix", msg.trackNamespacePrefix.toUtf8Path());
2209
+ require_emitter.logger.log("handler/subscribe_tracks", "prefix", msg.trackNamespacePrefix.toUtf8Path());
2110
2210
  if (require_model.MessageParameter.carriesRangeFilter(msg.parameters)) {
2111
2211
  let code = 3;
2112
2212
  let reason = "Range filters on SUBSCRIBE_TRACKS are not supported";
@@ -2117,15 +2217,14 @@ const handlerSubscribeTracks = async (client, msg, stream) => {
2117
2217
  code = 54;
2118
2218
  reason = error.details;
2119
2219
  }
2120
- require_logger.logger.warn("handler/subscribe_tracks", `requestId=${msg.requestId} refused: ${reason}`);
2220
+ require_emitter.logger.warn("handler/subscribe_tracks", `requestId=${msg.requestId} refused: ${reason}`);
2121
2221
  await stream.send(new require_model.RequestError(code, 0n, new require_model.ReasonPhrase(reason)));
2122
2222
  return;
2123
2223
  }
2124
- if (client.onPeerSubscribeTracks) client.onPeerSubscribeTracks(msg);
2224
+ client.emit("peersubscribetracks", msg);
2125
2225
  await stream.send(new require_model.RequestOk());
2126
2226
  };
2127
- //#endregion
2128
- //#region src/client/request/subscribe_namespace.ts
2227
+ // src/client/request/subscribe_namespace.ts
2129
2228
  /**
2130
2229
  * Copyright 2026 The MOQtail Authors
2131
2230
  *
@@ -2154,15 +2253,15 @@ var SubscribeNamespaceRequest = class {
2154
2253
  this._resolve = resolve;
2155
2254
  this._reject = reject;
2156
2255
  });
2157
- require_logger.logger.debug("request/subscribe_namespace", `created requestId=${this.requestId} namespace="${msg.trackNamespacePrefix}"`);
2256
+ require_emitter.logger.debug("request/subscribe_namespace", `created requestId=${this.requestId} namespace="${msg.trackNamespacePrefix}"`);
2158
2257
  }
2159
2258
  resolve(value) {
2160
- 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}"`);
2161
- else if (value instanceof require_model.RequestOk) require_logger.logger.debug("request/subscribe_namespace", `resolved with OK requestId=${this.requestId}`);
2259
+ 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}"`);
2260
+ else if (value instanceof require_model.RequestOk) require_emitter.logger.debug("request/subscribe_namespace", `resolved with OK requestId=${this.requestId}`);
2162
2261
  this._resolve(value);
2163
2262
  }
2164
2263
  reject(reason) {
2165
- require_logger.logger.error("request/subscribe_namespace", `rejected requestId=${this.requestId}`, reason);
2264
+ if (!isSessionClosed(reason)) require_emitter.logger.error("request/subscribe_namespace", `rejected requestId=${this.requestId}`, reason);
2166
2265
  this._reject(reason);
2167
2266
  }
2168
2267
  then(onfulfilled, onrejected) {
@@ -2175,8 +2274,7 @@ var SubscribeNamespaceRequest = class {
2175
2274
  return this.promise.finally(onfinally);
2176
2275
  }
2177
2276
  };
2178
- //#endregion
2179
- //#region src/client/publication/publish.ts
2277
+ // src/client/publication/publish.ts
2180
2278
  /**
2181
2279
  * @public
2182
2280
  * Manages the proactive publication of MOQT objects from a publisher to the relay.
@@ -2279,14 +2377,14 @@ var PublishPublication = class {
2279
2377
  }
2280
2378
  /**
2281
2379
  * Moves the Forward State: false parks the publication, true resumes it. The
2282
- * application hears about the move through {@link MOQtailClient.onForwardStateChange},
2380
+ * application hears about the move through the client's `forwardstatechange` event,
2283
2381
  * which is where a publisher starts or stops the work behind the track -- a camera
2284
2382
  * and an encoder cost the same whether or not anything is listening.
2285
2383
  */
2286
2384
  setForwardState(forward) {
2287
2385
  if (this.#forward === forward) return;
2288
2386
  this.#forward = forward;
2289
- this.client.onForwardStateChange?.(this.publishMsg.requestId, forward);
2387
+ this.client.emit("forwardstatechange", this.publishMsg.requestId, forward);
2290
2388
  }
2291
2389
  /**
2292
2390
  * Applies a REQUEST_UPDATE the peer sent on this publication's request stream. It
@@ -2322,7 +2420,7 @@ var PublishPublication = class {
2322
2420
  }
2323
2421
  this.#isCompleted = true;
2324
2422
  this.#lock.acquire().then(() => {
2325
- 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));
2423
+ 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));
2326
2424
  this.#streams.clear();
2327
2425
  this.#lock.release();
2328
2426
  });
@@ -2360,7 +2458,7 @@ var PublishPublication = class {
2360
2458
  const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
2361
2459
  const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
2362
2460
  const header = subgroupHeaderFor(obj, subgroupId ?? obj.location.object, this.#trackAlias, this.#publisherPriority, firstObject);
2363
- const sendStream = await SendStream.new(writeStream, header, this.client.onDataSent, void 0, this.client.dataStreamObserver(() => this.track.fullTrackName));
2461
+ const sendStream = await SendStream.new(writeStream, header, this.client, void 0, () => this.track.fullTrackName);
2364
2462
  this.#streams.set(obj.location.group, sendStream);
2365
2463
  this.#streamsOpened++;
2366
2464
  this.#markGroupSeen(obj.location.group);
@@ -2369,8 +2467,13 @@ var PublishPublication = class {
2369
2467
  }
2370
2468
  const sendStream = this.#streams.get(obj.location.group);
2371
2469
  await this.#lock.acquire();
2372
- await sendStream.write(obj.tryIntoSubgroupObject());
2373
- await this.#lock.release();
2470
+ try {
2471
+ await sendStream.write(obj.tryIntoSubgroupObject());
2472
+ } catch (err) {
2473
+ require_emitter.logger.warn("publication/publish", "subgroup stream write failed, skipping rest of group", obj.location.group, err);
2474
+ } finally {
2475
+ await this.#lock.release();
2476
+ }
2374
2477
  if (this.latestLocation && this.latestLocation.group !== obj.location.group) {
2375
2478
  const prevGroup = this.latestLocation.group;
2376
2479
  try {
@@ -2380,13 +2483,13 @@ var PublishPublication = class {
2380
2483
  try {
2381
2484
  await prevStream.close();
2382
2485
  } catch (err) {
2383
- require_logger.logger.warn("publication/publish", "error in closing stream", prevGroup, err);
2486
+ require_emitter.logger.warn("publication/publish", "error in closing stream", prevGroup, err);
2384
2487
  }
2385
2488
  this.#streams.delete(prevGroup);
2386
2489
  }
2387
2490
  await this.#lock.release();
2388
2491
  } catch (err) {
2389
- require_logger.logger.warn("publication/publish", "error in closing stream: id, latestLocation.group, err", this.#id, this.latestLocation.group, err);
2492
+ require_emitter.logger.warn("publication/publish", "error in closing stream: id, latestLocation.group, err", this.#id, this.latestLocation.group, err);
2390
2493
  }
2391
2494
  }
2392
2495
  await this.#lock.acquire();
@@ -2399,8 +2502,7 @@ var PublishPublication = class {
2399
2502
  });
2400
2503
  }
2401
2504
  };
2402
- //#endregion
2403
- //#region src/client/handler/subscription_response.ts
2505
+ // src/client/handler/subscription_response.ts
2404
2506
  /**
2405
2507
  * Copyright 2026 The MOQtail Authors
2406
2508
  *
@@ -2432,18 +2534,17 @@ function applySubscriptionResponse(client, request, parameters, trackProperties)
2432
2534
  const expires = parameters.find(require_model.MessageParameter.isExpires);
2433
2535
  if (expires) request.expires = expires.expires;
2434
2536
  if (trackProperties.length > 0) {
2435
- require_logger.logger.debug("handler/subscription_response", `requestId=${request.requestId} — applying ${trackProperties.length} track propert(ies)`);
2537
+ require_emitter.logger.debug("handler/subscription_response", `requestId=${request.requestId} — applying ${trackProperties.length} track propert(ies)`);
2436
2538
  const track = client.trackSources.get(request.fullTrackName.toString());
2437
2539
  if (track !== void 0) track.trackProperties = trackProperties;
2438
2540
  }
2439
2541
  }
2440
- //#endregion
2441
- //#region src/client/handler/request_ok.ts
2542
+ // src/client/handler/request_ok.ts
2442
2543
  const handlerRequestOk = async (client, msg, _stream, requestId) => {
2443
- require_logger.logger.log("handler/request_ok", "received RequestOk for requestId:", requestId);
2544
+ require_emitter.logger.log("handler/request_ok", "received RequestOk for requestId:", requestId);
2444
2545
  const request = client.requests.get(requestId);
2445
2546
  if (!request) {
2446
- require_logger.logger.warn("handler/request_ok", `Received RequestOk for unknown or already-resolved request id: ${requestId}`);
2547
+ require_emitter.logger.warn("handler/request_ok", `Received RequestOk for unknown or already-resolved request id: ${requestId}`);
2447
2548
  return;
2448
2549
  }
2449
2550
  msg.validateTrackProperties(request instanceof TrackStatusRequest);
@@ -2451,12 +2552,12 @@ const handlerRequestOk = async (client, msg, _stream, requestId) => {
2451
2552
  request.resolve(msg);
2452
2553
  const fullTrackName = client.requestIdMap.getNameByRequestId(requestId);
2453
2554
  if (!fullTrackName) {
2454
- require_logger.logger.warn("handler/request_ok", `No track mapped for PublishRequest requestId: ${requestId}`);
2555
+ require_emitter.logger.warn("handler/request_ok", `No track mapped for PublishRequest requestId: ${requestId}`);
2455
2556
  return;
2456
2557
  }
2457
2558
  const track = client.trackSources.get(fullTrackName.toString());
2458
2559
  if (!track || !track.trackSource.live) {
2459
- require_logger.logger.warn("handler/request_ok", `Live track source not found for ${fullTrackName.toString()}`);
2560
+ require_emitter.logger.warn("handler/request_ok", `Live track source not found for ${fullTrackName.toString()}`);
2460
2561
  return;
2461
2562
  }
2462
2563
  client.publications.set(requestId, new PublishPublication(client, track, request.message));
@@ -2471,33 +2572,46 @@ const handlerRequestOk = async (client, msg, _stream, requestId) => {
2471
2572
  client.requests.delete(requestId);
2472
2573
  } else throw new require_model.ProtocolViolationError("handlerRequestOk", `Request ID ${requestId} matched a pending request, but it does not expect a RequestOk response.`);
2473
2574
  };
2474
- //#endregion
2475
- //#region src/client/handler/request_error.ts
2575
+ // src/client/handler/request_error.ts
2476
2576
  const handlerRequestError = async (client, msg, _stream, requestId) => {
2477
- require_logger.logger.error("handler/request_error", `received requestId=${requestId} code=${msg.errorCode} reason="${msg.reasonPhrase.phrase}"`);
2577
+ require_emitter.logger.error("handler/request_error", `received requestId=${requestId} code=${msg.errorCode} reason="${msg.reasonPhrase.phrase}"`);
2478
2578
  const request = client.requests.get(requestId);
2479
2579
  if (!request) {
2480
- require_logger.logger.warn("handler/request_error", `requestId=${requestId} — no pending request found (already resolved or unknown)`);
2580
+ require_emitter.logger.warn("handler/request_error", `requestId=${requestId} — no pending request found (already resolved or unknown)`);
2481
2581
  return;
2482
2582
  }
2483
- require_logger.logger.debug("handler/request_error", `requestId=${requestId} — resolving ${request.constructor.name} with error`);
2583
+ require_emitter.logger.debug("handler/request_error", `requestId=${requestId} — resolving ${request.constructor.name} with error`);
2484
2584
  if (request instanceof SubscribeRequest || request instanceof PublishRequest || request instanceof PublishNamespaceRequest || request instanceof SubscribeNamespaceRequest || request instanceof TrackStatusRequest || request instanceof FetchRequest) {
2485
2585
  request.resolve(msg);
2486
2586
  client.requests.delete(requestId);
2487
2587
  }
2488
2588
  };
2489
- //#endregion
2490
- //#region src/client/handler/publish_done.ts
2589
+ // src/client/handler/publish_done.ts
2590
+ /**
2591
+ * Copyright 2025 The MOQtail Authors
2592
+ *
2593
+ * Licensed under the Apache License, Version 2.0 (the "License");
2594
+ * you may not use this file except in compliance with the License.
2595
+ * You may obtain a copy of the License at
2596
+ *
2597
+ * http://www.apache.org/licenses/LICENSE-2.0
2598
+ *
2599
+ * Unless required by applicable law or agreed to in writing, software
2600
+ * distributed under the License is distributed on an "AS IS" BASIS,
2601
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2602
+ * See the License for the specific language governing permissions and
2603
+ * limitations under the License.
2604
+ */
2491
2605
  const handlerPublishDone = async (client, msg, _stream, openingRequestId) => {
2492
- if (client.onPeerPublishDone) client.onPeerPublishDone(msg, openingRequestId);
2606
+ client.emit("peerpublishdone", msg, openingRequestId);
2493
2607
  const request = client.requests.get(openingRequestId);
2494
2608
  if (request instanceof SubscribeRequest) {
2495
2609
  request.expectedStreams = msg.streamCount;
2610
+ request.publishDone = msg;
2496
2611
  client.completeSubscription(request);
2497
2612
  }
2498
2613
  };
2499
- //#endregion
2500
- //#region src/client/handler/subscribe_ok.ts
2614
+ // src/client/handler/subscribe_ok.ts
2501
2615
  /**
2502
2616
  * Copyright 2025 The MOQtail Authors
2503
2617
  *
@@ -2514,19 +2628,18 @@ const handlerPublishDone = async (client, msg, _stream, openingRequestId) => {
2514
2628
  * limitations under the License.
2515
2629
  */
2516
2630
  const handlerSubscribeOk = async (client, msg, _stream, requestId) => {
2517
- require_logger.logger.debug("handler/subscribe_ok", `received requestId=${requestId} trackAlias=${msg.trackAlias}`);
2631
+ require_emitter.logger.debug("handler/subscribe_ok", `received requestId=${requestId} trackAlias=${msg.trackAlias}`);
2518
2632
  const request = client.requests.get(requestId);
2519
2633
  if (request instanceof SubscribeRequest) {
2520
2634
  applySubscriptionResponse(client, request, msg.parameters, msg.trackProperties);
2521
- require_logger.logger.debug("handler/subscribe_ok", `requestId=${requestId} — resolving SubscribeRequest ftn="${request.fullTrackName}"`);
2635
+ require_emitter.logger.debug("handler/subscribe_ok", `requestId=${requestId} — resolving SubscribeRequest ftn="${request.fullTrackName}"`);
2522
2636
  request.resolve(msg);
2523
2637
  } else {
2524
- require_logger.logger.error("handler/subscribe_ok", `requestId=${requestId} — no pending SubscribeRequest found (got ${request?.constructor.name ?? "undefined"})`);
2638
+ require_emitter.logger.error("handler/subscribe_ok", `requestId=${requestId} — no pending SubscribeRequest found (got ${request?.constructor.name ?? "undefined"})`);
2525
2639
  throw new require_model.ProtocolViolationError("handlerSubscribeOk", "SUBSCRIBE_OK on a stream with no pending subscribe request");
2526
2640
  }
2527
2641
  };
2528
- //#endregion
2529
- //#region src/client/handler/request_update.ts
2642
+ // src/client/handler/request_update.ts
2530
2643
  /**
2531
2644
  * Copyright 2025 The MOQtail Authors
2532
2645
  *
@@ -2549,7 +2662,7 @@ const handlerSubscribeOk = async (client, msg, _stream, requestId) => {
2549
2662
  * arriving anywhere else, a TRACK_STATUS among them, closes the session.
2550
2663
  */
2551
2664
  const handlerRequestUpdate = async (client, msg, stream, requestId) => {
2552
- require_logger.logger.log("handler/request_update", "requestId", requestId);
2665
+ require_emitter.logger.log("handler/request_update", "requestId", requestId);
2553
2666
  if (!isExpectedUpdate(stream)) {
2554
2667
  await client.disconnect(new require_model.ProtocolViolationError("handler/request_update", `Unexpected REQUEST_UPDATE on a ${stream.first ? "locally" : "peer"} opened ${describe(stream.openingType)} stream`));
2555
2668
  return;
@@ -2557,7 +2670,7 @@ const handlerRequestUpdate = async (client, msg, stream, requestId) => {
2557
2670
  const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
2558
2671
  if (filterRejection) {
2559
2672
  const reason = filterRejection.reasonPhrase.phrase;
2560
- require_logger.logger.warn("handler/request_update", `requestId=${requestId} has filters this client cannot take: ${reason}`);
2673
+ require_emitter.logger.warn("handler/request_update", `requestId=${requestId} has filters this client cannot take: ${reason}`);
2561
2674
  await failUpdate(client, stream, requestId, 54, reason);
2562
2675
  return;
2563
2676
  }
@@ -2567,14 +2680,14 @@ const handlerRequestUpdate = async (client, msg, stream, requestId) => {
2567
2680
  publication.update(msg);
2568
2681
  } catch (error) {
2569
2682
  const invalid = error instanceof require_model.InvalidFilterError;
2570
- require_logger.logger.error("handler/request_update", `update failed for requestId=${requestId}`, error);
2683
+ require_emitter.logger.error("handler/request_update", `update failed for requestId=${requestId}`, error);
2571
2684
  await failUpdate(client, stream, requestId, invalid ? 54 : 0, invalid ? error.details : "REQUEST_UPDATE failed");
2572
2685
  return;
2573
2686
  }
2574
2687
  await stream.send(new require_model.RequestOk());
2575
2688
  return;
2576
2689
  }
2577
- require_logger.logger.warn("handler/request_update", `no updatable request for requestId=${requestId}`);
2690
+ require_emitter.logger.warn("handler/request_update", `no updatable request for requestId=${requestId}`);
2578
2691
  await failUpdate(client, stream, requestId, 3, "REQUEST_UPDATE cannot be applied");
2579
2692
  };
2580
2693
  /**
@@ -2616,13 +2729,10 @@ async function failUpdate(client, stream, requestId, errorCode, reason) {
2616
2729
  break;
2617
2730
  case 6:
2618
2731
  case 80:
2619
- case 81:
2620
- await stream.close();
2621
- break;
2732
+ case 81: await stream.close();
2622
2733
  }
2623
2734
  }
2624
- //#endregion
2625
- //#region src/client/handler/track_status.ts
2735
+ // src/client/handler/track_status.ts
2626
2736
  /**
2627
2737
  * Copyright 2025 The MOQtail Authors
2628
2738
  *
@@ -2639,11 +2749,10 @@ async function failUpdate(client, stream, requestId, errorCode, reason) {
2639
2749
  * limitations under the License.
2640
2750
  */
2641
2751
  const handlerTrackStatus = async (_client, msg, stream) => {
2642
- require_logger.logger.debug("handler/track_status", `requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2752
+ require_emitter.logger.debug("handler/track_status", `requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2643
2753
  await stream.send(new require_model.RequestOk());
2644
2754
  };
2645
- //#endregion
2646
- //#region src/client/handler/handler.ts
2755
+ // src/client/handler/handler.ts
2647
2756
  /**
2648
2757
  * Copyright 2025 The MOQtail Authors
2649
2758
  *
@@ -2661,7 +2770,7 @@ const handlerTrackStatus = async (_client, msg, stream) => {
2661
2770
  */
2662
2771
  /**
2663
2772
  * The control stream carries SETUP and GOAWAY, nothing else. SETUP is
2664
- * consumed by the handshake in {@link MOQtailClient.new}, so GOAWAY is all that reaches
2773
+ * consumed by the handshake in {@link MOQtailClient.init}, so GOAWAY is all that reaches
2665
2774
  * the read loop. Every request type has moved to its own bidi stream — see
2666
2775
  * {@link getHandlerForRequestStreamMessage}.
2667
2776
  */
@@ -2690,8 +2799,7 @@ function getHandlerForRequestStreamMessage(msg) {
2690
2799
  if (msg instanceof require_model.PublishDone) return handlerPublishDone;
2691
2800
  if (msg instanceof require_model.PublishSkipped) return handlerPublishSkipped;
2692
2801
  }
2693
- //#endregion
2694
- //#region src/client/util/random_id.ts
2802
+ // src/client/util/random_id.ts
2695
2803
  /**
2696
2804
  * Copyright 2025 The MOQtail Authors
2697
2805
  *
@@ -2715,53 +2823,37 @@ function random60bitId() {
2715
2823
  for (const b of buf) id = id << 8n | BigInt(b);
2716
2824
  return id;
2717
2825
  }
2718
- //#endregion
2719
- //#region src/client/datagram_stream.ts
2720
- /**
2721
- * Copyright 2025 The MOQtail Authors
2722
- *
2723
- * Licensed under the Apache License, Version 2.0 (the "License");
2724
- * you may not use this file except in compliance with the License.
2725
- * You may obtain a copy of the License at
2726
- *
2727
- * http://www.apache.org/licenses/LICENSE-2.0
2728
- *
2729
- * Unless required by applicable law or agreed to in writing, software
2730
- * distributed under the License is distributed on an "AS IS" BASIS,
2731
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2732
- * See the License for the specific language governing permissions and
2733
- * limitations under the License.
2734
- */
2826
+ // src/client/datagram_stream.ts
2735
2827
  /**
2736
2828
  * Sends MoqtObjects as WebTransport datagrams.
2737
2829
  * Parallel to SendStream but for datagram-based delivery.
2738
2830
  *
2739
2831
  * @example
2740
2832
  * ```ts
2741
- * const sender = new SendDatagramStream(client.webTransport.datagrams.writable, trackAlias);
2833
+ * const sender = await SendDatagramStream.new(client.webTransport.datagrams.writable, trackAlias);
2742
2834
  * await sender.write(moqtObject);
2743
2835
  * ```
2744
2836
  */
2745
2837
  var SendDatagramStream = class SendDatagramStream {
2746
2838
  #writer;
2747
2839
  #trackAlias;
2748
- onDataSent;
2749
- constructor(writer, trackAlias, onDataSent) {
2840
+ #events;
2841
+ constructor(writer, trackAlias, events) {
2750
2842
  this.#writer = writer;
2751
2843
  this.#trackAlias = trackAlias;
2752
- if (onDataSent) this.onDataSent = onDataSent;
2844
+ this.#events = events;
2753
2845
  }
2754
2846
  /**
2755
2847
  * Create a new datagram sender for a specific track.
2756
2848
  *
2757
2849
  * @param writeStream - WebTransport datagram writable stream
2758
2850
  * @param trackAlias - Track alias for this datagram stream
2759
- * @param onDataSent - Optional callback fired when datagram is sent
2851
+ * @param events - Receives `datagramsent` for each datagram written
2760
2852
  * @returns SendDatagramStream instance
2761
2853
  */
2762
- static async new(writeStream, trackAlias, onDataSent) {
2854
+ static async new(writeStream, trackAlias, events) {
2763
2855
  const writer = writeStream.getWriter();
2764
- return new SendDatagramStream(writer, trackAlias, onDataSent);
2856
+ return new SendDatagramStream(writer, trackAlias, events);
2765
2857
  }
2766
2858
  /**
2767
2859
  * Create a datagram sender using an existing shared writer.
@@ -2769,11 +2861,11 @@ var SendDatagramStream = class SendDatagramStream {
2769
2861
  *
2770
2862
  * @param writer - Existing WritableStreamDefaultWriter
2771
2863
  * @param trackAlias - Track alias for this datagram stream
2772
- * @param onDataSent - Optional callback fired when datagram is sent
2864
+ * @param events - Receives `datagramsent` for each datagram written
2773
2865
  * @returns SendDatagramStream instance
2774
2866
  */
2775
- static fromWriter(writer, trackAlias, onDataSent) {
2776
- return new SendDatagramStream(writer, trackAlias, onDataSent);
2867
+ static fromWriter(writer, trackAlias, events) {
2868
+ return new SendDatagramStream(writer, trackAlias, events);
2777
2869
  }
2778
2870
  /**
2779
2871
  * Write a MoqtObject as a datagram.
@@ -2784,13 +2876,13 @@ var SendDatagramStream = class SendDatagramStream {
2784
2876
  async write(object) {
2785
2877
  const datagram = object.tryIntoDatagram(this.#trackAlias);
2786
2878
  const serialized = datagram.serialize().toUint8Array();
2787
- require_logger.logger.log("datagram_stream", `Writing datagram: trackAlias=${this.#trackAlias}, group=${object.location?.group}, obj=${object.location?.object}, size=${serialized.byteLength}`);
2788
- if (this.onDataSent) this.onDataSent(datagram);
2879
+ require_emitter.logger.log("datagram_stream", `Writing datagram: trackAlias=${this.#trackAlias}, group=${object.location?.group}, obj=${object.location?.object}, size=${serialized.byteLength}`);
2880
+ this.#events?.emit("datagramsent", datagram);
2789
2881
  try {
2790
2882
  await this.#writer.write(serialized);
2791
- require_logger.logger.log("datagram_stream", `Successfully wrote ${serialized.byteLength} bytes to WebTransport datagram`);
2883
+ require_emitter.logger.log("datagram_stream", `Successfully wrote ${serialized.byteLength} bytes to WebTransport datagram`);
2792
2884
  } catch (err) {
2793
- require_logger.logger.error("datagram_stream", `ERROR writing datagram:`, err);
2885
+ require_emitter.logger.error("datagram_stream", `ERROR writing datagram:`, err);
2794
2886
  throw err;
2795
2887
  }
2796
2888
  }
@@ -2807,91 +2899,160 @@ var SendDatagramStream = class SendDatagramStream {
2807
2899
  this.#writer.releaseLock();
2808
2900
  }
2809
2901
  };
2902
+ // src/client/ordering.ts
2903
+ /** IDs before this object in its group that don't exist (moqt-22 Prior Object ID Gap). */
2904
+ const objectGap = (object) => require_model.findProperty(object.properties, require_model.PriorObjectIdGapProperty)?.gap ?? 0n;
2905
+ /** Group IDs before this object's group that don't exist (moqt-22 Prior Group ID Gap). */
2906
+ const groupGap = (object) => require_model.findProperty(object.properties, require_model.PriorGroupIdGapProperty)?.gap ?? 0n;
2810
2907
  /**
2811
- * Receives and parses WebTransport datagrams as MoqtObjects.
2812
- * Parallel to RecvStream but for datagram-based delivery.
2813
- *
2814
- * Automatically handles:
2815
- * - Datagram parsing (both payload and status datagrams)
2816
- * - Track alias to full track name resolution
2817
- *
2818
- * @example
2819
- * ```ts
2820
- * const receiver = new RecvDatagramStream(
2821
- * client.webTransport.datagrams.readable,
2822
- * (trackAlias) => client.requestIdMap.getNameByTrackAlias(trackAlias)
2823
- * );
2908
+ * @public
2909
+ * Releases one request's objects in location order, whatever streams or datagrams they
2910
+ * arrived on. An object goes out as soon as its predecessor has; one whose predecessor
2911
+ * is missing waits until the window is exceeded, then everything up to the oldest held
2912
+ * object goes out and the expected locations skipped are reported through `gap`.
2824
2913
  *
2825
- * for await (const object of receiver.stream) {
2826
- * console.log('Received:', object);
2827
- * }
2828
- * ```
2914
+ * Nothing is released yet, so the first object goes out at once only when it starts a
2915
+ * group: a mid-group first object waits for the start of its group, which a fill fetch
2916
+ * stream may still bring.
2829
2917
  */
2830
- var RecvDatagramStream = class RecvDatagramStream {
2831
- stream;
2832
- #reader;
2833
- #trackAliasResolver;
2834
- onDataReceived;
2835
- constructor(reader, trackAliasResolver, onDataReceived) {
2836
- this.#reader = reader;
2837
- this.#trackAliasResolver = trackAliasResolver;
2838
- if (onDataReceived) this.onDataReceived = onDataReceived;
2839
- this.stream = new ReadableStream({
2840
- start: (controller) => this.#ingestLoop(controller),
2841
- cancel: () => this.#reader.cancel()
2842
- });
2843
- }
2844
- /**
2845
- * Create a new datagram receiver.
2846
- *
2847
- * @param readStream - WebTransport datagram readable stream
2848
- * @param trackAliasResolver - Function to resolve track alias to full track name
2849
- * @param onDataReceived - Optional callback fired when datagram is received
2850
- * @returns RecvDatagramStream instance
2851
- */
2852
- static async new(readStream, trackAliasResolver, onDataReceived) {
2853
- const reader = readStream.getReader();
2854
- return new RecvDatagramStream(reader, trackAliasResolver, onDataReceived);
2855
- }
2856
- async #ingestLoop(controller) {
2857
- try {
2858
- while (true) {
2859
- const { done, value: datagramBytes } = await this.#reader.read();
2860
- if (done) {
2861
- controller.close();
2862
- break;
2863
- }
2864
- if (!datagramBytes || datagramBytes.length === 0) continue;
2865
- try {
2866
- const datagram = require_model.Datagram.deserialize(new require_model.FrozenByteBuffer(datagramBytes));
2867
- if (this.onDataReceived) this.onDataReceived(datagram);
2868
- const fullTrackName = this.#trackAliasResolver(datagram.trackAlias);
2869
- const moqtObject = require_model.MoqtObject.fromDatagram(datagram, fullTrackName);
2870
- controller.enqueue(moqtObject);
2871
- } catch (error) {
2872
- require_logger.logger.warn("datagram_stream", "Failed to parse datagram:", error);
2873
- continue;
2874
- }
2918
+ var ObjectOrderer = class {
2919
+ #ordering;
2920
+ #onRelease;
2921
+ #onGap;
2922
+ #suspended = /* @__PURE__ */ new Set();
2923
+ #held = [];
2924
+ /** The location of the last object released in order. */
2925
+ #released;
2926
+ /** The last Object ID of each group known to be complete. */
2927
+ #ends = /* @__PURE__ */ new Map();
2928
+ #timer;
2929
+ #arrivals = 0;
2930
+ constructor(ordering, onRelease, onGap) {
2931
+ this.#ordering = ordering;
2932
+ this.#onRelease = onRelease;
2933
+ this.#onGap = onGap;
2934
+ }
2935
+ /** Takes an object; `previous` is the object before it on the same fetch stream. */
2936
+ push(object, previous) {
2937
+ if (this.#released && object.location.compare(this.#released) <= 0) {
2938
+ if (this.#ordering.onWindowExceeded !== "drop") this.#onRelease(object);
2939
+ return;
2940
+ }
2941
+ const index = this.#held.findIndex((held) => held.object.location.compare(object.location) >= 0);
2942
+ if (index >= 0 && this.#held[index].object.location.equals(object.location)) return;
2943
+ const entry = {
2944
+ object,
2945
+ previous,
2946
+ at: performance.now(),
2947
+ seq: this.#arrivals++
2948
+ };
2949
+ if (index < 0) this.#held.push(entry);
2950
+ else this.#held.splice(index, 0, entry);
2951
+ this.#drain();
2952
+ this.#expire();
2953
+ }
2954
+ /** While suspended for any reason nothing exceeds the window, so held objects wait for what's missing. */
2955
+ suspendWindow(reason) {
2956
+ if (this.#suspended.has(reason)) return;
2957
+ this.#suspended.add(reason);
2958
+ this.#expire();
2959
+ }
2960
+ /** Resuming the last reason releases at once what waited longer than the window. */
2961
+ resumeWindow(reason) {
2962
+ if (!this.#suspended.delete(reason)) return;
2963
+ this.#expire();
2964
+ }
2965
+ /** A stream carrying the End of Group for `group` ended cleanly with `lastObject`. */
2966
+ endGroup(group, lastObject) {
2967
+ this.#ends.set(group, lastObject);
2968
+ this.#drain();
2969
+ this.#schedule();
2970
+ }
2971
+ /** Releases everything held, in order, and stops the timer. Call before closing the stream. */
2972
+ flush() {
2973
+ this.#clearTimer();
2974
+ while (this.#held.length > 0) this.#force(this.#held.shift());
2975
+ }
2976
+ #drain() {
2977
+ while (this.#held.length > 0 && this.#isNext(this.#held[0])) this.#release(this.#held.shift().object);
2978
+ }
2979
+ #expire() {
2980
+ while (this.#exceeded()) {
2981
+ const oldest = this.#oldest().object.location;
2982
+ while (this.#held[0] && this.#held[0].object.location.compare(oldest) <= 0) this.#force(this.#held.shift());
2983
+ this.#drain();
2984
+ }
2985
+ this.#schedule();
2986
+ }
2987
+ #exceeded() {
2988
+ if (this.#suspended.size > 0 || this.#held.length === 0) return false;
2989
+ const { durationMs, objects } = this.#ordering.window;
2990
+ if (objects !== void 0 && this.#held.length > objects) return true;
2991
+ return durationMs !== void 0 && performance.now() - this.#oldest().at >= durationMs;
2992
+ }
2993
+ #oldest() {
2994
+ return this.#held.reduce((oldest, held) => held.seq < oldest.seq ? held : oldest);
2995
+ }
2996
+ /** One timer, armed only while objects are held, for when the oldest one exceeds the window. */
2997
+ #schedule() {
2998
+ this.#clearTimer();
2999
+ const { durationMs } = this.#ordering.window;
3000
+ if (this.#suspended.size > 0 || durationMs === void 0 || this.#held.length === 0) return;
3001
+ const wait = this.#oldest().at + durationMs - performance.now();
3002
+ this.#timer = setTimeout(() => {
3003
+ try {
3004
+ this.#expire();
3005
+ } catch (error) {
3006
+ require_emitter.logger.debug("ordering", "release after the stream closed", error);
3007
+ this.#held = [];
2875
3008
  }
2876
- } catch (error) {
2877
- controller.error(error);
3009
+ }, Math.max(0, wait));
3010
+ }
3011
+ #clearTimer() {
3012
+ clearTimeout(this.#timer);
3013
+ this.#timer = void 0;
3014
+ }
3015
+ #isNext({ object, previous }) {
3016
+ const last = this.#released;
3017
+ const { group, object: id } = object.location;
3018
+ const sparseObjects = this.#ordering.sparseObjectIds === true;
3019
+ const startsGroup = sparseObjects || id === objectGap(object);
3020
+ if (!last) return startsGroup;
3021
+ if (previous?.equals(last)) return true;
3022
+ if (group === last.group) return sparseObjects || id - 1n - objectGap(object) <= last.object;
3023
+ const followsGroup = this.#ordering.sparseGroupIds === true || group - 1n - groupGap(object) <= last.group;
3024
+ return startsGroup && followsGroup && this.#ends.get(last.group) === last.object;
3025
+ }
3026
+ /** Releases `held` out of turn, reporting the expected locations it skips. */
3027
+ #force(held) {
3028
+ const from = this.#skippedFrom(held);
3029
+ if (from) this.#onGap(from, held.object.location);
3030
+ this.#release(held.object);
3031
+ }
3032
+ /**
3033
+ * The first expected location skipped between the release point and `held`, if any.
3034
+ * A group's missing tail isn't counted: its last ID is unknown.
3035
+ */
3036
+ #skippedFrom({ object, previous }) {
3037
+ const last = this.#released;
3038
+ if (!last || previous?.equals(last)) return void 0;
3039
+ const { group, object: id } = object.location;
3040
+ const sparseObjects = this.#ordering.sparseObjectIds === true;
3041
+ if (group === last.group) return !sparseObjects && id - 1n - objectGap(object) > last.object ? new require_model.Location(group, last.object + 1n) : void 0;
3042
+ if (this.#ordering.sparseGroupIds !== true && group - 1n - groupGap(object) > last.group) return new require_model.Location(last.group + 1n, 0n);
3043
+ return !sparseObjects && id > objectGap(object) ? new require_model.Location(group, 0n) : void 0;
3044
+ }
3045
+ #release(object) {
3046
+ const { group, object: id } = object.location;
3047
+ if (this.#released?.group !== group) {
3048
+ for (const known of this.#ends.keys()) if (known < group) this.#ends.delete(known);
2878
3049
  }
2879
- }
2880
- /**
2881
- * Cancel the datagram reader.
2882
- */
2883
- async cancel() {
2884
- await this.#reader.cancel();
2885
- }
2886
- /**
2887
- * Release the reader lock without canceling.
2888
- */
2889
- releaseLock() {
2890
- this.#reader.releaseLock();
3050
+ this.#released = object.location;
3051
+ if (object.isEndOfGroup()) this.#ends.set(group, id);
3052
+ this.#onRelease(object);
2891
3053
  }
2892
3054
  };
2893
- //#endregion
2894
- //#region src/client/client.ts
3055
+ // src/client/client.ts
2895
3056
  /**
2896
3057
  * Copyright 2025 The MOQtail Authors
2897
3058
  *
@@ -2911,17 +3072,17 @@ var RecvDatagramStream = class RecvDatagramStream {
2911
3072
  * @public
2912
3073
  * Represents a Media Over QUIC Transport (MOQT) client session.
2913
3074
  *
2914
- * Use {@link MOQtailClient.new} to establish a connection and perform MOQT operations such as subscribing to tracks,
2915
- * fetching historical data, announcing tracks for publication, and managing session lifecycle.
2916
- *
2917
- * Once initialized, the client provides high-level methods for MOQT requests and publishing. If a protocol violation
2918
- * occurs, the client will terminate and must be re-initialized.
3075
+ * Construct it, attach listeners with `on()`, then call {@link MOQtailClient.init} to open the
3076
+ * session. Once initialized, the client provides high-level methods for MOQT requests and publishing. If a protocol
3077
+ * violation occurs, the client terminates; a new client is needed to reconnect.
2919
3078
  *
2920
3079
  * ## Usage
2921
3080
  *
2922
3081
  * ### Connect and Subscribe to a Track
2923
3082
  * ```ts
2924
- * const client = await MOQtailClient.new({ url });
3083
+ * const client = new MOQtailClient({ url });
3084
+ * client.on('sessionterminated', (reason) => console.warn('Session ended:', reason));
3085
+ * await client.init();
2925
3086
  * const result = await client.subscribe({
2926
3087
  * fullTrackName,
2927
3088
  * locationFilter: new LocationFilter(LocationFilterType.NextObject),
@@ -2938,7 +3099,8 @@ var RecvDatagramStream = class RecvDatagramStream {
2938
3099
  *
2939
3100
  * ### Publish a namespace for Publishing
2940
3101
  * ```ts
2941
- * const client = await MOQtailClient.new({ url });
3102
+ * const client = new MOQtailClient({ url });
3103
+ * await client.init();
2942
3104
  * const publishNamespaceResult = await client.publishNamespace(["camera", "main"]);
2943
3105
  * if (!(publishNamespaceResult instanceof RequestError)) {
2944
3106
  * // Ready to publish objects under this namespace
@@ -2950,7 +3112,7 @@ var RecvDatagramStream = class RecvDatagramStream {
2950
3112
  * await client.disconnect();
2951
3113
  * ```
2952
3114
  */
2953
- var MOQtailClient = class MOQtailClient {
3115
+ var MOQtailClient = class extends require_emitter.Emitter {
2954
3116
  /**
2955
3117
  * Namespace prefixes (tuples) the peer has requested announce notifications for via SUBSCRIBE_NAMESPACE.
2956
3118
  * Used to decide which locally issued ANNOUNCE messages should be forwarded (future optimization: prefix trie).
@@ -3018,10 +3180,12 @@ var MOQtailClient = class MOQtailClient {
3018
3180
  * stream to close.
3019
3181
  */
3020
3182
  #namespaceRequestIds = /* @__PURE__ */ new Map();
3021
- /** Underlying WebTransport session (set after successful construction in MOQtailClient.new). */
3183
+ /** Underlying WebTransport session (set by {@link MOQtailClient.init}). */
3022
3184
  webTransport;
3023
3185
  /** Validated Setup message the server sent back during handshake (protocol parameters negotiated). */
3024
3186
  #serverSetup;
3187
+ /** Setup message this client sent during handshake. */
3188
+ #clientSetup;
3025
3189
  /** How many filter ranges this client allows the server per request, as advertised in SETUP. */
3026
3190
  #maxFilterRanges = 0n;
3027
3191
  /** Outgoing / incoming control message stream pair. */
@@ -3042,6 +3206,8 @@ var MOQtailClient = class MOQtailClient {
3042
3206
  * retired anyway, if no PUBLISH_DONE ends its drain first.
3043
3207
  */
3044
3208
  switchDrainTimeoutMs = DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
3209
+ /** How long (ms) after SUBSCRIBE_OK a fill fetch stream may take to open before ordering stops waiting for it. */
3210
+ fillOpenTimeoutMs = DEFAULT_FILL_OPEN_TIMEOUT_MS;
3045
3211
  /**
3046
3212
  * Callbacks waiting for a track alias to be registered, keyed by alias. Each entry
3047
3213
  * belongs to a data stream that arrived before the control message naming its alias.
@@ -3049,129 +3215,19 @@ var MOQtailClient = class MOQtailClient {
3049
3215
  #aliasWaiters = /* @__PURE__ */ new Map();
3050
3216
  /** Flag indicating the client has been disconnected/destroyed and cannot accept further API calls. */
3051
3217
  #isDestroyed = false;
3218
+ /** Where {@link MOQtailClient.init} is: it runs once, and only a `ready` client takes requests. */
3219
+ #state = "idle";
3220
+ #options;
3052
3221
  /** Internal monotonically increasing client-assigned request id counter (even/odd parity scheme advances by 2). */
3053
3222
  #dontUseRequestId = 0n;
3054
3223
  /** Active early discard policy; undefined means no per-stream deadline is applied. */
3055
3224
  #earlyDiscardPolicy;
3056
3225
  /**
3057
- * TODO: onNamespaceAnnounced may be a better name
3058
- * Fired when an PUBLISH_NAMESPACE control message is processed for a track namespace.
3059
- * Use to update UI or trigger discovery logic.
3060
- * Discovery event.
3061
- */
3062
- onNamespacePublished;
3063
- /**
3064
- * Fired on GOAWAY reception signaling graceful session wind-down.
3065
- * Use to prepare for disconnect or cleanup.
3066
- * Lifecycle handler.
3067
- */
3068
- onGoaway;
3069
- /**
3070
3226
  * Whether the peer has sent a GOAWAY on the control stream. Once it has, this side
3071
3227
  * should not start new requests; a second one closes the session with
3072
3228
  * PROTOCOL_VIOLATION.
3073
3229
  */
3074
3230
  goawayReceived = false;
3075
- /**
3076
- * Fired if the underlying WebTransport session fails (ready -\> closed prematurely).
3077
- * Use to log or alert on transport errors.
3078
- * Lifecycle/error handler.
3079
- */
3080
- onWebTransportFail;
3081
- /**
3082
- * Fired exactly once when the client transitions to terminated (disconnect).
3083
- * Use to clean up resources or notify user.
3084
- * Lifecycle handler.
3085
- */
3086
- onSessionTerminated;
3087
- /**
3088
- * Invoked after each outbound control message is sent.
3089
- * Use for logging or analytics.
3090
- * Informational event.
3091
- */
3092
- onMessageSent;
3093
- /**
3094
- * Invoked upon receiving each inbound control message before handling.
3095
- * Use for logging or debugging.
3096
- * Informational event.
3097
- */
3098
- onMessageReceived;
3099
- /**
3100
- * Invoked for each decoded data object/header arriving on a uni stream (fetch or subgroup).
3101
- * Use to process or display incoming media/data.
3102
- * Informational event.
3103
- */
3104
- onDataReceived;
3105
- /**
3106
- * Invoked after enqueuing each outbound data object/header.
3107
- * Reserved for future use.
3108
- * Informational event.
3109
- */
3110
- onDataSent;
3111
- /**
3112
- * Invoked for every data stream this client opens or accepts: once for its header, once
3113
- * per object (identity and payload length only), and once when the stream ends.
3114
- * Use for counters and diagnostics.
3115
- * Informational event.
3116
- */
3117
- onDataEvent;
3118
- /**
3119
- * General-purpose error callback for surfaced exceptions not thrown to caller synchronously.
3120
- * Use to log or display errors.
3121
- * Error handler.
3122
- */
3123
- onError;
3124
- /** Invoked for each decoded datagram object/status arriving. */
3125
- onDatagramReceived;
3126
- /** Invoked after enqueuing each outbound datagram object/status. */
3127
- onDatagramSent;
3128
- /** Fired when an inbound PUBLISH control message is received. */
3129
- onPeerPublish;
3130
- /**
3131
- * Fired when an inbound PUBLISH_DONE control message is received. The message names
3132
- * no request of its own, so `requestId` is the request the stream it arrived on
3133
- * opened: for a track the peer pushed, the `requestId` of the {@link Publish} handed
3134
- * to {@link MOQtailClient.onPeerPublish}. It is what says which track just ended.
3135
- */
3136
- onPeerPublishDone;
3137
- /**
3138
- * Fired when the peer moves the Forward State of a track this side is publishing,
3139
- * either in its PUBLISH_OK or in a later REQUEST_UPDATE. `requestId` is the one
3140
- * {@link MOQtailClient.publish} returned.
3141
- *
3142
- * A publication that declared FORWARD=0 sends nothing until this reports `true`, so
3143
- * this is where the work behind the track starts and stops -- leaving a camera and
3144
- * an encoder running for a track nobody is taking costs the same as publishing it.
3145
- */
3146
- onForwardStateChange;
3147
- /** Fired when an inbound SUBSCRIBE_NAMESPACE control message is received. */
3148
- onPeerSubscribeNamespace;
3149
- /**
3150
- * Fired when an inbound SUBSCRIBE_TRACKS control message is received. The PUBLISH
3151
- * sent for each matching track:
3152
- * - states the request's settings as its parameters, from
3153
- * `MessageParameter.publishParametersFor(msg.parameters)`: FORWARD, GROUP_ORDER and
3154
- * the LOCATION_FILTER the subscription starts from, but never the request's
3155
- * AUTHORIZATION_TOKEN;
3156
- * - goes without Track Properties when
3157
- * `MessageParameter.includesProperties(msg.parameters)` is false.
3158
- *
3159
- * A request carrying FILL_PARAMETERS also asks for a fill of what each track has
3160
- * already published. This client cannot open a fill for a pushed track, so such a
3161
- * subscriber gets only the live Objects.
3162
- */
3163
- onPeerSubscribeTracks;
3164
- /**
3165
- * Fired when a PUBLISH_SKIPPED arrives on a {@link MOQtailClient.subscribeTracks}
3166
- * stream: the peer has a matching track but no bidi stream to send its PUBLISH on
3167
- * until its stream limit lifts (§10.20). `prefix` is the prefix this side subscribed
3168
- * with, which is what the message's suffix hangs off.
3169
- */
3170
- onPeerPublishSkipped;
3171
- /** Fired when a NAMESPACE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
3172
- onPeerNamespace;
3173
- /** Fired when a NAMESPACE_DONE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
3174
- onPeerNamespaceDone;
3175
3231
  /** Datagram writer for sending datagrams. */
3176
3232
  #datagramWriter;
3177
3233
  /** Datagram reader for receiving datagrams. */
@@ -3214,9 +3270,13 @@ var MOQtailClient = class MOQtailClient {
3214
3270
  return this.#serverSetup;
3215
3271
  }
3216
3272
  /**
3217
- * How many filter ranges the server allows in one request: its MAX_FILTER_RANGES,
3218
- * or 0 when it sent none, which allows no Range Filter at all.
3273
+ * Gets the setup this client sent during handshake.
3274
+ *
3275
+ * @returns The {@link Setup} instance written first on the control stream.
3219
3276
  */
3277
+ get clientSetup() {
3278
+ return this.#clientSetup;
3279
+ }
3220
3280
  /**
3221
3281
  * How many filter ranges this client allows the server in one request: the
3222
3282
  * MAX_FILTER_RANGES it advertised, {@link DEFAULT_MAX_FILTER_RANGES} unless the
@@ -3247,24 +3307,31 @@ var MOQtailClient = class MOQtailClient {
3247
3307
  * @param level - The minimum {@link LogLevel} to output. Use `LogLevel.NONE` to silence all logs.
3248
3308
  */
3249
3309
  static setLogLevel(level) {
3250
- require_logger.setLogLevel(level);
3310
+ require_emitter.setLogLevel(level);
3251
3311
  }
3252
3312
  /**
3253
3313
  * Restricts log output to the specified module names. Pass `null` to allow all modules.
3254
3314
  * @param modules - Array of module name strings, or `null` to enable all modules.
3255
3315
  */
3256
3316
  static setLogEnabledModules(modules) {
3257
- require_logger.setLogEnabledModules(modules);
3317
+ require_emitter.setLogEnabledModules(modules);
3258
3318
  }
3259
3319
  /**
3260
- * Guard that throws if the client has been destroyed (disconnect already called). Used at start of public APIs
3261
- * to fail fast rather than perform partial operations on a torn-down session.
3262
- * @throws MOQtailError when #isDestroyed is true.
3320
+ * Guard that throws unless the client is initialized and not yet destroyed. Used at start of public APIs
3321
+ * to fail fast rather than perform partial operations on a session that is not open.
3322
+ * @throws MOQtailError when the client is destroyed or {@link MOQtailClient.init} has not completed.
3263
3323
  */
3264
3324
  #ensureActive() {
3265
3325
  if (this.#isDestroyed) throw new require_model.MOQtailError("MOQtailClient is destroyed and cannot be used.");
3326
+ if (this.#state !== "ready") throw new require_model.MOQtailError("MOQtailClient is not initialized. Await init() first.");
3266
3327
  }
3267
- constructor() {
3328
+ /**
3329
+ * Stores `options`; nothing happens on the network until {@link MOQtailClient.init}, so
3330
+ * listeners attached in between see everything, the handshake included.
3331
+ */
3332
+ constructor(options) {
3333
+ super();
3334
+ this.#options = options;
3268
3335
  this.receivedDatagramObjects = new ReadableStream({
3269
3336
  start: (controller) => {
3270
3337
  this.#receivedDatagramObjectController = controller;
@@ -3273,95 +3340,73 @@ var MOQtailClient = class MOQtailClient {
3273
3340
  });
3274
3341
  }
3275
3342
  /**
3276
- * Establishes a new {@link MOQtailClient} session over WebTransport and performs the MOQT setup handshake.
3277
- *
3278
- * @param args - {@link MOQtailClientOptions}
3279
- *
3280
- * @returns Promise resolving to a ready {@link MOQtailClient} instance.
3343
+ * Opens the WebTransport session and performs the MOQT setup handshake. Runs once: a
3344
+ * second call throws, and a failed one leaves the client unusable, so a retry needs a
3345
+ * new client.
3281
3346
  *
3347
+ * @throws :{@link MOQtailError} If called more than once, or after {@link MOQtailClient.disconnect}.
3282
3348
  * @throws :{@link ProtocolViolationError} If the server sends an unexpected or invalid message during setup.
3283
3349
  *
3284
- * @example Minimal connection
3285
- * ```ts
3286
- * const client = await MOQtailClient.new({
3287
- * url: 'https://relay.example.com/transport'
3288
- * });
3289
- * ```
3290
- *
3291
- * @example With callbacks and options
3350
+ * @example
3292
3351
  * ```ts
3293
- * const client = await MOQtailClient.new({
3294
- * url,
3295
- * setupOptions: new SetupOptions().addPath('/live'),
3296
- * transportOptions: { congestionControl: 'default' },
3297
- * dataStreamTimeoutMs: 5000,
3298
- * controlStreamTimeoutMs: 2000,
3299
- * trackAliasResolutionTimeoutMs: 2000,
3300
- * enableDatagrams: true,
3301
- * callbacks: {
3302
- * onMessageSent: msg => console.log('Sent:', msg),
3303
- * onMessageReceived: msg => console.log('Received:', msg),
3304
- * onSessionTerminated: reason => console.warn('Session ended:', reason),
3305
- * onDatagramReceived: data => console.log('Datagram:', data),
3306
- * }
3307
- * });
3352
+ * const client = new MOQtailClient({ url: 'https://relay.example.com/transport' })
3353
+ * client.on('messagesent', (msg) => console.log('Sent:', msg))
3354
+ * await client.init()
3308
3355
  * ```
3309
3356
  */
3310
- static async new(args) {
3311
- let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, trackAliasResolutionTimeoutMs, switchDrainTimeoutMs, enableDatagrams, callbacks } = args;
3312
- const client = new MOQtailClient();
3357
+ async init() {
3358
+ if (this.#state !== "idle" || this.#isDestroyed) throw new require_model.MOQtailError("MOQtailClient.init may only run once.");
3359
+ this.#state = "initializing";
3360
+ let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, trackAliasResolutionTimeoutMs, switchDrainTimeoutMs, fillOpenTimeoutMs, enableDatagrams } = this.#options;
3313
3361
  if (!transportOptions) transportOptions = { protocols: [] };
3314
3362
  if (!transportOptions.protocols) transportOptions = {
3315
3363
  ...transportOptions,
3316
3364
  protocols: [...require_model.SUPPORTED_VERSIONS]
3317
3365
  };
3318
3366
  else transportOptions.protocols.push(...require_model.SUPPORTED_VERSIONS);
3319
- require_logger.logger.log("MOQtailClient", "transportOptions", transportOptions);
3320
- const { transportUrl, moqtUrl } = require_model.resolveTransportUrl(url);
3321
- if (moqtUrl) {
3322
- require_logger.logger.log("MOQtailClient", `moqt:// resolved to ${transportUrl}`);
3323
- if (moqtUrl.fragment) require_logger.logger.log("MOQtailClient", `moqt:// fragment (local-only): ${moqtUrl.fragment.kind}:${moqtUrl.fragment.value}`);
3324
- }
3325
- client.webTransport = new WebTransport(transportUrl, transportOptions);
3326
- await client.webTransport.ready;
3367
+ require_emitter.logger.log("MOQtailClient", "transportOptions", transportOptions);
3327
3368
  try {
3328
- if (callbacks?.onMessageSent) client.onMessageSent = callbacks.onMessageSent;
3329
- if (callbacks?.onMessageReceived) client.onMessageReceived = callbacks.onMessageReceived;
3330
- if (callbacks?.onSessionTerminated) client.onSessionTerminated = callbacks.onSessionTerminated;
3331
- if (callbacks?.onDatagramReceived) client.onDatagramReceived = callbacks.onDatagramReceived;
3332
- if (callbacks?.onDatagramSent) client.onDatagramSent = callbacks.onDatagramSent;
3333
- if (callbacks?.onDataEvent) client.onDataEvent = callbacks.onDataEvent;
3334
- if (dataStreamTimeoutMs) client.dataStreamTimeoutMs = dataStreamTimeoutMs;
3335
- if (controlStreamTimeoutMs) client.controlStreamTimeoutMs = controlStreamTimeoutMs;
3336
- if (trackAliasResolutionTimeoutMs !== void 0) client.trackAliasResolutionTimeoutMs = trackAliasResolutionTimeoutMs;
3337
- if (switchDrainTimeoutMs !== void 0) client.switchDrainTimeoutMs = switchDrainTimeoutMs;
3338
- const sendHalf = new ControlSendStream(await client.webTransport.createUnidirectionalStream({ sendOrder: Number.MAX_SAFE_INTEGER }), client.onMessageSent);
3369
+ const { transportUrl, moqtUrl } = require_model.resolveTransportUrl(url);
3370
+ if (moqtUrl) {
3371
+ require_emitter.logger.log("MOQtailClient", `moqt:// resolved to ${transportUrl}`);
3372
+ if (moqtUrl.fragment) require_emitter.logger.log("MOQtailClient", `moqt:// fragment (local-only): ${moqtUrl.fragment.kind}:${moqtUrl.fragment.value}`);
3373
+ }
3374
+ this.webTransport = new WebTransport(transportUrl, transportOptions);
3375
+ await this.webTransport.ready;
3376
+ if (dataStreamTimeoutMs) this.dataStreamTimeoutMs = dataStreamTimeoutMs;
3377
+ if (controlStreamTimeoutMs) this.controlStreamTimeoutMs = controlStreamTimeoutMs;
3378
+ if (trackAliasResolutionTimeoutMs !== void 0) this.trackAliasResolutionTimeoutMs = trackAliasResolutionTimeoutMs;
3379
+ if (switchDrainTimeoutMs !== void 0) this.switchDrainTimeoutMs = switchDrainTimeoutMs;
3380
+ if (fillOpenTimeoutMs !== void 0) this.fillOpenTimeoutMs = fillOpenTimeoutMs;
3381
+ const sendHalf = new ControlSendStream(await this.webTransport.createUnidirectionalStream({ sendOrder: Number.MAX_SAFE_INTEGER }), this);
3339
3382
  const params = setupOptions ? setupOptions.build() : new require_model.SetupOptions().build();
3340
3383
  let maxFilterRanges = params.map((p) => require_model.MaxFilterRanges.fromKeyValuePair(p)).find((o) => o !== void 0);
3341
3384
  if (!maxFilterRanges) {
3342
3385
  maxFilterRanges = new require_model.MaxFilterRanges(DEFAULT_MAX_FILTER_RANGES);
3343
3386
  params.push(maxFilterRanges.toKeyValuePair());
3344
3387
  }
3345
- client.#maxFilterRanges = maxFilterRanges.value;
3388
+ this.#maxFilterRanges = maxFilterRanges.value;
3346
3389
  require_model.assertNoAuthorityOverWebTransport(params);
3347
- await sendHalf.send(new require_model.Setup(params));
3348
- client.#incomingUniStreams = client.webTransport.incomingUnidirectionalStreams.getReader();
3349
- const { value: recvStream, done: recvStreamDone } = await client.#incomingUniStreams.read();
3350
- if (recvStreamDone || !recvStream) throw new require_model.ProtocolViolationError("MOQtailClient.new", "Session closed before the server control stream");
3351
- client.controlStream = new ControlStream(sendHalf, new ControlRecvStream(recvStream, client.controlStreamTimeoutMs, client.onMessageReceived));
3352
- const reader = client.controlStream.stream.getReader();
3390
+ this.#clientSetup = new require_model.Setup(params);
3391
+ await sendHalf.send(this.#clientSetup);
3392
+ this.#incomingUniStreams = this.webTransport.incomingUnidirectionalStreams.getReader();
3393
+ const { value: recvStream, done: recvStreamDone } = await this.#incomingUniStreams.read();
3394
+ if (recvStreamDone || !recvStream) throw new require_model.ProtocolViolationError("MOQtailClient.init", "Session closed before the server control stream");
3395
+ const recvHalf = new ControlRecvStream(recvStream, this.controlStreamTimeoutMs, this);
3396
+ this.controlStream = new ControlStream(sendHalf, recvHalf);
3397
+ const reader = this.controlStream.stream.getReader();
3353
3398
  const { value: response, done } = await reader.read();
3354
- if (done) throw new require_model.ProtocolViolationError("MOQtailClient.new", "Stream closed after client setup");
3355
- if (!(response instanceof require_model.Setup)) throw new require_model.ProtocolViolationError("MOQtailClient.new", "Expected setup as the first control message");
3356
- client.#serverSetup = response;
3399
+ if (done) throw new require_model.ProtocolViolationError("MOQtailClient.init", "Stream closed after client setup");
3400
+ if (!(response instanceof require_model.Setup)) throw new require_model.ProtocolViolationError("MOQtailClient.init", "Expected setup as the first control message");
3401
+ this.#serverSetup = response;
3357
3402
  reader.releaseLock();
3358
- client.#handleIncomingControlMessages();
3359
- client.#acceptIncomingUniStreams();
3360
- client.#acceptIncomingBiStreams();
3361
- if (enableDatagrams) await client.startDatagrams();
3362
- return client;
3403
+ this.#state = "ready";
3404
+ this.#handleIncomingControlMessages();
3405
+ this.#acceptIncomingUniStreams();
3406
+ this.#acceptIncomingBiStreams();
3407
+ if (enableDatagrams) await this.startDatagrams();
3363
3408
  } catch (error) {
3364
- await client.disconnect(new require_model.InternalError("MOQtailClient.new", error instanceof Error ? error.message : String(error)));
3409
+ await this.disconnect(new require_model.InternalError("MOQtailClient.init", errorMessage(error)));
3365
3410
  throw error;
3366
3411
  }
3367
3412
  }
@@ -3374,15 +3419,16 @@ var MOQtailClient = class MOQtailClient {
3374
3419
  async startDatagrams() {
3375
3420
  this.#ensureActive();
3376
3421
  if (this.#isReceivingDatagrams) {
3377
- require_logger.logger.warn("MOQtailClient", "Datagrams already started");
3422
+ require_emitter.logger.warn("MOQtailClient", "Datagrams already started");
3378
3423
  return;
3379
3424
  }
3380
- require_logger.logger.log("MOQtailClient", "Starting datagram support...");
3425
+ require_emitter.logger.log("MOQtailClient", "Starting datagram support...");
3381
3426
  this.#datagramReader = this.webTransport.datagrams.readable.getReader();
3382
- this.#datagramWriter = this.webTransport.datagrams.writable.getWriter();
3427
+ const datagrams = this.webTransport.datagrams;
3428
+ this.#datagramWriter = (datagrams.writable ?? datagrams.createWritable()).getWriter();
3383
3429
  this.#isReceivingDatagrams = true;
3384
3430
  this.#acceptIncomingDatagrams();
3385
- require_logger.logger.log("MOQtailClient", "Datagram support started");
3431
+ require_emitter.logger.log("MOQtailClient", "Datagram support started");
3386
3432
  }
3387
3433
  /**
3388
3434
  * Stop receiving datagrams and release resources.
@@ -3390,7 +3436,7 @@ var MOQtailClient = class MOQtailClient {
3390
3436
  */
3391
3437
  async stopDatagrams() {
3392
3438
  if (!this.#isReceivingDatagrams) return;
3393
- require_logger.logger.log("MOQtailClient", "Stopping datagram support...");
3439
+ require_emitter.logger.log("MOQtailClient", "Stopping datagram support...");
3394
3440
  this.#isReceivingDatagrams = false;
3395
3441
  this.#datagramTrackHandlers.clear();
3396
3442
  if (this.#datagramReader) {
@@ -3424,10 +3470,10 @@ var MOQtailClient = class MOQtailClient {
3424
3470
  */
3425
3471
  subscribeToTrackDatagrams(trackAlias, handler) {
3426
3472
  const key = trackAlias.toString();
3427
- require_logger.logger.log("MOQtailClient", `Registering datagram handler for trackAlias=${trackAlias}`);
3473
+ require_emitter.logger.log("MOQtailClient", `Registering datagram handler for trackAlias=${trackAlias}`);
3428
3474
  this.#datagramTrackHandlers.set(key, handler);
3429
3475
  return () => {
3430
- require_logger.logger.log("MOQtailClient", `Unregistering datagram handler for trackAlias=${trackAlias}`);
3476
+ require_emitter.logger.log("MOQtailClient", `Unregistering datagram handler for trackAlias=${trackAlias}`);
3431
3477
  this.#datagramTrackHandlers.delete(key);
3432
3478
  };
3433
3479
  }
@@ -3456,8 +3502,8 @@ var MOQtailClient = class MOQtailClient {
3456
3502
  createDatagramSender(trackAlias) {
3457
3503
  this.#ensureActive();
3458
3504
  if (!this.#datagramWriter) throw new require_model.MOQtailError("Datagrams not started. Call startDatagrams() first or set enableDatagrams: true in options.");
3459
- require_logger.logger.log("MOQtailClient", `Creating datagram sender for trackAlias=${trackAlias}`);
3460
- return SendDatagramStream.fromWriter(this.#datagramWriter, trackAlias, this.onDatagramSent);
3505
+ require_emitter.logger.log("MOQtailClient", `Creating datagram sender for trackAlias=${trackAlias}`);
3506
+ return SendDatagramStream.fromWriter(this.#datagramWriter, trackAlias, this);
3461
3507
  }
3462
3508
  /**
3463
3509
  * Send a single MoqtObject as a datagram.
@@ -3477,19 +3523,19 @@ var MOQtailClient = class MOQtailClient {
3477
3523
  if (!this.#datagramWriter) throw new require_model.MOQtailError("Datagrams not started. Call startDatagrams() first or set enableDatagrams: true in options.");
3478
3524
  const datagram = object.tryIntoDatagram(trackAlias);
3479
3525
  const serialized = datagram.serialize().toUint8Array();
3480
- if (this.onDatagramSent) this.onDatagramSent(datagram);
3526
+ this.emit("datagramsent", datagram);
3481
3527
  await this.#datagramWriter.write(serialized);
3482
3528
  }
3483
3529
  /**
3484
3530
  * Background loop that receives and parses incoming datagrams.
3485
3531
  */
3486
3532
  async #acceptIncomingDatagrams() {
3487
- require_logger.logger.log("MOQtailClient", "Starting datagram reception loop...");
3533
+ require_emitter.logger.log("MOQtailClient", "Starting datagram reception loop...");
3488
3534
  try {
3489
3535
  while (this.#isReceivingDatagrams && this.#datagramReader) {
3490
3536
  const { done, value: datagramBytes } = await this.#datagramReader.read();
3491
3537
  if (done) {
3492
- require_logger.logger.log("MOQtailClient", "Datagram reader done, stopping reception");
3538
+ require_emitter.logger.log("MOQtailClient", "Datagram reader done, stopping reception");
3493
3539
  this.#isReceivingDatagrams = false;
3494
3540
  if (this.#receivedDatagramObjectController) try {
3495
3541
  this.#receivedDatagramObjectController.close();
@@ -3500,7 +3546,7 @@ var MOQtailClient = class MOQtailClient {
3500
3546
  try {
3501
3547
  const datagram = require_model.Datagram.deserialize(new require_model.FrozenByteBuffer(datagramBytes));
3502
3548
  const trackAlias = datagram.trackAlias;
3503
- if (this.onDatagramReceived) this.onDatagramReceived(datagram);
3549
+ this.emit("datagramreceived", datagram);
3504
3550
  const fullTrackName = this.#resolveTrackAlias(trackAlias);
3505
3551
  const moqtObject = require_model.MoqtObject.fromDatagram(datagram, fullTrackName);
3506
3552
  const trackKey = trackAlias.toString();
@@ -3508,18 +3554,23 @@ var MOQtailClient = class MOQtailClient {
3508
3554
  if (handler) try {
3509
3555
  handler(moqtObject);
3510
3556
  } catch (handlerError) {
3511
- require_logger.logger.warn("MOQtailClient", "Datagram track handler error:", handlerError);
3557
+ require_emitter.logger.warn("MOQtailClient", "Datagram track handler error:", handlerError);
3558
+ }
3559
+ const holder = this.subscriptions.get(trackAlias);
3560
+ if (holder instanceof SubscribeRequest && holder.orderer) {
3561
+ if (!holder.largestLocation || holder.largestLocation.compare(moqtObject.location) < 0) holder.largestLocation = moqtObject.location;
3562
+ if (holder.manager.deliver(holder, moqtObject) && require_model.ObjectDatagramType.isEndOfGroup(datagram.type)) holder.orderer.endGroup(moqtObject.location.group, moqtObject.location.object);
3512
3563
  }
3513
3564
  if (this.#receivedDatagramObjectController) try {
3514
3565
  this.#receivedDatagramObjectController.enqueue(moqtObject);
3515
3566
  } catch {}
3516
3567
  } catch (error) {
3517
- require_logger.logger.warn("MOQtailClient", "Failed to parse datagram:", error);
3568
+ require_emitter.logger.warn("MOQtailClient", "Failed to parse datagram:", error);
3518
3569
  continue;
3519
3570
  }
3520
3571
  }
3521
3572
  } catch (error) {
3522
- require_logger.logger.error("MOQtailClient", "Datagram reception error:", error);
3573
+ require_emitter.logger.error("MOQtailClient", "Datagram reception error:", error);
3523
3574
  if (this.#receivedDatagramObjectController) try {
3524
3575
  this.#receivedDatagramObjectController.error(error);
3525
3576
  } catch {}
@@ -3527,6 +3578,22 @@ var MOQtailClient = class MOQtailClient {
3527
3578
  }
3528
3579
  }
3529
3580
  /**
3581
+ * The track a data stream carries. A subgroup stream can open before the response
3582
+ * that names its alias, so its header event may lack `fullTrackName`: ask again on a
3583
+ * later event of the same stream.
3584
+ */
3585
+ trackNameOf(header) {
3586
+ if (header.fullTrackName || header.trackAlias === void 0) return header.fullTrackName;
3587
+ return this.aliasFullTrackNameMap.get(header.trackAlias);
3588
+ }
3589
+ /** A fetch stream is named by its FETCH, or by the SUBSCRIBE it fills. */
3590
+ #streamTrackName(header) {
3591
+ if (header instanceof require_model.SubgroupHeader) return this.aliasFullTrackNameMap.get(header.trackAlias);
3592
+ const request = this.requests.get(this.#clientRequestId(header.requestId));
3593
+ if (request instanceof FetchRequest) return request.message.fullTrackName;
3594
+ return request instanceof SubscribeRequest ? request.fullTrackName : void 0;
3595
+ }
3596
+ /**
3530
3597
  * Resolve track alias to the full track name it was claimed for.
3531
3598
  * Falls back to a placeholder if no request holds the alias.
3532
3599
  */
@@ -3559,7 +3626,7 @@ var MOQtailClient = class MOQtailClient {
3559
3626
  * Gracefully terminates this {@link MOQtailClient} session and releases underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} resources.
3560
3627
  *
3561
3628
  * @param reason - Optional application-level reason (string or error) recorded and wrapped in an {@link InternalError}
3562
- * passed to the {@link MOQtailClient.onSessionTerminated | onSessionTerminated} callback.
3629
+ * passed to `sessionterminated` listeners. Before {@link MOQtailClient.init} it only marks the client destroyed.
3563
3630
  *
3564
3631
  * @returns Promise that resolves once shutdown logic completes. Subsequent calls are safe no-ops.
3565
3632
  *
@@ -3587,16 +3654,18 @@ var MOQtailClient = class MOQtailClient {
3587
3654
  * ```
3588
3655
  */
3589
3656
  async disconnect(reason) {
3590
- require_logger.logger.log("MOQtailClient", "disconnect", reason);
3657
+ require_emitter.logger.log("MOQtailClient", "disconnect", reason);
3591
3658
  if (this.#isDestroyed) return;
3592
3659
  this.#isDestroyed = true;
3660
+ if (this.#state === "idle") return;
3593
3661
  await this.stopDatagrams();
3594
3662
  const openStreams = [...this.#requestStreams.values()];
3595
3663
  this.#requestStreams.clear();
3596
3664
  this.#namespaceRequestIds.clear();
3597
3665
  await Promise.allSettled(openStreams.map((requestStream) => requestStream.close()));
3598
- this.webTransport.close();
3599
- if (this.onSessionTerminated) this.onSessionTerminated(new require_model.InternalError("MOQtailClient.disconnect", reason instanceof Error ? reason.message : String(reason)));
3666
+ for (const request of this.requests.values()) if (request instanceof SubscribeRequest) request.finish();
3667
+ this.webTransport?.close();
3668
+ this.emit("sessionterminated", new require_model.InternalError("MOQtailClient.disconnect", errorMessage(reason)));
3600
3669
  }
3601
3670
  /**
3602
3671
  * Registers or updates a {@link Track} definition for local publishing or serving.
@@ -3627,7 +3696,7 @@ var MOQtailClient = class MOQtailClient {
3627
3696
  * });
3628
3697
  *
3629
3698
  * // For a hybrid track (live + past):
3630
- * import { MemoryObjectCache } from './track/object_cache';
3699
+ * import { MemoryObjectCache } from '@/client/track/object_cache';
3631
3700
  * const cache = new MemoryObjectCache(); // Caches are not yet fully supported
3632
3701
  * client.addOrUpdateTrack({
3633
3702
  * fullTrackName: { namespace: ["camera"], name: "main" },
@@ -3680,11 +3749,12 @@ var MOQtailClient = class MOQtailClient {
3680
3749
  * future waits for that object.
3681
3750
  * - A {@link FillParameters} in `parameters` also retrieves Objects already published, on a fill fetch stream.
3682
3751
  *
3683
- * The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId`, the `trackAlias` and a `ReadableStream` of {@link MoqtObject}s.
3752
+ * The method returns either a {@link RequestError} (on refusal) or a {@link SubscribeResult}: the subscription `requestId`, its
3753
+ * SUBSCRIBE_OK, a `ReadableStream` of {@link MoqtObject}s, and a `done` promise carrying the PUBLISH_DONE that ends it.
3684
3754
  * Use the `requestId` for {@link MOQtailClient.unsubscribe} or {@link MOQtailClient.subscribeUpdate}. Use the `stream` to decode and display objects.
3685
3755
  *
3686
3756
  * @param args - {@link SubscribeOptions} describing the subscription window and relay forwarding behavior.
3687
- * @returns Either a {@link RequestError} or `{ requestId, trackAlias, stream }` for consuming objects.
3757
+ * @returns Either a {@link RequestError} or `{ requestId, subscribeOk, stream, done }`.
3688
3758
  * @throws : {@link MOQtailError} If the client is destroyed.
3689
3759
  * @throws : {@link ProtocolViolationError} If required fields are missing or inconsistent.
3690
3760
  * @throws : {@link InvalidFilterError} If the Range Filters exceed the server's MAX_FILTER_RANGES; nothing is sent.
@@ -3722,7 +3792,7 @@ var MOQtailClient = class MOQtailClient {
3722
3792
  assertWithinFilterRangeLimit(args.parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.subscribe");
3723
3793
  try {
3724
3794
  const { fullTrackName, priority, groupOrder, forward, locationFilter, parameters } = args;
3725
- require_logger.logger.debug("MOQtailClient", `subscribe: ftn="${fullTrackName}" locationFilter=${locationFilter?.filterType} priority=${priority} forward=${forward} groupOrder=${groupOrder}`);
3795
+ require_emitter.logger.debug("MOQtailClient", `subscribe: ftn="${fullTrackName}" locationFilter=${locationFilter?.filterType} priority=${priority} forward=${forward} groupOrder=${groupOrder}`);
3726
3796
  const msg = new require_model.Subscribe(this.#nextClientRequestId, fullTrackName, [
3727
3797
  new require_model.SubscriberPriority(priority),
3728
3798
  ...forward !== void 0 ? [new require_model.Forward(forward)] : [],
@@ -3731,31 +3801,38 @@ var MOQtailClient = class MOQtailClient {
3731
3801
  ...parameters ?? []
3732
3802
  ]);
3733
3803
  const request = new SubscribeRequest(msg);
3734
- request.manager = new Subscription(request);
3804
+ const subscription = new Subscription(request);
3735
3805
  request.earlyDiscardPolicy = args.earlyDiscardPolicy;
3806
+ request.onEndOfRange = args.onEndOfRange;
3807
+ request.orderer = this.#createOrderer(args.ordering, groupOrder, request.requestId, (obj) => request.output(obj));
3808
+ const fills = parameters?.some(require_model.MessageParameter.isFillParameters) ?? false;
3809
+ if (fills) request.orderer?.suspendWindow("fill");
3736
3810
  this.requests.set(request.requestId, request);
3737
3811
  this.requestIdMap.addMapping(request.requestId, request.fullTrackName);
3738
- require_logger.logger.debug("MOQtailClient", `subscribe: sending SUBSCRIBE requestId=${msg.requestId} ftn="${fullTrackName}"`);
3812
+ require_emitter.logger.debug("MOQtailClient", `subscribe: sending SUBSCRIBE requestId=${msg.requestId} ftn="${fullTrackName}"`);
3739
3813
  await this.#openRequestStream(request.requestId, msg);
3740
- require_logger.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE sent, awaiting SUBSCRIBE_OK/REQUEST_ERROR requestId=${msg.requestId}`);
3814
+ require_emitter.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE sent, awaiting SUBSCRIBE_OK/REQUEST_ERROR requestId=${msg.requestId}`);
3741
3815
  const response = await request;
3742
3816
  if (response instanceof require_model.RequestError) {
3743
- require_logger.logger.error("MOQtailClient", `subscribe: SUBSCRIBE_ERROR requestId=${request.requestId} code=${response.errorCode} reason="${response.reasonPhrase.phrase}"`);
3817
+ require_emitter.logger.error("MOQtailClient", `subscribe: SUBSCRIBE_ERROR requestId=${request.requestId} code=${response.errorCode} reason="${response.reasonPhrase.phrase}"`);
3744
3818
  this.requests.delete(request.requestId);
3745
3819
  this.requestIdMap.removeMappingByRequestId(request.requestId);
3746
3820
  return response;
3747
3821
  } else {
3748
- require_logger.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE_OK requestId=${request.requestId} trackAlias=${response.trackAlias}`);
3822
+ require_emitter.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE_OK requestId=${request.requestId} trackAlias=${response.trackAlias}`);
3749
3823
  this.#claimTrackAlias(response.trackAlias, request);
3824
+ if (fills) this.#liftFillSuspension(request);
3750
3825
  return {
3751
3826
  requestId: msg.requestId,
3752
- trackAlias: response.trackAlias,
3753
- stream: request.stream
3827
+ subscribeOk: response,
3828
+ stream: request.stream,
3829
+ done: subscription.done
3754
3830
  };
3755
3831
  }
3756
3832
  } catch (error) {
3757
- require_logger.logger.error("MOQtailClient", `subscribe: unexpected error — ${error instanceof Error ? error.message : String(error)}`);
3758
- await this.disconnect(new require_model.InternalError("MOQtailClient.subscribe", error instanceof Error ? error.message : String(error)));
3833
+ const reason = errorMessage(error);
3834
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", `subscribe: unexpected error — ${reason}`);
3835
+ await this.disconnect(new require_model.InternalError("MOQtailClient.subscribe", reason));
3759
3836
  throw error;
3760
3837
  }
3761
3838
  }
@@ -3805,14 +3882,10 @@ var MOQtailClient = class MOQtailClient {
3805
3882
  target.unsubscribe();
3806
3883
  }
3807
3884
  } catch (error) {
3808
- await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribe", error instanceof Error ? error.message : String(error)));
3885
+ await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribe", errorMessage(error)));
3809
3886
  throw error;
3810
3887
  } finally {
3811
- for (const target of targets) {
3812
- this.requests.delete(target.requestId);
3813
- this.requestIdMap.removeMappingByRequestId(target.requestId);
3814
- this.#releaseTrackAlias(target);
3815
- }
3888
+ for (const target of targets) this.#forgetSubscription(target);
3816
3889
  owner?.clear();
3817
3890
  }
3818
3891
  }
@@ -3874,18 +3947,19 @@ var MOQtailClient = class MOQtailClient {
3874
3947
  const subscription = this.subscriptions.get(trackAlias);
3875
3948
  if (!subscription) throw new require_model.InternalError("MOQtailClient.subscribeUpdate", "Request exists but subscription does not");
3876
3949
  const requestId = this.#nextClientRequestId;
3877
- const msg = new require_model.RequestUpdate(requestId, [
3878
- new require_model.SubscriberPriority(priority),
3879
- new require_model.Forward(forward),
3950
+ const updateParams = [
3951
+ ...priority !== void 0 ? [new require_model.SubscriberPriority(priority)] : [],
3952
+ ...forward !== void 0 ? [new require_model.Forward(forward)] : [],
3880
3953
  ...locationFilter ? [locationFilter] : [],
3881
3954
  ...parameters ?? []
3882
- ]);
3955
+ ];
3956
+ const msg = new require_model.RequestUpdate(requestId, updateParams);
3883
3957
  subscription.update(msg);
3884
3958
  await this.#requestStreamFor(subscriptionRequestId, "MOQtailClient.subscribeUpdate").send(msg);
3885
3959
  }
3886
3960
  }
3887
3961
  } catch (error) {
3888
- await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeUpdate", error instanceof Error ? error.message : String(error)));
3962
+ await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeUpdate", errorMessage(error)));
3889
3963
  throw error;
3890
3964
  }
3891
3965
  }
@@ -3899,8 +3973,9 @@ var MOQtailClient = class MOQtailClient {
3899
3973
  * delivered by the newest switch target retires everything older.
3900
3974
  *
3901
3975
  * @param args - {@link SwitchOptions} referencing the subscription to switch from and the new subscription options.
3902
- * @returns Either a {@link RequestError} (refusal) or `{ requestId, stream }`, where `stream` is the
3903
- * same {@link https://developer.mozilla.org/docs/Web/API/ReadableStream | ReadableStream} object returned by the original `subscribe()` call.
3976
+ * @returns Either a {@link RequestError} (refusal) or the new request's {@link SubscribeResult}, where `stream`
3977
+ * is the same {@link https://developer.mozilla.org/docs/Web/API/ReadableStream | ReadableStream} object returned by the
3978
+ * original `subscribe()` call and `done` that subscription's, which resolves once the whole switched chain is over.
3904
3979
  * @throws :{@link MOQtailError} If the client is destroyed.
3905
3980
  * @throws :{@link ProtocolViolationError} If `switchFromRequestId` does not name an active subscription.
3906
3981
  * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
@@ -3910,7 +3985,7 @@ var MOQtailClient = class MOQtailClient {
3910
3985
  * await client.switch({
3911
3986
  * switchFromRequestId,
3912
3987
  * switchMode: SwitchMode.Soft,
3913
- * newSubscribeOptions: { fullTrackName: newTrackName, priority: 0, groupOrder: GroupOrder.Original, forward: true, locationFilter: new LocationFilter(LocationFilterType.NextObject) },
3988
+ * newSubscribeOptions: { fullTrackName: newTrackName, priority: 0, groupOrder: GroupOrder.Original, locationFilter: new LocationFilter(LocationFilterType.NextObject) },
3914
3989
  * onDrainDecision: (request) => true
3915
3990
  * });
3916
3991
  * ```
@@ -3929,7 +4004,7 @@ var MOQtailClient = class MOQtailClient {
3929
4004
  subscription.drainTimeoutMs = this.switchDrainTimeoutMs;
3930
4005
  if (onDrainDecision) subscription.onDrainDecision = onDrainDecision;
3931
4006
  const drains = switchMode === 1;
3932
- if (newSubscribeOptions.parameters?.find(require_model.MessageParameter.isSwitchFrom)) require_logger.logger.warn("MOQtailClient", `switch: overwriting existing SwitchFrom parameter for requestId=${switchFromRequestId}`);
4007
+ if (newSubscribeOptions.parameters?.find(require_model.MessageParameter.isSwitchFrom)) require_emitter.logger.warn("MOQtailClient", `switch: overwriting existing SwitchFrom parameter for requestId=${switchFromRequestId}`);
3933
4008
  const parameters = [...newSubscribeOptions.parameters?.filter((p) => !require_model.MessageParameter.isSwitchFrom(p)) ?? [], new require_model.SwitchFrom(switchFromRequestId, switchMode, drains)];
3934
4009
  const result = await this.subscribe({
3935
4010
  ...newSubscribeOptions,
@@ -3939,15 +4014,25 @@ var MOQtailClient = class MOQtailClient {
3939
4014
  const newRequest = this.requests.get(result.requestId);
3940
4015
  subscription.addSwitchTarget(newRequest, drains);
3941
4016
  return {
3942
- requestId: result.requestId,
3943
- stream: subscription.stream
4017
+ ...result,
4018
+ stream: subscription.stream,
4019
+ done: subscription.done
3944
4020
  };
3945
4021
  } catch (error) {
3946
- await this.disconnect(new require_model.InternalError("MOQtailClient.switch", error instanceof Error ? error.message : String(error)));
4022
+ await this.disconnect(new require_model.InternalError("MOQtailClient.switch", errorMessage(error)));
3947
4023
  throw error;
3948
4024
  }
3949
4025
  }
3950
4026
  /**
4027
+ * The orderer for a request, unless its ordering, else the client's, is `'none'` or
4028
+ * unset. Descending group order is never ordered: every group after the first would be late.
4029
+ */
4030
+ #createOrderer(ordering, groupOrder, requestId, release) {
4031
+ const resolved = ordering ?? this.#options.ordering ?? "none";
4032
+ if (resolved === "none" || groupOrder === 2) return void 0;
4033
+ return new ObjectOrderer(resolved, release, (from, to) => this.emit("orderinggap", requestId, from, to));
4034
+ }
4035
+ /**
3951
4036
  * Ends a subscription whose publisher has said how many streams it opened and has
3952
4037
  * now delivered all of them, and reports whether that happened.
3953
4038
  *
@@ -3958,16 +4043,15 @@ var MOQtailClient = class MOQtailClient {
3958
4043
  */
3959
4044
  completeSubscription(request, force = false) {
3960
4045
  if (!force && (!request.expectedStreams || request.streamsAccepted < request.expectedStreams)) return false;
4046
+ request.orderer?.flush();
3961
4047
  const owner = request.manager;
3962
4048
  if (owner) {
3963
4049
  owner.drop(request);
3964
- if (owner.requests.length === 0) owner.controller.close();
3965
- } else request.controller?.close();
3966
- this.#releaseTrackAlias(request);
3967
- this.requests.delete(request.requestId);
3968
- this.requestIdMap.removeMappingByRequestId(request.requestId);
4050
+ if (owner.requests.length === 0) owner.objects.close();
4051
+ } else request.objects.close();
4052
+ this.#forgetSubscription(request);
3969
4053
  this.#closeRequestStream(request.requestId);
3970
- require_logger.logger.debug("MOQtailClient", `subscription for request ${request.requestId} completed`);
4054
+ require_emitter.logger.debug("MOQtailClient", `subscription for request ${request.requestId} completed`);
3971
4055
  return true;
3972
4056
  }
3973
4057
  /**
@@ -3993,7 +4077,7 @@ var MOQtailClient = class MOQtailClient {
3993
4077
  * {@link MOQtailClient.trackAliasResolutionTimeoutMs} elapses with it still unclaimed.
3994
4078
  */
3995
4079
  async #waitForTrackAlias(trackAlias) {
3996
- require_logger.logger.debug("MOQtailClient", `data stream waiting for the track alias ${trackAlias} to be named`);
4080
+ require_emitter.logger.debug("MOQtailClient", `data stream waiting for the track alias ${trackAlias} to be named`);
3997
4081
  return new Promise((resolve) => {
3998
4082
  let waiters = this.#aliasWaiters.get(trackAlias);
3999
4083
  if (!waiters) {
@@ -4029,12 +4113,30 @@ var MOQtailClient = class MOQtailClient {
4029
4113
  this.subscriptions.delete(trackAlias);
4030
4114
  this.aliasFullTrackNameMap.delete(trackAlias);
4031
4115
  }
4116
+ /**
4117
+ * Lifts the fill's ordering suspension when no fill fetch stream will open: nothing was
4118
+ * published yet (no LARGEST_OBJECT), or none opened shortly after SUBSCRIBE_OK (an empty
4119
+ * fill range, moqt-22 3.4).
4120
+ */
4121
+ #liftFillSuspension(request) {
4122
+ const lift = () => {
4123
+ if (!request.fillOpened) request.orderer?.resumeWindow("fill");
4124
+ };
4125
+ if (!request.fillBoundary) lift();
4126
+ else setTimeout(lift, this.fillOpenTimeoutMs);
4127
+ }
4032
4128
  /** Tears down a switch target that lost the handover race to a newer one. */
4033
4129
  async #retireSwitchedRequest(request) {
4130
+ request.orderer?.flush();
4131
+ this.#forgetSubscription(request);
4132
+ await this.#resetRequestStream(request.requestId, 1);
4133
+ }
4134
+ /** Drops `request` from the request tables, frees its alias, and resolves its `done`. */
4135
+ #forgetSubscription(request) {
4034
4136
  this.requests.delete(request.requestId);
4035
4137
  this.requestIdMap.removeMappingByRequestId(request.requestId);
4036
4138
  this.#releaseTrackAlias(request);
4037
- await this.#resetRequestStream(request.requestId, 1);
4139
+ request.finish();
4038
4140
  }
4039
4141
  /**
4040
4142
  * One-shot retrieval of a bounded object span, optionally anchored to an existing subscription, returning a stream of {@link MoqtObject}s.
@@ -4050,7 +4152,7 @@ var MOQtailClient = class MOQtailClient {
4050
4152
  * - typeAndProps: Discriminated union carrying parameters specific to each fetch mode (see examples).
4051
4153
  * - parameters: Optional version-specific extension block.
4052
4154
  *
4053
- * Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, stream }` whose `stream`
4155
+ * Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, fetchOk, stream }` whose `stream`
4054
4156
  * ends naturally after the bounded range completes (no explicit cancel needed for normal completion).
4055
4157
  *
4056
4158
  * Use cases:
@@ -4105,30 +4207,30 @@ var MOQtailClient = class MOQtailClient {
4105
4207
  ...parameters ?? []
4106
4208
  ];
4107
4209
  const requestId = this.#nextClientRequestId;
4108
- require_logger.logger.log("MOQtailClient", "fetch: generated requestId:", requestId, "current #dontUseRequestId:", this.#dontUseRequestId);
4210
+ require_emitter.logger.log("MOQtailClient", "fetch: generated requestId:", requestId, "current #dontUseRequestId:", this.#dontUseRequestId);
4109
4211
  const msg = new require_model.Fetch(requestId, fullTrackName, params);
4110
4212
  const request = new FetchRequest(msg);
4111
- require_logger.logger.log("MOQtailClient", "fetch: full fetch message:", {
4213
+ request.onEndOfRange = args.onEndOfRange;
4214
+ request.orderer = this.#createOrderer(args.ordering, groupOrder, requestId, (obj) => request.objects.enqueue(obj));
4215
+ require_emitter.logger.log("MOQtailClient", "fetch: full fetch message:", {
4112
4216
  requestId: msg.requestId,
4113
4217
  fullTrackName: `${fullTrackName}`
4114
4218
  });
4115
4219
  this.requests.set(msg.requestId, request);
4116
- require_logger.logger.log("MOQtailClient", "fetch: about to send fetch message to server");
4220
+ require_emitter.logger.log("MOQtailClient", "fetch: about to send fetch message to server");
4117
4221
  await this.#openRequestStream(msg.requestId, msg);
4118
- require_logger.logger.log("MOQtailClient", "fetch: fetch message sent successfully, waiting for response");
4222
+ require_emitter.logger.log("MOQtailClient", "fetch: fetch message sent successfully, waiting for response");
4119
4223
  const response = await request;
4120
4224
  if (response instanceof require_model.RequestError) {
4121
4225
  this.requests.delete(msg.requestId);
4122
4226
  return response;
4123
- } else {
4124
- const stream = request.stream;
4125
- return {
4126
- requestId: msg.requestId,
4127
- stream
4128
- };
4129
- }
4227
+ } else return {
4228
+ requestId: msg.requestId,
4229
+ fetchOk: response,
4230
+ stream: request.stream
4231
+ };
4130
4232
  } catch (error) {
4131
- await this.disconnect(new require_model.InternalError("MOQtailClient.fetch", error instanceof Error ? error.message : String(error)));
4233
+ await this.disconnect(new require_model.InternalError("MOQtailClient.fetch", errorMessage(error)));
4132
4234
  throw error;
4133
4235
  }
4134
4236
  }
@@ -4173,7 +4275,7 @@ var MOQtailClient = class MOQtailClient {
4173
4275
  if (typeof requestId === "number") requestId = BigInt(requestId);
4174
4276
  if (this.requests.get(requestId) instanceof FetchRequest) await this.#resetRequestStream(requestId, 1);
4175
4277
  } catch (error) {
4176
- await this.disconnect(new require_model.InternalError("MOQtailClient.fetchCancel", error instanceof Error ? error.message : String(error)));
4278
+ await this.disconnect(new require_model.InternalError("MOQtailClient.fetchCancel", errorMessage(error)));
4177
4279
  throw error;
4178
4280
  }
4179
4281
  }
@@ -4201,7 +4303,7 @@ var MOQtailClient = class MOQtailClient {
4201
4303
  trackAlias
4202
4304
  };
4203
4305
  } catch (error) {
4204
- await this.disconnect(new require_model.InternalError("MOQtailClient.publish", error instanceof Error ? error.message : String(error)));
4306
+ await this.disconnect(new require_model.InternalError("MOQtailClient.publish", errorMessage(error)));
4205
4307
  throw error;
4206
4308
  }
4207
4309
  }
@@ -4214,17 +4316,18 @@ var MOQtailClient = class MOQtailClient {
4214
4316
  try {
4215
4317
  if (typeof publishRequestId === "number") publishRequestId = BigInt(publishRequestId);
4216
4318
  const publication = this.publications.get(publishRequestId);
4217
- const msg = new require_model.PublishDone(statusCode, publication instanceof PublishPublication ? publication.streamsOpened : require_model.PublishDone.UNKNOWN_STREAM_COUNT, new require_model.ReasonPhrase(reasonPhrase));
4319
+ const streamCount = publication instanceof PublishPublication ? publication.streamsOpened : require_model.PublishDone.UNKNOWN_STREAM_COUNT;
4320
+ const msg = new require_model.PublishDone(statusCode, streamCount, new require_model.ReasonPhrase(reasonPhrase));
4218
4321
  const requestStream = this.#requestStreams.get(publishRequestId);
4219
4322
  if (requestStream) {
4220
4323
  await requestStream.send(msg);
4221
4324
  await this.#closeRequestStream(publishRequestId);
4222
- } else require_logger.logger.warn("MOQtailClient", `publishDone: no request stream for requestId=${publishRequestId}`);
4325
+ } else require_emitter.logger.warn("MOQtailClient", `publishDone: no request stream for requestId=${publishRequestId}`);
4223
4326
  this.requests.delete(publishRequestId);
4224
4327
  this.requestIdMap.removeMappingByRequestId(publishRequestId);
4225
4328
  this.subscriptionAliasMap.delete(publishRequestId);
4226
4329
  } catch (error) {
4227
- await this.disconnect(new require_model.InternalError("MOQtailClient.publishDone", error instanceof Error ? error.message : String(error)));
4330
+ await this.disconnect(new require_model.InternalError("MOQtailClient.publishDone", errorMessage(error)));
4228
4331
  throw error;
4229
4332
  }
4230
4333
  }
@@ -4309,7 +4412,7 @@ var MOQtailClient = class MOQtailClient {
4309
4412
  this.requests.delete(msg.requestId);
4310
4413
  return response;
4311
4414
  } catch (error) {
4312
- await this.disconnect(new require_model.InternalError("MOQtailClient.publishNamespace", error instanceof Error ? error.message : String(error)));
4415
+ await this.disconnect(new require_model.InternalError("MOQtailClient.publishNamespace", errorMessage(error)));
4313
4416
  throw error;
4314
4417
  }
4315
4418
  }
@@ -4368,13 +4471,13 @@ var MOQtailClient = class MOQtailClient {
4368
4471
  try {
4369
4472
  const params = parameters ?? [];
4370
4473
  const msg = new require_model.SubscribeNamespace(this.#nextClientRequestId, trackNamespacePrefix, params);
4371
- const requestStream = await RequestStream.open(this.webTransport, msg, this.#requestStreamHooks);
4474
+ const requestStream = await RequestStream.open(this.webTransport, msg, this);
4372
4475
  this.#requestStreams.set(msg.requestId, requestStream);
4373
- require_logger.logger.log("MOQtailClient", "subscribeNamespace | sent msg", msg, msg.trackNamespacePrefix.toUtf8Path(), msg.requestId);
4476
+ require_emitter.logger.log("MOQtailClient", "subscribeNamespace | sent msg", msg, msg.trackNamespacePrefix.toUtf8Path(), msg.requestId);
4374
4477
  const response = await requestStream.next();
4375
4478
  if (!response) throw new require_model.InternalError("MOQtailClient.subscribeNamespace", "Stream closed before response");
4376
4479
  if (!(response instanceof require_model.RequestOk || response instanceof require_model.RequestError)) throw new require_model.ProtocolViolationError("MOQtailClient.subscribeNamespace", "Unexpected response message type");
4377
- require_logger.logger.log("MOQtailClient", "subscribeNamespace | got response", response);
4480
+ require_emitter.logger.log("MOQtailClient", "subscribeNamespace | got response", response);
4378
4481
  if (response instanceof require_model.RequestOk) {
4379
4482
  this.subscribedNamespaces.add(trackNamespacePrefix);
4380
4483
  this.#namespaceRequestIds.set(trackNamespacePrefix.toUtf8Path(), msg.requestId);
@@ -4389,7 +4492,7 @@ var MOQtailClient = class MOQtailClient {
4389
4492
  }
4390
4493
  };
4391
4494
  } catch (error) {
4392
- await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeNamespace", error instanceof Error ? error.message : String(error)));
4495
+ await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeNamespace", errorMessage(error)));
4393
4496
  throw error;
4394
4497
  }
4395
4498
  }
@@ -4398,7 +4501,7 @@ var MOQtailClient = class MOQtailClient {
4398
4501
  assertWithinFilterRangeLimit(parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.subscribeTracks");
4399
4502
  try {
4400
4503
  const msg = new require_model.SubscribeTracks(this.#nextClientRequestId, trackNamespacePrefix, parameters ?? []);
4401
- const requestStream = await RequestStream.open(this.webTransport, msg, this.#requestStreamHooks);
4504
+ const requestStream = await RequestStream.open(this.webTransport, msg, this);
4402
4505
  this.#requestStreams.set(msg.requestId, requestStream);
4403
4506
  const response = await requestStream.next();
4404
4507
  if (!response) throw new require_model.InternalError("MOQtailClient.subscribeTracks", "Stream closed before response");
@@ -4415,7 +4518,7 @@ var MOQtailClient = class MOQtailClient {
4415
4518
  }
4416
4519
  };
4417
4520
  } catch (error) {
4418
- await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeTracks", error instanceof Error ? error.message : String(error)));
4521
+ await this.disconnect(new require_model.InternalError("MOQtailClient.subscribeTracks", errorMessage(error)));
4419
4522
  throw error;
4420
4523
  }
4421
4524
  }
@@ -4424,8 +4527,8 @@ var MOQtailClient = class MOQtailClient {
4424
4527
  while (true) {
4425
4528
  const msg = await requestStream.next();
4426
4529
  if (!msg) break;
4427
- if (msg instanceof require_model.Namespace && this.onPeerNamespace) this.onPeerNamespace(prefix, msg.trackNamespaceSuffix);
4428
- else if (msg instanceof require_model.NamespaceDone && this.onPeerNamespaceDone) this.onPeerNamespaceDone(prefix, msg.trackNamespaceSuffix);
4530
+ if (msg instanceof require_model.Namespace) this.emit("peernamespace", prefix, msg.trackNamespaceSuffix);
4531
+ else if (msg instanceof require_model.NamespaceDone) this.emit("peernamespacedone", prefix, msg.trackNamespaceSuffix);
4429
4532
  }
4430
4533
  } finally {
4431
4534
  this.#requestStreams.delete(requestId);
@@ -4443,7 +4546,7 @@ var MOQtailClient = class MOQtailClient {
4443
4546
  this.subscribedNamespaces.delete(trackNamespacePrefix);
4444
4547
  await this.#closeNamespaceRequestStream(trackNamespacePrefix);
4445
4548
  } catch (error) {
4446
- await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribeNamespace", error instanceof Error ? error.message : String(error)));
4549
+ await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribeNamespace", errorMessage(error)));
4447
4550
  throw error;
4448
4551
  }
4449
4552
  }
@@ -4478,7 +4581,7 @@ var MOQtailClient = class MOQtailClient {
4478
4581
  this.requests.delete(msg.requestId);
4479
4582
  return response;
4480
4583
  } catch (error) {
4481
- await this.disconnect(new require_model.InternalError("MOQtailClient.trackStatus", error instanceof Error ? error.message : String(error)));
4584
+ await this.disconnect(new require_model.InternalError("MOQtailClient.trackStatus", errorMessage(error)));
4482
4585
  throw error;
4483
4586
  }
4484
4587
  }
@@ -4487,28 +4590,8 @@ var MOQtailClient = class MOQtailClient {
4487
4590
  *
4488
4591
  * @param requestId - The requestId carried by `first`; the key the stream is filed under.
4489
4592
  */
4490
- /**
4491
- * Hands a data stream {@link MOQtailClient.onDataEvent}, read at call time so an observer assigned
4492
- * after connecting still sees streams that are already open.
4493
- *
4494
- * @internal
4495
- */
4496
- dataStreamObserver(fullTrackNameOf) {
4497
- return {
4498
- onDataEvent: (event) => this.onDataEvent?.(event),
4499
- ...fullTrackNameOf && { fullTrackNameOf }
4500
- };
4501
- }
4502
- /**
4503
- * Forwards request-stream traffic to {@link onMessageSent} and {@link onMessageReceived},
4504
- * read at call time so callbacks assigned after connecting still see it.
4505
- */
4506
- #requestStreamHooks = {
4507
- onMessageSent: (msg) => this.onMessageSent?.(msg),
4508
- onMessageReceived: (msg) => this.onMessageReceived?.(msg)
4509
- };
4510
4593
  async #openRequestStream(requestId, first) {
4511
- const requestStream = await RequestStream.open(this.webTransport, first, this.#requestStreamHooks);
4594
+ const requestStream = await RequestStream.open(this.webTransport, first, this);
4512
4595
  this.#requestStreams.set(requestId, requestStream);
4513
4596
  this.#pumpRequestStream(requestId, requestStream);
4514
4597
  return requestStream;
@@ -4523,8 +4606,8 @@ var MOQtailClient = class MOQtailClient {
4523
4606
  * the wire changes.
4524
4607
  *
4525
4608
  * @returns True if the request was re-issued here. A GOAWAY naming a new session URI
4526
- * is not: opening a session is the application's call, so it is surfaced through
4527
- * {@link MOQtailClient.onGoaway} and the request stream is closed.
4609
+ * is not: opening a session is the application's call, so it is surfaced as a
4610
+ * `goaway` event and the request stream is closed.
4528
4611
  *
4529
4612
  * @internal
4530
4613
  */
@@ -4532,12 +4615,12 @@ var MOQtailClient = class MOQtailClient {
4532
4615
  const oldStream = this.#requestStreams.get(requestId);
4533
4616
  const first = oldStream?.first;
4534
4617
  if (!oldStream || !first) {
4535
- require_logger.logger.warn("MOQtailClient", `GOAWAY on a request stream this side did not open (request id ${requestId})`);
4618
+ require_emitter.logger.warn("MOQtailClient", `GOAWAY on a request stream this side did not open (request id ${requestId})`);
4536
4619
  return false;
4537
4620
  }
4538
4621
  if (goAway.newSessionUri) {
4539
- require_logger.logger.log("MOQtailClient", `GOAWAY migrates request ${requestId} to ${goAway.newSessionUri}`);
4540
- this.onGoaway?.(goAway);
4622
+ require_emitter.logger.log("MOQtailClient", `GOAWAY migrates request ${requestId} to ${goAway.newSessionUri}`);
4623
+ this.emit("goaway", goAway);
4541
4624
  await this.#closeRequestStream(requestId);
4542
4625
  return false;
4543
4626
  }
@@ -4548,10 +4631,18 @@ var MOQtailClient = class MOQtailClient {
4548
4631
  oldStream.migrated = true;
4549
4632
  await oldStream.close();
4550
4633
  await this.#openRequestStream(requestId, reissued);
4551
- require_logger.logger.log("MOQtailClient", `re-issued request ${requestId} as request id ${wireRequestId}`);
4634
+ require_emitter.logger.log("MOQtailClient", `re-issued request ${requestId} as request id ${wireRequestId}`);
4552
4635
  return true;
4553
4636
  }
4554
4637
  /** The request a peer-supplied Request ID belongs to, undoing any migration. */
4638
+ /** A handler that throws must not end the stream the marker arrived on. */
4639
+ #notifyEndOfRange(handler, marker) {
4640
+ try {
4641
+ handler?.(marker.endOfRange, marker.location);
4642
+ } catch (handlerError) {
4643
+ require_emitter.logger.warn("MOQtailClient", "End of Range handler error:", handlerError);
4644
+ }
4645
+ }
4555
4646
  #clientRequestId(wireRequestId) {
4556
4647
  return this.#clientRequestIds.get(wireRequestId) ?? wireRequestId;
4557
4648
  }
@@ -4573,6 +4664,7 @@ var MOQtailClient = class MOQtailClient {
4573
4664
  */
4574
4665
  async #pumpRequestStream(requestId, requestStream) {
4575
4666
  let answered = false;
4667
+ let closedBy;
4576
4668
  try {
4577
4669
  while (true) {
4578
4670
  const msg = await requestStream.next();
@@ -4582,13 +4674,16 @@ var MOQtailClient = class MOQtailClient {
4582
4674
  await handler(this, msg, requestStream, requestId);
4583
4675
  answered = true;
4584
4676
  }
4585
- require_logger.logger.debug("MOQtailClient", `request stream for requestId=${requestId} closed by peer`);
4677
+ require_emitter.logger.debug("MOQtailClient", `request stream for requestId=${requestId} closed by peer`);
4586
4678
  } catch (error) {
4587
- require_logger.logger.error("MOQtailClient", `request stream for requestId=${requestId} failed`, error);
4679
+ if (this.#sessionClosing(error)) closedBy = error;
4680
+ else require_emitter.logger.error("MOQtailClient", `request stream for requestId=${requestId} failed`, error);
4681
+ const request = this.requests.get(requestId);
4682
+ if (!requestStream.migrated && request instanceof SubscribeRequest) request.finish();
4588
4683
  } finally {
4589
4684
  if (!requestStream.migrated) {
4590
4685
  this.#requestStreams.delete(requestId);
4591
- if (!answered) this.requests.get(requestId)?.reject(new require_model.InternalError("MOQtailClient", `Request stream closed before answering request ${requestId}`));
4686
+ if (!answered) this.requests.get(requestId)?.reject(closedBy ?? new require_model.InternalError("MOQtailClient", `Request stream closed before answering request ${requestId}`));
4592
4687
  }
4593
4688
  }
4594
4689
  }
@@ -4620,7 +4715,6 @@ var MOQtailClient = class MOQtailClient {
4620
4715
  * Reads the shared control stream, every request type has its own bidi stream.
4621
4716
  */
4622
4717
  async #handleIncomingControlMessages() {
4623
- this.#ensureActive();
4624
4718
  try {
4625
4719
  const reader = this.controlStream.stream.getReader();
4626
4720
  while (true) {
@@ -4628,47 +4722,51 @@ var MOQtailClient = class MOQtailClient {
4628
4722
  if (done) throw new require_model.MOQtailError("WebTransport session is terminated");
4629
4723
  const handler = getHandlerForControlMessage(msg);
4630
4724
  if (!handler) {
4631
- require_logger.logger.warn("MOQtailClient", `${msg.constructor.name} on the control stream`);
4725
+ require_emitter.logger.warn("MOQtailClient", `${msg.constructor.name} on the control stream`);
4632
4726
  continue;
4633
4727
  }
4634
4728
  await handler(this, msg);
4635
4729
  }
4636
4730
  } catch (error) {
4637
- this.disconnect();
4638
- throw error;
4731
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", "control stream failed", error);
4732
+ await this.disconnect(error);
4639
4733
  }
4640
4734
  }
4641
4735
  async #acceptIncomingUniStreams() {
4642
- this.#ensureActive();
4643
4736
  const reader = this.#incomingUniStreams;
4644
- let isDone = false;
4645
- while (!isDone) try {
4646
- const { done, value: stream } = await reader.read();
4647
- if (done) {
4648
- isDone = true;
4649
- throw new require_model.MOQtailError("WebTransport session is terminated");
4737
+ try {
4738
+ while (true) {
4739
+ const { done, value: stream } = await reader.read();
4740
+ if (done) return;
4741
+ this.#handleRecvStreams(stream).catch((error) => {
4742
+ if (error instanceof PeerStreamResetError || this.#sessionClosing(error)) {
4743
+ require_emitter.logger.debug("MOQtailClient", `data stream ended: ${error.message}`);
4744
+ return;
4745
+ }
4746
+ require_emitter.logger.error("MOQtailClient", "handleRecvStreams error", error);
4747
+ });
4650
4748
  }
4651
- this.#handleRecvStreams(stream).catch((error) => {
4652
- if (error instanceof PeerStreamResetError) {
4653
- require_logger.logger.debug("MOQtailClient", `data stream ended: ${error.message}`);
4654
- return;
4655
- }
4656
- require_logger.logger.error("MOQtailClient", "handleRecvStreams error", error);
4657
- });
4658
4749
  } catch (error) {
4659
- require_logger.logger.error("MOQtailClient", "acceptIncomingUniStreams error", error);
4660
- if (this.#isDestroyed) break;
4750
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", "acceptIncomingUniStreams error", error);
4661
4751
  }
4662
4752
  }
4663
- #acceptIncomingBiStreams() {
4664
- (async () => {
4665
- const reader = this.webTransport.incomingBidirectionalStreams.getReader();
4753
+ async #acceptIncomingBiStreams() {
4754
+ const reader = this.webTransport.incomingBidirectionalStreams.getReader();
4755
+ try {
4666
4756
  while (true) {
4667
4757
  const { value: biStream, done } = await reader.read();
4668
- if (done) break;
4669
- this.#dispatchIncomingRequestStream(new RequestStream(biStream, this.#requestStreamHooks));
4758
+ if (done) return;
4759
+ this.#dispatchIncomingRequestStream(new RequestStream(biStream, this)).catch((error) => {
4760
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", "incoming request stream failed", error);
4761
+ });
4670
4762
  }
4671
- })();
4763
+ } catch (error) {
4764
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", "acceptIncomingBiStreams error", error);
4765
+ }
4766
+ }
4767
+ /** The session is going away, so a read or write failing is expected, not an error to log. */
4768
+ #sessionClosing(error) {
4769
+ return this.#isDestroyed || isSessionClosed(error);
4672
4770
  }
4673
4771
  /**
4674
4772
  * Serves one peer-opened request stream: the first message must be a `First`-marked
@@ -4680,7 +4778,7 @@ var MOQtailClient = class MOQtailClient {
4680
4778
  const first = await requestStream.next();
4681
4779
  if (!first) return;
4682
4780
  if (!require_model.ControlMessageType.isFirst(first.getType())) {
4683
- require_logger.logger.warn("MOQtailClient", `${first.constructor.name} may not open a request stream; resetting it`);
4781
+ require_emitter.logger.warn("MOQtailClient", `${first.constructor.name} may not open a request stream; resetting it`);
4684
4782
  await requestStream.reset(0);
4685
4783
  return;
4686
4784
  }
@@ -4695,7 +4793,7 @@ var MOQtailClient = class MOQtailClient {
4695
4793
  msg = await requestStream.next();
4696
4794
  }
4697
4795
  } catch (error) {
4698
- require_logger.logger.error("MOQtailClient", "incoming request stream failed", error);
4796
+ if (!this.#sessionClosing(error)) require_emitter.logger.error("MOQtailClient", "incoming request stream failed", error);
4699
4797
  } finally {
4700
4798
  const requestId = "requestId" in first ? first.requestId : void 0;
4701
4799
  if (requestId !== void 0) {
@@ -4705,239 +4803,136 @@ var MOQtailClient = class MOQtailClient {
4705
4803
  await requestStream.close();
4706
4804
  }
4707
4805
  }
4806
+ /** The objects on a fetch data stream. End-of-range markers carry no Object, so they go to `onEndOfRange`. */
4807
+ async *#readFetchObjects(reader, fullTrackName, onEndOfRange) {
4808
+ while (true) {
4809
+ const { done, value } = await reader.read();
4810
+ if (done) return;
4811
+ if (!value) continue;
4812
+ if (!(value instanceof require_model.FetchObject)) throw new require_model.ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
4813
+ if (value.kind === "end_of_range") this.#notifyEndOfRange(onEndOfRange, value);
4814
+ else yield require_model.MoqtObject.fromFetchObject(value, fullTrackName);
4815
+ }
4816
+ }
4708
4817
  async #handleRecvStreams(incomingUniStream) {
4709
4818
  this.#ensureActive();
4710
- try {
4711
- const recvStream = await RecvStream.new(incomingUniStream, this.dataStreamTimeoutMs, this.onDataReceived, (header) => {
4712
- if (!(header instanceof require_model.FetchHeader)) return 0;
4713
- const request = this.requests.get(this.#clientRequestId(header.requestId));
4714
- if (!(request instanceof FetchRequest)) return 0;
4715
- return require_model.MessageParameter.groupOrderOf(request.message.parameters);
4716
- }, this.dataStreamObserver((header) => header instanceof require_model.SubgroupHeader ? this.aliasFullTrackNameMap.get(header.trackAlias) : void 0));
4717
- const header = recvStream.header;
4718
- const reader = recvStream.stream.getReader();
4719
- let forceComplete = false;
4720
- if (header instanceof require_model.FetchHeader) {
4721
- const request = this.requests.get(this.#clientRequestId(header.requestId));
4722
- if (request && request instanceof FetchRequest) {
4723
- const fullTrackName = request.message.fullTrackName;
4724
- try {
4725
- while (true) {
4726
- const { done, value: nextObject } = await reader.read();
4727
- if (done) {
4728
- request.controller?.close();
4729
- break;
4730
- }
4731
- if (nextObject) {
4732
- if (nextObject instanceof require_model.FetchObject) {
4733
- if (nextObject.kind === "end_of_range") continue;
4734
- const moqtObject = require_model.MoqtObject.fromFetchObject(nextObject, fullTrackName);
4735
- request.controller?.enqueue(moqtObject);
4736
- continue;
4737
- }
4738
- throw new require_model.ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
4739
- }
4819
+ const recvStream = await RecvStream.new(incomingUniStream, this.dataStreamTimeoutMs, this, (header) => {
4820
+ if (!(header instanceof require_model.FetchHeader)) return 0;
4821
+ const request = this.requests.get(this.#clientRequestId(header.requestId));
4822
+ if (!(request instanceof FetchRequest)) return 0;
4823
+ return require_model.MessageParameter.groupOrderOf(request.message.parameters);
4824
+ }, (header) => this.#streamTrackName(header));
4825
+ const header = recvStream.header;
4826
+ const reader = recvStream.stream.getReader();
4827
+ let forceComplete = false;
4828
+ if (header instanceof require_model.FetchHeader) {
4829
+ const request = this.requests.get(this.#clientRequestId(header.requestId));
4830
+ if (request instanceof FetchRequest) {
4831
+ let previous;
4832
+ try {
4833
+ const objects = this.#readFetchObjects(reader, request.message.fullTrackName, request.onEndOfRange);
4834
+ for await (const moqtObject of objects) {
4835
+ if (!request.objects.open) {
4836
+ await recvStream.stopSending(1);
4837
+ break;
4740
4838
  }
4741
- } finally {
4742
- reader.releaseLock();
4839
+ if (request.orderer) request.orderer.push(moqtObject, previous);
4840
+ else request.objects.enqueue(moqtObject);
4841
+ previous = moqtObject.location;
4743
4842
  }
4744
- return;
4843
+ request.orderer?.flush();
4844
+ request.objects.close();
4845
+ } finally {
4846
+ reader.releaseLock();
4745
4847
  }
4746
- if (request instanceof SubscribeRequest) {
4747
- request.streamsAccepted++;
4748
- try {
4749
- while (true) {
4750
- const { done, value: nextObject } = await reader.read();
4751
- if (done) break;
4752
- if (!nextObject) continue;
4753
- if (!(nextObject instanceof require_model.FetchObject)) throw new require_model.ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
4754
- if (nextObject.kind === "end_of_range") continue;
4755
- const moqtObject = require_model.MoqtObject.fromFetchObject(nextObject, request.fullTrackName);
4756
- if (request.manager) {
4757
- if (!request.manager.deliver(request, moqtObject)) {
4758
- await recvStream.stopSending(1);
4759
- forceComplete = true;
4760
- break;
4761
- }
4762
- } else request.controller?.enqueue(moqtObject);
4848
+ return;
4849
+ }
4850
+ if (request instanceof SubscribeRequest) {
4851
+ request.streamsAccepted++;
4852
+ request.fillOpened = true;
4853
+ request.openFills++;
4854
+ request.orderer?.suspendWindow("fill");
4855
+ let previous;
4856
+ try {
4857
+ for await (const moqtObject of this.#readFetchObjects(reader, request.fullTrackName, request.onEndOfRange)) {
4858
+ if (!request.manager.objects.open) {
4859
+ await recvStream.stopSending(1);
4860
+ break;
4861
+ }
4862
+ if (!request.manager.deliver(request, moqtObject, previous)) {
4863
+ await recvStream.stopSending(1);
4864
+ forceComplete = true;
4865
+ break;
4763
4866
  }
4764
- } finally {
4765
- reader.releaseLock();
4867
+ previous = moqtObject.location;
4766
4868
  }
4767
- this.completeSubscription(request, forceComplete);
4768
- return;
4769
- }
4770
- throw new require_model.ProtocolViolationError("MOQtailClient", "No request for received request id");
4771
- } else {
4772
- let subscription = this.subscriptions.get(header.trackAlias);
4773
- if (!subscription) {
4774
- await this.#waitForTrackAlias(header.trackAlias);
4775
- subscription = this.subscriptions.get(header.trackAlias);
4869
+ } finally {
4870
+ reader.releaseLock();
4871
+ request.openFills--;
4872
+ if (request.openFills === 0) request.orderer?.resumeWindow("fill");
4776
4873
  }
4777
- if (subscription) {
4778
- subscription.streamsAccepted++;
4779
- const fullTrackName = subscription.fullTrackName;
4780
- let firstObjectId = null;
4781
- let subgroupTimeoutId;
4782
- const effectiveDiscardPolicy = subscription.earlyDiscardPolicy ?? this.#earlyDiscardPolicy;
4783
- if (effectiveDiscardPolicy?.subgroupReceiveTimeout !== void 0) subgroupTimeoutId = setTimeout(() => {
4784
- reader.cancel(streamResetReason(2)).catch(() => {});
4785
- }, effectiveDiscardPolicy.subgroupReceiveTimeout);
4786
- try {
4787
- while (true) {
4788
- const { done, value: nextObject } = await reader.read();
4789
- if (done) break;
4790
- if (nextObject) {
4791
- if (nextObject instanceof require_model.SubgroupObject) {
4792
- if (!firstObjectId) firstObjectId = nextObject.objectId;
4793
- let subgroupId = null;
4794
- if (require_model.SubgroupHeaderType.isSubgroupIdZero(header.type)) subgroupId = 0n;
4795
- else if (require_model.SubgroupHeaderType.isSubgroupIdFirstObjectId(header.type)) subgroupId = firstObjectId ?? null;
4796
- else if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(header.type)) subgroupId = header.subgroupId ?? null;
4797
- const moqtObject = require_model.MoqtObject.fromSubgroupObject(nextObject, header.groupId, header.publisherPriority, subgroupId, fullTrackName);
4798
- if (!subscription.largestLocation) subscription.largestLocation = moqtObject.location;
4799
- if (subscription.largestLocation.compare(moqtObject.location) == -1) subscription.largestLocation = moqtObject.location;
4800
- if (subscription.manager) {
4801
- if (!subscription.manager.deliver(subscription, moqtObject)) {
4802
- forceComplete = true;
4803
- await recvStream.stopSending(1);
4804
- break;
4805
- }
4806
- } else subscription.controller?.enqueue(moqtObject);
4807
- continue;
4874
+ this.completeSubscription(request, forceComplete);
4875
+ return;
4876
+ }
4877
+ throw new require_model.ProtocolViolationError("MOQtailClient", "No request for received request id");
4878
+ } else {
4879
+ let subscription = this.subscriptions.get(header.trackAlias);
4880
+ if (!subscription) {
4881
+ await this.#waitForTrackAlias(header.trackAlias);
4882
+ subscription = this.subscriptions.get(header.trackAlias);
4883
+ }
4884
+ if (subscription) {
4885
+ subscription.streamsAccepted++;
4886
+ const fullTrackName = subscription.fullTrackName;
4887
+ let firstObjectId = null;
4888
+ let lastObjectId;
4889
+ let subgroupTimeoutId;
4890
+ const effectiveDiscardPolicy = subscription.earlyDiscardPolicy ?? this.#earlyDiscardPolicy;
4891
+ if (effectiveDiscardPolicy?.subgroupReceiveTimeout !== void 0) subgroupTimeoutId = setTimeout(() => {
4892
+ reader.cancel(streamResetReason(2)).catch(() => {});
4893
+ }, effectiveDiscardPolicy.subgroupReceiveTimeout);
4894
+ try {
4895
+ while (true) {
4896
+ const { done, value: nextObject } = await reader.read();
4897
+ if (done) {
4898
+ if (lastObjectId !== void 0 && require_model.SubgroupHeaderType.containsEndOfGroup(header.type)) subscription.orderer?.endGroup(header.groupId, lastObjectId);
4899
+ break;
4900
+ }
4901
+ if (nextObject) {
4902
+ if (nextObject instanceof require_model.SubgroupObject) {
4903
+ lastObjectId = nextObject.objectId;
4904
+ if (firstObjectId === null) firstObjectId = nextObject.objectId;
4905
+ let subgroupId = null;
4906
+ if (require_model.SubgroupHeaderType.isSubgroupIdZero(header.type)) subgroupId = 0n;
4907
+ else if (require_model.SubgroupHeaderType.isSubgroupIdFirstObjectId(header.type)) subgroupId = firstObjectId ?? null;
4908
+ else if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(header.type)) subgroupId = header.subgroupId ?? null;
4909
+ const moqtObject = require_model.MoqtObject.fromSubgroupObject(nextObject, header.groupId, header.publisherPriority, subgroupId, fullTrackName);
4910
+ if (!subscription.largestLocation) subscription.largestLocation = moqtObject.location;
4911
+ if (subscription.largestLocation.compare(moqtObject.location) == -1) subscription.largestLocation = moqtObject.location;
4912
+ if (!subscription.manager.objects.open) {
4913
+ await recvStream.stopSending(1);
4914
+ break;
4915
+ }
4916
+ if (!subscription.manager.deliver(subscription, moqtObject)) {
4917
+ forceComplete = true;
4918
+ await recvStream.stopSending(1);
4919
+ break;
4808
4920
  }
4809
- throw new require_model.ProtocolViolationError("MOQtailClient", "Received fetch object after subgroup header");
4921
+ continue;
4810
4922
  }
4923
+ throw new require_model.ProtocolViolationError("MOQtailClient", "Received fetch object after subgroup header");
4811
4924
  }
4812
- } finally {
4813
- if (subgroupTimeoutId !== void 0) clearTimeout(subgroupTimeoutId);
4814
4925
  }
4815
- this.completeSubscription(subscription, forceComplete);
4816
- return;
4926
+ } finally {
4927
+ if (subgroupTimeoutId !== void 0) clearTimeout(subgroupTimeoutId);
4817
4928
  }
4818
- throw new require_model.ProtocolViolationError("MOQtailClient", "No subscription for received track alias");
4929
+ this.completeSubscription(subscription, forceComplete);
4930
+ return;
4819
4931
  }
4820
- } catch (error) {
4821
- throw error;
4822
- }
4823
- }
4824
- };
4825
- //#endregion
4826
- //#region src/client/track/object_cache.ts
4827
- /**
4828
- * Copyright 2025 The MOQtail Authors
4829
- *
4830
- * Licensed under the Apache License, Version 2.0 (the "License");
4831
- * you may not use this file except in compliance with the License.
4832
- * You may obtain a copy of the License at
4833
- *
4834
- * http://www.apache.org/licenses/LICENSE-2.0
4835
- *
4836
- * Unless required by applicable law or agreed to in writing, software
4837
- * distributed under the License is distributed on an "AS IS" BASIS,
4838
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4839
- * See the License for the specific language governing permissions and
4840
- * limitations under the License.
4841
- */
4842
- var MemoryObjectCache = class {
4843
- objects = [];
4844
- add(obj) {
4845
- const idx = this._findInsertIndex(obj);
4846
- this.objects.splice(idx, 0, obj);
4847
- }
4848
- getRange(start, end) {
4849
- const startIdx = start ? this._findIndex(start, false) : 0;
4850
- const endIdx = end ? this._findIndex(end, true) : this.objects.length;
4851
- return this.objects.slice(startIdx, endIdx);
4852
- }
4853
- getByLocation(location) {
4854
- const idx = this._findIndex(location, false);
4855
- const obj = this.objects[idx];
4856
- if (obj && obj.groupId === location.group && obj.objectId === location.object) return obj;
4857
- }
4858
- size() {
4859
- return this.objects.length;
4860
- }
4861
- clear() {
4862
- this.objects = [];
4863
- }
4864
- _findInsertIndex(obj) {
4865
- let low = 0, high = this.objects.length;
4866
- while (low < high) {
4867
- const mid = low + high >> 1;
4868
- const midObj = this.objects[mid];
4869
- if (!midObj) break;
4870
- if (new require_model.Location(midObj.groupId, midObj.objectId).compare(new require_model.Location(obj.groupId, obj.objectId)) < 0) low = mid + 1;
4871
- else high = mid;
4872
- }
4873
- return low;
4874
- }
4875
- _findIndex(location, exclusive) {
4876
- let low = 0, high = this.objects.length;
4877
- while (low < high) {
4878
- const mid = low + high >> 1;
4879
- const midObj = this.objects[mid];
4880
- if (!midObj) break;
4881
- const cmp = new require_model.Location(midObj.groupId, midObj.objectId).compare(location);
4882
- if (cmp < 0 || exclusive && cmp === 0) low = mid + 1;
4883
- else high = mid;
4884
- }
4885
- return low;
4886
- }
4887
- };
4888
- var RingBufferObjectCache = class {
4889
- buffer;
4890
- maxSize;
4891
- constructor(maxSize = 100) {
4892
- this.buffer = [];
4893
- this.maxSize = maxSize;
4894
- }
4895
- add(obj) {
4896
- const idx = this._findInsertIndex(obj);
4897
- this.buffer.splice(idx, 0, obj);
4898
- if (this.buffer.length > this.maxSize) this.buffer.shift();
4899
- }
4900
- getRange(start, end) {
4901
- const startIdx = start ? this._findIndex(start, false) : 0;
4902
- const endIdx = end ? this._findIndex(end, true) : this.buffer.length;
4903
- return this.buffer.slice(startIdx, endIdx);
4904
- }
4905
- getByLocation(location) {
4906
- const idx = this._findIndex(location, false);
4907
- const obj = this.buffer[idx];
4908
- if (obj && obj.groupId === location.group && obj.objectId === location.object) return obj;
4909
- }
4910
- size() {
4911
- return this.buffer.length;
4912
- }
4913
- clear() {
4914
- this.buffer = [];
4915
- }
4916
- _findInsertIndex(obj) {
4917
- let low = 0, high = this.buffer.length;
4918
- while (low < high) {
4919
- const mid = low + high >> 1;
4920
- const midObj = this.buffer[mid];
4921
- if (!midObj) break;
4922
- if (new require_model.Location(midObj.groupId, midObj.objectId).compare(new require_model.Location(obj.groupId, obj.objectId)) < 0) low = mid + 1;
4923
- else high = mid;
4924
- }
4925
- return low;
4926
- }
4927
- _findIndex(location, exclusive) {
4928
- let low = 0, high = this.buffer.length;
4929
- while (low < high) {
4930
- const mid = low + high >> 1;
4931
- const midObj = this.buffer[mid];
4932
- if (!midObj) break;
4933
- const cmp = new require_model.Location(midObj.groupId, midObj.objectId).compare(location);
4934
- if (cmp < 0 || exclusive && cmp === 0) low = mid + 1;
4935
- else high = mid;
4932
+ throw new require_model.ProtocolViolationError("MOQtailClient", "No subscription for received track alias");
4936
4933
  }
4937
- return low;
4938
4934
  }
4939
4935
  };
4940
- //#endregion
4941
4936
  Object.defineProperty(exports, "ControlRecvStream", {
4942
4937
  enumerable: true,
4943
4938
  get: function() {
@@ -4956,6 +4951,12 @@ Object.defineProperty(exports, "ControlStream", {
4956
4951
  return ControlStream;
4957
4952
  }
4958
4953
  });
4954
+ Object.defineProperty(exports, "DEFAULT_FILL_OPEN_TIMEOUT_MS", {
4955
+ enumerable: true,
4956
+ get: function() {
4957
+ return DEFAULT_FILL_OPEN_TIMEOUT_MS;
4958
+ }
4959
+ });
4959
4960
  Object.defineProperty(exports, "DEFAULT_MAX_FILTER_RANGES", {
4960
4961
  enumerable: true,
4961
4962
  get: function() {
@@ -5010,10 +5011,16 @@ Object.defineProperty(exports, "MOQtailClient", {
5010
5011
  return MOQtailClient;
5011
5012
  }
5012
5013
  });
5013
- Object.defineProperty(exports, "MemoryObjectCache", {
5014
+ Object.defineProperty(exports, "ObjectOrderer", {
5014
5015
  enumerable: true,
5015
5016
  get: function() {
5016
- return MemoryObjectCache;
5017
+ return ObjectOrderer;
5018
+ }
5019
+ });
5020
+ Object.defineProperty(exports, "ObjectStream", {
5021
+ enumerable: true,
5022
+ get: function() {
5023
+ return ObjectStream;
5017
5024
  }
5018
5025
  });
5019
5026
  Object.defineProperty(exports, "PublishNamespaceRequest", {
@@ -5034,12 +5041,6 @@ Object.defineProperty(exports, "PublishRequest", {
5034
5041
  return PublishRequest;
5035
5042
  }
5036
5043
  });
5037
- Object.defineProperty(exports, "RecvDatagramStream", {
5038
- enumerable: true,
5039
- get: function() {
5040
- return RecvDatagramStream;
5041
- }
5042
- });
5043
5044
  Object.defineProperty(exports, "RecvStream", {
5044
5045
  enumerable: true,
5045
5046
  get: function() {
@@ -5052,12 +5053,6 @@ Object.defineProperty(exports, "RequestStream", {
5052
5053
  return RequestStream;
5053
5054
  }
5054
5055
  });
5055
- Object.defineProperty(exports, "RingBufferObjectCache", {
5056
- enumerable: true,
5057
- get: function() {
5058
- return RingBufferObjectCache;
5059
- }
5060
- });
5061
5056
  Object.defineProperty(exports, "SendDatagramStream", {
5062
5057
  enumerable: true,
5063
5058
  get: function() {
@@ -5106,3 +5101,9 @@ Object.defineProperty(exports, "TrackStatusRequest", {
5106
5101
  return TrackStatusRequest;
5107
5102
  }
5108
5103
  });
5104
+ Object.defineProperty(exports, "errorMessage", {
5105
+ enumerable: true,
5106
+ get: function() {
5107
+ return errorMessage;
5108
+ }
5109
+ });