moqtail 0.13.0 → 0.15.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.
@@ -329,7 +329,9 @@ var RequestStream = class RequestStream {
329
329
  #receiveBuffer;
330
330
  /** Held for the stream's lifetime once {@link next} is first called. */
331
331
  #messageReader;
332
- constructor(biStream) {
332
+ #hooks;
333
+ constructor(biStream, hooks = {}) {
334
+ this.#hooks = hooks;
333
335
  this.#receiveBuffer = new require_model.ByteBuffer();
334
336
  this.#reader = biStream.readable.getReader();
335
337
  this.#writer = biStream.writable.getWriter();
@@ -345,10 +347,10 @@ var RequestStream = class RequestStream {
345
347
  * @throws :{@link ProtocolViolationError} If `first` is not one of the seven types
346
348
  * Table 5 marks `First`; those are the only ones allowed to open a request stream.
347
349
  */
348
- static async open(webTransport, first) {
350
+ static async open(webTransport, first, hooks = {}) {
349
351
  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`);
350
352
  const biStream = await webTransport.createBidirectionalStream();
351
- const requestStream = new RequestStream(biStream);
353
+ const requestStream = new RequestStream(biStream, hooks);
352
354
  requestStream.first = first;
353
355
  requestStream.openingType = first.getType();
354
356
  await requestStream.send(first);
@@ -372,6 +374,7 @@ var RequestStream = class RequestStream {
372
374
  await this.#writer.ready;
373
375
  await this.#writer.write(serialized.toUint8Array());
374
376
  require_logger.logger.debug("request_stream", `sent ${message.constructor.name}`);
377
+ this.#hooks.onMessageSent?.(message);
375
378
  } catch (error) {
376
379
  await this.close();
377
380
  const msg = error instanceof Error ? error.message : String(error);
@@ -384,8 +387,7 @@ var RequestStream = class RequestStream {
384
387
  await Promise.allSettled([this.#writer.close().catch(() => {}), this.#reader.cancel().catch(() => {})]);
385
388
  }
386
389
  /**
387
- * Cancels the request by resetting its stream with `code` (§3.3.2), which is how
388
- * draft-18 cancels a request now that the dedicated cancel messages are gone.
390
+ * Cancels the request by resetting its stream with `code`.
389
391
  */
390
392
  async reset(code) {
391
393
  require_logger.logger.debug("request_stream", `reset code=${code}`);
@@ -413,6 +415,7 @@ var RequestStream = class RequestStream {
413
415
  this.#receiveBuffer.commit();
414
416
  const msg = require_model.ControlMessage.deserialize(new require_model.FrozenByteBuffer(messageBytes));
415
417
  controller.enqueue(msg);
418
+ this.#hooks.onMessageReceived?.(msg);
416
419
  continue;
417
420
  }
418
421
  const readResult = await this.#reader.read();
@@ -446,6 +449,118 @@ var RequestStream = class RequestStream {
446
449
  }
447
450
  };
448
451
  //#endregion
452
+ //#region src/client/data_event.ts
453
+ /**
454
+ * Copyright 2026 The MOQtail Authors
455
+ *
456
+ * Licensed under the Apache License, Version 2.0 (the "License");
457
+ * you may not use this file except in compliance with the License.
458
+ * You may obtain a copy of the License at
459
+ *
460
+ * http://www.apache.org/licenses/LICENSE-2.0
461
+ *
462
+ * Unless required by applicable law or agreed to in writing, software
463
+ * distributed under the License is distributed on an "AS IS" BASIS,
464
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
465
+ * See the License for the specific language governing permissions and
466
+ * limitations under the License.
467
+ */
468
+ let lastStreamId = 0;
469
+ function locTimestampOf(properties) {
470
+ if (!properties) return void 0;
471
+ for (const pair of properties) {
472
+ const timestamp = require_model.Timestamp.fromKeyValuePair(pair);
473
+ if (timestamp) return timestamp.timestamp;
474
+ }
475
+ }
476
+ /**
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.
479
+ */
480
+ var DataStreamReporter = class {
481
+ direction;
482
+ observer;
483
+ streamId = ++lastStreamId;
484
+ #hasEnded = false;
485
+ constructor(direction, observer) {
486
+ this.direction = direction;
487
+ this.observer = observer;
488
+ }
489
+ header(header) {
490
+ if (!this.observer) return;
491
+ const fullTrackName = this.observer.fullTrackNameOf?.(header);
492
+ const event = require_model.Header.isFetch(header) ? {
493
+ ...this.#base("header"),
494
+ stream: "fetch",
495
+ requestId: header.requestId
496
+ } : {
497
+ ...this.#base("header"),
498
+ stream: "subgroup",
499
+ trackAlias: header.trackAlias,
500
+ groupId: header.groupId,
501
+ ...header.subgroupId !== void 0 && { subgroupId: header.subgroupId }
502
+ };
503
+ if (fullTrackName) event.fullTrackName = fullTrackName;
504
+ this.#emit(event);
505
+ }
506
+ /** `header` is the stream's own: a subgroup object takes its group and subgroup from it. */
507
+ object(header, object) {
508
+ if (!this.observer) return;
509
+ let event;
510
+ if (object instanceof require_model.FetchObject) {
511
+ if (object.kind !== "object") return;
512
+ event = {
513
+ ...this.#base("object"),
514
+ groupId: object.location.group,
515
+ subgroupId: object.subgroupId,
516
+ objectId: object.location.object,
517
+ payloadLength: object.payload?.byteLength ?? 0
518
+ };
519
+ const locTimestamp = locTimestampOf(object.properties);
520
+ if (locTimestamp !== void 0) event.locTimestamp = locTimestamp;
521
+ } else {
522
+ if (require_model.Header.isFetch(header)) return;
523
+ event = {
524
+ ...this.#base("object"),
525
+ groupId: header.groupId,
526
+ objectId: object.objectId,
527
+ payloadLength: object.payload?.byteLength ?? 0,
528
+ ...header.subgroupId !== void 0 && { subgroupId: header.subgroupId },
529
+ ...object.objectStatus !== null && { objectStatus: object.objectStatus }
530
+ };
531
+ const locTimestamp = locTimestampOf(object.properties);
532
+ if (locTimestamp !== void 0) event.locTimestamp = locTimestamp;
533
+ }
534
+ this.#emit(event);
535
+ }
536
+ /** Reports how the stream ended. Only the first call counts. */
537
+ end(reason, resetCode) {
538
+ if (this.#hasEnded) return;
539
+ this.#hasEnded = true;
540
+ if (!this.observer) return;
541
+ this.#emit({
542
+ ...this.#base("end"),
543
+ reason,
544
+ ...resetCode !== void 0 && { resetCode }
545
+ });
546
+ }
547
+ #base(kind) {
548
+ return {
549
+ kind,
550
+ direction: this.direction,
551
+ streamId: this.streamId,
552
+ at: performance.now()
553
+ };
554
+ }
555
+ #emit(event) {
556
+ try {
557
+ this.observer.onDataEvent(event);
558
+ } catch (error) {
559
+ require_logger.logger.warn("data_event", "onDataEvent threw", error);
560
+ }
561
+ }
562
+ };
563
+ //#endregion
449
564
  //#region src/client/data_stream.ts
450
565
  /**
451
566
  * Copyright 2025 The MOQtail Authors
@@ -468,27 +583,31 @@ var SendStream = class SendStream {
468
583
  #fetchPrevCtx;
469
584
  #writer;
470
585
  #groupOrder;
586
+ #reporter;
471
587
  onDataSent;
472
- constructor(header, writer, onDataSent, groupOrder = 0) {
588
+ constructor(header, writer, reporter, onDataSent, groupOrder = 0) {
473
589
  this.header = header;
474
590
  if (onDataSent) this.onDataSent = onDataSent;
475
591
  this.#writer = writer;
592
+ this.#reporter = reporter;
476
593
  this.#groupOrder = groupOrder;
477
594
  }
478
- static async new(writeStream, header, onDataSent, groupOrder = 0) {
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) {
479
597
  const writer = writeStream.getWriter();
480
598
  const serializedHeader = header.serialize().toUint8Array();
481
599
  await writer.write(serializedHeader);
482
600
  if (onDataSent) onDataSent(header);
601
+ const reporter = new DataStreamReporter("out", observer);
602
+ reporter.header(header);
483
603
  require_logger.logger.debug("data_stream", `SendStream opened type=${header.type}`);
484
- return new SendStream(header, writer, onDataSent, groupOrder);
604
+ return new SendStream(header, writer, reporter, onDataSent, groupOrder);
485
605
  }
486
606
  async write(object) {
487
607
  let serializedObject;
488
608
  if (object instanceof require_model.FetchObject) {
489
609
  serializedObject = object.serialize(this.#fetchPrevCtx, this.#groupOrder).toUint8Array();
490
- const newCtx = object.toContext();
491
- if (newCtx) this.#fetchPrevCtx = newCtx;
610
+ this.#fetchPrevCtx = object.nextContext(this.#fetchPrevCtx);
492
611
  } else {
493
612
  if (this.#lastObjectId !== void 0 && object.objectId <= this.#lastObjectId) {
494
613
  require_logger.logger.error("data_stream", `SendStream out-of-order objectId=${object.objectId} lastObjectId=${this.#lastObjectId}`);
@@ -497,19 +616,27 @@ var SendStream = class SendStream {
497
616
  serializedObject = object.serialize(this.#lastObjectId).toUint8Array();
498
617
  this.#lastObjectId = object.objectId;
499
618
  }
500
- await this.#writer.write(serializedObject);
619
+ try {
620
+ await this.#writer.write(serializedObject);
621
+ } catch (error) {
622
+ this.#reporter.end("error");
623
+ throw error;
624
+ }
501
625
  if (this.onDataSent) this.onDataSent(object);
626
+ this.#reporter.object(this.header, object);
502
627
  }
503
628
  async close() {
504
629
  if (this.#writer) {
505
630
  require_logger.logger.debug("data_stream", `SendStream closed type=${this.header.type}`);
506
631
  await this.#writer.close();
632
+ this.#reporter.end("fin");
507
633
  }
508
634
  }
509
635
  /** Abruptly tears the stream down, so the peer reads back `code` (§3.3.3). */
510
636
  async reset(code) {
511
637
  require_logger.logger.debug("data_stream", `SendStream reset type=${this.header.type} code=${code}`);
512
638
  await this.#writer.abort(streamResetReason(code)).catch(() => {});
639
+ this.#reporter.end("reset", code);
513
640
  }
514
641
  };
515
642
  function withTimeout(promise, ms, errorMsg) {
@@ -527,10 +654,12 @@ var RecvStream = class RecvStream {
527
654
  #reader;
528
655
  #internalBuffer;
529
656
  #groupOrder;
657
+ #reporter;
530
658
  onDataReceived;
531
- constructor(header, reader, internalBuffer, partialDataTimeout, onDataReceived, groupOrder = 0) {
659
+ constructor(header, reader, internalBuffer, reporter, partialDataTimeout, onDataReceived, groupOrder = 0) {
532
660
  this.header = header;
533
661
  this.#reader = reader;
662
+ this.#reporter = reporter;
534
663
  this.#internalBuffer = internalBuffer;
535
664
  this.#partialDataTimeout = partialDataTimeout;
536
665
  this.#groupOrder = groupOrder;
@@ -543,8 +672,9 @@ var RecvStream = class RecvStream {
543
672
  /**
544
673
  * @param resolveGroupOrder - Consulted once the FETCH header names its request, since
545
674
  * Group ID deltas on the stream are signed by the Group Order the request negotiated.
675
+ * @param observer - Receives a {@link DataEvent} for the header, each object, and the stream's end.
546
676
  */
547
- static async new(readStream, partialDataTimeout, onDataReceived, resolveGroupOrder) {
677
+ static async new(readStream, partialDataTimeout, onDataReceived, resolveGroupOrder, observer) {
548
678
  const reader = readStream.getReader();
549
679
  const internalBuffer = new require_model.ByteBuffer();
550
680
  let headerInstance;
@@ -560,7 +690,6 @@ var RecvStream = class RecvStream {
560
690
  internalBuffer.checkpoint();
561
691
  headerInstance = require_model.Header.deserialize(internalBuffer);
562
692
  internalBuffer.commit();
563
- if (onDataReceived) onDataReceived(headerInstance);
564
693
  break;
565
694
  } catch (e) {
566
695
  if (e instanceof require_model.NotEnoughBytesError) {
@@ -575,9 +704,11 @@ var RecvStream = class RecvStream {
575
704
  throw asStreamResetError("RecvStream.new", error);
576
705
  }
577
706
  if (onDataReceived) onDataReceived(headerInstance);
707
+ const reporter = new DataStreamReporter("in", observer);
708
+ reporter.header(headerInstance);
578
709
  require_logger.logger.debug("data_stream", `RecvStream opened type=${headerInstance.type}`);
579
710
  const groupOrder = require_model.Header.isFetch(headerInstance) && resolveGroupOrder ? resolveGroupOrder(headerInstance) : 0;
580
- return new RecvStream(headerInstance, reader, internalBuffer, partialDataTimeout, onDataReceived, groupOrder);
711
+ return new RecvStream(headerInstance, reader, internalBuffer, reporter, partialDataTimeout, onDataReceived, groupOrder);
581
712
  }
582
713
  async #ingestLoop(controller) {
583
714
  try {
@@ -589,8 +720,7 @@ var RecvStream = class RecvStream {
589
720
  let object;
590
721
  if (require_model.Header.isFetch(this.header)) {
591
722
  object = require_model.FetchObject.deserialize(this.#internalBuffer, fetchPrevCtx, this.#groupOrder);
592
- const newCtx = object.toContext();
593
- if (newCtx) fetchPrevCtx = newCtx;
723
+ fetchPrevCtx = object.nextContext(fetchPrevCtx);
594
724
  } else {
595
725
  object = require_model.SubgroupObject.deserialize(this.#internalBuffer, require_model.SubgroupHeaderType.hasProperties(this.header.type), previousObjectId);
596
726
  this.header.resolveSubgroupId(object.objectId);
@@ -599,10 +729,12 @@ var RecvStream = class RecvStream {
599
729
  this.#internalBuffer.commit();
600
730
  controller.enqueue(object);
601
731
  if (this.onDataReceived) this.onDataReceived(object);
732
+ this.#reporter.object(this.header, object);
602
733
  continue;
603
734
  } catch (e) {
604
735
  if (e instanceof require_model.NotEnoughBytesError) this.#internalBuffer.restore();
605
736
  else {
737
+ this.#reporter.end("error");
606
738
  controller.error(e);
607
739
  break;
608
740
  }
@@ -614,9 +746,11 @@ var RecvStream = class RecvStream {
614
746
  if (done) {
615
747
  if (this.#internalBuffer.remaining > 0) {
616
748
  require_logger.logger.error("data_stream", `RecvStream closed with incomplete data remaining=${this.#internalBuffer.remaining}`);
749
+ this.#reporter.end("error");
617
750
  controller.error(new require_model.ProtocolViolationError("RecvStream", `Stream closed with incomplete object data. Remaining: ${this.#internalBuffer.remaining} bytes.`));
618
751
  } else {
619
752
  require_logger.logger.debug("data_stream", `RecvStream closed type=${this.header.type}`);
753
+ this.#reporter.end("fin");
620
754
  controller.close();
621
755
  }
622
756
  break;
@@ -625,9 +759,12 @@ var RecvStream = class RecvStream {
625
759
  }
626
760
  } catch (error) {
627
761
  const peerReset = streamResetCodeOf(error);
628
- if (peerReset !== void 0) require_logger.logger.debug("data_stream", `RecvStream reset by peer code=${require_model.StreamResetCode[peerReset]}`);
629
- else {
762
+ if (peerReset !== void 0) {
763
+ require_logger.logger.debug("data_stream", `RecvStream reset by peer code=${require_model.StreamResetCode[peerReset]}`);
764
+ this.#reporter.end("reset", peerReset);
765
+ } else {
630
766
  require_logger.logger.error("data_stream", "RecvStream ingest loop error", error);
767
+ this.#reporter.end("error");
631
768
  await this.#reader.cancel(streamResetReason(0)).catch(() => {});
632
769
  }
633
770
  controller.error(asStreamResetError("RecvStream", error));
@@ -763,21 +900,6 @@ var PublishNamespaceRequest = class {
763
900
  };
764
901
  //#endregion
765
902
  //#region src/client/request/fetch.ts
766
- /**
767
- * Copyright 2025 The MOQtail Authors
768
- *
769
- * Licensed under the Apache License, Version 2.0 (the "License");
770
- * you may not use this file except in compliance with the License.
771
- * You may obtain a copy of the License at
772
- *
773
- * http://www.apache.org/licenses/LICENSE-2.0
774
- *
775
- * Unless required by applicable law or agreed to in writing, software
776
- * distributed under the License is distributed on an "AS IS" BASIS,
777
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
778
- * See the License for the specific language governing permissions and
779
- * limitations under the License.
780
- */
781
903
  var FetchRequest = class {
782
904
  requestId;
783
905
  message;
@@ -786,6 +908,7 @@ var FetchRequest = class {
786
908
  promise;
787
909
  controller;
788
910
  stream;
911
+ onEndOfRange;
789
912
  isActive = true;
790
913
  isResolved = false;
791
914
  constructor(message) {
@@ -820,21 +943,36 @@ var FetchRequest = class {
820
943
  }
821
944
  };
822
945
  //#endregion
823
- //#region src/client/request/subscribe.ts
946
+ //#region src/client/types.ts
824
947
  /**
825
- * Copyright 2025 The MOQtail Authors
826
- *
827
- * Licensed under the Apache License, Version 2.0 (the "License");
828
- * you may not use this file except in compliance with the License.
829
- * You may obtain a copy of the License at
948
+ * Default for {@link MOQtailClientOptions.trackAliasResolutionTimeoutMs}: how long a
949
+ * data stream waits for the control message that establishes its track alias.
830
950
  *
831
- * http://www.apache.org/licenses/LICENSE-2.0
951
+ * A subscription's data streams and the SUBSCRIBE_OK naming their alias travel on
952
+ * separate streams, so nothing orders them; the data can arrive first. Waiting costs
953
+ * a stalled reader, giving up costs the whole subgroup, so the wait is generous.
954
+ */
955
+ const DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS = 2e3;
956
+ /**
957
+ * Default for {@link MOQtailClientOptions.switchDrainTimeoutMs}: how long a track a
958
+ * soft switch handed over from may stay quiet before it is retired anyway.
832
959
  *
833
- * Unless required by applicable law or agreed to in writing, software
834
- * distributed under the License is distributed on an "AS IS" BASIS,
835
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
836
- * See the License for the specific language governing permissions and
837
- * limitations under the License.
960
+ * A soft switch leaves that track delivering up to the group the new one starts at,
961
+ * so the two meet without a hole, and a PUBLISH_DONE normally ends it. This is the
962
+ * backstop for a publisher that never sends one.
963
+ */
964
+ const DEFAULT_SWITCH_DRAIN_TIMEOUT_MS = 2e3;
965
+ /**
966
+ * @public
967
+ * The MAX_FILTER_RANGES a client advertises when its setup options set none: how
968
+ * many Range Filter ranges it applies, in total, for one subscription or fetch.
969
+ */
970
+ const DEFAULT_MAX_FILTER_RANGES = 32n;
971
+ //#endregion
972
+ //#region src/client/request/subscribe.ts
973
+ /**
974
+ * Represents an active subscription request in MOQT, implementing `PromiseLike`
975
+ * for convenient async resolution when subscription setup succeeds or fails.
838
976
  */
839
977
  var SubscribeRequest = class {
840
978
  requestId;
@@ -846,9 +984,19 @@ var SubscribeRequest = class {
846
984
  forward;
847
985
  subscribeParameters;
848
986
  earlyDiscardPolicy;
987
+ onEndOfRange;
849
988
  largestLocation;
989
+ /**
990
+ * The publisher's Largest Object as of the last SUBSCRIBE_OK or REQUEST_UPDATE_OK,
991
+ * which is where a fill fetch stream stops.
992
+ */
993
+ fillBoundary;
994
+ /** EXPIRES from the last SUBSCRIBE_OK or REQUEST_UPDATE_OK, in milliseconds. */
995
+ expires;
850
996
  streamsAccepted = 0n;
851
997
  expectedStreams;
998
+ /** The Subscription managing this request's output stream once switching is involved. */
999
+ manager;
852
1000
  controller;
853
1001
  stream;
854
1002
  #promise;
@@ -857,9 +1005,9 @@ var SubscribeRequest = class {
857
1005
  constructor(msg) {
858
1006
  this.requestId = msg.requestId;
859
1007
  this.fullTrackName = msg.fullTrackName;
860
- const filter = msg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
861
- this.startLocation = filter?.startLocation;
862
- this.endGroup = filter?.endGroup;
1008
+ const filter = msg.parameters.find(require_model.MessageParameter.isLocationFilter);
1009
+ this.startLocation = filter?.absoluteStart;
1010
+ this.endGroup = filter?.endLocation()?.group;
863
1011
  const subPriority = msg.parameters.find(require_model.MessageParameter.isSubscriberPriority);
864
1012
  this.priority = subPriority?.priority ?? 128;
865
1013
  const fwd = msg.parameters.find(require_model.MessageParameter.isForward);
@@ -874,30 +1022,36 @@ var SubscribeRequest = class {
874
1022
  });
875
1023
  require_logger.logger.debug("request/subscribe", `created requestId=${this.requestId} ftn="${this.fullTrackName}" priority=${this.priority} forward=${this.forward}`);
876
1024
  }
1025
+ /**
1026
+ * Updates subscription parameters in-place when a `RequestUpdate` message is received.
1027
+ */
877
1028
  update(msg) {
878
- const filter = msg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
879
- if (filter?.startLocation !== void 0) this.startLocation = filter.startLocation;
880
- if (filter?.endGroup !== void 0) this.endGroup = filter.endGroup;
1029
+ const filter = msg.parameters.find(require_model.MessageParameter.isLocationFilter);
1030
+ if (filter) {
1031
+ this.startLocation = filter.absoluteStart;
1032
+ this.endGroup = filter.endLocation()?.group;
1033
+ }
881
1034
  for (const param of msg.parameters) if (require_model.MessageParameter.isSubscriberPriority?.(param)) this.priority = param.priority;
882
1035
  else if (require_model.MessageParameter.isForward?.(param)) this.forward = param.forward;
883
1036
  if (typeof require_model.applyMessageParameterUpdate === "function") require_model.applyMessageParameterUpdate(this.subscribeParameters, msg.parameters);
884
1037
  }
885
- switch(newTrackName, newParameters) {
886
- this.fullTrackName = newTrackName;
887
- this.subscribeParameters = newParameters;
888
- this.#promise = new Promise((resolve, reject) => {
889
- this.#resolve = resolve;
890
- this.#reject = reject;
891
- });
892
- }
1038
+ /**
1039
+ * Marks this subscription request as canceled.
1040
+ */
893
1041
  unsubscribe() {
894
1042
  this.isCanceled = true;
895
1043
  }
1044
+ /**
1045
+ * Resolves the internal promise with a `SubscribeOk` or `RequestError`.
1046
+ */
896
1047
  resolve(value) {
897
1048
  if (value instanceof require_model.RequestError) require_logger.logger.error("request/subscribe", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
898
1049
  else if (value instanceof require_model.SubscribeOk) require_logger.logger.debug("request/subscribe", `resolved with OK requestId=${this.requestId} trackAlias=${value.trackAlias}`);
899
1050
  this.#resolve(value);
900
1051
  }
1052
+ /**
1053
+ * Rejects the internal promise with an error/reason.
1054
+ */
901
1055
  reject(reason) {
902
1056
  require_logger.logger.error("request/subscribe", `rejected requestId=${this.requestId}`, reason);
903
1057
  this.#reject(reason);
@@ -912,6 +1066,122 @@ var SubscribeRequest = class {
912
1066
  return this.#promise.finally(onfinally);
913
1067
  }
914
1068
  };
1069
+ /**
1070
+ * Owns the single consumer-facing stream for a SUBSCRIBE that may be switched to a
1071
+ * new track one or more times. A soft switch can keep producing from the old track
1072
+ * for an unknown time after SUBSCRIBE_OK, and a second switch may be issued before the
1073
+ * first target ever delivers anything, so only the first object actually delivered by
1074
+ * the newest tracked request is the guarantee that nothing older will send again.
1075
+ *
1076
+ * That first delivery is the handover, not the end of the old track: a soft switch
1077
+ * leaves it delivering up to the group the new one starts at, so the two meet without
1078
+ * a hole. Those objects keep coming through here until the publisher says the
1079
+ * subscription is done, or until it has been quiet long enough to say so itself.
1080
+ */
1081
+ var Subscription = class {
1082
+ controller;
1083
+ stream;
1084
+ /** Oldest first; the last entry is the newest switch target still racing to produce data. */
1085
+ #requests;
1086
+ /**
1087
+ * Requests a soft switch handed over from, still delivering the tail of what they
1088
+ * were told to finish, each with the timer that retires it if it goes quiet.
1089
+ */
1090
+ #draining = /* @__PURE__ */ new Map();
1091
+ /** Switch targets whose handover drains what it supersedes rather than cutting it. */
1092
+ #drainsSuperseded = /* @__PURE__ */ new WeakSet();
1093
+ /** Set once by `MOQtailClient.switch`; invoked with everything older on cutover. */
1094
+ onSuperseded;
1095
+ /** Set by the client to decide whether draining a request should continue. */
1096
+ onDrainDecision = () => true;
1097
+ /**
1098
+ * How long a drained request may stay quiet before it is retired anyway, in
1099
+ * milliseconds. The publisher normally ends the drain with a PUBLISH_DONE; this is
1100
+ * what keeps a request that never gets one from being tracked forever.
1101
+ */
1102
+ drainTimeoutMs = DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
1103
+ constructor(initial) {
1104
+ this.stream = initial.stream;
1105
+ this.controller = initial.controller;
1106
+ initial.manager = this;
1107
+ this.#requests = [initial];
1108
+ }
1109
+ /** Requests still tracked, oldest first, draining ones last. */
1110
+ get requests() {
1111
+ return [...this.#requests, ...this.#draining.keys()];
1112
+ }
1113
+ /** The request most recently switched to; must deliver data to win the handover. */
1114
+ get newest() {
1115
+ return this.#requests[this.#requests.length - 1];
1116
+ }
1117
+ /**
1118
+ * Track a newly issued switch target alongside whatever is still delivering.
1119
+ *
1120
+ * `drainSuperseded` says what its handover does to the requests it takes over from:
1121
+ * a soft switch leaves them delivering to the end of what the publisher was told to
1122
+ * finish, a hard one retires them on the spot.
1123
+ */
1124
+ addSwitchTarget(request, drainSuperseded = false) {
1125
+ request.manager = this;
1126
+ if (drainSuperseded) this.#drainsSuperseded.add(request);
1127
+ this.#requests.push(request);
1128
+ }
1129
+ /** Stop tracking `request` (e.g. it naturally completed without ever losing/winning a handover). */
1130
+ drop(request) {
1131
+ this.#clearDrain(request);
1132
+ this.#requests = this.#requests.filter((r) => r !== request);
1133
+ }
1134
+ /** Stop tracking everything (used when the whole switch chain is torn down at once). */
1135
+ clear() {
1136
+ for (const request of [...this.#draining.keys()]) this.#clearDrain(request);
1137
+ this.#requests = [];
1138
+ }
1139
+ /** Starts, or on each further object restarts, the quiet period that ends a drain. */
1140
+ #keepDraining(request) {
1141
+ this.#clearDrain(request);
1142
+ this.#draining.set(request, setTimeout(() => {
1143
+ this.#draining.delete(request);
1144
+ require_logger.logger.debug("Subscription", `drain of request ${request.requestId} ended on silence`);
1145
+ this.onSuperseded?.([request]);
1146
+ }, this.drainTimeoutMs));
1147
+ }
1148
+ #clearDrain(request) {
1149
+ const timeout = this.#draining.get(request);
1150
+ if (timeout === void 0) return;
1151
+ clearTimeout(timeout);
1152
+ this.#draining.delete(request);
1153
+ }
1154
+ /**
1155
+ * Delivers an object received for `request`. The first object delivered by the
1156
+ * newest tracked request retires everything older — only then is it guaranteed no
1157
+ * more data is coming from them.
1158
+ *
1159
+ * Returns `true` if the object was delivered to the caller,
1160
+ * `false` if it was not consumed, and client should cancel the stream.
1161
+ */
1162
+ deliver(request, obj) {
1163
+ if (this.#draining.has(request)) {
1164
+ if (this.onDrainDecision?.(request)) {
1165
+ this.#keepDraining(request);
1166
+ this.controller.enqueue(obj);
1167
+ return true;
1168
+ }
1169
+ return false;
1170
+ }
1171
+ if (!this.#requests.includes(request)) {
1172
+ require_logger.logger.warn("Subscription", `discarding object from superseded request ${request.requestId}`);
1173
+ return false;
1174
+ }
1175
+ if (request === this.newest && this.#requests.length > 1) {
1176
+ const superseded = this.#requests.slice(0, -1);
1177
+ this.#requests = [request];
1178
+ if (this.#drainsSuperseded.has(request)) for (const old of superseded) this.#keepDraining(old);
1179
+ else this.onSuperseded?.(superseded);
1180
+ }
1181
+ this.controller.enqueue(obj);
1182
+ return true;
1183
+ }
1184
+ };
915
1185
  //#endregion
916
1186
  //#region src/client/request/publish.ts
917
1187
  /**
@@ -1052,9 +1322,9 @@ const handlerPublish = async (client, msg, stream) => {
1052
1322
  await stream.send(new require_model.RequestOk());
1053
1323
  };
1054
1324
  //#endregion
1055
- //#region src/client/handler/publish_blocked.ts
1325
+ //#region src/client/handler/publish_namespace.ts
1056
1326
  /**
1057
- * Copyright 2026 The MOQtail Authors
1327
+ * Copyright 2025 The MOQtail Authors
1058
1328
  *
1059
1329
  * Licensed under the Apache License, Version 2.0 (the "License");
1060
1330
  * you may not use this file except in compliance with the License.
@@ -1068,16 +1338,15 @@ const handlerPublish = async (client, msg, stream) => {
1068
1338
  * See the License for the specific language governing permissions and
1069
1339
  * limitations under the License.
1070
1340
  */
1071
- const handlerPublishBlocked = async (client, msg, stream) => {
1072
- const first = stream.first;
1073
- if (!(first instanceof require_model.SubscribeTracks)) throw new require_model.ProtocolViolationError("handlerPublishBlocked", "PUBLISH_BLOCKED on a stream this side did not open with SUBSCRIBE_TRACKS");
1074
- require_logger.logger.log("handler/publish_blocked", "prefix", first.trackNamespacePrefix.toUtf8Path(), "suffix", msg.trackNamespaceSuffix.toUtf8Path());
1075
- client.onPeerPublishBlocked?.(first.trackNamespacePrefix, msg);
1341
+ const handlerPublishNamespace = async (client, msg, stream) => {
1342
+ require_logger.logger.log("handler/publish_namespace", "namespace", msg.trackNamespace.toUtf8Path());
1343
+ if (client.onNamespacePublished) client.onNamespacePublished(msg);
1344
+ await stream.send(new require_model.RequestOk());
1076
1345
  };
1077
1346
  //#endregion
1078
- //#region src/client/handler/publish_namespace.ts
1347
+ //#region src/client/handler/publish_skipped.ts
1079
1348
  /**
1080
- * Copyright 2025 The MOQtail Authors
1349
+ * Copyright 2026 The MOQtail Authors
1081
1350
  *
1082
1351
  * Licensed under the Apache License, Version 2.0 (the "License");
1083
1352
  * you may not use this file except in compliance with the License.
@@ -1091,42 +1360,77 @@ const handlerPublishBlocked = async (client, msg, stream) => {
1091
1360
  * See the License for the specific language governing permissions and
1092
1361
  * limitations under the License.
1093
1362
  */
1094
- const handlerPublishNamespace = async (client, msg, stream) => {
1095
- require_logger.logger.log("handler/publish_namespace", "namespace", msg.trackNamespace.toUtf8Path());
1096
- if (client.onNamespacePublished) client.onNamespacePublished(msg);
1097
- await stream.send(new require_model.RequestOk());
1363
+ const handlerPublishSkipped = async (client, msg, stream) => {
1364
+ const first = stream.first;
1365
+ if (!(first instanceof require_model.SubscribeTracks)) throw new require_model.ProtocolViolationError("handlerPublishSkipped", "PUBLISH_SKIPPED on a stream this side did not open with SUBSCRIBE_TRACKS");
1366
+ require_logger.logger.log("handler/publish_skipped", "prefix", first.trackNamespacePrefix.toUtf8Path(), "suffix", msg.trackNamespaceSuffix.toUtf8Path());
1367
+ client.onPeerPublishSkipped?.(first.trackNamespacePrefix, msg);
1098
1368
  };
1099
1369
  //#endregion
1100
- //#region src/util/simple_lock.ts
1101
- var SimpleLock = class {
1102
- acquiredLock = false;
1103
- contQueue = [];
1104
- /**
1105
- * Acquires the lock. If the lock is already held, waits until it is released.
1106
- */
1107
- async acquire() {
1108
- if (!this.acquiredLock) this.acquiredLock = true;
1109
- else return new Promise((resolve, _) => {
1110
- this.contQueue.push(resolve);
1111
- });
1370
+ //#region src/client/publication/subgroup.ts
1371
+ /**
1372
+ * Copyright 2026 The MOQtail Authors
1373
+ *
1374
+ * Licensed under the Apache License, Version 2.0 (the "License");
1375
+ * you may not use this file except in compliance with the License.
1376
+ * You may obtain a copy of the License at
1377
+ *
1378
+ * http://www.apache.org/licenses/LICENSE-2.0
1379
+ *
1380
+ * Unless required by applicable law or agreed to in writing, software
1381
+ * distributed under the License is distributed on an "AS IS" BASIS,
1382
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1383
+ * See the License for the specific language governing permissions and
1384
+ * limitations under the License.
1385
+ */
1386
+ /** Groups kept behind the newest in {@link SubgroupIds}, for objects that arrive late. */
1387
+ const GROUPS_KEPT = 4n;
1388
+ /**
1389
+ * Resolves the Subgroup ID of Objects that leave it to their subgroup's first Object
1390
+ * ID (a `null` {@link MoqtObject.subgroupId}). An Object cannot tell that on its own
1391
+ * once the first one has gone by, so the first Object ID of each group is noted as
1392
+ * the Objects arrive, whether or not they are then sent.
1393
+ *
1394
+ * This assumes one subgroup per group, which is how this client publishes.
1395
+ */
1396
+ var SubgroupIds = class {
1397
+ #firstObject = /* @__PURE__ */ new Map();
1398
+ /** Notes `obj`. Call it for every Object the track produces, sent or not. */
1399
+ note(obj) {
1400
+ const group = obj.location.group;
1401
+ const first = this.#firstObject.get(group);
1402
+ if (first !== void 0 && first <= obj.location.object) return;
1403
+ this.#firstObject.set(group, obj.location.object);
1404
+ for (const old of this.#firstObject.keys()) if (old + GROUPS_KEPT < group) this.#firstObject.delete(old);
1112
1405
  }
1113
1406
  /**
1114
- * Releases the lock. If there are queued waiters, resumes the next one.
1407
+ * The Subgroup ID `obj` travels in, or `null` for a datagram. An Object whose
1408
+ * group was never noted is taken to be its subgroup's first.
1115
1409
  */
1116
- async release() {
1117
- if (this.contQueue.length === 0 && this.acquiredLock) {
1118
- this.acquiredLock = false;
1119
- return;
1120
- }
1121
- const continuation = this.contQueue.shift();
1122
- return new Promise((res) => {
1123
- continuation();
1124
- res();
1125
- });
1410
+ of(obj) {
1411
+ if (obj.isDatagram()) return null;
1412
+ return obj.subgroupId ?? this.#firstObject.get(obj.location.group) ?? obj.location.object;
1126
1413
  }
1127
1414
  };
1415
+ /**
1416
+ * The header for a subgroup stream that starts with `obj`.
1417
+ *
1418
+ * An Object that leaves its Subgroup ID to the first Object ID only gets that header
1419
+ * when it is the first: a stream that starts later — a filter dropped the Objects
1420
+ * before it, or the subscription joined mid-group — states the ID, or a receiver
1421
+ * would read the wrong one off it.
1422
+ */
1423
+ function subgroupHeaderFor(obj, subgroupId, trackAlias, publisherPriority, firstObject) {
1424
+ let headerType = obj.getSubgroupHeaderType(true, false, firstObject);
1425
+ if (obj.subgroupId === null && subgroupId !== obj.location.object) {
1426
+ const hasProperties = !!obj.properties && obj.properties.length > 0;
1427
+ headerType = require_model.SubgroupHeaderType.fromProperties(hasProperties, 2, true, false, firstObject);
1428
+ }
1429
+ const explicit = require_model.SubgroupHeaderType.hasExplicitSubgroupId(headerType) ? subgroupId : void 0;
1430
+ return new require_model.SubgroupHeader(headerType, trackAlias, obj.location.group, explicit, publisherPriority);
1431
+ }
1128
1432
  //#endregion
1129
- //#region src/client/util/priority.ts
1433
+ //#region src/client/publication/fetch.ts
1130
1434
  /**
1131
1435
  * Copyright 2025 The MOQtail Authors
1132
1436
  *
@@ -1142,16 +1446,84 @@ var SimpleLock = class {
1142
1446
  * See the License for the specific language governing permissions and
1143
1447
  * limitations under the License.
1144
1448
  */
1145
- function getTransportPriority(priority) {
1146
- priority = Math.max(0, Math.min(255, Math.round(priority)));
1147
- if (priority === 0) return Number.MAX_SAFE_INTEGER;
1148
- if (priority === 255) return 0;
1149
- return Math.round((255 - priority) * (Number.MAX_SAFE_INTEGER / 255));
1150
- }
1449
+ var FetchPublication = class {
1450
+ #requestId;
1451
+ #track;
1452
+ #startLocation;
1453
+ /** The last Location to send, inclusive. */
1454
+ #endLocation;
1455
+ #msg;
1456
+ #client;
1457
+ /** What the FETCH's Range Filters let through. */
1458
+ #filter;
1459
+ #sendStream;
1460
+ #objects;
1461
+ #isCanceled = false;
1462
+ /** `start` and `end` are the FETCH's range resolved against the Largest Object, inclusive. */
1463
+ constructor(client, track, fetchRequest, start, end) {
1464
+ this.#client = client;
1465
+ this.#requestId = fetchRequest.requestId;
1466
+ this.#track = track;
1467
+ this.#msg = fetchRequest;
1468
+ this.#startLocation = start;
1469
+ this.#endLocation = end;
1470
+ this.#filter = new require_model.CombinedFilter(fetchRequest.parameters);
1471
+ require_logger.logger.debug("publication/fetch", `created requestId=${this.#requestId}`);
1472
+ this.publish();
1473
+ }
1474
+ cancel() {
1475
+ require_logger.logger.debug("publication/fetch", `canceled requestId=${this.#requestId}`);
1476
+ this.#isCanceled = true;
1477
+ }
1478
+ /**
1479
+ * Resets the data stream this fetch is being delivered on, which §10.9.1 requires when
1480
+ * a REQUEST_UPDATE for a FETCH fails.
1481
+ */
1482
+ async resetDataStream(code) {
1483
+ require_logger.logger.debug("publication/fetch", `reset data stream requestId=${this.#requestId} code=${code}`);
1484
+ this.#isCanceled = true;
1485
+ await this.#sendStream?.reset(code);
1486
+ }
1487
+ async publish() {
1488
+ if (this.#isCanceled) return;
1489
+ if (!this.#track.trackSource.past) throw new require_model.MOQtailError("FetchPublication.publish, Track does not support fetch");
1490
+ require_logger.logger.debug("publication/fetch", `publishing requestId=${this.#requestId} start=${this.#startLocation} end=${this.#endLocation}`);
1491
+ try {
1492
+ const objects = await this.#track.trackSource.past.getRange(this.#startLocation);
1493
+ this.#objects = objects.filter((obj) => obj.location.compare(this.#endLocation) <= 0);
1494
+ const writeStream = await this.#client.webTransport.createUnidirectionalStream();
1495
+ const header = new require_model.FetchHeader(5, this.#requestId);
1496
+ this.#sendStream = await SendStream.new(writeStream, header, this.#client.onDataSent, require_model.MessageParameter.groupOrderOf(this.#msg.parameters), this.#client.dataStreamObserver(() => this.#track.fullTrackName));
1497
+ const subgroupIds = new SubgroupIds();
1498
+ let sent = 0;
1499
+ for (const obj of this.#objects) {
1500
+ subgroupIds.note(obj);
1501
+ if (!this.#filter.matches(obj, subgroupIds.of(obj))) continue;
1502
+ if (this.#isCanceled) {
1503
+ require_logger.logger.debug("publication/fetch", `aborted during publish requestId=${this.#requestId}`);
1504
+ await this.#sendStream.reset(1);
1505
+ this.#client.publications.delete(this.#requestId);
1506
+ return;
1507
+ }
1508
+ await this.#sendStream.write(obj.tryIntoFetchObject());
1509
+ sent++;
1510
+ }
1511
+ await this.#sendStream.close();
1512
+ require_logger.logger.debug("publication/fetch", `published requestId=${this.#requestId} objects=${sent} of ${this.#objects.length}`);
1513
+ this.#client.publications.delete(this.#requestId);
1514
+ } catch (error) {
1515
+ if (this.#isCanceled) return;
1516
+ await this.#sendStream?.reset(0);
1517
+ const message = error instanceof Error ? error.message : String(error);
1518
+ require_logger.logger.error("publication/fetch", `publish failed requestId=${this.#requestId}`, message);
1519
+ throw new require_model.InternalError("FetchPublication.publish", `Failed to publish: ${message}`);
1520
+ }
1521
+ }
1522
+ };
1151
1523
  //#endregion
1152
- //#region src/client/publication/subscribe.ts
1524
+ //#region src/client/util/validators.ts
1153
1525
  /**
1154
- * Copyright 2025 The MOQtail Authors
1526
+ * Copyright 2026 The MOQtail Authors
1155
1527
  *
1156
1528
  * Licensed under the Apache License, Version 2.0 (the "License");
1157
1529
  * you may not use this file except in compliance with the License.
@@ -1165,16 +1537,226 @@ function getTransportPriority(priority) {
1165
1537
  * See the License for the specific language governing permissions and
1166
1538
  * limitations under the License.
1167
1539
  */
1540
+ /** Returns true when `trackAlias` is a valid (non-negative) track alias. Zero is a legal value. */
1541
+ function isValidTrackAlias(trackAlias) {
1542
+ return trackAlias !== void 0 && trackAlias >= 0n;
1543
+ }
1168
1544
  /**
1169
- * @public
1170
- * Manages the publication of MOQT objects to a subscriber for a specific track.
1171
- * Handles live object streaming, subscription lifecycle, and stream management.
1545
+ * The REQUEST_ERROR INVALID_FILTER for a request whose Range Filters this client
1546
+ * cannot take: more ranges than the `limit` it advertised (with a limit of 0, any
1547
+ * filter at all), or a filter that cannot be applied. `undefined` when they are
1548
+ * fine, which includes carrying none.
1172
1549
  */
1173
- var SubscribePublication = class {
1174
- client;
1175
- track;
1176
- subscribeMsg;
1177
- requestStream;
1550
+ function rangeFilterRejection(params, limit) {
1551
+ try {
1552
+ assertWithinFilterRangeLimit(params, limit, "request");
1553
+ new require_model.CombinedFilter(params);
1554
+ for (const fill of params.filter(require_model.MessageParameter.isFillParameters)) new require_model.CombinedFilter(fill.parameters);
1555
+ return;
1556
+ } catch (error) {
1557
+ if (!(error instanceof require_model.InvalidFilterError)) throw error;
1558
+ return new require_model.RequestError(54, 0n, new require_model.ReasonPhrase(error.details));
1559
+ }
1560
+ }
1561
+ /**
1562
+ * Throws unless `params` stay within a MAX_FILTER_RANGES of `limit`: the peer's,
1563
+ * so a request it would have to refuse is never sent, or this client's own, for
1564
+ * a request it received.
1565
+ *
1566
+ * A limit of 0 allows no Range Filter parameter at all, not even a
1567
+ * zero-length removal. Otherwise the Ranges of every filter in the request count
1568
+ * against the limit together. FILL_PARAMETERS describes a separate fill fetch
1569
+ * stream, so the filters inside it count against a limit of their own.
1570
+ *
1571
+ * @throws :{@link InvalidFilterError} When the limit is exceeded.
1572
+ */
1573
+ function assertWithinFilterRangeLimit(params, limit, context) {
1574
+ const filters = params.filter(require_model.MessageParameter.isRangeFilter);
1575
+ if (filters.length > 0) {
1576
+ if (limit === 0n) throw new require_model.InvalidFilterError(context, "no range filters are allowed (MAX_FILTER_RANGES is 0)");
1577
+ const count = BigInt(filters.reduce((sum, f) => sum + f.rangeCount, 0));
1578
+ if (count > limit) throw new require_model.InvalidFilterError(context, `${count} filter ranges exceed MAX_FILTER_RANGES of ${limit}`);
1579
+ }
1580
+ for (const fill of params.filter(require_model.MessageParameter.isFillParameters)) assertWithinFilterRangeLimit(fill.parameters, limit, `${context} (FILL_PARAMETERS)`);
1581
+ }
1582
+ //#endregion
1583
+ //#region src/client/handler/fetch.ts
1584
+ /**
1585
+ * Copyright 2025 The MOQtail Authors
1586
+ *
1587
+ * Licensed under the Apache License, Version 2.0 (the "License");
1588
+ * you may not use this file except in compliance with the License.
1589
+ * You may obtain a copy of the License at
1590
+ *
1591
+ * http://www.apache.org/licenses/LICENSE-2.0
1592
+ *
1593
+ * Unless required by applicable law or agreed to in writing, software
1594
+ * distributed under the License is distributed on an "AS IS" BASIS,
1595
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1596
+ * See the License for the specific language governing permissions and
1597
+ * limitations under the License.
1598
+ */
1599
+ const handlerFetch = async (client, msg, stream) => {
1600
+ require_logger.logger.log("handler/fetch", "requestId", msg.requestId);
1601
+ const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
1602
+ if (filterRejection) {
1603
+ require_logger.logger.warn("handler/fetch", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
1604
+ await stream.send(filterRejection);
1605
+ return;
1606
+ }
1607
+ const fullTrackName = msg.fullTrackName;
1608
+ const track = client.trackSources.get(fullTrackName.toString());
1609
+ if (!track) {
1610
+ const response = new require_model.RequestError(16, 0n, new require_model.ReasonPhrase("Track does not exists"));
1611
+ await stream.send(response);
1612
+ return;
1613
+ }
1614
+ if (!track.trackSource.past) {
1615
+ const response = new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("Requested track does not support fetch"));
1616
+ await stream.send(response);
1617
+ return;
1618
+ }
1619
+ const largest = track.trackSource.live?.largestLocation ?? (await track.trackSource.past.getRange()).at(-1)?.location;
1620
+ const range = msg.locationFilter.fetchRange(largest);
1621
+ if (!range) {
1622
+ require_logger.logger.warn("handler/fetch", `requestId=${msg.requestId} selects nothing published (largest=${largest})`);
1623
+ const response = new require_model.RequestError(17, 0n, new require_model.ReasonPhrase("Nothing published in the requested range"));
1624
+ await stream.send(response);
1625
+ return;
1626
+ }
1627
+ const publication = new FetchPublication(client, track, msg, range.start, range.end);
1628
+ client.publications.set(msg.requestId, publication);
1629
+ const trackProperties = require_model.MessageParameter.includesProperties(msg.parameters) ? track.trackProperties ?? [] : [];
1630
+ const response = new require_model.FetchOk(false, range.end, [], trackProperties);
1631
+ await stream.send(response);
1632
+ };
1633
+ //#endregion
1634
+ //#region src/client/handler/fetch_ok.ts
1635
+ /**
1636
+ * Copyright 2025 The MOQtail Authors
1637
+ *
1638
+ * Licensed under the Apache License, Version 2.0 (the "License");
1639
+ * you may not use this file except in compliance with the License.
1640
+ * You may obtain a copy of the License at
1641
+ *
1642
+ * http://www.apache.org/licenses/LICENSE-2.0
1643
+ *
1644
+ * Unless required by applicable law or agreed to in writing, software
1645
+ * distributed under the License is distributed on an "AS IS" BASIS,
1646
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1647
+ * See the License for the specific language governing permissions and
1648
+ * limitations under the License.
1649
+ */
1650
+ const handlerFetchOk = async (client, msg, _stream, requestId) => {
1651
+ require_logger.logger.log("handler/fetch_ok", "requestId", requestId);
1652
+ const request = client.requests.get(requestId);
1653
+ if (request instanceof FetchRequest) {
1654
+ if (msg.trackProperties.length > 0) {
1655
+ const track = client.trackSources.get(request.message.fullTrackName.toString());
1656
+ if (track !== void 0) track.trackProperties = msg.trackProperties;
1657
+ }
1658
+ request.resolve(msg);
1659
+ } else throw new require_model.ProtocolViolationError("handlerFetchOk", `FETCH_OK on a stream with no pending fetch request (request id ${requestId})`);
1660
+ };
1661
+ //#endregion
1662
+ //#region src/client/handler/goaway.ts
1663
+ const handlerGoAway = async (client, msg) => {
1664
+ require_logger.logger.log("handler/goaway", "newSessionUri", msg.newSessionUri, "timeout", msg.timeout);
1665
+ if (client.goawayReceived) {
1666
+ await client.disconnect(new require_model.ProtocolViolationError("handler/goaway", "A second GOAWAY arrived on the control stream"));
1667
+ return;
1668
+ }
1669
+ client.goawayReceived = true;
1670
+ if (client.onGoaway) client.onGoaway(msg);
1671
+ };
1672
+ /**
1673
+ * GOAWAY on a request stream: the peer is migrating that one request (§10.4). The
1674
+ * request is re-issued on a fresh stream and the session, along with every other request
1675
+ * on it, carries on.
1676
+ */
1677
+ const handlerGoAwayOnRequestStream = async (client, msg, _stream, requestId) => {
1678
+ require_logger.logger.log("handler/goaway", `GOAWAY migrating request ${requestId}`, "timeout", msg.timeout);
1679
+ await client.migrateRequest(requestId, msg);
1680
+ };
1681
+ //#endregion
1682
+ //#region src/util/simple_lock.ts
1683
+ var SimpleLock = class {
1684
+ acquiredLock = false;
1685
+ contQueue = [];
1686
+ /**
1687
+ * Acquires the lock. If the lock is already held, waits until it is released.
1688
+ */
1689
+ async acquire() {
1690
+ if (!this.acquiredLock) this.acquiredLock = true;
1691
+ else return new Promise((resolve, _) => {
1692
+ this.contQueue.push(resolve);
1693
+ });
1694
+ }
1695
+ /**
1696
+ * Releases the lock. If there are queued waiters, resumes the next one.
1697
+ */
1698
+ async release() {
1699
+ if (this.contQueue.length === 0 && this.acquiredLock) {
1700
+ this.acquiredLock = false;
1701
+ return;
1702
+ }
1703
+ const continuation = this.contQueue.shift();
1704
+ return new Promise((res) => {
1705
+ continuation();
1706
+ res();
1707
+ });
1708
+ }
1709
+ };
1710
+ //#endregion
1711
+ //#region src/client/util/priority.ts
1712
+ /**
1713
+ * Copyright 2025 The MOQtail Authors
1714
+ *
1715
+ * Licensed under the Apache License, Version 2.0 (the "License");
1716
+ * you may not use this file except in compliance with the License.
1717
+ * You may obtain a copy of the License at
1718
+ *
1719
+ * http://www.apache.org/licenses/LICENSE-2.0
1720
+ *
1721
+ * Unless required by applicable law or agreed to in writing, software
1722
+ * distributed under the License is distributed on an "AS IS" BASIS,
1723
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1724
+ * See the License for the specific language governing permissions and
1725
+ * limitations under the License.
1726
+ */
1727
+ function getTransportPriority(priority) {
1728
+ priority = Math.max(0, Math.min(255, Math.round(priority)));
1729
+ if (priority === 0) return Number.MAX_SAFE_INTEGER;
1730
+ if (priority === 255) return 0;
1731
+ return Math.round((255 - priority) * (Number.MAX_SAFE_INTEGER / 255));
1732
+ }
1733
+ //#endregion
1734
+ //#region src/client/publication/subscribe.ts
1735
+ /**
1736
+ * Copyright 2025 The MOQtail Authors
1737
+ *
1738
+ * Licensed under the Apache License, Version 2.0 (the "License");
1739
+ * you may not use this file except in compliance with the License.
1740
+ * You may obtain a copy of the License at
1741
+ *
1742
+ * http://www.apache.org/licenses/LICENSE-2.0
1743
+ *
1744
+ * Unless required by applicable law or agreed to in writing, software
1745
+ * distributed under the License is distributed on an "AS IS" BASIS,
1746
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1747
+ * See the License for the specific language governing permissions and
1748
+ * limitations under the License.
1749
+ */
1750
+ /**
1751
+ * @public
1752
+ * Manages the publication of MOQT objects to a subscriber for a specific track.
1753
+ * Handles live object streaming, subscription lifecycle, and stream management.
1754
+ */
1755
+ var SubscribePublication = class {
1756
+ client;
1757
+ track;
1758
+ subscribeMsg;
1759
+ requestStream;
1178
1760
  /**
1179
1761
  * The latest location that was published to the subscriber.
1180
1762
  */
@@ -1188,9 +1770,9 @@ var SubscribePublication = class {
1188
1770
  */
1189
1771
  #startLocation;
1190
1772
  /**
1191
- * The end group for AbsoluteRange subscriptions, if specified.
1773
+ * The last Location delivered, inclusive, when the Location Filter has an end.
1192
1774
  */
1193
- #endGroup;
1775
+ #endLocation;
1194
1776
  /**
1195
1777
  * The priority of the subscriber.
1196
1778
  */
@@ -1208,6 +1790,14 @@ var SubscribePublication = class {
1208
1790
  */
1209
1791
  #parameters;
1210
1792
  /**
1793
+ * What the subscription's Range Filters let through.
1794
+ */
1795
+ #filter;
1796
+ /**
1797
+ * The Subgroup ID of each Object, which the filter and the stream header need.
1798
+ */
1799
+ #subgroupIds = new SubgroupIds();
1800
+ /**
1211
1801
  * The number of streams opened for this subscription.
1212
1802
  */
1213
1803
  #streamsOpened = 0n;
@@ -1259,28 +1849,13 @@ var SubscribePublication = class {
1259
1849
  this.#publisherPriority = track.publisherPriority;
1260
1850
  const subPriority = subscribeMsg.parameters.find(require_model.MessageParameter.isSubscriberPriority);
1261
1851
  const fwd = subscribeMsg.parameters.find(require_model.MessageParameter.isForward);
1262
- const filter = subscribeMsg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
1852
+ const filter = subscribeMsg.parameters.find(require_model.MessageParameter.isLocationFilter);
1263
1853
  this.#subscriberPriority = subPriority?.priority ?? 128;
1264
1854
  this.#forward = fwd?.forward ?? true;
1265
1855
  this.#parameters = [...subscribeMsg.parameters];
1266
- this.#startLocation = new require_model.Location(0n, 0n);
1267
- switch (filter?.filterType ?? 2) {
1268
- case 2:
1269
- if (largestLocation) this.#startLocation = new require_model.Location(largestLocation.group, largestLocation.object + 1n);
1270
- else this.#startLocation = new require_model.Location(0n, 0n);
1271
- break;
1272
- case 1:
1273
- if (largestLocation) this.#startLocation = new require_model.Location(largestLocation.group + 1n, 0n);
1274
- else this.#startLocation = new require_model.Location(0n, 0n);
1275
- break;
1276
- case 3:
1277
- this.#startLocation = filter?.startLocation ?? new require_model.Location(0n, 0n);
1278
- break;
1279
- case 4:
1280
- this.#startLocation = filter?.startLocation ?? new require_model.Location(0n, 0n);
1281
- this.#endGroup = filter?.endGroup;
1282
- break;
1283
- }
1856
+ this.#filter = new require_model.CombinedFilter(this.#parameters);
1857
+ this.#startLocation = filter?.startLocation(largestLocation) ?? new require_model.Location(0n, 0n);
1858
+ this.#endLocation = filter?.endLocation();
1284
1859
  this.publish();
1285
1860
  }
1286
1861
  /**
@@ -1313,14 +1888,39 @@ var SubscribePublication = class {
1313
1888
  /**
1314
1889
  * Updates the subscription parameters and locations based on a RequestUpdate message.
1315
1890
  * @param msg - The update message containing new request details.
1891
+ * @throws :{@link InvalidFilterError} If the Range Filters the subscription would be
1892
+ * left with cannot be applied; nothing is updated.
1316
1893
  */
1317
1894
  update(msg) {
1318
- const filter = msg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
1319
- if (filter?.startLocation !== void 0) this.#startLocation = filter.startLocation;
1320
- if (filter?.endGroup !== void 0) this.#endGroup = filter.endGroup;
1895
+ const parameters = [...this.#parameters];
1896
+ require_model.applyMessageParameterUpdate(parameters, msg.parameters);
1897
+ assertWithinFilterRangeLimit(parameters, this.client.maxFilterRanges, "REQUEST_UPDATE");
1898
+ this.#filter = new require_model.CombinedFilter(parameters);
1899
+ const filter = msg.parameters.find(require_model.MessageParameter.isLocationFilter);
1900
+ if (filter) {
1901
+ this.#startLocation = filter.startLocation(this.latestLocation) ?? new require_model.Location(0n, 0n);
1902
+ this.#endLocation = filter.endLocation();
1903
+ }
1321
1904
  for (const param of msg.parameters) if (require_model.MessageParameter.isSubscriberPriority?.(param)) this.#subscriberPriority = param.priority;
1322
1905
  else if (require_model.MessageParameter.isForward?.(param)) this.#forward = param.forward;
1323
- require_model.applyMessageParameterUpdate(this.#parameters, msg.parameters);
1906
+ this.#parameters = parameters;
1907
+ }
1908
+ /**
1909
+ * Closes the stream carrying `group`, if one is open.
1910
+ */
1911
+ async #closeGroupStream(group) {
1912
+ await this.#lock.acquire();
1913
+ try {
1914
+ const stream = this.#streams.get(group);
1915
+ if (stream) {
1916
+ this.#streams.delete(group);
1917
+ await stream.close();
1918
+ }
1919
+ } catch (err) {
1920
+ require_logger.logger.warn("publication/subscribe", "error in closing stream: id, group, err", this.#id, group, err);
1921
+ } finally {
1922
+ await this.#lock.release();
1923
+ }
1324
1924
  }
1325
1925
  #markGroupSeen(group) {
1326
1926
  if (this.#highestGroupSeen === void 0 || group > this.#highestGroupSeen) this.#highestGroupSeen = group;
@@ -1338,305 +1938,56 @@ var SubscribePublication = class {
1338
1938
  this.#highestGroupSeen = this.track.trackSource.live.largestLocation?.group;
1339
1939
  this.#cancelPublishing = this.track.trackSource.live.onNewObject(async (obj) => {
1340
1940
  if (this.#isCompleted) return;
1941
+ this.#subgroupIds.note(obj);
1341
1942
  if (!this.#forward) {
1342
1943
  this.#markGroupSeen(obj.location.group);
1343
1944
  return;
1344
1945
  }
1345
1946
  if (!this.#isStarted && this.#startLocation.compare(obj.location) <= 0) this.#isStarted = true;
1346
1947
  if (!this.#isStarted) this.#markGroupSeen(obj.location.group);
1347
- if (this.#isStarted) try {
1348
- if (!this.#streams.has(obj.location.group)) {
1349
- await this.#lock.acquire();
1350
- if (!this.#streams.has(obj.location.group)) {
1351
- const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
1352
- const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
1353
- const headerType = obj.getSubgroupHeaderType(true, false, firstObject);
1354
- let subgroupId;
1355
- if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(headerType)) subgroupId = obj.subgroupId;
1356
- const header = new require_model.SubgroupHeader(headerType, this.#trackAlias, obj.location.group, subgroupId, this.#publisherPriority);
1357
- const sendStream = await SendStream.new(writeStream, header);
1358
- this.#streams.set(obj.location.group, sendStream);
1359
- this.#streamsOpened++;
1360
- this.#markGroupSeen(obj.location.group);
1361
- }
1362
- await this.#lock.release();
1363
- }
1364
- const sendStream = this.#streams.get(obj.location.group);
1365
- await this.#lock.acquire();
1366
- await sendStream.write(obj.tryIntoSubgroupObject());
1367
- await this.#lock.release();
1368
- if (this.#endGroup && obj.location.group === this.#endGroup) {
1369
- try {
1370
- await this.#lock.acquire();
1371
- if (this.#streams.has(obj.location.group)) {
1372
- await sendStream.close();
1373
- this.#streams.delete(obj.location.group);
1374
- }
1375
- await this.#lock.release();
1376
- } catch (err) {
1377
- require_logger.logger.warn("publication/subscribe", "error in closing stream: id, endGroup, err", this.#id, this.#endGroup, err);
1378
- }
1379
- await this.done(3);
1380
- this.cancel();
1381
- } else if (this.latestLocation && this.latestLocation.group !== obj.location.group) {
1382
- const prevGroup = this.latestLocation.group;
1383
- try {
1384
- await this.#lock.acquire();
1385
- const prevStream = this.#streams.get(prevGroup);
1386
- if (prevStream) {
1387
- try {
1388
- await prevStream.close();
1389
- } catch (err) {
1390
- require_logger.logger.warn("publication/subscribe", "error in closing stream", prevGroup, err);
1391
- }
1392
- this.#streams.delete(prevGroup);
1393
- }
1394
- await this.#lock.release();
1395
- } catch (err) {
1396
- require_logger.logger.warn("publication/subscribe", "error in closing stream: id, latestLocation.group, err", this.#id, this.latestLocation.group, err);
1397
- }
1398
- }
1399
- await this.#lock.acquire();
1400
- this.latestLocation = obj.location;
1401
- await this.#lock.release();
1402
- } catch (err) {
1403
- this.cancel();
1404
- throw err;
1405
- }
1406
- });
1407
- }
1408
- };
1409
- //#endregion
1410
- //#region src/client/publication/fetch.ts
1411
- /**
1412
- * Copyright 2025 The MOQtail Authors
1413
- *
1414
- * Licensed under the Apache License, Version 2.0 (the "License");
1415
- * you may not use this file except in compliance with the License.
1416
- * You may obtain a copy of the License at
1417
- *
1418
- * http://www.apache.org/licenses/LICENSE-2.0
1419
- *
1420
- * Unless required by applicable law or agreed to in writing, software
1421
- * distributed under the License is distributed on an "AS IS" BASIS,
1422
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1423
- * See the License for the specific language governing permissions and
1424
- * limitations under the License.
1425
- */
1426
- var FetchPublication = class {
1427
- #requestId;
1428
- #track;
1429
- #startLocation;
1430
- #endLocation;
1431
- #msg;
1432
- #client;
1433
- #stream;
1434
- #writer;
1435
- #objects;
1436
- #isCanceled = false;
1437
- constructor(client, track, fetchRequest) {
1438
- this.#client = client;
1439
- this.#requestId = fetchRequest.requestId;
1440
- this.#track = track;
1441
- this.#msg = fetchRequest;
1442
- let joiningRequest;
1443
- switch (this.#msg.typeAndProps.type) {
1444
- case 1:
1445
- this.#startLocation = this.#msg.typeAndProps.props.startLocation;
1446
- this.#endLocation = this.#msg.typeAndProps.props.endLocation;
1447
- break;
1448
- case 2:
1449
- joiningRequest = client.publications.get(this.#msg.typeAndProps.props.joiningRequestId);
1450
- if (!(joiningRequest instanceof SubscribePublication)) throw new require_model.InternalError("FetchPublication.constructor", "No subscription for the joining request id");
1451
- if (!joiningRequest.latestLocation) throw new require_model.InternalError("FetchPublication.constructor", "joiningRequest.largestLocation does not exist");
1452
- this.#startLocation = new require_model.Location(joiningRequest.latestLocation.group - this.#msg.typeAndProps.props.joiningStart, 0n);
1453
- this.#endLocation = joiningRequest.latestLocation;
1454
- break;
1455
- case 3:
1456
- joiningRequest = client.publications.get(this.#msg.typeAndProps.props.joiningRequestId);
1457
- if (!(joiningRequest instanceof SubscribePublication)) throw new require_model.InternalError("FetchPublication.constructor", "No subscription for the joining request id");
1458
- if (!joiningRequest.latestLocation) throw new require_model.InternalError("FetchPublication.constructor", "joiningRequest.largestLocation does not exist");
1459
- this.#startLocation = new require_model.Location(this.#msg.typeAndProps.props.joiningStart, 0n);
1460
- this.#endLocation = joiningRequest.latestLocation;
1461
- break;
1462
- }
1463
- require_logger.logger.debug("publication/fetch", `created requestId=${this.#requestId} type=${this.#msg.typeAndProps.type}`);
1464
- this.publish();
1465
- }
1466
- cancel() {
1467
- require_logger.logger.debug("publication/fetch", `canceled requestId=${this.#requestId}`);
1468
- this.#isCanceled = true;
1469
- }
1470
- /**
1471
- * Resets the data stream this fetch is being delivered on, which §10.9.1 requires when
1472
- * a REQUEST_UPDATE for a FETCH fails.
1473
- */
1474
- async resetDataStream(code) {
1475
- require_logger.logger.debug("publication/fetch", `reset data stream requestId=${this.#requestId} code=${code}`);
1476
- this.#isCanceled = true;
1477
- await this.#writer?.abort(streamResetReason(code)).catch(() => {});
1478
- }
1479
- async publish() {
1480
- if (this.#isCanceled) return;
1481
- if (!this.#track.trackSource.past) throw new require_model.MOQtailError("FetchPublication.publish, Track does not support fetch");
1482
- require_logger.logger.debug("publication/fetch", `publishing requestId=${this.#requestId} start=${this.#startLocation} end=${this.#endLocation}`);
1483
- try {
1484
- this.#objects = await this.#track.trackSource.past.getRange(this.#startLocation, this.#endLocation);
1485
- this.#stream = await this.#client.webTransport.createUnidirectionalStream();
1486
- this.#writer = this.#stream.getWriter();
1487
- const header = new require_model.FetchHeader(5, this.#requestId);
1488
- await this.#writer.write(header);
1489
- const groupOrder = require_model.MessageParameter.groupOrderOf(this.#msg.parameters);
1490
- let fetchPrevCtx = void 0;
1491
- for (const obj of this.#objects) {
1492
- if (this.#isCanceled) {
1493
- require_logger.logger.debug("publication/fetch", `aborted during publish requestId=${this.#requestId}`);
1494
- await this.#writer.abort(streamResetReason(1));
1495
- this.#client.publications.delete(this.#requestId);
1496
- return;
1497
- }
1498
- const fetchObj = obj.tryIntoFetchObject();
1499
- await this.#writer.write(fetchObj.serialize(fetchPrevCtx, groupOrder).toUint8Array());
1500
- const newCtx = fetchObj.toContext();
1501
- if (newCtx) fetchPrevCtx = newCtx;
1502
- }
1503
- await this.#writer.close();
1504
- require_logger.logger.debug("publication/fetch", `published requestId=${this.#requestId} objects=${this.#objects.length}`);
1505
- this.#client.publications.delete(this.#requestId);
1506
- } catch (error) {
1507
- if (this.#isCanceled) return;
1508
- await this.#writer?.abort(streamResetReason(0));
1509
- const message = error instanceof Error ? error.message : String(error);
1510
- require_logger.logger.error("publication/fetch", `publish failed requestId=${this.#requestId}`, message);
1511
- throw new require_model.InternalError("FetchPublication.publish", `Failed to publish: ${message}`);
1512
- }
1513
- }
1514
- };
1515
- //#endregion
1516
- //#region src/client/handler/fetch.ts
1517
- /**
1518
- * Copyright 2025 The MOQtail Authors
1519
- *
1520
- * Licensed under the Apache License, Version 2.0 (the "License");
1521
- * you may not use this file except in compliance with the License.
1522
- * You may obtain a copy of the License at
1523
- *
1524
- * http://www.apache.org/licenses/LICENSE-2.0
1525
- *
1526
- * Unless required by applicable law or agreed to in writing, software
1527
- * distributed under the License is distributed on an "AS IS" BASIS,
1528
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1529
- * See the License for the specific language governing permissions and
1530
- * limitations under the License.
1531
- */
1532
- const handlerFetch = async (client, msg, stream) => {
1533
- require_logger.logger.log("handler/fetch", "requestId, type", msg.requestId, msg.typeAndProps.type);
1534
- let fullTrackName;
1535
- let joiningRequest;
1536
- switch (msg.typeAndProps.type) {
1537
- case 1:
1538
- fullTrackName = msg.typeAndProps.props.fullTrackName;
1539
- break;
1540
- case 2:
1541
- case 3:
1542
- joiningRequest = client.publications.get(msg.typeAndProps.props.joiningRequestId);
1543
- if (!(joiningRequest instanceof SubscribePublication)) throw new require_model.InternalError("handlerFetch", "No subscription for the joining request id");
1544
- fullTrackName = joiningRequest.track.fullTrackName;
1545
- break;
1546
- }
1547
- const track = client.trackSources.get(fullTrackName.toString());
1548
- if (!track) {
1549
- const response = new require_model.RequestError(16, 0n, new require_model.ReasonPhrase("Track does not exists"));
1550
- await stream.send(response);
1551
- return;
1552
- }
1553
- if (!track.trackSource.past) {
1554
- const response = new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("Requested track does not support fetch"));
1555
- await stream.send(response);
1556
- return;
1557
- }
1558
- const publication = new FetchPublication(client, track, msg);
1559
- client.publications.set(msg.requestId, publication);
1560
- const response = new require_model.FetchOk(false, new require_model.Location(0n, 0n), msg.parameters, track.trackProperties ?? []);
1561
- await stream.send(response);
1562
- };
1563
- //#endregion
1564
- //#region src/client/handler/fetch_ok.ts
1565
- /**
1566
- * Copyright 2025 The MOQtail Authors
1567
- *
1568
- * Licensed under the Apache License, Version 2.0 (the "License");
1569
- * you may not use this file except in compliance with the License.
1570
- * You may obtain a copy of the License at
1571
- *
1572
- * http://www.apache.org/licenses/LICENSE-2.0
1573
- *
1574
- * Unless required by applicable law or agreed to in writing, software
1575
- * distributed under the License is distributed on an "AS IS" BASIS,
1576
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1577
- * See the License for the specific language governing permissions and
1578
- * limitations under the License.
1579
- */
1580
- const handlerFetchOk = async (client, msg, _stream, requestId) => {
1581
- require_logger.logger.log("handler/fetch_ok", "requestId", requestId);
1582
- const request = client.requests.get(requestId);
1583
- if (request instanceof FetchRequest) {
1584
- if (msg.trackProperties.length > 0) {
1585
- const fetchMsg = request.message;
1586
- let fullTrackName = fetchMsg.typeAndProps.type === 1 ? fetchMsg.typeAndProps.props.fullTrackName : (() => {
1587
- const joiningReq = client.requests.get(fetchMsg.typeAndProps.props.joiningRequestId);
1588
- return joiningReq instanceof SubscribeRequest ? joiningReq.fullTrackName : void 0;
1589
- })();
1590
- if (fullTrackName !== void 0) {
1591
- const track = client.trackSources.get(fullTrackName.toString());
1592
- if (track !== void 0) track.trackProperties = msg.trackProperties;
1948
+ if (this.#isStarted && this.#endLocation && obj.location.compare(this.#endLocation) > 0) {
1949
+ this.#markGroupSeen(obj.location.group);
1950
+ if (this.latestLocation) await this.#closeGroupStream(this.latestLocation.group);
1951
+ return;
1593
1952
  }
1594
- }
1595
- request.resolve(msg);
1596
- } else throw new require_model.ProtocolViolationError("handlerFetchOk", `FETCH_OK on a stream with no pending fetch request (request id ${requestId})`);
1597
- };
1598
- //#endregion
1599
- //#region src/client/handler/goaway.ts
1600
- const handlerGoAway = async (client, msg) => {
1601
- require_logger.logger.log("handler/goaway", "newSessionUri", msg.newSessionUri, "timeout", msg.timeout, "requestId", msg.requestId);
1602
- if (client.goawayReceived) {
1603
- await client.disconnect(new require_model.ProtocolViolationError("handler/goaway", "A second GOAWAY arrived on the control stream"));
1604
- return;
1953
+ if (!this.#isStarted) return;
1954
+ const subgroupId = this.#subgroupIds.of(obj);
1955
+ if (!this.#filter.matches(obj, subgroupId)) {
1956
+ this.#markGroupSeen(obj.location.group);
1957
+ if (this.latestLocation && this.latestLocation.group !== obj.location.group) await this.#closeGroupStream(this.latestLocation.group);
1958
+ return;
1959
+ }
1960
+ try {
1961
+ if (!this.#streams.has(obj.location.group)) {
1962
+ await this.#lock.acquire();
1963
+ if (!this.#streams.has(obj.location.group)) {
1964
+ const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
1965
+ const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
1966
+ const header = subgroupHeaderFor(obj, subgroupId ?? obj.location.object, this.#trackAlias, this.#publisherPriority, firstObject);
1967
+ const sendStream = await SendStream.new(writeStream, header, this.client.onDataSent, void 0, this.client.dataStreamObserver(() => this.track.fullTrackName));
1968
+ this.#streams.set(obj.location.group, sendStream);
1969
+ this.#streamsOpened++;
1970
+ this.#markGroupSeen(obj.location.group);
1971
+ }
1972
+ await this.#lock.release();
1973
+ }
1974
+ const sendStream = this.#streams.get(obj.location.group);
1975
+ await this.#lock.acquire();
1976
+ await sendStream.write(obj.tryIntoSubgroupObject());
1977
+ await this.#lock.release();
1978
+ if (this.#endLocation && obj.location.equals(this.#endLocation)) await this.#closeGroupStream(obj.location.group);
1979
+ else if (this.latestLocation && this.latestLocation.group !== obj.location.group) await this.#closeGroupStream(this.latestLocation.group);
1980
+ await this.#lock.acquire();
1981
+ this.latestLocation = obj.location;
1982
+ await this.#lock.release();
1983
+ } catch (err) {
1984
+ this.cancel();
1985
+ throw err;
1986
+ }
1987
+ });
1605
1988
  }
1606
- client.goawayReceived = true;
1607
- if (client.onGoaway) client.onGoaway(msg);
1608
- };
1609
- /**
1610
- * GOAWAY on a request stream: the peer is migrating that one request (§10.4). The
1611
- * request is re-issued on a fresh stream and the session, along with every other request
1612
- * on it, carries on.
1613
- */
1614
- const handlerGoAwayOnRequestStream = async (client, msg, _stream, requestId) => {
1615
- require_logger.logger.log("handler/goaway", `GOAWAY migrating request ${requestId}`, "timeout", msg.timeout);
1616
- await client.migrateRequest(requestId, msg);
1617
1989
  };
1618
1990
  //#endregion
1619
- //#region src/client/util/validators.ts
1620
- /**
1621
- * Copyright 2026 The MOQtail Authors
1622
- *
1623
- * Licensed under the Apache License, Version 2.0 (the "License");
1624
- * you may not use this file except in compliance with the License.
1625
- * You may obtain a copy of the License at
1626
- *
1627
- * http://www.apache.org/licenses/LICENSE-2.0
1628
- *
1629
- * Unless required by applicable law or agreed to in writing, software
1630
- * distributed under the License is distributed on an "AS IS" BASIS,
1631
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1632
- * See the License for the specific language governing permissions and
1633
- * limitations under the License.
1634
- */
1635
- /** Returns true when `trackAlias` is a valid (non-negative) track alias. Zero is a legal value. */
1636
- function isValidTrackAlias(trackAlias) {
1637
- return trackAlias !== void 0 && trackAlias >= 0n;
1638
- }
1639
- //#endregion
1640
1991
  //#region src/client/handler/subscribe.ts
1641
1992
  /**
1642
1993
  * Copyright 2025 The MOQtail Authors
@@ -1655,6 +2006,12 @@ function isValidTrackAlias(trackAlias) {
1655
2006
  */
1656
2007
  const handlerSubscribe = async (client, msg, stream) => {
1657
2008
  require_logger.logger.debug("handler/subscribe", `received requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2009
+ const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
2010
+ if (filterRejection) {
2011
+ require_logger.logger.warn("handler/subscribe", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
2012
+ await stream.send(filterRejection);
2013
+ return;
2014
+ }
1658
2015
  const track = client.trackSources.get(msg.fullTrackName.toString());
1659
2016
  if (!track) {
1660
2017
  require_logger.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track not found, sending REQUEST_ERROR`);
@@ -1670,10 +2027,10 @@ const handlerSubscribe = async (client, msg, stream) => {
1670
2027
  }
1671
2028
  if (!isValidTrackAlias(track.trackAlias)) throw new Error("Expected track alias to be set");
1672
2029
  const largestLocation = track.trackSource.live.largestLocation;
1673
- const parameters = [...msg.parameters];
1674
- if (largestLocation) parameters.push(new require_model.LargestObject(largestLocation));
2030
+ const parameters = largestLocation ? [new require_model.LargestObject(largestLocation)] : [];
2031
+ const trackProperties = require_model.MessageParameter.includesProperties(msg.parameters) ? track.trackProperties ?? [] : [];
1675
2032
  require_logger.logger.debug("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" trackAlias=${track.trackAlias} largestLocation=${largestLocation ? `${largestLocation.group}:${largestLocation.object}` : "none"} — sending SUBSCRIBE_OK`);
1676
- const subscribeOk = require_model.SubscribeOk.create(track.trackAlias, parameters, track.trackProperties ?? []);
2033
+ const subscribeOk = require_model.SubscribeOk.create(track.trackAlias, parameters, trackProperties);
1677
2034
  const publication = new SubscribePublication(client, track, msg, stream, largestLocation);
1678
2035
  client.publications.set(msg.requestId, publication);
1679
2036
  await stream.send(subscribeOk);
@@ -1720,6 +2077,20 @@ const handlerSubscribeNamespace = async (client, msg, stream) => {
1720
2077
  */
1721
2078
  const handlerSubscribeTracks = async (client, msg, stream) => {
1722
2079
  require_logger.logger.log("handler/subscribe_tracks", "prefix", msg.trackNamespacePrefix.toUtf8Path());
2080
+ if (require_model.MessageParameter.carriesRangeFilter(msg.parameters)) {
2081
+ let code = 3;
2082
+ let reason = "Range filters on SUBSCRIBE_TRACKS are not supported";
2083
+ try {
2084
+ assertWithinFilterRangeLimit(msg.parameters, client.maxFilterRanges, "SUBSCRIBE_TRACKS");
2085
+ } catch (error) {
2086
+ if (!(error instanceof require_model.InvalidFilterError)) throw error;
2087
+ code = 54;
2088
+ reason = error.details;
2089
+ }
2090
+ require_logger.logger.warn("handler/subscribe_tracks", `requestId=${msg.requestId} refused: ${reason}`);
2091
+ await stream.send(new require_model.RequestError(code, 0n, new require_model.ReasonPhrase(reason)));
2092
+ return;
2093
+ }
1723
2094
  if (client.onPeerSubscribeTracks) client.onPeerSubscribeTracks(msg);
1724
2095
  await stream.send(new require_model.RequestOk());
1725
2096
  };
@@ -1833,6 +2204,15 @@ var PublishPublication = class {
1833
2204
  */
1834
2205
  #parameters;
1835
2206
  /**
2207
+ * What the subscriber's Range Filters let through. A PUBLISH carries none, so this
2208
+ * passes everything until a REQUEST_UPDATE says otherwise.
2209
+ */
2210
+ #filter = new require_model.CombinedFilter([]);
2211
+ /**
2212
+ * The Subgroup ID of each Object, which the filter and the stream header need.
2213
+ */
2214
+ #subgroupIds = new SubgroupIds();
2215
+ /**
1836
2216
  * Highest group this publication has already opened a stream for or skipped objects of.
1837
2217
  * A stream for a group at or below it reopens a subgroup, so it cannot claim FIRST_OBJECT.
1838
2218
  */
@@ -1879,14 +2259,20 @@ var PublishPublication = class {
1879
2259
  this.client.onForwardStateChange?.(this.publishMsg.requestId, forward);
1880
2260
  }
1881
2261
  /**
1882
- * Applies a REQUEST_UPDATE the peer sent on this publication's request stream. The
1883
- * Forward State is the one thing it can move; what a publisher sends, and when,
1884
- * is otherwise its own to decide.
2262
+ * Applies a REQUEST_UPDATE the peer sent on this publication's request stream. It
2263
+ * can move the Forward State and the Range Filters; what a publisher sends, and
2264
+ * when, is otherwise its own to decide.
2265
+ * @throws :{@link InvalidFilterError} If the Range Filters the publication would be
2266
+ * left with cannot be applied; nothing is updated.
1885
2267
  */
1886
2268
  update(msg) {
2269
+ const parameters = [...this.#parameters];
2270
+ require_model.applyMessageParameterUpdate(parameters, msg.parameters);
2271
+ assertWithinFilterRangeLimit(parameters, this.client.maxFilterRanges, "REQUEST_UPDATE");
2272
+ this.#filter = new require_model.CombinedFilter(parameters);
2273
+ this.#parameters = parameters;
1887
2274
  const forward = msg.parameters.find(require_model.MessageParameter.isForward);
1888
2275
  if (forward) this.setForwardState(forward.forward);
1889
- require_model.applyMessageParameterUpdate(this.#parameters, msg.parameters);
1890
2276
  }
1891
2277
  /**
1892
2278
  * Calculates the stream priority based on publisher priority.
@@ -1927,21 +2313,24 @@ var PublishPublication = class {
1927
2313
  this.#highestGroupSeen = this.track.trackSource.live.largestLocation?.group;
1928
2314
  this.#cancelPublishing = this.track.trackSource.live.onNewObject(async (obj) => {
1929
2315
  if (this.#isCompleted) return;
2316
+ this.#subgroupIds.note(obj);
1930
2317
  if (!this.#forward) {
1931
2318
  this.#markGroupSeen(obj.location.group);
1932
2319
  return;
1933
2320
  }
2321
+ const subgroupId = this.#subgroupIds.of(obj);
2322
+ if (!this.#filter.matches(obj, subgroupId)) {
2323
+ this.#markGroupSeen(obj.location.group);
2324
+ return;
2325
+ }
1934
2326
  try {
1935
2327
  if (!this.#streams.has(obj.location.group)) {
1936
2328
  await this.#lock.acquire();
1937
2329
  if (!this.#streams.has(obj.location.group)) {
1938
2330
  const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
1939
2331
  const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
1940
- const headerType = obj.getSubgroupHeaderType(true, false, firstObject);
1941
- let subgroupId;
1942
- if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(headerType)) subgroupId = obj.subgroupId;
1943
- const header = new require_model.SubgroupHeader(headerType, this.#trackAlias, obj.location.group, subgroupId, this.#publisherPriority);
1944
- const sendStream = await SendStream.new(writeStream, header);
2332
+ const header = subgroupHeaderFor(obj, subgroupId ?? obj.location.object, this.#trackAlias, this.#publisherPriority, firstObject);
2333
+ const sendStream = await SendStream.new(writeStream, header, this.client.onDataSent, void 0, this.client.dataStreamObserver(() => this.track.fullTrackName));
1945
2334
  this.#streams.set(obj.location.group, sendStream);
1946
2335
  this.#streamsOpened++;
1947
2336
  this.#markGroupSeen(obj.location.group);
@@ -1981,6 +2370,44 @@ var PublishPublication = class {
1981
2370
  }
1982
2371
  };
1983
2372
  //#endregion
2373
+ //#region src/client/handler/subscription_response.ts
2374
+ /**
2375
+ * Copyright 2026 The MOQtail Authors
2376
+ *
2377
+ * Licensed under the Apache License, Version 2.0 (the "License");
2378
+ * you may not use this file except in compliance with the License.
2379
+ * You may obtain a copy of the License at
2380
+ *
2381
+ * http://www.apache.org/licenses/LICENSE-2.0
2382
+ *
2383
+ * Unless required by applicable law or agreed to in writing, software
2384
+ * distributed under the License is distributed on an "AS IS" BASIS,
2385
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2386
+ * See the License for the specific language governing permissions and
2387
+ * limitations under the License.
2388
+ */
2389
+ /**
2390
+ * Records what a SUBSCRIBE_OK or REQUEST_UPDATE_OK says about a subscription.
2391
+ * Both carry the same things, so both are read the same way.
2392
+ *
2393
+ * LARGEST_OBJECT is where a fill fetch stream stops, which is how a subscriber
2394
+ * tells a fill that finished from one that was cut short. Track properties, such
2395
+ * as whether the track supports dynamic groups, belong to the track rather than
2396
+ * to this subscription and are recorded there. EXPIRES is kept for callers to
2397
+ * read but nothing acts on it: no subscription expires on a timer here yet.
2398
+ */
2399
+ function applySubscriptionResponse(client, request, parameters, trackProperties) {
2400
+ const largest = parameters.find(require_model.MessageParameter.isLargestObject);
2401
+ if (largest) request.fillBoundary = largest.location;
2402
+ const expires = parameters.find(require_model.MessageParameter.isExpires);
2403
+ if (expires) request.expires = expires.expires;
2404
+ if (trackProperties.length > 0) {
2405
+ require_logger.logger.debug("handler/subscription_response", `requestId=${request.requestId} — applying ${trackProperties.length} track propert(ies)`);
2406
+ const track = client.trackSources.get(request.fullTrackName.toString());
2407
+ if (track !== void 0) track.trackProperties = trackProperties;
2408
+ }
2409
+ }
2410
+ //#endregion
1984
2411
  //#region src/client/handler/request_ok.ts
1985
2412
  const handlerRequestOk = async (client, msg, _stream, requestId) => {
1986
2413
  require_logger.logger.log("handler/request_ok", "received RequestOk for requestId:", requestId);
@@ -2002,10 +2429,11 @@ const handlerRequestOk = async (client, msg, _stream, requestId) => {
2002
2429
  require_logger.logger.warn("handler/request_ok", `Live track source not found for ${fullTrackName.toString()}`);
2003
2430
  return;
2004
2431
  }
2005
- const publication = new PublishPublication(client, track, request.message);
2006
- client.publications.set(requestId, publication);
2007
- const forward = msg.parameters.find(require_model.MessageParameter.isForward);
2008
- if (forward) publication.setForwardState(forward.forward);
2432
+ client.publications.set(requestId, new PublishPublication(client, track, request.message));
2433
+ return;
2434
+ }
2435
+ if (request instanceof SubscribeRequest) {
2436
+ applySubscriptionResponse(client, request, msg.parameters, msg.trackProperties);
2009
2437
  return;
2010
2438
  }
2011
2439
  if (request instanceof PublishNamespaceRequest || request instanceof SubscribeNamespaceRequest || request instanceof TrackStatusRequest) {
@@ -2033,7 +2461,10 @@ const handlerRequestError = async (client, msg, _stream, requestId) => {
2033
2461
  const handlerPublishDone = async (client, msg, _stream, openingRequestId) => {
2034
2462
  if (client.onPeerPublishDone) client.onPeerPublishDone(msg, openingRequestId);
2035
2463
  const request = client.requests.get(openingRequestId);
2036
- if (request instanceof SubscribeRequest) request.expectedStreams = msg.streamCount;
2464
+ if (request instanceof SubscribeRequest) {
2465
+ request.expectedStreams = msg.streamCount;
2466
+ client.completeSubscription(request);
2467
+ }
2037
2468
  };
2038
2469
  //#endregion
2039
2470
  //#region src/client/handler/subscribe_ok.ts
@@ -2056,11 +2487,7 @@ const handlerSubscribeOk = async (client, msg, _stream, requestId) => {
2056
2487
  require_logger.logger.debug("handler/subscribe_ok", `received requestId=${requestId} trackAlias=${msg.trackAlias}`);
2057
2488
  const request = client.requests.get(requestId);
2058
2489
  if (request instanceof SubscribeRequest) {
2059
- if (msg.trackProperties.length > 0) {
2060
- require_logger.logger.debug("handler/subscribe_ok", `requestId=${requestId} — applying ${msg.trackProperties.length} track propert(ies)`);
2061
- const track = client.trackSources.get(request.fullTrackName.toString());
2062
- if (track !== void 0) track.trackProperties = msg.trackProperties;
2063
- }
2490
+ applySubscriptionResponse(client, request, msg.parameters, msg.trackProperties);
2064
2491
  require_logger.logger.debug("handler/subscribe_ok", `requestId=${requestId} — resolving SubscribeRequest ftn="${request.fullTrackName}"`);
2065
2492
  request.resolve(msg);
2066
2493
  } else {
@@ -2087,37 +2514,54 @@ const handlerSubscribeOk = async (client, msg, _stream, requestId) => {
2087
2514
  */
2088
2515
  /**
2089
2516
  * A REQUEST_UPDATE modifies the request whose stream it arrived on, and §10.9 requires
2090
- * exactly one REQUEST_OK or REQUEST_ERROR back on that stream. TRACK_STATUS is no longer
2091
- * one of the updatable request types, so an update naming one is refused.
2517
+ * exactly one REQUEST_OK or REQUEST_ERROR back on that stream. Only the sender of a
2518
+ * request may update it, plus a subscriber on a PUBLISH it was offered. An update
2519
+ * arriving anywhere else, a TRACK_STATUS among them, closes the session.
2092
2520
  */
2093
2521
  const handlerRequestUpdate = async (client, msg, stream, requestId) => {
2094
2522
  require_logger.logger.log("handler/request_update", "requestId", requestId);
2095
- const openingType = stream.openingType;
2096
- if (openingType !== void 0 && !require_model.ControlMessageType.isUpdatable(openingType)) {
2097
- await stream.send(new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("request does not support REQUEST_UPDATE")));
2523
+ if (!isExpectedUpdate(stream)) {
2524
+ await client.disconnect(new require_model.ProtocolViolationError("handler/request_update", `Unexpected REQUEST_UPDATE on a ${stream.first ? "locally" : "peer"} opened ${describe(stream.openingType)} stream`));
2525
+ return;
2526
+ }
2527
+ const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
2528
+ if (filterRejection) {
2529
+ const reason = filterRejection.reasonPhrase.phrase;
2530
+ require_logger.logger.warn("handler/request_update", `requestId=${requestId} has filters this client cannot take: ${reason}`);
2531
+ await failUpdate(client, stream, requestId, 54, reason);
2098
2532
  return;
2099
2533
  }
2100
2534
  const publication = client.publications.get(requestId);
2101
- if (publication instanceof SubscribePublication) {
2535
+ if (publication instanceof SubscribePublication || publication instanceof PublishPublication) {
2102
2536
  try {
2103
2537
  publication.update(msg);
2104
2538
  } catch (error) {
2539
+ const invalid = error instanceof require_model.InvalidFilterError;
2105
2540
  require_logger.logger.error("handler/request_update", `update failed for requestId=${requestId}`, error);
2106
- await failUpdate(client, stream, requestId, 0, "REQUEST_UPDATE failed");
2541
+ await failUpdate(client, stream, requestId, invalid ? 54 : 0, invalid ? error.details : "REQUEST_UPDATE failed");
2107
2542
  return;
2108
2543
  }
2109
2544
  await stream.send(new require_model.RequestOk());
2110
2545
  return;
2111
2546
  }
2112
- if (publication instanceof PublishPublication) {
2113
- publication.update(msg);
2114
- await stream.send(new require_model.RequestOk());
2115
- return;
2116
- }
2117
2547
  require_logger.logger.warn("handler/request_update", `no updatable request for requestId=${requestId}`);
2118
2548
  await failUpdate(client, stream, requestId, 3, "REQUEST_UPDATE cannot be applied");
2119
2549
  };
2120
2550
  /**
2551
+ * Whether the peer may send a REQUEST_UPDATE on this stream. On a stream the peer
2552
+ * opened, it is the requester and may update any of the updatable request types. On a
2553
+ * stream this side opened, it may only update a PUBLISH, as that PUBLISH's subscriber.
2554
+ */
2555
+ function isExpectedUpdate(stream) {
2556
+ const openingType = stream.openingType;
2557
+ if (openingType === void 0) return false;
2558
+ if (stream.first) return openingType === 29;
2559
+ return require_model.ControlMessageType.isUpdatable(openingType);
2560
+ }
2561
+ function describe(openingType) {
2562
+ return openingType === void 0 ? "unknown" : require_model.ControlMessageType[openingType];
2563
+ }
2564
+ /**
2121
2565
  * Refuses the update, then ends the request the way §10.9.1 requires for its type: a
2122
2566
  * subscription is terminated with PUBLISH_DONE(UPDATE_FAILED), a FETCH has its data
2123
2567
  * stream reset, and a namespace request has its bidi stream closed.
@@ -2186,7 +2630,7 @@ const handlerTrackStatus = async (_client, msg, stream) => {
2186
2630
  * limitations under the License.
2187
2631
  */
2188
2632
  /**
2189
- * Draft-18 §3.3: the control stream carries SETUP and GOAWAY, nothing else. SETUP is
2633
+ * The control stream carries SETUP and GOAWAY, nothing else. SETUP is
2190
2634
  * consumed by the handshake in {@link MOQtailClient.new}, so GOAWAY is all that reaches
2191
2635
  * the read loop. Every request type has moved to its own bidi stream — see
2192
2636
  * {@link getHandlerForRequestStreamMessage}.
@@ -2214,7 +2658,7 @@ function getHandlerForRequestStreamMessage(msg) {
2214
2658
  if (msg instanceof require_model.GoAway) return handlerGoAwayOnRequestStream;
2215
2659
  if (msg instanceof require_model.RequestUpdate) return handlerRequestUpdate;
2216
2660
  if (msg instanceof require_model.PublishDone) return handlerPublishDone;
2217
- if (msg instanceof require_model.PublishBlocked) return handlerPublishBlocked;
2661
+ if (msg instanceof require_model.PublishSkipped) return handlerPublishSkipped;
2218
2662
  }
2219
2663
  //#endregion
2220
2664
  //#region src/client/util/random_id.ts
@@ -2450,7 +2894,7 @@ var RecvDatagramStream = class RecvDatagramStream {
2450
2894
  * const client = await MOQtailClient.new({ url });
2451
2895
  * const result = await client.subscribe({
2452
2896
  * fullTrackName,
2453
- * filterType: FilterType.LatestObject,
2897
+ * locationFilter: new LocationFilter(LocationFilterType.NextObject),
2454
2898
  * forward: true,
2455
2899
  * groupOrder: GroupOrder.Original,
2456
2900
  * priority: 0
@@ -2526,23 +2970,17 @@ var MOQtailClient = class MOQtailClient {
2526
2970
  */
2527
2971
  aliasFullTrackNameMap = /* @__PURE__ */ new Map();
2528
2972
  /**
2529
- * Pending state updates keyed by requestId and applied once a new track alias is seen.
2530
- * Used to avoid premature state updates.
2531
- */
2532
- pendingStateUpdates = /* @__PURE__ */ new Map();
2533
- /**
2534
2973
  * The bidirectional request stream each locally issued request runs on, keyed by the
2535
- * requestId of the message that opened it (draft-18 §3.3.2). The stream stays open for
2974
+ * requestId of the message that opened it. The stream stays open for
2536
2975
  * the request's lifetime: responses and follow-ups arrive on it, updates are written to
2537
2976
  * it, and closing it is how the request is cancelled.
2538
2977
  */
2539
2978
  #requestStreams = /* @__PURE__ */ new Map();
2540
2979
  /**
2541
- * Request ids of requests re-issued after a per-request GOAWAY (§10.4), which consumes
2980
+ * Request ids of requests re-issued after a per-request GOAWAY, which consumes
2542
2981
  * a fresh Request ID each time (§10.1). The id the caller was given stays the client's
2543
2982
  * key for the request; these two maps translate it to and from the id now on the wire.
2544
2983
  */
2545
- #wireRequestIds = /* @__PURE__ */ new Map();
2546
2984
  #clientRequestIds = /* @__PURE__ */ new Map();
2547
2985
  /**
2548
2986
  * Namespace path -\> the requestId that announced or subscribed to it, so the
@@ -2554,6 +2992,8 @@ var MOQtailClient = class MOQtailClient {
2554
2992
  webTransport;
2555
2993
  /** Validated Setup message the server sent back during handshake (protocol parameters negotiated). */
2556
2994
  #serverSetup;
2995
+ /** How many filter ranges this client allows the server per request, as advertised in SETUP. */
2996
+ #maxFilterRanges = 0n;
2557
2997
  /** Outgoing / incoming control message stream pair. */
2558
2998
  controlStream;
2559
2999
  /** Reader over incoming uni streams: the control recv half first, data streams after. */
@@ -2562,6 +3002,21 @@ var MOQtailClient = class MOQtailClient {
2562
3002
  dataStreamTimeoutMs;
2563
3003
  /** Timeout (ms) for control stream read operations; undefined =\> no explicit timeout. */
2564
3004
  controlStreamTimeoutMs;
3005
+ /**
3006
+ * How long (ms) an incoming data stream waits for the control message that establishes
3007
+ * its track alias before the stream is abandoned.
3008
+ */
3009
+ trackAliasResolutionTimeoutMs = DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS;
3010
+ /**
3011
+ * How long (ms) a track a soft switch handed over from may stay quiet before it is
3012
+ * retired anyway, if no PUBLISH_DONE ends its drain first.
3013
+ */
3014
+ switchDrainTimeoutMs = DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
3015
+ /**
3016
+ * Callbacks waiting for a track alias to be registered, keyed by alias. Each entry
3017
+ * belongs to a data stream that arrived before the control message naming its alias.
3018
+ */
3019
+ #aliasWaiters = /* @__PURE__ */ new Map();
2565
3020
  /** Flag indicating the client has been disconnected/destroyed and cannot accept further API calls. */
2566
3021
  #isDestroyed = false;
2567
3022
  /** Internal monotonically increasing client-assigned request id counter (even/odd parity scheme advances by 2). */
@@ -2583,7 +3038,7 @@ var MOQtailClient = class MOQtailClient {
2583
3038
  onGoaway;
2584
3039
  /**
2585
3040
  * Whether the peer has sent a GOAWAY on the control stream. Once it has, this side
2586
- * should not start new requests (§10.4); a second one closes the session with
3041
+ * should not start new requests; a second one closes the session with
2587
3042
  * PROTOCOL_VIOLATION.
2588
3043
  */
2589
3044
  goawayReceived = false;
@@ -2624,6 +3079,13 @@ var MOQtailClient = class MOQtailClient {
2624
3079
  */
2625
3080
  onDataSent;
2626
3081
  /**
3082
+ * Invoked for every data stream this client opens or accepts: once for its header, once
3083
+ * per object (identity and payload length only), and once when the stream ends.
3084
+ * Use for counters and diagnostics.
3085
+ * Informational event.
3086
+ */
3087
+ onDataEvent;
3088
+ /**
2627
3089
  * General-purpose error callback for surfaced exceptions not thrown to caller synchronously.
2628
3090
  * Use to log or display errors.
2629
3091
  * Error handler.
@@ -2654,15 +3116,28 @@ var MOQtailClient = class MOQtailClient {
2654
3116
  onForwardStateChange;
2655
3117
  /** Fired when an inbound SUBSCRIBE_NAMESPACE control message is received. */
2656
3118
  onPeerSubscribeNamespace;
2657
- /** Fired when an inbound SUBSCRIBE_TRACKS control message is received. */
3119
+ /**
3120
+ * Fired when an inbound SUBSCRIBE_TRACKS control message is received. The PUBLISH
3121
+ * sent for each matching track:
3122
+ * - states the request's settings as its parameters, from
3123
+ * `MessageParameter.publishParametersFor(msg.parameters)`: FORWARD, GROUP_ORDER and
3124
+ * the LOCATION_FILTER the subscription starts from, but never the request's
3125
+ * AUTHORIZATION_TOKEN;
3126
+ * - goes without Track Properties when
3127
+ * `MessageParameter.includesProperties(msg.parameters)` is false.
3128
+ *
3129
+ * A request carrying FILL_PARAMETERS also asks for a fill of what each track has
3130
+ * already published. This client cannot open a fill for a pushed track, so such a
3131
+ * subscriber gets only the live Objects.
3132
+ */
2658
3133
  onPeerSubscribeTracks;
2659
3134
  /**
2660
- * Fired when a PUBLISH_BLOCKED arrives on a {@link MOQtailClient.subscribeTracks}
3135
+ * Fired when a PUBLISH_SKIPPED arrives on a {@link MOQtailClient.subscribeTracks}
2661
3136
  * stream: the peer has a matching track but no bidi stream to send its PUBLISH on
2662
3137
  * until its stream limit lifts (§10.20). `prefix` is the prefix this side subscribed
2663
3138
  * with, which is what the message's suffix hangs off.
2664
3139
  */
2665
- onPeerPublishBlocked;
3140
+ onPeerPublishSkipped;
2666
3141
  /** Fired when a NAMESPACE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
2667
3142
  onPeerNamespace;
2668
3143
  /** Fired when a NAMESPACE_DONE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
@@ -2709,6 +3184,29 @@ var MOQtailClient = class MOQtailClient {
2709
3184
  return this.#serverSetup;
2710
3185
  }
2711
3186
  /**
3187
+ * How many filter ranges the server allows in one request: its MAX_FILTER_RANGES,
3188
+ * or 0 when it sent none, which allows no Range Filter at all.
3189
+ */
3190
+ /**
3191
+ * How many filter ranges this client allows the server in one request: the
3192
+ * MAX_FILTER_RANGES it advertised, {@link DEFAULT_MAX_FILTER_RANGES} unless the
3193
+ * caller's setup options set one.
3194
+ */
3195
+ get maxFilterRanges() {
3196
+ return this.#maxFilterRanges;
3197
+ }
3198
+ /**
3199
+ * How many filter ranges the server allows in one request: its MAX_FILTER_RANGES,
3200
+ * or 0 when it sent none, which allows no Range Filter at all.
3201
+ */
3202
+ get peerMaxFilterRanges() {
3203
+ for (const pair of this.#serverSetup?.setupOptions ?? []) {
3204
+ const option = require_model.MaxFilterRanges.fromKeyValuePair(pair);
3205
+ if (option) return option.value;
3206
+ }
3207
+ return 0n;
3208
+ }
3209
+ /**
2712
3210
  * Returns true if datagram support is currently active
2713
3211
  */
2714
3212
  get isDatagramsEnabled() {
@@ -2768,6 +3266,7 @@ var MOQtailClient = class MOQtailClient {
2768
3266
  * transportOptions: { congestionControl: 'default' },
2769
3267
  * dataStreamTimeoutMs: 5000,
2770
3268
  * controlStreamTimeoutMs: 2000,
3269
+ * trackAliasResolutionTimeoutMs: 2000,
2771
3270
  * enableDatagrams: true,
2772
3271
  * callbacks: {
2773
3272
  * onMessageSent: msg => console.log('Sent:', msg),
@@ -2779,7 +3278,7 @@ var MOQtailClient = class MOQtailClient {
2779
3278
  * ```
2780
3279
  */
2781
3280
  static async new(args) {
2782
- let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, enableDatagrams, callbacks } = args;
3281
+ let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, trackAliasResolutionTimeoutMs, switchDrainTimeoutMs, enableDatagrams, callbacks } = args;
2783
3282
  const client = new MOQtailClient();
2784
3283
  if (!transportOptions) transportOptions = { protocols: [] };
2785
3284
  if (!transportOptions.protocols) transportOptions = {
@@ -2801,10 +3300,19 @@ var MOQtailClient = class MOQtailClient {
2801
3300
  if (callbacks?.onSessionTerminated) client.onSessionTerminated = callbacks.onSessionTerminated;
2802
3301
  if (callbacks?.onDatagramReceived) client.onDatagramReceived = callbacks.onDatagramReceived;
2803
3302
  if (callbacks?.onDatagramSent) client.onDatagramSent = callbacks.onDatagramSent;
3303
+ if (callbacks?.onDataEvent) client.onDataEvent = callbacks.onDataEvent;
2804
3304
  if (dataStreamTimeoutMs) client.dataStreamTimeoutMs = dataStreamTimeoutMs;
2805
3305
  if (controlStreamTimeoutMs) client.controlStreamTimeoutMs = controlStreamTimeoutMs;
3306
+ if (trackAliasResolutionTimeoutMs !== void 0) client.trackAliasResolutionTimeoutMs = trackAliasResolutionTimeoutMs;
3307
+ if (switchDrainTimeoutMs !== void 0) client.switchDrainTimeoutMs = switchDrainTimeoutMs;
2806
3308
  const sendHalf = new ControlSendStream(await client.webTransport.createUnidirectionalStream({ sendOrder: Number.MAX_SAFE_INTEGER }), client.onMessageSent);
2807
3309
  const params = setupOptions ? setupOptions.build() : new require_model.SetupOptions().build();
3310
+ let maxFilterRanges = params.map((p) => require_model.MaxFilterRanges.fromKeyValuePair(p)).find((o) => o !== void 0);
3311
+ if (!maxFilterRanges) {
3312
+ maxFilterRanges = new require_model.MaxFilterRanges(DEFAULT_MAX_FILTER_RANGES);
3313
+ params.push(maxFilterRanges.toKeyValuePair());
3314
+ }
3315
+ client.#maxFilterRanges = maxFilterRanges.value;
2808
3316
  require_model.assertNoAuthorityOverWebTransport(params);
2809
3317
  await sendHalf.send(new require_model.Setup(params));
2810
3318
  client.#incomingUniStreams = client.webTransport.incomingUnidirectionalStreams.getReader();
@@ -2989,17 +3497,11 @@ var MOQtailClient = class MOQtailClient {
2989
3497
  }
2990
3498
  }
2991
3499
  /**
2992
- * Resolve track alias to full track name using client's request ID map.
2993
- * Falls back to a placeholder if not found.
3500
+ * Resolve track alias to the full track name it was claimed for.
3501
+ * Falls back to a placeholder if no request holds the alias.
2994
3502
  */
2995
3503
  #resolveTrackAlias(trackAlias) {
2996
- try {
2997
- const requestId = this.subscriptionAliasMap.get(trackAlias);
2998
- if (requestId !== void 0) return this.requestIdMap.getNameByRequestId(requestId);
2999
- return require_model.FullTrackName.tryNew("unknown", `track-${trackAlias}`);
3000
- } catch {
3001
- return require_model.FullTrackName.tryNew("unknown", `track-${trackAlias}`);
3002
- }
3504
+ return this.aliasFullTrackNameMap.get(trackAlias) ?? require_model.FullTrackName.tryNew("unknown", `track-${trackAlias}`);
3003
3505
  }
3004
3506
  /**
3005
3507
  * Sets (or replaces) the client-level default early discard policy for incoming subgroup streams.
@@ -3063,7 +3565,7 @@ var MOQtailClient = class MOQtailClient {
3063
3565
  this.#requestStreams.clear();
3064
3566
  this.#namespaceRequestIds.clear();
3065
3567
  await Promise.allSettled(openStreams.map((requestStream) => requestStream.close()));
3066
- if (!this.webTransport.closed) this.webTransport.close();
3568
+ this.webTransport.close();
3067
3569
  if (this.onSessionTerminated) this.onSessionTerminated(new require_model.InternalError("MOQtailClient.disconnect", reason instanceof Error ? reason.message : String(reason)));
3068
3570
  }
3069
3571
  /**
@@ -3144,25 +3646,25 @@ var MOQtailClient = class MOQtailClient {
3144
3646
  *
3145
3647
  * - `forward: true` tells the relay to forward objects to this subscriber as they arrive.
3146
3648
  * - `forward: false` means the relay subscribes upstream but buffers objects locally, not forwarding them to you.
3147
- * - `filterType: AbsoluteStart` lets you specify a start position in the future; the stream waits for that object. If the start location is \< the latest object
3148
- * observed at the publisher then it behaves as `filterType: LatestObject`
3149
- * - `filterType: AbsoluteRange` lets you specify a start and end group, both of should be in the future; the stream waits for those objects. If the start location is \< the latest object
3150
- * observed at the publisher then it behaves as `filterType: LatestObject`.
3649
+ * - `locationFilter` selects which Objects are delivered; omitted, the subscription is unfiltered. An absolute start in the
3650
+ * future waits for that object.
3651
+ * - A {@link FillParameters} in `parameters` also retrieves Objects already published, on a fill fetch stream.
3151
3652
  *
3152
- * The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId` and a `ReadableStream` of {@link MoqtObject}s.
3653
+ * The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId`, the `trackAlias` and a `ReadableStream` of {@link MoqtObject}s.
3153
3654
  * Use the `requestId` for {@link MOQtailClient.unsubscribe} or {@link MOQtailClient.subscribeUpdate}. Use the `stream` to decode and display objects.
3154
3655
  *
3155
3656
  * @param args - {@link SubscribeOptions} describing the subscription window and relay forwarding behavior.
3156
- * @returns Either a {@link RequestError} or `{ requestId, stream }` for consuming objects.
3657
+ * @returns Either a {@link RequestError} or `{ requestId, trackAlias, stream }` for consuming objects.
3157
3658
  * @throws : {@link MOQtailError} If the client is destroyed.
3158
3659
  * @throws : {@link ProtocolViolationError} If required fields are missing or inconsistent.
3660
+ * @throws : {@link InvalidFilterError} If the Range Filters exceed the server's MAX_FILTER_RANGES; nothing is sent.
3159
3661
  * @throws : {@link InternalError} On transport/protocol failure (disconnect is triggered before rethrow).
3160
3662
  *
3161
3663
  * @example Subscribe to the latest object and receive future objects as they arrive
3162
3664
  * ```ts
3163
3665
  * const result = await client.subscribe({
3164
3666
  * fullTrackName,
3165
- * filterType: FilterType.LatestObject,
3667
+ * locationFilter: new LocationFilter(LocationFilterType.NextObject),
3166
3668
  * forward: true,
3167
3669
  * groupOrder: GroupOrder.Original,
3168
3670
  * priority: 32
@@ -3174,13 +3676,11 @@ var MOQtailClient = class MOQtailClient {
3174
3676
  * }
3175
3677
  * ```
3176
3678
  *
3177
- * @example Subscribe to a future range (waits for those objects to arrive)
3679
+ * @example Subscribe to a future range of groups (waits for those objects to arrive)
3178
3680
  * ```ts
3179
3681
  * const result = await client.subscribe({
3180
3682
  * fullTrackName,
3181
- * filterType: FilterType.AbsoluteRange,
3182
- * startLocation: futureStart,
3183
- * endGroup: futureEnd,
3683
+ * locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, startGroup, 0n, endGroup),
3184
3684
  * forward: true,
3185
3685
  * groupOrder: GroupOrder.Original,
3186
3686
  * priority: 128
@@ -3189,36 +3689,21 @@ var MOQtailClient = class MOQtailClient {
3189
3689
  */
3190
3690
  async subscribe(args) {
3191
3691
  this.#ensureActive();
3692
+ assertWithinFilterRangeLimit(args.parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.subscribe");
3192
3693
  try {
3193
- let { fullTrackName, priority, groupOrder, forward, filterType, parameters, startLocation, endGroup } = args;
3194
- require_logger.logger.debug("MOQtailClient", `subscribe: ftn="${fullTrackName}" filterType=${filterType} priority=${priority} forward=${forward} groupOrder=${groupOrder}`);
3195
- let msg;
3196
- if (typeof endGroup === "number") endGroup = BigInt(endGroup);
3197
- const baseParams = [
3694
+ const { fullTrackName, priority, groupOrder, forward, locationFilter, parameters } = args;
3695
+ require_logger.logger.debug("MOQtailClient", `subscribe: ftn="${fullTrackName}" locationFilter=${locationFilter?.filterType} priority=${priority} forward=${forward} groupOrder=${groupOrder}`);
3696
+ const msg = new require_model.Subscribe(this.#nextClientRequestId, fullTrackName, [
3198
3697
  new require_model.SubscriberPriority(priority),
3199
- new require_model.Forward(forward),
3698
+ ...forward !== void 0 ? [new require_model.Forward(forward)] : [],
3200
3699
  ...groupOrder !== 0 ? [new require_model.GroupOrderParam(groupOrder)] : [],
3700
+ ...locationFilter ? [locationFilter] : [],
3201
3701
  ...parameters ?? []
3202
- ];
3203
- switch (filterType) {
3204
- case 2:
3205
- msg = require_model.Subscribe.newLatestObject(this.#nextClientRequestId, fullTrackName, baseParams);
3206
- break;
3207
- case 1:
3208
- msg = require_model.Subscribe.newNextGroupStart(this.#nextClientRequestId, fullTrackName, baseParams);
3209
- break;
3210
- case 3:
3211
- if (!startLocation) throw new require_model.ProtocolViolationError("MOQtailClient.subscribe", "FilterType.AbsoluteStart must have a start location");
3212
- msg = require_model.Subscribe.newAbsoluteStart(this.#nextClientRequestId, fullTrackName, startLocation, baseParams);
3213
- break;
3214
- case 4:
3215
- if (startLocation === void 0 || endGroup === void 0) throw new require_model.ProtocolViolationError("MOQtailClient.subscribe", "FilterType.AbsoluteRange must have a start location and an end group");
3216
- if (endGroup > 0 && startLocation.group >= endGroup) throw new require_model.ProtocolViolationError("MOQtailClient.subscribe", "End group must be greater than start group");
3217
- msg = require_model.Subscribe.newAbsoluteRange(this.#nextClientRequestId, fullTrackName, startLocation, endGroup, baseParams);
3218
- break;
3219
- }
3702
+ ]);
3220
3703
  const request = new SubscribeRequest(msg);
3704
+ request.manager = new Subscription(request);
3221
3705
  request.earlyDiscardPolicy = args.earlyDiscardPolicy;
3706
+ request.onEndOfRange = args.onEndOfRange;
3222
3707
  this.requests.set(request.requestId, request);
3223
3708
  this.requestIdMap.addMapping(request.requestId, request.fullTrackName);
3224
3709
  require_logger.logger.debug("MOQtailClient", `subscribe: sending SUBSCRIBE requestId=${msg.requestId} ftn="${fullTrackName}"`);
@@ -3232,11 +3717,10 @@ var MOQtailClient = class MOQtailClient {
3232
3717
  return response;
3233
3718
  } else {
3234
3719
  require_logger.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE_OK requestId=${request.requestId} trackAlias=${response.trackAlias}`);
3235
- this.subscriptions.set(response.trackAlias, request);
3236
- this.subscriptionAliasMap.set(request.requestId, response.trackAlias);
3237
- this.aliasFullTrackNameMap.set(response.trackAlias, fullTrackName);
3720
+ this.#claimTrackAlias(response.trackAlias, request);
3238
3721
  return {
3239
3722
  requestId: msg.requestId,
3723
+ trackAlias: response.trackAlias,
3240
3724
  stream: request.stream
3241
3725
  };
3242
3726
  }
@@ -3266,7 +3750,7 @@ var MOQtailClient = class MOQtailClient {
3266
3750
  *
3267
3751
  * @example Subscribe and later unsubscribe
3268
3752
  * ```ts
3269
- * const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 });
3753
+ * const sub = await client.subscribe({ fullTrackName, locationFilter: new LocationFilter(LocationFilterType.NextObject), forward: true, groupOrder: GroupOrder.Original, priority: 0 });
3270
3754
  * if (!(sub instanceof RequestError)) {
3271
3755
  * // ...consume objects...
3272
3756
  * await client.unsubscribe(sub.requestId);
@@ -3282,31 +3766,25 @@ var MOQtailClient = class MOQtailClient {
3282
3766
  async unsubscribe(requestId) {
3283
3767
  this.#ensureActive();
3284
3768
  if (typeof requestId === "number") requestId = BigInt(requestId);
3285
- let cleanupData = null;
3769
+ const subscription = this.requests.get(requestId);
3770
+ if (!(subscription instanceof SubscribeRequest)) return;
3771
+ const owner = subscription.manager;
3772
+ const targets = owner ? owner.requests.slice() : [subscription];
3286
3773
  try {
3287
- if (this.requests.has(requestId)) {
3288
- const subscription = this.requests.get(requestId);
3289
- if (subscription instanceof SubscribeRequest) {
3290
- const trackAlias = this.subscriptionAliasMap.get(requestId);
3291
- cleanupData = {
3292
- requestId,
3293
- trackAlias,
3294
- subscription
3295
- };
3296
- await this.#resetRequestStream(requestId, 1);
3297
- subscription.unsubscribe();
3298
- }
3774
+ for (const target of targets) {
3775
+ await this.#resetRequestStream(target.requestId, 1);
3776
+ target.unsubscribe();
3299
3777
  }
3300
3778
  } catch (error) {
3301
3779
  await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribe", error instanceof Error ? error.message : String(error)));
3302
3780
  throw error;
3303
3781
  } finally {
3304
- if (cleanupData) {
3305
- this.requests.delete(cleanupData.requestId);
3306
- this.subscriptions.delete(cleanupData.trackAlias);
3307
- this.aliasFullTrackNameMap.delete(cleanupData.trackAlias);
3308
- this.requestIdMap.removeMappingByRequestId(cleanupData.requestId);
3782
+ for (const target of targets) {
3783
+ this.requests.delete(target.requestId);
3784
+ this.requestIdMap.removeMappingByRequestId(target.requestId);
3785
+ this.#releaseTrackAlias(target);
3309
3786
  }
3787
+ owner?.clear();
3310
3788
  }
3311
3789
  }
3312
3790
  /**
@@ -3335,23 +3813,30 @@ var MOQtailClient = class MOQtailClient {
3335
3813
  *
3336
3814
  * @example Trim start forward
3337
3815
  * ```ts
3338
- * await client.subscribeUpdate({ requestId, startLocation: laterLoc, endGroup, forward: true, priority });
3816
+ * await client.subscribeUpdate({ subscriptionRequestId, locationFilter: new LocationFilter(LocationFilterType.AbsoluteStart, laterGroup, 0n), forward: true, priority });
3339
3817
  * ```
3340
3818
  *
3341
3819
  * @example Convert tailing subscription into bounded slice
3342
3820
  * ```ts
3343
- * await client.subscribeUpdate({ requestId, startLocation: origStart, endGroup: cutoffGroup, forward: false, priority });
3821
+ * await client.subscribeUpdate({ subscriptionRequestId, locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, startGroup, 0n, cutoffGroup), forward: false, priority });
3344
3822
  * ```
3345
3823
  *
3346
3824
  * @example Lower priority only
3347
3825
  * ```ts
3348
- * await client.subscribeUpdate({ requestId, startLocation: currentStart, endGroup: currentEnd, forward: true, priority: 200 });
3826
+ * await client.subscribeUpdate({ subscriptionRequestId, forward: true, priority: 200 });
3349
3827
  * ```
3350
3828
  */
3351
3829
  async subscribeUpdate(args) {
3352
3830
  this.#ensureActive();
3353
- let { subscriptionRequestId, priority, forward, parameters, startLocation, endGroup } = args;
3354
- if (endGroup && startLocation.group >= endGroup) throw new require_model.ProtocolViolationError("MOQtailClient.subscribeUpdate", "End group must be greater than start group");
3831
+ const { subscriptionRequestId, priority, forward, parameters, locationFilter } = args;
3832
+ const limit = this.peerMaxFilterRanges;
3833
+ assertWithinFilterRangeLimit(parameters ?? [], limit, "MOQtailClient.subscribeUpdate");
3834
+ const current = this.requests.get(subscriptionRequestId);
3835
+ if (current instanceof SubscribeRequest) {
3836
+ const resulting = [...current.subscribeParameters];
3837
+ require_model.applyMessageParameterUpdate(resulting, parameters ?? []);
3838
+ assertWithinFilterRangeLimit(resulting, limit, "MOQtailClient.subscribeUpdate");
3839
+ }
3355
3840
  try {
3356
3841
  if (this.requests.has(subscriptionRequestId)) {
3357
3842
  if (this.requests.get(subscriptionRequestId) instanceof SubscribeRequest) {
@@ -3363,7 +3848,7 @@ var MOQtailClient = class MOQtailClient {
3363
3848
  const msg = new require_model.RequestUpdate(requestId, [
3364
3849
  new require_model.SubscriberPriority(priority),
3365
3850
  new require_model.Forward(forward),
3366
- new require_model.SubscriptionFilter(4, startLocation, endGroup),
3851
+ ...locationFilter ? [locationFilter] : [],
3367
3852
  ...parameters ?? []
3368
3853
  ]);
3369
3854
  subscription.update(msg);
@@ -3376,70 +3861,153 @@ var MOQtailClient = class MOQtailClient {
3376
3861
  }
3377
3862
  }
3378
3863
  /**
3379
- * Switches an active subscription to a different track while retaining the same subscription parameters.
3864
+ * Switches an active subscription to a different track while retaining the same subscription's
3865
+ * output stream.
3380
3866
  *
3381
- * Use this to change the subscribed track without tearing down and re-establishing a new subscription.
3867
+ * Sends a fresh SUBSCRIBE carrying a SwitchFrom parameter referencing `switchFromRequestId`. A soft
3868
+ * switch may keep delivering objects from the old track for a while after SUBSCRIBE_OK, and this can
3869
+ * be called again before the previous target has produced anything; only the first object actually
3870
+ * delivered by the newest switch target retires everything older.
3382
3871
  *
3383
- * @param args - {@link SwitchOptions} referencing the original subscription `requestId` and new track name.
3384
- * @returns Promise that resolves when the switch control frame is sent.
3872
+ * @param args - {@link SwitchOptions} referencing the subscription to switch from and the new subscription options.
3873
+ * @returns Either a {@link RequestError} (refusal) or `{ requestId, stream }`, where `stream` is the
3874
+ * same {@link https://developer.mozilla.org/docs/Web/API/ReadableStream | ReadableStream} object returned by the original `subscribe()` call.
3385
3875
  * @throws :{@link MOQtailError} If the client is destroyed.
3876
+ * @throws :{@link ProtocolViolationError} If `switchFromRequestId` does not name an active subscription.
3386
3877
  * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
3387
3878
  *
3388
- * @remarks
3389
- * - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
3390
- * - All other subscription parameters (window, forwarding, priority) remain unchanged.
3391
- *
3392
3879
  * @example Switch to a different track
3393
3880
  * ```ts
3394
- * await client.switch({ subscriptionRequestId, fullTrackName: newTrackName });
3881
+ * await client.switch({
3882
+ * switchFromRequestId,
3883
+ * switchMode: SwitchMode.Soft,
3884
+ * newSubscribeOptions: { fullTrackName: newTrackName, priority: 0, groupOrder: GroupOrder.Original, forward: true, locationFilter: new LocationFilter(LocationFilterType.NextObject) },
3885
+ * onDrainDecision: (request) => true
3886
+ * });
3395
3887
  * ```
3396
3888
  */
3397
3889
  async switch(args) {
3398
3890
  this.#ensureActive();
3399
- let { fullTrackName, subscriptionRequestId, parameters } = args;
3891
+ const { switchFromRequestId, switchMode, newSubscribeOptions, onDrainDecision } = args;
3892
+ assertWithinFilterRangeLimit(newSubscribeOptions.parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.switch");
3400
3893
  try {
3401
- if (!this.requests.has(subscriptionRequestId)) throw new require_model.ProtocolViolationError("MOQtailClient.switch", "Unknown subscription request id");
3402
- if (!(this.requests.get(subscriptionRequestId) instanceof SubscribeRequest)) throw new require_model.ProtocolViolationError("MOQtailClient.switch", "Request id is not a subscription");
3403
- const trackAlias = this.subscriptionAliasMap.get(subscriptionRequestId);
3404
- if (!isValidTrackAlias(trackAlias)) throw new require_model.InternalError("MOQtailClient.switch", "Request exists but track alias mapping does not");
3405
- const subscription = this.subscriptions.get(trackAlias);
3406
- if (!subscription) throw new require_model.InternalError("MOQtailClient.switch", "Request exists but subscription does not");
3407
- const requestId = this.#nextClientRequestId;
3408
- this.requests.set(requestId, subscription);
3409
- const switchParams = parameters ?? [];
3410
- const msg = new require_model.Switch(requestId, fullTrackName, subscriptionRequestId, switchParams.map((p) => p.toKeyValuePair()));
3411
- subscription.switch(fullTrackName, switchParams);
3412
- const requestStream = this.#requestStreamFor(subscriptionRequestId, "MOQtailClient.switch");
3413
- await requestStream.send(msg);
3414
- this.#requestStreams.set(requestId, requestStream);
3415
- const response = await subscription;
3416
- if (response instanceof require_model.SubscribeOk) {
3417
- this.aliasFullTrackNameMap.set(response.trackAlias, fullTrackName);
3418
- this.pendingStateUpdates.set(subscriptionRequestId, (newTrackAlias) => {
3419
- if (newTrackAlias !== response.trackAlias) return false;
3420
- this.subscriptions.set(response.trackAlias, subscription);
3421
- this.subscriptionAliasMap.set(requestId, response.trackAlias);
3422
- subscription.requestId = requestId;
3423
- this.requestIdMap.removeMappingByRequestId(subscriptionRequestId);
3424
- this.requestIdMap.addMapping(subscriptionRequestId, fullTrackName);
3425
- this.subscriptions.delete(trackAlias);
3426
- return true;
3427
- });
3428
- return {
3429
- requestId,
3430
- stream: subscription.stream
3431
- };
3432
- } else {
3433
- this.requestIdMap.removeMappingByRequestId(requestId);
3434
- this.requests.delete(requestId);
3435
- return response;
3436
- }
3894
+ const fromRequest = this.requests.get(switchFromRequestId);
3895
+ if (!(fromRequest instanceof SubscribeRequest) || !fromRequest.manager) throw new require_model.ProtocolViolationError("MOQtailClient.switch", "switchFromRequestId is not an active subscription");
3896
+ const subscription = fromRequest.manager;
3897
+ subscription.onSuperseded ??= (superseded) => {
3898
+ for (const request of superseded) this.#retireSwitchedRequest(request);
3899
+ };
3900
+ subscription.drainTimeoutMs = this.switchDrainTimeoutMs;
3901
+ if (onDrainDecision) subscription.onDrainDecision = onDrainDecision;
3902
+ const drains = switchMode === 1;
3903
+ if (newSubscribeOptions.parameters?.find(require_model.MessageParameter.isSwitchFrom)) require_logger.logger.warn("MOQtailClient", `switch: overwriting existing SwitchFrom parameter for requestId=${switchFromRequestId}`);
3904
+ const parameters = [...newSubscribeOptions.parameters?.filter((p) => !require_model.MessageParameter.isSwitchFrom(p)) ?? [], new require_model.SwitchFrom(switchFromRequestId, switchMode, drains)];
3905
+ const result = await this.subscribe({
3906
+ ...newSubscribeOptions,
3907
+ parameters
3908
+ });
3909
+ if (result instanceof require_model.RequestError) return result;
3910
+ const newRequest = this.requests.get(result.requestId);
3911
+ subscription.addSwitchTarget(newRequest, drains);
3912
+ return {
3913
+ requestId: result.requestId,
3914
+ stream: subscription.stream
3915
+ };
3437
3916
  } catch (error) {
3438
3917
  await this.disconnect(new require_model.InternalError("MOQtailClient.switch", error instanceof Error ? error.message : String(error)));
3439
3918
  throw error;
3440
3919
  }
3441
3920
  }
3442
3921
  /**
3922
+ * Ends a subscription whose publisher has said how many streams it opened and has
3923
+ * now delivered all of them, and reports whether that happened.
3924
+ *
3925
+ * Both halves of that arrive on their own: a PUBLISH_DONE carries the count, and
3926
+ * the streams finish whenever they finish. Either can be last, so this is checked
3927
+ * from both -- a drained switch target has usually finished its streams well
3928
+ * before the PUBLISH_DONE that ends it.
3929
+ */
3930
+ completeSubscription(request, force = false) {
3931
+ if (!force && (!request.expectedStreams || request.streamsAccepted < request.expectedStreams)) return false;
3932
+ const owner = request.manager;
3933
+ if (owner) {
3934
+ owner.drop(request);
3935
+ if (owner.requests.length === 0) owner.controller.close();
3936
+ } else request.controller?.close();
3937
+ this.#releaseTrackAlias(request);
3938
+ this.requests.delete(request.requestId);
3939
+ this.requestIdMap.removeMappingByRequestId(request.requestId);
3940
+ this.#closeRequestStream(request.requestId);
3941
+ require_logger.logger.debug("MOQtailClient", `subscription for request ${request.requestId} completed`);
3942
+ return true;
3943
+ }
3944
+ /**
3945
+ * Records the alias a publisher just named for `request`, releasing any data stream
3946
+ * that arrived before the control message carrying it.
3947
+ */
3948
+ #claimTrackAlias(trackAlias, holder) {
3949
+ this.subscriptions.set(trackAlias, holder);
3950
+ this.subscriptionAliasMap.set(holder.requestId, trackAlias);
3951
+ this.aliasFullTrackNameMap.set(trackAlias, holder.fullTrackName);
3952
+ const waiters = this.#aliasWaiters.get(trackAlias);
3953
+ if (!waiters) return;
3954
+ this.#aliasWaiters.delete(trackAlias);
3955
+ for (const waiter of waiters) waiter();
3956
+ }
3957
+ /**
3958
+ * Waits out the race between a subscription's data streams and the control message
3959
+ * that names their track alias. The two travel on separate streams, so nothing
3960
+ * orders them and the data can arrive first; giving up on it immediately would drop
3961
+ * a whole subgroup, which is a visible gap in the media.
3962
+ *
3963
+ * Returns once the alias is claimed, or once
3964
+ * {@link MOQtailClient.trackAliasResolutionTimeoutMs} elapses with it still unclaimed.
3965
+ */
3966
+ async #waitForTrackAlias(trackAlias) {
3967
+ require_logger.logger.debug("MOQtailClient", `data stream waiting for the track alias ${trackAlias} to be named`);
3968
+ return new Promise((resolve) => {
3969
+ let waiters = this.#aliasWaiters.get(trackAlias);
3970
+ if (!waiters) {
3971
+ waiters = /* @__PURE__ */ new Set();
3972
+ this.#aliasWaiters.set(trackAlias, waiters);
3973
+ }
3974
+ const claimed = () => {
3975
+ clearTimeout(timeoutId);
3976
+ resolve();
3977
+ };
3978
+ const timeoutId = setTimeout(() => {
3979
+ waiters.delete(claimed);
3980
+ if (waiters.size === 0) this.#aliasWaiters.delete(trackAlias);
3981
+ resolve();
3982
+ }, this.trackAliasResolutionTimeoutMs);
3983
+ waiters.add(claimed);
3984
+ });
3985
+ }
3986
+ /**
3987
+ * Drops `request`'s hold on its track alias.
3988
+ *
3989
+ * An alias names a track, not a subscription, so two requests for the same track
3990
+ * carry the same one -- a switch back to a track whose earlier request has not
3991
+ * been retired yet is exactly that. The alias-keyed maps can only describe the
3992
+ * request that holds the alias now, so the other one clears its own row and leaves
3993
+ * theirs alone.
3994
+ */
3995
+ #releaseTrackAlias(holder) {
3996
+ const trackAlias = this.subscriptionAliasMap.get(holder.requestId);
3997
+ this.subscriptionAliasMap.delete(holder.requestId);
3998
+ if (trackAlias === void 0) return;
3999
+ if (this.subscriptions.get(trackAlias) !== holder) return;
4000
+ this.subscriptions.delete(trackAlias);
4001
+ this.aliasFullTrackNameMap.delete(trackAlias);
4002
+ }
4003
+ /** Tears down a switch target that lost the handover race to a newer one. */
4004
+ async #retireSwitchedRequest(request) {
4005
+ this.requests.delete(request.requestId);
4006
+ this.requestIdMap.removeMappingByRequestId(request.requestId);
4007
+ this.#releaseTrackAlias(request);
4008
+ await this.#resetRequestStream(request.requestId, 1);
4009
+ }
4010
+ /**
3443
4011
  * One-shot retrieval of a bounded object span, optionally anchored to an existing subscription, returning a stream of {@link MoqtObject}s.
3444
4012
  *
3445
4013
  * Choose a fetch type via `typeAndProps.type`:
@@ -3470,15 +4038,13 @@ var MOQtailClient = class MOQtailClient {
3470
4038
  * - Result stream is finite; reader close occurs automatically when last object delivered.
3471
4039
  * - Use {@link MOQtailClient.fetchCancel} only for early termination (not yet fully implemented: see TODO in code).
3472
4040
  *
3473
- * @example Standalone window
4041
+ * @example Groups 10 through 12, inclusive
3474
4042
  * ```ts
3475
4043
  * const r = await client.fetch({
4044
+ * fullTrackName,
3476
4045
  * priority: 64,
3477
4046
  * groupOrder: GroupOrder.Original,
3478
- * typeAndProps: {
3479
- * type: FetchType.Standalone,
3480
- * props: { fullTrackName, startLocation, endLocation }
3481
- * }
4047
+ * locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, 10n, 0n, 12n)
3482
4048
  * })
3483
4049
  * if (!(r instanceof RequestError)) {
3484
4050
  * for await (const obj of r.stream as any) {
@@ -3487,68 +4053,36 @@ var MOQtailClient = class MOQtailClient {
3487
4053
  * }
3488
4054
  * ```
3489
4055
  *
3490
- * @example Relative to live subscription (e.g. last 5 groups)
4056
+ * @example The last 5 groups, counting the current one
3491
4057
  * ```ts
3492
- * const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 })
3493
- * if (!(sub instanceof RequestError)) {
3494
- * const slice = await client.fetch({
3495
- * priority: 32,
3496
- * groupOrder: GroupOrder.Original,
3497
- * typeAndProps: { type: FetchType.Relative, props: { joiningRequestId: sub.requestId, joiningStart: 0n } }
3498
- * })
3499
- * }
4058
+ * const slice = await client.fetch({
4059
+ * fullTrackName,
4060
+ * priority: 32,
4061
+ * groupOrder: GroupOrder.Original,
4062
+ * locationFilter: new LocationFilter(LocationFilterType.RelativeStart, 5n)
4063
+ * })
3500
4064
  * ```
3501
4065
  */
3502
4066
  async fetch(args) {
3503
4067
  this.#ensureActive();
4068
+ assertWithinFilterRangeLimit(args.parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.fetch");
3504
4069
  try {
3505
- const { priority, groupOrder, typeAndProps, parameters } = args;
4070
+ const { priority, groupOrder, fullTrackName, locationFilter, parameters } = args;
3506
4071
  if (priority < 0 || priority > 255) throw new require_model.ProtocolViolationError("MOQtailClient.fetch", `subscriberPriority: ${priority} must be in range of [0-255]`);
3507
4072
  const params = [
3508
4073
  new require_model.SubscriberPriority(priority),
4074
+ ...locationFilter ? [locationFilter] : [],
3509
4075
  ...groupOrder !== 0 ? [new require_model.GroupOrderParam(groupOrder)] : [],
3510
4076
  ...parameters ?? []
3511
4077
  ];
3512
- let msg;
3513
- let joiningRequest;
3514
4078
  const requestId = this.#nextClientRequestId;
3515
- require_logger.logger.log("MOQtailClient", "fetch: generated requestId:", requestId, "for fetch type:", typeAndProps.type, "current #dontUseRequestId:", this.#dontUseRequestId);
3516
- switch (typeAndProps.type) {
3517
- case 1:
3518
- msg = new require_model.Fetch(requestId, {
3519
- type: typeAndProps.type,
3520
- props: typeAndProps.props
3521
- }, params);
3522
- break;
3523
- case 2:
3524
- joiningRequest = this.requests.get(typeAndProps.props.joiningRequestId);
3525
- if (!(joiningRequest instanceof SubscribeRequest)) throw new require_model.ProtocolViolationError("MOQtailClient.fetch", `No subscribe request for the given joiningRequestId: ${typeAndProps.props.joiningRequestId}`);
3526
- msg = new require_model.Fetch(requestId, {
3527
- type: typeAndProps.type,
3528
- props: {
3529
- ...typeAndProps.props,
3530
- joiningRequestId: this.#wireRequestId(typeAndProps.props.joiningRequestId)
3531
- }
3532
- }, params);
3533
- break;
3534
- case 3:
3535
- joiningRequest = this.requests.get(typeAndProps.props.joiningRequestId);
3536
- if (!(joiningRequest instanceof SubscribeRequest)) throw new require_model.ProtocolViolationError("MOQtailClient.fetch", `No subscribe request for the given joiningRequestId: ${typeAndProps.props.joiningRequestId}`);
3537
- msg = new require_model.Fetch(requestId, {
3538
- type: typeAndProps.type,
3539
- props: {
3540
- ...typeAndProps.props,
3541
- joiningRequestId: this.#wireRequestId(typeAndProps.props.joiningRequestId)
3542
- }
3543
- }, params);
3544
- break;
3545
- }
4079
+ require_logger.logger.log("MOQtailClient", "fetch: generated requestId:", requestId, "current #dontUseRequestId:", this.#dontUseRequestId);
4080
+ const msg = new require_model.Fetch(requestId, fullTrackName, params);
3546
4081
  const request = new FetchRequest(msg);
3547
- require_logger.logger.log("MOQtailClient", "fetch: storing FetchRequest with requestId:", msg.requestId, "for fetch type:", typeAndProps.type);
4082
+ request.onEndOfRange = args.onEndOfRange;
3548
4083
  require_logger.logger.log("MOQtailClient", "fetch: full fetch message:", {
3549
4084
  requestId: msg.requestId,
3550
- fetchType: typeAndProps.type,
3551
- joiningRequestId: typeAndProps.type !== 1 ? typeAndProps.props.joiningRequestId : "N/A"
4085
+ fullTrackName: `${fullTrackName}`
3552
4086
  });
3553
4087
  this.requests.set(msg.requestId, request);
3554
4088
  require_logger.logger.log("MOQtailClient", "fetch: about to send fetch message to server");
@@ -3592,7 +4126,7 @@ var MOQtailClient = class MOQtailClient {
3592
4126
  *
3593
4127
  * @example Cancel shortly after starting
3594
4128
  * ```ts
3595
- * const r = await client.fetch({ priority: 32, groupOrder: GroupOrder.Original, typeAndProps: { type: FetchType.Standalone, props: { fullTrackName, startLocation, endLocation } } })
4129
+ * const r = await client.fetch({ fullTrackName, priority: 32, groupOrder: GroupOrder.Original, locationFilter })
3596
4130
  * if (!(r instanceof RequestError)) {
3597
4131
  * // user navigated away
3598
4132
  * await client.fetchCancel(r.requestId)
@@ -3651,7 +4185,8 @@ var MOQtailClient = class MOQtailClient {
3651
4185
  this.#ensureActive();
3652
4186
  try {
3653
4187
  if (typeof publishRequestId === "number") publishRequestId = BigInt(publishRequestId);
3654
- const msg = new require_model.PublishDone(statusCode, 0n, new require_model.ReasonPhrase(reasonPhrase));
4188
+ const publication = this.publications.get(publishRequestId);
4189
+ const msg = new require_model.PublishDone(statusCode, publication instanceof PublishPublication ? publication.streamsOpened : require_model.PublishDone.UNKNOWN_STREAM_COUNT, new require_model.ReasonPhrase(reasonPhrase));
3655
4190
  const requestStream = this.#requestStreams.get(publishRequestId);
3656
4191
  if (requestStream) {
3657
4192
  await requestStream.send(msg);
@@ -3678,15 +4213,14 @@ var MOQtailClient = class MOQtailClient {
3678
4213
  streamController = c;
3679
4214
  } });
3680
4215
  this.requestIdMap.addMapping(msg.requestId, msg.fullTrackName);
3681
- this.subscriptionAliasMap.set(msg.requestId, msg.trackAlias);
3682
- this.aliasFullTrackNameMap.set(msg.trackAlias, msg.fullTrackName);
3683
4216
  const receiver = {
3684
4217
  requestId: msg.requestId,
4218
+ fullTrackName: msg.fullTrackName,
3685
4219
  streamsAccepted: 0,
3686
4220
  largestLocation: void 0,
3687
4221
  controller: streamController
3688
4222
  };
3689
- this.subscriptions.set(msg.trackAlias, receiver);
4223
+ this.#claimTrackAlias(msg.trackAlias, receiver);
3690
4224
  return stream;
3691
4225
  }
3692
4226
  /**
@@ -3806,7 +4340,7 @@ var MOQtailClient = class MOQtailClient {
3806
4340
  try {
3807
4341
  const params = parameters ?? [];
3808
4342
  const msg = new require_model.SubscribeNamespace(this.#nextClientRequestId, trackNamespacePrefix, params);
3809
- const requestStream = await RequestStream.open(this.webTransport, msg);
4343
+ const requestStream = await RequestStream.open(this.webTransport, msg, this.#requestStreamHooks);
3810
4344
  this.#requestStreams.set(msg.requestId, requestStream);
3811
4345
  require_logger.logger.log("MOQtailClient", "subscribeNamespace | sent msg", msg, msg.trackNamespacePrefix.toUtf8Path(), msg.requestId);
3812
4346
  const response = await requestStream.next();
@@ -3833,9 +4367,10 @@ var MOQtailClient = class MOQtailClient {
3833
4367
  }
3834
4368
  async subscribeTracks(trackNamespacePrefix, parameters) {
3835
4369
  this.#ensureActive();
4370
+ assertWithinFilterRangeLimit(parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.subscribeTracks");
3836
4371
  try {
3837
4372
  const msg = new require_model.SubscribeTracks(this.#nextClientRequestId, trackNamespacePrefix, parameters ?? []);
3838
- const requestStream = await RequestStream.open(this.webTransport, msg);
4373
+ const requestStream = await RequestStream.open(this.webTransport, msg, this.#requestStreamHooks);
3839
4374
  this.#requestStreams.set(msg.requestId, requestStream);
3840
4375
  const response = await requestStream.next();
3841
4376
  if (!response) throw new require_model.InternalError("MOQtailClient.subscribeTracks", "Stream closed before response");
@@ -3906,7 +4441,7 @@ var MOQtailClient = class MOQtailClient {
3906
4441
  async trackStatus(fullTrackName, trackAlias, parameters) {
3907
4442
  this.#ensureActive();
3908
4443
  try {
3909
- const msg = require_model.TrackStatus.newLatestObject(this.#nextClientRequestId, trackAlias, fullTrackName, 128, 0, false, parameters ?? []);
4444
+ const msg = new require_model.TrackStatus(this.#nextClientRequestId, trackAlias, fullTrackName, 128, 0, false, new require_model.LocationFilter(5), parameters ?? []);
3910
4445
  const request = new TrackStatusRequest(msg);
3911
4446
  this.requests.set(msg.requestId, request);
3912
4447
  await this.#openRequestStream(msg.requestId, msg);
@@ -3924,8 +4459,28 @@ var MOQtailClient = class MOQtailClient {
3924
4459
  *
3925
4460
  * @param requestId - The requestId carried by `first`; the key the stream is filed under.
3926
4461
  */
4462
+ /**
4463
+ * Hands a data stream {@link MOQtailClient.onDataEvent}, read at call time so an observer assigned
4464
+ * after connecting still sees streams that are already open.
4465
+ *
4466
+ * @internal
4467
+ */
4468
+ dataStreamObserver(fullTrackNameOf) {
4469
+ return {
4470
+ onDataEvent: (event) => this.onDataEvent?.(event),
4471
+ ...fullTrackNameOf && { fullTrackNameOf }
4472
+ };
4473
+ }
4474
+ /**
4475
+ * Forwards request-stream traffic to {@link onMessageSent} and {@link onMessageReceived},
4476
+ * read at call time so callbacks assigned after connecting still see it.
4477
+ */
4478
+ #requestStreamHooks = {
4479
+ onMessageSent: (msg) => this.onMessageSent?.(msg),
4480
+ onMessageReceived: (msg) => this.onMessageReceived?.(msg)
4481
+ };
3927
4482
  async #openRequestStream(requestId, first) {
3928
- const requestStream = await RequestStream.open(this.webTransport, first);
4483
+ const requestStream = await RequestStream.open(this.webTransport, first, this.#requestStreamHooks);
3929
4484
  this.#requestStreams.set(requestId, requestStream);
3930
4485
  this.#pumpRequestStream(requestId, requestStream);
3931
4486
  return requestStream;
@@ -3961,7 +4516,6 @@ var MOQtailClient = class MOQtailClient {
3961
4516
  const wireRequestId = this.#nextClientRequestId;
3962
4517
  const reissued = require_model.ControlMessage.deserialize(require_model.ControlMessage.serialize(first));
3963
4518
  reissued.requestId = wireRequestId;
3964
- this.#wireRequestIds.set(requestId, wireRequestId);
3965
4519
  this.#clientRequestIds.set(wireRequestId, requestId);
3966
4520
  oldStream.migrated = true;
3967
4521
  await oldStream.close();
@@ -3969,11 +4523,15 @@ var MOQtailClient = class MOQtailClient {
3969
4523
  require_logger.logger.log("MOQtailClient", `re-issued request ${requestId} as request id ${wireRequestId}`);
3970
4524
  return true;
3971
4525
  }
3972
- /** The Request ID `requestId` currently travels under, which a migration has moved on. */
3973
- #wireRequestId(requestId) {
3974
- return this.#wireRequestIds.get(requestId) ?? requestId;
3975
- }
3976
4526
  /** The request a peer-supplied Request ID belongs to, undoing any migration. */
4527
+ /** A handler that throws must not end the stream the marker arrived on. */
4528
+ #notifyEndOfRange(handler, marker) {
4529
+ try {
4530
+ handler?.(marker.endOfRange, marker.location);
4531
+ } catch (handlerError) {
4532
+ require_logger.logger.warn("MOQtailClient", "End of Range handler error:", handlerError);
4533
+ }
4534
+ }
3977
4535
  #clientRequestId(wireRequestId) {
3978
4536
  return this.#clientRequestIds.get(wireRequestId) ?? wireRequestId;
3979
4537
  }
@@ -4023,8 +4581,6 @@ var MOQtailClient = class MOQtailClient {
4023
4581
  }
4024
4582
  /**
4025
4583
  * Resets the request stream filed under `requestId` with `code`, if it is still open.
4026
- * §3.3.2: this is how draft-18 cancels a request now that the cancel messages are
4027
- * gone — the peer reads the code back off the RESET_STREAM.
4028
4584
  */
4029
4585
  async #resetRequestStream(requestId, code) {
4030
4586
  const requestStream = this.#requestStreams.get(requestId);
@@ -4041,9 +4597,7 @@ var MOQtailClient = class MOQtailClient {
4041
4597
  await this.#closeRequestStream(requestId);
4042
4598
  }
4043
4599
  /**
4044
- * Reads the shared control stream, which after draft-18 §3.3 carries only SETUP and
4045
- * GOAWAY. SETUP is consumed by the handshake, so GOAWAY is all that is handled here;
4046
- * every request type has its own bidi stream.
4600
+ * Reads the shared control stream, every request type has its own bidi stream.
4047
4601
  */
4048
4602
  async #handleIncomingControlMessages() {
4049
4603
  this.#ensureActive();
@@ -4054,7 +4608,7 @@ var MOQtailClient = class MOQtailClient {
4054
4608
  if (done) throw new require_model.MOQtailError("WebTransport session is terminated");
4055
4609
  const handler = getHandlerForControlMessage(msg);
4056
4610
  if (!handler) {
4057
- require_logger.logger.warn("MOQtailClient", `${msg.constructor.name} on the control stream; draft-18 allows only SETUP and GOAWAY there`);
4611
+ require_logger.logger.warn("MOQtailClient", `${msg.constructor.name} on the control stream`);
4058
4612
  continue;
4059
4613
  }
4060
4614
  await handler(this, msg);
@@ -4092,7 +4646,7 @@ var MOQtailClient = class MOQtailClient {
4092
4646
  while (true) {
4093
4647
  const { value: biStream, done } = await reader.read();
4094
4648
  if (done) break;
4095
- this.#dispatchIncomingRequestStream(new RequestStream(biStream));
4649
+ this.#dispatchIncomingRequestStream(new RequestStream(biStream, this.#requestStreamHooks));
4096
4650
  }
4097
4651
  })();
4098
4652
  }
@@ -4139,28 +4693,14 @@ var MOQtailClient = class MOQtailClient {
4139
4693
  const request = this.requests.get(this.#clientRequestId(header.requestId));
4140
4694
  if (!(request instanceof FetchRequest)) return 0;
4141
4695
  return require_model.MessageParameter.groupOrderOf(request.message.parameters);
4142
- });
4696
+ }, this.dataStreamObserver((header) => header instanceof require_model.SubgroupHeader ? this.aliasFullTrackNameMap.get(header.trackAlias) : void 0));
4143
4697
  const header = recvStream.header;
4144
4698
  const reader = recvStream.stream.getReader();
4699
+ let forceComplete = false;
4145
4700
  if (header instanceof require_model.FetchHeader) {
4146
4701
  const request = this.requests.get(this.#clientRequestId(header.requestId));
4147
4702
  if (request && request instanceof FetchRequest) {
4148
- let fullTrackName;
4149
- switch (request.message.typeAndProps.type) {
4150
- case 1:
4151
- fullTrackName = request.message.typeAndProps.props.fullTrackName;
4152
- break;
4153
- case 2:
4154
- case 3: {
4155
- const joiningSubscription = this.requests.get(request.message.typeAndProps.props.joiningRequestId);
4156
- if (joiningSubscription instanceof SubscribeRequest) {
4157
- fullTrackName = joiningSubscription.fullTrackName;
4158
- break;
4159
- }
4160
- throw new require_model.ProtocolViolationError("_handleRecvStreams", "No active subscription for given joining request id");
4161
- }
4162
- default: throw new require_model.ProtocolViolationError("_handleRecvStreams", "Unknown fetchType");
4163
- }
4703
+ const fullTrackName = request.message.fullTrackName;
4164
4704
  try {
4165
4705
  while (true) {
4166
4706
  const { done, value: nextObject } = await reader.read();
@@ -4170,7 +4710,10 @@ var MOQtailClient = class MOQtailClient {
4170
4710
  }
4171
4711
  if (nextObject) {
4172
4712
  if (nextObject instanceof require_model.FetchObject) {
4173
- if (nextObject.kind === "end_of_range") continue;
4713
+ if (nextObject.kind === "end_of_range") {
4714
+ this.#notifyEndOfRange(request.onEndOfRange, nextObject);
4715
+ continue;
4716
+ }
4174
4717
  const moqtObject = require_model.MoqtObject.fromFetchObject(nextObject, fullTrackName);
4175
4718
  request.controller?.enqueue(moqtObject);
4176
4719
  continue;
@@ -4183,18 +4726,43 @@ var MOQtailClient = class MOQtailClient {
4183
4726
  }
4184
4727
  return;
4185
4728
  }
4729
+ if (request instanceof SubscribeRequest) {
4730
+ request.streamsAccepted++;
4731
+ try {
4732
+ while (true) {
4733
+ const { done, value: nextObject } = await reader.read();
4734
+ if (done) break;
4735
+ if (!nextObject) continue;
4736
+ if (!(nextObject instanceof require_model.FetchObject)) throw new require_model.ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
4737
+ if (nextObject.kind === "end_of_range") {
4738
+ this.#notifyEndOfRange(request.onEndOfRange, nextObject);
4739
+ continue;
4740
+ }
4741
+ const moqtObject = require_model.MoqtObject.fromFetchObject(nextObject, request.fullTrackName);
4742
+ if (request.manager) {
4743
+ if (!request.manager.deliver(request, moqtObject)) {
4744
+ await recvStream.stopSending(1);
4745
+ forceComplete = true;
4746
+ break;
4747
+ }
4748
+ } else request.controller?.enqueue(moqtObject);
4749
+ }
4750
+ } finally {
4751
+ reader.releaseLock();
4752
+ }
4753
+ this.completeSubscription(request, forceComplete);
4754
+ return;
4755
+ }
4186
4756
  throw new require_model.ProtocolViolationError("MOQtailClient", "No request for received request id");
4187
4757
  } else {
4188
4758
  let subscription = this.subscriptions.get(header.trackAlias);
4189
4759
  if (!subscription) {
4190
- for (const [subscriptionId, callback] of this.pendingStateUpdates) if (callback(header.trackAlias)) {
4191
- subscription = this.subscriptions.get(header.trackAlias);
4192
- this.pendingStateUpdates.delete(subscriptionId);
4193
- break;
4194
- }
4760
+ await this.#waitForTrackAlias(header.trackAlias);
4761
+ subscription = this.subscriptions.get(header.trackAlias);
4195
4762
  }
4196
4763
  if (subscription) {
4197
4764
  subscription.streamsAccepted++;
4765
+ const fullTrackName = subscription.fullTrackName;
4198
4766
  let firstObjectId = null;
4199
4767
  let subgroupTimeoutId;
4200
4768
  const effectiveDiscardPolicy = subscription.earlyDiscardPolicy ?? this.#earlyDiscardPolicy;
@@ -4212,12 +4780,16 @@ var MOQtailClient = class MOQtailClient {
4212
4780
  if (require_model.SubgroupHeaderType.isSubgroupIdZero(header.type)) subgroupId = 0n;
4213
4781
  else if (require_model.SubgroupHeaderType.isSubgroupIdFirstObjectId(header.type)) subgroupId = firstObjectId ?? null;
4214
4782
  else if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(header.type)) subgroupId = header.subgroupId ?? null;
4215
- const fullTrackName = this.aliasFullTrackNameMap.get(header.trackAlias);
4216
- if (!fullTrackName) throw new require_model.ProtocolViolationError("MOQtailClient", "No full track name for received track alias");
4217
4783
  const moqtObject = require_model.MoqtObject.fromSubgroupObject(nextObject, header.groupId, header.publisherPriority, subgroupId, fullTrackName);
4218
4784
  if (!subscription.largestLocation) subscription.largestLocation = moqtObject.location;
4219
4785
  if (subscription.largestLocation.compare(moqtObject.location) == -1) subscription.largestLocation = moqtObject.location;
4220
- subscription.controller?.enqueue(moqtObject);
4786
+ if (subscription.manager) {
4787
+ if (!subscription.manager.deliver(subscription, moqtObject)) {
4788
+ forceComplete = true;
4789
+ await recvStream.stopSending(1);
4790
+ break;
4791
+ }
4792
+ } else subscription.controller?.enqueue(moqtObject);
4221
4793
  continue;
4222
4794
  }
4223
4795
  throw new require_model.ProtocolViolationError("MOQtailClient", "Received fetch object after subgroup header");
@@ -4226,11 +4798,7 @@ var MOQtailClient = class MOQtailClient {
4226
4798
  } finally {
4227
4799
  if (subgroupTimeoutId !== void 0) clearTimeout(subgroupTimeoutId);
4228
4800
  }
4229
- if (subscription.expectedStreams && subscription.expectedStreams === subscription.streamsAccepted) {
4230
- subscription.controller?.close();
4231
- this.subscriptions.delete(header.trackAlias);
4232
- this.requests.delete(subscription.requestId);
4233
- }
4801
+ this.completeSubscription(subscription, forceComplete);
4234
4802
  return;
4235
4803
  }
4236
4804
  throw new require_model.ProtocolViolationError("MOQtailClient", "No subscription for received track alias");
@@ -4374,6 +4942,30 @@ Object.defineProperty(exports, "ControlStream", {
4374
4942
  return ControlStream;
4375
4943
  }
4376
4944
  });
4945
+ Object.defineProperty(exports, "DEFAULT_MAX_FILTER_RANGES", {
4946
+ enumerable: true,
4947
+ get: function() {
4948
+ return DEFAULT_MAX_FILTER_RANGES;
4949
+ }
4950
+ });
4951
+ Object.defineProperty(exports, "DEFAULT_SWITCH_DRAIN_TIMEOUT_MS", {
4952
+ enumerable: true,
4953
+ get: function() {
4954
+ return DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
4955
+ }
4956
+ });
4957
+ Object.defineProperty(exports, "DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS", {
4958
+ enumerable: true,
4959
+ get: function() {
4960
+ return DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS;
4961
+ }
4962
+ });
4963
+ Object.defineProperty(exports, "DataStreamReporter", {
4964
+ enumerable: true,
4965
+ get: function() {
4966
+ return DataStreamReporter;
4967
+ }
4968
+ });
4377
4969
  Object.defineProperty(exports, "FetchPublication", {
4378
4970
  enumerable: true,
4379
4971
  get: function() {
@@ -4488,6 +5080,12 @@ Object.defineProperty(exports, "SubscribeRequest", {
4488
5080
  return SubscribeRequest;
4489
5081
  }
4490
5082
  });
5083
+ Object.defineProperty(exports, "Subscription", {
5084
+ enumerable: true,
5085
+ get: function() {
5086
+ return Subscription;
5087
+ }
5088
+ });
4491
5089
  Object.defineProperty(exports, "TrackStatusRequest", {
4492
5090
  enumerable: true,
4493
5091
  get: function() {