diff --git a/public/libs/red5pro/docs/api/README.md b/public/libs/red5pro/docs/api/README.md index 8ffcb615..5d98cd44 100644 --- a/public/libs/red5pro/docs/api/README.md +++ b/public/libs/red5pro/docs/api/README.md @@ -1,4 +1,4 @@ -**Red5 Pro WebRTC SDK v16.0.0-beta.1** +**Red5 Pro WebRTC SDK v16.0.0-beta.2** *** diff --git a/public/libs/red5pro/docs/api/classes/Event.md b/public/libs/red5pro/docs/api/classes/Event.md index ae9fd93b..46d922ed 100644 --- a/public/libs/red5pro/docs/api/classes/Event.md +++ b/public/libs/red5pro/docs/api/classes/Event.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/EventEmitter.md b/public/libs/red5pro/docs/api/classes/EventEmitter.md index 543b8cc8..5035e897 100644 --- a/public/libs/red5pro/docs/api/classes/EventEmitter.md +++ b/public/libs/red5pro/docs/api/classes/EventEmitter.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/HLSSubscriber.md b/public/libs/red5pro/docs/api/classes/HLSSubscriber.md index 83e48635..87558ff3 100644 --- a/public/libs/red5pro/docs/api/classes/HLSSubscriber.md +++ b/public/libs/red5pro/docs/api/classes/HLSSubscriber.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/LiveSeekClient.md b/public/libs/red5pro/docs/api/classes/LiveSeekClient.md index bd122d5f..415a7fdb 100644 --- a/public/libs/red5pro/docs/api/classes/LiveSeekClient.md +++ b/public/libs/red5pro/docs/api/classes/LiveSeekClient.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/MOQCatalog.md b/public/libs/red5pro/docs/api/classes/MOQCatalog.md index 8aa89533..a5c4515b 100644 --- a/public/libs/red5pro/docs/api/classes/MOQCatalog.md +++ b/public/libs/red5pro/docs/api/classes/MOQCatalog.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/MOQPublisher.md b/public/libs/red5pro/docs/api/classes/MOQPublisher.md index e6b00109..609168b5 100644 --- a/public/libs/red5pro/docs/api/classes/MOQPublisher.md +++ b/public/libs/red5pro/docs/api/classes/MOQPublisher.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/MOQSubscriber.md b/public/libs/red5pro/docs/api/classes/MOQSubscriber.md index 18b0eac9..54d26aa2 100644 --- a/public/libs/red5pro/docs/api/classes/MOQSubscriber.md +++ b/public/libs/red5pro/docs/api/classes/MOQSubscriber.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/MessageChannel.md b/public/libs/red5pro/docs/api/classes/MessageChannel.md index 06e7cc51..d44ffaf5 100644 --- a/public/libs/red5pro/docs/api/classes/MessageChannel.md +++ b/public/libs/red5pro/docs/api/classes/MessageChannel.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/MessageChannelEvent.md b/public/libs/red5pro/docs/api/classes/MessageChannelEvent.md index 86851eee..dca8576d 100644 --- a/public/libs/red5pro/docs/api/classes/MessageChannelEvent.md +++ b/public/libs/red5pro/docs/api/classes/MessageChannelEvent.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/MessageTransportStateEvent.md b/public/libs/red5pro/docs/api/classes/MessageTransportStateEvent.md index 90b1f792..78eb1001 100644 --- a/public/libs/red5pro/docs/api/classes/MessageTransportStateEvent.md +++ b/public/libs/red5pro/docs/api/classes/MessageTransportStateEvent.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/PlaybackController.md b/public/libs/red5pro/docs/api/classes/PlaybackController.md index 0e307b73..f7c2e18b 100644 --- a/public/libs/red5pro/docs/api/classes/PlaybackController.md +++ b/public/libs/red5pro/docs/api/classes/PlaybackController.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/PlaybackControls.md b/public/libs/red5pro/docs/api/classes/PlaybackControls.md index bcd632ae..72075c40 100644 --- a/public/libs/red5pro/docs/api/classes/PlaybackControls.md +++ b/public/libs/red5pro/docs/api/classes/PlaybackControls.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/PubNubClient.md b/public/libs/red5pro/docs/api/classes/PubNubClient.md index 2ca29d82..ee82fc05 100644 --- a/public/libs/red5pro/docs/api/classes/PubNubClient.md +++ b/public/libs/red5pro/docs/api/classes/PubNubClient.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/PubNubEvent.md b/public/libs/red5pro/docs/api/classes/PubNubEvent.md index 57b31044..267bba7d 100644 --- a/public/libs/red5pro/docs/api/classes/PubNubEvent.md +++ b/public/libs/red5pro/docs/api/classes/PubNubEvent.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/PublisherEvent.md b/public/libs/red5pro/docs/api/classes/PublisherEvent.md index d5b08cef..f77cd877 100644 --- a/public/libs/red5pro/docs/api/classes/PublisherEvent.md +++ b/public/libs/red5pro/docs/api/classes/PublisherEvent.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/SourceHandler.md b/public/libs/red5pro/docs/api/classes/SourceHandler.md index e88bd1d0..f25e8c37 100644 --- a/public/libs/red5pro/docs/api/classes/SourceHandler.md +++ b/public/libs/red5pro/docs/api/classes/SourceHandler.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/SourceHandlerImpl.md b/public/libs/red5pro/docs/api/classes/SourceHandlerImpl.md index 5b73e737..ed89bc9d 100644 --- a/public/libs/red5pro/docs/api/classes/SourceHandlerImpl.md +++ b/public/libs/red5pro/docs/api/classes/SourceHandlerImpl.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/SubscriberEvent.md b/public/libs/red5pro/docs/api/classes/SubscriberEvent.md index 51639eee..eb0a047a 100644 --- a/public/libs/red5pro/docs/api/classes/SubscriberEvent.md +++ b/public/libs/red5pro/docs/api/classes/SubscriberEvent.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/WHEPClient.md b/public/libs/red5pro/docs/api/classes/WHEPClient.md index 63e08521..d8f2daf2 100644 --- a/public/libs/red5pro/docs/api/classes/WHEPClient.md +++ b/public/libs/red5pro/docs/api/classes/WHEPClient.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/classes/WHIPClient.md b/public/libs/red5pro/docs/api/classes/WHIPClient.md index 9f355adf..333a5320 100644 --- a/public/libs/red5pro/docs/api/classes/WHIPClient.md +++ b/public/libs/red5pro/docs/api/classes/WHIPClient.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/MessageChannelEventTypes.md b/public/libs/red5pro/docs/api/enumerations/MessageChannelEventTypes.md index 71d0a868..d4d52039 100644 --- a/public/libs/red5pro/docs/api/enumerations/MessageChannelEventTypes.md +++ b/public/libs/red5pro/docs/api/enumerations/MessageChannelEventTypes.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/MessageTransportStateEventTypes.md b/public/libs/red5pro/docs/api/enumerations/MessageTransportStateEventTypes.md index f952dfa9..5a663010 100644 --- a/public/libs/red5pro/docs/api/enumerations/MessageTransportStateEventTypes.md +++ b/public/libs/red5pro/docs/api/enumerations/MessageTransportStateEventTypes.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/PlaybackAudioEncoder.md b/public/libs/red5pro/docs/api/enumerations/PlaybackAudioEncoder.md index 35aa2d80..9c6dfd24 100644 --- a/public/libs/red5pro/docs/api/enumerations/PlaybackAudioEncoder.md +++ b/public/libs/red5pro/docs/api/enumerations/PlaybackAudioEncoder.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/PlaybackState.md b/public/libs/red5pro/docs/api/enumerations/PlaybackState.md index 9c75217d..87117ba6 100644 --- a/public/libs/red5pro/docs/api/enumerations/PlaybackState.md +++ b/public/libs/red5pro/docs/api/enumerations/PlaybackState.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/PlaybackVideoEncoder.md b/public/libs/red5pro/docs/api/enumerations/PlaybackVideoEncoder.md index df9438f8..9c30ad87 100644 --- a/public/libs/red5pro/docs/api/enumerations/PlaybackVideoEncoder.md +++ b/public/libs/red5pro/docs/api/enumerations/PlaybackVideoEncoder.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/PubNubEventTypes.md b/public/libs/red5pro/docs/api/enumerations/PubNubEventTypes.md index c9b5ec14..9246c509 100644 --- a/public/libs/red5pro/docs/api/enumerations/PubNubEventTypes.md +++ b/public/libs/red5pro/docs/api/enumerations/PubNubEventTypes.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/PublishAudioEncoder.md b/public/libs/red5pro/docs/api/enumerations/PublishAudioEncoder.md index fcf20192..6f8c1b35 100644 --- a/public/libs/red5pro/docs/api/enumerations/PublishAudioEncoder.md +++ b/public/libs/red5pro/docs/api/enumerations/PublishAudioEncoder.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/PublishVideoEncoder.md b/public/libs/red5pro/docs/api/enumerations/PublishVideoEncoder.md index aab906b0..3c3afa6c 100644 --- a/public/libs/red5pro/docs/api/enumerations/PublishVideoEncoder.md +++ b/public/libs/red5pro/docs/api/enumerations/PublishVideoEncoder.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/PublisherEventTypes.md b/public/libs/red5pro/docs/api/enumerations/PublisherEventTypes.md index 6d80ec3c..02cd4fd2 100644 --- a/public/libs/red5pro/docs/api/enumerations/PublisherEventTypes.md +++ b/public/libs/red5pro/docs/api/enumerations/PublisherEventTypes.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/RTCPublisherEventTypes.md b/public/libs/red5pro/docs/api/enumerations/RTCPublisherEventTypes.md index 63f175aa..a24a73ed 100644 --- a/public/libs/red5pro/docs/api/enumerations/RTCPublisherEventTypes.md +++ b/public/libs/red5pro/docs/api/enumerations/RTCPublisherEventTypes.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/RTCSubscriberEventTypes.md b/public/libs/red5pro/docs/api/enumerations/RTCSubscriberEventTypes.md index c8125ec0..b87438fb 100644 --- a/public/libs/red5pro/docs/api/enumerations/RTCSubscriberEventTypes.md +++ b/public/libs/red5pro/docs/api/enumerations/RTCSubscriberEventTypes.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/StatsEndpointType.md b/public/libs/red5pro/docs/api/enumerations/StatsEndpointType.md index 3c03bee2..9bc27898 100644 --- a/public/libs/red5pro/docs/api/enumerations/StatsEndpointType.md +++ b/public/libs/red5pro/docs/api/enumerations/StatsEndpointType.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/SubscriberEventTypes.md b/public/libs/red5pro/docs/api/enumerations/SubscriberEventTypes.md index f9043f6c..08cd9a5d 100644 --- a/public/libs/red5pro/docs/api/enumerations/SubscriberEventTypes.md +++ b/public/libs/red5pro/docs/api/enumerations/SubscriberEventTypes.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/enumerations/WebRTCConnectionEventTypes.md b/public/libs/red5pro/docs/api/enumerations/WebRTCConnectionEventTypes.md index 50c71140..a8ce5e5e 100644 --- a/public/libs/red5pro/docs/api/enumerations/WebRTCConnectionEventTypes.md +++ b/public/libs/red5pro/docs/api/enumerations/WebRTCConnectionEventTypes.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/functions/getRecordedLogs.md b/public/libs/red5pro/docs/api/functions/getRecordedLogs.md index 1ed23a78..850baa0f 100644 --- a/public/libs/red5pro/docs/api/functions/getRecordedLogs.md +++ b/public/libs/red5pro/docs/api/functions/getRecordedLogs.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/functions/getVersion.md b/public/libs/red5pro/docs/api/functions/getVersion.md index 7b06c83c..b0d8b5cc 100644 --- a/public/libs/red5pro/docs/api/functions/getVersion.md +++ b/public/libs/red5pro/docs/api/functions/getVersion.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/functions/setLogLevel.md b/public/libs/red5pro/docs/api/functions/setLogLevel.md index 2dc18a69..596146ee 100644 --- a/public/libs/red5pro/docs/api/functions/setLogLevel.md +++ b/public/libs/red5pro/docs/api/functions/setLogLevel.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/globals.md b/public/libs/red5pro/docs/api/globals.md index 9ae74e38..338f43f3 100644 --- a/public/libs/red5pro/docs/api/globals.md +++ b/public/libs/red5pro/docs/api/globals.md @@ -1,8 +1,8 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](README.md) *** -# Red5 Pro WebRTC SDK v16.0.0-beta.1 +# Red5 Pro WebRTC SDK v16.0.0-beta.2 Red5 Pro WebRTC SDK diff --git a/public/libs/red5pro/docs/api/interfaces/EventEmitterInterface.md b/public/libs/red5pro/docs/api/interfaces/EventEmitterInterface.md index 94f6e115..93bfd88a 100644 --- a/public/libs/red5pro/docs/api/interfaces/EventEmitterInterface.md +++ b/public/libs/red5pro/docs/api/interfaces/EventEmitterInterface.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/BandwidthConfig.md b/public/libs/red5pro/docs/api/type-aliases/BandwidthConfig.md index 5edd0078..004454e5 100644 --- a/public/libs/red5pro/docs/api/type-aliases/BandwidthConfig.md +++ b/public/libs/red5pro/docs/api/type-aliases/BandwidthConfig.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/HLSSubscriberConfigType.md b/public/libs/red5pro/docs/api/type-aliases/HLSSubscriberConfigType.md index d2d22c85..201d3373 100644 --- a/public/libs/red5pro/docs/api/type-aliases/HLSSubscriberConfigType.md +++ b/public/libs/red5pro/docs/api/type-aliases/HLSSubscriberConfigType.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/LiveSeekConfigType.md b/public/libs/red5pro/docs/api/type-aliases/LiveSeekConfigType.md index 9d776002..17087cae 100644 --- a/public/libs/red5pro/docs/api/type-aliases/LiveSeekConfigType.md +++ b/public/libs/red5pro/docs/api/type-aliases/LiveSeekConfigType.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/LiveSeekOptions.md b/public/libs/red5pro/docs/api/type-aliases/LiveSeekOptions.md index 09de6b2f..cccd5b15 100644 --- a/public/libs/red5pro/docs/api/type-aliases/LiveSeekOptions.md +++ b/public/libs/red5pro/docs/api/type-aliases/LiveSeekOptions.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/MediaConstraintRange.md b/public/libs/red5pro/docs/api/type-aliases/MediaConstraintRange.md index e1d57d70..95c250e7 100644 --- a/public/libs/red5pro/docs/api/type-aliases/MediaConstraintRange.md +++ b/public/libs/red5pro/docs/api/type-aliases/MediaConstraintRange.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/MediaConstraints.md b/public/libs/red5pro/docs/api/type-aliases/MediaConstraints.md index d549fbf1..bd1e4219 100644 --- a/public/libs/red5pro/docs/api/type-aliases/MediaConstraints.md +++ b/public/libs/red5pro/docs/api/type-aliases/MediaConstraints.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/RTCPublisherConfigType.md b/public/libs/red5pro/docs/api/type-aliases/RTCPublisherConfigType.md index 7d26496c..707f30f3 100644 --- a/public/libs/red5pro/docs/api/type-aliases/RTCPublisherConfigType.md +++ b/public/libs/red5pro/docs/api/type-aliases/RTCPublisherConfigType.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/RTCSubscriberConfigType.md b/public/libs/red5pro/docs/api/type-aliases/RTCSubscriberConfigType.md index 564b1f00..e66d640d 100644 --- a/public/libs/red5pro/docs/api/type-aliases/RTCSubscriberConfigType.md +++ b/public/libs/red5pro/docs/api/type-aliases/RTCSubscriberConfigType.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/RTCWhepSubscriberConfigType.md b/public/libs/red5pro/docs/api/type-aliases/RTCWhepSubscriberConfigType.md index abacff1a..3e21d945 100644 --- a/public/libs/red5pro/docs/api/type-aliases/RTCWhepSubscriberConfigType.md +++ b/public/libs/red5pro/docs/api/type-aliases/RTCWhepSubscriberConfigType.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/RTCWhipPublisherConfigType.md b/public/libs/red5pro/docs/api/type-aliases/RTCWhipPublisherConfigType.md index 9a689ecd..1ca4dec9 100644 --- a/public/libs/red5pro/docs/api/type-aliases/RTCWhipPublisherConfigType.md +++ b/public/libs/red5pro/docs/api/type-aliases/RTCWhipPublisherConfigType.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/StatsConfig.md b/public/libs/red5pro/docs/api/type-aliases/StatsConfig.md index 5316b2a9..b1e705ee 100644 --- a/public/libs/red5pro/docs/api/type-aliases/StatsConfig.md +++ b/public/libs/red5pro/docs/api/type-aliases/StatsConfig.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/type-aliases/VideoConstraints.md b/public/libs/red5pro/docs/api/type-aliases/VideoConstraints.md index 91415f04..0f17a00b 100644 --- a/public/libs/red5pro/docs/api/type-aliases/VideoConstraints.md +++ b/public/libs/red5pro/docs/api/type-aliases/VideoConstraints.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/variables/Capability.md b/public/libs/red5pro/docs/api/variables/Capability.md index d9031c51..f32ed23b 100644 --- a/public/libs/red5pro/docs/api/variables/Capability.md +++ b/public/libs/red5pro/docs/api/variables/Capability.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/variables/LOG_LEVELS.md b/public/libs/red5pro/docs/api/variables/LOG_LEVELS.md index 44e62425..810f09ae 100644 --- a/public/libs/red5pro/docs/api/variables/LOG_LEVELS.md +++ b/public/libs/red5pro/docs/api/variables/LOG_LEVELS.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/variables/PlaybackStateReadableMap.md b/public/libs/red5pro/docs/api/variables/PlaybackStateReadableMap.md index e21c4c8b..c03ecb3a 100644 --- a/public/libs/red5pro/docs/api/variables/PlaybackStateReadableMap.md +++ b/public/libs/red5pro/docs/api/variables/PlaybackStateReadableMap.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/variables/default.md b/public/libs/red5pro/docs/api/variables/default.md index 7ba57691..acbf7f46 100644 --- a/public/libs/red5pro/docs/api/variables/default.md +++ b/public/libs/red5pro/docs/api/variables/default.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/variables/defaultHLSSubscriberConfig.md b/public/libs/red5pro/docs/api/variables/defaultHLSSubscriberConfig.md index 73cfb6de..bbda1eac 100644 --- a/public/libs/red5pro/docs/api/variables/defaultHLSSubscriberConfig.md +++ b/public/libs/red5pro/docs/api/variables/defaultHLSSubscriberConfig.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/variables/defaultLiveSeekConfig.md b/public/libs/red5pro/docs/api/variables/defaultLiveSeekConfig.md index bfe90c74..be910260 100644 --- a/public/libs/red5pro/docs/api/variables/defaultLiveSeekConfig.md +++ b/public/libs/red5pro/docs/api/variables/defaultLiveSeekConfig.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/variables/defaultStatsConfig.md b/public/libs/red5pro/docs/api/variables/defaultStatsConfig.md index 6dd767f2..794752f9 100644 --- a/public/libs/red5pro/docs/api/variables/defaultStatsConfig.md +++ b/public/libs/red5pro/docs/api/variables/defaultStatsConfig.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/variables/defaultWhepSubscriberConfig.md b/public/libs/red5pro/docs/api/variables/defaultWhepSubscriberConfig.md index d47df1f5..3a0cca48 100644 --- a/public/libs/red5pro/docs/api/variables/defaultWhepSubscriberConfig.md +++ b/public/libs/red5pro/docs/api/variables/defaultWhepSubscriberConfig.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/api/variables/defaultWhipPublisherConfig.md b/public/libs/red5pro/docs/api/variables/defaultWhipPublisherConfig.md index 265d7a6b..fa70a579 100644 --- a/public/libs/red5pro/docs/api/variables/defaultWhipPublisherConfig.md +++ b/public/libs/red5pro/docs/api/variables/defaultWhipPublisherConfig.md @@ -1,4 +1,4 @@ -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/llms-full.md b/public/libs/red5pro/docs/llms-full.md index 1f1b98f2..fce1f1a0 100644 --- a/public/libs/red5pro/docs/llms-full.md +++ b/public/libs/red5pro/docs/llms-full.md @@ -1,8 +1,8 @@ # Red5 Pro HTML SDK - LLM Reference - project: red5pro-html-sdk-ts -- version: 16.0.0-beta.1 -- generated_at: 2026-07-03T12:56:20.169Z +- version: 16.0.0-beta.2 +- generated_at: 2026-07-27T18:13:29.489Z ## Included Files @@ -2625,7 +2625,7 @@ The following events are dispatched by the underlying pubnub integration and bub ### Source: `docs/api/classes/Event.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -2693,7 +2693,7 @@ Get the type of event. ### Source: `docs/api/classes/EventEmitter.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -2803,7 +2803,7 @@ Dispatch an event to be handled by any assigned callbacks. ### Source: `docs/api/classes/HLSSubscriber.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -3207,7 +3207,7 @@ Unsubscribe from the HLS stream. ### Source: `docs/api/classes/LiveSeekClient.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -4075,7 +4075,7 @@ The channel to unsubscribe from. ### Source: `docs/api/classes/MessageChannel.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -4828,7 +4828,7 @@ The optimization parameters to update. ### Source: `docs/api/classes/MessageChannelEvent.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -4930,7 +4930,7 @@ Get the type of event. ### Source: `docs/api/classes/MessageTransportStateEvent.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -5032,7 +5032,7 @@ Get the type of event. ### Source: `docs/api/classes/MOQCatalog.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -5254,7 +5254,7 @@ Dispatch an event to be handled by any assigned callbacks. ### Source: `docs/api/classes/MOQPublisher.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -5536,7 +5536,7 @@ Dispatch an event to be handled by any assigned callbacks. ### Source: `docs/api/classes/MOQSubscriber.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -5931,7 +5931,7 @@ Dispatch an event to be handled by any assigned callbacks. ### Source: `docs/api/classes/PlaybackController.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -6260,7 +6260,7 @@ Unmute the media element. ### Source: `docs/api/classes/PlaybackControls.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -6557,7 +6557,7 @@ The event to trigger. ### Source: `docs/api/classes/PublisherEvent.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -6659,7 +6659,7 @@ Get the type of event. ### Source: `docs/api/classes/PubNubClient.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -6879,7 +6879,7 @@ Dispatch an event to be handled by any assigned callbacks. ### Source: `docs/api/classes/PubNubEvent.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -6981,7 +6981,7 @@ Get the type of event. ### Source: `docs/api/classes/SourceHandler.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -7416,7 +7416,7 @@ Unpublish the media element. ### Source: `docs/api/classes/SourceHandlerImpl.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -7830,7 +7830,7 @@ Unpublish the media element. ### Source: `docs/api/classes/SubscriberEvent.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -7932,7 +7932,7 @@ Get the type of event. ### Source: `docs/api/classes/WHEPClient.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -8699,7 +8699,7 @@ The channel to unsubscribe from. ### Source: `docs/api/classes/WHIPClient.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9305,7 +9305,7 @@ The optimization parameters to update. ### Source: `docs/api/enumerations/MessageChannelEventTypes.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9351,7 +9351,7 @@ The optimization parameters to update. ### Source: `docs/api/enumerations/MessageTransportStateEventTypes.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9385,7 +9385,7 @@ The optimization parameters to update. ### Source: `docs/api/enumerations/PlaybackAudioEncoder.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9407,7 +9407,7 @@ The optimization parameters to update. ### Source: `docs/api/enumerations/PlaybackState.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9447,7 +9447,7 @@ The optimization parameters to update. ### Source: `docs/api/enumerations/PlaybackVideoEncoder.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9487,7 +9487,7 @@ The optimization parameters to update. ### Source: `docs/api/enumerations/PublishAudioEncoder.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9505,7 +9505,7 @@ Enumeration of Audio Encoder types to request for Broadcast. ### Source: `docs/api/enumerations/PublisherEventTypes.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9629,7 +9629,7 @@ Enumeration of Audio Encoder types to request for Broadcast. ### Source: `docs/api/enumerations/PublishVideoEncoder.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9665,7 +9665,7 @@ Enumeration of Video Encoder types to request for Broadcast. ### Source: `docs/api/enumerations/PubNubEventTypes.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9753,7 +9753,7 @@ Enumeration of Video Encoder types to request for Broadcast. ### Source: `docs/api/enumerations/RTCPublisherEventTypes.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -9895,7 +9895,7 @@ Enumeration of Video Encoder types to request for Broadcast. ### Source: `docs/api/enumerations/RTCSubscriberEventTypes.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10037,7 +10037,7 @@ Enumeration of Video Encoder types to request for Broadcast. ### Source: `docs/api/enumerations/StatsEndpointType.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10065,7 +10065,7 @@ Enumeration of Video Encoder types to request for Broadcast. ### Source: `docs/api/enumerations/SubscriberEventTypes.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10237,7 +10237,7 @@ Enumeration of Video Encoder types to request for Broadcast. ### Source: `docs/api/enumerations/WebRTCConnectionEventTypes.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10271,7 +10271,7 @@ Enumeration of Video Encoder types to request for Broadcast. ### Source: `docs/api/functions/getRecordedLogs.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10291,7 +10291,7 @@ Array of recorded log messages. ### Source: `docs/api/functions/getVersion.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10309,7 +10309,7 @@ Get the version of the SDK. ### Source: `docs/api/functions/setLogLevel.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10335,11 +10335,11 @@ Get the version of the SDK. ### Source: `docs/api/globals.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](README.md) *** -# Red5 Pro WebRTC SDK v16.0.0-beta.1 +# Red5 Pro WebRTC SDK v16.0.0-beta.2 Red5 Pro WebRTC SDK @@ -10422,7 +10422,7 @@ Red5 Pro WebRTC SDK ### Source: `docs/api/interfaces/EventEmitterInterface.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10496,7 +10496,7 @@ Dispatch an event to be handled by any assigned callbacks. ### Source: `docs/api/README.md` -**Red5 Pro WebRTC SDK v16.0.0-beta.1** +**Red5 Pro WebRTC SDK v16.0.0-beta.2** *** @@ -10732,7 +10732,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/BandwidthConfig.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10756,7 +10756,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/HLSSubscriberConfigType.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10826,7 +10826,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/LiveSeekConfigType.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10844,7 +10844,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/LiveSeekOptions.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10900,7 +10900,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/MediaConstraintRange.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10936,7 +10936,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/MediaConstraints.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -10960,7 +10960,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/RTCPublisherConfigType.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11150,7 +11150,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/RTCSubscriberConfigType.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11324,7 +11324,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/RTCWhepSubscriberConfigType.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11346,7 +11346,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/RTCWhipPublisherConfigType.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11368,7 +11368,7 @@ The initialization configurations and relevant APIs available for each client ca ### Source: `docs/api/type-aliases/StatsConfig.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11406,7 +11406,7 @@ Configuration for RTC Stats Monitoring. ### Source: `docs/api/type-aliases/VideoConstraints.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11442,7 +11442,7 @@ Configuration for RTC Stats Monitoring. ### Source: `docs/api/variables/Capability.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11464,7 +11464,7 @@ Configuration for RTC Stats Monitoring. ### Source: `docs/api/variables/default.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11710,7 +11710,7 @@ Get the version of the SDK. ### Source: `docs/api/variables/defaultHLSSubscriberConfig.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11722,7 +11722,7 @@ Get the version of the SDK. ### Source: `docs/api/variables/defaultLiveSeekConfig.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11734,7 +11734,7 @@ Get the version of the SDK. ### Source: `docs/api/variables/defaultStatsConfig.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11746,7 +11746,7 @@ Get the version of the SDK. ### Source: `docs/api/variables/defaultWhepSubscriberConfig.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11758,7 +11758,7 @@ Get the version of the SDK. ### Source: `docs/api/variables/defaultWhipPublisherConfig.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11770,7 +11770,7 @@ Get the version of the SDK. ### Source: `docs/api/variables/LOG_LEVELS.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** @@ -11808,7 +11808,7 @@ Get the version of the SDK. ### Source: `docs/api/variables/PlaybackStateReadableMap.md` -[**Red5 Pro WebRTC SDK v16.0.0-beta.1**](../README.md) +[**Red5 Pro WebRTC SDK v16.0.0-beta.2**](../README.md) *** diff --git a/public/libs/red5pro/docs/llms.txt b/public/libs/red5pro/docs/llms.txt index 11d61088..99bc989a 100644 --- a/public/libs/red5pro/docs/llms.txt +++ b/public/libs/red5pro/docs/llms.txt @@ -1,8 +1,8 @@ # LLM Docs Index - project: red5pro-html-sdk-ts -- version: 16.0.0-beta.1 -- generated_at: 2026-07-03T12:56:20.168Z +- version: 16.0.0-beta.2 +- generated_at: 2026-07-27T18:13:29.488Z ## Included Markdown Files diff --git a/public/libs/red5pro/red5pro-sdk.esm.min.js b/public/libs/red5pro/red5pro-sdk.esm.min.js index 8343cf97..f7699e14 100644 --- a/public/libs/red5pro/red5pro-sdk.esm.min.js +++ b/public/libs/red5pro/red5pro-sdk.esm.min.js @@ -2,7 +2,7 @@ * * red5pro-html-sdk - Red5 Pro HTML SDK * Author: Infrared5 Inc. - * Version: 16.0.0-beta.1 + * Version: 16.0.0-beta.2 * Url: https://www.red5.net * * Copyright © 2015 Infrared5, Inc. All rights reserved. @@ -31,14 +31,14 @@ * */ -var e,t,i,s;!function(e){e.OPUS="OPUS",e.NONE="NONE"}(e||(e={})),function(e){e.VP8="VP8",e.H264="H264",e.H265="H265",e.AV1="AV1",e.NONE="NONE"}(t||(t={})),function(e){e[e.UNAVAILABLE=1e3]="UNAVAILABLE",e[e.AVAILABLE=0]="AVAILABLE",e[e.IDLE=1]="IDLE",e[e.PLAYING=2]="PLAYING",e[e.PAUSED=3]="PAUSED"}(i||(i={})),function(e){e.UNAVAILABLE="Playback.UNAVAILABLE",e.AVAILABLE="Playback.AVAILABLE",e.IDLE="Playback.IDLE",e.PLAYING="Playback.PLAYING",e.PAUSED="Playback.PAUSED"}(s||(s={}));const n={[i.UNAVAILABLE]:s.UNAVAILABLE,[i.AVAILABLE]:s.AVAILABLE,[i.IDLE]:s.IDLE,[i.PLAYING]:s.PLAYING,[i.PAUSED]:s.PAUSED};var r,a,o,c;!function(e){e.RTMP="rtmp",e.RTC="rtc"}(r||(r={})),function(e){e.LIVE="live",e.RECORD="record",e.APPEND="append"}(a||(a={})),function(e){e.OPUS="OPUS"}(o||(o={})),function(e){e.VP8="VP8",e.H264="H264",e.H265="H265",e.AV1="AV1"}(c||(c={}));var d={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},h={};function l(e){return"string"==typeof e?d[e.toLowerCase()]:e}function u(e,t){return u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},u(e,t)}function p(e,t,i){return p=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}()?Reflect.construct:function(e,t,i){var s=[null];s.push.apply(s,t);var n=new(Function.bind.apply(e,s));return i&&u(n,i.prototype),n},p.apply(null,arguments)}function m(e){if(null==e)return e;if(Array.isArray(e))return e.slice();if("object"==typeof e){var t={};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t}return e}function g(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"[ "+e.map(function(e){return g(e)}).join(", ")+" ]":"object"==typeof e?JSON.stringify(e):"function"==typeof e?"[Function: "+e.name+"]":"boolean"==typeof e||"number"==typeof e?e:"'"+e.toString()+"'"}function f(e){if("string"!=typeof e){for(var t=new Array(arguments.length),i=0;i=r)return e;switch(e){case"%s":return String(n[s++]);case"%d":return Number(n[s++]);case"%j":try{return JSON.stringify(n[s++])}catch(e){return"[Circular]"}default:return e}}),o=n[s];se||(n=function(n){var r;n[0]instanceof Error?(i={err:t.serializers&&t.serializers.err?t.serializers.err(n[0]):T.err(n[0])},r={err:!0},s=1===n.length?[i.err.message]:Array.prototype.slice.call(n,1)):"object"!=typeof n[0]&&null!==n[0]||Array.isArray(n[0])?(i=null,s=Array.prototype.slice.call(n)):(i=n[0],s=1===n.length&&i.err&&i.err instanceof Error?[i.err.message]:Array.prototype.slice.call(n,1));var a=m(t.fields);a.level=e;var o=i?m(i):null;if(o&&(t.serializers&&t._applySerializers(o,r),Object.keys(o).forEach(function(e){a[e]=o[e]})),a.levelName=h[e],a.msg=s.length?f.apply(t,s):"",a.time||(a.time=new Date),t.src&&!a.src)try{throw new Error("call-stack-error")}catch(e){var c=e.stack?function(e,t){var i=e.split("\n");i[0]&&i[0].indexOf("call-stack-error")>=0&&i.shift();var s=i[t],n=null;if(s){var r=/^\s*(at|.*@)\s*(.+)?$/.exec(s);n=Array.isArray(r)&&r[2]?r[2]:s}return n}(e.stack,2):"";c||function(e){return _[e]}("src")||v("Unable to determine src line info","src"),a.src=c||""}return a.v=1,a}(s),this._emit(n))}}function y(e){var t=e.stack||e.toString();if(e.cause&&"function"==typeof e.cause){var i=e.cause();i&&(t+="\nCaused by: "+y(i))}return t}S.prototype.trace=E(10),S.prototype.debug=E(20),S.prototype.info=E(30),S.prototype.warn=E(40),S.prototype.error=E(50),S.prototype.fatal=E(60);var T={err:function(e){return e&&e.stack?{message:e.message,name:e.name,stack:y(e),code:e.code,signal:e.signal}:e}};const C={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"};class w{write(e){console.log("%s - [%s] %s: %s",e.time.toISOString(),e.name,C[e.level]||"UNKNOWN",e.msg)}}let R,I;const A=e=>(t,i)=>{var s;R&&"function"==typeof R[e]&&R[e]((s=t,e=>`(${s}) ${e}`)(i))},k={TRACE:"trace",INFO:"info",DEBUG:"debug",WARN:"warn",ERROR:"error",FATAL:"fatal"},O=(e,t=!1,i)=>{const s=[{level:e,stream:new w,type:"raw"}];if(i){const t=i.map(t=>({...t,level:e}));s.push(...t)}t&&(I=[],s.push({level:e,stream:{write:t=>{const i=`[${t.time.toISOString()}] ${e.toUpperCase()}: ${t.msg}`;null==I||I.push(i)}},type:"raw"}));R=function(){return p(S,[].slice.call(arguments))}({level:e,name:"red5pro-sdk",streams:s})},N=()=>(R||O(k.INFO),R),P=()=>I||[];A(k.TRACE),A(k.INFO);const L=A(k.DEBUG),U=A(k.WARN),D=A(k.ERROR);A(k.FATAL);const M="RED5PRO";class B{constructor(){this._callbacks={},this._callbacks[M]=[]}_notify(e,t){let i;const s=e.length;for(i=0;i1&&(n=H.exec(e),s[1]===t&&n&&n.length>1)?n[1]:void 0}}function q(e){const t=V(e,"orientation");if(t)return{orientation:parseInt(t)}}function G(e){const t=V(e,"streamingMode");if(t)return{streamingMode:t}}const j=e=>$.get(e),W=e=>{const t=e.textTracks;t&&(e.addTextTrack("metadata"),t.addEventListener("addtrack",t=>{const i=t.track;i.mode="hidden",i.addEventListener("cuechange",t=>{let s,n;for(t&&t.currentTarget?s=t.currentTarget.cues:(s=i.cues,s=s&&s.length>0?s:i.activeCues),s=s||[],n=0;n{e(s)}),n&&r&&r.streamingMode&&r.streamingMode.forEach(e=>{e(n)})}}})}))},Q=4611686018427387903n;function K(e){if("number"==typeof e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Varint value must be a non-negative integer, got ${e}`);if(e>Number.MAX_SAFE_INTEGER)throw new RangeError(`Varint number value ${e} exceeds MAX_SAFE_INTEGER; use bigint for values > 2^53-1`);return BigInt(e)}if(e<0n||e>Q)throw new RangeError(`Varint value must be 0 ≤ n ≤ ${Q}, got ${e}`);return e}function z(e){return e<=63n?1:e<=16383n?2:e<=1073741823n?4:8}function Y(e,t){if(t>=e.length)throw new RangeError(`Varint read out of bounds: offset ${t}, length ${e.length}`);const i=e[t],s=1<<(i>>6);if(t+s>e.length)throw new RangeError(`Varint requires ${s} bytes but only ${e.length-t} available`);let n;switch(s){case 1:n=BigInt(63&i);break;case 2:n=BigInt((63&i)<<8|e[t+1]);break;case 4:n=BigInt(((63&i)<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0);break;case 8:n=BigInt(63&i)<<56n|BigInt(e[t+1])<<48n|BigInt(e[t+2])<<40n|BigInt(e[t+3])<<32n|BigInt(e[t+4])<<24n|BigInt(e[t+5])<<16n|BigInt(e[t+6])<<8n|BigInt(e[t+7])}return{value:n,bytesRead:s}}function J(e,t,i){switch(z(e)){case 1:return t[i]=Number(e),1;case 2:return t[i]=64|Number(e>>8n),t[i+1]=Number(0xffn&e),2;case 4:return t[i]=128|Number(e>>24n&0x3fn),t[i+1]=Number(e>>16n&0xffn),t[i+2]=Number(e>>8n&0xffn),t[i+3]=Number(0xffn&e),4;case 8:return t[i]=192|Number(e>>56n&0x3fn),t[i+1]=Number(e>>48n&0xffn),t[i+2]=Number(e>>40n&0xffn),t[i+3]=Number(e>>32n&0xffn),t[i+4]=Number(e>>24n&0xffn),t[i+5]=Number(e>>16n&0xffn),t[i+6]=Number(e>>8n&0xffn),t[i+7]=Number(0xffn&e),8}}const X={NO_ERROR:K(0),INTERNAL_ERROR:K(1),UNAUTHORIZED:K(2),PROTOCOL_VIOLATION:K(3),INVALID_REQUEST_ID:K(4),DUPLICATE_TRACK_ALIAS:K(5),KEY_VALUE_FORMATTING_ERROR:K(6),TOO_MANY_REQUESTS:K(7),INVALID_PATH:K(8),MALFORMED_PATH:K(9),GOAWAY_TIMEOUT:K(16),CONTROL_MESSAGE_TIMEOUT:K(17),DATA_STREAM_TIMEOUT:K(18),AUTH_TOKEN_CACHE_OVERFLOW:K(19),DUPLICATE_AUTH_TOKEN_ALIAS:K(20),VERSION_NEGOTIATION_FAILED:K(21),MALFORMED_AUTH_TOKEN:K(22),UNKNOWN_AUTH_TOKEN_ALIAS:K(23),EXPIRED_AUTH_TOKEN:K(24),INVALID_AUTHORITY:K(25),MALFORMED_AUTHORITY:K(26)},Z={INTERNAL_ERROR:K(0),UNAUTHORIZED:K(1),TIMEOUT:K(2),NOT_SUPPORTED:K(3),MALFORMED_AUTH_TOKEN:K(4),EXPIRED_AUTH_TOKEN:K(5),DOES_NOT_EXIST:K(16),INVALID_RANGE:K(17),MALFORMED_TRACK:K(18),DUPLICATE_SUBSCRIPTION:K(25),UNINTERESTED:K(32),PREFIX_OVERLAP:K(48),INVALID_JOINING_REQUEST_ID:K(50)},ee={INTERNAL_ERROR:K(0),UNAUTHORIZED:K(1),TRACK_ENDED:K(2),SUBSCRIPTION_ENDED:K(3),GOING_AWAY:K(4),EXPIRED:K(5),TOO_FAR_BEHIND:K(6),UPDATE_FAILED:K(8),MALFORMED_TRACK:K(18)};K(0),K(1),K(2),K(3),K(4),K(18);class te extends Error{constructor(e){super(e),this.name="ProtocolViolationError"}}function ie(e,t){if(t>=e.length)throw new RangeError(`readUint8 out of bounds: offset ${t}, length ${e.length}`);return{value:e[t],bytesRead:1}}function se(e,t){const{value:i,bytesRead:s}=Y(e,t),n=Number(i),{value:r,bytesRead:a}=function(e,t,i){if(t+i>e.length)throw new RangeError(`readBytes: need ${i} bytes at offset ${t}, but buffer length is ${e.length}`);return{value:e.slice(t,t+i),bytesRead:i}}(e,t+s,n);return{value:r,bytesRead:s+a}}function ne(e,t,i){let s=i;return s+=J(K(e.length),t,s),t.set(e,s),s+=e.length,s-i}function re(e){return z(K(e.length))+e.length}function ae(e,t){let i=t;const{value:s,bytesRead:n}=Y(e,i);i+=n;const r=Number(s),a=[];for(let t=0;te+t.length,0)}function le(e){for(let t=0;t32)throw new te(` Track Namespace has ${e.length} fields; maximum is 32 (§2.4.1)`);le(e);const t=he(e);if(t>de)throw new te(` Track Namespace length ${t} exceeds maximum 4096 bytes (§2.4.1)`)}function pe(e){if(e.length>32)throw new te(` Track Namespace Prefix has ${e.length} fields; maximum is 32 (§9.25)`);le(e);const t=he(e);if(t>de)throw new te(` Track Namespace Prefix length ${t} exceeds maximum 4096 bytes (§2.4.1)`)}function me(e,t){ue(e);const i=he(e)+t.length;if(i>de)throw new te(` Full Track Name length ${i} exceeds maximum 4096 bytes (§2.4.1)`)}function ge(e){if(e.length>32)throw new te(` Track Namespace Suffix has ${e.length} fields; maximum is 32 (§2.4.1)`);le(e);const t=he(e);if(t>de)throw new te(` Track Namespace Suffix length ${t} exceeds maximum 4096 bytes (§2.4.1)`)}function fe(e,t,i){let s=i,n=0n;const r=[...e.keys()].sort((e,t)=>et?1:0);for(const i of r){const r=e.get(i);for(const e of r){const r=K(i-n);if(n=i,s+=J(r,t,s),i%2n==0n)s+=J(e,t,s);else{const i=e;if(i.length>65535)throw new RangeError(`KVP byte value length ${i.length} exceeds maximum 65535 (2^16-1)`);s+=ne(i,t,s)}}}return s-i}function _e(e){let t=0,i=0n;const s=[...e.keys()].sort((e,t)=>et?1:0);for(const n of s){const s=e.get(n);for(const e of s){const s=K(n-i);i=n,t+=z(s),t+=n%2n==0n?z(e):re(e)}}return t}function ve(e){let t=0;for(const i of e.values())t+=i.length;return t}function be(e,t){let i=t;const{value:s,bytesRead:n}=Y(e,i);i+=n;const{value:r,bytesRead:a}=Y(e,i);return i+=a,{value:{group:s,object:r},bytesRead:i-t}}function Se(e,t,i){let s=i;return s+=J(e.group,t,s),s+=J(e.object,t,s),s-i}function Ee(e){return z(e.group)+z(e.object)}const ye=new TextEncoder,Te=new TextDecoder;function Ce(e,t){let i=t;const{value:s,bytesRead:n}=Y(e,i);i+=n;const r=Number(s);if(r>1024)throw new RangeError(`Reason Phrase length ${r} exceeds maximum 1024 bytes`);if(i+r>e.length)throw new RangeError(`Reason Phrase declared length ${r} exceeds remaining buffer (${e.length-i} bytes available)`);const a=e.slice(i,i+r);return i+=r,{value:Te.decode(a),bytesRead:i-t}}function we(e,t,i){const s=ye.encode(e);if(s.length>1024)throw new RangeError(`Reason Phrase length ${s.length} exceeds maximum 1024 bytes`);let n=i;return n+=J(K(s.length),t,n),t.set(s,n),n+=s.length,n-i}function Re(e){const t=ye.encode(e).length;return z(K(t))+t}const Ie={REQUEST_UPDATE:K(2),SUBSCRIBE:K(3),SUBSCRIBE_OK:K(4),REQUEST_ERROR:K(5),PUBLISH_NAMESPACE:K(6),REQUEST_OK:K(7),NAMESPACE:K(8),PUBLISH_NAMESPACE_DONE:K(9),UNSUBSCRIBE:K(10),PUBLISH_DONE:K(11),PUBLISH_NAMESPACE_CANCEL:K(12),TRACK_STATUS:K(13),NAMESPACE_DONE:K(14),GOAWAY:K(16),SUBSCRIBE_NAMESPACE:K(17),MAX_REQUEST_ID:K(21),FETCH:K(22),FETCH_CANCEL:K(23),FETCH_OK:K(24),REQUESTS_BLOCKED:K(26),PUBLISH:K(29),PUBLISH_OK:K(30),CLIENT_SETUP:K(32),SERVER_SETUP:K(33)},Ae={PATH:K(1),MAX_REQUEST_ID:K(2),AUTHORIZATION_TOKEN:K(3),MAX_AUTH_TOKEN_CACHE_SIZE:K(4),AUTHORITY:K(5),MOQT_IMPLEMENTATION:K(7)},ke={DELIVERY_TIMEOUT:K(2),AUTHORIZATION_TOKEN:K(3),EXPIRES:K(8),LARGEST_OBJECT:K(9),FORWARD:K(16),SUBSCRIBER_PRIORITY:K(32),SUBSCRIPTION_FILTER:K(33),GROUP_ORDER:K(34),NEW_GROUP_REQUEST:K(50)},Oe=new Set([ke.DELIVERY_TIMEOUT,ke.EXPIRES,ke.LARGEST_OBJECT,ke.FORWARD,ke.SUBSCRIBER_PRIORITY,ke.SUBSCRIPTION_FILTER,ke.GROUP_ORDER,ke.NEW_GROUP_REQUEST]),Ne=new Map([[ke.DELIVERY_TIMEOUT,"DELIVERY_TIMEOUT"],[ke.EXPIRES,"EXPIRES"],[ke.LARGEST_OBJECT,"LARGEST_OBJECT"],[ke.FORWARD,"FORWARD"],[ke.SUBSCRIBER_PRIORITY,"SUBSCRIBER_PRIORITY"],[ke.SUBSCRIPTION_FILTER,"SUBSCRIPTION_FILTER"],[ke.GROUP_ORDER,"GROUP_ORDER"],[ke.NEW_GROUP_REQUEST,"NEW_GROUP_REQUEST"]]);function Pe(e){!function(e){switch(e.type){case"SUBSCRIBE":case"TRACK_STATUS":case"PUBLISH":me(e.trackNamespace,e.trackName);break;case"FETCH":1===e.fetch.fetchType&&me(e.fetch.trackNamespace,e.fetch.trackName);break;case"PUBLISH_NAMESPACE":ue(e.trackNamespace);break;case"NAMESPACE":case"NAMESPACE_DONE":ge(e.trackNamespaceSuffix);break;case"SUBSCRIBE_NAMESPACE":pe(e.trackNamespacePrefix)}}(e),function(e){return"CLIENT_SETUP"!==e.type&&"SERVER_SETUP"!==e.type&&"parameters"in e}(e)&&function(e){for(const[t,i]of e)if(Oe.has(t)&&i.length>1){const e=Ne.get(t)??`0x${t.toString(16)}`;throw new Error(`Duplicate message parameter: ${e} may not appear multiple times`)}}(e.parameters);const t=function(e){switch(e){case"CLIENT_SETUP":return Ie.CLIENT_SETUP;case"SERVER_SETUP":return Ie.SERVER_SETUP;case"GOAWAY":return Ie.GOAWAY;case"MAX_REQUEST_ID":return Ie.MAX_REQUEST_ID;case"REQUESTS_BLOCKED":return Ie.REQUESTS_BLOCKED;case"REQUEST_OK":return Ie.REQUEST_OK;case"REQUEST_ERROR":return Ie.REQUEST_ERROR;case"SUBSCRIBE":return Ie.SUBSCRIBE;case"SUBSCRIBE_OK":return Ie.SUBSCRIBE_OK;case"REQUEST_UPDATE":return Ie.REQUEST_UPDATE;case"UNSUBSCRIBE":return Ie.UNSUBSCRIBE;case"PUBLISH":return Ie.PUBLISH;case"PUBLISH_OK":return Ie.PUBLISH_OK;case"PUBLISH_DONE":return Ie.PUBLISH_DONE;case"FETCH":return Ie.FETCH;case"FETCH_OK":return Ie.FETCH_OK;case"FETCH_CANCEL":return Ie.FETCH_CANCEL;case"TRACK_STATUS":return Ie.TRACK_STATUS;case"PUBLISH_NAMESPACE":return Ie.PUBLISH_NAMESPACE;case"NAMESPACE":return Ie.NAMESPACE;case"PUBLISH_NAMESPACE_DONE":return Ie.PUBLISH_NAMESPACE_DONE;case"NAMESPACE_DONE":return Ie.NAMESPACE_DONE;case"PUBLISH_NAMESPACE_CANCEL":return Ie.PUBLISH_NAMESPACE_CANCEL;case"SUBSCRIBE_NAMESPACE":return Ie.SUBSCRIBE_NAMESPACE;case"UNSUBSCRIBE_NAMESPACE":case"PUBLISH_NAMESPACE_OK":case"PUBLISH_NAMESPACE_ERROR":case"PUBLISH_ERROR":throw new Error(`Cannot encode draft-14-only message type "${e}" with draft-16 encoder`)}}(e.type),i=function(e){switch(e.type){case"CLIENT_SETUP":case"SERVER_SETUP":return Le(e.parameters);case"GOAWAY":{const t=(new TextEncoder).encode(e.newSessionUri);if(t.length>8192)throw new RangeError(`GOAWAY URI length ${t.length} exceeds maximum 8192 bytes`);return z(K(t.length))+t.length}case"MAX_REQUEST_ID":return z(e.maxRequestId);case"REQUESTS_BLOCKED":return z(e.maximumRequestId);case"REQUEST_OK":case"PUBLISH_OK":return z(e.requestId)+Le(e.parameters);case"REQUEST_ERROR":return z(e.requestId)+z(e.errorCode)+z(e.retryInterval)+Re(e.errorReason);case"SUBSCRIBE":case"TRACK_STATUS":return z(e.requestId)+ce(e.trackNamespace)+Be(e.trackName)+Le(e.parameters);case"SUBSCRIBE_OK":return z(e.requestId)+z(e.trackAlias)+Le(e.parameters)+De(e.trackExtensions);case"REQUEST_UPDATE":return z(e.requestId)+z(e.existingRequestId)+Le(e.parameters);case"UNSUBSCRIBE":case"FETCH_CANCEL":case"PUBLISH_NAMESPACE_DONE":return z(e.requestId);case"PUBLISH":return z(e.requestId)+ce(e.trackNamespace)+Be(e.trackName)+z(e.trackAlias)+Le(e.parameters)+De(e.trackExtensions);case"PUBLISH_DONE":return z(e.requestId)+z(e.statusCode)+z(e.streamCount)+Re(e.errorReason);case"FETCH":{let t=z(e.requestId)+z(K(e.fetch.fetchType));return 1===e.fetch.fetchType?t+=ce(e.fetch.trackNamespace)+Be(e.fetch.trackName)+Ee(e.fetch.startLocation)+Ee(e.fetch.endLocation):t+=z(e.fetch.joiningRequestId)+z(e.fetch.joiningStart),t+=Le(e.parameters),t}case"FETCH_OK":return z(e.requestId)+1+Ee(e.endLocation)+Le(e.parameters)+De(e.trackExtensions);case"PUBLISH_NAMESPACE":return z(e.requestId)+ce(e.trackNamespace)+Le(e.parameters);case"NAMESPACE":case"NAMESPACE_DONE":return ce(e.trackNamespaceSuffix);case"PUBLISH_NAMESPACE_CANCEL":return z(e.requestId)+z(e.errorCode)+Re(e.errorReason);case"SUBSCRIBE_NAMESPACE":return z(e.requestId)+ce(e.trackNamespacePrefix)+z(e.subscribeOptions)+Le(e.parameters);case"UNSUBSCRIBE_NAMESPACE":case"PUBLISH_NAMESPACE_OK":case"PUBLISH_NAMESPACE_ERROR":case"PUBLISH_ERROR":throw new Error(`Cannot encode draft-14-only message type "${e.type}" with draft-16 encoder`)}}(e);if(i>65535)throw new RangeError(`Control message payload length ${i} exceeds maximum 65535 (uint16)`);const s=z(t),n=new Uint8Array(s+2+i);let r=0;return r+=J(t,n,r),n[r++]=i>>8&255,n[r++]=255&i,r+=function(e,t,i){let s=i;switch(e.type){case"CLIENT_SETUP":case"SERVER_SETUP":s+=Ue(e.parameters,t,s);break;case"GOAWAY":{const i=(new TextEncoder).encode(e.newSessionUri);s+=J(K(i.length),t,s),t.set(i,s),s+=i.length;break}case"MAX_REQUEST_ID":s+=J(e.maxRequestId,t,s);break;case"REQUESTS_BLOCKED":s+=J(e.maximumRequestId,t,s);break;case"REQUEST_OK":case"PUBLISH_OK":s+=J(e.requestId,t,s),s+=Ue(e.parameters,t,s);break;case"REQUEST_ERROR":s+=J(e.requestId,t,s),s+=J(e.errorCode,t,s),s+=J(e.retryInterval,t,s),s+=we(e.errorReason,t,s);break;case"SUBSCRIBE":case"TRACK_STATUS":s+=J(e.requestId,t,s),s+=oe(e.trackNamespace,t,s),s+=xe(e.trackName,t,s),s+=Ue(e.parameters,t,s);break;case"SUBSCRIBE_OK":s+=J(e.requestId,t,s),s+=J(e.trackAlias,t,s),s+=Ue(e.parameters,t,s),s+=Me(e.trackExtensions,t,s);break;case"REQUEST_UPDATE":s+=J(e.requestId,t,s),s+=J(e.existingRequestId,t,s),s+=Ue(e.parameters,t,s);break;case"UNSUBSCRIBE":case"FETCH_CANCEL":case"PUBLISH_NAMESPACE_DONE":s+=J(e.requestId,t,s);break;case"PUBLISH":s+=J(e.requestId,t,s),s+=oe(e.trackNamespace,t,s),s+=xe(e.trackName,t,s),s+=J(e.trackAlias,t,s),s+=Ue(e.parameters,t,s),s+=Me(e.trackExtensions,t,s);break;case"PUBLISH_DONE":s+=J(e.requestId,t,s),s+=J(e.statusCode,t,s),s+=J(e.streamCount,t,s),s+=we(e.errorReason,t,s);break;case"FETCH":s+=J(e.requestId,t,s),s+=J(K(e.fetch.fetchType),t,s),1===e.fetch.fetchType?(s+=oe(e.fetch.trackNamespace,t,s),s+=xe(e.fetch.trackName,t,s),s+=Se(e.fetch.startLocation,t,s),s+=Se(e.fetch.endLocation,t,s)):(s+=J(e.fetch.joiningRequestId,t,s),s+=J(e.fetch.joiningStart,t,s)),s+=Ue(e.parameters,t,s);break;case"FETCH_OK":s+=J(e.requestId,t,s),t[s++]=255&e.endOfTrack,s+=Se(e.endLocation,t,s),s+=Ue(e.parameters,t,s),s+=Me(e.trackExtensions,t,s);break;case"PUBLISH_NAMESPACE":s+=J(e.requestId,t,s),s+=oe(e.trackNamespace,t,s),s+=Ue(e.parameters,t,s);break;case"NAMESPACE":case"NAMESPACE_DONE":s+=oe(e.trackNamespaceSuffix,t,s);break;case"PUBLISH_NAMESPACE_CANCEL":s+=J(e.requestId,t,s),s+=J(e.errorCode,t,s),s+=we(e.errorReason,t,s);break;case"SUBSCRIBE_NAMESPACE":s+=J(e.requestId,t,s),s+=oe(e.trackNamespacePrefix,t,s),s+=J(e.subscribeOptions,t,s),s+=Ue(e.parameters,t,s);break;case"UNSUBSCRIBE_NAMESPACE":case"PUBLISH_NAMESPACE_OK":case"PUBLISH_NAMESPACE_ERROR":case"PUBLISH_ERROR":throw new Error(`Cannot encode draft-14-only message type "${e.type}" with draft-16 encoder`)}return s-i}(e,n,r),n}function Le(e){return z(K(ve(e)))+_e(e)}function Ue(e,t,i){let s=i;return s+=J(K(ve(e)),t,s),s+=fe(e,t,s),s-i}function De(e){return 0===e.size?0:_e(e)}function Me(e,t,i){return 0===e.size?0:fe(e,t,i)}function Be(e){return re(e)}function xe(e,t,i){return ne(e,t,i)}function He(e,t=0){let i=t;const{value:s,bytesRead:n}=Y(e,i);if(i+=n,i+2>e.length)throw new RangeError("Buffer too short for message length field");const r=e[i]<<8|e[i+1];i+=2;const a=i+r;if(a>e.length)throw new RangeError(`Buffer too short for message payload: need ${r} bytes, have ${e.length-i}`);const o=function(e,t,i,s){const n=qe.get(e);if(void 0===n)throw new te(`Unknown message type: 0x${e.toString(16)}`);const{message:r,finalPos:a}=function(e,t,i,s){let n=i;switch(e){case"CLIENT_SETUP":case"SERVER_SETUP":{const{value:i,bytesRead:s}=$e(t,n);return n+=s,{message:{type:e,parameters:i},finalPos:n}}case"GOAWAY":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const s=Number(e);if(s>8192)throw new RangeError(`GOAWAY URI length ${s} exceeds maximum 8192 bytes`);const r=t.slice(n,n+s);n+=s;return{message:{type:"GOAWAY",newSessionUri:(new TextDecoder).decode(r)},finalPos:n}}case"MAX_REQUEST_ID":{const{value:e,bytesRead:i}=Y(t,n);return n+=i,{message:{type:"MAX_REQUEST_ID",maxRequestId:e},finalPos:n}}case"REQUESTS_BLOCKED":{const{value:e,bytesRead:i}=Y(t,n);return n+=i,{message:{type:"REQUESTS_BLOCKED",maximumRequestId:e},finalPos:n}}case"REQUEST_OK":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:s,bytesRead:r}=$e(t,n);return n+=r,{message:{type:"REQUEST_OK",requestId:e,parameters:s},finalPos:n}}case"REQUEST_ERROR":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:s,bytesRead:r}=Y(t,n);n+=r;const{value:a,bytesRead:o}=Y(t,n);n+=o;const{value:c,bytesRead:d}=Ce(t,n);return n+=d,{message:{type:"REQUEST_ERROR",requestId:e,errorCode:s,retryInterval:a,errorReason:c},finalPos:n}}case"SUBSCRIBE":case"TRACK_STATUS":{const{value:i,bytesRead:s}=Y(t,n);n+=s;const{value:r,bytesRead:a}=ae(t,n);n+=a;const{value:o,bytesRead:c}=Ve(t,n);n+=c,me(r,o);const{value:d,bytesRead:h}=$e(t,n);return n+=h,{message:{type:e,requestId:i,trackNamespace:r,trackName:o,parameters:d},finalPos:n}}case"SUBSCRIBE_OK":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:r,bytesRead:a}=Y(t,n);n+=a;const{value:o,bytesRead:c}=$e(t,n);n+=c;const{value:d,bytesRead:h}=Fe(t,n,s);return n+=h,{message:{type:"SUBSCRIBE_OK",requestId:e,trackAlias:r,parameters:o,trackExtensions:d},finalPos:n}}case"REQUEST_UPDATE":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:s,bytesRead:r}=Y(t,n);n+=r;const{value:a,bytesRead:o}=$e(t,n);return n+=o,{message:{type:"REQUEST_UPDATE",requestId:e,existingRequestId:s,parameters:a},finalPos:n}}case"UNSUBSCRIBE":{const{value:e,bytesRead:i}=Y(t,n);return n+=i,{message:{type:"UNSUBSCRIBE",requestId:e},finalPos:n}}case"PUBLISH":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:r,bytesRead:a}=ae(t,n);n+=a;const{value:o,bytesRead:c}=Ve(t,n);n+=c,me(r,o);const{value:d,bytesRead:h}=Y(t,n);n+=h;const{value:l,bytesRead:u}=$e(t,n);n+=u;const{value:p,bytesRead:m}=Fe(t,n,s);return n+=m,{message:{type:"PUBLISH",requestId:e,trackNamespace:r,trackName:o,trackAlias:d,parameters:l,trackExtensions:p},finalPos:n}}case"PUBLISH_OK":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:s,bytesRead:r}=$e(t,n);return n+=r,{message:{type:"PUBLISH_OK",requestId:e,parameters:s},finalPos:n}}case"PUBLISH_DONE":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:s,bytesRead:r}=Y(t,n);n+=r;const{value:a,bytesRead:o}=Y(t,n);n+=o;const{value:c,bytesRead:d}=Ce(t,n);return n+=d,{message:{type:"PUBLISH_DONE",requestId:e,statusCode:s,streamCount:a,errorReason:c},finalPos:n}}case"FETCH":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:s,bytesRead:r}=Y(t,n);let a;if(n+=r,0x1n===s){const{value:e,bytesRead:i}=ae(t,n);n+=i;const{value:s,bytesRead:r}=Ve(t,n);n+=r,me(e,s);const{value:o,bytesRead:c}=be(t,n);n+=c;const{value:d,bytesRead:h}=be(t,n);n+=h,a={fetchType:1,trackNamespace:e,trackName:s,startLocation:o,endLocation:d}}else{if(0x2n!==s&&0x3n!==s)throw new te(`Invalid Fetch Type: 0x${s.toString(16)}`);{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:r,bytesRead:o}=Y(t,n);n+=o,a={fetchType:Number(s),joiningRequestId:e,joiningStart:r}}}const{value:o,bytesRead:c}=$e(t,n);return n+=c,{message:{type:"FETCH",requestId:e,fetch:a,parameters:o},finalPos:n}}case"FETCH_OK":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:r}=ie(t,n);n+=1;const{value:a,bytesRead:o}=be(t,n);n+=o;const{value:c,bytesRead:d}=$e(t,n);n+=d;const{value:h,bytesRead:l}=Fe(t,n,s);return n+=l,{message:{type:"FETCH_OK",requestId:e,endOfTrack:r,endLocation:a,parameters:c,trackExtensions:h},finalPos:n}}case"FETCH_CANCEL":{const{value:e,bytesRead:i}=Y(t,n);return n+=i,{message:{type:"FETCH_CANCEL",requestId:e},finalPos:n}}case"PUBLISH_NAMESPACE":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:s,bytesRead:r}=ae(t,n);n+=r,ue(s);const{value:a,bytesRead:o}=$e(t,n);return n+=o,{message:{type:"PUBLISH_NAMESPACE",requestId:e,trackNamespace:s,parameters:a},finalPos:n}}case"NAMESPACE":{const{value:e,bytesRead:i}=ae(t,n);return n+=i,ge(e),{message:{type:"NAMESPACE",trackNamespaceSuffix:e},finalPos:n}}case"PUBLISH_NAMESPACE_DONE":{const{value:e,bytesRead:i}=Y(t,n);return n+=i,{message:{type:"PUBLISH_NAMESPACE_DONE",requestId:e},finalPos:n}}case"NAMESPACE_DONE":{const{value:e,bytesRead:i}=ae(t,n);return n+=i,ge(e),{message:{type:"NAMESPACE_DONE",trackNamespaceSuffix:e},finalPos:n}}case"PUBLISH_NAMESPACE_CANCEL":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:s,bytesRead:r}=Y(t,n);n+=r;const{value:a,bytesRead:o}=Ce(t,n);return n+=o,{message:{type:"PUBLISH_NAMESPACE_CANCEL",requestId:e,errorCode:s,errorReason:a},finalPos:n}}case"SUBSCRIBE_NAMESPACE":{const{value:e,bytesRead:i}=Y(t,n);n+=i;const{value:s,bytesRead:r}=ae(t,n);n+=r,pe(s);const{value:a,bytesRead:o}=Y(t,n);n+=o;const{value:c,bytesRead:d}=$e(t,n);return n+=d,{message:{type:"SUBSCRIBE_NAMESPACE",requestId:e,trackNamespacePrefix:s,subscribeOptions:a,parameters:c},finalPos:n}}case"UNSUBSCRIBE_NAMESPACE":case"PUBLISH_NAMESPACE_OK":case"PUBLISH_NAMESPACE_ERROR":case"PUBLISH_ERROR":throw new te(`Draft-14-only message type "${e}" cannot be decoded by draft-16 decoder`)}}(n,t,i,s);if(a!==s)throw new RangeError(`Payload not fully consumed for ${n}: consumed ${a-i} bytes, expected ${s-i}`);return r}(s,e,i,a);return{message:o,bytesRead:n+2+r}}function $e(e,t){let i=t;const{value:s,bytesRead:n}=Y(e,i);i+=n;const{value:r,bytesRead:a}=function(e,t,i){const s=new Map;let n=t,r=0n;for(let t=0;t65535)throw new RangeError(`KVP byte value length ${t.length} exceeds maximum 65535 (2^16-1)`);n+=i,c=t}const d=s.get(o);d?d.push(c):s.set(o,[c])}return{value:s,bytesRead:n-t}}(e,i,Number(s));return i+=a,{value:r,bytesRead:i-t}}function Fe(e,t,i){if(i-t<=0)return{value:new Map,bytesRead:0};const s=new Map;let n=t,r=0n;for(;n65535)throw new RangeError(`Track extension byte value length ${t.length} exceeds maximum 65535 (2^16-1)`);n+=i,c=t}const d=s.get(o);d?d.push(c):s.set(o,[c])}return{value:s,bytesRead:n-t}}function Ve(e,t){return se(e,t)}const qe=new Map;for(const[e,t]of Object.entries(Ie))qe.set(t,e);const Ge=32,je=3,We=2,Qe=17,Ke=20,ze=10,Ye=22,Je=23,Xe=13,Ze=7,et=8,tt=33,it=4,st=5,nt=24,rt=25,at=14,ot=15,ct=18,dt=19,ht=6,lt=9,ut=12,pt=11,mt=16,gt=21,ft=26,_t=29,vt=30,bt=31,St=new Set([_t,vt,bt]);class Et{version=14;encode(e){switch(e.type){case"CLIENT_SETUP":return this.encodeClientSetup(e);case"SUBSCRIBE":return this.encodeSubscribe(e);case"REQUEST_UPDATE":return this.encodeSubscribeUpdate(e);case"SUBSCRIBE_NAMESPACE":return this.encodeSubscribeNamespace(e);case"UNSUBSCRIBE_NAMESPACE":return this.encodeUnsubscribeNamespace(e);case"UNSUBSCRIBE":return this.encodeSimpleRequestId(ze,e.requestId);case"FETCH":return this.encodeFetch(e);case"FETCH_CANCEL":return this.encodeSimpleRequestId(Je,e.requestId);case"TRACK_STATUS":return this.encodeTrackStatus(e);case"PUBLISH_NAMESPACE":return this.encodePublishNamespace(e);case"PUBLISH_NAMESPACE_OK":return this.encodeSimpleRequestId(Ze,e.requestId);case"PUBLISH_NAMESPACE_ERROR":return this.encodePublishNamespaceError(e);case"PUBLISH_OK":return this.encodePublishOk(e);case"PUBLISH_ERROR":return this.encodePublishError(e);case"SUBSCRIBE_OK":return this.encodeSubscribeOk(e);case"PUBLISH_DONE":return this.encodePublishDone(e);case"PUBLISH_NAMESPACE_DONE":return this.encodeNamespaceTuple(lt,e.trackNamespace);case"REQUEST_ERROR":throw new Error("Draft-14 does not have generic REQUEST_ERROR — use specific error types");case"REQUEST_OK":throw new Error("Draft-14 does not have generic REQUEST_OK — use specific OK types");default:throw new Error(`Draft14Codec cannot encode message type "${e.type}"`)}}decode(e,t){let i=t;const{value:s,bytesRead:n}=Y(e,i);i+=n;const r=Number(s);let a,o;if(St.has(r)){const{value:t,bytesRead:s}=Y(e,i);i+=s,a=Number(t),o=n+s}else{if(i+2>e.length)throw new RangeError("Buffer too short for message length field");a=e[i]<<8|e[i+1],i+=2,o=n+2}const c=i+a;if(c>e.length)throw new RangeError(`Buffer too short: need ${a} bytes, have ${e.length-i}`);return{message:this.decodePayload(r,e,i,c),bytesRead:o+a}}peekFrameSize(e){if(0===e.length)return;const t=1<<(e[0]>>6);if(e.length>6);if(e.length>8&255,n[r++]=255&t.length,n.set(t,r),n}writeParams(e,t,i){let s=i;return s+=J(K(ve(e)),t,s),s+=function(e,t,i){let s=i;const n=[...e.keys()].sort((e,t)=>et?1:0);for(const i of n){const n=e.get(i);for(const e of n)if(s+=J(i,t,s),i%2n==0n)s+=J(e,t,s);else{const i=e;if(i.length>65535)throw new RangeError(`KVP byte value length ${i.length} exceeds maximum 65535 (2^16-1)`);s+=ne(i,t,s)}}return s-i}(e,t,s),s-i}paramsLength(e){return z(K(ve(e)))+function(e){let t=0;const i=[...e.keys()].sort((e,t)=>et?1:0);for(const s of i){const i=e.get(s);for(const e of i)t+=z(s),t+=s%2n==0n?z(e):re(e)}return t}(e)}assertUint8(e,t,i){if(!Number.isInteger(e)||e<0||e>255)throw new te(`${i}: ${t} must be 0-255 for 8-bit wire encoding, got ${e}`)}encodeSimpleRequestId(e,t){const i=z(t),s=new Uint8Array(i);return J(t,s,0),this.frame16(e,s)}encodeClientSetup(e){const t=K(4278190094),i=z(K(1))+z(t)+this.paramsLength(e.parameters),s=new Uint8Array(i);let n=0;return n+=J(K(1),s,n),n+=J(t,s,n),n+=this.writeParams(e.parameters,s,n),this.frame16(Ge,s)}encodeSubscribe(e){ue(e.trackNamespace);const t=Number(this.extractParamVarint(e.parameters,ke.SUBSCRIBER_PRIORITY)??128n),i=Number(this.extractParamVarint(e.parameters,ke.GROUP_ORDER)??0n),s=Number(this.extractParamVarint(e.parameters,ke.FORWARD)??1n);this.assertUint8(t,"SUBSCRIBER_PRIORITY","SUBSCRIBE"),this.assertUint8(i,"GROUP_ORDER","SUBSCRIBE"),this.assertUint8(s,"FORWARD","SUBSCRIBE");const n=this.extractFilter(e.parameters),r=this.cloneParamsWithout(e.parameters,[ke.SUBSCRIBER_PRIORITY,ke.GROUP_ORDER,ke.FORWARD,ke.SUBSCRIPTION_FILTER]);let a=0;n.startLocation&&(a+=Ee(n.startLocation)),void 0!==n.endGroup&&(a+=z(n.endGroup));const o=z(e.requestId)+ce(e.trackNamespace)+re(e.trackName)+1+1+1+z(n.filterType)+a+this.paramsLength(r),c=new Uint8Array(o);let d=0;return d+=J(e.requestId,c,d),d+=oe(e.trackNamespace,c,d),d+=ne(e.trackName,c,d),c[d++]=255&t,c[d++]=255&i,c[d++]=255&s,d+=J(n.filterType,c,d),n.startLocation&&(d+=Se(n.startLocation,c,d)),void 0!==n.endGroup&&(d+=J(n.endGroup,c,d)),d+=this.writeParams(r,c,d),this.frame16(je,c)}encodeFetch(e){1===e.fetch.fetchType&&ue(e.fetch.trackNamespace);const t=Number(this.extractParamVarint(e.parameters,ke.SUBSCRIBER_PRIORITY)??128n),i=Number(this.extractParamVarint(e.parameters,ke.GROUP_ORDER)??0n);this.assertUint8(t,"SUBSCRIBER_PRIORITY","FETCH"),this.assertUint8(i,"GROUP_ORDER","FETCH");const s=this.cloneParamsWithout(e.parameters,[ke.SUBSCRIBER_PRIORITY,ke.GROUP_ORDER]);let n=z(K(e.fetch.fetchType));1===e.fetch.fetchType?n+=ce(e.fetch.trackNamespace)+re(e.fetch.trackName)+Ee(e.fetch.startLocation)+Ee(e.fetch.endLocation):n+=z(e.fetch.joiningRequestId)+z(e.fetch.joiningStart);const r=z(e.requestId)+1+1+n+this.paramsLength(s),a=new Uint8Array(r);let o=0;return o+=J(e.requestId,a,o),a[o++]=255&t,a[o++]=255&i,o+=J(K(e.fetch.fetchType),a,o),1===e.fetch.fetchType?(o+=oe(e.fetch.trackNamespace,a,o),o+=ne(e.fetch.trackName,a,o),o+=Se(e.fetch.startLocation,a,o),o+=Se(e.fetch.endLocation,a,o)):(o+=J(e.fetch.joiningRequestId,a,o),o+=J(e.fetch.joiningStart,a,o)),o+=this.writeParams(s,a,o),this.frame16(Ye,a)}encodeTrackStatus(e){ue(e.trackNamespace);const t=z(e.requestId)+ce(e.trackNamespace)+re(e.trackName)+this.paramsLength(e.parameters),i=new Uint8Array(t);let s=0;return s+=J(e.requestId,i,s),s+=oe(e.trackNamespace,i,s),s+=ne(e.trackName,i,s),s+=this.writeParams(e.parameters,i,s),this.frame16(Xe,i)}encodeSubscribeNamespace(e){pe(e.trackNamespacePrefix);const t=z(e.requestId)+ce(e.trackNamespacePrefix)+this.paramsLength(e.parameters),i=new Uint8Array(t);let s=0;return s+=J(e.requestId,i,s),s+=oe(e.trackNamespacePrefix,i,s),s+=this.writeParams(e.parameters,i,s),this.frame16(Qe,i)}encodeUnsubscribeNamespace(e){pe(e.trackNamespacePrefix);const t=ce(e.trackNamespacePrefix),i=new Uint8Array(t);return oe(e.trackNamespacePrefix,i,0),this.frame16(Ke,i)}encodePublishNamespace(e){const t=z(e.requestId)+ce(e.trackNamespace)+this.paramsLength(e.parameters),i=new Uint8Array(t);let s=0;return s+=J(e.requestId,i,s),s+=oe(e.trackNamespace,i,s),s+=this.writeParams(e.parameters,i,s),this.frame16(ht,i)}encodeNamespaceTuple(e,t){const i=ce(t),s=new Uint8Array(i);return oe(t,s,0),this.frame16(e,s)}encodePublishNamespaceError(e){const t=z(e.requestId)+z(e.errorCode)+Re(e.errorReason),i=new Uint8Array(t);let s=0;return s+=J(e.requestId,i,s),s+=J(e.errorCode,i,s),s+=we(e.errorReason,i,s),this.frame16(et,i)}decodePayload(e,t,i,s){let n=i;switch(e){case Ge:{const{value:e,bytesRead:i}=Y(t,n);n+=i;for(let i=0;i0n?d-1n:0);if(d>0n){const e=new Uint8Array(z(K(4))+Ee(o)+z(g));let t=J(K(4),e,0);t+=Se(o,e,t),J(g,e,t),p.set(ke.SUBSCRIPTION_FILTER,[e])}else if(o.group>0n||o.object>0n){const e=new Uint8Array(z(K(3))+Ee(o));Se(o,e,J(K(3),e,0)),p.set(ke.SUBSCRIPTION_FILTER,[e])}return this.assertConsumed(n,s,"SUBSCRIBE_UPDATE"),{type:"REQUEST_UPDATE",requestId:e,existingRequestId:r,parameters:p}}case vt:{const{value:e,bytesRead:i}=Y(t,n);n+=i;const r=t[n++],a=t[n++],o=t[n++],{value:c,bytesRead:d}=Y(t,n);let h,l;if(n+=d,0x3n===c||0x4n===c){const{value:e,bytesRead:i}=be(t,n);n+=i,h=e}if(0x4n===c){const{value:e,bytesRead:i}=Y(t,n);n+=i,l=e}const{value:u,bytesRead:p}=this.readParams(t,n);n+=p,u.set(ke.FORWARD,[K(r)]),u.set(ke.SUBSCRIBER_PRIORITY,[K(a)]),u.set(ke.GROUP_ORDER,[K(o)]);const m=this.encodeFilterBytes(K(c),h,l);return u.set(ke.SUBSCRIPTION_FILTER,[m]),this.assertConsumed(n,s,"PUBLISH_OK"),{type:"PUBLISH_OK",requestId:e,parameters:u}}default:throw new te(`Unknown draft-14 message type: 0x${e.toString(16)}`)}}readParams(e,t){let i=t;const{value:s,bytesRead:n}=Y(e,i);i+=n;const{value:r,bytesRead:a}=function(e,t,i){const s=new Map;let n=t;for(let t=0;t65535)throw new RangeError(`KVP byte value length ${t.length} exceeds maximum 65535 (2^16-1)`);n+=i,a=t}const o=s.get(r);o?o.push(a):s.set(r,[a])}return{value:s,bytesRead:n-t}}(e,i,Number(s));return i+=a,{value:r,bytesRead:i-t}}assertConsumed(e,t,i){if(e!==t)throw new RangeError(`Payload not fully consumed for ${i}: consumed ${e} bytes, expected ${t}`)}extractParamVarint(e,t){const i=e.get(t);if(i&&0!==i.length)return i[0]}encodeFilterBytes(e,t,i){let s=z(e);t&&(s+=Ee(t)),void 0!==i&&(s+=z(i));const n=new Uint8Array(s);let r=J(e,n,0);return t&&(r+=Se(t,n,r)),void 0!==i&&J(i,n,r),n}cloneParamsWithout(e,t){const i=new Map,s=new Set(t.map(e=>e));for(const[t,n]of e)s.has(t)||i.set(t,n);return i}extractFilter(e){const t=e.get(ke.SUBSCRIPTION_FILTER);if(!t||0===t.length)return{filterType:K(1)};const i=t[0];if("bigint"==typeof i)return{filterType:i};const s=i;let n=0;const{value:r,bytesRead:a}=Y(s,n);let o,c;if(n+=a,0x3n===r||0x4n===r){const{value:e,bytesRead:t}=be(s,n);n+=t,o=e}if(0x4n===r){const{value:e,bytesRead:t}=Y(s,n);n+=t,c=e}const d={filterType:K(r)};return void 0!==o&&(d.startLocation=o),void 0!==c&&(d.endGroup=c),d}encodeSubscribeUpdate(e){const t=Number(this.extractParamVarint(e.parameters,ke.SUBSCRIBER_PRIORITY)??128n),i=Number(this.extractParamVarint(e.parameters,ke.FORWARD)??1n);this.assertUint8(t,"SUBSCRIBER_PRIORITY","SUBSCRIBE_UPDATE"),this.assertUint8(i,"FORWARD","SUBSCRIBE_UPDATE");const s=this.extractFilter(e.parameters),n=s.startLocation??{group:K(0),object:K(0)},r=s.endGroup??K(0),a=K(0n===r?0:r+1n),o=this.cloneParamsWithout(e.parameters,[ke.SUBSCRIBER_PRIORITY,ke.FORWARD,ke.SUBSCRIPTION_FILTER]),c=z(e.requestId)+z(e.existingRequestId)+Ee(n)+z(a)+1+1+this.paramsLength(o),d=new Uint8Array(c);let h=0;return h+=J(e.requestId,d,h),h+=J(e.existingRequestId,d,h),h+=Se(n,d,h),h+=J(a,d,h),d[h++]=255&t,d[h++]=255&i,h+=this.writeParams(o,d,h),this.frame16(We,d)}frameVarint(e,t){const i=K(e),s=z(i),n=K(t.length),r=s+z(n)+t.length,a=new Uint8Array(r);let o=0;return o+=J(i,a,o),o+=J(n,a,o),a.set(t,o),a}encodePublishOk(e){const t=Number(this.extractParamVarint(e.parameters,ke.FORWARD)??1n),i=Number(this.extractParamVarint(e.parameters,ke.SUBSCRIBER_PRIORITY)??128n),s=Number(this.extractParamVarint(e.parameters,ke.GROUP_ORDER)??1n);this.assertUint8(t,"FORWARD","PUBLISH_OK"),this.assertUint8(i,"SUBSCRIBER_PRIORITY","PUBLISH_OK"),this.assertUint8(s,"GROUP_ORDER","PUBLISH_OK");const n=this.extractFilter(e.parameters),r=n.filterType,a=new Map(e.parameters);a.delete(K(ke.FORWARD)),a.delete(K(ke.SUBSCRIBER_PRIORITY)),a.delete(K(ke.GROUP_ORDER)),a.delete(K(ke.SUBSCRIPTION_FILTER));let o=z(r);n.startLocation&&(o+=Ee(n.startLocation)),void 0!==n.endGroup&&(o+=z(n.endGroup));const c=z(e.requestId)+1+1+1+o+this.paramsLength(a),d=new Uint8Array(c);let h=0;return h+=J(e.requestId,d,h),d[h++]=255&t,d[h++]=255&i,d[h++]=255&s,h+=J(r,d,h),n.startLocation&&(h+=Se(n.startLocation,d,h)),void 0!==n.endGroup&&(h+=J(n.endGroup,d,h)),h+=this.writeParams(a,d,h),this.frameVarint(vt,d)}encodePublishError(e){const t=z(e.requestId)+z(e.errorCode)+Re(e.errorReason),i=new Uint8Array(t);let s=0;return s+=J(e.requestId,i,s),s+=J(e.errorCode,i,s),s+=we(e.errorReason,i,s),this.frameVarint(bt,i)}encodeSubscribeOk(e){const t=Number(e.parameters.get(ke.GROUP_ORDER)?.[0]??1n),i=e.parameters.get(ke.EXPIRES)?.[0],s=K("bigint"==typeof i?i:0n),n=e.parameters.get(ke.LARGEST_OBJECT)?.[0],r=void 0!==n?1:0,a=new Map;for(const[t,i]of e.parameters)t!==ke.GROUP_ORDER&&t!==ke.EXPIRES&&t!==ke.LARGEST_OBJECT&&a.set(t,i);let o=z(e.requestId)+z(e.trackAlias)+z(s)+1+1;1===r&&n instanceof Uint8Array&&(o+=n.byteLength);let c=z(K(BigInt(a.size)));for(const[e,t]of a)for(const i of t)c+=z(e),"bigint"==typeof i?(c+=z(K(z(i))),c+=z(i)):(c+=z(K(BigInt(i.byteLength))),c+=i.byteLength);o+=c;const d=new Uint8Array(o);let h=0;return h+=J(e.requestId,d,h),h+=J(e.trackAlias,d,h),h+=J(s,d,h),d[h++]=255&t,d[h++]=r,1===r&&n instanceof Uint8Array&&(d.set(n,h),h+=n.byteLength),h+=this.writeParams(a,d,h),this.frame16(it,d)}encodePublishDone(e){const t=z(e.requestId)+z(e.statusCode)+z(e.streamCount)+Re(e.errorReason),i=new Uint8Array(t);let s=0;return s+=J(e.requestId,i,s),s+=J(e.statusCode,i,s),s+=J(e.streamCount,i,s),s+=we(e.errorReason,i,s),this.frame16(pt,i)}}function yt(e=16){switch(e){case 16:return new Tt;case 14:return new Et}}class Tt{version=16;encode(e){return Pe(e)}decode(e,t){return He(e,t)}peekFrameSize(e){if(0===e.length)return;const t=1<<(e[0]>>6),i=t+2;if(e.length=16&&e<=29&&!!(6&~e):e<=63&&!!(16&e)&&!(192&e)}function Xt(e){return(e&It)>>1}const Zt=new Set([Ct.NORMAL,Ct.END_OF_GROUP,Ct.END_OF_TRACK]),ei=new Set([Ct.NORMAL,Ct.OBJECT_DOES_NOT_EXIST,Ct.END_OF_GROUP,Ct.END_OF_TRACK]);function ti(e,t=16){if(!(14===t?ei:Zt).has(e)){const i=14===t?"0x0, 0x1, 0x3, 0x4":"0x0, 0x3, 0x4";throw new te(`Invalid Object Status code: 0x${e.toString(16)} (allowed: ${i})`)}}function ii(e,t,i=16){let s=t;const{value:n,bytesRead:r}=Y(e,s);s+=r;const a=Number(n);if(!Jt(a,i))throw new te(`Invalid SUBGROUP_HEADER type byte: 0x${a.toString(16)}`);if((a&It)>>1===Lt)throw new te(`Reserved subgroup ID mode (0b11) in type byte: 0x${a.toString(16)}`);const{value:o,bytesRead:c}=Y(e,s);s+=c;const{value:d,bytesRead:h}=Y(e,s);s+=h;let l,u;if(Xt(a)===Pt){const{value:t,bytesRead:i}=Y(e,s);s+=i,l=t}else l=K(0);if(14===i||0===(a&Ot)){const{value:t}=ie(e,s);s+=1,u=t}return{header:{typeByte:a,trackAlias:o,groupId:d,subgroupId:l,publisherPriority:u,hasExtensions:0!==(a&Rt),isEndOfGroup:0!==(a&At)},bytesRead:s-t}}function si(e,t,i,s,n=!0,r=16){let a=t;const{value:o,bytesRead:c}=Y(e,a);let d,h;a+=c,d=n?o:K(s+o+1n);let l=0;if(i){const{value:t,bytesRead:i}=Y(e,a);if(a+=i,l=Number(t),a+l>e.length)throw new RangeError(`Extension length ${l} exceeds remaining buffer (${e.length-a} bytes)`);h=e.slice(a,a+l),a+=l}const{value:u,bytesRead:p}=Y(e,a);a+=p;const m=Number(u);let g,f;if(0===m){g=new Uint8Array(0);const{value:t,bytesRead:i}=Y(e,a);if(a+=i,f=t,ti(f,r),l>0&&f!==Ct.NORMAL)throw new te(`Extensions present on status object (status=0x${f.toString(16)}) per §10.2.1.2`)}else{if(a+m>e.length)throw new RangeError(`Payload length ${m} exceeds remaining buffer (${e.length-a} bytes)`);g=e.slice(a,a+m),a+=m}return{object:{objectId:d,extensions:h,payload:g,status:f},bytesRead:a-t}}function ni(e,t){let i=t;const{value:s,bytesRead:n}=Y(e,i);i+=n;const r=Number(s);if(r!==wt)throw new te(`Invalid FETCH_HEADER type byte: expected 0x05, got 0x${r.toString(16)}`);const{value:a,bytesRead:o}=Y(e,i);i+=o;return{header:{requestId:a},bytesRead:i-t}}function ri(e){return e===BigInt(zt)||e===BigInt(Yt)}function ai(e,t,i,s){let n=t;const{value:r,bytesRead:a}=Y(e,n);if(n+=a,function(e){if(!(ri(e)||e>=0n&&e<=0x7fn))throw new te(`Invalid fetch serialization flags 0x${e.toString(16)} (allowed: 0x00-0x7F, 0x8C, 0x10C)`)}(r),ri(r)){const{value:i,bytesRead:s}=Y(e,n);n+=s;const{value:a,bytesRead:o}=Y(e,n);n+=o;const{value:c,bytesRead:d}=Y(e,n);n+=d;const h=Number(c);if(h>0){if(n+h>e.length)throw new RangeError(`End of Range payload length ${h} exceeds remaining buffer (${e.length-n} bytes)`);n+=h}return{item:{flags:r,groupId:i,objectId:a,nonExistent:r===BigInt(zt)},bytesRead:n-t}}s&&function(e){const t=Number(e),i=0!==(t&Gt);if(0===(t&Ft))throw new te("First fetch object cannot inherit Group ID (GROUP_ID flag must be set)");if(0===(t&$t))throw new te("First fetch object cannot inherit Object ID (OBJECT_ID flag must be set)");if(0===(t&Vt))throw new te("First fetch object cannot inherit Priority (PRIORITY flag must be set)");if(!i){const e=t&Ht;if(e===Wt||e===Qt)throw new te(`First fetch object cannot inherit Subgroup ID (subgroup mode ${e} requires prior object)`)}}(r);const o=Number(r),c=0!==(o&Gt);let d,h,l,u,p;if(0!==(o&Ft)){const{value:t,bytesRead:i}=Y(e,n);n+=i,d=t}else d=K(i.groupId);if(c)h=K(0);else{const t=o&Ht;switch(t){case jt:h=K(0);break;case Wt:h=K(i.subgroupId);break;case Qt:h=K(i.subgroupId+1n);break;case Kt:{const{value:t,bytesRead:i}=Y(e,n);n+=i,h=t;break}default:throw new te(`Invalid subgroup mode: ${t}`)}}if(0!==(o&$t)){const{value:t,bytesRead:i}=Y(e,n);n+=i,l=t}else l=K(i.objectId+1n);if(0!==(o&Vt)){const{value:t}=ie(e,n);n+=1,u=t}else void 0!==i?.priority&&(u=i.priority);if(0!==(o&qt)){const{value:t,bytesRead:i}=Y(e,n);n+=i;const s=Number(t);if(n+s>e.length)throw new RangeError(`Extension length ${s} exceeds remaining buffer (${e.length-n} bytes)`);p=e.slice(n,n+s),n+=s}const{value:m,bytesRead:g}=Y(e,n);n+=g;const f=Number(m);if(n+f>e.length)throw new RangeError(`Payload length ${f} exceeds remaining buffer (${e.length-n} bytes)`);const _=e.slice(n,n+f);n+=f;return{item:{flags:r,groupId:d,subgroupId:h,objectId:l,publisherPriority:u,isDatagram:c,extensions:p,payload:_},bytesRead:n-t}}function oi(e,t){let i=t;const{value:s,bytesRead:n}=Y(e,i);i+=n;const{value:r,bytesRead:a}=Y(e,i);i+=a;const{value:o,bytesRead:c}=Y(e,i);i+=c;const{value:d}=ie(e,i);i+=1;const{value:h,bytesRead:l}=Y(e,i);i+=l;const u=Number(h);let p;if(u>0){if(i+u>e.length)throw new RangeError(`Extension length ${u} exceeds remaining buffer (${e.length-i} bytes)`);p=e.slice(i,i+u),i+=u}const{value:m,bytesRead:g}=Y(e,i);i+=g;const f=Number(m);if(0===f){const{value:n,bytesRead:r}=Y(e,i);i+=r,ti(n,14);return{item:{flags:K(0n),groupId:s,objectId:o,nonExistent:n===Ct.OBJECT_DOES_NOT_EXIST,rawStatus:n},bytesRead:i-t}}if(i+f>e.length)throw new RangeError(`Payload length ${f} exceeds remaining buffer (${e.length-i} bytes)`);const _=e.slice(i,i+f);i+=f;return{item:{flags:K(0n),groupId:s,subgroupId:r,objectId:o,publisherPriority:d,isDatagram:!1,extensions:p,payload:_},bytesRead:i-t}}function ci(e,t,i=16){let s=t;const{value:n,bytesRead:r}=Y(e,s);s+=r;const a=Number(n);if(!function(e,t=16){return 14===t?e>=0&&e<=7||e>=32&&e<=33:e<=47&&!(16&e)&&!(192&e)}(a,i))throw new te(`Invalid OBJECT_DATAGRAM type byte: 0x${a.toString(16)}`);if(0!==((o=a)&xt)&&0!==(o&Dt))throw new te(`Invalid OBJECT_DATAGRAM flag combination (STATUS + END_OF_GROUP): 0x${a.toString(16)}`);var o;const{value:c,bytesRead:d}=Y(e,s);s+=d;const{value:h,bytesRead:l}=Y(e,s);let u,p,m;if(s+=l,0!==(a&Mt))u=K(1);else{const{value:t,bytesRead:i}=Y(e,s);s+=i,u=t}if(14===i||0===(a&Bt)){const{value:t}=ie(e,s);s+=1,p=t}let g=0;if(0!==(a&Ut)){const{value:t,bytesRead:i}=Y(e,s);if(s+=i,g=Number(t),0===g)throw new te("OBJECT_DATAGRAM has EXTENSIONS flag set but Extension Headers Length is 0");if(s+g>e.length)throw new RangeError(`Extension length ${g} exceeds remaining buffer (${e.length-s} bytes)`);m=e.slice(s,s+g),s+=g}const f=0!==(a&Dt);let _,v;if(0!==(a&xt)){const{value:t,bytesRead:n}=Y(e,s);if(s+=n,v=t,_=new Uint8Array(0),ti(v,i),g>0&&v!==Ct.NORMAL)throw new te(`Extensions present on status datagram (status=0x${v.toString(16)}) per §10.2.1.2`);if(s=this.peerMaxRequestId)throw this.blocked=!0,new Ii(`Cannot allocate request ID ${this.nextOutgoingId}: exceeds peer MAX_REQUEST_ID ${this.peerMaxRequestId}`,"TOO_MANY_REQUESTS");const e=K(this.nextOutgoingId);return this.nextOutgoingId+=2n,e}validateIncoming(e){const t=1n&e;if(t!==this.peerParityBit)throw new Ii(`Invalid request ID parity: ${e} has LSB=${t}, expected ${this.peerParityBit} from peer`,"INVALID_REQUEST_ID");if(e>=this.ourMaxRequestId)throw new Ii(`Request ID ${e} exceeds our MAX_REQUEST_ID ${this.ourMaxRequestId}`,"TOO_MANY_REQUESTS");const i=this.highestIncomingId+2n;if(e!==i)throw new Ii(`Request ID ${e} not next in sequence: expected ${i}`,"INVALID_REQUEST_ID");this.highestIncomingId=e}validateOurRequestId(e){const t=1n&e;if(t!==this.parityBit)throw new Ii(`Response has wrong parity: ${e} has LSB=${t}, expected ${this.parityBit} for our requests`,"INVALID_REQUEST_ID");if(e>=this.nextOutgoingId)throw new Ii(`Response for unknown request ID ${e}: next outgoing is ${this.nextOutgoingId}`,"INVALID_REQUEST_ID")}peekNextId(){return K(this.nextOutgoingId)}getPeerMaxRequestId(){return K(this.peerMaxRequestId)}shouldReplenish(){if(0n===this.ourMaxRequestId)return!1;const e=this.ourMaxRequestId/2n;return this.highestIncomingId>=e}nextReplenishValue(){return K(this.ourMaxRequestId+this.windowSize)}commitReplenish(){const e=this.ourMaxRequestId+this.windowSize;this.ourMaxRequestId=e}}const ki={DELETE:K(0),REGISTER:K(1),USE_ALIAS:K(2),USE_VALUE:K(3)};function Oi(e){if(0===e.length)throw new te("Empty AUTHORIZATION_TOKEN parameter");let t=0;const{value:i,bytesRead:s}=Y(e,t);switch(t+=s,i){case ki.DELETE:{if(t>=e.length)throw new te("DELETE token missing Token Alias");const{value:i,bytesRead:s}=Y(e,t);if(t+=s,t!==e.length)throw new te(`DELETE token has ${e.length-t} trailing bytes`);return{aliasType:ki.DELETE,tokenAlias:i}}case ki.REGISTER:{if(t>=e.length)throw new te("REGISTER token missing Token Alias");const{value:i,bytesRead:s}=Y(e,t);if(t+=s,t>=e.length)throw new te("REGISTER token missing Token Type");const{value:n,bytesRead:r}=Y(e,t);t+=r;const a=e.slice(t);return{aliasType:ki.REGISTER,tokenAlias:i,tokenType:n,tokenValue:a}}case ki.USE_ALIAS:{if(t>=e.length)throw new te("USE_ALIAS token missing Token Alias");const{value:i,bytesRead:s}=Y(e,t);if(t+=s,t!==e.length)throw new te(`USE_ALIAS token has ${e.length-t} trailing bytes`);return{aliasType:ki.USE_ALIAS,tokenAlias:i}}case ki.USE_VALUE:{if(t>=e.length)throw new te("USE_VALUE token missing Token Type");const{value:i,bytesRead:s}=Y(e,t);t+=s;const n=e.slice(t);return{aliasType:ki.USE_VALUE,tokenType:i,tokenValue:n}}default:throw new te(`Unknown AUTHORIZATION_TOKEN Alias Type: ${i}`)}}class Ni extends Error{code;constructor(e,t){super(e),this.code=t,this.name="SetupError"}}class Pi{role;state=di;setupResult;constructor(e){this.role=e}get sessionState(){return this.state}isComplete(){return this.state===li}getResult(){if(!this.setupResult)throw new Error("Setup handshake not complete");return this.setupResult}validateMessage(e){if(this.state===di){if(this.role===mi)throw new Ni("Client must send CLIENT_SETUP before receiving any messages","PROTOCOL_VIOLATION");if("CLIENT_SETUP"!==e.type)throw new Ni(`First message must be CLIENT_SETUP, got ${e.type}`,"PROTOCOL_VIOLATION")}else if(this.state===hi){if(this.role===mi&&"SERVER_SETUP"!==e.type)throw new Ni(`Expected SERVER_SETUP after CLIENT_SETUP, got ${e.type}`,"PROTOCOL_VIOLATION");if(this.role===gi)throw new Ni("Server should not receive messages while SETUP_PENDING","PROTOCOL_VIOLATION")}}createClientSetup(e={}){if(this.role!==mi)throw new Error("Only client can create CLIENT_SETUP");if(this.state!==di)throw new Error(`Cannot create CLIENT_SETUP in state ${this.state}`);const t=new Map;return void 0!==e.maxRequestId&&t.set(K(Ae.MAX_REQUEST_ID),[e.maxRequestId]),void 0!==e.path&&t.set(K(Ae.PATH),[(new TextEncoder).encode(e.path)]),void 0!==e.authority&&t.set(K(Ae.AUTHORITY),[(new TextEncoder).encode(e.authority)]),void 0!==e.implementation&&t.set(K(Ae.MOQT_IMPLEMENTATION),[(new TextEncoder).encode(e.implementation)]),void 0!==e.maxAuthTokenCacheSize&&t.set(K(Ae.MAX_AUTH_TOKEN_CACHE_SIZE),[e.maxAuthTokenCacheSize]),void 0!==e.authTokens&&e.authTokens.length>0&&t.set(K(Ae.AUTHORIZATION_TOKEN),e.authTokens),this.state=hi,{type:"CLIENT_SETUP",parameters:t}}handleClientSetup(e){if(this.role!==gi)throw new Ni("Only server handles CLIENT_SETUP","PROTOCOL_VIOLATION");if(this.state!==di)throw new Ni(`Cannot handle CLIENT_SETUP in state ${this.state}`,"PROTOCOL_VIOLATION");const t=this.extractSetupParams(e.parameters,!0);return this.setupResult=t,this.state=hi,t}createServerSetup(e={}){if(this.role!==gi)throw new Error("Only server can create SERVER_SETUP");if(this.state!==hi)throw new Error(`Cannot create SERVER_SETUP in state ${this.state}`);const t=new Map;return void 0!==e.maxRequestId&&t.set(K(Ae.MAX_REQUEST_ID),[e.maxRequestId]),void 0!==e.implementation&&t.set(K(Ae.MOQT_IMPLEMENTATION),[(new TextEncoder).encode(e.implementation)]),void 0!==e.maxAuthTokenCacheSize&&t.set(K(Ae.MAX_AUTH_TOKEN_CACHE_SIZE),[e.maxAuthTokenCacheSize]),void 0!==e.authTokens&&e.authTokens.length>0&&t.set(K(Ae.AUTHORIZATION_TOKEN),e.authTokens),this.state=li,{type:"SERVER_SETUP",parameters:t}}handleServerSetup(e){if(this.role!==mi)throw new Ni("Only client handles SERVER_SETUP","PROTOCOL_VIOLATION");if(this.state!==hi)throw new Ni(`Cannot handle SERVER_SETUP in state ${this.state}`,"PROTOCOL_VIOLATION");if(e.parameters.has(Ae.PATH))throw new Ni("Server sent PATH parameter","INVALID_PATH");if(e.parameters.has(Ae.AUTHORITY))throw new Ni("Server sent AUTHORITY parameter","INVALID_AUTHORITY");const t=this.extractSetupParams(e.parameters,!1);return this.setupResult=t,this.state=li,t}extractSetupParams(e,t){let i,s,n,r,a=K(0);const o=[];for(const[c,d]of e){if(!(c===Ae.MAX_REQUEST_ID||c===Ae.MOQT_IMPLEMENTATION||c===Ae.PATH||c===Ae.AUTHORITY||c===Ae.AUTHORIZATION_TOKEN||c===Ae.MAX_AUTH_TOKEN_CACHE_SIZE))continue;if(c===Ae.AUTHORIZATION_TOKEN){for(const e of d){if(!(e instanceof Uint8Array))continue;let i;try{i=Oi(e)}catch{throw new Ni("Malformed AUTHORIZATION_TOKEN structure","KEY_VALUE_FORMATTING_ERROR")}if(t&&(i.aliasType===ki.DELETE||i.aliasType===ki.USE_ALIAS))throw new Ni(`CLIENT_SETUP AUTHORIZATION_TOKEN cannot use Alias Type ${i.aliasType} (DELETE and USE_ALIAS are prohibited in CLIENT_SETUP)`,"PROTOCOL_VIOLATION");o.push(i)}continue}if(d.length>1)throw new Ni(`Duplicate setup parameter: ${c}`,"PROTOCOL_VIOLATION");const e=d[0];if(c===Ae.MAX_REQUEST_ID)"bigint"==typeof e&&(a=e);else if(c===Ae.MOQT_IMPLEMENTATION)e instanceof Uint8Array&&(i=(new TextDecoder).decode(e));else if(c===Ae.MAX_AUTH_TOKEN_CACHE_SIZE)"bigint"==typeof e&&(r=e);else if(c===Ae.PATH){if(t&&e instanceof Uint8Array){const t=(new TextDecoder).decode(e);this.validatePath(t),s=t}}else if(c===Ae.AUTHORITY&&t&&e instanceof Uint8Array){const t=(new TextDecoder).decode(e);this.validateAuthority(t),n=t}}const c={peerMaxRequestId:a};return void 0!==i&&(c.peerImplementation=i),void 0!==s&&(c.path=s),void 0!==n&&(c.authority=n),void 0!==r&&(c.peerMaxAuthTokenCacheSize=r),o.length>0&&(c.authTokens=o),c}validatePath(e){const t=e.indexOf("?"),i=-1===t?e:e.slice(0,t),s=-1===t?"":e.slice(t+1);if(i.length>0&&!i.startsWith("/"))throw new Ni("PATH path component must start with / or be empty","MALFORMED_PATH");if(!/^(\/[A-Za-z0-9\-._~!$&'()*+,;=:@%]*)*$/.test(i))throw new Ni("PATH contains invalid characters","MALFORMED_PATH");if(s.length>0){if(!/^[A-Za-z0-9\-._~!$&'()*+,;=:@%\/?]*$/.test(s))throw new Ni("PATH query contains invalid characters","MALFORMED_PATH")}if(e.replace(/%[0-9A-Fa-f]{2}/g,"").includes("%"))throw new Ni("PATH contains malformed percent encoding","MALFORMED_PATH")}validateAuthority(e){if(0===e.length)throw new Ni("AUTHORITY cannot be empty","MALFORMED_AUTHORITY");let t=e;const i=t.indexOf("@");if(-1!==i){const e=t.slice(0,i);t=t.slice(i+1);if(!/^[A-Za-z0-9\-._~!$&'()*+,;=:%]*$/.test(e))throw new Ni("AUTHORITY userinfo contains invalid characters","MALFORMED_AUTHORITY");if(!this.hasValidPercentEncoding(e))throw new Ni("AUTHORITY userinfo has malformed percent encoding","MALFORMED_AUTHORITY")}let s,n=t;if(t.startsWith("[")){const e=t.indexOf("]");if(-1===e)throw new Ni("AUTHORITY has unclosed IP-literal bracket","MALFORMED_AUTHORITY");if(n=t.slice(0,e+1),t.length>e+1){if(":"!==t[e+1])throw new Ni("AUTHORITY has invalid characters after IP-literal","MALFORMED_AUTHORITY");s=t.slice(e+2)}const i=n.slice(1,-1);if(i.startsWith("v")){if(!/^v[0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&'()*+,;=:]+$/.test(i))throw new Ni("AUTHORITY has invalid IPvFuture","MALFORMED_AUTHORITY")}else this.validateIPv6(i)}else{const e=t.lastIndexOf(":");if(-1!==e){const i=t.slice(e+1);/^\d*$/.test(i)&&(n=t.slice(0,e),s=i)}if(0===n.length)throw new Ni("AUTHORITY MUST NOT contain an empty host portion","MALFORMED_AUTHORITY");if(!/^[A-Za-z0-9\-._~!$&'()*+,;=%]*$/.test(n))throw new Ni("AUTHORITY host contains invalid characters","MALFORMED_AUTHORITY");if(!this.hasValidPercentEncoding(n))throw new Ni("AUTHORITY host has malformed percent encoding","MALFORMED_AUTHORITY")}if(void 0!==s&&s.length>0){const e=parseInt(s,10);if(isNaN(e)||e<0||e>65535)throw new Ni("AUTHORITY has invalid port number","MALFORMED_AUTHORITY")}}hasValidPercentEncoding(e){return!e.replace(/%[0-9A-Fa-f]{2}/g,"").includes("%")}validateIPv6(e){let t=!1,i=e;const s=e.lastIndexOf(":");if(-1!==s&&e.slice(s+1).includes(".")){const n=e.slice(s+1),r=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(n);if(!r)throw new Ni("AUTHORITY has invalid embedded IPv4 in IPv6","MALFORMED_AUTHORITY");for(let e=1;e<=4;e++){const t=r[e];if(t.length>1&&"0"===t[0])throw new Ni("AUTHORITY has invalid embedded IPv4 in IPv6 (leading zeros)","MALFORMED_AUTHORITY");if(parseInt(t,10)>255)throw new Ni("AUTHORITY has invalid embedded IPv4 in IPv6","MALFORMED_AUTHORITY")}t=!0,i=s>0&&":"===e[s-1]?e.slice(0,s+1):e.slice(0,s)}if(i.includes(":::"))throw new Ni("AUTHORITY IPv6 has invalid consecutive colons","MALFORMED_AUTHORITY");const n=i.includes("::");if((i.match(/::/g)||[]).length>1)throw new Ni("AUTHORITY IPv6 has multiple zero-compression (::)","MALFORMED_AUTHORITY");const r=i.split(":"),a=/^[0-9A-Fa-f]{1,4}$/;let o=0;const c=[];for(let e=0;e=d)throw new Ni("AUTHORITY IPv6 :: must compress at least one segment","MALFORMED_AUTHORITY")}else{if(r.length!==d)throw new Ni(`AUTHORITY IPv6 must have ${d} segments, got ${r.length}`,"MALFORMED_AUTHORITY");if(o!==d)throw new Ni("AUTHORITY IPv6 has empty segment without ::","MALFORMED_AUTHORITY")}}}class Li{_requestId;_isPublisher;_trackNamespace;_trackName;_state=fi;_forwardState=Si;_trackAlias;_errorCode;_errorReason;_terminationCode;_largestLocation;_trackKey;_streamCount=0n;_currentFilter;_currentPriority;_publishInitiated=!1;_publishParameters=new Map;constructor(e,t,i,s){this._requestId=e,this._isPublisher=t,this._trackNamespace=i,this._trackName=s,i&&s&&(this._trackKey=this.computeTrackKey(i,s))}static createAsSubscriber(e,t,i){return new Li(e,!1,t,i)}static createAsPublisher(e,t,i){return new Li(e,!0,t,i)}static createFromPublish(e,t,i,s){const n=new Li(e,!0,t,i);return n._publishInitiated=!0,s&&(n._publishParameters=s),n}get state(){return this._state}get forwardState(){return this._forwardState}get requestId(){return this._requestId}get trackAlias(){return this._trackAlias}get errorCode(){return this._errorCode}get errorReason(){return this._errorReason}get terminationCode(){return this._terminationCode}get largestLocation(){return this._largestLocation}get streamCount(){return K(this._streamCount)}incrementStreamCount(){this._streamCount++}get trackNamespace(){return this._trackNamespace}get trackName(){return this._trackName}get trackKey(){return this._trackKey}get isPublishInitiated(){return this._publishInitiated}get publishParameters(){return this._publishParameters}get currentFilter(){return this._currentFilter}set currentFilter(e){this._currentFilter=e}get currentPriority(){return this._currentPriority}set currentPriority(e){this._currentPriority=e}get isPublisher(){return this._isPublisher}get isPending(){return this._state===fi}get isActive(){return this._state===_i&&this._forwardState===Si}get isTerminated(){return this._state===vi}handleSubscribeOk(e){this.assertState(fi,"handleSubscribeOk"),this.assertNotPublisher("handleSubscribeOk"),this._trackAlias=e,this._state=_i}handleRequestError(e,t){this.assertNotTerminated("handleRequestError"),this.assertNotPublisher("handleRequestError"),this._errorCode=e,this._errorReason=t,this._state=vi}handlePublishDone(e,t){this.assertState(_i,"handlePublishDone"),this.assertNotPublisher("handlePublishDone"),this._terminationCode=e,this._errorReason=t,this._state=vi}sendSubscribeOk(e){this.assertState(fi,"sendSubscribeOk"),this.assertPublisher("sendSubscribeOk"),this._trackAlias=e,this._state=_i}sendRequestError(e,t){this.assertNotTerminated("sendRequestError"),this.assertPublisher("sendRequestError"),this._errorCode=e,this._errorReason=t,this._state=vi}sendUnsubscribe(){this.assertState(_i,"sendUnsubscribe"),this.assertNotPublisher("sendUnsubscribe"),this._state=vi}handleUnsubscribe(){this.assertState(_i,"handleUnsubscribe"),this.assertPublisher("handleUnsubscribe"),this._state=vi}sendPublishDone(e,t){this.assertState(_i,"sendPublishDone"),this.assertPublisher("sendPublishDone"),this._terminationCode=e,this._errorReason=t,this._state=vi}updateForwardState(e){this.assertState(_i,"updateForwardState"),this._forwardState=e}updateLargestLocation(e,t){this._largestLocation?(e>this._largestLocation.groupId||e===this._largestLocation.groupId&&t>this._largestLocation.objectId)&&(this._largestLocation={groupId:e,objectId:t}):this._largestLocation={groupId:e,objectId:t}}assertState(e,t){if(this._state!==e)throw new Error(`Cannot ${t} in state ${this._state}; expected ${e}`)}assertNotTerminated(e){if(this._state===vi)throw new Error(`Cannot ${e} in TERMINATED state`)}assertPublisher(e){if(!this._isPublisher)throw new Error(`${e} is only valid for publisher side`)}assertNotPublisher(e){if(this._isPublisher)throw new Error(`${e} is only valid for subscriber side`)}computeTrackKey(e,t){const i=[];for(const t of e)i.push(this.bytesToHex(t));return i.push(this.bytesToHex(t)),i.join("/")}bytesToHex(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}}class Ui{_requestId;_isPublisher;_startGroup;_startObject;_endGroup;_endObject;_state=Ei;_errorCode;_errorReason;_wasCanceled=!1;constructor(e,t,i,s,n,r){this._requestId=e,this._isPublisher=t,this._startGroup=i,this._startObject=s,this._endGroup=n,this._endObject=r}static createAsFetcher(e,t,i,s,n){return new Ui(e,!1,t,i,s,n)}static createAsPublisher(e,t,i,s,n){return new Ui(e,!0,t,i,s,n)}get state(){return this._state}get requestId(){return this._requestId}get errorCode(){return this._errorCode}get errorReason(){return this._errorReason}get wasCanceled(){return this._wasCanceled}get isPublisher(){return this._isPublisher}get startGroup(){return this._startGroup}get startObject(){return this._startObject}get endGroup(){return this._endGroup}get endObject(){return this._endObject}get isPending(){return this._state===Ei}get isTransferring(){return this._state===yi}get isCompleted(){return this._state===Ti}handleFetchOk(){this.assertState(Ei,"handleFetchOk"),this.assertNotPublisher("handleFetchOk"),this._state=yi}handleRequestError(e,t){this.assertNotCompleted("handleRequestError"),this.assertNotTransferring("handleRequestError"),this.assertNotPublisher("handleRequestError"),this._errorCode=e,this._errorReason=t,this._state=Ti}sendFetchOk(){this.assertState(Ei,"sendFetchOk"),this.assertPublisher("sendFetchOk"),this._state=yi}sendRequestError(e,t){this.assertNotCompleted("sendRequestError"),this.assertNotTransferring("sendRequestError"),this.assertPublisher("sendRequestError"),this._errorCode=e,this._errorReason=t,this._state=Ti}handleFetchCancel(){this.assertState(yi,"handleFetchCancel"),this.assertPublisher("handleFetchCancel"),this._wasCanceled=!0,this._state=Ti}sendFetchCancel(){this.assertNotCompleted("sendFetchCancel"),this.assertNotPublisher("sendFetchCancel"),this._wasCanceled=!0,this._state=Ti}handleStreamFinish(){this.assertState(yi,"handleStreamFinish"),this._state=Ti}assertState(e,t){if(this._state!==e)throw new Error(`Cannot ${t} in state ${this._state}; expected ${e}`)}assertNotCompleted(e){if(this._state===Ti)throw new Error(`Cannot ${e} in COMPLETED state`)}assertNotTransferring(e){if(this._state===yi)throw new Error(`Cannot ${e} in TRANSFERRING state`)}assertPublisher(e){if(!this._isPublisher)throw new Error(`${e} is only valid for publisher side`)}assertNotPublisher(e){if(this._isPublisher)throw new Error(`${e} is only valid for fetcher side`)}}class Di{_requestId;_isPublisher;_namespacePrefix;_state=Ci;_errorCode;_errorReason;_discoveredNamespaces=[];_prefixKey;constructor(e,t,i){this._requestId=e,this._isPublisher=t,this._namespacePrefix=i,this._prefixKey=this.computePrefixKey(i)}static createAsSubscriber(e,t){return new Di(e,!1,t)}static createAsPublisher(e,t){return new Di(e,!0,t)}get state(){return this._state}get requestId(){return this._requestId}get namespacePrefix(){return this._namespacePrefix}get errorCode(){return this._errorCode}get errorReason(){return this._errorReason}get discoveredNamespaces(){return this._discoveredNamespaces}get prefixKey(){return this._prefixKey}get isPublisher(){return this._isPublisher}get isPending(){return this._state===Ci}get isActive(){return this._state===wi}get isTerminated(){return this._state===Ri}handleRequestOk(){this.assertState(Ci,"handleRequestOk"),this.assertNotPublisher("handleRequestOk"),this._state=wi}handleRequestError(e,t){this.assertNotTerminated("handleRequestError"),this.assertNotPublisher("handleRequestError"),this._errorCode=e,this._errorReason=t,this._state=Ri}handleNamespace(e){this.assertState(wi,"handleNamespace"),this.assertNotPublisher("handleNamespace"),this._discoveredNamespaces.push(e)}hasDiscoveredSuffix(e){return this._discoveredNamespaces.some(t=>this.suffixEquals(t,e))}withdrawNamespace(e){this.assertState(wi,"withdrawNamespace");const t=this._discoveredNamespaces.findIndex(t=>this.suffixEquals(t,e));-1!==t&&this._discoveredNamespaces.splice(t,1)}handleNamespaceDone(){this.assertState(wi,"handleNamespaceDone"),this.assertNotPublisher("handleNamespaceDone"),this._state=Ri}sendRequestOk(){this.assertState(Ci,"sendRequestOk"),this.assertPublisher("sendRequestOk"),this._state=wi}sendRequestError(e,t){this.assertNotTerminated("sendRequestError"),this.assertPublisher("sendRequestError"),this._errorCode=e,this._errorReason=t,this._state=Ri}sendNamespace(e){this.assertState(wi,"sendNamespace"),this.assertPublisher("sendNamespace"),this._discoveredNamespaces.push(e)}sendNamespaceDone(){this.assertState(wi,"sendNamespaceDone"),this.assertPublisher("sendNamespaceDone"),this._state=Ri}assertState(e,t){if(this._state!==e)throw new Error(`Cannot ${t} in state ${this._state}; expected ${e}`)}assertNotTerminated(e){if(this._state===Ri)throw new Error(`Cannot ${e} in TERMINATED state`)}assertPublisher(e){if(!this._isPublisher)throw new Error(`${e} is only valid for publisher side`)}assertNotPublisher(e){if(this._isPublisher)throw new Error(`${e} is only valid for subscriber side`)}computePrefixKey(e){const t=[];for(const i of e)t.push(this.bytesToHex(i));return t.join("/")}bytesToHex(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}suffixEquals(e,t){if(e.length!==t.length)return!1;for(let i=0;ie.toString(16).padStart(2,"0")).join("")}}class Bi extends Error{code;constructor(e,t){super(e),this.code=t,this.name="AuthCacheError"}get sessionErrorCode(){return X[this.code]}}class xi{maxBytes;cache=new Map;_currentSize=0;constructor(e){this.maxBytes=e}register(e,t,i,s){if(this.cache.has(e))throw new Bi(`Token alias ${e} is already registered`,"DUPLICATE_AUTH_TOKEN_ALIAS");const n=16+i.length;if(this._currentSize+n>this.maxBytes){if(s)return null;throw new Bi(`Registering alias ${e} would exceed MAX_AUTH_TOKEN_CACHE_SIZE (current: ${this._currentSize}, entry: ${n}, max: ${this.maxBytes})`,"AUTH_TOKEN_CACHE_OVERFLOW")}const r={tokenType:t,tokenValue:i};return this.cache.set(e,r),this._currentSize+=n,r}delete(e){const t=this.cache.get(e);if(!t)throw new Bi(`Token alias ${e} is not registered`,"UNKNOWN_AUTH_TOKEN_ALIAS");const i=16+t.tokenValue.length;this.cache.delete(e),this._currentSize-=i}resolve(e){const t=this.cache.get(e);if(!t)throw new Bi(`Token alias ${e} is not registered`,"UNKNOWN_AUTH_TOKEN_ALIAS");return t}get currentSize(){return this._currentSize}get size(){return this.cache.size}}const Hi=new Set([ke.DELIVERY_TIMEOUT,ke.AUTHORIZATION_TOKEN,ke.EXPIRES,ke.LARGEST_OBJECT,ke.FORWARD,ke.SUBSCRIBER_PRIORITY,ke.SUBSCRIPTION_FILTER,ke.GROUP_ORDER,ke.NEW_GROUP_REQUEST]),$i=new Map([[ke.DELIVERY_TIMEOUT,new Set(["PUBLISH_OK","SUBSCRIBE","REQUEST_UPDATE"])],[ke.AUTHORIZATION_TOKEN,new Set(["PUBLISH","SUBSCRIBE","REQUEST_UPDATE","SUBSCRIBE_NAMESPACE","PUBLISH_NAMESPACE","TRACK_STATUS","FETCH"])],[ke.EXPIRES,new Set(["SUBSCRIBE_OK","PUBLISH","PUBLISH_OK"])],[ke.LARGEST_OBJECT,new Set(["SUBSCRIBE_OK","PUBLISH","REQUEST_OK"])],[ke.FORWARD,new Set(["SUBSCRIBE","REQUEST_UPDATE","PUBLISH","PUBLISH_OK","SUBSCRIBE_NAMESPACE"])],[ke.SUBSCRIBER_PRIORITY,new Set(["SUBSCRIBE","FETCH","REQUEST_UPDATE","PUBLISH_OK"])],[ke.SUBSCRIPTION_FILTER,new Set(["SUBSCRIBE","PUBLISH_OK","REQUEST_UPDATE"])],[ke.GROUP_ORDER,new Set(["SUBSCRIBE","PUBLISH_OK","FETCH"])],[ke.NEW_GROUP_REQUEST,new Set(["PUBLISH_OK","SUBSCRIBE","REQUEST_UPDATE"])]]);class Fi extends Error{code;constructor(e,t){super(e),this.code=t,this.name="SessionError"}}class Vi extends Error{newUri;constructor(e,t){super(e),this.newUri=t,this.name="SessionDrainingError"}}class qi{_role;_draftVersion;setupGate;requestIdAllocator;trackAliases=new Mi;subscriptions=new Map;subscriptionTracks=new Map;fetches=new Map;incomingSubscriptions=new Map;incomingFetches=new Map;namespaceSubscriptions=new Map;pendingUpdates=new Map;pendingTrackStatuses=new Map;publishedNamespaces=new Map;incomingTrackStatuses=new Map;authCache=null;_ownMaxAuthTokenCacheSize=0;_peerMaxAuthTokenCacheSize=K(0n);_state=di;_newSessionUri;_peerMaxRequestId=K(0n);_goawayReceived=!1;constructor(e,t=16){this._role=e,this._draftVersion=t,this.setupGate=new Pi(e),this.requestIdAllocator=new Ai(e)}get state(){return this._state}get role(){return this._role}get newSessionUri(){return this._newSessionUri}get draftVersion(){return this._draftVersion}get peerMaxRequestId(){return this._peerMaxRequestId}get peerMaxAuthTokenCacheSize(){return this._peerMaxAuthTokenCacheSize}initiateSetup(e={}){this.assertState(di,"initiateSetup");const t=this.setupGate.createClientSetup(e);return e.maxRequestId&&e.maxRequestId>0n&&this.requestIdAllocator.setOurMaxRequestId(e.maxRequestId),void 0!==e.maxAuthTokenCacheSize&&(this._ownMaxAuthTokenCacheSize=Number(e.maxAuthTokenCacheSize)),this._state=hi,[this.sendControl(t)]}completeSetup(e={}){if(this.assertState(hi,"completeSetup"),this._role!==gi)throw new Fi("Only server can call completeSetup","INVALID_STATE");const t=this.setupGate.createServerSetup(e);return e.maxRequestId&&e.maxRequestId>0n&&this.requestIdAllocator.setOurMaxRequestId(e.maxRequestId),void 0!==e.maxAuthTokenCacheSize&&(this._ownMaxAuthTokenCacheSize=Number(e.maxAuthTokenCacheSize)),this._state=li,[this.sendControl(t)]}handleControlMessage(e){if(this._state===di||this._state===hi)return this.handleSetupMessage(e);if(this._state===pi)throw new Fi("Session is closed","INVALID_STATE");const t=this.validateControlMessageParams(e);if(t)return this.closeWithError(t.error,t.reason);try{switch(e.type){case"GOAWAY":return this.handleGoaway(e);case"MAX_REQUEST_ID":return this.handleMaxRequestId(e);case"REQUESTS_BLOCKED":return this.handleRequestsBlocked(e);case"SUBSCRIBE_OK":return this.handleSubscribeOk(e);case"REQUEST_ERROR":return this.handleRequestError(e);case"FETCH_OK":return this.handleFetchOk(e);case"REQUEST_OK":return this.handleRequestOk(e);case"PUBLISH_DONE":return this.handlePublishDone(e);case"UNSUBSCRIBE":return this.handleUnsubscribe(e);case"SUBSCRIBE":return this.handleIncomingSubscribe(e);case"PUBLISH":return this.handleIncomingPublish(e);case"FETCH":return this.handleIncomingFetch(e);case"FETCH_CANCEL":return this.handleFetchCancel(e);case"REQUEST_UPDATE":return this.handleIncomingRequestUpdate(e);case"TRACK_STATUS":return this.handleIncomingTrackStatus(e);case"PUBLISH_NAMESPACE":return this.handleIncomingPublishNamespace(e);case"PUBLISH_NAMESPACE_DONE":return this.handlePublishNamespaceDone(e);case"PUBLISH_NAMESPACE_CANCEL":return this.handlePublishNamespaceCancel(e);case"PUBLISH_NAMESPACE_OK":return this.handlePublishNamespaceOk(e);case"PUBLISH_NAMESPACE_ERROR":return this.handlePublishNamespaceError(e);case"UNSUBSCRIBE_NAMESPACE":return this.handleIncomingUnsubscribeNamespace(e);default:if(14===this._draftVersion)return this.closeWithError(X.PROTOCOL_VIOLATION,`Unsupported message type ${e.type}`);if("requestId"in e&&"bigint"==typeof e.requestId){const t=e.requestId;return[this.sendControl({type:"REQUEST_ERROR",requestId:t,errorCode:Z.NOT_SUPPORTED,retryInterval:K(0n),errorReason:`Message type ${e.type} is not supported`})]}return[]}}catch(e){return this.closeWithError(X.PROTOCOL_VIOLATION,e instanceof Error?e.message:String(e))}}handleSetupMessage(e){try{if(this.setupGate.validateMessage(e),"CLIENT_SETUP"===e.type){const t=this.setupGate.handleClientSetup(e);this._peerMaxRequestId=t.peerMaxRequestId,t.peerMaxRequestId>0n&&this.requestIdAllocator.updatePeerMaxRequestId(t.peerMaxRequestId),void 0!==t.peerMaxAuthTokenCacheSize&&(this._peerMaxAuthTokenCacheSize=t.peerMaxAuthTokenCacheSize),this.initAuthCache(),t.authTokens&&this.processSetupAuthTokens(t.authTokens,!0),this._state=hi}else if("SERVER_SETUP"===e.type){const t=this.setupGate.handleServerSetup(e);this._peerMaxRequestId=t.peerMaxRequestId,t.peerMaxRequestId>0n&&this.requestIdAllocator.updatePeerMaxRequestId(t.peerMaxRequestId),void 0!==t.peerMaxAuthTokenCacheSize&&(this._peerMaxAuthTokenCacheSize=t.peerMaxAuthTokenCacheSize),this.initAuthCache(),t.authTokens&&this.processSetupAuthTokens(t.authTokens,!1),this._state=li}return[]}catch(e){if(e instanceof Ni){const t=this.mapSetupErrorCode(e.code);return this.closeWithError(t,e.message)}if(e instanceof Ii){const t="PROTOCOL_VIOLATION"===e.code?X.PROTOCOL_VIOLATION:X.INVALID_REQUEST_ID;return this.closeWithError(t,e.message)}if(e instanceof Bi)return this.closeWithError(e.sessionErrorCode,e.message);throw e}}mapSetupErrorCode(e){switch(e){case"INVALID_PATH":return X.INVALID_PATH;case"MALFORMED_PATH":return X.MALFORMED_PATH;case"INVALID_AUTHORITY":return X.INVALID_AUTHORITY;case"MALFORMED_AUTHORITY":return X.MALFORMED_AUTHORITY;case"KEY_VALUE_FORMATTING_ERROR":return X.KEY_VALUE_FORMATTING_ERROR;case"VERSION_NEGOTIATION_FAILED":return X.VERSION_NEGOTIATION_FAILED;default:return X.PROTOCOL_VIOLATION}}initAuthCache(){this.authCache=new xi(this._ownMaxAuthTokenCacheSize)}processSetupAuthTokens(e,t){if(this.authCache)for(const i of e)this.processOneToken(i,t)}processOneToken(e,t){if(this.authCache)switch(e.aliasType){case ki.DELETE:{const t=e;return void this.authCache.delete(t.tokenAlias)}case ki.REGISTER:{const i=e,s=this.authCache.register(i.tokenAlias,i.tokenType,i.tokenValue,t);return null===s?{tokenType:i.tokenType,tokenValue:i.tokenValue}:s}case ki.USE_ALIAS:{const t=e;return this.authCache.resolve(t.tokenAlias)}case ki.USE_VALUE:{const t=e;return{tokenType:t.tokenType,tokenValue:t.tokenValue}}default:return}}processMessageAuthTokens(e){if(!this.authCache)return;const t=[];for(const i of e){if(!(i instanceof Uint8Array))continue;let e;try{e=Oi(i)}catch{return{error:X.KEY_VALUE_FORMATTING_ERROR,reason:"Malformed AUTHORIZATION_TOKEN structure"}}try{const i=this.processOneToken(e,!1);i&&t.push(i)}catch(e){if(e instanceof Bi)return{error:e.sessionErrorCode,reason:e.message};throw e}}for(let e=0;e0?this.closeWithError(X.PROTOCOL_VIOLATION,"Server received GOAWAY with non-empty New Session URI"):(this._goawayReceived=!0,this._newSessionUri=e.newSessionUri,this._state=ui,[])}handleMaxRequestId(e){try{return this.requestIdAllocator.updatePeerMaxRequestId(e.maxRequestId),this._peerMaxRequestId=e.maxRequestId,[]}catch(e){if(e instanceof Ii)return this.closeWithError(X.PROTOCOL_VIOLATION,e.message);throw e}}handleRequestsBlocked(e){return this.maybeReplenishMaxRequestId(!0)}validateAndReplenish(e){try{this.requestIdAllocator.validateIncoming(e)}catch(e){if(e instanceof Ii){const t="TOO_MANY_REQUESTS"===e.code?X.TOO_MANY_REQUESTS:X.INVALID_REQUEST_ID;return{error:this.closeWithError(t,e.message)}}throw e}const t=this.maybeReplenishMaxRequestId();return t.length>0?{replenish:t}:{}}maybeReplenishMaxRequestId(e=!1){if(!e&&!this.requestIdAllocator.shouldReplenish())return[];if(0n===this.requestIdAllocator.getOurMaxRequestId())return[];const t=this.requestIdAllocator.nextReplenishValue();return this.requestIdAllocator.commitReplenish(),[{type:"send_control",message:{type:"MAX_REQUEST_ID",maxRequestId:t}}]}handleSubscribeOk(e){const t=this.subscriptions.get(e.requestId);if(!t)return this.closeWithError(X.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for SUBSCRIBE_OK`);t.handleSubscribeOk(e.trackAlias);const i=this.subscriptionTracks.get(e.requestId);if(i)try{this.trackAliases.register(e.trackAlias,i.namespace,i.name)}catch{return this.closeWithError(X.DUPLICATE_TRACK_ALIAS,`Duplicate track alias ${e.trackAlias}`)}return[]}handleRequestError(e){if(this.pendingUpdates.get(e.requestId))return this.pendingUpdates.delete(e.requestId),[];if(this.pendingTrackStatuses.get(e.requestId))return this.pendingTrackStatuses.delete(e.requestId),[];const t=this.subscriptions.get(e.requestId);if(t)return t.handleRequestError(e.errorCode,e.errorReason),[];const i=this.fetches.get(e.requestId);if(i)return i.handleRequestError(e.errorCode,e.errorReason),[];const s=this.namespaceSubscriptions.get(e.requestId);if(s)return s.handleRequestError(e.errorCode,e.errorReason),[];const n=this.publishedNamespaces.get(e.requestId);return n&&"pending"===n.state?(this.publishedNamespaces.delete(e.requestId),[]):this.closeWithError(X.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for REQUEST_ERROR`)}handleFetchOk(e){const t=this.fetches.get(e.requestId);if(!t)return this.closeWithError(X.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for FETCH_OK`);if(e.endLocation&&void 0!==t.startGroup){const i=e.endLocation.group,s=e.endLocation.object,n=t.startGroup,r=t.startObject??0n;if(i0&&i){const e=n[0];"bigint"==typeof e&&i.updateForwardState(0n===e?bi:Si)}if(14===this._draftVersion)return t.replenish??[];const r={type:"REQUEST_OK",requestId:e.requestId,parameters:new Map};return[this.sendControl(r),...t.replenish??[]]}handleIncomingTrackStatus(e){const t=this.validateAndReplenish(e.requestId);return t.error?t.error:(this.incomingTrackStatuses.set(e.requestId,{namespace:e.trackNamespace,name:e.trackName}),t.replenish??[])}subscribe(e,t,i={}){if(this.assertEstablishedOrDraining("subscribe"),this._state===ui)throw new Vi("Cannot create new subscriptions after GOAWAY; session is DRAINING",this._newSessionUri??"");const s=this.requestIdAllocator.allocate(),n=Li.createAsSubscriber(s,e,t);this.subscriptions.set(s,n),this.subscriptionTracks.set(s,{namespace:e,name:t});const r=new Map;if(void 0!==i.deliveryTimeout&&r.set(ke.DELIVERY_TIMEOUT,[i.deliveryTimeout]),void 0!==i.subscriberPriority&&(r.set(ke.SUBSCRIBER_PRIORITY,[i.subscriberPriority]),n.currentPriority=i.subscriberPriority),void 0!==i.groupOrder&&r.set(ke.GROUP_ORDER,[i.groupOrder]),void 0!==i.subscriptionFilter){const e=this.encodeSubscriptionFilter(i.subscriptionFilter);r.set(ke.SUBSCRIPTION_FILTER,[e]),n.currentFilter=e}const a={type:"SUBSCRIBE",requestId:s,trackNamespace:e,trackName:t,parameters:r};return{requestId:s,actions:[this.sendControl(a)]}}getSubscription(e){return this.subscriptions.get(e)}unsubscribe(e){const t=this.subscriptions.get(e);if(!t)throw new Fi(`Unknown subscription ${e} for unsubscribe`,"INVALID_STATE");t.sendUnsubscribe(),void 0!==t.trackAlias&&this.trackAliases.unregister(t.trackAlias);const i={type:"UNSUBSCRIBE",requestId:e};return[this.sendControl(i)]}requestUpdate(e,t={}){this.assertEstablishedOrDraining("requestUpdate");const i=this.subscriptions.get(e);if(!i)throw new Fi(`Unknown subscription ${e} for REQUEST_UPDATE`,"INVALID_STATE");if("established"!==i.state)throw new Fi(`Cannot update subscription in state ${i.state}; expected established`,"INVALID_STATE");const s=this.requestIdAllocator.allocate(),n=new Map;if(void 0!==t.forward)n.set(ke.FORWARD,[K(BigInt(t.forward))]);else if(14===this._draftVersion){const e=K(BigInt(i.forwardState));n.set(ke.FORWARD,[e])}if(void 0!==t.subscriberPriority?(n.set(ke.SUBSCRIBER_PRIORITY,[t.subscriberPriority]),i.currentPriority=t.subscriberPriority):14===this._draftVersion&&void 0!==i.currentPriority&&n.set(ke.SUBSCRIBER_PRIORITY,[i.currentPriority]),void 0!==t.subscriptionFilter){const e=this.encodeSubscriptionFilter(t.subscriptionFilter);n.set(ke.SUBSCRIPTION_FILTER,[e]),i.currentFilter=e}else 14===this._draftVersion&&i.currentFilter&&n.set(ke.SUBSCRIPTION_FILTER,[i.currentFilter]);if(14===this._draftVersion)void 0!==t.forward&&i.updateForwardState(t.forward);else{const i={existingRequestId:e};void 0!==t.forward&&(i.forward=t.forward),this.pendingUpdates.set(s,i)}const r={type:"REQUEST_UPDATE",requestId:s,existingRequestId:e,parameters:n};return{requestId:s,actions:[this.sendControl(r)]}}fetch(e,t,i){if(this.assertEstablishedOrDraining("fetch"),this._state===ui)throw new Vi("Cannot create new fetches after GOAWAY; session is DRAINING",this._newSessionUri??"");const s=this.requestIdAllocator.allocate(),n=Ui.createAsFetcher(s,i.startGroup,i.startObject,i.endGroup,i.endObject);this.fetches.set(s,n);const r={group:i.startGroup,object:i.startObject},a={group:i.endGroup??K(0n),object:i.endObject??K(0n)};if(a.group1)return{error:X.PROTOCOL_VIOLATION,reason:`Duplicate message parameter type: ${i}`};if(i===ke.AUTHORIZATION_TOKEN){const e=this.processMessageAuthTokens(s);if(e)return e;continue}for(const e of s){const s=this.validateParamValue(i,e,t);if(s)return s}}}}validateParamValue(e,t,i){if("bigint"==typeof t){switch(e){case ke.DELIVERY_TIMEOUT:if(0n===t&&14!==this._draftVersion)return{error:X.PROTOCOL_VIOLATION,reason:"DELIVERY_TIMEOUT must be greater than 0"};break;case ke.FORWARD:if(0n!==t&&1n!==t)return{error:X.PROTOCOL_VIOLATION,reason:`FORWARD must be 0 or 1, got ${t}`};break;case ke.SUBSCRIBER_PRIORITY:if(t<0n||t>255n)return{error:X.PROTOCOL_VIOLATION,reason:`SUBSCRIBER_PRIORITY must be 0-255, got ${t}`};break;case ke.GROUP_ORDER:if(14!==this._draftVersion||"SUBSCRIBE"!==i&&"FETCH"!==i){if(0x1n!==t&&0x2n!==t)return{error:X.PROTOCOL_VIOLATION,reason:`GROUP_ORDER must be Ascending (0x1) or Descending (0x2), got ${t}`}}else if(t>0x2n)return{error:X.PROTOCOL_VIOLATION,reason:`GROUP_ORDER must be 0x0-0x2, got ${t}`}}return}const s=t;switch(e){case ke.LARGEST_OBJECT:return this.validateLargestObject(s);case ke.SUBSCRIPTION_FILTER:return this.validateSubscriptionFilter(s)}}validateLargestObject(e){try{const{bytesRead:t}=be(e,0);if(t!==e.length)return{error:X.KEY_VALUE_FORMATTING_ERROR,reason:`LARGEST_OBJECT has ${e.length-t} trailing bytes after Location`}}catch{return{error:X.KEY_VALUE_FORMATTING_ERROR,reason:"LARGEST_OBJECT is not a valid Location structure"}}}encodeSubscriptionFilter(e){const t={NextGroupStart:K(0x1n),LargestObject:K(0x2n),LatestObject:K(0x2n),AbsoluteStart:K(0x3n),AbsoluteRange:K(0x4n)}[e.type];let i=z(t);"AbsoluteStart"!==e.type&&"AbsoluteRange"!==e.type||(i+=z(e.startGroup),i+=z(e.startObject)),"AbsoluteRange"===e.type&&(i+=z(e.endGroup));const s=new Uint8Array(i);let n=J(t,s,0);return"AbsoluteStart"!==e.type&&"AbsoluteRange"!==e.type||(n+=J(e.startGroup,s,n),n+=J(e.startObject,s,n)),"AbsoluteRange"===e.type&&J(e.endGroup,s,n),s}validateSubscriptionFilter(e){if(0===e.length)return{error:X.PROTOCOL_VIOLATION,reason:"SUBSCRIPTION_FILTER is empty"};let t,i,s,n=0;try{const{value:i,bytesRead:s}=Y(e,n);t=i,n+=s}catch{return{error:X.PROTOCOL_VIOLATION,reason:"SUBSCRIPTION_FILTER has malformed Filter Type varint"}}if(t<1n||t>4n)return{error:X.PROTOCOL_VIOLATION,reason:`SUBSCRIPTION_FILTER has unknown Filter Type ${t}`};if(1n===t||2n===t)return n!==e.length?{error:X.PROTOCOL_VIOLATION,reason:`SUBSCRIPTION_FILTER length mismatch: ${e.length-n} trailing bytes for Filter Type ${t}`}:void 0;try{const{value:t,bytesRead:s}=be(e,n);i=t.group,n+=s}catch{return{error:X.PROTOCOL_VIOLATION,reason:"SUBSCRIPTION_FILTER has malformed Start Location"}}if(3n===t)return n!==e.length?{error:X.PROTOCOL_VIOLATION,reason:`SUBSCRIPTION_FILTER length mismatch: ${e.length-n} trailing bytes for AbsoluteStart`}:void 0;try{const{value:t,bytesRead:i}=Y(e,n);s=t,n+=i}catch{return{error:X.PROTOCOL_VIOLATION,reason:"SUBSCRIPTION_FILTER has malformed End Group varint for AbsoluteRange"}}return n!==e.length?{error:X.PROTOCOL_VIOLATION,reason:`SUBSCRIPTION_FILTER length mismatch: ${e.length-n} trailing bytes for AbsoluteRange`}:s0&&t.set(K(ke.FORWARD),[...i]),14===this._draftVersion){const i=e.get(K(ke.GROUP_ORDER));i&&i.length>0?t.set(K(ke.GROUP_ORDER),[...i]):t.set(K(ke.GROUP_ORDER),[K(1n)])}return t}}class Gi{buffer=new Uint8Array(0);codec;constructor(e){this.codec=e??yt()}push(e){if(0!==e.length)if(0===this.buffer.length)this.buffer=e;else{const t=new Uint8Array(this.buffer.length+e.length);t.set(this.buffer,0),t.set(e,this.buffer.length),this.buffer=t}}drain(){const e=[];for(;this.buffer.length>0;){const t=this.peekFrameSize();if(void 0===t)break;if(this.buffer.length{this.rawAliasMaps.delete(a.trackAlias),this.rawSubscriptions.delete(r),await this.unsubscribe(n)}};return new Promise((e,t)=>{const i={requestId:r,trackAlias:null,sub:a,resolve:e,reject:t};this.rawSubscriptions.set(r,i)})}routeToTrackSubscription(e){const t=BigInt(e.trackAlias),i=this.rawAliasMaps.get(t);return!!i&&(i.sub.onObject?.(e),!0)}handleRawSubControlMessage(e){if("SUBSCRIBE_OK"===e.type&&"requestId"in e&&"trackAlias"in e){const t=BigInt(e.requestId),i=this.rawSubscriptions.get(t);if(i){const t=BigInt(e.trackAlias);return i.trackAlias=t,i.sub.trackAlias=t,this.rawAliasMaps.set(t,i),i.resolve?.(i.sub),i.resolve=null,i.reject=null,!0}}if("REQUEST_ERROR"===e.type&&"requestId"in e){const t=BigInt(e.requestId),i=this.rawSubscriptions.get(t);if(i){const s=e;return i.reject?.(new Error(`Subscribe failed: ${s.errorReason} (${s.errorCode})`)),i.resolve=null,i.reject=null,this.rawSubscriptions.delete(t),!0}}return!1}async requestUpdate(e,t){const{requestId:i,actions:s}=this.session.requestUpdate(e,t);return await this.executeActions(s),i}async unsubscribe(e){const t=this.session.unsubscribe(e);await this.executeActions(t)}async close(e,t){const i=this.session.close(e,t);await this.executeActions(i)}async subscribeNamespace(e,t){const{requestId:i,actions:s}=this.session.subscribeNamespace(e,t);return await this.executeActions(s),i}async cancelNamespace(e){if(14===this.codec.version){const t=this.session.cancelNamespace(e);return void await this.executeActions(t)}const t=this.namespaceStreams.get(e);if(t){try{await t.close()}catch{}this.namespaceStreams.delete(e)}}async fetch(e,t,i){const{requestId:s,actions:n}=this.session.fetch(e,t,i);return await this.executeActions(n),s}async fetchCancel(e){const t=this.session.fetchCancel(e);await this.executeActions(t);const i=this.fetchStreams.get(e);if(void 0!==i){const t=this.dataStreamReaders.get(i);if(t){try{await t.cancel(new Error("FETCH_CANCEL"))}catch{}this.dataStreamReaders.delete(i)}this.fetchStreams.delete(e)}}async trackStatus(e,t){const{requestId:i,actions:s}=this.session.trackStatus(e,t);return await this.executeActions(s),i}async stopSending(e,t){await this.executeActions([{type:"stop_sending",streamId:e,error:t}])}async publishNamespace(e){const{requestId:t,actions:i}=this.session.publishNamespace(e);return await this.executeActions(i),t}async publishNamespaceDone(e){const t=this.session.publishNamespaceDone(e);await this.executeActions(t)}async acceptSubscribe(e,t){const i=this.session.acceptSubscribe(e,t);await this.executeActions(i)}async rejectSubscribe(e,t,i){const s=this.session.rejectSubscribe(e,t,i);await this.executeActions(s)}async publishDone(e,t,i){const s=this.session.publishDone(e,t,i);await this.executeActions(s)}async openSubgroup(e,t,i,s){if(!this.transport?.createUnidirectionalStream)throw new ji("Transport does not support createUnidirectionalStream",{errorSource:"transport"});let n;try{n=await this.transport.createUnidirectionalStream()}catch(e){throw new ji(`Failed to open unidirectional stream for group ${t}: ${e.message??e}. The relay may not be granting enough stream credits (MAX_STREAMS / WT_MAX_STREAMS).`,{errorSource:"transport",isFatal:!1,...e instanceof Error?{cause:e}:{}})}const r=n.getWriter();let a=kt;a|=(s?.subgroupIdMode??Pt)<<1,s?.hasExtensions&&(a|=Rt),s?.endOfGroup&&(a|=At),s?.defaultPriority&&(a|=Ot);const o=function(e){let t=z(K(e.typeByte));t+=z(e.trackAlias),t+=z(e.groupId);const i=(e.typeByte&It)>>1;i===Pt&&(t+=z(e.subgroupId)),void 0!==e.publisherPriority&&(t+=1);const s=new Uint8Array(t);let n=0;return n+=J(K(e.typeByte),s,n),n+=J(e.trackAlias,s,n),n+=J(e.groupId,s,n),i===Pt&&(n+=J(e.subgroupId,s,n)),void 0!==e.publisherPriority&&(s[n++]=e.publisherPriority),s}({typeByte:a,trackAlias:e,groupId:t,subgroupId:i,publisherPriority:s?.defaultPriority?void 0:s?.publisherPriority??128,hasExtensions:s?.hasExtensions??!1,isEndOfGroup:s?.endOfGroup??!1});await r.write(o);const c=this.nextOutgoingStreamId++;return this.outgoingStreams.set(c,{writer:r,hasExtensions:s?.hasExtensions??!1,previousObjectId:0n,isFirstObject:!0}),c}async sendObject(e,t,i,s){const n=this.outgoingStreams.get(e);if(!n)throw new ji(`Unknown outgoing stream ${e}`,{errorSource:"data"});const r=function(e,t,i,s=!0){if(void 0!==e.status&&e.payload.length>0)throw new Error(`SubgroupObject: status (0x${e.status.toString(16)}) is only valid on empty payloads; got payload.length=${e.payload.length}`);let n;n=s?e.objectId:K(e.objectId-i-1n);let r=z(n);if(t){const t=e.extensions?.length??0;r+=z(K(t)),r+=t}const a=e.payload.length;r+=z(K(a));const o=0===a?e.status??Ct.NORMAL:e.status;r+=0===a&&void 0!==o?z(o):a;const c=new Uint8Array(r);let d=0;if(d+=J(n,c,d),t){const t=e.extensions?.length??0;d+=J(K(t),c,d),t>0&&e.extensions&&(c.set(e.extensions,d),d+=t)}return d+=J(K(a),c,d),0===a&&void 0!==o?d+=J(o,c,d):a>0&&(c.set(e.payload,d),d+=a),c}({objectId:t,extensions:s,payload:i,status:void 0},n.hasExtensions,K(n.previousObjectId),n.isFirstObject);await n.writer.write(r),n.previousObjectId=t,n.isFirstObject=!1}async closeSubgroup(e){const t=this.outgoingStreams.get(e);if(t){try{await t.writer.close()}catch{}this.outgoingStreams.delete(e)}}async executeActions(e){for(const t of e)switch(t.type){case"send_control":{const e=this.codec.encode(t.message);this.onQlogEvent?.({type:"control_message_created",stream_id:Wi.CONTROL_STREAM_QLOG_ID,length:e.byteLength,message:t.message}),await this.controlWriter.write(e);break}case"close_connection":this.transport?.close({closeCode:Number(t.error),reason:t.reason});break;case"open_namespace_stream":this.openNamespaceStream(t.requestId,t.message);break;case"stop_sending":{const e=this.dataStreamReaders.get(t.streamId);if(e){try{await e.cancel(new Error(`STOP_SENDING: ${t.error}`))}catch{}this.dataStreamReaders.delete(t.streamId)}break}case"notify_namespace":this.onNamespaceMessage?.(t.requestId,t.message);break;case"close_stream":case"reset_stream":case"open_data_stream":case"send_object":this.onError?.(new ji(`Unhandled session action type: "${t.type}"`,{errorSource:"control"}))}}async runControlReadLoop(e){try{for(;;){const{value:t,done:i}=await e.read();if(i){const e=this.session.close(X.PROTOCOL_VIOLATION,"Control stream closed unexpectedly");await this.executeActions(e),this.onClose?.(3,"Control stream closed unexpectedly");break}let s;this.framer.push(t);try{s=this.framer.drain()}catch(e){const t=e instanceof Error?e.message:String(e),i=this.session.close(X.PROTOCOL_VIOLATION,`Malformed control message: ${t}`);return await this.executeActions(i),void this.onClose?.(3,`Malformed control message: ${t}`)}for(const{message:e}of s){this.onQlogEvent?.({type:"control_message_parsed",stream_id:Wi.CONTROL_STREAM_QLOG_ID,message:e});this.handleRawSubControlMessage(e)||this.onMessage?.(e);const t=this.session.handleControlMessage(e);if(await this.executeActions(t),"SUBSCRIBE"===e.type&&this.onSubscribe){const t=e;this.onSubscribe(t.requestId,t.trackNamespace,t.trackName,t.parameters)}}}}catch(e){this.onError?.(new ji(e instanceof Error?e.message:String(e),{errorSource:"control",...e instanceof Error?{cause:e}:{}}))}}async runIncomingStreamLoop(e){try{const t=e.incomingUnidirectionalStreams.getReader();for(;;){const{value:e,done:i}=await t.read();if(i)break;const s=this.nextStreamId++;this.processDataStream(e,s)}}catch(e){this.onError?.(new ji(e instanceof Error?e.message:String(e),{errorSource:"transport",...e instanceof Error?{cause:e}:{}}))}}async runDatagramLoop(e){try{const t=e.datagrams.readable.getReader();for(;;){const{value:e,done:i}=await t.read();if(i)break;try{const{datagram:t}=ci(e,0,this.codec.version);this.onQlogEvent?.({type:"object_datagram_parsed",track_alias:t.trackAlias,group_id:t.groupId,object_id:t.objectId,...void 0!==t.publisherPriority?{publisher_priority:t.publisherPriority}:{},...t.extensions?{extension_headers_length:t.extensions.byteLength}:{},...void 0!==t.status?{object_status:t.status}:{},...t.payload.byteLength>0?{object_payload:{payload_length:t.payload.byteLength}}:{},end_of_group:t.isEndOfGroup}),this.onDatagram?.(t)}catch(e){if(e instanceof te){const t=this.session.close(X.PROTOCOL_VIOLATION,e.message);return await this.executeActions(t),void this.onClose?.(3,e.message)}if(!(e instanceof RangeError)){const t=e instanceof Error?e.message:String(e);this.onError?.(new ji(t,{errorSource:"datagram",...e instanceof Error?{cause:e}:{}}))}}}}catch(e){this.onError?.(new ji(e instanceof Error?e.message:String(e),{errorSource:"transport",...e instanceof Error?{cause:e}:{}}))}}async processDataStream(e,t){const i=e.getReader();this.dataStreamReaders.set(t,i);let s=new Uint8Array(0);try{const e=await this.readStreamHeader(i,s);if(!e)return void this.onStreamClosed?.(t);if(s=e.remaining,"subgroup"===e.type){const n=e.header;this.onQlogEvent?.({type:"stream_type_set",owner:"remote",stream_id:t,stream_type:"subgroup_header"}),this.onQlogEvent?.({type:"subgroup_header_parsed",stream_id:t,track_alias:n.trackAlias,group_id:n.groupId,subgroup_id_mode:Xt(n.typeByte),...void 0!==n.subgroupId?{subgroup_id:n.subgroupId}:{},...void 0!==n.publisherPriority?{publisher_priority:n.publisherPriority}:{},contains_end_of_group:n.isEndOfGroup,extensions_present:n.hasExtensions}),this.onDataStream?.(t,{type:"subgroup",header:n}),await this.readSubgroupObjects(i,s,t,n)}else{const n=e.header;this.fetchStreams.set(n.requestId,t),this.onQlogEvent?.({type:"stream_type_set",owner:"remote",stream_id:t,stream_type:"fetch_header"}),this.onQlogEvent?.({type:"fetch_header_parsed",stream_id:t,request_id:n.requestId}),this.onDataStream?.(t,{type:"fetch",header:n}),await this.readFetchObjects(i,s,t)}this.onStreamClosed?.(t)}catch(e){if(e instanceof te){const t=this.session.close(X.PROTOCOL_VIOLATION,e.message);return await this.executeActions(t),void this.onClose?.(3,e.message)}const i="number"==typeof e?.streamErrorCode?e.streamErrorCode:void 0;void 0===i&&this.onError?.(new ji(e instanceof Error?e.message:String(e),{errorSource:"data",streamId:BigInt(t),...e instanceof Error?{cause:e}:{}})),this.onStreamClosed?.(t,i)}finally{this.dataStreamReaders.delete(t);for(const[e,i]of this.fetchStreams)if(i===t){this.fetchStreams.delete(e);break}}}async readStreamHeader(e,t){for(;;){if(t.length>0){const e=t[0];if(Jt(e,this.codec.version))try{const{header:e,bytesRead:i}=ii(t,0,this.codec.version);return{type:"subgroup",header:e,remaining:t.subarray(i)}}catch(e){if(!(e instanceof RangeError))throw e}else{if(e!==wt)throw new te(`Unknown data stream type byte 0x${e.toString(16)} — expected SUBGROUP_HEADER (0x10–0x3D) or FETCH_HEADER (0x05)`);try{const{header:e,bytesRead:i}=ni(t,0);return{type:"fetch",header:e,remaining:t.subarray(i)}}catch(e){if(!(e instanceof RangeError))throw e}}}const{value:i,done:s}=await e.read();if(s){if(t.length>0){const e=this.session.close(X.PROTOCOL_VIOLATION,"Stream FIN received mid-header (§10.4)");await this.executeActions(e),this.onClose?.(3,"Stream FIN received mid-header")}return}t=this.appendBuffer(t,i)}}async readSubgroupObjects(e,t,i,s){let n=K(0),r=!0;for(;;){if(t.length>0)try{const{object:e,bytesRead:a}=si(t,0,s.hasExtensions,n,r,this.codec.version);t=t.subarray(a),r&&Xt(s.typeByte)===Nt&&(s={...s,subgroupId:e.objectId});const o=0===e.payload.length&&void 0!==e.status?{kind:"gap",trackAlias:s.trackAlias,groupId:s.groupId,subgroupId:s.subgroupId,objectId:e.objectId,status:e.status}:{kind:"data",trackAlias:s.trackAlias,groupId:s.groupId,subgroupId:s.subgroupId,objectId:e.objectId,publisherPriority:s.publisherPriority,extensions:e.extensions,payload:e.payload},c=r?e.objectId:e.objectId-n-1n;this.onQlogEvent?.({type:"subgroup_object_parsed",stream_id:i,object_id_delta:c,object_payload_length:e.payload.byteLength,...e.extensions&&e.extensions.byteLength>0?{extension_headers:[]}:{},...void 0!==e.status?{object_status:e.status}:{}}),this.routeToTrackSubscription(o)||this.onObject?.(i,o),n=e.objectId,r=!1;continue}catch(e){if(!(e instanceof RangeError))throw e}const{value:a,done:o}=await e.read();if(o){if(t.length>0){const e=this.session.close(X.PROTOCOL_VIOLATION,"Stream FIN received mid-object (§10.4)");return await this.executeActions(e),void this.onClose?.(3,"Stream FIN received mid-object")}if(s.isEndOfGroup){const e={kind:"gap",trackAlias:s.trackAlias,groupId:s.groupId,subgroupId:s.subgroupId,objectId:K(n+1n),status:Ct.END_OF_GROUP};this.routeToTrackSubscription(e)||this.onObject?.(i,e)}return}t=this.appendBuffer(t,a)}}async readFetchObjects(e,t,i){let s,n=!0;for(;;){if(t.length>0)try{const{item:e,bytesRead:r}=14===this.codec.version?oi(t,0):ai(t,0,s,n);if(t=t.subarray(r),"payload"in e){this.onQlogEvent?.({type:"fetch_object_parsed",stream_id:i,datagram:e.isDatagram??!1,end_of_nonexistent_range:!1,end_of_unknown_range:!1,...void 0!==e.groupId?{group_id:e.groupId}:{},...void 0!==e.subgroupId?{subgroup_id:e.subgroupId}:{},...void 0!==e.objectId?{object_id:e.objectId}:{},...void 0!==e.publisherPriority?{publisher_priority:e.publisherPriority}:{},...e.extensions?{extension_headers_length:e.extensions.byteLength}:{},object_payload_length:e.payload.byteLength});const t={kind:"data",trackAlias:K(0),groupId:e.groupId,subgroupId:e.subgroupId,objectId:e.objectId,publisherPriority:e.publisherPriority,extensions:e.extensions,payload:e.payload};this.routeToTrackSubscription(t)||this.onObject?.(i,t),s={groupId:e.groupId,subgroupId:e.subgroupId,objectId:e.objectId,...void 0!==e.publisherPriority?{priority:e.publisherPriority}:{}}}else{const t=e.rawStatus??K(e.nonExistent?3:0),s={kind:"gap",trackAlias:K(0),groupId:e.groupId,subgroupId:K(0),objectId:e.objectId,status:t};this.routeToTrackSubscription(s)||this.onObject?.(i,s)}n=!1;continue}catch(e){if(!(e instanceof RangeError))throw e}const{value:r,done:a}=await e.read();if(a){if(t.length>0){const e=this.session.close(X.PROTOCOL_VIOLATION,"Fetch stream FIN received mid-object (§10.4)");await this.executeActions(e),this.onClose?.(3,"Fetch stream FIN received mid-object")}return}t=this.appendBuffer(t,r)}}async openNamespaceStream(e,t){try{const i=await this.transport.createBidirectionalStream(),s=i.writable.getWriter();this.namespaceStreams.set(e,s);const n=this.codec.encode(t);await s.write(n);const r=i.readable.getReader();this.runNamespaceStreamReadLoop(r,e)}catch(e){this.onError?.(new ji(e instanceof Error?e.message:String(e),{errorSource:"control",...e instanceof Error?{cause:e}:{}}))}}async runNamespaceStreamReadLoop(e,t){const i=new Gi(this.codec);try{for(;;){const{value:s,done:n}=await e.read();if(n)break;i.push(s);const r=i.drain();for(const{message:e}of r){this.onNamespaceMessage?.(t,e);const i=this.session.handleNamespaceStreamMessage(t,e);await this.executeActions(i)}}}catch(e){this.onError?.(new ji(e instanceof Error?e.message:String(e),{errorSource:"control",...e instanceof Error?{cause:e}:{}}))}finally{this.namespaceStreams.delete(t)}}appendBuffer(e,t){if(0===e.length)return t;const i=new Uint8Array(e.length+t.length);return i.set(e,0),i.set(t,e.length),i}}function Qi(e,t){return e.groupIdt.groupId?1:e.objectIdt.objectId?1:0}class Ki{heap=[];maxDepth;constructor(e){this.maxDepth=e}get size(){return this.heap.length}insert(e){return!(this.heap.length>=this.maxDepth)&&(this.heap.push(e),this.bubbleUp(this.heap.length-1),!0)}peek(){return this.heap[0]}extract(){if(0===this.heap.length)return;const e=this.heap[0],t=this.heap.pop();return this.heap.length>0&&(this.heap[0]=t,this.sinkDown(0)),e}hasContiguous(e,t){if(0===this.heap.length)return!1;const i=this.heap[0];return i.groupId===e&&i.objectId===t}drainGroup(e){const t=[],i=[];for(const s of this.heap)s.groupId===e?t.push(s):i.push(s);t.sort(Qi),this.heap.length=0;for(const e of i)this.heap.push(e);return this.rebuild(),t}discardBefore(e){const t=[];let i=0;for(const s of this.heap)s.groupIdt||r===t&&n.groupId0;){const t=e-1>>1;if(Qi(this.heap[e],this.heap[t])>=0)break;this.swap(e,t),e=t}}sinkDown(e){const t=this.heap.length;for(;;){let i=e;const s=2*e+1,n=2*e+2;if(s>1)-1;e>=0;e--)this.sinkDown(e)}}const zi="wait",Yi="skip_forward",Ji="track_ended";class Xi{_gapTimeoutUs;clock;endedGroups=new Set;trackEnded=!1;groupFirstSeenUs=new Map;constructor(e){this._gapTimeoutUs=e.gapTimeoutUs,this.clock=e.clock}get gapTimeoutUs(){return this._gapTimeoutUs}set gapTimeoutUs(e){this._gapTimeoutUs=e}observeGroup(e){this.groupFirstSeenUs.has(e)||this.groupFirstSeenUs.set(e,this.clock.now())}observeEndOfGroup(e){this.endedGroups.add(e)}observeEndOfTrack(){this.trackEnded=!0}get isTrackEnded(){return this.trackEnded}reset(){this.endedGroups.clear(),this.trackEnded=!1,this.groupFirstSeenUs.clear()}evaluate(e,t){if(this.trackEnded)return{action:Ji};if(0===t.length)return{action:zi};const i=e+1n,s=[...t].sort((e,t)=>et?1:0),n=s[0];if(n<=i)return{action:zi};let r=!0;for(let e=i;e=this.gapTimeoutUs)return{action:Yi,targetGroupId:n}}return{action:zi}}}const Zi="idle",es="needs_keyframe",ts="decoding",is="ended";class ss{_state=Zi;_mediaType;lastConfig=null;constructor(e){this._mediaType=e}get state(){return this._state}get mediaType(){return this._mediaType}configure(e){return null!==this.lastConfig&&this.configEquals(this.lastConfig,e)?{action:"skip",reason:"config unchanged"}:(this.lastConfig=e,"audio"===this._mediaType?this._state=ts:this._state=es,{action:"configure",config:e})}configEquals(e,t){if(e.length!==t.length)return!1;for(let i=0;i1e3*Date.now()};class rs{_driftThresholdUs;dropThresholdUs;clock;localBaselineUs;captureBaselineUs;_currentDriftUs=0;_videoJoinOffsetUs=0;wallClock;targetLatencyMs;maxCatchUpRate;catchUpThresholdMs;catchUpRecoveryMs;_catchUpActive=!1;_currentRate=1;_lastLatencyUs=0;constructor(e){this._driftThresholdUs=e.driftThresholdUs,this.dropThresholdUs=e.dropThresholdUs??5e5,this.clock=e.clock,this.wallClock=e.wallClock??ns,this.targetLatencyMs=e.targetLatencyMs,this.maxCatchUpRate=e.maxCatchUpRate??1,this.catchUpThresholdMs=e.catchUpThresholdMs??500,this.catchUpRecoveryMs=e.catchUpRecoveryMs??50}get hasReference(){return void 0!==this.localBaselineUs}get currentDriftUs(){return this._currentDriftUs}get driftThresholdUs(){return this._driftThresholdUs}set driftThresholdUs(e){this._driftThresholdUs=e}get needsResync(){return!(this._videoJoinOffsetUs>0)&&Math.abs(this._currentDriftUs)>=this._driftThresholdUs}get catchUpActive(){return this._catchUpActive}get currentRate(){return this._currentRate}get latencyUs(){return this._lastLatencyUs}setAudioReference(e){this.localBaselineUs=this.clock.now(),this.captureBaselineUs=e,this._currentDriftUs=0}setVideoReference(e){this.hasReference||(this.localBaselineUs=this.clock.now(),this.captureBaselineUs=e,this._currentDriftUs=0)}get videoJoinOffsetUs(){return this._videoJoinOffsetUs}onVideoJoin(e,t=16e3){if(void 0===this.localBaselineUs||void 0===this.captureBaselineUs)return;const i=this.localBaselineUs+Number(e-this.captureBaselineUs),s=this.clock.now()+t-i;s>0&&(this._videoJoinOffsetUs=s)}computeVideoRenderTime(e){const t=this.computeRenderTime(e);if(null===t)return null;if(this._videoJoinOffsetUs>0){const e=t.renderTimeUs+this._videoJoinOffsetUs,i=this.clock.now();if(t.renderTimeUs>i)return this._videoJoinOffsetUs=0,t;const s=e-i;return{renderTimeUs:e,offsetUs:s,shouldDrop:s<-this.dropThresholdUs}}return t}computeAudioRenderTime(e){return this.computeRenderTime(e)}reportActualRenderTime(e,t){if(void 0===this.localBaselineUs||void 0===this.captureBaselineUs)return;const i=this.localBaselineUs+Number(e-this.captureBaselineUs);this._currentDriftUs=t-i}measureLatency(e){return 0n===e?null:this.wallClock.now()-Number(e)}evaluateCatchUp(e){const t=this.measureLatency(e);if(null===t)return null;if(this._lastLatencyUs=t,void 0===this.targetLatencyMs||this.maxCatchUpRate<=1)return null;const i=t/1e3,s=this.targetLatencyMs;if(!this._catchUpActive&&i>s+this.catchUpThresholdMs)this._catchUpActive=!0;else if(this._catchUpActive&&i<=s+this.catchUpRecoveryMs)return this._catchUpActive=!1,this._currentRate=1,{active:!1,currentRate:1,latencyMs:i,targetMs:s};if(this._catchUpActive){const e=i-s,t=Math.min(Math.max(e/this.catchUpThresholdMs,0),1),n=1+(this.maxCatchUpRate-1)*t,r=Math.round(20*n)/20;this._currentRate=Math.min(Math.max(r,1),this.maxCatchUpRate)}return{active:this._catchUpActive,currentRate:this._currentRate,latencyMs:i,targetMs:s}}reset(){this.localBaselineUs=void 0,this.captureBaselineUs=void 0,this._currentDriftUs=0,this._videoJoinOffsetUs=0,this._catchUpActive=!1,this._currentRate=1}computeRenderTime(e){if(void 0===this.localBaselineUs||void 0===this.captureBaselineUs)return null;const t=this.clock.now(),i=this.localBaselineUs+Number(e-this.captureBaselineUs),s=i-t;return{renderTimeUs:i,offsetUs:s,shouldDrop:s<-this.dropThresholdUs}}}class as{gapEscalationThreshold;maxDecodeErrors;windowedThreshold;windowedWindowUs;stallThresholdMs;clock;consecutiveGaps=0;qualityReductionPending=!1;decodeErrorCount=0;gapTimestamps=[];constructor(e){this.gapEscalationThreshold=e?.gapEscalationThreshold??3,this.maxDecodeErrors=e?.maxDecodeErrors??2,this.windowedThreshold=e?.windowedEscalationThreshold??5,this.windowedWindowUs=1e3*(e?.windowedEscalationWindowMs??3e4),this.stallThresholdMs=e?.stallThresholdMs??300,this.clock=null}setClock(e){this.clock=e}evaluate(e){switch(e.type){case"gap":return this.handleGap();case"stall":return this.handleStall(e.durationMs);case"buffer_overflow":return this.escalateOrSkip("jitter buffer overflow");case"too_far_behind":return this.escalateOrSkip("server reported TOO_FAR_BEHIND");case"delivery_timeout":return{type:"resubscribe"};case"decode_error":return this.handleDecodeError(e.message)}}notifySuccess(){this.consecutiveGaps=0,this.qualityReductionPending=!1}reset(){this.consecutiveGaps=0,this.qualityReductionPending=!1,this.decodeErrorCount=0,this.gapTimestamps.length=0}escalateOrSkip(e){return this.qualityReductionPending?{type:"skip_forward"}:(this.qualityReductionPending=!0,{type:"reduce_quality",reason:e})}handleGap(){if(this.consecutiveGaps++,this.consecutiveGaps>=this.gapEscalationThreshold)return this.consecutiveGaps=0,this.gapTimestamps.length=0,this.escalateOrSkip("repeated gaps detected");if(this.clock){const e=this.clock.now();this.gapTimestamps.push(e);const t=e-this.windowedWindowUs;for(;this.gapTimestamps.length>0&&this.gapTimestamps[0]=this.windowedThreshold)return this.gapTimestamps.length=0,this.consecutiveGaps=0,this.escalateOrSkip("repeated stalls within window")}return{type:"skip_forward"}}handleStall(e){if(e0&&this.gapTimestamps[0]=this.windowedThreshold)return this.gapTimestamps.length=0,this.escalateOrSkip("sustained stalls within window")}return{type:"skip_forward"}}handleDecodeError(e){return this.decodeErrorCount++,this.decodeErrorCount>=this.maxDecodeErrors?{type:"terminate",reason:`repeated decode error: ${e}`}:{type:"resubscribe"}}}const os="normal",cs="monitoring",ds="extended_wait",hs={emaAlpha:.125,varianceAlpha:.25,slidingWindowSize:128,jitterMultiplier:4,minGapTimeoutMs:50,maxGapTimeoutMs:2e3,minDriftThresholdMs:80,driftThresholdMultiplier:3,stallIncrementMs:33,maxStallIncrements:3,monitorWindowMs:500,monitorCleanFrames:60,monitorCleanDurationMs:1e3,maxExtendedWaitMs:2e3,skipFrequencyThreshold:3,skipFrequencyWindowMs:3e4,decayMinCleanFrames:120,decayMinCleanDurationMs:2e3,decayFactor:.9},ls={shouldSkip:!1},us={shouldSkip:!0};class ps{buf;deq;capacity;writePos=0;count=0;dHead=0;dTail=0;constructor(e){this.capacity=e,this.buf=new Float64Array(e),this.deq=new Uint32Array(e)}push(e){const t=this.capacity,i=this.writePos%t;for(this.count===t&&this.dHead!==this.dTail&&this.deq[this.dHead%t]===i&&this.dHead++;this.dHead!==this.dTail&&this.buf[this.deq[(this.dTail-1)%t]%t]<=e;)this.dTail--;this.deq[this.dTail%t]=i,this.dTail++,this.buf[i]=e,this.writePos++,this.count0&&(t=Math.min(t,this._deliveryTimeoutMs)),t}get effectiveDriftThresholdMs(){return this._hasCaptureRef&&0!==this._captureJitterEma?Math.max(this.cfg.minDriftThresholdMs,this._captureJitterEma*this.cfg.driftThresholdMultiplier):this.cfg.minDriftThresholdMs}onFrameArrived(e,t,i){const s=i-.001*t;if(this._hasLastTransit){const e=s-this._lastTransitMs,t=e<0?-e:e,i=t-this._jitterEma;this._jitterEma+=this.cfg.emaAlpha*i,this._jitterVar+=this.cfg.varianceAlpha*(t-this._jitterVar),this._slidingMax.push(t)}if(this._lastTransitMs=s,this._hasLastTransit=!0,this._hasCaptureRef){const e=t-this._lastCaptureUs,i=.001*Math.abs(e);0===this._captureJitterEma?this._captureJitterEma=i:this._captureJitterEma+=this.cfg.emaAlpha*(i-this._captureJitterEma)}this._lastCaptureUs=t,this._hasCaptureRef=!0,this._cleanFrameCount++,1===this._cleanFrameCount&&(this._cleanStreakStartMs=e)}onGapDetected(e,t){switch(this._cleanFrameCount=0,this._phase){case os:this._phase=cs,this._phaseEnteredMs=e,this._monitorGapCount=1;break;case cs:this._monitorGapCount++,this._monitorGapCount>=2&&e-this._phaseEnteredMs<=this.cfg.monitorWindowMs&&(this._phase=ds,this._phaseEnteredMs=e)}}tick(e){switch(this._phase){case cs:if(e-this._phaseEnteredMs>this.cfg.monitorWindowMs&&this._cleanFrameCount>=this.cfg.monitorCleanFrames&&e-this._cleanStreakStartMs>=this.cfg.monitorCleanDurationMs)return this._phase=os,ls;break;case ds:if(e-this._phaseEnteredMs>=this.cfg.maxExtendedWaitMs)return this._stallCount++,this._stallEscalationMs=Math.min(this._stallCount*this.cfg.stallIncrementMs,this.cfg.maxStallIncrements*this.cfg.stallIncrementMs),this._skipTimestamps.push(e),this._pruneSkipTimestamps(e),this._skipTimestamps.length>=this.cfg.skipFrequencyThreshold&&(this._shouldReduceQuality=!0),this._phase=os,this._cleanFrameCount=0,us;break;case os:this._stallEscalationMs>0&&this._cleanFrameCount>=this.cfg.decayMinCleanFrames&&this._cleanStreakStartMs>0&&e-this._cleanStreakStartMs>=this.cfg.decayMinCleanDurationMs&&(this._stallEscalationMs*=this.cfg.decayFactor,this._stallEscalationMs<1&&(this._stallEscalationMs=0,this._stallCount=0),this._cleanFrameCount=0,this._cleanStreakStartMs=e),this._shouldReduceQuality&&(this._pruneSkipTimestamps(e),this._skipTimestamps.lengthe>=t)}}function gs(e,t){switch(e.split(".")[0].toLowerCase()){case"avc1":case"avc3":return function(e){if(e.length<5)return null;let t=0,i=0;for(;t+4fs)return null;const s=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];if(t+=4,s<=0||t>=e.length)break;const n=31&e[t];if(5===n)return!0;if(7===n)return!0;if(6!==n&&8!==n&&9!==n)return!1;t+=s}return null}(t);case"hvc1":case"hev1":return function(e){if(e.length<6)return null;let t=0,i=0;for(;t+4fs)return null;const s=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];if(t+=4,s<=0||t+1>=e.length)break;const n=e[t]>>1&63;if(19===n||20===n)return!0;if(21===n)return!0;if(32!==n&&33!==n&&34!==n){if(35!==n&&39!==n&&40!==n)return!1;t+=s}else t+=s}return null}(t);case"av01":return function(e){if(e.length<2)return null;const t=e[0]>>3&15;if(1===t)return!0;if(2===t&&e.length>=3){if(1===(e[2]>>3&15))return!0}return 3!==t&&6!==t&&null}(t);default:return null}}const fs=256;const _s=2,vs=4,bs=6,Ss=13;function Es(e){const t=Number(e),i=t>=256,s=i?t>>8&255:255&t,n={startOfFrame:!!(128&s),endOfFrame:!!(64&s),independent:!!(32&s),discardable:!!(16&s),baseLayerSync:!!(8&s),temporalId:7&s};return i&&(n.layerId=255&t),n}function ys(e){let t=0;if(e.startOfFrame&&(t|=128),e.endOfFrame&&(t|=64),e.independent&&(t|=32),e.discardable&&(t|=16),e.baseLayerSync&&(t|=8),t|=7&e.temporalId,void 0!==e.layerId){const i=255&e.layerId;return BigInt(t<<8|i)}return BigInt(t)}function Ts(e){const t=255&Number(e);return{voiceActivity:!!(128&t),level:127&t}}function Cs(e){let t=127&e.level;return e.voiceActivity&&(t|=128),BigInt(t)}function ws(e,t){const i=[];if(void 0!==e.captureTimestamp&&i.push({id:_s,value:e.captureTimestamp}),void 0!==e.videoFrameMarking&&i.push({id:vs,value:ys(e.videoFrameMarking)}),void 0!==e.audioLevel&&i.push({id:bs,value:Cs(e.audioLevel)}),void 0!==e.videoConfig&&i.push({id:Ss,value:e.videoConfig}),e.unknown)for(const[t,s]of e.unknown)i.push({id:t,value:s});if(0===i.length)return;const s=!1!==t?.deltaEncoded;i.sort((e,t)=>e.id-t.id);let n=0,r=0;for(const e of i){const t=s?e.id-r:e.id;r=e.id,n+=z(K(t)),e.id%2==0?n+=z(K(e.value)):n+=re(e.value)}const a=new Uint8Array(n);let o=0;r=0;for(const e of i){const t=s?e.id-r:e.id;r=e.id,o+=J(K(t),a,o),e.id%2==0?o+=J(K(e.value),a,o):o+=ne(e.value,a,o)}return a}class Rs{mediaType;clock;sync;onCommand;onEvent;recovery;buffer;gapDetector;decoderState;headerMap=new Map;bufferedGroupCounts=new Map;nextExpectedObjectId=0n;lastConsumedGroupId=-1n;endedGroups=new Set;activeGroupWaitStartUs=null;minAcceptGroupId=-1n;lastKeyframeWaitingGroupId=-1n;resetPending=!0;_trackEnded=!1;_lastEmittedRate=1;_throttled=!1;adaptiveTolerance;maxReleasePerTick;maxBacklogGroups;_videoCodec;_videoOnly;constructor(e){this.mediaType=e.mediaType,this.clock=e.clock,this.sync=e.sync,this.onCommand=e.onCommand,this.onEvent=e.onEvent,this.recovery=e.recovery,this._videoOnly=e.videoOnly??!1;const t="video"===e.mediaType&&(e.isLive??!0);this.maxReleasePerTick=t?e.config.maxReleasePerTick??5:0,this.maxBacklogGroups=t?e.config.maxBacklogGroups??3:0,this.buffer=new Ki(e.config.maxBufferDepth),this.gapDetector=new Xi({gapTimeoutUs:e.config.gapTimeoutUs,clock:e.clock}),this.decoderState=new ss(e.mediaType),this.adaptiveTolerance=e.config.adaptiveTolerance?new ms(hs):null}setCodec(e){this._videoCodec=e}get effectiveGapTimeoutUs(){return this.adaptiveTolerance?1e3*this.adaptiveTolerance.effectiveGapTimeoutMs:this.gapDetector.gapTimeoutUs}get currentGroupId(){return this.lastConsumedGroupId}get bufferedGroupCount(){return this.bufferedGroupCounts.size}get throttled(){return this._throttled}handleFeedback(e){switch(e.type){case"queue_pressure":this._throttled=e.depth>=e.maxRecommended;break;case"decode_error":this._throttled=!1;{const e=this.decoderState.notifyGap();this.emitFsmDecision(e)}if(this.recovery){const t=this.recovery.evaluate({type:"decode_error",message:e.message});this.onEvent({type:"recovery",action:t})}break;case"frame_rendered":if(e.captureTimestampUs>0n){this.sync.reportActualRenderTime(e.captureTimestampUs,e.actualRenderUs);const t=this.sync.currentDriftUs;this.sync.needsResync&&Math.abs(t)<5e6&&this.onEvent({type:"sync_drift",driftUs:t})}}}configure(e){"configure"===this.decoderState.configure(e).action&&this.onCommand({type:"configure",mediaType:this.mediaType,config:e})}pushObject(e,t){if("gap"===e.kind)return void(e.status===Ct.END_OF_GROUP?(this.gapDetector.observeEndOfGroup(e.groupId),this.endedGroups.add(e.groupId)):e.status===Ct.END_OF_TRACK&&this.gapDetector.observeEndOfTrack());if(e.groupId=0n&&e.groupId0){const e=this.buffer.peek();if(0n!==e.objectId)return this.buffer.extract(),void this.decrementGroupCount(e.groupId);this.lastConsumedGroupId=e.groupId-1n,this.endedGroups.add(this.lastConsumedGroupId),this.resetPending=!1}const e=[...this.bufferedGroupCounts.keys()],t=this.gapDetector.evaluate(this.lastConsumedGroupId,e);if(t.action===Ji){if(!this._trackEnded){this._trackEnded=!0;const e=this.decoderState.notifyTrackEnded();this.emitFsmDecision(e),this.onEvent({type:"track_ended"})}return}if(t.action===Yi&&void 0!==t.targetGroupId){const e=t.targetGroupId;"video"===this.mediaType&&this.lastConsumedGroupId>=0n&&!this.endedGroups.has(this.lastConsumedGroupId)&&this.onEvent({type:"partial_group_abandoned",fromGroupId:this.lastConsumedGroupId,toGroupId:e,reason:"gap timeout"});for(const t of this.endedGroups)t0&&this.bufferedGroupCounts.size>this.maxBacklogGroups&&this.shedBacklog(),this._throttled)return;if("video"===this.mediaType&&null!==this.activeGroupWaitStartUs){if(this.clock.now()-this.activeGroupWaitStartUs>this.gapDetector.gapTimeoutUs){const e=this.lastConsumedGroupId+1n;this.onEvent({type:"partial_group_abandoned",fromGroupId:this.lastConsumedGroupId,toGroupId:e,reason:"intra-group timeout"}),this.endedGroups.add(this.lastConsumedGroupId);const t=this.decoderState.notifyGap();this.emitFsmDecision(t),this.activeGroupWaitStartUs=null}}let i=0;const s=this.maxReleasePerTick;for(;this.buffer.size>0&&!(s>0&&i>=s)&&!this._throttled;){const e=this.buffer.peek();if(!e)break;const t=this.lastConsumedGroupId+1n;if(e.groupId>t)break;if(e.groupId>this.lastConsumedGroupId&&this.lastConsumedGroupId>=0n){if("video"===this.mediaType&&!this.endedGroups.has(this.lastConsumedGroupId)){null===this.activeGroupWaitStartUs&&(this.activeGroupWaitStartUs=this.clock.now());break}this.activeGroupWaitStartUs=null,this.endedGroups.delete(this.lastConsumedGroupId)}if(e.groupId>this.lastConsumedGroupId&&(this.nextExpectedObjectId=0n),"video"===this.mediaType&&e.objectId>this.nextExpectedObjectId){const t=e.groupId;for(;this.buffer.size>0;){const e=this.buffer.peek();if(!e||e.groupId!==t)break;this.buffer.extract(),this.decrementGroupCount(t)}this.lastConsumedGroupId=t,this.nextExpectedObjectId=0n;const i=this.decoderState.notifyGap();this.emitFsmDecision(i);break}const s=this.buffer.extract();this.decrementGroupCount(s.groupId),"data"===s.kind&&this.processDataObject(s),this.nextExpectedObjectId=s.objectId+1n,i++,s.groupId>this.lastConsumedGroupId&&(this.lastConsumedGroupId=s.groupId)}}shedBacklog(){const e=[...this.bufferedGroupCounts.keys()].sort((e,t)=>et?1:0),t=e.length-this.maxBacklogGroups;if(t<=0)return;const i=e.slice(0,t),s=i[i.length-1]+1n;this.buffer.discardBefore(s);for(const e of i)this.bufferedGroupCounts.delete(e);for(const e of this.headerMap.keys()){BigInt(e.split(":")[0])=this.lastConsumedGroupId&&(this.lastConsumedGroupId=n),this.minAcceptGroupId=n+1n;const r=this.decoderState.notifyGap();this.emitFsmDecision(r),this.onEvent({type:"backlog_shed",droppedGroups:t,remainingGroups:this.bufferedGroupCounts.size,reason:`backlog exceeded ${this.maxBacklogGroups} groups`})}tryEvictAndInsert(e,t){const i=this.buffer.evictLowestImportance();if(!i)return!1;if(i.publisherPriority>e.publisherPriority){this.decrementGroupCount(i.groupId);const s=`${i.groupId}:${i.objectId}`;this.headerMap.delete(s),this.buffer.insert(e);const n=`${e.groupId}:${e.objectId}`;this.headerMap.set(n,t??{});const r=this.bufferedGroupCounts.get(e.groupId)??0;return this.bufferedGroupCounts.set(e.groupId,r+1),!0}return this.buffer.insert(i),!1}processDataObject(e){const t=`${e.groupId}:${e.objectId}`,i=this.headerMap.get(t)??{};if(this.headerMap.delete(t),i.videoConfig){"configure"===this.decoderState.configure(i.videoConfig).action&&this.onCommand({type:"configure",mediaType:this.mediaType,config:i.videoConfig})}let s;if(void 0===i.captureTimestamp||this.sync.hasReference||("audio"===this.mediaType?this.sync.setAudioReference(i.captureTimestamp):this._videoOnly&&this.sync.setVideoReference(i.captureTimestamp)),void 0!==i.captureTimestamp){const e="video"===this.mediaType?this.sync.computeVideoRenderTime(i.captureTimestamp):this.sync.computeAudioRenderTime(i.captureTimestamp);if(null===e)s=0;else if(e.shouldDrop){if(!(e.offsetUs<-5e6))return;s=this.clock.now()}else s=e.offsetUs>5e6?this.clock.now():e.renderTimeUs}else s=this.clock.now();if(void 0!==i.captureTimestamp){const e=this.sync.evaluateCatchUp(i.captureTimestamp);null!==e&&e.currentRate!==this._lastEmittedRate&&(this._lastEmittedRate=e.currentRate,this.onEvent({type:"catch_up_changed",state:e}),this.onCommand({type:"set_playback_rate",rate:e.currentRate}))}if("video"===this.mediaType){const t=i.videoFrameMarking??(0n===e.objectId?{independent:!0,startOfFrame:!0,endOfFrame:!0,discardable:!1,baseLayerSync:!1,temporalId:0}:void 0);if(t?.independent&&this._videoCodec&&e.payload.length>5){!1===gs(this._videoCodec,e.payload)&&this.onEvent({type:"keyframe_validation_failed",groupId:e.groupId,objectId:e.objectId,codec:this._videoCodec})}const n=void 0!==t?{...i,videoFrameMarking:t}:i,r=function(e,t){return{type:!0===t.videoFrameMarking?.independent?"key":"delta",timestamp:void 0!==t.captureTimestamp?Number(t.captureTimestamp):0,data:e}}(e.payload,n),a=this.decoderState.state,o=this.decoderState.processVideoChunk(r,t);if("needs_keyframe"===a&&"decoding"===this.decoderState.state&&void 0!==i.captureTimestamp){this.sync.onVideoJoin(i.captureTimestamp);const e=this.sync.computeVideoRenderTime(i.captureTimestamp);e&&(s=e.renderTimeUs)}"decode"===o.action?this.onCommand({type:"decode_video",chunk:o.chunk,renderTimeUs:s,...void 0!==i.captureTimestamp?{captureTimestampUs:i.captureTimestamp}:{}}):"skip"===o.action&&"waiting for keyframe"===o.reason&&e.groupId!==this.lastKeyframeWaitingGroupId&&(this.lastKeyframeWaitingGroupId=e.groupId,this.onEvent({type:"keyframe_waiting",groupId:e.groupId}))}else{const t=function(e,t){return{type:"key",timestamp:void 0!==t.captureTimestamp?Number(t.captureTimestamp):0,data:e}}(e.payload,i),n=this.decoderState.processAudioChunk(t);"decode"===n.action&&this.onCommand({type:"decode_audio",chunk:n.chunk,renderTimeUs:s})}}emitFsmDecision(e){"reset"===e.action?this.onCommand({type:"reset",mediaType:this.mediaType,reason:e.reason??"gap"}):"flush"===e.action&&this.onCommand({type:"flush",mediaType:this.mediaType})}discardBefore(e){this.buffer.discardBefore(e);for(const[t]of this.bufferedGroupCounts)t0){this.sampleCount++;const t=8*e/(i/1e6);null===this.estimateBps?this.estimateBps=t:this.estimateBps=this.alpha*t+(1-this.alpha)*this.estimateBps}}this.lastTimestampUs=t,this.lastGroupBytes=e}getEstimateKbps(){return null===this.estimateBps||this.sampleCount0&&e.bufferDepthUs>=this.highThresholdUs){const t=this.ladder[this.currentIndex-1];if(e.bandwidthEstimateKbps>t.bitrateKbps*this.upshiftMultiple)return{action:"upshift",targetIndex:this.currentIndex-1}}return{action:"hold"}}commitDownshift(){this.currentIndex0&&this.currentIndex--}setIndex(e){this.currentIndex=Math.max(0,Math.min(e,this.ladder.length-1))}}const ks="catalog",Os=new Set(["loc","mediatimeline","eventtimeline","cmaf"]);function Ns(e,t){const i="string"==typeof e?e:(new TextDecoder).decode(e),s=JSON.parse(i);if("object"!=typeof s||null===s||Array.isArray(s))throw new Error("Catalog must be a JSON object");const n=s;if(!("version"in n)||"number"!=typeof n.version)throw new Error("Catalog version is required and must be a number (§5.1.1)");if(1!==n.version)throw new Error(`Unsupported catalog version ${n.version}; expected 1 (§5.1.1)`);if(!("tracks"in n)||!Array.isArray(n.tracks))throw new Error("Catalog tracks field is required and must be an array (§5.1.8)");const r=n.tracks.map((e,i)=>function(e,t,i){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`Track at index ${t} must be a JSON object`);const s=e;if("string"!=typeof s.name)throw new Error(`Track at index ${t}: name is required and must be a string (§5.1.11)`);const n=s.name;if("string"!=typeof s.packaging||!Os.has(s.packaging))throw new Error(`Track "${n}" at index ${t}: packaging is required and must be one of ${[...Os].join(", ")} (§5.1.12)`);const r=s.packaging;if("boolean"!=typeof s.isLive)throw new Error(`Track "${n}" at index ${t}: isLive is required and must be a boolean (§5.1.15)`);const a=s.isLive;if(!a&&void 0!==s.targetLatency)throw new Error(`Track "${n}": targetLatency MUST NOT be included when isLive is false (§5.1.16)`);if(a&&void 0!==s.trackDuration)throw new Error(`Track "${n}": trackDuration MUST NOT be included when isLive is true (§5.1.37)`);if("eventtimeline"===r&&"string"!=typeof s.eventType)throw new Error(`Track "${n}": eventType is required when packaging is "eventtimeline" (§5.1.13)`);if("eventtimeline"!==r&&void 0!==s.eventType)throw new Error(`Track "${n}": eventType MUST NOT be used when packaging is not "eventtimeline" (§5.1.13)`);if("mediatimeline"===r||"eventtimeline"===r){const e="mediatimeline"===r?"§7.2":"§8.2";if(!Array.isArray(s.depends)||0===s.depends.length)throw new Error(`Track "${n}": depends is required for packaging "${r}" (${e})`);if("application/json"!==s.mimeType)throw new Error(`Track "${n}": mimeType MUST be "application/json" for packaging "${r}" (${e})`)}if("string"==typeof s.initData&&""!==s.initData&&((o=s.initData).length%4!=0||!Ls.test(o)))throw new Error(`Track "${n}" at index ${t}: initData is not valid Base64 (§5.1.20)`);var o;if("string"==typeof s.lang&&(c=s.lang,!Us.test(c)))throw new Error(`Track "${n}" at index ${t}: lang "${s.lang}" is not a valid BCP 47 language tag (§5.1.35)`);var c;if("parentName"in s)throw new Error(`Track "${n}" at index ${t}: parentName MUST only appear in clone context (§5.1.36)`);const d="string"==typeof s.namespace?s.namespace:i,h={name:n,packaging:r,isLive:a,...void 0!==d?{namespace:d}:{},..."string"==typeof s.role?{role:s.role}:{},..."number"==typeof s.renderGroup?{renderGroup:s.renderGroup}:{},..."number"==typeof s.altGroup?{altGroup:s.altGroup}:{},..."string"==typeof s.codec?{codec:s.codec}:{},..."string"==typeof s.mimeType?{mimeType:s.mimeType}:{},..."number"==typeof s.framerate?{framerate:s.framerate}:{},..."number"==typeof s.timescale?{timescale:s.timescale}:{},..."number"==typeof s.bitrate?{bitrate:s.bitrate}:{},..."number"==typeof s.width?{width:s.width}:{},..."number"==typeof s.height?{height:s.height}:{},..."number"==typeof s.samplerate?{samplerate:s.samplerate}:{},..."string"==typeof s.channelConfig?{channelConfig:s.channelConfig}:{},..."number"==typeof s.displayWidth?{displayWidth:s.displayWidth}:{},..."number"==typeof s.displayHeight?{displayHeight:s.displayHeight}:{},..."string"==typeof s.lang?{lang:s.lang}:{},..."string"==typeof s.label?{label:s.label}:{},..."string"==typeof s.initData?{initData:s.initData}:{},..."string"==typeof s.initTrack?{initTrack:s.initTrack}:{},...Array.isArray(s.depends)?{depends:s.depends}:{},..."number"==typeof s.temporalId?{temporalId:s.temporalId}:{},..."number"==typeof s.spatialId?{spatialId:s.spatialId}:{},..."number"==typeof s.targetLatency?{targetLatency:s.targetLatency}:{},..."number"==typeof s.trackDuration?{trackDuration:s.trackDuration}:{},..."string"==typeof s.eventType?{eventType:s.eventType}:{},..."string"==typeof s.parentName?{parentName:s.parentName}:{},..."number"==typeof s.maxGrpSapStartingType?{maxGrpSapStartingType:s.maxGrpSapStartingType}:{},..."number"==typeof s.maxObjSapStartingType?{maxObjSapStartingType:s.maxObjSapStartingType}:{}};return h}(e,i,t));if(function(e){const t=new Set;for(const i of e){const e=`${i.namespace??""}\0${i.name}`;if(t.has(e))throw new Error(`Duplicate track name "${i.name}" in namespace "${i.namespace??"(inherited)"}" (§5.1.11)`);t.add(e)}} +var e,t,s,i;!function(e){e.OPUS="OPUS",e.NONE="NONE"}(e||(e={})),function(e){e.VP8="VP8",e.H264="H264",e.H265="H265",e.AV1="AV1",e.NONE="NONE"}(t||(t={})),function(e){e[e.UNAVAILABLE=1e3]="UNAVAILABLE",e[e.AVAILABLE=0]="AVAILABLE",e[e.IDLE=1]="IDLE",e[e.PLAYING=2]="PLAYING",e[e.PAUSED=3]="PAUSED"}(s||(s={})),function(e){e.UNAVAILABLE="Playback.UNAVAILABLE",e.AVAILABLE="Playback.AVAILABLE",e.IDLE="Playback.IDLE",e.PLAYING="Playback.PLAYING",e.PAUSED="Playback.PAUSED"}(i||(i={}));const r={[s.UNAVAILABLE]:i.UNAVAILABLE,[s.AVAILABLE]:i.AVAILABLE,[s.IDLE]:i.IDLE,[s.PLAYING]:i.PLAYING,[s.PAUSED]:i.PAUSED};var n,a,o,c;!function(e){e.RTMP="rtmp",e.RTC="rtc"}(n||(n={})),function(e){e.LIVE="live",e.RECORD="record",e.APPEND="append"}(a||(a={})),function(e){e.OPUS="OPUS"}(o||(o={})),function(e){e.VP8="VP8",e.H264="H264",e.H265="H265",e.AV1="AV1"}(c||(c={}));var d={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},h={};function u(e){return"string"==typeof e?d[e.toLowerCase()]:e}function l(e,t){return l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},l(e,t)}function p(e,t,s){return p=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}()?Reflect.construct:function(e,t,s){var i=[null];i.push.apply(i,t);var r=new(Function.bind.apply(e,i));return s&&l(r,s.prototype),r},p.apply(null,arguments)}function m(e){if(null==e)return e;if(Array.isArray(e))return e.slice();if("object"==typeof e){var t={};return Object.keys(e).forEach(function(s){t[s]=e[s]}),t}return e}function g(e){return void 0===e?"undefined":null===e?"null":Array.isArray(e)?"[ "+e.map(function(e){return g(e)}).join(", ")+" ]":"object"==typeof e?JSON.stringify(e):"function"==typeof e?"[Function: "+e.name+"]":"boolean"==typeof e||"number"==typeof e?e:"'"+e.toString()+"'"}function f(e){if("string"!=typeof e){for(var t=new Array(arguments.length),s=0;s=n)return e;switch(e){case"%s":return String(r[i++]);case"%d":return Number(r[i++]);case"%j":try{return JSON.stringify(r[i++])}catch(e){return"[Circular]"}default:return e}}),o=r[i];ie||(r=function(r){var n;r[0]instanceof Error?(s={err:t.serializers&&t.serializers.err?t.serializers.err(r[0]):T.err(r[0])},n={err:!0},i=1===r.length?[s.err.message]:Array.prototype.slice.call(r,1)):"object"!=typeof r[0]&&null!==r[0]||Array.isArray(r[0])?(s=null,i=Array.prototype.slice.call(r)):(s=r[0],i=1===r.length&&s.err&&s.err instanceof Error?[s.err.message]:Array.prototype.slice.call(r,1));var a=m(t.fields);a.level=e;var o=s?m(s):null;if(o&&(t.serializers&&t._applySerializers(o,n),Object.keys(o).forEach(function(e){a[e]=o[e]})),a.levelName=h[e],a.msg=i.length?f.apply(t,i):"",a.time||(a.time=new Date),t.src&&!a.src)try{throw new Error("call-stack-error")}catch(e){var c=e.stack?function(e,t){var s=e.split("\n");s[0]&&s[0].indexOf("call-stack-error")>=0&&s.shift();var i=s[t],r=null;if(i){var n=/^\s*(at|.*@)\s*(.+)?$/.exec(i);r=Array.isArray(n)&&n[2]?n[2]:i}return r}(e.stack,2):"";c||function(e){return b[e]}("src")||S("Unable to determine src line info","src"),a.src=c||""}return a.v=1,a}(i),this._emit(r))}}function E(e){var t=e.stack||e.toString();if(e.cause&&"function"==typeof e.cause){var s=e.cause();s&&(t+="\nCaused by: "+E(s))}return t}v.prototype.trace=y(10),v.prototype.debug=y(20),v.prototype.info=y(30),v.prototype.warn=y(40),v.prototype.error=y(50),v.prototype.fatal=y(60);var T={err:function(e){return e&&e.stack?{message:e.message,name:e.name,stack:E(e),code:e.code,signal:e.signal}:e}};const w={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"};class R{write(e){console.log("%s - [%s] %s: %s",e.time.toISOString(),e.name,w[e.level]||"UNKNOWN",e.msg)}}let C,I;const A=e=>(t,s)=>{var i;C&&"function"==typeof C[e]&&C[e]((i=t,e=>`(${i}) ${e}`)(s))},k={TRACE:"trace",INFO:"info",DEBUG:"debug",WARN:"warn",ERROR:"error",FATAL:"fatal"},O=(e,t=!1,s)=>{const i=[{level:e,stream:new R,type:"raw"}];if(s){const t=s.map(t=>({...t,level:e}));i.push(...t)}t&&(I=[],i.push({level:e,stream:{write:t=>{const s=`[${t.time.toISOString()}] ${e.toUpperCase()}: ${t.msg}`;null==I||I.push(s)}},type:"raw"}));C=function(){return p(v,[].slice.call(arguments))}({level:e,name:"red5pro-sdk",streams:i})},P=()=>(C||O(k.INFO),C),N=()=>I||[];A(k.TRACE),A(k.INFO);const U=A(k.DEBUG),M=A(k.WARN),L=A(k.ERROR);A(k.FATAL);const D="RED5PRO";class B{constructor(){this._callbacks={},this._callbacks[D]=[]}_notify(e,t){let s;const i=e.length;for(s=0;s1&&(r=F.exec(e),i[1]===t&&r&&r.length>1)?r[1]:void 0}}function V(e){const t=H(e,"orientation");if(t)return{orientation:parseInt(t)}}function G(e){const t=H(e,"streamingMode");if(t)return{streamingMode:t}}const j=e=>q.get(e),K=e=>{const t=e.textTracks;t&&(e.addTextTrack("metadata"),t.addEventListener("addtrack",t=>{const s=t.track;s.mode="hidden",s.addEventListener("cuechange",t=>{let i,r;for(t&&t.currentTarget?i=t.currentTarget.cues:(i=s.cues,i=i&&i.length>0?i:s.activeCues),i=i||[],r=0;r{e(i)}),r&&n&&n.streamingMode&&n.streamingMode.forEach(e=>{e(r)})}}})}))},W=4611686018427387903n;function Q(e){if("number"==typeof e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Varint value must be a non-negative integer, got ${e}`);if(e>Number.MAX_SAFE_INTEGER)throw new RangeError(`Varint number value ${e} exceeds MAX_SAFE_INTEGER; use bigint for values > 2^53-1`);return BigInt(e)}if(e<0n||e>W)throw new RangeError(`Varint value must be 0 ≤ n ≤ ${W}, got ${e}`);return e}function z(e){if(e<0n||e>W)throw new RangeError(`QUIC varint value out of range (0..${W}): ${e}`);return e<=63n?1:e<=16383n?2:e<=1073741823n?4:8}function Y(e,t){if(t>=e.length)throw new RangeError(`Varint read out of bounds: offset ${t}, length ${e.length}`);const s=e[t],i=1<<(s>>6);if(t+i>e.length)throw new RangeError(`Varint requires ${i} bytes but only ${e.length-t} available`);let r;switch(i){case 1:r=BigInt(63&s);break;case 2:r=BigInt((63&s)<<8|e[t+1]);break;case 4:r=BigInt(((63&s)<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0);break;case 8:r=BigInt(63&s)<<56n|BigInt(e[t+1])<<48n|BigInt(e[t+2])<<40n|BigInt(e[t+3])<<32n|BigInt(e[t+4])<<24n|BigInt(e[t+5])<<16n|BigInt(e[t+6])<<8n|BigInt(e[t+7])}return{value:r,bytesRead:i}}function J(e,t,s){switch(z(e)){case 1:return t[s]=Number(e),1;case 2:return t[s]=64|Number(e>>8n),t[s+1]=Number(0xffn&e),2;case 4:return t[s]=128|Number(e>>24n&0x3fn),t[s+1]=Number(e>>16n&0xffn),t[s+2]=Number(e>>8n&0xffn),t[s+3]=Number(0xffn&e),4;case 8:return t[s]=192|Number(e>>56n&0x3fn),t[s+1]=Number(e>>48n&0xffn),t[s+2]=Number(e>>40n&0xffn),t[s+3]=Number(e>>32n&0xffn),t[s+4]=Number(e>>24n&0xffn),t[s+5]=Number(e>>16n&0xffn),t[s+6]=Number(e>>8n&0xffn),t[s+7]=Number(0xffn&e),8}}const X=18446744073709551615n;function Z(e){return function(e){if(e<0n||e>X)throw new RangeError(`vi64 value must be 0 ≤ n ≤ ${X}, got ${e}`)}(e),e<=0x7fn?1:e<=0x3fffn?2:e<=0x1fffffn?3:e<=0xfffffffn?4:e<=0x7ffffffffn?5:e<=0x3ffffffffffn?6:e<=0x1ffffffffffffn?7:e<=0xffffffffffffffn?8:9}function ee(e,t){if(t>=e.length)throw new RangeError(`vi64 read out of bounds: offset ${t}, length ${e.length}`);const s=e[t];let i=0;for(let e=128;0!==e&&0!==(s&e);e>>=1)i++;const r=i+1;if(t+r>e.length)throw new RangeError(`vi64 requires ${r} bytes but only ${e.length-t} available`);let n=9===r?0n:BigInt(s&255>>r);for(let s=1;s=0;r--)t[s+r]=Number(0xffn&e),e>>=8n;const r=1===i?0:255<<9-i&255;return t[s]=t[s]|r,i}const se=2,ie=3,re=4,ne=5,ae=6,oe=7,ce=8,de=11,he=13,ue=14,le=15,pe=16,me=22,ge=24,fe=29,be=80,Se=81,_e=12032,ve=1,ye=3,Ee=4,Te=5,we=7,Re=5,Ce=12032,Ie=321601064,Ae=1,ke=6,Oe=8,Pe=32,Ne=64,Ue=1,Me=2,Le=4,De=8,Be=32;function xe(e){return(e&ke)>>1}function Fe(e){return e>=16&&e<=127&&!!(16&e)}function qe(e){return e<=47&&!(16&e)&&!(192&e)}function $e(e){if(!qe(e))return!1;return!(0!==(e&Be)&&0!==(e&Me))}function He(e){return e===BigInt(Re)?"fetch":e===BigInt(Ce)?"setup":e===BigInt(Ie)?"padding":e<=0x7fn&&Fe(Number(e))?"subgroup":"unknown"}const Ve={NO_ERROR:Q(0),INTERNAL_ERROR:Q(1),UNAUTHORIZED:Q(2),PROTOCOL_VIOLATION:Q(3),INVALID_REQUEST_ID:Q(4),DUPLICATE_TRACK_ALIAS:Q(5),KEY_VALUE_FORMATTING_ERROR:Q(6),TOO_MANY_REQUESTS:Q(7),INVALID_PATH:Q(8),MALFORMED_PATH:Q(9),GOAWAY_TIMEOUT:Q(16),CONTROL_MESSAGE_TIMEOUT:Q(17),DATA_STREAM_TIMEOUT:Q(18),AUTH_TOKEN_CACHE_OVERFLOW:Q(19),DUPLICATE_AUTH_TOKEN_ALIAS:Q(20),VERSION_NEGOTIATION_FAILED:Q(21),MALFORMED_AUTH_TOKEN:Q(22),UNKNOWN_AUTH_TOKEN_ALIAS:Q(23),EXPIRED_AUTH_TOKEN:Q(24),INVALID_AUTHORITY:Q(25),MALFORMED_AUTHORITY:Q(26)},Ge={INTERNAL_ERROR:Q(0),UNAUTHORIZED:Q(1),TIMEOUT:Q(2),NOT_SUPPORTED:Q(3),MALFORMED_AUTH_TOKEN:Q(4),EXPIRED_AUTH_TOKEN:Q(5),DOES_NOT_EXIST:Q(16),INVALID_RANGE:Q(17),MALFORMED_TRACK:Q(18),DUPLICATE_SUBSCRIPTION:Q(25),UNINTERESTED:Q(32),PREFIX_OVERLAP:Q(48),NAMESPACE_TOO_LARGE:Q(49),INVALID_JOINING_REQUEST_ID:Q(50),UNSUPPORTED_EXTENSION:Q(51),REDIRECT:Q(52)},je={INTERNAL_ERROR:Q(0),UNAUTHORIZED:Q(1),TRACK_ENDED:Q(2),SUBSCRIPTION_ENDED:Q(3),GOING_AWAY:Q(4),EXPIRED:Q(5),TOO_FAR_BEHIND:Q(6),UPDATE_FAILED:Q(8),MALFORMED_TRACK:Q(18)};Q(0),Q(1),Q(2),Q(3),Q(4),Q(18);const Ke={INTERNAL_ERROR:Q(0),UNAUTHORIZED:Q(1),TIMEOUT:Q(2),NOT_SUPPORTED:Q(3),MALFORMED_AUTH_TOKEN:Q(4),EXPIRED_AUTH_TOKEN:Q(5),GOING_AWAY:Q(6),EXCESSIVE_LOAD:Q(9),DOES_NOT_EXIST:Q(16),INVALID_RANGE:Q(17),MALFORMED_TRACK:Q(18),DUPLICATE_SUBSCRIPTION:Q(25),UNINTERESTED:Q(32),PREFIX_OVERLAP:Q(48),NAMESPACE_TOO_LARGE:Q(49),INVALID_JOINING_REQUEST_ID:Q(50),UNSUPPORTED_EXTENSION:Q(51),REDIRECT:Q(52)},We={INTERNAL_ERROR:Q(0),UNAUTHORIZED:Q(1),TRACK_ENDED:Q(2),SUBSCRIPTION_ENDED:Q(3),GOING_AWAY:Q(4),TOO_FAR_BEHIND:Q(5),EXPIRED:Q(6),UPDATE_FAILED:Q(8),EXCESSIVE_LOAD:Q(9),MALFORMED_TRACK:Q(18)},Qe={INTERNAL_ERROR:Q(0),CANCELLED:Q(1),DELIVERY_TIMEOUT:Q(2),SESSION_CLOSED:Q(3),GOING_AWAY:Q(4),TOO_FAR_BEHIND:Q(5),UNKNOWN_OBJECT_STATUS:Q(6),EXPIRED_AUTH_TOKEN:Q(7),EXCESSIVE_LOAD:Q(9),MALFORMED_TRACK:Q(18)};class ze extends Error{constructor(e){super(e),this.name="ProtocolViolationError"}}function Ye(e,t){if(t>=e.length)throw new RangeError(`readUint8 out of bounds: offset ${t}, length ${e.length}`);return{value:e[t],bytesRead:1}}function Je(e,t){const{value:s,bytesRead:i}=Y(e,t),r=Number(s),{value:n,bytesRead:a}=function(e,t,s){if(t+s>e.length)throw new RangeError(`readBytes: need ${s} bytes at offset ${t}, but buffer length is ${e.length}`);return{value:e.slice(t,t+s),bytesRead:s}}(e,t+i,r);return{value:n,bytesRead:i+a}}function Xe(e,t,s){let i=s;return i+=J(Q(e.length),t,i),t.set(e,i),i+=e.length,i-s}function Ze(e){return z(Q(e.length))+e.length}function et(e,t){let s=t;const{value:i,bytesRead:r}=Y(e,s);s+=r;const n=Number(i),a=[];for(let t=0;te+t.length,0)}function nt(e){for(let t=0;t32)throw new ze(` Track Namespace has ${e.length} fields; maximum is 32 (§2.4.1)`);nt(e);const s=rt(e);if(s>it)throw new ze(` Track Namespace length ${s} exceeds maximum 4096 bytes (§2.4.1)`)}const ot=new Uint8Array([46,115,101,115,115,105,111,110]);function ct(e){return function(e,t){const s=e[0];if(void 0===s||s.length!==t.length)return!1;for(let e=0;e32)throw new ze(` Track Namespace Prefix has ${e.length} fields; maximum is 32 (§9.25)`);nt(e);const t=rt(e);if(t>it)throw new ze(` Track Namespace Prefix length ${t} exceeds maximum 4096 bytes (§2.4.1)`)}function ut(e,t,s={}){at(e,s.allowEmptyNamespace?{allowEmpty:!0}:{});const i=rt(e)+t.length;if(i>it)throw new ze(` Full Track Name length ${i} exceeds maximum 4096 bytes (§2.4.1)`)}function lt(e){if(e.length>32)throw new ze(` Track Namespace Suffix has ${e.length} fields; maximum is 32 (§2.4.1)`);nt(e);const t=rt(e);if(t>it)throw new ze(` Track Namespace Suffix length ${t} exceeds maximum 4096 bytes (§2.4.1)`)}function pt(e){!function(e){for(let t=0;t[BigInt(e.type),e.kind]));function gt(e){switch(e.kind){case"uint8":return 1;case"varint":return Z(e.value);case"location":return Z(e.group)+Z(e.object);case"bytes":return Z(BigInt(e.value.length))+e.value.length;case"namespace":return pt(e.value)}}function ft(e,t,s){switch(e.kind){case"uint8":return function(e,t,s){return t[s]=255&e,1}(e.value,t,s);case"varint":return te(e.value,t,s);case"location":{let i=s;return i+=te(e.group,t,i),i+=te(e.object,t,i),i-s}case"bytes":{let i=s;return i+=te(BigInt(e.value.length),t,i),t.set(e.value,i),i+=e.value.length,i-s}case"namespace":return function(e,t,s){let i=s+te(BigInt(e.length),t,s);for(const s of e)i+=te(BigInt(s.length),t,i),t.set(s,i),i+=s.length;return i-s}(e.value,t,s)}}function bt(e,t,s){switch(e){case"uint8":{const{value:e,bytesRead:i}=Ye(t,s);return{value:{kind:"uint8",value:e},bytesRead:i}}case"varint":{const{value:e,bytesRead:i}=ee(t,s);return{value:{kind:"varint",value:e},bytesRead:i}}case"location":{const e=ee(t,s),i=ee(t,s+e.bytesRead);return{value:{kind:"location",group:e.value,object:i.value},bytesRead:e.bytesRead+i.bytesRead}}case"bytes":{const e=ee(t,s),i=s+e.bytesRead,r=Number(e.value);if(i+r>t.length)throw new ze("Message parameter bytes value exceeds buffer");return{value:{kind:"bytes",value:t.slice(i,i+r)},bytesRead:e.bytesRead+r}}case"namespace":{const{value:e,bytesRead:i}=function(e,t){const s=ee(e,t);let i=t+s.bytesRead;const r=[];for(let t=0n;te.length)throw new ze("Track Namespace field exceeds buffer");r.push(e.slice(i,i+s)),i+=s}return ht(r),{value:r,bytesRead:i-t}}(t,s);return{value:{kind:"namespace",value:e},bytesRead:i}}}}function St(e,t){for(const[s,i]of e){const e=t.get(s);if(void 0===e)throw new ze(`Cannot encode unknown message parameter Type 0x${s.toString(16)}`);for(const t of i)if(t.kind!==e)throw new ze(`Message parameter Type 0x${s.toString(16)} expects ${e}, got ${t.kind}`)}}function _t(e){const t=[...e.entries()].sort(([e],[t])=>et?1:0),s=[];let i=0n;for(const[e,r]of t)for(const t of r)s.push({delta:e-i,value:t}),i=e;return s}function vt(e,t=mt){St(e,t);const s=_t(e);let i=Z(BigInt(s.length));for(const{delta:e,value:t}of s)i+=Z(e)+gt(t);return i}function yt(e,t=mt){St(e,t);const s=_t(e),i=new Uint8Array(Z(BigInt(s.length))+s.reduce((e,{delta:t,value:s})=>e+Z(t)+gt(s),0));let r=te(BigInt(s.length),i,0);for(const{delta:e,value:t}of s)r+=te(e,i,r),r+=ft(t,i,r);return i}function Et(e,t,s){let i=t;const r=ee(e,i);i+=r.bytesRead;const n=new Map;let a=0n;for(let t=0n;tX)throw new ze(`Message parameter Type ${r} exceeds 2^64-1`);a=r;const o=s.get(r);if(void 0===o)throw new ze(`Unknown message parameter Type 0x${r.toString(16)}`);const{value:c,bytesRead:d}=bt(o,e,i);i+=d;const h=n.get(r);h?h.push(c):n.set(r,[c])}return{params:n,bytesRead:i-t}}const Tt=65535;class wt extends RangeError{category;constructor(e,t){super(t),this.category=e,this.name="PropertyWireError"}}const Rt={read:(e,t)=>{const s=Y(e,t);return{value:s.value,bytesRead:s.bytesRead}},write:(e,t,s)=>J(e,t,s),length:e=>z(e),max:4611686018427387903n},Ct={read:(e,t)=>ee(e,t),write:(e,t,s)=>te(e,t,s),length:e=>Z(e),max:X};function It(e){switch(e){case"d14-absolute-varint":return{int:Rt,delta:!1};case"d16-delta-varint":return{int:Rt,delta:!0};case"d18-delta-vi64":return{int:Ct,delta:!0}}}function At(e,t,s){const{int:i,delta:r}=It(s.profile),n=s.end??e.length;if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||ne.length)throw new RangeError(`property block bounds out of range: offset ${t}, end ${n}, buffer length ${e.length}`);if(void 0!==s.count&&(!Number.isInteger(s.count)||s.count<0))throw new RangeError(`property block count must be a non-negative integer, got ${s.count}`);const a=nvoid 0!==s.count?hX)throw new wt("delta-overflow",`property id ${s} exceeds 2^64-1`);let u;if(d=s,1n==(1n&s)){const t=i.read(a,c);c+=t.bytesRead;const s=Number(t.value);if(t.value>BigInt(Tt))throw new wt("odd-value-too-long",`odd-property value length ${t.value} exceeds maximum 65535 (2^16-1)`);if(c+s>n)throw new wt("length-overrun",`odd-property value of ${s} bytes exceeds the block`);u=e.slice(c,c+s),c+=s}else{const e=i.read(a,c);c+=e.bytesRead,u=e.value}o.push({id:s,value:u}),h+=1}return{entries:o,bytesRead:c-t}}function kt(e){return e.map((e,t)=>[e,t]).sort((e,t)=>e[0].idt[0].id?1:e[1]-t[1]).map(([e])=>e)}function Ot(e,t){if(e<0n||e>X)throw new wt("value-out-of-range",`property id ${e} exceeds 2^64-1`);if(1n==(1n&e)){if(!(t instanceof Uint8Array))throw new wt("parity-mismatch",`odd property id ${e} expects a bytes value`);if(t.length>Tt)throw new wt("odd-value-too-long",`odd-property value length ${t.length} exceeds maximum 65535 (2^16-1)`)}else if("bigint"!=typeof t)throw new wt("parity-mismatch",`even property id ${e} expects a varint value`)}function Pt(e,t){const{int:s,delta:i}=It(t),r=kt(e);let n=0,a=0n;for(const{id:e,value:o}of r){Ot(e,o);const r=i?e-a:e;if(r<0n||r>s.max)throw new wt("value-out-of-range",`property id field ${r} exceeds the ${t} range`);if(n+=s.length(r),a=e,1n==(1n&e)){const e=o;n+=s.length(BigInt(e.length))+e.length}else{if(o<0n||o>s.max)throw new wt("value-out-of-range",`value ${o} exceeds the ${t} range`);n+=s.length(o)}}return n}function Nt(e,t){const{int:s,delta:i}=It(t),r=kt(e),n=new Uint8Array(Pt(e,t));let a=0,o=0n;for(const{id:e,value:t}of r)if(a+=s.write(i?e-o:e,n,a),o=e,1n==(1n&e)){const e=t;a+=s.write(BigInt(e.length),n,a),n.set(e,a),a+=e.length}else try{a+=s.write(t,n,a)}catch(e){if(e instanceof RangeError)throw new wt("value-out-of-range",e.message);throw e}return n}const Ut="d18-delta-vi64";function Mt(e){if(e instanceof wt)throw new ze(e.message);throw e}const Lt=new Set([0x3cn,0x3en]);function Dt(e,t){switch(e){case 0x0en:if("bigint"!=typeof t||t<0n||t>255n)throw new ze(`DEFAULT_PUBLISHER_PRIORITY (0x0E) must be 0..255, got ${t}`);break;case 0x22n:if(1n!==t&&2n!==t)throw new ze(`DEFAULT_PUBLISHER_GROUP_ORDER (0x22) must be 1 or 2, got ${t}`);break;case 0x30n:if(0n!==t&&1n!==t)throw new ze(`DYNAMIC_GROUPS (0x30) must be 0 or 1, got ${t}`)}}function Bt(e){const t=[];for(const[s,i]of e.entries()){const e=s;for(const s of i)Dt(e,s),t.push({id:e,value:s})}return t}function xt(e){try{return Pt(Bt(e),Ut)}catch(e){Mt(e)}}function Ft(e){try{return Nt(Bt(e),Ut)}catch(e){Mt(e)}}function qt(e,t,s=e.length){const i=(()=>{try{return At(e,t,{profile:Ut,end:s})}catch(e){Mt(e)}})(),r=new Map;for(const{id:e,value:t}of i.entries){Dt(e,t);const s=r.get(e);s?s.push(t):r.set(e,[t])}return{properties:r,bytesRead:i.bytesRead}}function $t(e){const t=new Map;for(const{id:s,value:i}of e){const e="bigint"==typeof i?Q(i):i,r=t.get(s);r?r.push(e):t.set(s,[e])}return t}function Ht(e){const t=[];for(const[s,i]of e)for(const e of i)t.push({id:s,value:e});return t}function Vt(e,t,s,i){const{entries:r,bytesRead:n}=At(e,t,{profile:i,count:s});return{value:$t(r),bytesRead:n}}function Gt(e,t,s,i){const r=Nt(Ht(e),i);return t.set(r,s),r.length}function jt(e,t,s){return Gt(e,t,s,"d16-delta-varint")}function Kt(e){return Pt(Ht(e),"d16-delta-varint")}function Wt(e){let t=0;for(const s of e.values())t+=s.length;return t}function Qt(e,t){let s=t;const{value:i,bytesRead:r}=Y(e,s);s+=r;const{value:n,bytesRead:a}=Y(e,s);return s+=a,{value:{group:i,object:n},bytesRead:s-t}}function zt(e,t,s){let i=s;return i+=J(e.group,t,i),i+=J(e.object,t,i),i-s}function Yt(e){return z(e.group)+z(e.object)}const Jt=new TextEncoder,Xt=new TextDecoder;function Zt(e,t){let s=t;const{value:i,bytesRead:r}=Y(e,s);s+=r;const n=Number(i);if(n>1024)throw new RangeError(`Reason Phrase length ${n} exceeds maximum 1024 bytes`);if(s+n>e.length)throw new RangeError(`Reason Phrase declared length ${n} exceeds remaining buffer (${e.length-s} bytes available)`);const a=e.slice(s,s+n);return s+=n,{value:Xt.decode(a),bytesRead:s-t}}function es(e,t,s){const i=Jt.encode(e);if(i.length>1024)throw new RangeError(`Reason Phrase length ${i.length} exceeds maximum 1024 bytes`);let r=s;return r+=J(Q(i.length),t,r),t.set(i,r),r+=i.length,r-s}function ts(e){const t=Jt.encode(e).length;return z(Q(t))+t}const ss={REQUEST_UPDATE:Q(2),SUBSCRIBE:Q(3),SUBSCRIBE_OK:Q(4),REQUEST_ERROR:Q(5),PUBLISH_NAMESPACE:Q(6),REQUEST_OK:Q(7),NAMESPACE:Q(8),PUBLISH_NAMESPACE_DONE:Q(9),UNSUBSCRIBE:Q(10),PUBLISH_DONE:Q(11),PUBLISH_NAMESPACE_CANCEL:Q(12),TRACK_STATUS:Q(13),NAMESPACE_DONE:Q(14),GOAWAY:Q(16),SUBSCRIBE_NAMESPACE:Q(17),MAX_REQUEST_ID:Q(21),FETCH:Q(22),FETCH_CANCEL:Q(23),FETCH_OK:Q(24),REQUESTS_BLOCKED:Q(26),PUBLISH:Q(29),PUBLISH_OK:Q(30),CLIENT_SETUP:Q(32),SERVER_SETUP:Q(33)},is={PATH:Q(1),MAX_REQUEST_ID:Q(2),AUTHORIZATION_TOKEN:Q(3),MAX_AUTH_TOKEN_CACHE_SIZE:Q(4),AUTHORITY:Q(5),MOQT_IMPLEMENTATION:Q(7)},rs={DELIVERY_TIMEOUT:Q(2),OBJECT_DELIVERY_TIMEOUT:Q(2),AUTHORIZATION_TOKEN:Q(3),RENDEZVOUS_TIMEOUT:Q(4),SUBGROUP_DELIVERY_TIMEOUT:Q(6),EXPIRES:Q(8),LARGEST_OBJECT:Q(9),FILL_TIMEOUT:Q(10),FORWARD:Q(16),SUBSCRIBER_PRIORITY:Q(32),SUBSCRIPTION_FILTER:Q(33),GROUP_ORDER:Q(34),NEW_GROUP_REQUEST:Q(50),TRACK_NAMESPACE_PREFIX:Q(52)};function ns(e){const t=new Map;for(const[s,i]of e)t.set(s,i.map(e=>{if("bigint"==typeof e)return e;if(e instanceof Uint8Array)return e;const t=Array.isArray(e)?"Track Namespace tuple":"Location";throw new ze(`${t}-valued parameter 0x${s.toString(16)} cannot be encoded as draft-14/16 KVP`)}));return t}const as=new Set([rs.DELIVERY_TIMEOUT,rs.EXPIRES,rs.LARGEST_OBJECT,rs.FORWARD,rs.SUBSCRIBER_PRIORITY,rs.SUBSCRIPTION_FILTER,rs.GROUP_ORDER,rs.NEW_GROUP_REQUEST]),os=new Map([[rs.DELIVERY_TIMEOUT,"DELIVERY_TIMEOUT"],[rs.EXPIRES,"EXPIRES"],[rs.LARGEST_OBJECT,"LARGEST_OBJECT"],[rs.FORWARD,"FORWARD"],[rs.SUBSCRIBER_PRIORITY,"SUBSCRIBER_PRIORITY"],[rs.SUBSCRIPTION_FILTER,"SUBSCRIPTION_FILTER"],[rs.GROUP_ORDER,"GROUP_ORDER"],[rs.NEW_GROUP_REQUEST,"NEW_GROUP_REQUEST"]]);function cs(e){!function(e){switch(e.type){case"SUBSCRIBE":case"TRACK_STATUS":case"PUBLISH":ut(e.trackNamespace,e.trackName);break;case"FETCH":1===e.fetch.fetchType&&ut(e.fetch.trackNamespace,e.fetch.trackName);break;case"PUBLISH_NAMESPACE":at(e.trackNamespace);break;case"NAMESPACE":case"NAMESPACE_DONE":lt(e.trackNamespaceSuffix);break;case"SUBSCRIBE_NAMESPACE":ht(e.trackNamespacePrefix)}}(e),function(e){return"CLIENT_SETUP"!==e.type&&"SERVER_SETUP"!==e.type&&"parameters"in e}(e)&&function(e){for(const[t,s]of e)if(as.has(t)&&s.length>1){const e=os.get(t)??`0x${t.toString(16)}`;throw new Error(`Duplicate message parameter: ${e} may not appear multiple times`)}}(e.parameters);const t=function(e){switch(e){case"CLIENT_SETUP":return ss.CLIENT_SETUP;case"SERVER_SETUP":return ss.SERVER_SETUP;case"SETUP":throw new Error("SETUP is a draft-18 message; the draft-14/16 codec uses CLIENT_SETUP/SERVER_SETUP");case"GOAWAY":return ss.GOAWAY;case"MAX_REQUEST_ID":return ss.MAX_REQUEST_ID;case"REQUESTS_BLOCKED":return ss.REQUESTS_BLOCKED;case"REQUEST_OK":return ss.REQUEST_OK;case"REQUEST_ERROR":return ss.REQUEST_ERROR;case"SUBSCRIBE":return ss.SUBSCRIBE;case"SUBSCRIBE_OK":return ss.SUBSCRIBE_OK;case"REQUEST_UPDATE":return ss.REQUEST_UPDATE;case"UNSUBSCRIBE":return ss.UNSUBSCRIBE;case"PUBLISH":return ss.PUBLISH;case"PUBLISH_OK":return ss.PUBLISH_OK;case"PUBLISH_DONE":return ss.PUBLISH_DONE;case"FETCH":return ss.FETCH;case"FETCH_OK":return ss.FETCH_OK;case"FETCH_CANCEL":return ss.FETCH_CANCEL;case"TRACK_STATUS":return ss.TRACK_STATUS;case"PUBLISH_NAMESPACE":return ss.PUBLISH_NAMESPACE;case"NAMESPACE":return ss.NAMESPACE;case"PUBLISH_NAMESPACE_DONE":return ss.PUBLISH_NAMESPACE_DONE;case"NAMESPACE_DONE":return ss.NAMESPACE_DONE;case"PUBLISH_NAMESPACE_CANCEL":return ss.PUBLISH_NAMESPACE_CANCEL;case"SUBSCRIBE_NAMESPACE":return ss.SUBSCRIBE_NAMESPACE;case"UNSUBSCRIBE_NAMESPACE":case"PUBLISH_NAMESPACE_OK":case"PUBLISH_NAMESPACE_ERROR":case"PUBLISH_ERROR":throw new Error(`Cannot encode draft-14-only message type "${e}" with draft-16 encoder`);case"SUBSCRIBE_TRACKS":case"PUBLISH_BLOCKED":throw new Error(`Cannot encode draft-18-only message type "${e}" with draft-16 encoder`)}}(e.type),s=function(e){switch(e.type){case"CLIENT_SETUP":case"SERVER_SETUP":return ds(e.parameters);case"SETUP":throw new Error("SETUP is a draft-18 message; not supported by the draft-14/16 codec");case"GOAWAY":{const t=(new TextEncoder).encode(e.newSessionUri);if(t.length>8192)throw new RangeError(`GOAWAY URI length ${t.length} exceeds maximum 8192 bytes`);return z(Q(t.length))+t.length}case"MAX_REQUEST_ID":return z(e.maxRequestId);case"REQUESTS_BLOCKED":return z(e.maximumRequestId);case"REQUEST_OK":case"PUBLISH_OK":return z(e.requestId)+ds(e.parameters);case"REQUEST_ERROR":return z(e.requestId)+z(e.errorCode)+z(e.retryInterval)+ts(e.errorReason);case"SUBSCRIBE":case"TRACK_STATUS":return z(e.requestId)+st(e.trackNamespace)+ms(e.trackName)+ds(e.parameters);case"SUBSCRIBE_OK":return z(e.requestId)+z(e.trackAlias)+ds(e.parameters)+ls(e.trackProperties??e.trackExtensions??new Map);case"REQUEST_UPDATE":return z(e.requestId)+z(e.existingRequestId)+ds(e.parameters);case"UNSUBSCRIBE":case"FETCH_CANCEL":case"PUBLISH_NAMESPACE_DONE":return z(e.requestId);case"PUBLISH":return z(e.requestId)+st(e.trackNamespace)+ms(e.trackName)+z(e.trackAlias)+ds(e.parameters)+ls(e.trackProperties??e.trackExtensions??new Map);case"PUBLISH_DONE":return z(e.requestId)+z(e.statusCode)+z(e.streamCount)+ts(e.errorReason);case"FETCH":{let t=z(e.requestId)+z(Q(e.fetch.fetchType));return 1===e.fetch.fetchType?t+=st(e.fetch.trackNamespace)+ms(e.fetch.trackName)+Yt(e.fetch.startLocation)+Yt(e.fetch.endLocation):t+=z(e.fetch.joiningRequestId)+z(e.fetch.joiningStart),t+=ds(e.parameters),t}case"FETCH_OK":return z(e.requestId)+1+Yt(e.endLocation)+ds(e.parameters)+ls(e.trackProperties??e.trackExtensions??new Map);case"PUBLISH_NAMESPACE":return z(e.requestId)+st(e.trackNamespace)+ds(e.parameters);case"NAMESPACE":case"NAMESPACE_DONE":return st(e.trackNamespaceSuffix);case"PUBLISH_NAMESPACE_CANCEL":return z(e.requestId)+z(e.errorCode)+ts(e.errorReason);case"SUBSCRIBE_NAMESPACE":return z(e.requestId)+st(e.trackNamespacePrefix)+z(e.subscribeOptions)+ds(e.parameters);case"UNSUBSCRIBE_NAMESPACE":case"PUBLISH_NAMESPACE_OK":case"PUBLISH_NAMESPACE_ERROR":case"PUBLISH_ERROR":throw new Error(`Cannot encode draft-14-only message type "${e.type}" with draft-16 encoder`);case"SUBSCRIBE_TRACKS":case"PUBLISH_BLOCKED":throw new Error(`Cannot encode draft-18-only message type "${e.type}" with draft-16 encoder`)}}(e);if(s>65535)throw new RangeError(`Control message payload length ${s} exceeds maximum 65535 (uint16)`);const i=z(t),r=new Uint8Array(i+2+s);let n=0;return n+=J(t,r,n),r[n++]=s>>8&255,r[n++]=255&s,n+=function(e,t,s){let i=s;switch(e.type){case"CLIENT_SETUP":case"SERVER_SETUP":i+=hs(e.parameters,t,i);break;case"GOAWAY":{const s=(new TextEncoder).encode(e.newSessionUri);i+=J(Q(s.length),t,i),t.set(s,i),i+=s.length;break}case"MAX_REQUEST_ID":i+=J(e.maxRequestId,t,i);break;case"REQUESTS_BLOCKED":i+=J(e.maximumRequestId,t,i);break;case"REQUEST_OK":case"PUBLISH_OK":i+=J(e.requestId,t,i),i+=hs(e.parameters,t,i);break;case"REQUEST_ERROR":i+=J(e.requestId,t,i),i+=J(e.errorCode,t,i),i+=J(e.retryInterval,t,i),i+=es(e.errorReason,t,i);break;case"SUBSCRIBE":case"TRACK_STATUS":i+=J(e.requestId,t,i),i+=tt(e.trackNamespace,t,i),i+=gs(e.trackName,t,i),i+=hs(e.parameters,t,i);break;case"SUBSCRIBE_OK":i+=J(e.requestId,t,i),i+=J(e.trackAlias,t,i),i+=hs(e.parameters,t,i),i+=ps(e.trackProperties??e.trackExtensions??new Map,t,i);break;case"REQUEST_UPDATE":i+=J(e.requestId,t,i),i+=J(e.existingRequestId,t,i),i+=hs(e.parameters,t,i);break;case"UNSUBSCRIBE":case"FETCH_CANCEL":case"PUBLISH_NAMESPACE_DONE":i+=J(e.requestId,t,i);break;case"PUBLISH":i+=J(e.requestId,t,i),i+=tt(e.trackNamespace,t,i),i+=gs(e.trackName,t,i),i+=J(e.trackAlias,t,i),i+=hs(e.parameters,t,i),i+=ps(e.trackProperties??e.trackExtensions??new Map,t,i);break;case"PUBLISH_DONE":i+=J(e.requestId,t,i),i+=J(e.statusCode,t,i),i+=J(e.streamCount,t,i),i+=es(e.errorReason,t,i);break;case"FETCH":i+=J(e.requestId,t,i),i+=J(Q(e.fetch.fetchType),t,i),1===e.fetch.fetchType?(i+=tt(e.fetch.trackNamespace,t,i),i+=gs(e.fetch.trackName,t,i),i+=zt(e.fetch.startLocation,t,i),i+=zt(e.fetch.endLocation,t,i)):(i+=J(e.fetch.joiningRequestId,t,i),i+=J(e.fetch.joiningStart,t,i)),i+=hs(e.parameters,t,i);break;case"FETCH_OK":i+=J(e.requestId,t,i),t[i++]=255&e.endOfTrack,i+=zt(e.endLocation,t,i),i+=hs(e.parameters,t,i),i+=ps(e.trackProperties??e.trackExtensions??new Map,t,i);break;case"PUBLISH_NAMESPACE":i+=J(e.requestId,t,i),i+=tt(e.trackNamespace,t,i),i+=hs(e.parameters,t,i);break;case"NAMESPACE":case"NAMESPACE_DONE":i+=tt(e.trackNamespaceSuffix,t,i);break;case"PUBLISH_NAMESPACE_CANCEL":i+=J(e.requestId,t,i),i+=J(e.errorCode,t,i),i+=es(e.errorReason,t,i);break;case"SUBSCRIBE_NAMESPACE":i+=J(e.requestId,t,i),i+=tt(e.trackNamespacePrefix,t,i),i+=J(e.subscribeOptions,t,i),i+=hs(e.parameters,t,i);break;case"UNSUBSCRIBE_NAMESPACE":case"PUBLISH_NAMESPACE_OK":case"PUBLISH_NAMESPACE_ERROR":case"PUBLISH_ERROR":throw new Error(`Cannot encode draft-14-only message type "${e.type}" with draft-16 encoder`);case"SUBSCRIBE_TRACKS":case"PUBLISH_BLOCKED":throw new Error(`Cannot encode draft-18-only message type "${e.type}" with draft-16 encoder`)}return i-s}(e,r,n),r}function ds(e){const t=ns(e);return z(Q(Wt(t)))+Kt(t)}function hs(e,t,s){let i=s;const r=ns(e);return i+=J(Q(Wt(r)),t,i),i+=jt(r,t,i),i-s}const us=e=>e;function ls(e){return 0===e.size?0:Kt(us(e))}function ps(e,t,s){return 0===e.size?0:jt(us(e),t,s)}function ms(e){return Ze(e)}function gs(e,t,s){return Xe(e,t,s)}function fs(e,t=0){let s=t;const{value:i,bytesRead:r}=Y(e,s);if(s+=r,s+2>e.length)throw new RangeError("Buffer too short for message length field");const n=e[s]<<8|e[s+1];s+=2;const a=s+n;if(a>e.length)throw new RangeError(`Buffer too short for message payload: need ${n} bytes, have ${e.length-s}`);const o=function(e,t,s,i){const r=vs.get(e);if(void 0===r)throw new ze(`Unknown message type: 0x${e.toString(16)}`);const{message:n,finalPos:a}=function(e,t,s,i){let r=s;switch(e){case"CLIENT_SETUP":case"SERVER_SETUP":{const{value:s,bytesRead:i}=bs(t,r);return r+=i,{message:{type:e,parameters:s},finalPos:r}}case"SETUP":throw new Error("SETUP is a draft-18 message; not produced by the draft-14/16 codec");case"GOAWAY":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const i=Number(e);if(i>8192)throw new RangeError(`GOAWAY URI length ${i} exceeds maximum 8192 bytes`);const n=t.slice(r,r+i);r+=i;return{message:{type:"GOAWAY",newSessionUri:(new TextDecoder).decode(n)},finalPos:r}}case"MAX_REQUEST_ID":{const{value:e,bytesRead:s}=Y(t,r);return r+=s,{message:{type:"MAX_REQUEST_ID",maxRequestId:e},finalPos:r}}case"REQUESTS_BLOCKED":{const{value:e,bytesRead:s}=Y(t,r);return r+=s,{message:{type:"REQUESTS_BLOCKED",maximumRequestId:e},finalPos:r}}case"REQUEST_OK":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:i,bytesRead:n}=bs(t,r);return r+=n,{message:{type:"REQUEST_OK",requestId:e,parameters:i},finalPos:r}}case"REQUEST_ERROR":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:i,bytesRead:n}=Y(t,r);r+=n;const{value:a,bytesRead:o}=Y(t,r);r+=o;const{value:c,bytesRead:d}=Zt(t,r);return r+=d,{message:{type:"REQUEST_ERROR",requestId:e,errorCode:i,retryInterval:a,errorReason:c},finalPos:r}}case"SUBSCRIBE":case"TRACK_STATUS":{const{value:s,bytesRead:i}=Y(t,r);r+=i;const{value:n,bytesRead:a}=et(t,r);r+=a;const{value:o,bytesRead:c}=_s(t,r);r+=c,ut(n,o);const{value:d,bytesRead:h}=bs(t,r);return r+=h,{message:{type:e,requestId:s,trackNamespace:n,trackName:o,parameters:d},finalPos:r}}case"SUBSCRIBE_OK":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:n,bytesRead:a}=Y(t,r);r+=a;const{value:o,bytesRead:c}=bs(t,r);r+=c;const{value:d,bytesRead:h}=Ss(t,r,i);return r+=h,{message:{type:"SUBSCRIBE_OK",requestId:e,trackAlias:n,parameters:o,trackExtensions:d},finalPos:r}}case"REQUEST_UPDATE":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:i,bytesRead:n}=Y(t,r);r+=n;const{value:a,bytesRead:o}=bs(t,r);return r+=o,{message:{type:"REQUEST_UPDATE",requestId:e,existingRequestId:i,parameters:a},finalPos:r}}case"UNSUBSCRIBE":{const{value:e,bytesRead:s}=Y(t,r);return r+=s,{message:{type:"UNSUBSCRIBE",requestId:e},finalPos:r}}case"PUBLISH":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:n,bytesRead:a}=et(t,r);r+=a;const{value:o,bytesRead:c}=_s(t,r);r+=c,ut(n,o);const{value:d,bytesRead:h}=Y(t,r);r+=h;const{value:u,bytesRead:l}=bs(t,r);r+=l;const{value:p,bytesRead:m}=Ss(t,r,i);return r+=m,{message:{type:"PUBLISH",requestId:e,trackNamespace:n,trackName:o,trackAlias:d,parameters:u,trackExtensions:p},finalPos:r}}case"PUBLISH_OK":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:i,bytesRead:n}=bs(t,r);return r+=n,{message:{type:"PUBLISH_OK",requestId:e,parameters:i},finalPos:r}}case"PUBLISH_DONE":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:i,bytesRead:n}=Y(t,r);r+=n;const{value:a,bytesRead:o}=Y(t,r);r+=o;const{value:c,bytesRead:d}=Zt(t,r);return r+=d,{message:{type:"PUBLISH_DONE",requestId:e,statusCode:i,streamCount:a,errorReason:c},finalPos:r}}case"FETCH":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:i,bytesRead:n}=Y(t,r);let a;if(r+=n,0x1n===i){const{value:e,bytesRead:s}=et(t,r);r+=s;const{value:i,bytesRead:n}=_s(t,r);r+=n,ut(e,i);const{value:o,bytesRead:c}=Qt(t,r);r+=c;const{value:d,bytesRead:h}=Qt(t,r);r+=h,a={fetchType:1,trackNamespace:e,trackName:i,startLocation:o,endLocation:d}}else{if(0x2n!==i&&0x3n!==i)throw new ze(`Invalid Fetch Type: 0x${i.toString(16)}`);{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:n,bytesRead:o}=Y(t,r);r+=o,a={fetchType:Number(i),joiningRequestId:e,joiningStart:n}}}const{value:o,bytesRead:c}=bs(t,r);return r+=c,{message:{type:"FETCH",requestId:e,fetch:a,parameters:o},finalPos:r}}case"FETCH_OK":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:n}=Ye(t,r);r+=1;const{value:a,bytesRead:o}=Qt(t,r);r+=o;const{value:c,bytesRead:d}=bs(t,r);r+=d;const{value:h,bytesRead:u}=Ss(t,r,i);return r+=u,{message:{type:"FETCH_OK",requestId:e,endOfTrack:n,endLocation:a,parameters:c,trackExtensions:h},finalPos:r}}case"FETCH_CANCEL":{const{value:e,bytesRead:s}=Y(t,r);return r+=s,{message:{type:"FETCH_CANCEL",requestId:e},finalPos:r}}case"PUBLISH_NAMESPACE":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:i,bytesRead:n}=et(t,r);r+=n,at(i);const{value:a,bytesRead:o}=bs(t,r);return r+=o,{message:{type:"PUBLISH_NAMESPACE",requestId:e,trackNamespace:i,parameters:a},finalPos:r}}case"NAMESPACE":{const{value:e,bytesRead:s}=et(t,r);return r+=s,lt(e),{message:{type:"NAMESPACE",trackNamespaceSuffix:e},finalPos:r}}case"PUBLISH_NAMESPACE_DONE":{const{value:e,bytesRead:s}=Y(t,r);return r+=s,{message:{type:"PUBLISH_NAMESPACE_DONE",requestId:e},finalPos:r}}case"NAMESPACE_DONE":{const{value:e,bytesRead:s}=et(t,r);return r+=s,lt(e),{message:{type:"NAMESPACE_DONE",trackNamespaceSuffix:e},finalPos:r}}case"PUBLISH_NAMESPACE_CANCEL":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:i,bytesRead:n}=Y(t,r);r+=n;const{value:a,bytesRead:o}=Zt(t,r);return r+=o,{message:{type:"PUBLISH_NAMESPACE_CANCEL",requestId:e,errorCode:i,errorReason:a},finalPos:r}}case"SUBSCRIBE_NAMESPACE":{const{value:e,bytesRead:s}=Y(t,r);r+=s;const{value:i,bytesRead:n}=et(t,r);r+=n,ht(i);const{value:a,bytesRead:o}=Y(t,r);r+=o;const{value:c,bytesRead:d}=bs(t,r);return r+=d,{message:{type:"SUBSCRIBE_NAMESPACE",requestId:e,trackNamespacePrefix:i,subscribeOptions:a,parameters:c},finalPos:r}}case"UNSUBSCRIBE_NAMESPACE":case"PUBLISH_NAMESPACE_OK":case"PUBLISH_NAMESPACE_ERROR":case"PUBLISH_ERROR":throw new ze(`Draft-14-only message type "${e}" cannot be decoded by draft-16 decoder`);case"SUBSCRIBE_TRACKS":case"PUBLISH_BLOCKED":throw new ze(`Draft-18-only message type "${e}" cannot be decoded by draft-16 decoder`)}}(r,t,s,i);if(a!==i)throw new RangeError(`Payload not fully consumed for ${r}: consumed ${a-s} bytes, expected ${i-s}`);return n}(i,e,s,a);return{message:o,bytesRead:r+2+n}}function bs(e,t){let s=t;const{value:i,bytesRead:r}=Y(e,s);s+=r;const{value:n,bytesRead:a}=function(e,t,s){return Vt(e,t,s,"d16-delta-varint")}(e,s,Number(i));return s+=a,{value:n,bytesRead:s-t}}function Ss(e,t,s){if(s-t<=0)return{value:new Map,bytesRead:0};const i=new Map;let r=t,n=0n;for(;r65535)throw new RangeError(`Track extension byte value length ${t.length} exceeds maximum 65535 (2^16-1)`);r+=s,c=t}const d=i.get(o);d?d.push(c):i.set(o,[c])}return{value:i,bytesRead:r-t}}function _s(e,t){return Je(e,t)}const vs=new Map;for(const[e,t]of Object.entries(ss))vs.set(t,e);const ys=32,Es=3,Ts=2,ws=17,Rs=20,Cs=10,Is=22,As=23,ks=13,Os=7,Ps=8,Ns=33,Us=4,Ms=5,Ls=24,Ds=25,Bs=14,xs=15,Fs=18,qs=19,$s=6,Hs=9,Vs=12,Gs=11,js=16,Ks=21,Ws=26,Qs=29,zs=30,Ys=31,Js=new Set([Qs,zs,Ys]);class Xs{version=14;encode(e){switch(e.type){case"CLIENT_SETUP":return this.encodeClientSetup(e);case"SERVER_SETUP":return this.encodeServerSetup(e);case"SUBSCRIBE":return this.encodeSubscribe(e);case"REQUEST_UPDATE":return this.encodeSubscribeUpdate(e);case"SUBSCRIBE_NAMESPACE":return this.encodeSubscribeNamespace(e);case"UNSUBSCRIBE_NAMESPACE":return this.encodeUnsubscribeNamespace(e);case"UNSUBSCRIBE":return this.encodeSimpleRequestId(Cs,e.requestId);case"FETCH":return this.encodeFetch(e);case"FETCH_CANCEL":return this.encodeSimpleRequestId(As,e.requestId);case"TRACK_STATUS":return this.encodeTrackStatus(e);case"PUBLISH_NAMESPACE":return this.encodePublishNamespace(e);case"PUBLISH_NAMESPACE_OK":return this.encodeSimpleRequestId(Os,e.requestId);case"PUBLISH_NAMESPACE_ERROR":return this.encodePublishNamespaceError(e);case"PUBLISH_OK":return this.encodePublishOk(e);case"PUBLISH_ERROR":return this.encodePublishError(e);case"SUBSCRIBE_OK":return this.encodeSubscribeOk(e);case"PUBLISH_DONE":return this.encodePublishDone(e);case"PUBLISH_NAMESPACE_DONE":return this.encodeNamespaceTuple(Hs,e.trackNamespace);case"REQUEST_ERROR":return this.encodeRequestError(e);case"REQUEST_OK":throw new Error("Draft-14 does not have generic REQUEST_OK — use specific OK types");default:throw new Error(`Draft14Codec cannot encode message type "${e.type}"`)}}decode(e,t){let s=t;const{value:i,bytesRead:r}=Y(e,s);s+=r;const n=Number(i);let a,o;if(Js.has(n)){const{value:t,bytesRead:i}=Y(e,s);s+=i,a=Number(t),o=r+i}else{if(s+2>e.length)throw new RangeError("Buffer too short for message length field");a=e[s]<<8|e[s+1],s+=2,o=r+2}const c=s+a;if(c>e.length)throw new RangeError(`Buffer too short: need ${a} bytes, have ${e.length-s}`);return{message:this.decodePayload(n,e,s,c),bytesRead:o+a}}peekFrameSize(e){if(0===e.length)return;const t=1<<(e[0]>>6);if(e.length>6);if(e.length>8&255,r[n++]=255&t.length,r.set(t,n),r}writeParams(e,t,s){let i=s;const r=ns(e);return i+=J(Q(Wt(r)),t,i),i+=function(e,t,s){return Gt(e,t,s,"d14-absolute-varint")}(r,t,i),i-s}paramsLength(e){const t=ns(e);return z(Q(Wt(t)))+function(e){return Pt(Ht(e),"d14-absolute-varint")}(t)}assertUint8(e,t,s){if(!Number.isInteger(e)||e<0||e>255)throw new ze(`${s}: ${t} must be 0-255 for 8-bit wire encoding, got ${e}`)}encodeSimpleRequestId(e,t){const s=z(t),i=new Uint8Array(s);return J(t,i,0),this.frame16(e,i)}encodeClientSetup(e){const t=Q(4278190094),s=z(Q(1))+z(t)+this.paramsLength(e.parameters),i=new Uint8Array(s);let r=0;return r+=J(Q(1),i,r),r+=J(t,i,r),r+=this.writeParams(e.parameters,i,r),this.frame16(ys,i)}encodeServerSetup(e){const t=Q(4278190094),s=z(t)+this.paramsLength(e.parameters),i=new Uint8Array(s);let r=0;return r+=J(t,i,r),r+=this.writeParams(e.parameters,i,r),this.frame16(Ns,i)}encodeRequestError(e){const t={SUBSCRIBE:Ms,FETCH:Ds,TRACK_STATUS:xs,SUBSCRIBE_NAMESPACE:qs};if(void 0===e.requestKind)throw new Error("Draft-14 does not have generic REQUEST_ERROR — use specific error types");const s=t[e.requestKind],i=z(e.requestId)+z(e.errorCode)+ts(e.errorReason),r=new Uint8Array(i);let n=0;return n+=J(e.requestId,r,n),n+=J(e.errorCode,r,n),n+=es(e.errorReason,r,n),this.frame16(s,r)}encodeSubscribe(e){at(e.trackNamespace);const t=Number(this.extractParamVarint(e.parameters,rs.SUBSCRIBER_PRIORITY)??128n),s=Number(this.extractParamVarint(e.parameters,rs.GROUP_ORDER)??0n),i=Number(this.extractParamVarint(e.parameters,rs.FORWARD)??1n);this.assertUint8(t,"SUBSCRIBER_PRIORITY","SUBSCRIBE"),this.assertUint8(s,"GROUP_ORDER","SUBSCRIBE"),this.assertUint8(i,"FORWARD","SUBSCRIBE");const r=this.extractFilter(e.parameters),n=this.cloneParamsWithout(e.parameters,[rs.SUBSCRIBER_PRIORITY,rs.GROUP_ORDER,rs.FORWARD,rs.SUBSCRIPTION_FILTER]);let a=0;r.startLocation&&(a+=Yt(r.startLocation)),void 0!==r.endGroup&&(a+=z(r.endGroup));const o=z(e.requestId)+st(e.trackNamespace)+Ze(e.trackName)+1+1+1+z(r.filterType)+a+this.paramsLength(n),c=new Uint8Array(o);let d=0;return d+=J(e.requestId,c,d),d+=tt(e.trackNamespace,c,d),d+=Xe(e.trackName,c,d),c[d++]=255&t,c[d++]=255&s,c[d++]=255&i,d+=J(r.filterType,c,d),r.startLocation&&(d+=zt(r.startLocation,c,d)),void 0!==r.endGroup&&(d+=J(r.endGroup,c,d)),d+=this.writeParams(n,c,d),this.frame16(Es,c)}encodeFetch(e){1===e.fetch.fetchType&&at(e.fetch.trackNamespace);const t=Number(this.extractParamVarint(e.parameters,rs.SUBSCRIBER_PRIORITY)??128n),s=Number(this.extractParamVarint(e.parameters,rs.GROUP_ORDER)??0n);this.assertUint8(t,"SUBSCRIBER_PRIORITY","FETCH"),this.assertUint8(s,"GROUP_ORDER","FETCH");const i=this.cloneParamsWithout(e.parameters,[rs.SUBSCRIBER_PRIORITY,rs.GROUP_ORDER]);let r=z(Q(e.fetch.fetchType));1===e.fetch.fetchType?r+=st(e.fetch.trackNamespace)+Ze(e.fetch.trackName)+Yt(e.fetch.startLocation)+Yt(e.fetch.endLocation):r+=z(e.fetch.joiningRequestId)+z(e.fetch.joiningStart);const n=z(e.requestId)+1+1+r+this.paramsLength(i),a=new Uint8Array(n);let o=0;return o+=J(e.requestId,a,o),a[o++]=255&t,a[o++]=255&s,o+=J(Q(e.fetch.fetchType),a,o),1===e.fetch.fetchType?(o+=tt(e.fetch.trackNamespace,a,o),o+=Xe(e.fetch.trackName,a,o),o+=zt(e.fetch.startLocation,a,o),o+=zt(e.fetch.endLocation,a,o)):(o+=J(e.fetch.joiningRequestId,a,o),o+=J(e.fetch.joiningStart,a,o)),o+=this.writeParams(i,a,o),this.frame16(Is,a)}encodeTrackStatus(e){at(e.trackNamespace);const t=z(e.requestId)+st(e.trackNamespace)+Ze(e.trackName)+this.paramsLength(e.parameters),s=new Uint8Array(t);let i=0;return i+=J(e.requestId,s,i),i+=tt(e.trackNamespace,s,i),i+=Xe(e.trackName,s,i),i+=this.writeParams(e.parameters,s,i),this.frame16(ks,s)}encodeSubscribeNamespace(e){ht(e.trackNamespacePrefix);const t=z(e.requestId)+st(e.trackNamespacePrefix)+this.paramsLength(e.parameters),s=new Uint8Array(t);let i=0;return i+=J(e.requestId,s,i),i+=tt(e.trackNamespacePrefix,s,i),i+=this.writeParams(e.parameters,s,i),this.frame16(ws,s)}encodeUnsubscribeNamespace(e){ht(e.trackNamespacePrefix);const t=st(e.trackNamespacePrefix),s=new Uint8Array(t);return tt(e.trackNamespacePrefix,s,0),this.frame16(Rs,s)}encodePublishNamespace(e){const t=z(e.requestId)+st(e.trackNamespace)+this.paramsLength(e.parameters),s=new Uint8Array(t);let i=0;return i+=J(e.requestId,s,i),i+=tt(e.trackNamespace,s,i),i+=this.writeParams(e.parameters,s,i),this.frame16($s,s)}encodeNamespaceTuple(e,t){const s=st(t),i=new Uint8Array(s);return tt(t,i,0),this.frame16(e,i)}encodePublishNamespaceError(e){const t=z(e.requestId)+z(e.errorCode)+ts(e.errorReason),s=new Uint8Array(t);let i=0;return i+=J(e.requestId,s,i),i+=J(e.errorCode,s,i),i+=es(e.errorReason,s,i),this.frame16(Ps,s)}decodePayload(e,t,s,i){let r=s;switch(e){case ys:{const{value:e,bytesRead:s}=Y(t,r);r+=s;for(let s=0;s0n?d-1n:0);if(d>0n){const e=new Uint8Array(z(Q(4))+Yt(o)+z(g));let t=J(Q(4),e,0);t+=zt(o,e,t),J(g,e,t),p.set(rs.SUBSCRIPTION_FILTER,[e])}else if(o.group>0n||o.object>0n){const e=new Uint8Array(z(Q(3))+Yt(o));zt(o,e,J(Q(3),e,0)),p.set(rs.SUBSCRIPTION_FILTER,[e])}return this.assertConsumed(r,i,"SUBSCRIBE_UPDATE"),{type:"REQUEST_UPDATE",requestId:e,existingRequestId:n,parameters:p}}case zs:{const{value:e,bytesRead:s}=Y(t,r);r+=s;const n=t[r++],a=t[r++],o=t[r++],{value:c,bytesRead:d}=Y(t,r);let h,u;if(r+=d,0x3n===c||0x4n===c){const{value:e,bytesRead:s}=Qt(t,r);r+=s,h=e}if(0x4n===c){const{value:e,bytesRead:s}=Y(t,r);r+=s,u=e}const{value:l,bytesRead:p}=this.readParams(t,r);r+=p,l.set(rs.FORWARD,[Q(n)]),l.set(rs.SUBSCRIBER_PRIORITY,[Q(a)]),l.set(rs.GROUP_ORDER,[Q(o)]);const m=this.encodeFilterBytes(Q(c),h,u);return l.set(rs.SUBSCRIPTION_FILTER,[m]),this.assertConsumed(r,i,"PUBLISH_OK"),{type:"PUBLISH_OK",requestId:e,parameters:l}}default:throw new ze(`Unknown draft-14 message type: 0x${e.toString(16)}`)}}readParams(e,t){let s=t;const{value:i,bytesRead:r}=Y(e,s);s+=r;const{value:n,bytesRead:a}=function(e,t,s){return Vt(e,t,s,"d14-absolute-varint")}(e,s,Number(i));return s+=a,{value:n,bytesRead:s-t}}assertConsumed(e,t,s){if(e!==t)throw new RangeError(`Payload not fully consumed for ${s}: consumed ${e} bytes, expected ${t}`)}extractParamVarint(e,t){const s=e.get(t);if(s&&0!==s.length)return s[0]}encodeFilterBytes(e,t,s){let i=z(e);t&&(i+=Yt(t)),void 0!==s&&(i+=z(s));const r=new Uint8Array(i);let n=J(e,r,0);return t&&(n+=zt(t,r,n)),void 0!==s&&J(s,r,n),r}cloneParamsWithout(e,t){const s=new Map,i=new Set(t.map(e=>e));for(const[t,r]of e)i.has(t)||s.set(t,r);return s}extractFilter(e){const t=e.get(rs.SUBSCRIPTION_FILTER);if(!t||0===t.length)return{filterType:Q(1)};const s=t[0];if("bigint"==typeof s)return{filterType:s};const i=s;let r=0;const{value:n,bytesRead:a}=Y(i,r);let o,c;if(r+=a,0x3n===n||0x4n===n){const{value:e,bytesRead:t}=Qt(i,r);r+=t,o=e}if(0x4n===n){const{value:e,bytesRead:t}=Y(i,r);r+=t,c=e}const d={filterType:Q(n)};return void 0!==o&&(d.startLocation=o),void 0!==c&&(d.endGroup=c),d}encodeSubscribeUpdate(e){const t=Number(this.extractParamVarint(e.parameters,rs.SUBSCRIBER_PRIORITY)??128n),s=Number(this.extractParamVarint(e.parameters,rs.FORWARD)??1n);this.assertUint8(t,"SUBSCRIBER_PRIORITY","SUBSCRIBE_UPDATE"),this.assertUint8(s,"FORWARD","SUBSCRIBE_UPDATE");const i=this.extractFilter(e.parameters),r=i.startLocation??{group:Q(0),object:Q(0)},n=i.endGroup??Q(0),a=Q(0n===n?0:n+1n),o=this.cloneParamsWithout(e.parameters,[rs.SUBSCRIBER_PRIORITY,rs.FORWARD,rs.SUBSCRIPTION_FILTER]),c=z(e.requestId)+z(e.existingRequestId)+Yt(r)+z(a)+1+1+this.paramsLength(o),d=new Uint8Array(c);let h=0;return h+=J(e.requestId,d,h),h+=J(e.existingRequestId,d,h),h+=zt(r,d,h),h+=J(a,d,h),d[h++]=255&t,d[h++]=255&s,h+=this.writeParams(o,d,h),this.frame16(Ts,d)}frameVarint(e,t){const s=Q(e),i=z(s),r=Q(t.length),n=i+z(r)+t.length,a=new Uint8Array(n);let o=0;return o+=J(s,a,o),o+=J(r,a,o),a.set(t,o),a}encodePublishOk(e){const t=Number(this.extractParamVarint(e.parameters,rs.FORWARD)??1n),s=Number(this.extractParamVarint(e.parameters,rs.SUBSCRIBER_PRIORITY)??128n),i=Number(this.extractParamVarint(e.parameters,rs.GROUP_ORDER)??1n);this.assertUint8(t,"FORWARD","PUBLISH_OK"),this.assertUint8(s,"SUBSCRIBER_PRIORITY","PUBLISH_OK"),this.assertUint8(i,"GROUP_ORDER","PUBLISH_OK");const r=this.extractFilter(e.parameters),n=r.filterType,a=new Map(e.parameters);a.delete(Q(rs.FORWARD)),a.delete(Q(rs.SUBSCRIBER_PRIORITY)),a.delete(Q(rs.GROUP_ORDER)),a.delete(Q(rs.SUBSCRIPTION_FILTER));let o=z(n);r.startLocation&&(o+=Yt(r.startLocation)),void 0!==r.endGroup&&(o+=z(r.endGroup));const c=z(e.requestId)+1+1+1+o+this.paramsLength(a),d=new Uint8Array(c);let h=0;return h+=J(e.requestId,d,h),d[h++]=255&t,d[h++]=255&s,d[h++]=255&i,h+=J(n,d,h),r.startLocation&&(h+=zt(r.startLocation,d,h)),void 0!==r.endGroup&&(h+=J(r.endGroup,d,h)),h+=this.writeParams(a,d,h),this.frameVarint(zs,d)}encodePublishError(e){const t=z(e.requestId)+z(e.errorCode)+ts(e.errorReason),s=new Uint8Array(t);let i=0;return i+=J(e.requestId,s,i),i+=J(e.errorCode,s,i),i+=es(e.errorReason,s,i),this.frameVarint(Ys,s)}encodeSubscribeOk(e){const t=Number(e.parameters.get(rs.GROUP_ORDER)?.[0]??1n),s=e.parameters.get(rs.EXPIRES)?.[0],i=Q("bigint"==typeof s?s:0n),r=e.parameters.get(rs.LARGEST_OBJECT)?.[0],n=void 0!==r?1:0,a=new Map;for(const[t,s]of e.parameters)t!==rs.GROUP_ORDER&&t!==rs.EXPIRES&&t!==rs.LARGEST_OBJECT&&a.set(t,s);let o=z(e.requestId)+z(e.trackAlias)+z(i)+1+1;1===n&&r instanceof Uint8Array&&(o+=r.byteLength);let c=z(Q(BigInt(a.size)));for(const[e,t]of a)for(const s of t)if(c+=z(e),"bigint"==typeof s)c+=z(Q(z(s))),c+=z(s);else{if(!(s instanceof Uint8Array))throw new ze("Location-valued parameter cannot be encoded as draft-14 KVP");c+=z(Q(BigInt(s.byteLength))),c+=s.byteLength}o+=c;const d=new Uint8Array(o);let h=0;return h+=J(e.requestId,d,h),h+=J(e.trackAlias,d,h),h+=J(i,d,h),d[h++]=255&t,d[h++]=n,1===n&&r instanceof Uint8Array&&(d.set(r,h),h+=r.byteLength),h+=this.writeParams(a,d,h),this.frame16(Us,d)}encodePublishDone(e){const t=z(e.requestId)+z(e.statusCode)+z(e.streamCount)+ts(e.errorReason),s=new Uint8Array(t);let i=0;return i+=J(e.requestId,s,i),i+=J(e.statusCode,s,i),i+=J(e.streamCount,s,i),i+=es(e.errorReason,s,i),this.frame16(Gs,s)}}function Zs(e){return e.trackProperties??e.trackExtensions??new Map}function ei(e){return Z(BigInt(e.length))+e.length}function ti(e,t,s){let i=s+te(BigInt(e.length),t,s);return t.set(e,i),i+e.length-s}function si(e,t){const{value:s,bytesRead:i}=ee(e,t),r=t+i,n=Number(s);if(r+n>e.length)throw new ze("vi64 length-prefixed bytes exceed buffer");return{value:e.slice(r,r+n),bytesRead:i+n}}function ii(e){let t=Z(BigInt(e.length));for(const s of e)t+=ei(s);return t}function ri(e,t,s){let i=s+te(BigInt(e.length),t,s);for(const s of e)i+=ti(s,t,i);return i-s}function ni(e,t){let s=t;const{value:i,bytesRead:r}=ee(e,s);s+=r;const n=[];for(let t=0n;tpi)throw new ze(`Reason Phrase length ${t.length} exceeds maximum 1024 bytes`);return ei(t)}function gi(e,t,s){const i=hi.encode(e);if(i.length>pi)throw new ze(`Reason Phrase length ${i.length} exceeds maximum 1024 bytes`);return ti(i,t,s)}function fi(e,t){const{value:s,bytesRead:i}=si(e,t);if(s.length>pi)throw new ze(`Reason Phrase length ${s.length} exceeds maximum 1024 bytes`);return{value:ui.decode(s),bytesRead:i}}const bi=new Set([BigInt(ve),BigInt(Te),BigInt(Ee),BigInt(we)]);function Si(e,t){if(e%2n==0n){if("bigint"!=typeof t)throw new ze(`Setup Option 0x${e.toString(16)} (even) requires a vi64 value`);return Z(t)}if(!(t instanceof Uint8Array))throw new ze(`Setup Option 0x${e.toString(16)} (odd) requires a byte value`);return ei(t)}function _i(e,t,s,i){return e%2n==0n?te(t,s,i):ti(t,s,i)}function vi(e){const t=new Map;let s=0,i=0n;for(;sX)throw new ze(`Setup Option type ${n} exceeds 2^64-1`);let a;if(i=n,n%2n==0n){const t=ee(e,s);s+=t.bytesRead,a=t.value}else{const t=si(e,s);s+=t.bytesRead,a=t.value}const o=t.get(n);o?o.push(a):t.set(n,[a])}return t}function yi(e,t){const s=mt.get(e);if(void 0===s)throw new ze(`Unknown draft-18 message parameter 0x${e.toString(16)}`);switch(s){case"uint8":if("bigint"!=typeof t)throw new ze(`Parameter 0x${e.toString(16)} expects uint8`);if(t<0n||t>255n)throw new ze(`Parameter 0x${e.toString(16)} uint8 value out of range (0..255): ${t}`);return{kind:"uint8",value:Number(t)};case"varint":if("bigint"!=typeof t)throw new ze(`Parameter 0x${e.toString(16)} expects varint`);if(t<0n||t>X)throw new ze(`Parameter 0x${e.toString(16)} varint value out of range (0..2^64-1): ${t}`);return{kind:"varint",value:t};case"bytes":if(!(t instanceof Uint8Array))throw new ze(`Parameter 0x${e.toString(16)} expects bytes`);return{kind:"bytes",value:t};case"location":if(!function(e){return!("object"!=typeof e||null===e||e instanceof Uint8Array||Array.isArray(e))}(t))throw new ze(`Parameter 0x${e.toString(16)} expects Location`);return{kind:"location",group:t.group,object:t.object};case"namespace":{if(!Array.isArray(t))throw new ze(`Parameter 0x${e.toString(16)} expects a Track Namespace tuple`);const s=t;if(!s.every(e=>e instanceof Uint8Array))throw new ze(`Parameter 0x${e.toString(16)} Track Namespace tuple has a non-Uint8Array field`);return{kind:"namespace",value:[...s]}}}}function Ei(e){const t=new Map;for(const[s,i]of e)t.set(s,i.map(e=>yi(s,e)));return t}function Ti(e){switch(e.kind){case"uint8":return BigInt(e.value);case"varint":case"bytes":case"namespace":return e.value;case"location":return{group:e.group,object:e.object}}}function wi(e){const t=new Map;for(const[s,i]of e)t.set(s,i.map(Ti));return t}const Ri=e=>{throw new ze(`Draft18Codec: ${e} is not yet implemented`)};class Ci{version=18;encode(e){switch(e.type){case"SETUP":return this.frame(_e,function(e){const t=[...e.entries()].sort(([e],[t])=>et?1:0),s=[];let i=0n,r=0;for(const[e,n]of t){if(bi.has(e)&&n.length>1)throw new ze(`Setup Option 0x${e.toString(16)} must not be repeated`);for(const t of n){const n=e-i;i=e,s.push({delta:n,type:e,value:t}),r+=Z(n)+Si(e,t)}}const n=new Uint8Array(r);let a=0;for(const{delta:e,type:t,value:i}of s)a+=te(e,n,a),a+=_i(t,i,n,a);return n}(e.setupOptions));case"SUBSCRIBE":return this.frame(ie,this.encodeSubscribe(e));case"REQUEST_UPDATE":return this.frame(se,this.encodeRequestUpdate(e));case"SUBSCRIBE_OK":return this.frame(re,this.encodeSubscribeOk(e));case"REQUEST_OK":return this.frame(oe,this.encodeRequestOk(e));case"REQUEST_ERROR":return this.frame(ne,this.encodeRequestError(e));case"FETCH":return this.frame(me,this.encodeFetch(e));case"FETCH_OK":return this.frame(ge,this.encodeFetchOk(e));case"TRACK_STATUS":return this.frame(he,this.encodeTrackStatus(e));case"PUBLISH_NAMESPACE":return this.frame(ae,this.encodePublishNamespace(e));case"PUBLISH":return this.frame(fe,this.encodePublish(e));case"PUBLISH_DONE":return this.frame(de,this.encodePublishDone(e));case"SUBSCRIBE_NAMESPACE":return this.frame(be,this.encodeSubscribeNamespace(e));case"SUBSCRIBE_TRACKS":return this.frame(Se,this.encodeNamespacePrefixRequest(e.requestId,e.trackNamespacePrefix,e.parameters));case"NAMESPACE":return this.frame(ce,ai(e.trackNamespaceSuffix));case"NAMESPACE_DONE":return this.frame(ue,ai(e.trackNamespaceSuffix));case"PUBLISH_BLOCKED":return this.frame(le,this.encodePublishBlocked(e));case"GOAWAY":return this.frame(pe,this.encodeGoaway(e));case"PUBLISH_NAMESPACE_DONE":throw new ze("Draft18Codec: PUBLISH_NAMESPACE_DONE was removed in draft-18");default:return Ri(`encode of ${e.type}`)}}decode(e,t){const{value:s,bytesRead:i}=ee(e,t),r=t+i;if(r+2>e.length)throw new ze("draft-18 control frame: truncated length");const n=e[r]<<8|e[r+1],a=r+2;if(a+n>e.length)throw new ze("draft-18 control frame: truncated payload");const o=e.subarray(a,a+n),c=i+2+n;switch(Number(s)){case _e:return{message:{type:"SETUP",setupOptions:vi(o)},bytesRead:c};case ie:return{message:this.decodeSubscribe(o),bytesRead:c};case se:return{message:this.decodeRequestUpdate(o),bytesRead:c};case re:return{message:this.decodeSubscribeOk(o),bytesRead:c};case oe:return{message:this.decodeRequestOk(o),bytesRead:c};case ne:return{message:this.decodeRequestError(o),bytesRead:c};case me:return{message:this.decodeFetch(o),bytesRead:c};case ge:return{message:this.decodeFetchOk(o),bytesRead:c};case he:return{message:this.decodeTrackStatus(o),bytesRead:c};case ae:return{message:this.decodePublishNamespace(o),bytesRead:c};case fe:return{message:this.decodePublish(o),bytesRead:c};case de:return{message:this.decodePublishDone(o),bytesRead:c};case be:return{message:this.decodeSubscribeNamespace(o),bytesRead:c};case Se:return{message:this.decodeSubscribeTracks(o),bytesRead:c};case ce:return{message:this.decodeNamespaceSuffix("NAMESPACE",o),bytesRead:c};case ue:return{message:this.decodeNamespaceSuffix("NAMESPACE_DONE",o),bytesRead:c};case le:return{message:this.decodePublishBlocked(o),bytesRead:c};case pe:return{message:this.decodeGoaway(o),bytesRead:c};default:return Ri(`decode of type 0x${s.toString(16)}`)}}peekFrameSize(e){let t;try{t=ee(e,0)}catch{return}const s=t.bytesRead+2;if(e.length65535)throw new ze("draft-18 control payload exceeds 2^16-1");const s=new Uint8Array(Z(BigInt(e))+2+t.length);let i=te(BigInt(e),s,0);return s[i++]=t.length>>8&255,s[i++]=255&t.length,s.set(t,i),s}encodeSubscribe(e){ut(e.trackNamespace,e.trackName,{allowEmptyNamespace:!0});const t=Ei(e.parameters),s=Z(e.requestId)+ii(e.trackNamespace)+ei(e.trackName)+vt(t),i=new Uint8Array(s);let r=te(e.requestId,i,0);return r+=ri(e.trackNamespace,i,r),r+=ti(e.trackName,i,r),i.set(yt(t),r),i}decodeSubscribe(e){let t=0;const s=ee(e,t);t+=s.bytesRead;const i=ni(e,t);t+=i.bytesRead;const r=si(e,t);t+=r.bytesRead;const n=Et(e,t,mt);if(t+=n.bytesRead,t!==e.length)throw new ze("SUBSCRIBE: unexpected trailing bytes after parameters");return ut(i.value,r.value,{allowEmptyNamespace:!0}),{type:"SUBSCRIBE",requestId:s.value,trackNamespace:i.value,trackName:r.value,parameters:wi(n.params)}}encodeTrackStatus(e){ut(e.trackNamespace,e.trackName,{allowEmptyNamespace:!0});const t=Ei(e.parameters),s=Z(e.requestId)+ii(e.trackNamespace)+ei(e.trackName)+vt(t),i=new Uint8Array(s);let r=te(e.requestId,i,0);return r+=ri(e.trackNamespace,i,r),r+=ti(e.trackName,i,r),i.set(yt(t),r),i}decodeTrackStatus(e){let t=0;const s=ee(e,t);t+=s.bytesRead;const i=ni(e,t);t+=i.bytesRead;const r=si(e,t);t+=r.bytesRead;const n=Et(e,t,mt);if(t+=n.bytesRead,t!==e.length)throw new ze("TRACK_STATUS: unexpected trailing bytes after parameters");return ut(i.value,r.value,{allowEmptyNamespace:!0}),{type:"TRACK_STATUS",requestId:s.value,trackNamespace:i.value,trackName:r.value,parameters:wi(n.params)}}encodePublishNamespace(e){at(e.trackNamespace,{allowEmpty:!0});const t=Ei(e.parameters),s=Z(e.requestId)+ii(e.trackNamespace)+vt(t),i=new Uint8Array(s);let r=te(e.requestId,i,0);return r+=ri(e.trackNamespace,i,r),i.set(yt(t),r),i}decodePublishNamespace(e){let t=0;const s=ee(e,t);t+=s.bytesRead;const i=ni(e,t);t+=i.bytesRead;const r=Et(e,t,mt);if(t+=r.bytesRead,t!==e.length)throw new ze("PUBLISH_NAMESPACE: unexpected trailing bytes after parameters");return at(i.value,{allowEmpty:!0}),{type:"PUBLISH_NAMESPACE",requestId:s.value,trackNamespace:i.value,parameters:wi(r.params)}}encodePublish(e){ut(e.trackNamespace,e.trackName,{allowEmptyNamespace:!0});const t=Ei(e.parameters),s=Z(e.requestId)+ii(e.trackNamespace)+ei(e.trackName)+Z(e.trackAlias)+vt(t)+xt(Zs(e)),i=new Uint8Array(s);let r=te(e.requestId,i,0);r+=ri(e.trackNamespace,i,r),r+=ti(e.trackName,i,r),r+=te(e.trackAlias,i,r);const n=yt(t);return i.set(n,r),r+=n.length,i.set(Ft(Zs(e)),r),i}decodePublish(e){let t=0;const s=ee(e,t);t+=s.bytesRead;const i=ni(e,t);t+=i.bytesRead;const r=si(e,t);t+=r.bytesRead;const n=ee(e,t);t+=n.bytesRead;const a=Et(e,t,mt);t+=a.bytesRead;const o=qt(e,t);return t+=o.bytesRead,ut(i.value,r.value,{allowEmptyNamespace:!0}),{type:"PUBLISH",requestId:s.value,trackNamespace:i.value,trackName:r.value,trackAlias:n.value,parameters:wi(a.params),trackProperties:o.properties,trackExtensions:o.properties}}encodePublishDone(e){const t=Z(e.statusCode)+Z(e.streamCount)+mi(e.errorReason),s=new Uint8Array(t);let i=te(e.statusCode,s,0);return i+=te(e.streamCount,s,i),gi(e.errorReason,s,i),s}decodePublishDone(e){let t=0;const s=ee(e,t);t+=s.bytesRead;const i=ee(e,t);t+=i.bytesRead;const r=fi(e,t);if(t+=r.bytesRead,t!==e.length)throw new ze("PUBLISH_DONE: unexpected trailing bytes after Error Reason");return{type:"PUBLISH_DONE",statusCode:s.value,streamCount:i.value,errorReason:r.value}}encodeNamespacePrefixRequest(e,t,s){const i=Ei(s),r=Z(e)+ii(t)+vt(i),n=new Uint8Array(r);let a=te(e,n,0);return a+=ri(t,n,a),n.set(yt(i),a),n}decodeNamespacePrefixRequest(e,t){let s=0;const i=ee(t,s);s+=i.bytesRead;const r=ni(t,s);s+=r.bytesRead;const n=Et(t,s,mt);if(s+=n.bytesRead,s!==t.length)throw new ze(`${e}: unexpected trailing bytes after parameters`);return{requestId:i.value,prefix:r.value,parameters:wi(n.params)}}encodeSubscribeNamespace(e){return this.encodeNamespacePrefixRequest(e.requestId,e.trackNamespacePrefix,e.parameters)}decodeSubscribeNamespace(e){const{requestId:t,prefix:s,parameters:i}=this.decodeNamespacePrefixRequest("SUBSCRIBE_NAMESPACE",e);return{type:"SUBSCRIBE_NAMESPACE",requestId:t,trackNamespacePrefix:s,parameters:i}}decodeSubscribeTracks(e){const{requestId:t,prefix:s,parameters:i}=this.decodeNamespacePrefixRequest("SUBSCRIBE_TRACKS",e);return{type:"SUBSCRIBE_TRACKS",requestId:t,trackNamespacePrefix:s,parameters:i}}encodePublishBlocked(e){const t=ii(e.trackNamespaceSuffix)+ei(e.trackName),s=new Uint8Array(t);let i=ri(e.trackNamespaceSuffix,s,0);return i+=ti(e.trackName,s,i),s}decodePublishBlocked(e){let t=0;const s=ni(e,t);t+=s.bytesRead;const i=si(e,t);if(t+=i.bytesRead,t!==e.length)throw new ze("PUBLISH_BLOCKED: unexpected trailing bytes after Track Name");return{type:"PUBLISH_BLOCKED",trackNamespaceSuffix:s.value,trackName:i.value}}encodeGoaway(e){const t=hi.encode(e.newSessionUri);if(t.length>li)throw new ze(`GOAWAY New Session URI length ${t.length} exceeds maximum 8192 bytes`);const s=e.timeout??0n;let i=ei(t)+Z(s);void 0!==e.requestId&&(i+=Z(e.requestId));const r=new Uint8Array(i);let n=ti(t,r,0);return n+=te(s,r,n),void 0!==e.requestId&&te(e.requestId,r,n),r}decodeGoaway(e){let t=0;const s=si(e,t);if(t+=s.bytesRead,s.value.length>li)throw new ze(`GOAWAY New Session URI length ${s.value.length} exceeds maximum 8192 bytes`);const i=ee(e,t);let r;if(t+=i.bytesRead,t>6),s=t+2;if(e.length=16&&e<=29&&!!(6&~e):e<=63&&!!(16&e)&&!(192&e)}function ir(e,t=16){return 14===t?e>=0&&e<=7||e>=32&&e<=33:e<=47&&!(16&e)&&!(192&e)}function rr(e){return(e&Ni)>>1}const nr=new Set([0n,0x3n,0x4n]);function ar(e){if(!nr.has(e))throw new ze(`Invalid draft-18 Object Status 0x${e.toString(16)}`)}function or(e,t){if(0n!==e&&void 0!==t&&t.length>0)throw new ze(`Properties present on a non-Normal status object (status 0x${e.toString(16)})`)}function cr(e,t){let s=t;const i=ee(e,s);s+=i.bytesRead;const r=Number(i.value);if(!Fe(r))throw new ze(`Invalid SUBGROUP_HEADER type 0x${r.toString(16)}`);if(!Fe(n=r)||3===xe(n))throw new ze("SUBGROUP_HEADER uses the reserved subgroup-ID mode 0b11");var n;const a=ee(e,s);s+=a.bytesRead;const o=ee(e,s);let c,d;if(s+=o.bytesRead,2===xe(r)){const t=ee(e,s);s+=t.bytesRead,c=t.value}else c=0n;0===(r&Pe)&&(d=Ye(e,s).value,s+=1);return{header:{typeByte:r,trackAlias:a.value,groupId:o.value,subgroupId:c,publisherPriority:d,hasExtensions:0!==(r&Ae),isEndOfGroup:0!==(r&Oe),isFirstObjectInSubgroup:0!==(r&Ne)},bytesRead:s-t}}function dr(e,t,s,i){if(!s)return{value:void 0,bytesRead:0};const r=function(e,t){const{value:s,bytesRead:i}=ee(e,t),r=t+i,n=Number(s);if(r+n>e.length)throw new RangeError(`vi64 length-prefixed block (${n}) exceeds remaining buffer`);return{value:e.slice(r,r+n),bytesRead:i+n}}(e,t);if(0===r.value.length){if(i)throw new ze("PROPERTIES flag set but the Properties block is empty");return{value:void 0,bytesRead:r.bytesRead}}return{value:r.value,bytesRead:r.bytesRead}}function hr(e){return e===BigInt(er)||e===BigInt(tr)}function ur(e,t,s,i,r){let n=t;const a=ee(e,n);n+=a.bytesRead;const o=a.value;if(function(e){if(!(hr(e)||e>=0n&&e<=0x7fn))throw new ze(`Invalid draft-18 fetch Serialization Flags 0x${e.toString(16)} (allowed: 0x00-0x7F, 0x8C, 0x10C)`)}(o),hr(o)){const i=ee(e,n);n+=i.bytesRead;const r=ee(e,n);n+=r.bytesRead;const a=ee(e,n);if(n+=a.bytesRead,0n!==a.value)throw new ze(`End-of-Range marker has a non-zero payload length (${a.value})`);return{item:{flags:Q(o),groupId:i.value,objectId:r.value,nonExistent:o===BigInt(er)},bytesRead:n-t,nextPrior:{groupId:i.value,objectId:r.value,lastObjectSubgroupId:s?.lastObjectSubgroupId,lastObjectPriority:s?.lastObjectPriority}}}const c=Number(o),d=0!==(c&zi),h=0!==(c&Ki),u=0!==(c&ji),l=0!==(c&Wi),p=0!==(c&Qi),m=c&Gi;if(i){if(!h||!u)throw new ze("First fetch object must include Group ID Delta and Object ID Delta");if(!l)throw new ze("First fetch object cannot inherit Priority from a prior object");if(!d&&(m===Ji||m===Xi))throw new ze("First fetch object cannot inherit Subgroup ID from a prior object")}else if(void 0===s)throw new ze("Non-first fetch object requires prior-object context");let g,f,b,S;if(h){const t=ee(e,n);if(n+=t.bytesRead,i)g=t.value;else if("ascending"===r){if(g=s.groupId+t.value+1n,g>X)throw new ze(`Fetch Group ID overflow (ascending): ${g} > 2^64-1`)}else{const e=t.value+1n;if(e>s.groupId)throw new ze(`Fetch Group ID underflow (descending): ${s.groupId} - ${e} < 0`);g=s.groupId-e}}else g=s.groupId;if(d)f=0n;else switch(m){case Yi:f=0n;break;case Ji:case Xi:if(void 0===s?.lastObjectSubgroupId)throw new ze("Fetch object references prior Subgroup ID but no prior actual object exists");if(m===Xi){if(f=s.lastObjectSubgroupId+1n,f>X)throw new ze(`Fetch Subgroup ID overflow: ${f} > 2^64-1`)}else f=s.lastObjectSubgroupId;break;default:{const t=ee(e,n);n+=t.bytesRead,f=t.value;break}}if(u){const t=ee(e,n);if(n+=t.bytesRead,i||h)b=t.value;else if(b=s.objectId+t.value,b>X)throw new ze(`Fetch Object ID overflow: ${b} > 2^64-1`)}else if(b=s.objectId+1n,b>X)throw new ze(`Fetch Object ID overflow: ${b} > 2^64-1`);if(l)S=Ye(e,n).value,n+=1;else{if(void 0===s?.lastObjectPriority)throw new ze("Fetch object references prior Priority but no prior actual object exists");S=s.lastObjectPriority}const _=dr(e,n,p,!1);n+=_.bytesRead;const v=ee(e,n);n+=v.bytesRead;const y=Number(v.value);if(n+y>e.length)throw new RangeError(`Fetch object payload (${y}) exceeds remaining buffer`);const E=e.slice(n,n+y);n+=y;return{item:{flags:Q(o),groupId:g,subgroupId:f,objectId:b,publisherPriority:S,isDatagram:d,extensions:_.value,payload:E},bytesRead:n-t,nextPrior:{groupId:g,objectId:b,lastObjectSubgroupId:d?void 0:f,lastObjectPriority:S}}}function lr(){return{version:18,decodeSubgroupHeader:(e,t)=>cr(e,t),decodeSubgroupObject:(e,t,s,i,r=!0)=>function(e,t,s,i,r=!0){let n=t;const a=ee(e,n);n+=a.bytesRead;const o=r?a.value:i+a.value+1n;if(o>X)throw new ze(`Subgroup Object ID overflow: ${o} exceeds 2^64 - 1 (prev ${i} + delta ${a.value} + 1)`);const c=dr(e,n,s,!1);n+=c.bytesRead;const d=ee(e,n);n+=d.bytesRead;const h=Number(d.value);let u,l;if(0===h){u=new Uint8Array(0);const t=ee(e,n);n+=t.bytesRead,l=t.value,ar(l),or(l,c.value)}else{if(n+h>e.length)throw new RangeError(`object payload (${h}) exceeds remaining buffer`);u=e.slice(n,n+h),n+=h}return{object:{objectId:o,extensions:c.value,payload:u,status:l},bytesRead:n-t}}(e,t,s,i,r),decodeFetchHeader:(e,t)=>function(e,t){let s=t;const i=ee(e,s);if(s+=i.bytesRead,Number(i.value)!==Re)throw new ze(`Invalid FETCH_HEADER type: expected 0x05, got 0x${i.value.toString(16)}`);const r=ee(e,s);return s+=r.bytesRead,{header:{requestId:r.value},bytesRead:s-t}}(e,t),decodeFetchObject:()=>{throw new Error("Draft18DataCodec: use decodeFetchObject18 for draft-18 fetch streams")},decodeFetchObject18:(e,t,s,i,r)=>ur(e,t,s,i,r),decodeObjectDatagram:(e,t)=>function(e,t){let s=t;const i=ee(e,s);s+=i.bytesRead;const r=Number(i.value);if(!qe(r))throw new ze(`Invalid OBJECT_DATAGRAM type 0x${r.toString(16)}`);if(!$e(r))throw new ze(`OBJECT_DATAGRAM sets both STATUS and END_OF_GROUP (0x${r.toString(16)})`);const n=ee(e,s);s+=n.bytesRead;const a=ee(e,s);let o,c;if(s+=a.bytesRead,0!==(r&Le))o=0n;else{const t=ee(e,s);s+=t.bytesRead,o=t.value}0===(r&De)&&(c=Ye(e,s).value,s+=1);const d=dr(e,s,0!==(r&Ue),!0);let h,u;if(s+=d.bytesRead,0!==(r&Be)){const t=ee(e,s);if(s+=t.bytesRead,h=t.value,ar(h),or(h,d.value),u=new Uint8Array(0),s!==e.length)throw new ze(`STATUS datagram has ${e.length-s} trailing payload byte(s)`)}else u=e.slice(s),s=e.length;return{datagram:{typeByte:r,trackAlias:n.value,groupId:a.value,objectId:o,publisherPriority:c,isEndOfGroup:0!==(r&Me),extensions:d.value,payload:u,status:h},bytesRead:s-t}}(e,t),classifyStream:(e,t=0)=>function(e,t=0){const{value:s,bytesRead:i}=ee(e,t);return{streamType:s,kind:He(s),bytesRead:i}}(e,t).kind,classifyDatagram:(e,t=0)=>function(e,t=0){const{value:s}=ee(e,t);return s===BigInt(321601065)?"padding":s<=0x2fn&&qe(Number(s))&&$e(Number(s))?"object":"invalid"}(e,t)}}const pr=new Set([ki.NORMAL,ki.END_OF_GROUP,ki.END_OF_TRACK]),mr=new Set([ki.NORMAL,ki.OBJECT_DOES_NOT_EXIST,ki.END_OF_GROUP,ki.END_OF_TRACK]);function gr(e,t=16){if(!(14===t?mr:pr).has(e)){const s=14===t?"0x0, 0x1, 0x3, 0x4":"0x0, 0x3, 0x4";throw new ze(`Invalid Object Status code: 0x${e.toString(16)} (allowed: ${s})`)}}function fr(e,t,s=16){let i=t;const{value:r,bytesRead:n}=Y(e,i);i+=n;const a=Number(r);if(!sr(a,s))throw new ze(`Invalid SUBGROUP_HEADER type byte: 0x${a.toString(16)}`);if((a&Ni)>>1===xi)throw new ze(`Reserved subgroup ID mode (0b11) in type byte: 0x${a.toString(16)}`);const{value:o,bytesRead:c}=Y(e,i);i+=c;const{value:d,bytesRead:h}=Y(e,i);i+=h;let u,l;if(rr(a)===Bi){const{value:t,bytesRead:s}=Y(e,i);i+=s,u=t}else u=Q(0);if(14===s||0===(a&Li)){const{value:t}=Ye(e,i);i+=1,l=t}return{header:{typeByte:a,trackAlias:o,groupId:d,subgroupId:u,publisherPriority:l,hasExtensions:0!==(a&Pi),isEndOfGroup:0!==(a&Ui)},bytesRead:i-t}}function br(e){return e===BigInt(er)||e===BigInt(tr)}function Sr(e,t,s,i){let r=t;const{value:n,bytesRead:a}=Y(e,r);if(r+=a,function(e){if(!(br(e)||e>=0n&&e<=0x7fn))throw new ze(`Invalid fetch serialization flags 0x${e.toString(16)} (allowed: 0x00-0x7F, 0x8C, 0x10C)`)}(n),br(n)){const{value:s,bytesRead:i}=Y(e,r);r+=i;const{value:a,bytesRead:o}=Y(e,r);r+=o;const{value:c,bytesRead:d}=Y(e,r);r+=d;const h=Number(c);if(h>0){if(r+h>e.length)throw new RangeError(`End of Range payload length ${h} exceeds remaining buffer (${e.length-r} bytes)`);r+=h}return{item:{flags:n,groupId:s,objectId:a,nonExistent:n===BigInt(er)},bytesRead:r-t}}if(i)!function(e){const t=Number(e),s=0!==(t&zi);if(0===(t&Ki))throw new ze("First fetch object cannot inherit Group ID (GROUP_ID flag must be set)");if(0===(t&ji))throw new ze("First fetch object cannot inherit Object ID (OBJECT_ID flag must be set)");if(0===(t&Wi))throw new ze("First fetch object cannot inherit Priority (PRIORITY flag must be set)");if(!s){const e=t&Gi;if(e===Ji||e===Xi)throw new ze(`First fetch object cannot inherit Subgroup ID (subgroup mode ${e} requires prior object)`)}}(n);else if(void 0===s)throw new ze("Non-first fetch object requires prior-object context");const o=Number(n),c=0!==(o&zi);let d,h,u,l,p;if(0!==(o&Ki)){const{value:t,bytesRead:s}=Y(e,r);r+=s,d=t}else d=Q(s.groupId);if(c)h=Q(0);else{const t=o&Gi;switch(t){case Yi:h=Q(0);break;case Ji:h=Q(s.subgroupId);break;case Xi:h=Q(s.subgroupId+1n);break;case Zi:{const{value:t,bytesRead:s}=Y(e,r);r+=s,h=t;break}default:throw new ze(`Invalid subgroup mode: ${t}`)}}if(0!==(o&ji)){const{value:t,bytesRead:s}=Y(e,r);r+=s,u=t}else u=Q(s.objectId+1n);if(0!==(o&Wi)){const{value:t}=Ye(e,r);r+=1,l=t}else void 0!==s?.priority&&(l=s.priority);if(0!==(o&Qi)){const{value:t,bytesRead:s}=Y(e,r);r+=s;const i=Number(t);if(r+i>e.length)throw new RangeError(`Extension length ${i} exceeds remaining buffer (${e.length-r} bytes)`);p=e.slice(r,r+i),r+=i}const{value:m,bytesRead:g}=Y(e,r);r+=g;const f=Number(m);if(r+f>e.length)throw new RangeError(`Payload length ${f} exceeds remaining buffer (${e.length-r} bytes)`);const b=e.slice(r,r+f);r+=f;return{item:{flags:n,groupId:d,subgroupId:h,objectId:u,publisherPriority:l,isDatagram:c,extensions:p,payload:b},bytesRead:r-t}}function _r(e,t,s=16){let i=t;const{value:r,bytesRead:n}=Y(e,i);i+=n;const a=Number(r);if(!ir(a,s))throw new ze(`Invalid OBJECT_DATAGRAM type byte: 0x${a.toString(16)}`);if(0!==((o=a)&Vi)&&0!==(o&qi))throw new ze(`Invalid OBJECT_DATAGRAM flag combination (STATUS + END_OF_GROUP): 0x${a.toString(16)}`);var o;const{value:c,bytesRead:d}=Y(e,i);i+=d;const{value:h,bytesRead:u}=Y(e,i);let l,p,m;if(i+=u,0!==(a&$i))l=Q(1);else{const{value:t,bytesRead:s}=Y(e,i);i+=s,l=t}if(14===s||0===(a&Hi)){const{value:t}=Ye(e,i);i+=1,p=t}let g=0;if(0!==(a&Fi)){const{value:t,bytesRead:s}=Y(e,i);if(i+=s,g=Number(t),0===g)throw new ze("OBJECT_DATAGRAM has EXTENSIONS flag set but Extension Headers Length is 0");if(i+g>e.length)throw new RangeError(`Extension length ${g} exceeds remaining buffer (${e.length-i} bytes)`);m=e.slice(i,i+g),i+=g}const f=0!==(a&qi);let b,S;if(0!==(a&Vi)){const{value:t,bytesRead:r}=Y(e,i);if(i+=r,S=t,b=new Uint8Array(0),gr(S,s),g>0&&S!==ki.NORMAL)throw new ze(`Extensions present on status datagram (status=0x${S.toString(16)}) per §10.2.1.2`);if(ifr(e,s,t),decodeSubgroupObject:(e,s,i,r,n=!0)=>function(e,t,s,i,r=!0,n=16){let a=t;const{value:o,bytesRead:c}=Y(e,a);let d,h;a+=c,d=r?o:Q(i+o+1n);let u=0;if(s){const{value:t,bytesRead:s}=Y(e,a);if(a+=s,u=Number(t),a+u>e.length)throw new RangeError(`Extension length ${u} exceeds remaining buffer (${e.length-a} bytes)`);h=e.slice(a,a+u),a+=u}const{value:l,bytesRead:p}=Y(e,a);a+=p;const m=Number(l);let g,f;if(0===m){g=new Uint8Array(0);const{value:t,bytesRead:s}=Y(e,a);if(a+=s,f=t,gr(f,n),u>0&&f!==ki.NORMAL)throw new ze(`Extensions present on status object (status=0x${f.toString(16)}) per §10.2.1.2`)}else{if(a+m>e.length)throw new RangeError(`Payload length ${m} exceeds remaining buffer (${e.length-a} bytes)`);g=e.slice(a,a+m),a+=m}return{object:{objectId:d,extensions:h,payload:g,status:f},bytesRead:a-t}}(e,s,i,r,n,t),decodeFetchHeader:(e,t)=>function(e,t){let s=t;const{value:i,bytesRead:r}=Y(e,s);s+=r;const n=Number(i);if(n!==Oi)throw new ze(`Invalid FETCH_HEADER type byte: expected 0x05, got 0x${n.toString(16)}`);const{value:a,bytesRead:o}=Y(e,s);return s+=o,{header:{requestId:a},bytesRead:s-t}}(e,t),decodeFetchObject:(e,s,i,r)=>14===t?function(e,t){let s=t;const{value:i,bytesRead:r}=Y(e,s);s+=r;const{value:n,bytesRead:a}=Y(e,s);s+=a;const{value:o,bytesRead:c}=Y(e,s);s+=c;const{value:d}=Ye(e,s);s+=1;const{value:h,bytesRead:u}=Y(e,s);s+=u;const l=Number(h);let p;if(l>0){if(s+l>e.length)throw new RangeError(`Extension length ${l} exceeds remaining buffer (${e.length-s} bytes)`);p=e.slice(s,s+l),s+=l}const{value:m,bytesRead:g}=Y(e,s);s+=g;const f=Number(m);if(0===f){const{value:r,bytesRead:n}=Y(e,s);return s+=n,gr(r,14),{item:{flags:Q(0n),groupId:i,objectId:o,nonExistent:r===ki.OBJECT_DOES_NOT_EXIST,rawStatus:r},bytesRead:s-t}}if(s+f>e.length)throw new RangeError(`Payload length ${f} exceeds remaining buffer (${e.length-s} bytes)`);const b=e.slice(s,s+f);return s+=f,{item:{flags:Q(0n),groupId:i,subgroupId:n,objectId:o,publisherPriority:d,isDatagram:!1,extensions:p,payload:b},bytesRead:s-t}}(e,s):Sr(e,s,i,r),decodeFetchObject18:()=>{throw new Error(`DataCodec: decodeFetchObject18 is draft-18 only (this codec is draft-${t})`)},decodeObjectDatagram:(e,s)=>_r(e,s,t),classifyStream:(e,s=0)=>{if(s>=e.length)throw new RangeError(`classifyStream: offset ${s} out of bounds (length ${e.length})`);const i=e[s];return i===Oi?"fetch":sr(i,t)?"subgroup":"unknown"},classifyDatagram:(e,s=0)=>{if(s>=e.length)throw new RangeError(`classifyDatagram: offset ${s} out of bounds (length ${e.length})`);return ir(e[s],t)?"object":"invalid"}}}const yr={hasCredit:!0,allocationStep:2n,inboundValidation:"strict-sequence"},Er={hasCredit:!1,allocationStep:2n,inboundValidation:"parity-and-duplicate"};function Tr(e=16){return 18===e?Er:yr}const wr={usesUnifiedSetup:!1,usesRequestStreams:!1,responsesOmitRequestId:!1,usesFetchCancelMessage:!0,usesPublishNamespaceDoneMessage:!0},Rr={usesUnifiedSetup:!0,usesRequestStreams:!0,responsesOmitRequestId:!0,usesFetchCancelMessage:!1,usesPublishNamespaceDoneMessage:!1};function Cr(e){return 18===e?Rr:wr}const Ir="idle",Ar="setup_pending",kr="established",Or="draining",Pr="closed",Nr="client",Ur="server",Mr="pending",Lr="established",Dr="terminated",Br=0,xr=1,Fr="pending",qr="transferring",$r="completed",Hr="pending",Vr="active",Gr="terminated";class jr extends Error{code;constructor(e,t){super(e),this.code=t,this.name="RequestIdError"}}class Kr{role;nextOutgoingId;peerMaxRequestId=0n;highestIncomingId;ourMaxRequestId=0n;blocked=!1;windowSize;hasCredit;inboundValidation;seenIncoming=new Set;constructor(e,t,s){this.role=e,this.hasCredit=s?.hasCredit??!0,this.inboundValidation=s?.inboundValidation??"strict-sequence",this.nextOutgoingId=e===Nr?0n:1n;const i=e===Nr?1n:0n;this.highestIncomingId=i-2n,this.windowSize=BigInt(t?.windowSize??1e3)}get endpointRole(){return this.role}get parityBit(){return this.role===Nr?0n:1n}get peerParityBit(){return this.role===Nr?1n:0n}updatePeerMaxRequestId(e){if(e<=this.peerMaxRequestId)throw new jr(`MAX_REQUEST_ID must strictly increase: ${e} <= ${this.peerMaxRequestId}`,"PROTOCOL_VIOLATION");this.peerMaxRequestId=e,this.nextOutgoingId=this.peerMaxRequestId)throw this.blocked=!0,new jr(`Cannot allocate request ID ${this.nextOutgoingId}: exceeds peer MAX_REQUEST_ID ${this.peerMaxRequestId}`,"TOO_MANY_REQUESTS");const e=this.nextOutgoingId;return this.nextOutgoingId+=2n,e}validateIncoming(e){const t=1n&e;if(t!==this.peerParityBit)throw new jr(`Invalid request ID parity: ${e} has LSB=${t}, expected ${this.peerParityBit} from peer`,"INVALID_REQUEST_ID");if("parity-and-duplicate"===this.inboundValidation){if(this.seenIncoming.has(e))throw new jr(`Duplicate incoming Request ID ${e}`,"INVALID_REQUEST_ID");return this.seenIncoming.add(e),void(e>this.highestIncomingId&&(this.highestIncomingId=e))}if(e>=this.ourMaxRequestId)throw new jr(`Request ID ${e} exceeds our MAX_REQUEST_ID ${this.ourMaxRequestId}`,"TOO_MANY_REQUESTS");const s=this.highestIncomingId+2n;if(e!==s)throw new jr(`Request ID ${e} not next in sequence: expected ${s}`,"INVALID_REQUEST_ID");this.highestIncomingId=e}validateOurRequestId(e){const t=1n&e;if(t!==this.parityBit)throw new jr(`Response has wrong parity: ${e} has LSB=${t}, expected ${this.parityBit} for our requests`,"INVALID_REQUEST_ID");if(e>=this.nextOutgoingId)throw new jr(`Response for unknown request ID ${e}: next outgoing is ${this.nextOutgoingId}`,"INVALID_REQUEST_ID")}peekNextId(){return Q(this.nextOutgoingId)}getPeerMaxRequestId(){return Q(this.peerMaxRequestId)}shouldReplenish(){if(0n===this.ourMaxRequestId)return!1;const e=this.ourMaxRequestId/2n;return this.highestIncomingId>=e}nextReplenishValue(){return Q(this.ourMaxRequestId+this.windowSize)}commitReplenish(){const e=this.ourMaxRequestId+this.windowSize;this.ourMaxRequestId=e}}const Wr={DELETE:Q(0),REGISTER:Q(1),USE_ALIAS:Q(2),USE_VALUE:Q(3)};function Qr(e){if(0===e.length)throw new ze("Empty AUTHORIZATION_TOKEN parameter");let t=0;const{value:s,bytesRead:i}=Y(e,t);switch(t+=i,s){case Wr.DELETE:{if(t>=e.length)throw new ze("DELETE token missing Token Alias");const{value:s,bytesRead:i}=Y(e,t);if(t+=i,t!==e.length)throw new ze(`DELETE token has ${e.length-t} trailing bytes`);return{aliasType:Wr.DELETE,tokenAlias:s}}case Wr.REGISTER:{if(t>=e.length)throw new ze("REGISTER token missing Token Alias");const{value:s,bytesRead:i}=Y(e,t);if(t+=i,t>=e.length)throw new ze("REGISTER token missing Token Type");const{value:r,bytesRead:n}=Y(e,t);t+=n;const a=e.slice(t);return{aliasType:Wr.REGISTER,tokenAlias:s,tokenType:r,tokenValue:a}}case Wr.USE_ALIAS:{if(t>=e.length)throw new ze("USE_ALIAS token missing Token Alias");const{value:s,bytesRead:i}=Y(e,t);if(t+=i,t!==e.length)throw new ze(`USE_ALIAS token has ${e.length-t} trailing bytes`);return{aliasType:Wr.USE_ALIAS,tokenAlias:s}}case Wr.USE_VALUE:{if(t>=e.length)throw new ze("USE_VALUE token missing Token Type");const{value:s,bytesRead:i}=Y(e,t);t+=i;const r=e.slice(t);return{aliasType:Wr.USE_VALUE,tokenType:s,tokenValue:r}}default:throw new ze(`Unknown AUTHORIZATION_TOKEN Alias Type: ${s}`)}}function zr(e){if(0===e.length)throw new ze("Empty AUTHORIZATION_TOKEN parameter");let t=0;const{value:s,bytesRead:i}=ee(e,t);switch(t+=i,s){case Wr.DELETE:{if(t>=e.length)throw new ze("DELETE token missing Token Alias");const{value:s,bytesRead:i}=ee(e,t);if(t+=i,t!==e.length)throw new ze(`DELETE token has ${e.length-t} trailing bytes`);return{aliasType:Wr.DELETE,tokenAlias:s}}case Wr.REGISTER:{if(t>=e.length)throw new ze("REGISTER token missing Token Alias");const s=ee(e,t);if(t+=s.bytesRead,t>=e.length)throw new ze("REGISTER token missing Token Type");const i=ee(e,t);return t+=i.bytesRead,{aliasType:Wr.REGISTER,tokenAlias:s.value,tokenType:i.value,tokenValue:e.slice(t)}}case Wr.USE_ALIAS:{if(t>=e.length)throw new ze("USE_ALIAS token missing Token Alias");const{value:s,bytesRead:i}=ee(e,t);if(t+=i,t!==e.length)throw new ze(`USE_ALIAS token has ${e.length-t} trailing bytes`);return{aliasType:Wr.USE_ALIAS,tokenAlias:s}}case Wr.USE_VALUE:{if(t>=e.length)throw new ze("USE_VALUE token missing Token Type");const{value:s,bytesRead:i}=ee(e,t);return t+=i,{aliasType:Wr.USE_VALUE,tokenType:s,tokenValue:e.slice(t)}}default:throw new ze(`Unknown AUTHORIZATION_TOKEN Alias Type: ${s}`)}}class Yr extends Error{code;constructor(e,t){super(e),this.code=t,this.name="SetupError"}}const Jr=new Set([ve,Ee,Te,we]);class Xr{role;draftVersion;webtransport;state=Ir;setupResult;constructor(e,t=16,s=!1){this.role=e,this.draftVersion=t,this.webtransport=s}get sessionState(){return this.state}isComplete(){return this.state===kr}getResult(){if(!this.setupResult)throw new Error("Setup handshake not complete");return this.setupResult}validateMessage(e){if(18!==this.draftVersion){if(this.state===Ir){if(this.role===Nr)throw new Yr("Client must send CLIENT_SETUP before receiving any messages","PROTOCOL_VIOLATION");if("CLIENT_SETUP"!==e.type)throw new Yr(`First message must be CLIENT_SETUP, got ${e.type}`,"PROTOCOL_VIOLATION")}else if(this.state===Ar){if(this.role===Nr&&"SERVER_SETUP"!==e.type)throw new Yr(`Expected SERVER_SETUP after CLIENT_SETUP, got ${e.type}`,"PROTOCOL_VIOLATION");if(this.role===Ur)throw new Yr("Server should not receive messages while SETUP_PENDING","PROTOCOL_VIOLATION")}}else if(this.state!==kr&&"SETUP"!==e.type)throw new Yr(`draft-18 expects SETUP, got ${e.type}`,"PROTOCOL_VIOLATION")}createSetup18(e={}){const t=new TextEncoder,s=new Map;return void 0!==e.path&&s.set(BigInt(ve),[t.encode(e.path)]),void 0!==e.authority&&s.set(BigInt(Te),[t.encode(e.authority)]),void 0!==e.implementation&&s.set(BigInt(we),[t.encode(e.implementation)]),void 0!==e.maxAuthTokenCacheSize&&s.set(BigInt(Ee),[e.maxAuthTokenCacheSize]),void 0!==e.authTokens&&e.authTokens.length>0&&s.set(BigInt(ye),e.authTokens),this.state=this.state===Ir?Ar:kr,{type:"SETUP",setupOptions:s}}handleSetup18(e){const t=this.extractSetupOptions18(e.setupOptions);return this.setupResult=t,this.state=this.state===Ir?Ar:kr,t}extractSetupOptions18(e){if(this.webtransport){if(e.has(BigInt(ve)))throw new Yr("PATH MUST NOT be used over WebTransport (§10.3.1.2)","INVALID_PATH");if(e.has(BigInt(Te)))throw new Yr("AUTHORITY MUST NOT be used over WebTransport (§10.3.1.1)","INVALID_AUTHORITY")}if(this.role===Nr&&(e.has(BigInt(ve))||e.has(BigInt(Te))))throw new Yr("Server SETUP must not contain PATH or AUTHORITY","PROTOCOL_VIOLATION");const t=new TextDecoder;let s,i,r,n,a;for(const[o,c]of e){if(c.length>1&&Jr.has(Number(o)))throw new Yr(`Repeated Setup Option 0x${o.toString(16)} (singleton)`,"PROTOCOL_VIOLATION");const e=c[0];switch(Number(o)){case we:e instanceof Uint8Array&&(s=t.decode(e));break;case ve:e instanceof Uint8Array&&(i=t.decode(e));break;case Te:e instanceof Uint8Array&&(r=t.decode(e));break;case Ee:"bigint"==typeof e&&(n=e);break;case ye:a=c.filter(e=>e instanceof Uint8Array).map(e=>zr(e))}}return{peerMaxRequestId:Q(0n),...void 0!==s?{peerImplementation:s}:{},...void 0!==i?{path:i}:{},...void 0!==r?{authority:r}:{},...void 0!==n?{peerMaxAuthTokenCacheSize:n}:{},...void 0!==a?{authTokens:a}:{}}}createClientSetup(e={}){if(this.role!==Nr)throw new Error("Only client can create CLIENT_SETUP");if(this.state!==Ir)throw new Error(`Cannot create CLIENT_SETUP in state ${this.state}`);const t=new Map;return void 0!==e.maxRequestId&&t.set(Q(is.MAX_REQUEST_ID),[e.maxRequestId]),void 0!==e.path&&t.set(Q(is.PATH),[(new TextEncoder).encode(e.path)]),void 0!==e.authority&&t.set(Q(is.AUTHORITY),[(new TextEncoder).encode(e.authority)]),void 0!==e.implementation&&t.set(Q(is.MOQT_IMPLEMENTATION),[(new TextEncoder).encode(e.implementation)]),void 0!==e.maxAuthTokenCacheSize&&t.set(Q(is.MAX_AUTH_TOKEN_CACHE_SIZE),[e.maxAuthTokenCacheSize]),void 0!==e.authTokens&&e.authTokens.length>0&&t.set(Q(is.AUTHORIZATION_TOKEN),e.authTokens),this.state=Ar,{type:"CLIENT_SETUP",parameters:t}}handleClientSetup(e){if(this.role!==Ur)throw new Yr("Only server handles CLIENT_SETUP","PROTOCOL_VIOLATION");if(this.state!==Ir)throw new Yr(`Cannot handle CLIENT_SETUP in state ${this.state}`,"PROTOCOL_VIOLATION");const t=this.extractSetupParams(e.parameters,!0);return this.setupResult=t,this.state=Ar,t}createServerSetup(e={}){if(this.role!==Ur)throw new Error("Only server can create SERVER_SETUP");if(this.state!==Ar)throw new Error(`Cannot create SERVER_SETUP in state ${this.state}`);const t=new Map;return void 0!==e.maxRequestId&&t.set(Q(is.MAX_REQUEST_ID),[e.maxRequestId]),void 0!==e.implementation&&t.set(Q(is.MOQT_IMPLEMENTATION),[(new TextEncoder).encode(e.implementation)]),void 0!==e.maxAuthTokenCacheSize&&t.set(Q(is.MAX_AUTH_TOKEN_CACHE_SIZE),[e.maxAuthTokenCacheSize]),void 0!==e.authTokens&&e.authTokens.length>0&&t.set(Q(is.AUTHORIZATION_TOKEN),e.authTokens),this.state=kr,{type:"SERVER_SETUP",parameters:t}}handleServerSetup(e){if(this.role!==Nr)throw new Yr("Only client handles SERVER_SETUP","PROTOCOL_VIOLATION");if(this.state!==Ar)throw new Yr(`Cannot handle SERVER_SETUP in state ${this.state}`,"PROTOCOL_VIOLATION");if(e.parameters.has(is.PATH))throw new Yr("Server sent PATH parameter","INVALID_PATH");if(e.parameters.has(is.AUTHORITY))throw new Yr("Server sent AUTHORITY parameter","INVALID_AUTHORITY");const t=this.extractSetupParams(e.parameters,!1);return this.setupResult=t,this.state=kr,t}extractSetupParams(e,t){let s,i,r,n,a=Q(0);const o=[];for(const[c,d]of e){if(!(c===is.MAX_REQUEST_ID||c===is.MOQT_IMPLEMENTATION||c===is.PATH||c===is.AUTHORITY||c===is.AUTHORIZATION_TOKEN||c===is.MAX_AUTH_TOKEN_CACHE_SIZE))continue;if(c===is.AUTHORIZATION_TOKEN){for(const e of d){if(!(e instanceof Uint8Array))continue;let s;try{s=Qr(e)}catch{throw new Yr("Malformed AUTHORIZATION_TOKEN structure","KEY_VALUE_FORMATTING_ERROR")}if(t&&(s.aliasType===Wr.DELETE||s.aliasType===Wr.USE_ALIAS))throw new Yr(`CLIENT_SETUP AUTHORIZATION_TOKEN cannot use Alias Type ${s.aliasType} (DELETE and USE_ALIAS are prohibited in CLIENT_SETUP)`,"PROTOCOL_VIOLATION");o.push(s)}continue}if(d.length>1)throw new Yr(`Duplicate setup parameter: ${c}`,"PROTOCOL_VIOLATION");const e=d[0];if(c===is.MAX_REQUEST_ID)"bigint"==typeof e&&(a=Q(e));else if(c===is.MOQT_IMPLEMENTATION)e instanceof Uint8Array&&(s=(new TextDecoder).decode(e));else if(c===is.MAX_AUTH_TOKEN_CACHE_SIZE)"bigint"==typeof e&&(n=Q(e));else if(c===is.PATH){if(t&&e instanceof Uint8Array){const t=(new TextDecoder).decode(e);this.validatePath(t),i=t}}else if(c===is.AUTHORITY&&t&&e instanceof Uint8Array){const t=(new TextDecoder).decode(e);this.validateAuthority(t),r=t}}const c={peerMaxRequestId:a};return void 0!==s&&(c.peerImplementation=s),void 0!==i&&(c.path=i),void 0!==r&&(c.authority=r),void 0!==n&&(c.peerMaxAuthTokenCacheSize=n),o.length>0&&(c.authTokens=o),c}validatePath(e){const t=e.indexOf("?"),s=-1===t?e:e.slice(0,t),i=-1===t?"":e.slice(t+1);if(s.length>0&&!s.startsWith("/"))throw new Yr("PATH path component must start with / or be empty","MALFORMED_PATH");if(!/^(\/[A-Za-z0-9\-._~!$&'()*+,;=:@%]*)*$/.test(s))throw new Yr("PATH contains invalid characters","MALFORMED_PATH");if(i.length>0){if(!/^[A-Za-z0-9\-._~!$&'()*+,;=:@%\/?]*$/.test(i))throw new Yr("PATH query contains invalid characters","MALFORMED_PATH")}if(e.replace(/%[0-9A-Fa-f]{2}/g,"").includes("%"))throw new Yr("PATH contains malformed percent encoding","MALFORMED_PATH")}validateAuthority(e){if(0===e.length)throw new Yr("AUTHORITY cannot be empty","MALFORMED_AUTHORITY");let t=e;const s=t.indexOf("@");if(-1!==s){const e=t.slice(0,s);t=t.slice(s+1);if(!/^[A-Za-z0-9\-._~!$&'()*+,;=:%]*$/.test(e))throw new Yr("AUTHORITY userinfo contains invalid characters","MALFORMED_AUTHORITY");if(!this.hasValidPercentEncoding(e))throw new Yr("AUTHORITY userinfo has malformed percent encoding","MALFORMED_AUTHORITY")}let i,r=t;if(t.startsWith("[")){const e=t.indexOf("]");if(-1===e)throw new Yr("AUTHORITY has unclosed IP-literal bracket","MALFORMED_AUTHORITY");if(r=t.slice(0,e+1),t.length>e+1){if(":"!==t[e+1])throw new Yr("AUTHORITY has invalid characters after IP-literal","MALFORMED_AUTHORITY");i=t.slice(e+2)}const s=r.slice(1,-1);if(s.startsWith("v")){if(!/^v[0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&'()*+,;=:]+$/.test(s))throw new Yr("AUTHORITY has invalid IPvFuture","MALFORMED_AUTHORITY")}else this.validateIPv6(s)}else{const e=t.lastIndexOf(":");if(-1!==e){const s=t.slice(e+1);/^\d*$/.test(s)&&(r=t.slice(0,e),i=s)}if(0===r.length)throw new Yr("AUTHORITY MUST NOT contain an empty host portion","MALFORMED_AUTHORITY");if(!/^[A-Za-z0-9\-._~!$&'()*+,;=%]*$/.test(r))throw new Yr("AUTHORITY host contains invalid characters","MALFORMED_AUTHORITY");if(!this.hasValidPercentEncoding(r))throw new Yr("AUTHORITY host has malformed percent encoding","MALFORMED_AUTHORITY")}if(void 0!==i&&i.length>0){const e=parseInt(i,10);if(isNaN(e)||e<0||e>65535)throw new Yr("AUTHORITY has invalid port number","MALFORMED_AUTHORITY")}}hasValidPercentEncoding(e){return!e.replace(/%[0-9A-Fa-f]{2}/g,"").includes("%")}validateIPv6(e){let t=!1,s=e;const i=e.lastIndexOf(":");if(-1!==i&&e.slice(i+1).includes(".")){const r=e.slice(i+1),n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(r);if(!n)throw new Yr("AUTHORITY has invalid embedded IPv4 in IPv6","MALFORMED_AUTHORITY");for(let e=1;e<=4;e++){const t=n[e];if(t.length>1&&"0"===t[0])throw new Yr("AUTHORITY has invalid embedded IPv4 in IPv6 (leading zeros)","MALFORMED_AUTHORITY");if(parseInt(t,10)>255)throw new Yr("AUTHORITY has invalid embedded IPv4 in IPv6","MALFORMED_AUTHORITY")}t=!0,s=i>0&&":"===e[i-1]?e.slice(0,i+1):e.slice(0,i)}if(s.includes(":::"))throw new Yr("AUTHORITY IPv6 has invalid consecutive colons","MALFORMED_AUTHORITY");const r=s.includes("::");if((s.match(/::/g)||[]).length>1)throw new Yr("AUTHORITY IPv6 has multiple zero-compression (::)","MALFORMED_AUTHORITY");const n=s.split(":"),a=/^[0-9A-Fa-f]{1,4}$/;let o=0;const c=[];for(let e=0;e=d)throw new Yr("AUTHORITY IPv6 :: must compress at least one segment","MALFORMED_AUTHORITY")}else{if(n.length!==d)throw new Yr(`AUTHORITY IPv6 must have ${d} segments, got ${n.length}`,"MALFORMED_AUTHORITY");if(o!==d)throw new Yr("AUTHORITY IPv6 has empty segment without ::","MALFORMED_AUTHORITY")}}}class Zr{_requestId;_isPublisher;_trackNamespace;_trackName;_state=Mr;_forwardState=xr;_remoteFilterType;_trackAlias;_errorCode;_errorReason;_terminationCode;_terminationCause;_largestLocation;_trackKey;_streamCount=0n;_currentFilter;_currentPriority;_requestedDeliveryTimeoutMs;_requestedSubgroupDeliveryTimeoutMs;_publishInitiated=!1;_publishParameters=new Map;constructor(e,t,s,i){this._requestId=e,this._isPublisher=t,this._trackNamespace=s,this._trackName=i,s&&i&&(this._trackKey=this.computeTrackKey(s,i))}static createAsSubscriber(e,t,s){return new Zr(e,!1,t,s)}static createAsPublisher(e,t,s){return new Zr(e,!0,t,s)}get remoteFilterType(){return this._remoteFilterType}setRemoteFilterType(e){this._remoteFilterType=e}setInitialForwardState(e){this._forwardState=e}static createFromPublish(e,t,s,i,r){const n=new Zr(e,!0,t,s);return n._publishInitiated=!0,i&&(n._publishParameters=i),void 0!==r&&(n._trackAlias=r),n}get state(){return this._state}get forwardState(){return this._forwardState}get requestId(){return this._requestId}get trackAlias(){return this._trackAlias}get errorCode(){return this._errorCode}get errorReason(){return this._errorReason}get terminationCode(){return this._terminationCode}get largestLocation(){return this._largestLocation}get streamCount(){return Q(this._streamCount)}incrementStreamCount(){this._streamCount++}get trackNamespace(){return this._trackNamespace}get trackName(){return this._trackName}get trackKey(){return this._trackKey}get isPublishInitiated(){return this._publishInitiated}get publishParameters(){return this._publishParameters}get currentFilter(){return this._currentFilter}set currentFilter(e){this._currentFilter=e}get currentPriority(){return this._currentPriority}set currentPriority(e){this._currentPriority=e}get requestedDeliveryTimeoutMs(){return this._requestedDeliveryTimeoutMs}set requestedDeliveryTimeoutMs(e){this._requestedDeliveryTimeoutMs=e}get requestedSubgroupDeliveryTimeoutMs(){return this._requestedSubgroupDeliveryTimeoutMs}set requestedSubgroupDeliveryTimeoutMs(e){this._requestedSubgroupDeliveryTimeoutMs=e}get isPublisher(){return this._isPublisher}get isPending(){return this._state===Mr}get isActive(){return this._state===Lr&&this._forwardState===xr}get isTerminated(){return this._state===Dr}get terminationCause(){return this._terminationCause}handleSubscribeOk(e){this.assertState(Mr,"handleSubscribeOk"),this.assertNotPublisher("handleSubscribeOk"),this._trackAlias=e,this._state=Lr}handleRequestError(e,t){this.assertNotTerminated("handleRequestError"),this.assertNotPublisher("handleRequestError"),this._errorCode=e,this._errorReason=t,this._state=Dr,this._terminationCause="request-error"}handlePublishDone(e,t){this.assertState(Lr,"handlePublishDone"),this.assertNotPublisher("handlePublishDone"),this._terminationCode=e,this._errorReason=t,this._state=Dr,this._terminationCause="publish-done"}sendSubscribeOk(e){this.assertState(Mr,"sendSubscribeOk"),this.assertPublisher("sendSubscribeOk"),this._trackAlias=e,this._state=Lr}setOutboundPublishAlias(e){this.assertState(Mr,"setOutboundPublishAlias"),this.assertPublisher("setOutboundPublishAlias"),this._trackAlias=e,this._publishInitiated=!0}acceptOutboundPublish(){this.assertState(Mr,"acceptOutboundPublish"),this.assertPublisher("acceptOutboundPublish"),this._state=Lr}sendRequestError(e,t){this.assertNotTerminated("sendRequestError"),this.assertPublisher("sendRequestError"),this._errorCode=e,this._errorReason=t,this._state=Dr}sendUnsubscribe(){this.assertState(Lr,"sendUnsubscribe"),this.assertNotPublisher("sendUnsubscribe"),this._state=Dr,this._terminationCause="unsubscribed"}supersede(){this.assertNotTerminated("supersede"),this.assertNotPublisher("supersede"),this._state=Dr,this._terminationCause="unsubscribed"}handleUnsubscribe(){this.assertNotTerminated("handleUnsubscribe"),this.assertPublisher("handleUnsubscribe"),this._state=Dr,this._terminationCause="publisher-unsubscribed"}sendPublishDone(e,t){this.assertState(Lr,"sendPublishDone"),this.assertPublisher("sendPublishDone"),this._terminationCode=e,this._errorReason=t,this._state=Dr,this._terminationCause="publish-done"}updateForwardState(e){this.assertState(Lr,"updateForwardState"),this._forwardState=e}updateLargestLocation(e,t){this._largestLocation?(e>this._largestLocation.groupId||e===this._largestLocation.groupId&&t>this._largestLocation.objectId)&&(this._largestLocation={groupId:e,objectId:t}):this._largestLocation={groupId:e,objectId:t}}assertState(e,t){if(this._state!==e)throw new Error(`Cannot ${t} in state ${this._state}; expected ${e}`)}assertNotTerminated(e){if(this._state===Dr)throw new Error(`Cannot ${e} in TERMINATED state`)}assertPublisher(e){if(!this._isPublisher)throw new Error(`${e} is only valid for publisher side`)}assertNotPublisher(e){if(this._isPublisher)throw new Error(`${e} is only valid for subscriber side`)}computeTrackKey(e,t){const s=[];for(const t of e)s.push(this.bytesToHex(t));return s.push(this.bytesToHex(t)),s.join("/")}bytesToHex(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}}class en{_requestId;_isPublisher;_startGroup;_startObject;_endGroup;_endObject;_state=Fr;_errorCode;_errorReason;_wasCanceled=!1;_joining;_responseReceived=!1;_responseSent=!1;_dataFinished=!1;constructor(e,t,s,i,r,n){this._requestId=e,this._isPublisher=t,this._startGroup=s,this._startObject=i,this._endGroup=r,this._endObject=n}static createAsFetcher(e,t,s,i,r){return new en(e,!1,t,s,i,r)}static createAsPublisher(e,t,s,i,r){return new en(e,!0,t,s,i,r)}static createAsJoiningFetcher(e,t){const s=3===t.fetchType?new en(e,!1,t.joiningStart,0n):new en(e,!1);return s._joining=t,s}static createAsJoiningPublisher(e,t){const s=new en(e,!0);return s._joining=t,s}get isJoining(){return void 0!==this._joining}get joining(){return this._joining}setResolvedRange(e,t,s,i){if(void 0===this._joining)throw new Error("setResolvedRange is only valid for a joining fetch");this._startGroup=e,this._startObject=t,this._endGroup=s,this._endObject=i}get state(){return this._state}get requestId(){return this._requestId}get errorCode(){return this._errorCode}get errorReason(){return this._errorReason}get wasCanceled(){return this._wasCanceled}get isPublisher(){return this._isPublisher}get startGroup(){return this._startGroup}get startObject(){return this._startObject}get endGroup(){return this._endGroup}get endObject(){return this._endObject}get isPending(){return this._state===Fr}get isTransferring(){return this._state===qr}get isCompleted(){return this._state===$r}handleFetchOk(){if(this.assertNotPublisher("handleFetchOk"),this.assertNotCompleted("handleFetchOk"),this._responseReceived)throw new Error("Cannot handleFetchOk: FETCH_OK already received (§5.2: one response)");this._responseReceived=!0,this._state===Fr&&(this._state=qr)}get responseReceived(){return this._responseReceived}get dataFinished(){return this._dataFinished}get isFetcherComplete(){return this._responseReceived&&this._dataFinished}markDataFinished(){this._dataFinished=!0}handleRequestError(e,t){this.assertNotCompleted("handleRequestError"),this.assertNotTransferring("handleRequestError"),this.assertNotPublisher("handleRequestError"),this._errorCode=e,this._errorReason=t,this._state=$r}sendFetchOk(){this.assertState(Fr,"sendFetchOk"),this.assertPublisher("sendFetchOk"),this._responseSent=!0,this._state=qr}get responseSent(){return this._responseSent}get isPublisherComplete(){return this._responseSent&&this._dataFinished}sendRequestError(e,t){this.assertNotCompleted("sendRequestError"),this.assertNotTransferring("sendRequestError"),this.assertPublisher("sendRequestError"),this._errorCode=e,this._errorReason=t,this._state=$r}handleFetchCancel(){this.assertNotCompleted("handleFetchCancel"),this.assertPublisher("handleFetchCancel"),this._wasCanceled=!0,this._state=$r}sendFetchCancel(){this.assertNotCompleted("sendFetchCancel"),this.assertNotPublisher("sendFetchCancel"),this._wasCanceled=!0,this._state=$r}handleStreamFinish(){this.assertState(qr,"handleStreamFinish"),this._state=$r}assertState(e,t){if(this._state!==e)throw new Error(`Cannot ${t} in state ${this._state}; expected ${e}`)}assertNotCompleted(e){if(this._state===$r)throw new Error(`Cannot ${e} in COMPLETED state`)}assertNotTransferring(e){if(this._state===qr)throw new Error(`Cannot ${e} in TRANSFERRING state`)}assertPublisher(e){if(!this._isPublisher)throw new Error(`${e} is only valid for publisher side`)}assertNotPublisher(e){if(this._isPublisher)throw new Error(`${e} is only valid for fetcher side`)}}class tn{_requestId;_isPublisher;_namespacePrefix;_state=Hr;_errorCode;_errorReason;_discoveredNamespaces=[];_prefixKey;constructor(e,t,s){this._requestId=e,this._isPublisher=t,this._namespacePrefix=s,this._prefixKey=this.computePrefixKey(s)}updatePrefix(e){this._namespacePrefix=e,this._prefixKey=this.computePrefixKey(e)}static createAsSubscriber(e,t){return new tn(e,!1,t)}static createAsPublisher(e,t){return new tn(e,!0,t)}get state(){return this._state}get requestId(){return this._requestId}get namespacePrefix(){return this._namespacePrefix}get errorCode(){return this._errorCode}get errorReason(){return this._errorReason}get discoveredNamespaces(){return this._discoveredNamespaces}get prefixKey(){return this._prefixKey}get isPublisher(){return this._isPublisher}get isPending(){return this._state===Hr}get isActive(){return this._state===Vr}get isTerminated(){return this._state===Gr}handleRequestOk(){this.assertState(Hr,"handleRequestOk"),this.assertNotPublisher("handleRequestOk"),this._state=Vr}handleRequestError(e,t){this.assertNotTerminated("handleRequestError"),this.assertNotPublisher("handleRequestError"),this._errorCode=e,this._errorReason=t,this._state=Gr}handleNamespace(e){this.assertState(Vr,"handleNamespace"),this.assertNotPublisher("handleNamespace"),this._discoveredNamespaces.push(e)}hasDiscoveredSuffix(e){return this._discoveredNamespaces.some(t=>this.suffixEquals(t,e))}withdrawNamespace(e){this.assertState(Vr,"withdrawNamespace");const t=this._discoveredNamespaces.findIndex(t=>this.suffixEquals(t,e));-1!==t&&this._discoveredNamespaces.splice(t,1)}handleNamespaceDone(){this.assertState(Vr,"handleNamespaceDone"),this.assertNotPublisher("handleNamespaceDone"),this._state=Gr}sendRequestOk(){this.assertState(Hr,"sendRequestOk"),this.assertPublisher("sendRequestOk"),this._state=Vr}sendRequestError(e,t){this.assertNotTerminated("sendRequestError"),this.assertPublisher("sendRequestError"),this._errorCode=e,this._errorReason=t,this._state=Gr}sendNamespace(e){this.assertState(Vr,"sendNamespace"),this.assertPublisher("sendNamespace"),this._discoveredNamespaces.push(e)}sendNamespaceDone(){this.assertState(Vr,"sendNamespaceDone"),this.assertPublisher("sendNamespaceDone"),this._state=Gr}assertState(e,t){if(this._state!==e)throw new Error(`Cannot ${t} in state ${this._state}; expected ${e}`)}assertNotTerminated(e){if(this._state===Gr)throw new Error(`Cannot ${e} in TERMINATED state`)}assertPublisher(e){if(!this._isPublisher)throw new Error(`${e} is only valid for publisher side`)}assertNotPublisher(e){if(this._isPublisher)throw new Error(`${e} is only valid for subscriber side`)}computePrefixKey(e){const t=[];for(const s of e)t.push(this.bytesToHex(s));return t.join("/")}bytesToHex(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}suffixEquals(e,t){if(e.length!==t.length)return!1;for(let s=0;s0))return}const i=this.aliasToTrack.get(s);if(i){const e=this.computeTrackKey(i.namespace,i.name),t=this.trackToAliases.get(e);t&&(t.delete(s),0===t.size&&this.trackToAliases.delete(e)),this.aliasToTrack.delete(s)}this.aliasToOwner.delete(s)}getByAlias(e){return this.aliasToTrack.get(e)}getAliasByTrack(e,t){const s=this.computeTrackKey(e,t),i=this.trackToAliases.get(s);if(!i||0===i.size)return;let r;for(const e of i)r=e;return r}hasAlias(e){return this.aliasToTrack.has(e)}hasTrack(e,t){const s=this.computeTrackKey(e,t);return(this.trackToAliases.get(s)?.size??0)>0}get size(){return this.aliasToTrack.size}clear(){this.aliasToTrack.clear(),this.trackToAliases.clear(),this.aliasToOwner.clear()}computeTrackKey(e,t){const s=[];for(const t of e)s.push(this.bytesToHex(t));return s.push(this.bytesToHex(t)),s.join("/")}bytesToHex(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}}const rn={NextGroupStart:0x1n,LargestObject:0x2n,LatestObject:0x2n,AbsoluteStart:0x3n,AbsoluteRange:0x4n};function nn(e,t){const s=rn[e.type];if(18===t){let t=0n;if("AbsoluteRange"===e.type){if(e.endGroupX)throw new RangeError(`AbsoluteRange endGroup ${e.endGroup} exceeds 2^64-1`);t=e.endGroup-e.startGroup}let i=Z(s);"AbsoluteStart"!==e.type&&"AbsoluteRange"!==e.type||(i+=Z(e.startGroup)+Z(e.startObject)),"AbsoluteRange"===e.type&&(i+=Z(t));const r=new Uint8Array(i);let n=te(s,r,0);return"AbsoluteStart"!==e.type&&"AbsoluteRange"!==e.type||(n+=te(e.startGroup,r,n),n+=te(e.startObject,r,n)),"AbsoluteRange"===e.type&&te(t,r,n),r}const i=Q(s);let r=z(i);"AbsoluteStart"!==e.type&&"AbsoluteRange"!==e.type||(r+=z(e.startGroup),r+=z(e.startObject)),"AbsoluteRange"===e.type&&(r+=z(e.endGroup));const n=new Uint8Array(r);let a=J(i,n,0);return"AbsoluteStart"!==e.type&&"AbsoluteRange"!==e.type||(a+=J(e.startGroup,n,a),a+=J(e.startObject,n,a)),"AbsoluteRange"===e.type&&J(e.endGroup,n,a),n}function an(e,t){const s=on(e,t);if(void 0!==s)throw new RangeError(`decodeSubscriptionFilter: ${s}`);const i=18===t?t=>ee(e,t):t=>{const{value:s,bytesRead:i}=Y(e,t);return{value:s,bytesRead:i}};let r=0;const n=i(r);if(r+=n.bytesRead,1n===n.value)return{type:"NextGroupStart"};if(2n===n.value)return{type:"LargestObject"};const a=i(r);r+=a.bytesRead;const o=i(r);if(r+=o.bytesRead,3n===n.value)return{type:"AbsoluteStart",startGroup:a.value,startObject:o.value};const c=i(r),d=18===t?a.value+c.value:c.value;return{type:"AbsoluteRange",startGroup:a.value,startObject:o.value,endGroup:d}}function on(e,t){return 18===t?function(e){if(0===e.length)return"SUBSCRIPTION_FILTER is empty";let t,s,i,r=0;try{const s=ee(e,r);t=s.value,r+=s.bytesRead}catch{return"SUBSCRIPTION_FILTER has malformed Filter Type"}if(t<1n||t>4n)return`SUBSCRIPTION_FILTER has unknown Filter Type ${t}`;if(1n===t||2n===t)return r===e.length?void 0:`SUBSCRIPTION_FILTER length mismatch: ${e.length-r} trailing bytes for Filter Type ${t}`;try{const t=ee(e,r);s=t.value,r+=t.bytesRead;r+=ee(e,r).bytesRead}catch{return"SUBSCRIPTION_FILTER has malformed Start Location"}if(3n===t)return r===e.length?void 0:`SUBSCRIPTION_FILTER length mismatch: ${e.length-r} trailing bytes for AbsoluteStart`;try{const t=ee(e,r);i=t.value,r+=t.bytesRead}catch{return"SUBSCRIPTION_FILTER has malformed End Group Delta for AbsoluteRange"}if(r!==e.length)return`SUBSCRIPTION_FILTER length mismatch: ${e.length-r} trailing bytes for AbsoluteRange`;if(s+i>X)return`SUBSCRIPTION_FILTER AbsoluteRange overflows uint64: Start Group ${s} + End Group Delta ${i}`;return}(e):function(e){if(0===e.length)return"SUBSCRIPTION_FILTER is empty";let t,s,i,r=0;try{const{value:s,bytesRead:i}=Y(e,r);t=s,r+=i}catch{return"SUBSCRIPTION_FILTER has malformed Filter Type varint"}if(t<1n||t>4n)return`SUBSCRIPTION_FILTER has unknown Filter Type ${t}`;if(1n===t||2n===t)return r===e.length?void 0:`SUBSCRIPTION_FILTER length mismatch: ${e.length-r} trailing bytes for Filter Type ${t}`;try{const{value:t,bytesRead:i}=Qt(e,r);s=t.group,r+=i}catch{return"SUBSCRIPTION_FILTER has malformed Start Location"}if(3n===t)return r===e.length?void 0:`SUBSCRIPTION_FILTER length mismatch: ${e.length-r} trailing bytes for AbsoluteStart`;try{const{value:t,bytesRead:s}=Y(e,r);i=t,r+=s}catch{return"SUBSCRIPTION_FILTER has malformed End Group varint for AbsoluteRange"}if(r!==e.length)return`SUBSCRIPTION_FILTER length mismatch: ${e.length-r} trailing bytes for AbsoluteRange`;if(ithis.maxBytes){if(i)return null;throw new cn(`Registering alias ${e} would exceed MAX_AUTH_TOKEN_CACHE_SIZE (current: ${this._currentSize}, entry: ${r}, max: ${this.maxBytes})`,"AUTH_TOKEN_CACHE_OVERFLOW")}const n={tokenType:t,tokenValue:s};return this.cache.set(e,n),this._currentSize+=r,n}delete(e){const t=this.cache.get(e);if(!t)throw new cn(`Token alias ${e} is not registered`,"UNKNOWN_AUTH_TOKEN_ALIAS");const s=16+t.tokenValue.length;this.cache.delete(e),this._currentSize-=s}resolve(e){const t=this.cache.get(e);if(!t)throw new cn(`Token alias ${e} is not registered`,"UNKNOWN_AUTH_TOKEN_ALIAS");return t}get currentSize(){return this._currentSize}get size(){return this.cache.size}}const hn=new Set([rs.DELIVERY_TIMEOUT,rs.AUTHORIZATION_TOKEN,rs.EXPIRES,rs.LARGEST_OBJECT,rs.FORWARD,rs.SUBSCRIBER_PRIORITY,rs.SUBSCRIPTION_FILTER,rs.GROUP_ORDER,rs.NEW_GROUP_REQUEST,rs.TRACK_NAMESPACE_PREFIX]),un=new Map([[rs.DELIVERY_TIMEOUT,new Set(["PUBLISH_OK","SUBSCRIBE","REQUEST_UPDATE"])],[rs.AUTHORIZATION_TOKEN,new Set(["PUBLISH","SUBSCRIBE","REQUEST_UPDATE","SUBSCRIBE_NAMESPACE","PUBLISH_NAMESPACE","TRACK_STATUS","FETCH"])],[rs.EXPIRES,new Set(["SUBSCRIBE_OK","PUBLISH","PUBLISH_OK"])],[rs.LARGEST_OBJECT,new Set(["SUBSCRIBE_OK","PUBLISH","REQUEST_OK"])],[rs.FORWARD,new Set(["SUBSCRIBE","REQUEST_UPDATE","PUBLISH","PUBLISH_OK","SUBSCRIBE_NAMESPACE"])],[rs.SUBSCRIBER_PRIORITY,new Set(["SUBSCRIBE","FETCH","REQUEST_UPDATE","PUBLISH_OK"])],[rs.SUBSCRIPTION_FILTER,new Set(["SUBSCRIBE","PUBLISH_OK","REQUEST_UPDATE"])],[rs.GROUP_ORDER,new Set(["SUBSCRIBE","PUBLISH_OK","FETCH"])],[rs.NEW_GROUP_REQUEST,new Set(["PUBLISH_OK","SUBSCRIBE","REQUEST_UPDATE"])],[rs.TRACK_NAMESPACE_PREFIX,new Set(["REQUEST_UPDATE"])]]),ln=new Set([rs.OBJECT_DELIVERY_TIMEOUT,rs.AUTHORIZATION_TOKEN,rs.RENDEZVOUS_TIMEOUT,rs.SUBGROUP_DELIVERY_TIMEOUT,rs.EXPIRES,rs.LARGEST_OBJECT,rs.FILL_TIMEOUT,rs.FORWARD,rs.SUBSCRIBER_PRIORITY,rs.SUBSCRIPTION_FILTER,rs.GROUP_ORDER,rs.NEW_GROUP_REQUEST,rs.TRACK_NAMESPACE_PREFIX]),pn=new Map([[rs.OBJECT_DELIVERY_TIMEOUT,new Set(["PUBLISH_OK","SUBSCRIBE","REQUEST_UPDATE"])],[rs.AUTHORIZATION_TOKEN,new Set(["PUBLISH","SUBSCRIBE","REQUEST_UPDATE","SUBSCRIBE_NAMESPACE","SUBSCRIBE_TRACKS","PUBLISH_NAMESPACE","TRACK_STATUS","FETCH"])],[rs.RENDEZVOUS_TIMEOUT,new Set(["SUBSCRIBE"])],[rs.SUBGROUP_DELIVERY_TIMEOUT,new Set(["PUBLISH_OK","SUBSCRIBE","REQUEST_UPDATE"])],[rs.EXPIRES,new Set(["SUBSCRIBE_OK","PUBLISH","PUBLISH_OK","REQUEST_UPDATE_OK"])],[rs.LARGEST_OBJECT,new Set(["SUBSCRIBE_OK","PUBLISH","REQUEST_UPDATE_OK","TRACK_STATUS_OK"])],[rs.FILL_TIMEOUT,new Set(["FETCH"])],[rs.FORWARD,new Set(["SUBSCRIBE","REQUEST_UPDATE","PUBLISH","PUBLISH_OK","SUBSCRIBE_TRACKS"])],[rs.SUBSCRIBER_PRIORITY,new Set(["SUBSCRIBE","FETCH","REQUEST_UPDATE","PUBLISH_OK"])],[rs.SUBSCRIPTION_FILTER,new Set(["SUBSCRIBE","PUBLISH_OK","REQUEST_UPDATE"])],[rs.GROUP_ORDER,new Set(["SUBSCRIBE","PUBLISH_OK","FETCH"])],[rs.NEW_GROUP_REQUEST,new Set(["PUBLISH_OK","SUBSCRIBE","REQUEST_UPDATE"])],[rs.TRACK_NAMESPACE_PREFIX,new Set(["REQUEST_UPDATE"])]]);function mn(e,t){const s=e.length<=t.length?e:t,i=e.length<=t.length?t:e;for(let e=0;e0n&&this.requestIdAllocator.setOurMaxRequestId(e.maxRequestId),void 0!==e.maxAuthTokenCacheSize&&(this._ownMaxAuthTokenCacheSize=Number(e.maxAuthTokenCacheSize)),this._state=Ar,[this.sendControl(t)]}completeSetup(e={}){if(this.assertState(Ar,"completeSetup"),this._role!==Ur)throw new gn("Only server can call completeSetup","INVALID_STATE");if(18===this._draftVersion){const t=this.setupGate.createSetup18(e);return void 0!==e.maxAuthTokenCacheSize&&(this._ownMaxAuthTokenCacheSize=Number(e.maxAuthTokenCacheSize)),this._state=kr,[this.sendControl(t)]}const t=this.setupGate.createServerSetup(e);return e.maxRequestId&&e.maxRequestId>0n&&this.requestIdAllocator.setOurMaxRequestId(e.maxRequestId),void 0!==e.maxAuthTokenCacheSize&&(this._ownMaxAuthTokenCacheSize=Number(e.maxAuthTokenCacheSize)),this._state=kr,[this.sendControl(t)]}handleControlMessage(e,t){const s=this.applyRequestEndpoint(e,t);if(this._state===Ir||this._state===Ar)return this.handleSetupMessage(s);if(this._state===Pr)throw new gn("Session is closed","INVALID_STATE");const i=this.validateControlMessageParams(s);if(i)return this.closeWithError(i.error,i.reason);try{switch(s.type){case"GOAWAY":return this.handleGoaway(s);case"MAX_REQUEST_ID":return this.handleMaxRequestId(s);case"REQUESTS_BLOCKED":return this.handleRequestsBlocked(s);case"SUBSCRIBE_OK":return this.handleSubscribeOk(s);case"REQUEST_ERROR":return this.handleRequestError(s);case"FETCH_OK":return this.handleFetchOk(s);case"REQUEST_OK":return this.handleRequestOk(s);case"PUBLISH_DONE":return this.handlePublishDone(s);case"UNSUBSCRIBE":return this.handleUnsubscribe(s);case"SUBSCRIBE":return this.handleIncomingSubscribe(s);case"PUBLISH":return this.handleIncomingPublish(s);case"FETCH":return this.handleIncomingFetch(s);case"FETCH_CANCEL":return this.handleFetchCancel(s);case"REQUEST_UPDATE":return this.handleIncomingRequestUpdate(s);case"TRACK_STATUS":return this.handleIncomingTrackStatus(s);case"PUBLISH_NAMESPACE":return this.handleIncomingPublishNamespace(s);case"SUBSCRIBE_NAMESPACE":return 18===this._draftVersion?this.handleIncomingSubscribeNamespace(s):this.handleUnsupportedControlMessage(s);case"SUBSCRIBE_TRACKS":return 18===this._draftVersion?this.handleIncomingSubscribeTracks(s):this.handleUnsupportedControlMessage(s);case"PUBLISH_NAMESPACE_DONE":return this.handlePublishNamespaceDone(s);case"PUBLISH_NAMESPACE_CANCEL":return this.handlePublishNamespaceCancel(s);case"PUBLISH_NAMESPACE_OK":return this.handlePublishNamespaceOk(s);case"PUBLISH_NAMESPACE_ERROR":return this.handlePublishNamespaceError(s);case"UNSUBSCRIBE_NAMESPACE":return this.handleIncomingUnsubscribeNamespace(s);default:return this.handleUnsupportedControlMessage(s)}}catch(e){return this.closeWithError(Ve.PROTOCOL_VIOLATION,e instanceof Error?e.message:String(e))}}handleUnsupportedControlMessage(e){if(14===this._draftVersion)return this.closeWithError(Ve.PROTOCOL_VIOLATION,`Unsupported message type ${e.type}`);if("requestId"in e&&"bigint"==typeof e.requestId){const t=e.requestId;return[this.sendControl({type:"REQUEST_ERROR",requestId:t,errorCode:Ge.NOT_SUPPORTED,retryInterval:Q(0n),errorReason:`Message type ${e.type} is not supported`})]}return[]}applyRequestEndpoint(e,t){if(void 0===t)return e;if("REQUEST_UPDATE"===e.type){const s=e;return void 0!==t.existingRequestId&&void 0===s.existingRequestId?{...s,existingRequestId:t.existingRequestId}:e}return void 0===e.requestId?{...e,requestId:t.requestId}:e}handleSetupMessage(e){try{if(this.setupGate.validateMessage(e),"CLIENT_SETUP"===e.type){const t=this.setupGate.handleClientSetup(e);this._peerMaxRequestId=t.peerMaxRequestId,t.peerMaxRequestId>0n&&this.requestIdAllocator.updatePeerMaxRequestId(t.peerMaxRequestId),void 0!==t.peerMaxAuthTokenCacheSize&&(this._peerMaxAuthTokenCacheSize=t.peerMaxAuthTokenCacheSize),this.initAuthCache(),t.authTokens&&this.processSetupAuthTokens(t.authTokens,!0),this._state=Ar}else if("SERVER_SETUP"===e.type){const t=this.setupGate.handleServerSetup(e);this._peerMaxRequestId=t.peerMaxRequestId,t.peerMaxRequestId>0n&&this.requestIdAllocator.updatePeerMaxRequestId(t.peerMaxRequestId),void 0!==t.peerMaxAuthTokenCacheSize&&(this._peerMaxAuthTokenCacheSize=t.peerMaxAuthTokenCacheSize),this.initAuthCache(),t.authTokens&&this.processSetupAuthTokens(t.authTokens,!1),this._state=kr}else if("SETUP"===e.type){const t=this.setupGate.handleSetup18(e);this._peerMaxRequestId=t.peerMaxRequestId,void 0!==t.peerMaxAuthTokenCacheSize&&(this._peerMaxAuthTokenCacheSize=t.peerMaxAuthTokenCacheSize),this.initAuthCache(),t.authTokens&&this.processSetupAuthTokens(t.authTokens,!0),this._state=this.setupGate.sessionState}return[]}catch(e){if(e instanceof Yr){const t=this.mapSetupErrorCode(e.code);return this.closeWithError(t,e.message)}if(e instanceof jr){const t="PROTOCOL_VIOLATION"===e.code?Ve.PROTOCOL_VIOLATION:Ve.INVALID_REQUEST_ID;return this.closeWithError(t,e.message)}if(e instanceof cn)return this.closeWithError(e.sessionErrorCode,e.message);throw e}}mapSetupErrorCode(e){switch(e){case"INVALID_PATH":return Ve.INVALID_PATH;case"MALFORMED_PATH":return Ve.MALFORMED_PATH;case"INVALID_AUTHORITY":return Ve.INVALID_AUTHORITY;case"MALFORMED_AUTHORITY":return Ve.MALFORMED_AUTHORITY;case"KEY_VALUE_FORMATTING_ERROR":return Ve.KEY_VALUE_FORMATTING_ERROR;case"VERSION_NEGOTIATION_FAILED":return Ve.VERSION_NEGOTIATION_FAILED;default:return Ve.PROTOCOL_VIOLATION}}initAuthCache(){this.authCache=new dn(this._ownMaxAuthTokenCacheSize)}processSetupAuthTokens(e,t){if(this.authCache)for(const s of e)this.processOneToken(s,t)}processOneToken(e,t){if(this.authCache)switch(e.aliasType){case Wr.DELETE:{const t=e;return void this.authCache.delete(t.tokenAlias)}case Wr.REGISTER:{const s=e,i=this.authCache.register(s.tokenAlias,s.tokenType,s.tokenValue,t);return null===i?{tokenType:s.tokenType,tokenValue:s.tokenValue}:i}case Wr.USE_ALIAS:{const t=e;return this.authCache.resolve(t.tokenAlias)}case Wr.USE_VALUE:{const t=e;return{tokenType:t.tokenType,tokenValue:t.tokenValue}}default:return}}processMessageAuthTokens(e){if(!this.authCache)return;const t=[],s=18===this._draftVersion?zr:Qr;for(const i of e){if(!(i instanceof Uint8Array))continue;let e;try{e=s(i)}catch{return{error:Ve.KEY_VALUE_FORMATTING_ERROR,reason:"Malformed AUTHORIZATION_TOKEN structure"}}try{const s=this.processOneToken(e,!1);s&&t.push(s)}catch(e){if(e instanceof cn)return{error:e.sessionErrorCode,reason:e.message};throw e}}for(let e=0;e0)return this.closeWithError(Ve.PROTOCOL_VIOLATION,"Server received GOAWAY with non-empty New Session URI");if(18===this._draftVersion){if(void 0===e.requestId)return this.closeWithError(Ve.PROTOCOL_VIOLATION,"draft-18 control-stream GOAWAY is missing the Request ID");if((1n&e.requestId)!==this.requestIdAllocator.parityBit)return this.closeWithError(Ve.INVALID_REQUEST_ID,`GOAWAY Request ID ${e.requestId} has the wrong parity for this endpoint`)}return this._goawayReceived=!0,this._newSessionUri=e.newSessionUri,this._state=Or,[]}handleMaxRequestId(e){try{return this.requestIdAllocator.updatePeerMaxRequestId(e.maxRequestId),this._peerMaxRequestId=e.maxRequestId,[]}catch(e){if(e instanceof jr)return this.closeWithError(Ve.PROTOCOL_VIOLATION,e.message);throw e}}handleRequestsBlocked(e){return this.maybeReplenishMaxRequestId(!0)}validateAndReplenish(e){try{this.requestIdAllocator.validateIncoming(e)}catch(e){if(e instanceof jr){const t="TOO_MANY_REQUESTS"===e.code?Ve.TOO_MANY_REQUESTS:Ve.INVALID_REQUEST_ID;return{error:this.closeWithError(t,e.message)}}throw e}const t=this.maybeReplenishMaxRequestId();return t.length>0?{replenish:t}:{}}maybeReplenishMaxRequestId(e=!1){if(!e&&!this.requestIdAllocator.shouldReplenish())return[];if(0n===this.requestIdAllocator.getOurMaxRequestId())return[];const t=this.requestIdAllocator.nextReplenishValue();return this.requestIdAllocator.commitReplenish(),[{type:"send_control",message:{type:"MAX_REQUEST_ID",maxRequestId:t}}]}handleSubscribeOk(e){const t=this.subscriptions.get(e.requestId);if(!t)return this.toleratesCrossedOk(e.requestId,"subscribe")?[]:this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for SUBSCRIBE_OK`);t.handleSubscribeOk(e.trackAlias);const s=this.subscriptionTracks.get(e.requestId);if(s)try{this.trackAliases.register(e.trackAlias,s.namespace,s.name,e.requestId)}catch{return this.closeWithError(Ve.DUPLICATE_TRACK_ALIAS,`Duplicate track alias ${e.trackAlias}`)}return[]}handleRequestError(e){if(e.redirect){const t=this.validateRedirectContext(e);if(t)return t}if(this.pendingUpdates.get(e.requestId))return this.pendingUpdates.delete(e.requestId),[];if(this.pendingTrackStatuses.get(e.requestId))return this.pendingTrackStatuses.delete(e.requestId),[];const t=this.subscriptions.get(e.requestId);if(t)return t.handleRequestError(e.errorCode,e.errorReason),void 0!==t.trackAlias&&this.trackAliases.unregister(t.trackAlias,t.requestId),this.subscriptions.delete(e.requestId),this.subscriptionTracks.delete(e.requestId),[];const s=this.fetches.get(e.requestId);if(s)return s.handleRequestError(e.errorCode,e.errorReason),this.fetches.delete(e.requestId),[];const i=this.namespaceSubscriptions.get(e.requestId);if(i)return i.handleRequestError(e.errorCode,e.errorReason),[];const r=this.trackSubscriptions.get(e.requestId);if(r)return r.state="terminated",this.trackSubscriptions.delete(e.requestId),[];const n=this.publishedNamespaces.get(e.requestId);if(n&&"pending"===n.state)return this.publishedNamespaces.delete(e.requestId),[];return this.outgoingPublishes.get(e.requestId)?(this.outgoingPublishes.delete(e.requestId),[]):this.consumeCrossedTerminal(e.requestId,"request_error","subscribe","fetch")?[]:this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for REQUEST_ERROR`)}validateRedirectContext(e){const t=e.requestId,s=e.redirect;if(this._role===Ur&&s.connectUri.length>0)return this.closeWithError(Ve.PROTOCOL_VIOLATION,"REQUEST_ERROR Redirect with a non-empty Connect URI received by a server endpoint (§10.6.2)");if(this.pendingUpdates.has(t)||this.trackSubscriptions.has(t)||this.outgoingPublishes.has(t))return this.closeWithError(Ve.PROTOCOL_VIOLATION,`REQUEST_ERROR Redirect is not valid for this request type (request ${t})`);const i=this.publishedNamespaces.has(t),r=this.namespaceSubscriptions.has(t);return(this.subscriptions.has(t)||this.fetches.has(t)||this.pendingTrackStatuses.has(t)||i||r)&&(i||r)&&s.trackName.length>0?this.closeWithError(Ve.PROTOCOL_VIOLATION,"REQUEST_ERROR Redirect for a namespace-scoped request must have an empty Track Name (§10.6.2)"):null}handleFetchOk(e){const t=this.fetches.get(e.requestId);if(!t)return this.toleratesCrossedOk(e.requestId,"fetch")?[]:this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for FETCH_OK`);if(e.endLocation&&void 0!==t.startGroup){const s=e.endLocation.group,i=e.endLocation.object,r=t.startGroup,n=t.startObject??0n;if(s0&&!this.pendingTrackStatuses.has(e.requestId))return this.closeWithError(Ve.PROTOCOL_VIOLATION,`Track Properties are not valid on this REQUEST_OK (request ${e.requestId})`);if(18===this._draftVersion&&(e.parameters?.size??0)>0){const t=this.d18RequestOkContext(e.requestId);if(t){const s=this.validateMessageParams(e.parameters,t);if(s)return this.closeWithError(s.error,s.reason)}}const t=this.pendingUpdates.get(e.requestId);if(t){if(this.pendingUpdates.delete(e.requestId),void 0!==t.forward){const e=this.subscriptions.get(t.existingRequestId)??this.incomingSubscriptions.get(t.existingRequestId);e&&("pending"===e.state?e.setInitialForwardState(t.forward):"established"===e.state&&e.updateForwardState(t.forward))}if(void 0!==t.objectDeliveryTimeoutMs||void 0!==t.subgroupDeliveryTimeoutMs){const e=this.subscriptions.get(t.existingRequestId)??this.incomingSubscriptions.get(t.existingRequestId);e&&(void 0!==t.objectDeliveryTimeoutMs&&(e.requestedDeliveryTimeoutMs=t.objectDeliveryTimeoutMs),void 0!==t.subgroupDeliveryTimeoutMs&&(e.requestedSubgroupDeliveryTimeoutMs=t.subgroupDeliveryTimeoutMs))}if(t.namespacePrefix&&t.prefixTarget)if("namespace"===t.prefixTarget)this.namespaceSubscriptions.get(t.existingRequestId)?.updatePrefix(t.namespacePrefix);else{const e=this.trackSubscriptions.get(t.existingRequestId);e&&(e.trackNamespacePrefix=t.namespacePrefix)}return[]}if(this.pendingTrackStatuses.get(e.requestId))return this.pendingTrackStatuses.delete(e.requestId),[];const s=this.namespaceSubscriptions.get(e.requestId);if(s)return s.handleRequestOk(),[];const i=this.trackSubscriptions.get(e.requestId);if(i)return i.state="active",[];const r=this.publishedNamespaces.get(e.requestId);if(r&&"pending"===r.state)return r.state="active",[];const n=this.outgoingPublishes.get(e.requestId);return n&&n.state===Mr?(n.acceptOutboundPublish(),[]):this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for REQUEST_OK`)}handlePublishDone(e){if(this.pendingTrackStatuses.has(e.requestId))return this.closeWithError(Ve.PROTOCOL_VIOLATION,`Received PUBLISH_DONE for TRACK_STATUS request ${e.requestId}`);const t=this.subscriptions.get(e.requestId);return t?(t.handlePublishDone(e.statusCode,e.errorReason),void 0!==t.trackAlias&&this.trackAliases.unregister(t.trackAlias,t.requestId),this.subscriptions.delete(e.requestId),this.subscriptionTracks.delete(e.requestId),[]):this.consumeCrossedTerminal(e.requestId,"publish_done","subscribe")?[]:this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for PUBLISH_DONE`)}handleUnsubscribe(e){const t=this.incomingSubscriptions.get(e.requestId);return t?(t.handleUnsubscribe(),void 0!==t.trackAlias&&this.trackAliases.unregister(t.trackAlias,t.requestId),this.incomingSubscriptions.delete(e.requestId),[]):this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for UNSUBSCRIBE`)}validateFullName18(e,t){if(18!==this._draftVersion)return null;try{ut(e,t,{allowEmptyNamespace:!0})}catch(e){return this.closeWithError(Ve.PROTOCOL_VIOLATION,e instanceof Error?e.message:"invalid Full Track Name (§2.4.1)")}return null}validateNamespace18(e){if(18!==this._draftVersion)return null;try{at(e,{allowEmpty:!0})}catch(e){return this.closeWithError(Ve.PROTOCOL_VIOLATION,e instanceof Error?e.message:"invalid Track Namespace (§2.4.1)")}return null}handleIncomingSubscribe(e){const t=this.validateFullName18(e.trackNamespace,e.trackName);if(t)return t;const s=this.validateAndReplenish(e.requestId);if(s.error)return s.error;const i=this.rejectReservedNamespace(e.trackNamespace,e.requestId,s.replenish);if(i)return i;const r=Zr.createAsPublisher(e.requestId,e.trackNamespace,e.trackName);if(14!==this._draftVersion&&void 0!==r.trackKey&&(this.findLiveIncomingByTrack(r.trackKey,!1)||this.findLiveOutboundPublishByTrack(r.trackKey))){const t={type:"REQUEST_ERROR",requestId:e.requestId,errorCode:Ge.DUPLICATE_SUBSCRIPTION,retryInterval:Q(0n),errorReason:"Duplicate subscription: a publisher-role subscription for this track already exists (§5.1)"};return[this.sendControl(t),...s.replenish??[]]}const n=e.parameters.get(rs.SUBSCRIPTION_FILTER),a=n?.[0];if(a instanceof Uint8Array)try{r.setRemoteFilterType(an(a,this._draftVersion).type)}catch{}const o=e.parameters.get(rs.FORWARD),c=o?.[0];return"bigint"==typeof c&&r.setInitialForwardState(0n===c?Br:xr),this.incomingSubscriptions.set(e.requestId,r),s.replenish??[]}handleIncomingPublish(e){const t=this.validateFullName18(e.trackNamespace,e.trackName);if(t)return t;const s=this.validateAndReplenish(e.requestId);if(s.error)return s.error;const i=Zr.createFromPublish(e.requestId,e.trackNamespace,e.trackName,e.parameters,e.trackAlias);if(14!==this._draftVersion&&void 0!==i.trackKey){const t=this.findLiveOutboundSubscribeByTrack(i.trackKey);if(this.findLiveIncomingByTrack(i.trackKey,!0)||t&&"established"===t.state)return[this.buildPublishReject(e.requestId,Ge.DUPLICATE_SUBSCRIPTION,"Duplicate subscription: a subscriber-role subscription for this track already exists (§5.1)"),...s.replenish??[]];t&&"pending"===t.state&&this.pendingCollisions.set(e.requestId,t.requestId)}try{this.trackAliases.register(e.trackAlias,e.trackNamespace,e.trackName,e.requestId)}catch{return this.closeWithError(Ve.DUPLICATE_TRACK_ALIAS,`Duplicate track alias ${e.trackAlias} in PUBLISH`)}return this.incomingSubscriptions.set(e.requestId,i),s.replenish??[]}findLiveIncomingByTrack(e,t){for(const s of this.incomingSubscriptions.values())if(s.trackKey===e&&s.isPublishInitiated===t&&!s.isTerminated)return s}findLiveOutboundSubscribeByTrack(e){for(const t of this.subscriptions.values())if(t.trackKey===e&&!t.isTerminated)return t}findLiveOutboundPublishByTrack(e){for(const t of this.outgoingPublishes.values())if(t.trackKey===e&&!t.isTerminated)return t}cancelStagedCollision(e){const t=this.pendingCollisions.get(e);if(void 0===t)return[];this.pendingCollisions.delete(e);const s=this.subscriptions.get(t);if(!s||s.isTerminated)return[];this.terminateLocalSubscriberRequest(s);const i={type:"cancel_request",requestId:t,reason:"local SUBSCRIBE superseded by a peer PUBLISH for the same track (§5.1)"};return 18===this._draftVersion?[i]:[this.sendControl({type:"UNSUBSCRIBE",requestId:t}),i]}terminateLocalSubscriberRequest(e){const t=e.requestId,s=!e.isPending;e.isTerminated||e.supersede(),void 0!==e.trackAlias&&this.trackAliases.unregister(e.trackAlias,t),this.subscriptions.delete(t),this.subscriptionTracks.delete(t),this.recordCancellation(t,"subscribe",s)}recordCancellation(e,t,s){this.recentlyCancelled.delete(e),this.recentlyCancelled.set(e,{kind:t,phase:s?"established":"pending"})}toleratesCrossedOk(e,t){const s=this.recentlyCancelled.get(e);return!(!s||s.kind!==t||"pending"!==s.phase)&&("fetch"===t?this.recentlyCancelled.delete(e):s.phase="established",!0)}consumeCrossedTerminal(e,t,...s){const i=this.recentlyCancelled.get(e);return!(!i||!s.includes(i.kind))&&(("request_error"!==t||"established"!==i.phase)&&(this.recentlyCancelled.delete(e),!0))}isCancelledRequest(e){return this.recentlyCancelled.has(e)}buildPublishReject(e,t,s){return 14===this._draftVersion?this.sendControl({type:"PUBLISH_ERROR",requestId:e,errorCode:Q(t),errorReason:s}):this.sendControl({type:"REQUEST_ERROR",requestId:e,errorCode:t,retryInterval:Q(0n),errorReason:s})}handleIncomingFetch(e){if(1===e.fetch.fetchType){const t=e.fetch,s=this.validateFullName18(t.trackNamespace,t.trackName);if(s)return s}const t=this.validateAndReplenish(e.requestId);if(t.error)return t.error;if(1!==e.fetch.fetchType){const s=e.fetch,i=s.joiningRequestId,r=this.incomingSubscriptions.get(i);if(!(void 0!==r&&(r.state===Mr||r.state===Lr))){const s={type:"REQUEST_ERROR",requestId:e.requestId,errorCode:Ge.INVALID_JOINING_REQUEST_ID,retryInterval:Q(0n),errorReason:`Joining Fetch references request ${i}, which is not a subscription in PENDING/ESTABLISHED state (§9.16.2)`};return[this.sendControl(s),...t.replenish??[]]}if(18===this._draftVersion){if(r.state===Lr&&r.forwardState!==xr){const s={type:"REQUEST_ERROR",requestId:e.requestId,errorCode:Ge.INVALID_RANGE,retryInterval:Q(0n),errorReason:`Joining Fetch on subscription ${i} with Forward State 0 (§10.12.2)`};return[this.sendControl(s),...t.replenish??[]]}}else if("LargestObject"!==r.remoteFilterType)return this.closeWithError(Ve.PROTOCOL_VIOLATION,`Joining Fetch on subscription ${i} whose filter is ${r.remoteFilterType??"unfiltered"}, not Largest Object (§9.16.2)`);const n=en.createAsJoiningPublisher(e.requestId,{fetchType:e.fetch.fetchType,joiningRequestId:i,joiningStart:s.joiningStart});return this.incomingFetches.set(e.requestId,n),t.replenish??[]}const s=e.fetch,i=this.rejectReservedNamespace(s.trackNamespace,e.requestId,t.replenish);if(i)return i;const r=en.createAsPublisher(e.requestId,s.startLocation.group,s.startLocation.object,s.endLocation.group,s.endLocation.object);return this.incomingFetches.set(e.requestId,r),t.replenish??[]}handleFetchCancel(e){const t=this.incomingFetches.get(e.requestId);return t?(t.handleFetchCancel(),this.incomingFetches.delete(e.requestId),[]):this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for FETCH_CANCEL`)}handleIncomingRequestUpdate(e){const t=this.validateAndReplenish(e.requestId);if(t.error)return t.error;if(this.incomingNamespaceSubscriptions.has(e.existingRequestId)||this.incomingTrackSubscriptions.has(e.existingRequestId))return this.handleIncomingPrefixUpdate(e,t.replenish);if(18===this._draftVersion&&e.parameters.has(rs.TRACK_NAMESPACE_PREFIX))return this.closeWithError(Ve.PROTOCOL_VIOLATION,"TRACK_NAMESPACE_PREFIX is out of scope for a REQUEST_UPDATE that does not target a SUBSCRIBE_NAMESPACE/SUBSCRIBE_TRACKS (§10.2.14)");const s=this.incomingSubscriptions.get(e.existingRequestId)??this.outgoingPublishes.get(e.existingRequestId),i=this.incomingFetches.get(e.existingRequestId),r=this.incomingPublishNamespaces.get(e.existingRequestId);if(!s&&!i&&!r)return this.closeWithError(Ve.PROTOCOL_VIOLATION,`REQUEST_UPDATE references unknown Existing Request ID ${e.existingRequestId}`);if(r&&!s&&!i){if(14===this._draftVersion)return t.replenish??[];const s={type:"REQUEST_OK",requestId:e.requestId,parameters:new Map};return[this.sendControl(s),...t.replenish??[]]}if(s&&"established"!==s.state&&(18!==this._draftVersion||"pending"!==s.state||s.isPublishInitiated))return this.closeWithError(Ve.PROTOCOL_VIOLATION,`REQUEST_UPDATE for subscription ${e.existingRequestId} in state ${s.state}; expected established`);if(i&&"transferring"!==i.state)return this.closeWithError(Ve.PROTOCOL_VIOLATION,`REQUEST_UPDATE for fetch ${e.existingRequestId} in state ${i.state}; expected transferring`);if(i){const t=[rs.FORWARD,rs.SUBSCRIPTION_FILTER,rs.NEW_GROUP_REQUEST];for(const s of t)if(e.parameters.has(s))return this.closeWithError(Ve.PROTOCOL_VIOLATION,`Parameter 0x${s.toString(16)} is not valid for REQUEST_UPDATE on a fetch (§9.11)`)}const n=e.parameters.get(rs.FORWARD);if(n&&n.length>0&&s){const e=n[0];if("bigint"==typeof e){const t=0n===e?Br:xr;"pending"===s.state?s.setInitialForwardState(t):s.updateForwardState(t)}}const a=e.parameters.get(rs.SUBSCRIPTION_FILTER)?.[0];if(a instanceof Uint8Array&&s)try{s.setRemoteFilterType(an(a,this._draftVersion).type)}catch{}if(s){const t=e.parameters.get(rs.OBJECT_DELIVERY_TIMEOUT)?.[0];"bigint"==typeof t&&(s.requestedDeliveryTimeoutMs=Number(t));const i=e.parameters.get(rs.SUBGROUP_DELIVERY_TIMEOUT)?.[0];"bigint"==typeof i&&(s.requestedSubgroupDeliveryTimeoutMs=Number(i))}if(14===this._draftVersion)return t.replenish??[];const o={type:"REQUEST_OK",requestId:e.requestId,parameters:new Map};return[this.sendControl(o),...t.replenish??[]]}handleIncomingPrefixUpdate(e,t){const s=e.existingRequestId,i=this.incomingNamespaceSubscriptions.get(s),r=this.incomingTrackSubscriptions.get(s);if(!(i?i.isActive:"active"===r?.state))return this.closeWithError(Ve.PROTOCOL_VIOLATION,`REQUEST_UPDATE for ${i?"SUBSCRIBE_NAMESPACE":"SUBSCRIBE_TRACKS"} ${s} before it was accepted`);const n=e.parameters.get(rs.TRACK_NAMESPACE_PREFIX),a=n&&n.length>0?n[n.length-1]:void 0;if(void 0===a){const s={type:"REQUEST_OK",requestId:e.requestId,parameters:new Map};return[this.sendControl(s),...t??[]]}if(!Array.isArray(a))return this.closeWithError(Ve.PROTOCOL_VIOLATION,"TRACK_NAMESPACE_PREFIX value is not a Track Namespace tuple");try{ht(a)}catch(e){return this.closeWithError(Ve.PROTOCOL_VIOLATION,e instanceof Error?e.message:"Malformed Track Namespace Prefix in REQUEST_UPDATE")}if(i){for(const[i,r]of this.incomingNamespaceSubscriptions)if(i!==s&&!r.isTerminated&&mn(r.namespacePrefix,a))return this.prefixOverlapError(e.requestId,"SUBSCRIBE_NAMESPACE",s,t);i.updatePrefix(a)}else if(r){for(const[i,r]of this.incomingTrackSubscriptions)if(i!==s&&mn(r.trackNamespacePrefix,a))return this.prefixOverlapError(e.requestId,"SUBSCRIBE_TRACKS",s,t);r.trackNamespacePrefix=a}const o={type:"REQUEST_OK",requestId:e.requestId,parameters:new Map};return[this.sendControl(o),...t??[]]}prefixOverlapError(e,t,s,i){"SUBSCRIBE_NAMESPACE"===t&&this.incomingNamespaceSubscriptions.delete(s);const r={type:"REQUEST_ERROR",requestId:e,errorCode:Ge.PREFIX_OVERLAP,retryInterval:Q(0n),errorReason:`Track Namespace Prefix overlaps an existing ${t}`,..."SUBSCRIBE_NAMESPACE"===t?{requestKind:"SUBSCRIBE_NAMESPACE"}:{}};return[this.sendControl(r),...i??[]]}handleIncomingTrackStatus(e){const t=this.validateFullName18(e.trackNamespace,e.trackName);if(t)return t;const s=this.validateAndReplenish(e.requestId);if(s.error)return s.error;const i=this.rejectReservedNamespace(e.trackNamespace,e.requestId,s.replenish);return i||(this.incomingTrackStatuses.set(e.requestId,{namespace:e.trackNamespace,name:e.trackName}),s.replenish??[])}subscribe(e,t,s={}){if(this.assertEstablishedOrDraining("subscribe"),this._state===Or)throw new fn("Cannot create new subscriptions after GOAWAY; session is DRAINING",this._newSessionUri??"");const i=this.requestIdAllocator.allocate(),r=Zr.createAsSubscriber(i,e,t);this.subscriptions.set(i,r),this.subscriptionTracks.set(i,{namespace:e,name:t});const n=new Map;if(void 0!==s.deliveryTimeout&&(n.set(rs.DELIVERY_TIMEOUT,[s.deliveryTimeout]),r.requestedDeliveryTimeoutMs=Number(s.deliveryTimeout)),void 0!==s.subscriberPriority&&(n.set(rs.SUBSCRIBER_PRIORITY,[s.subscriberPriority]),r.currentPriority=s.subscriberPriority),void 0!==s.groupOrder&&n.set(rs.GROUP_ORDER,[s.groupOrder]),void 0!==s.forward&&(n.set(rs.FORWARD,[Q(BigInt(s.forward))]),r.setInitialForwardState(s.forward)),void 0!==s.subscriptionFilter){const e=nn(s.subscriptionFilter,this._draftVersion);n.set(rs.SUBSCRIPTION_FILTER,[e]),r.currentFilter=e}const a={type:"SUBSCRIBE",requestId:i,trackNamespace:e,trackName:t,parameters:n};return{requestId:i,actions:[this.sendControl(a)]}}publish(e,t,s,i={}){if(this.assertEstablishedOrDraining("publish"),this.assertNotReservedNamespace(e,"publish"),this._state===Or)throw new fn("Cannot PUBLISH after GOAWAY; session is DRAINING",this._newSessionUri??"");const r=this.resolveTrackProperties(i.trackProperties,"PUBLISH"),n=this.requestIdAllocator.allocate(),a=Zr.createAsPublisher(n,e,t);a.setOutboundPublishAlias(s),this.outgoingPublishes.set(n,a);const o={type:"PUBLISH",requestId:n,trackNamespace:e,trackName:t,trackAlias:s,parameters:i.parameters??new Map,trackProperties:r};return{requestId:n,actions:[this.sendControl(o)]}}getOutgoingPublish(e){return this.outgoingPublishes.get(e)}getSubscription(e){return this.subscriptions.get(e)}unsubscribe(e){const t=this.subscriptions.get(e);if(!t)throw new gn(`Unknown subscription ${e} for unsubscribe`,"INVALID_STATE");return this.terminateLocalSubscriberRequest(t),18===this._draftVersion?[]:[this.sendControl({type:"UNSUBSCRIBE",requestId:e})]}rollbackRequestUpdate(e){this.pendingUpdates.delete(e)}requestUpdate(e,t={}){if(this.assertEstablishedOrDraining("requestUpdate"),this.namespaceSubscriptions.has(e)||this.trackSubscriptions.has(e))return this.requestUpdatePrefix(e,t);const s=this.subscriptions.get(e);if(!s)throw new gn(`Unknown subscription ${e} for REQUEST_UPDATE`,"INVALID_STATE");if(void 0!==t.trackNamespacePrefix)throw new gn(`trackNamespacePrefix is only valid for a SUBSCRIBE_NAMESPACE / SUBSCRIBE_TRACKS update, not subscription ${e}`,"INVALID_STATE");const i=18===this._draftVersion&&"pending"===s.state;if("established"!==s.state&&!i)throw new gn(`Cannot update subscription in state ${s.state}; expected established`,"INVALID_STATE");const r=this.requestIdAllocator.allocate(),n=new Map;if(void 0!==t.forward)n.set(rs.FORWARD,[Q(BigInt(t.forward))]);else if(14===this._draftVersion){const e=Q(BigInt(s.forwardState));n.set(rs.FORWARD,[e])}if(void 0!==t.subscriberPriority?(n.set(rs.SUBSCRIBER_PRIORITY,[t.subscriberPriority]),s.currentPriority=t.subscriberPriority):14===this._draftVersion&&void 0!==s.currentPriority&&n.set(rs.SUBSCRIBER_PRIORITY,[s.currentPriority]),void 0!==t.subscriptionFilter){const e=nn(t.subscriptionFilter,this._draftVersion);n.set(rs.SUBSCRIPTION_FILTER,[e]),s.currentFilter=e}else 14===this._draftVersion&&s.currentFilter&&n.set(rs.SUBSCRIPTION_FILTER,[s.currentFilter]);if(void 0!==t.subgroupDeliveryTimeout&&18!==this._draftVersion)throw new gn("subgroupDeliveryTimeout (SUBGROUP_DELIVERY_TIMEOUT, 0x06) is draft-18 only","INVALID_STATE");if(void 0!==t.objectDeliveryTimeout&&n.set(rs.OBJECT_DELIVERY_TIMEOUT,[t.objectDeliveryTimeout]),void 0!==t.subgroupDeliveryTimeout&&n.set(rs.SUBGROUP_DELIVERY_TIMEOUT,[t.subgroupDeliveryTimeout]),14===this._draftVersion)void 0!==t.forward&&s.updateForwardState(t.forward),void 0!==t.objectDeliveryTimeout&&(s.requestedDeliveryTimeoutMs=Number(t.objectDeliveryTimeout));else{const s={existingRequestId:e};void 0!==t.forward&&(s.forward=t.forward?xr:Br),void 0!==t.objectDeliveryTimeout&&(s.objectDeliveryTimeoutMs=Number(t.objectDeliveryTimeout)),void 0!==t.subgroupDeliveryTimeout&&(s.subgroupDeliveryTimeoutMs=Number(t.subgroupDeliveryTimeout)),this.pendingUpdates.set(r,s)}const a={type:"REQUEST_UPDATE",requestId:r,existingRequestId:e,parameters:n};return{requestId:r,actions:[this.sendControl(a)]}}requestUpdatePrefix(e,t){if(18!==this._draftVersion)throw new gn(`Track Namespace Prefix REQUEST_UPDATE requires draft-18 (current draft-${this._draftVersion})`,"INVALID_STATE");const s=this.namespaceSubscriptions.get(e),i=this.trackSubscriptions.get(e),r=s?"namespace":"tracks";if(s&&!s.isActive)throw new gn(`Cannot update SUBSCRIBE_NAMESPACE ${e}: not active`,"INVALID_STATE");if(i&&"active"!==i.state)throw new gn(`Cannot update SUBSCRIBE_TRACKS ${e}: not active`,"INVALID_STATE");const n=t.trackNamespacePrefix;if(!n)throw new gn(`REQUEST_UPDATE for a ${"namespace"===r?"SUBSCRIBE_NAMESPACE":"SUBSCRIBE_TRACKS"} requires trackNamespacePrefix`,"INVALID_STATE");try{ht(n)}catch(e){throw new gn(e instanceof Error?e.message:"Malformed Track Namespace Prefix","PROTOCOL_VIOLATION")}const a=this.requestIdAllocator.allocate(),o=new Map([[rs.TRACK_NAMESPACE_PREFIX,[n]]]);this.pendingUpdates.set(a,{existingRequestId:e,namespacePrefix:n,prefixTarget:r});const c={type:"REQUEST_UPDATE",requestId:a,existingRequestId:e,parameters:o};return{requestId:a,actions:[this.sendControl(c)]}}fetch(e,t,s){if(this.assertEstablishedOrDraining("fetch"),this._state===Or)throw new fn("Cannot create new fetches after GOAWAY; session is DRAINING",this._newSessionUri??"");const i=this.requestIdAllocator.allocate(),r=en.createAsFetcher(i,s.startGroup,s.startObject,s.endGroup,s.endObject);this.fetches.set(i,r);const n={group:s.startGroup,object:s.startObject},a={group:s.endGroup??0n,object:s.endObject??0n};if(a.groupt.group)throw new RangeError(`Absolute Joining Fetch start group ${e.joiningStart} > largest group ${t.group} — §9.16.3 INVALID_RANGE`);return{startLocation:{group:e.joiningStart,object:0n},endLocation:s}}return{startLocation:{group:e.joiningStart>t.group?0n:t.group-e.joiningStart,object:0n},endLocation:s}}({fetchType:i.fetchType,joiningStart:i.joiningStart},t);return s.setResolvedRange(r.startLocation.group,r.startLocation.object,r.endLocation.group,r.endLocation.object),r}getFetch(e){return this.fetches.get(e)}fetchCancel(e){const t=this.fetches.get(e);if(!t)throw new gn(`Unknown fetch ${e} for FETCH_CANCEL`,"INVALID_STATE");const s=t.isTransferring;if(t.sendFetchCancel(),this.fetches.delete(e),s||this.recordCancellation(e,"fetch",!1),18===this._draftVersion)return[];const i={type:"FETCH_CANCEL",requestId:e};return[this.sendControl(i)]}handleFetchStreamFinished(e){const t=this.fetches.get(e);t&&(t.markDataFinished(),t.isFetcherComplete&&this.fetches.delete(e))}reclaimServedFetch(e){const t=this.incomingFetches.get(e);t&&(t.markDataFinished(),t.isPublisherComplete&&this.incomingFetches.delete(e))}getTrackByAlias(e){return this.trackAliases.getByAlias(e)}subscribeNamespace(e,t=Q(0n)){if(this.assertEstablishedOrDraining("subscribeNamespace"),this._state===Or)throw new fn("Cannot create new namespace subscriptions after GOAWAY; session is DRAINING",this._newSessionUri??"");const s=this.requestIdAllocator.allocate(),i=tn.createAsSubscriber(s,e);this.namespaceSubscriptions.set(s,i);const r={type:"SUBSCRIBE_NAMESPACE",requestId:s,trackNamespacePrefix:e,...14===this._draftVersion?{}:{subscribeOptions:t},parameters:new Map};if(14===this._draftVersion)return{requestId:s,actions:[this.sendControl(r)]};return{requestId:s,actions:[{type:"open_namespace_stream",requestId:s,message:r}]}}subscribeTracks(e){if(this.assertEstablishedOrDraining("subscribeTracks"),this._state===Or)throw new fn("Cannot create new track subscriptions after GOAWAY; session is DRAINING",this._newSessionUri??"");if(18!==this._draftVersion)throw new gn("SUBSCRIBE_TRACKS is a draft-18 message","INVALID_STATE");const t=this.requestIdAllocator.allocate();this.trackSubscriptions.set(t,{trackNamespacePrefix:e,state:"pending",blockedTracks:[]});const s={type:"SUBSCRIBE_TRACKS",requestId:t,trackNamespacePrefix:e,parameters:new Map};return{requestId:t,actions:[this.sendControl(s)]}}getTrackSubscription(e){return this.trackSubscriptions.get(e)}handleSubscribeTracksStreamMessage(e,t){const s=this.trackSubscriptions.get(e);if(!s)return this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e} for SUBSCRIBE_TRACKS stream message`);if("PUBLISH_BLOCKED"===t.type){if("active"!==s.state)return this.closeWithError(Ve.PROTOCOL_VIOLATION,"PUBLISH_BLOCKED received before SUBSCRIBE_TRACKS was accepted");const e=t;return s.blockedTracks.push({trackNamespaceSuffix:e.trackNamespaceSuffix,trackName:e.trackName}),[]}return this.closeWithError(Ve.PROTOCOL_VIOLATION,`Unexpected ${t.type} on a SUBSCRIBE_TRACKS response stream`)}handleSubscribeTracksStreamClosed(e){const t=this.trackSubscriptions.get(e);return t?(t.state="terminated",this.trackSubscriptions.delete(e),[]):[]}publishNamespace(e){if(this.assertEstablishedOrDraining("publishNamespace"),this.assertNotReservedNamespace(e,"publishNamespace"),this._state===Or)throw new fn("Cannot send PUBLISH_NAMESPACE after GOAWAY; session is DRAINING",this._newSessionUri??"");const t=this.requestIdAllocator.allocate();this.publishedNamespaces.set(t,{namespace:e,state:"pending"});const s={type:"PUBLISH_NAMESPACE",requestId:t,trackNamespace:e,parameters:new Map};return{requestId:t,actions:[this.sendControl(s)]}}publishNamespaceDone(e){this.assertEstablishedOrDraining("publishNamespaceDone");const t=this.publishedNamespaces.get(e);if(!t)throw new gn(`Unknown request ID ${e} for publishNamespaceDone`,"INVALID_STATE");if("active"!==t.state)throw new gn(`Cannot withdraw pending namespace (requestId=${e})`,"INVALID_STATE");if(this.publishedNamespaces.delete(e),18===this._draftVersion)return[];const s=14===this._draftVersion?{type:"PUBLISH_NAMESPACE_DONE",trackNamespace:t.namespace}:{type:"PUBLISH_NAMESPACE_DONE",requestId:e};return[this.sendControl(s)]}trackStatus(e,t){if(this.assertEstablishedOrDraining("trackStatus"),this._state===Or)throw new fn("Cannot send TRACK_STATUS after GOAWAY; session is DRAINING",this._newSessionUri??"");const s=this.requestIdAllocator.allocate();this.pendingTrackStatuses.set(s,{namespace:e,name:t});const i={type:"TRACK_STATUS",requestId:s,trackNamespace:e,trackName:t,parameters:new Map};return{requestId:s,actions:[this.sendControl(i)]}}resolveTrackProperties(e,t){const s=e??new Map;if(18!==this._draftVersion&&s.size>0)throw new gn(`Track Properties on ${t} require draft-18 (current draft-${this._draftVersion})`,"INVALID_STATE");return s}acceptTrackStatus(e,t=new Map){if(!this.incomingTrackStatuses.get(e))throw new gn(`Unknown incoming TRACK_STATUS ${e}`,"INVALID_STATE");const s=t instanceof Map?{parameters:t}:t,i=s.parameters??new Map,r=this.resolveTrackProperties(s.trackProperties,"TRACK_STATUS_OK");this.incomingTrackStatuses.delete(e);const n={type:"REQUEST_OK",requestId:e,parameters:i,...r.size>0?{trackProperties:r}:{}};return[this.sendControl(n)]}rejectTrackStatus(e,t,s){if(!this.incomingTrackStatuses.get(e))throw new gn(`Unknown incoming TRACK_STATUS ${e}`,"INVALID_STATE");this.incomingTrackStatuses.delete(e);const i={type:"REQUEST_ERROR",requestId:e,errorCode:t,retryInterval:Q(0n),errorReason:s,requestKind:"TRACK_STATUS"};return[this.sendControl(i)]}getIncomingTrackStatus(e){return this.incomingTrackStatuses.get(e)}getPendingTrackStatus(e){return this.pendingTrackStatuses.get(e)}handleNamespaceStreamClosed(e){const t=this.namespaceSubscriptions.get(e);return t?(t.isActive&&t.handleNamespaceDone(),this.namespaceSubscriptions.delete(e),[]):[]}handleNamespaceStreamMessage(e,t){const s=this.namespaceSubscriptions.get(e);if(!s)return this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e} for namespace stream message`);switch(t.type){case"REQUEST_OK":return s.handleRequestOk(),[];case"REQUEST_ERROR":{const e=t;return s.handleRequestError(e.errorCode,e.errorReason),[]}case"NAMESPACE":{const e=t,i=this.validateCombinedNamespace(s.namespacePrefix,e.trackNamespaceSuffix);return i||(s.handleNamespace(e.trackNamespaceSuffix),[])}case"NAMESPACE_DONE":{const e=t,i=this.validateCombinedNamespace(s.namespacePrefix,e.trackNamespaceSuffix);return i||(s.hasDiscoveredSuffix(e.trackNamespaceSuffix)?(s.handleNamespaceDone(),[]):this.closeWithError(Ve.PROTOCOL_VIOLATION,"NAMESPACE_DONE for suffix not previously announced via NAMESPACE (§6.1)"))}default:return this.closeWithError(Ve.PROTOCOL_VIOLATION,`Unexpected message type ${t.type} on namespace stream`)}}getNamespaceSubscription(e){return this.namespaceSubscriptions.get(e)}handleIncomingPublishNamespace(e){const t=this.validateNamespace18(e.trackNamespace);if(t)return t;const s=this.validateAndReplenish(e.requestId);if(s.error)return s.error;const i=this.rejectReservedNamespace(e.trackNamespace,e.requestId,s.replenish);if(i)return i;const r=this.findNamespaceSubscriptionByPrefix(e.trackNamespace),n=14===this._draftVersion;if(!r){if(n){const t={type:"PUBLISH_NAMESPACE_ERROR",requestId:e.requestId,errorCode:Q(0x4n),errorReason:"No matching namespace subscription"};return[this.sendControl(t),...s.replenish??[]]}const t={type:"REQUEST_OK",requestId:e.requestId,parameters:new Map},i={type:"notify_namespace",requestId:e.requestId,message:e};return 18===this._draftVersion&&this.incomingPublishNamespaces.set(e.requestId,{namespace:e.trackNamespace}),[this.sendControl(t),i,...s.replenish??[]]}r.nsSm.handleNamespace(e.trackNamespace),18===this._draftVersion&&this.incomingPublishNamespaces.set(e.requestId,{namespace:e.trackNamespace});const a=n?{type:"PUBLISH_NAMESPACE_OK",requestId:e.requestId}:{type:"REQUEST_OK",requestId:e.requestId,parameters:new Map},o={type:"notify_namespace",requestId:r.nsSm.requestId,message:e};return[this.sendControl(a),o,...s.replenish??[]]}handleInboundPublishNamespaceClosed(e){const t=this.incomingPublishNamespaces.get(e);if(!t)return[];this.incomingPublishNamespaces.delete(e);const s=this.findNamespaceSubscriptionByPrefix(t.namespace);return s&&s.nsSm.withdrawNamespace(t.namespace),[]}handleIncomingSubscribeNamespace(e){const t=this.validateAndReplenish(e.requestId);if(t.error)return t.error;try{ht(e.trackNamespacePrefix)}catch(e){return this.closeWithError(Ve.PROTOCOL_VIOLATION,e instanceof Error?e.message:"Malformed SUBSCRIBE_NAMESPACE prefix")}const s=this.rejectReservedNamespace(e.trackNamespacePrefix,e.requestId,t.replenish);if(s)return s;for(const s of this.incomingNamespaceSubscriptions.values())if(!s.isTerminated&&mn(s.namespacePrefix,e.trackNamespacePrefix)){const s={type:"REQUEST_ERROR",requestId:e.requestId,errorCode:Ge.PREFIX_OVERLAP,retryInterval:Q(0n),errorReason:"Track Namespace Prefix overlaps an existing SUBSCRIBE_NAMESPACE",requestKind:"SUBSCRIBE_NAMESPACE"};return[this.sendControl(s),...t.replenish??[]]}const i=tn.createAsPublisher(e.requestId,e.trackNamespacePrefix);return this.incomingNamespaceSubscriptions.set(e.requestId,i),t.replenish??[]}acceptSubscribeNamespace(e,t=new Map){const s=this.incomingNamespaceSubscriptions.get(e);if(!s)throw new gn(`Unknown incoming SUBSCRIBE_NAMESPACE ${e}`,"INVALID_STATE");s.sendRequestOk();const i={type:"REQUEST_OK",requestId:e,parameters:t};return[this.sendControl(i)]}rejectSubscribeNamespace(e,t,s){if(!this.incomingNamespaceSubscriptions.get(e))throw new gn(`Unknown incoming SUBSCRIBE_NAMESPACE ${e}`,"INVALID_STATE");this.incomingNamespaceSubscriptions.delete(e);const i={type:"REQUEST_ERROR",requestId:e,errorCode:t,retryInterval:Q(0n),errorReason:s,requestKind:"SUBSCRIBE_NAMESPACE"};return[this.sendControl(i)]}sendNamespace(e,t){this.requireActiveIncomingNamespaceSub(e,"sendNamespace").sendNamespace(t);const s={type:"NAMESPACE",trackNamespaceSuffix:t};return[this.sendControl(s)]}sendNamespaceDone(e,t){this.requireActiveIncomingNamespaceSub(e,"sendNamespaceDone").withdrawNamespace(t);const s={type:"NAMESPACE_DONE",trackNamespaceSuffix:t};return[this.sendControl(s)]}requireActiveIncomingNamespaceSub(e,t){const s=this.incomingNamespaceSubscriptions.get(e);if(!s)throw new gn(`Unknown incoming SUBSCRIBE_NAMESPACE ${e}`,"INVALID_STATE");if(!s.isActive)throw new gn(`Cannot ${t} for SUBSCRIBE_NAMESPACE ${e}: not accepted`,"INVALID_STATE");return s}getIncomingNamespaceSubscription(e){return this.incomingNamespaceSubscriptions.get(e)}handleInboundSubscribeNamespaceClosed(e){return this.incomingNamespaceSubscriptions.delete(e),[]}handleIncomingSubscribeTracks(e){const t=this.validateAndReplenish(e.requestId);if(t.error)return t.error;try{ht(e.trackNamespacePrefix)}catch(e){return this.closeWithError(Ve.PROTOCOL_VIOLATION,e instanceof Error?e.message:"Malformed SUBSCRIBE_TRACKS prefix")}const s=this.rejectReservedNamespace(e.trackNamespacePrefix,e.requestId,t.replenish);if(s)return s;for(const s of this.incomingTrackSubscriptions.values())if(mn(s.trackNamespacePrefix,e.trackNamespacePrefix)){const s={type:"REQUEST_ERROR",requestId:e.requestId,errorCode:Ge.PREFIX_OVERLAP,retryInterval:Q(0n),errorReason:"Track Namespace Prefix overlaps an existing SUBSCRIBE_TRACKS"};return[this.sendControl(s),...t.replenish??[]]}return this.incomingTrackSubscriptions.set(e.requestId,{trackNamespacePrefix:e.trackNamespacePrefix,state:"pending"}),t.replenish??[]}acceptSubscribeTracks(e,t=new Map){const s=this.incomingTrackSubscriptions.get(e);if(!s)throw new gn(`Unknown incoming SUBSCRIBE_TRACKS ${e}`,"INVALID_STATE");s.state="active";const i={type:"REQUEST_OK",requestId:e,parameters:t};return[this.sendControl(i)]}rejectSubscribeTracks(e,t,s){if(!this.incomingTrackSubscriptions.get(e))throw new gn(`Unknown incoming SUBSCRIBE_TRACKS ${e}`,"INVALID_STATE");this.incomingTrackSubscriptions.delete(e);const i={type:"REQUEST_ERROR",requestId:e,errorCode:t,retryInterval:Q(0n),errorReason:s};return[this.sendControl(i)]}sendPublishBlocked(e,t,s){const i=this.incomingTrackSubscriptions.get(e);if(!i)throw new gn(`Unknown incoming SUBSCRIBE_TRACKS ${e}`,"INVALID_STATE");if("active"!==i.state)throw new gn(`Cannot sendPublishBlocked for SUBSCRIBE_TRACKS ${e}: not accepted`,"INVALID_STATE");const r={type:"PUBLISH_BLOCKED",trackNamespaceSuffix:t,trackName:s};return[this.sendControl(r)]}getIncomingTrackSubscription(e){return this.incomingTrackSubscriptions.get(e)}handleInboundSubscribeTracksClosed(e){return this.incomingTrackSubscriptions.delete(e),[]}handleInboundRequestClosed(e){const t=this.incomingSubscriptions.get(e);return void 0!==t?.trackAlias&&this.trackAliases.unregister(t.trackAlias,t.requestId),this.incomingSubscriptions.delete(e),this.incomingFetches.delete(e),this.pendingCollisions.delete(e),this.dropPendingUpdatesFor(e),[]}dropPendingUpdatesFor(e){for(const[t,s]of[...this.pendingUpdates])s.existingRequestId===e&&this.pendingUpdates.delete(t)}handleOutboundRequestClosed(e){const t=this.subscriptions.get(e);return t&&(void 0!==t.trackAlias&&this.trackAliases.unregister(t.trackAlias,t.requestId),this.subscriptions.delete(e),this.subscriptionTracks.delete(e)),this.fetches.delete(e),this.pendingTrackStatuses.delete(e),this.outgoingPublishes.delete(e),this.publishedNamespaces.delete(e),this.dropPendingUpdatesFor(e),this.recentlyCancelled.delete(e),[]}handlePublishNamespaceDone(e){if(14===this._draftVersion){const t=e.trackNamespace;if(!t)return this.closeWithError(Ve.PROTOCOL_VIOLATION,"PUBLISH_NAMESPACE_DONE on control stream must include trackNamespace (v14)");const s=this.findNamespaceSubscriptionByPrefix(t);if(!s)return[];s.nsSm.withdrawNamespace(t);return[{type:"notify_namespace",requestId:s.nsSm.requestId,message:e}]}if(void 0===e.requestId)return this.closeWithError(Ve.PROTOCOL_VIOLATION,"PUBLISH_NAMESPACE_DONE on control stream must include requestId (v16)");return[{type:"notify_namespace",requestId:e.requestId,message:e}]}handlePublishNamespaceCancel(e){const t=e.trackNamespace;if(!t)return this.closeWithError(Ve.PROTOCOL_VIOLATION,"PUBLISH_NAMESPACE_CANCEL on control stream must include trackNamespace");const s=this.findNamespaceSubscriptionByPrefix(t);if(!s)return[];s.nsSm.withdrawNamespace(t);return[{type:"notify_namespace",requestId:s.nsSm.requestId,message:e}]}handlePublishNamespaceOk(e){const t=this.publishedNamespaces.get(e.requestId);return t&&"pending"===t.state?(t.state="active",[]):this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for PUBLISH_NAMESPACE_OK`)}handlePublishNamespaceError(e){const t=this.publishedNamespaces.get(e.requestId);return t&&"pending"===t.state?(this.publishedNamespaces.delete(e.requestId),[]):this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown request ID ${e.requestId} for PUBLISH_NAMESPACE_ERROR`)}handleIncomingUnsubscribeNamespace(e){return[]}cancelNamespace(e){const t=this.namespaceSubscriptions.get(e);if(!t)throw new gn(`Unknown namespace subscription ${e}`,"INVALID_STATE");const s={type:"UNSUBSCRIBE_NAMESPACE",trackNamespacePrefix:t.namespacePrefix};return t.handleNamespaceDone(),[this.sendControl(s)]}findNamespaceSubscriptionByPrefix(e){for(const t of this.namespaceSubscriptions.values()){if(!t.isActive)continue;const s=t.namespacePrefix;if(e.length0)throw new gn("Track Properties are not valid on a PUBLISH acceptance (only SUBSCRIBE_OK / TRACK_STATUS_OK / FETCH_OK)","INVALID_STATE");if(i.sendSubscribeOk(t),i.isPublishInitiated){const t=this.cancelStagedCollision(e);if(t.some(e=>"close_connection"===e.type))return t;if(18===this._draftVersion){const s={type:"REQUEST_OK",requestId:e,parameters:new Map};return[...t,this.sendControl(s)]}const s={type:"PUBLISH_OK",requestId:e,parameters:this.buildPublishOkParamsFromPublish(i.publishParameters)};return[...t,this.sendControl(s)]}const n={type:"SUBSCRIBE_OK",requestId:e,trackAlias:t,parameters:s.parameters??new Map,trackProperties:r};return[this.sendControl(n)]}rejectSubscribe(e,t,s){const i=this.incomingSubscriptions.get(e);if(!i)throw new gn(`Unknown incoming subscription ${e}`,"INVALID_STATE");if(i.sendRequestError(t,s),this.pendingCollisions.delete(e),void 0!==i.trackAlias&&this.trackAliases.unregister(i.trackAlias,i.requestId),this.incomingSubscriptions.delete(e),i.isPublishInitiated)return[this.buildPublishReject(e,t,s)];const r={type:"REQUEST_ERROR",requestId:e,errorCode:t,retryInterval:Q(0n),errorReason:s,requestKind:"SUBSCRIBE"};return[this.sendControl(r)]}handleInboundPublishDone(e){const t=this.incomingSubscriptions.get(e);return t?(void 0!==t.trackAlias&&this.trackAliases.unregister(t.trackAlias,t.requestId),this.incomingSubscriptions.delete(e),this.pendingCollisions.delete(e),[]):this.closeWithError(Ve.INVALID_REQUEST_ID,`Unknown PUBLISH ${e} for PUBLISH_DONE`)}updateIncomingSubscription(e,t={}){const s=this.incomingSubscriptions.get(e);if(!s)throw new gn(`Unknown incoming subscription ${e} for REQUEST_UPDATE`,"INVALID_STATE");if("established"!==s.state)throw new gn(`Cannot update incoming subscription in state ${s.state}; expected established`,"INVALID_STATE");const i=this.requestIdAllocator.allocate(),r=new Map;void 0!==t.forward&&r.set(rs.FORWARD,[Q(BigInt(t.forward))]),void 0!==t.subscriberPriority&&r.set(rs.SUBSCRIBER_PRIORITY,[t.subscriberPriority]),void 0!==t.objectDeliveryTimeout&&r.set(rs.OBJECT_DELIVERY_TIMEOUT,[t.objectDeliveryTimeout]),void 0!==t.subgroupDeliveryTimeout&&r.set(rs.SUBGROUP_DELIVERY_TIMEOUT,[t.subgroupDeliveryTimeout]),this.pendingUpdates.set(i,{existingRequestId:e,...void 0!==t.forward?{forward:t.forward?xr:Br}:{},...void 0!==t.objectDeliveryTimeout?{objectDeliveryTimeoutMs:Number(t.objectDeliveryTimeout)}:{},...void 0!==t.subgroupDeliveryTimeout?{subgroupDeliveryTimeoutMs:Number(t.subgroupDeliveryTimeout)}:{}});const n={type:"REQUEST_UPDATE",requestId:i,existingRequestId:e,parameters:r};return{requestId:i,actions:[this.sendControl(n)]}}publishDone(e,t,s){const i=this.incomingSubscriptions.get(e)??this.outgoingPublishes.get(e);if(!i)throw new gn(`Unknown incoming subscription ${e} for PUBLISH_DONE`,"INVALID_STATE");i.sendPublishDone(t,s),this.outgoingPublishes.delete(e),this.incomingSubscriptions.delete(e);const r={type:"PUBLISH_DONE",requestId:e,statusCode:t,streamCount:i.streamCount,errorReason:s};return[this.sendControl(r)]}getIncomingSubscription(e){return this.incomingSubscriptions.get(e)}acceptFetch(e,t={}){const s=this.incomingFetches.get(e);if(!s)throw new gn(`Unknown incoming fetch ${e}`,"INVALID_STATE");const i=this.resolveTrackProperties(t.trackProperties,"FETCH_OK");s.sendFetchOk();const r={type:"FETCH_OK",requestId:e,endOfTrack:t.endOfTrack??0,endLocation:t.endLocation??{group:0n,object:0n},parameters:t.parameters??new Map,trackProperties:i};return s.isPublisherComplete&&this.incomingFetches.delete(e),[this.sendControl(r)]}rejectFetch(e,t,s){const i=this.incomingFetches.get(e);if(!i)throw new gn(`Unknown incoming fetch ${e}`,"INVALID_STATE");i.sendRequestError(t,s),this.incomingFetches.delete(e);const r={type:"REQUEST_ERROR",requestId:e,errorCode:t,retryInterval:Q(0n),errorReason:s,requestKind:"FETCH"};return[this.sendControl(r)]}getIncomingFetch(e){return this.incomingFetches.get(e)}close(e,t){this._state=Pr;return[{type:"close_connection",error:e??Q(0n),reason:t??""}]}handleTransportClosed(){this._state=Pr}closeWithError(e,t){return this._state=Pr,[{type:"close_connection",error:e,reason:t}]}assertState(e,t){if(this._state!==e)throw new gn(`Cannot ${t} in state ${this._state}; expected ${e}`,"INVALID_STATE")}assertEstablishedOrDraining(e){if(this._state!==kr&&this._state!==Or)throw new gn(`Cannot ${e} in state ${this._state}; session must be ESTABLISHED`,"INVALID_STATE")}assertNotReservedNamespace(e,t){if(ct(e))throw new gn(`Cannot ${t} under the reserved .session namespace (§3.2.2)`,"PROTOCOL_VIOLATION");if(dt(e))throw new gn(`Cannot ${t} under the reserved '.' namespace (§3.2.1)`,"PROTOCOL_VIOLATION")}rejectReservedNamespace(e,t,s){if(18!==this._draftVersion)return;const i=dt(e);if(!i&&!ct(e))return;const r={type:"REQUEST_ERROR",requestId:t,errorCode:Ge.DOES_NOT_EXIST,retryInterval:Q(0n),errorReason:i?"Reserved '.' namespace does not exist (§3.2.1)":"Unrecognized .session namespace does not exist (§3.2.2)"};return[this.sendControl(r),...s??[]]}validateCombinedNamespace(e,t){const s=[...e,...t];try{at(s,{allowEmpty:18===this._draftVersion})}catch(i){return this.closeWithError(Ve.PROTOCOL_VIOLATION,`Combined namespace (prefix=${e.length} + suffix=${t.length} = ${s.length} fields) violates §2.4.1: ${i.message}`)}}sendControl(e){return{type:"send_control",message:e}}isParamValidForMessageType(e,t){if(14===this._draftVersion&&e===rs.GROUP_ORDER&&"PUBLISH"===t)return!0;const s=18===this._draftVersion?pn:un;return s.get(e)?.has(t)??!1}validateMessageParams(e,t){const s=18===this._draftVersion,i=s?ln:hn;for(const[r,n]of e){if(!i.has(r)){if(14===this._draftVersion)continue;return{error:Ve.PROTOCOL_VIOLATION,reason:`Unknown message parameter type: ${r}`}}if(this.isParamValidForMessageType(r,t)){if(r!==rs.AUTHORIZATION_TOKEN&&n.length>1)return{error:Ve.PROTOCOL_VIOLATION,reason:`Duplicate message parameter type: ${r}`};if(r===rs.AUTHORIZATION_TOKEN){const e=this.processMessageAuthTokens(n);if(e)return e;continue}for(const e of n){const s=this.validateParamValue(r,e,t);if(s)return s}}else if(s)return{error:Ve.PROTOCOL_VIOLATION,reason:`Parameter 0x${r.toString(16)} is out of scope for ${t} (§10.2.1)`}}}validateParamValue(e,t,s){if("bigint"!=typeof t){if(!(t instanceof Uint8Array))return Array.isArray(t)?e!==rs.TRACK_NAMESPACE_PREFIX?{error:Ve.KEY_VALUE_FORMATTING_ERROR,reason:`Parameter 0x${e.toString(16)} must not be encoded as a Track Namespace tuple`}:void 0:e!==rs.LARGEST_OBJECT?{error:Ve.KEY_VALUE_FORMATTING_ERROR,reason:`Parameter 0x${e.toString(16)} must not be encoded as a Location`}:void 0;switch(e){case rs.LARGEST_OBJECT:return this.validateLargestObject(t);case rs.SUBSCRIPTION_FILTER:{const e=on(t,this._draftVersion);return e?{error:Ve.PROTOCOL_VIOLATION,reason:e}:void 0}}}else switch(e){case rs.DELIVERY_TIMEOUT:if(0n===t&&16===this._draftVersion)return{error:Ve.PROTOCOL_VIOLATION,reason:"DELIVERY_TIMEOUT must be greater than 0"};break;case rs.FORWARD:if(0n!==t&&1n!==t)return{error:Ve.PROTOCOL_VIOLATION,reason:`FORWARD must be 0 or 1, got ${t}`};break;case rs.SUBSCRIBER_PRIORITY:if(t<0n||t>255n)return{error:Ve.PROTOCOL_VIOLATION,reason:`SUBSCRIBER_PRIORITY must be 0-255, got ${t}`};break;case rs.GROUP_ORDER:if(14!==this._draftVersion||"SUBSCRIBE"!==s&&"FETCH"!==s){if(0x1n!==t&&0x2n!==t)return{error:Ve.PROTOCOL_VIOLATION,reason:`GROUP_ORDER must be Ascending (0x1) or Descending (0x2), got ${t}`}}else if(t>0x2n)return{error:Ve.PROTOCOL_VIOLATION,reason:`GROUP_ORDER must be 0x0-0x2, got ${t}`}}}validateLargestObject(e){try{const{bytesRead:t}=Qt(e,0);if(t!==e.length)return{error:Ve.KEY_VALUE_FORMATTING_ERROR,reason:`LARGEST_OBJECT has ${e.length-t} trailing bytes after Location`}}catch{return{error:Ve.KEY_VALUE_FORMATTING_ERROR,reason:"LARGEST_OBJECT is not a valid Location structure"}}}validateControlMessageParams(e){if("parameters"in e&&e.parameters instanceof Map){if("CLIENT_SETUP"===e.type||"SERVER_SETUP"===e.type)return;if(18===this._draftVersion&&"REQUEST_OK"===e.type)return;return this.validateMessageParams(e.parameters,e.type)}}buildPublishOkParamsFromPublish(e){const t=new Map,s=e.get(Q(rs.FORWARD));if(s&&s.length>0&&t.set(Q(rs.FORWARD),[...s]),14===this._draftVersion){const s=e.get(Q(rs.GROUP_ORDER));s&&s.length>0?t.set(Q(rs.GROUP_ORDER),[...s]):t.set(Q(rs.GROUP_ORDER),[Q(1n)])}return t}}class Sn{buffer=new Uint8Array(0);codec;constructor(e){this.codec=e??Ii()}push(e){if(0!==e.length)if(0===this.buffer.length)this.buffer=e;else{const t=new Uint8Array(this.buffer.length+e.length);t.set(this.buffer,0),t.set(e,this.buffer.length),this.buffer=t}}drain(){const e=[];for(;this.buffer.length>0;){const t=this.peekFrameSize();if(void 0===t)break;if(this.buffer.lengththis.onPeerRequestUpdate?.(i,e),n.onGoaway=e=>this.onRequestGoaway?.(e);let a,o=!0;n.closed.catch(e=>{o=!1,this.onStreamError?.(e instanceof Error?e:new Error(String(e)))}).finally(()=>{this.contexts.get(i)===n&&(this.contexts.delete(i),this.onRequestClosed?.(i,o?"fin":"reset"))});try{({response:a}=await n.send(t,s)),Rn.has(t.type)&&await n.finishSending()}catch(e){this.contexts.get(i)===n&&this.contexts.delete(i);try{await n.cancel(Qe.CANCELLED)}catch{}throw e instanceof Error?e:new Error(String(e))}return{requestId:i,response:a}}async sendUpdate(e,t,s){if("function"!=typeof s)throw new Error("UniPairTopology.sendUpdate: an onResponse processor (the wire-order acknowledgement) is required");if("REQUEST_UPDATE"!==t.type)throw new Error(`UniPairTopology.sendUpdate expects REQUEST_UPDATE, got ${t.type}`);const i=this.contexts.get(e);if(!i)throw new Error(`UniPairTopology: no open request stream for request ${e}`);let r;try{({response:r}=await i.send(t,s))}catch(t){throw await this.terminateRequestContext(e),t instanceof Error?t:new Error(String(t))}return{requestId:t.requestId,response:r}}async terminateRequestContext(e){const t=this.contexts.get(e);if(t){this.contexts.delete(e);try{await t.cancel(Qe.CANCELLED)}catch{}this.onRequestClosed?.(e,"reset")}}hasRequestStream(e){return this.contexts.has(e)}async writeOnRequest(e,t){const s=this.contexts.get(e);s&&await s.writeMessage(t)}async cancelRequest(e,t=Qe.CANCELLED){const s=this.contexts.get(e);s&&(this.contexts.delete(e),await s.cancel(t))}async finishRequest(e,t){const s=this.contexts.get(e);s&&(this.contexts.delete(e),await s.finishWith(t))}continuingContexts=new Map;async openContinuingRequest(e,t,s){const i=Cn[t.type];if(!i||"SUBSCRIBE_NAMESPACE"!==t.type&&"SUBSCRIBE_TRACKS"!==t.type)throw new Error(`UniPairTopology.openContinuingRequest expects ${Object.keys(Cn).join("/")}, got ${t.type}`);const r=t.requestId,n=await e.createBidirectionalStream(),a=new An(n,this.codec,i,(e,t)=>s(r,e,t));this.continuingContexts.set(r,a),a.closed.then(()=>{},()=>{}).finally(()=>this.continuingContexts.delete(r));try{await a.send(t)}catch(e){this.continuingContexts.get(r)===a&&this.continuingContexts.delete(r);try{await a.close()}catch{}throw e instanceof Error?e:new Error(String(e))}return{requestId:r,closed:a.closed}}hasContinuingRequest(e){return this.continuingContexts.has(e)}async sendUpdateOnContinuing(e,t,s){if("function"!=typeof s)throw new Error("UniPairTopology.sendUpdateOnContinuing: an onResponse processor (the wire-order acknowledgement) is required");if("REQUEST_UPDATE"!==t.type)throw new Error(`UniPairTopology.sendUpdateOnContinuing expects REQUEST_UPDATE, got ${t.type}`);const i=this.continuingContexts.get(e);if(!i)throw new Error(`UniPairTopology.sendUpdateOnContinuing: no continuing request stream for ${e}`);try{return await i.sendUpdate(t,s)}catch(t){throw await this.closeContinuingRequest(e),t instanceof Error?t:new Error(String(t))}}async closeContinuingRequest(e){const t=this.continuingContexts.get(e);t&&(this.continuingContexts.delete(e),await t.close())}shutdown(){for(const[,e]of this.contexts)e.cancel(Qe.CANCELLED);this.contexts.clear();for(const[,e]of this.continuingContexts)e.close();this.continuingContexts.clear()}}function En(){let e,t;return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}}const Tn={SUBSCRIBE:new Set(["SUBSCRIBE_OK","REQUEST_ERROR"]),FETCH:new Set(["FETCH_OK","REQUEST_ERROR"]),TRACK_STATUS:new Set(["REQUEST_OK","REQUEST_ERROR"]),PUBLISH_NAMESPACE:new Set(["REQUEST_OK","REQUEST_ERROR"]),PUBLISH:new Set(["REQUEST_OK","REQUEST_ERROR"]),REQUEST_UPDATE:new Set(["REQUEST_OK","REQUEST_ERROR"])},wn=new Set(["SUBSCRIBE","FETCH","TRACK_STATUS","PUBLISH_NAMESPACE","PUBLISH"]),Rn=new Set(["TRACK_STATUS"]),Cn={SUBSCRIBE_NAMESPACE:new Set(["NAMESPACE","NAMESPACE_DONE"]),SUBSCRIBE_TRACKS:new Set(["PUBLISH_BLOCKED"])};class In{codec;openerType;requestId;writer;reader;framer;queue=[];started=!1;failure=null;cancelled=!1;firstResponseSeen=!1;subscribeEstablished=!1;terminalSeen=!1;rejectedTerminal=!1;writerFinished=!1;closedDeferred=En();onPeerRequest;onGoaway;get closed(){return this.closedDeferred.promise}constructor(e,t,s,i){this.codec=t,this.openerType=s,this.requestId=i,this.writer=e.writable.getWriter(),this.reader=e.readable.getReader(),this.framer=new Sn(t)}async writeMessage(e){await this.writer.write(this.codec.encode(e))}async send(e,t){if(this.cancelled)throw new _n(Qe.CANCELLED);if(this.failure)throw this.failure;const s=Tn[e.type];if(!s)throw new Error(`UniPairTopology: no response mapping for request type ${e.type}`);const i=En(),r={...i,allowed:s,...t?{process:t}:{}};this.queue.push(r),this.startReading();try{await this.writer.write(this.codec.encode(e))}catch(e){const t=this.queue.indexOf(r);t>=0&&this.queue.splice(t,1);const s=e instanceof Error?e:new Error(String(e));throw i.promise.catch(()=>{}),i.reject(s),s}return{response:i.promise}}async cancel(e){if(this.cancelled)return;this.cancelled=!0;const t=new _n(e);try{await this.reader.cancel(t)}catch{}try{await this.writer.abort(t)}catch{}for(const e of this.queue.splice(0))e.reject(t);this.closedDeferred.resolve()}async finishSending(){try{await this.writer.close()}catch{}}async finishWith(e){if(!this.cancelled){if(this.cancelled=!0,e)try{await this.writer.write(this.codec.encode(e))}catch{}try{await this.writer.close()}catch{}try{await this.reader.cancel()}catch{}for(const e of this.queue.splice(0))e.reject(new _n(Qe.CANCELLED));this.closedDeferred.resolve()}}startReading(){this.started||(this.started=!0,this.readLoop())}async readLoop(){try{for(;;){const{value:e,done:t}=await this.reader.read();e&&this.framer.push(e);for(const{message:e}of this.framer.drain()){if(this.terminalSeen)throw new ze(`${e.type} received after the terminal PUBLISH_DONE (§10.11)`);if("REQUEST_UPDATE"===e.type){if("PUBLISH"!==this.openerType)throw new ze(`peer REQUEST_UPDATE not accepted on a ${this.openerType} request stream`);if(!this.firstResponseSeen)throw new ze("peer REQUEST_UPDATE before the initial PUBLISH response");await(this.onPeerRequest?.(e));continue}if("PUBLISH_DONE"===e.type){if("SUBSCRIBE"!==this.openerType)throw new ze(`PUBLISH_DONE not accepted on a ${this.openerType} request stream`);if(!this.subscribeEstablished)throw new ze("PUBLISH_DONE without a preceding SUBSCRIBE_OK");if(this.queue.length>0)throw new ze("PUBLISH_DONE while update responses are still outstanding");if(this.terminalSeen=!0,await(this.onPeerRequest?.(e)),!this.writerFinished){this.writerFinished=!0;try{await this.writer.close()}catch{}}continue}if("GOAWAY"===e.type){this.cancelled=!0;const t=new vn(this.requestId,e);await(this.onGoaway?.(t));for(const e of this.queue.splice(0))e.reject(t);try{await this.reader.cancel(t)}catch{}try{await this.writer.abort(t)}catch{}return void this.closedDeferred.resolve()}const t=this.queue.shift();if(!t)throw new Error(`UniPairTopology: unsolicited response ${e.type} on request stream`);if(!t.allowed.has(e.type)){const s=new Error(`UniPairTopology: expected ${[...t.allowed].join("/")} on request stream, got ${e.type}`);throw t.reject(s),s}const s=!this.firstResponseSeen;if(this.firstResponseSeen=!0,"SUBSCRIBE_OK"===e.type&&(this.subscribeEstablished=!0),t.process)try{await t.process(e)}catch(e){const s=e instanceof Error?e:new Error(String(e));throw t.reject(s),s}if(t.resolve(e),s&&"REQUEST_ERROR"===e.type&&(this.rejectedTerminal=!0),this.rejectedTerminal&&0===this.queue.length&&!this.writerFinished){this.writerFinished=!0;try{await this.writer.close()}catch{}}}if(t){if(!this.cancelled&&this.queue.length>0)throw new Error("UniPairTopology: request stream ended before all responses");if(!this.cancelled&&!this.writerFinished){this.writerFinished=!0;try{await this.writer.close()}catch{}}return void this.closedDeferred.resolve()}}}catch(e){if(this.cancelled)return void this.closedDeferred.resolve();if(this.failure=e instanceof Error?e:new Error(String(e)),!this.writerFinished){this.writerFinished=!0;try{await this.writer.abort(this.failure)}catch{}}for(const e of this.queue.splice(0))e.reject(this.failure);this.closedDeferred.reject(this.failure)}finally{this.started=!1}}}class An{codec;allowedContinuation;handler;writer;reader;framer;closedDeferred=En();closing=!1;pendingUpdates=[];get closed(){return this.closedDeferred.promise}constructor(e,t,s,i){this.codec=t,this.allowedContinuation=s,this.handler=i,this.writer=e.writable.getWriter(),this.reader=e.readable.getReader(),this.framer=new Sn(t)}async send(e){this.readLoop(),await this.writer.write(this.codec.encode(e))}async sendUpdate(e,t){const s={...En(),...t?{process:t}:{}};this.pendingUpdates.push(s);try{await this.writer.write(this.codec.encode(e))}catch(e){const t=this.pendingUpdates.indexOf(s);throw-1!==t&&this.pendingUpdates.splice(t,1),e}return s.promise}async close(){if(!this.closing){this.closing=!0;try{await this.writer.close()}catch{}try{await this.reader.cancel()}catch{}this.closedDeferred.resolve()}}async readLoop(){let e=!1,t=!1;try{for(;;){const{value:s,done:i}=await this.reader.read();s&&this.framer.push(s);for(const{message:s}of this.framer.drain())if(e){if(t)throw new ze("SUBSCRIBE_NAMESPACE: message received after REQUEST_ERROR");if("REQUEST_OK"===s.type||"REQUEST_ERROR"===s.type){const e=this.pendingUpdates.shift();if(!e)throw new ze(`continuing request: unsolicited ${s.type} (no pending REQUEST_UPDATE)`);if(e.process)try{await e.process(s)}catch(t){const s=t instanceof Error?t:new Error(String(t));throw e.reject(s),s}e.resolve(s);continue}if(!this.allowedContinuation.has(s.type))throw new ze(`continuing request: expected ${[...this.allowedContinuation].join("/")} after REQUEST_OK, got ${s.type}`);await this.handler(s,"continuation")}else{if("REQUEST_OK"!==s.type&&"REQUEST_ERROR"!==s.type)throw new ze(`SUBSCRIBE_NAMESPACE: first response must be REQUEST_OK/REQUEST_ERROR, got ${s.type}`);if(e=!0,t="REQUEST_ERROR"===s.type,await this.handler(s,"first"),t)return void await this.close()}if(i){for(const e of this.pendingUpdates.splice(0))e.reject(new ze("continuing request stream FIN before REQUEST_UPDATE response"));return void this.closedDeferred.resolve()}}}catch(e){const t=e instanceof Error?e:new Error(String(e));for(const e of this.pendingUpdates.splice(0))e.reject(t);if(this.closing)return void this.closedDeferred.resolve();this.closedDeferred.reject(t)}}}function kn(){let e,t;return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}}class On{codec;handlers;requestId=null;openerKind=null;sealed=!1;writer;reader;framer;pendingUpdates=[];aborted=!1;constructor(e,t,s){this.codec=t,this.handlers=s,this.writer=e.writable.getWriter(),this.reader=e.readable.getReader(),this.framer=new Sn(t)}start(){this.readLoop()}bind(e,t){this.requestId=e,this.openerKind=t}seal(){this.sealed=!0}async sendUpdate(e,t){if("function"!=typeof t)throw new Error("InboundRequestStreamContext.sendUpdate: an onResponse processor (the wire-order acknowledgement) is required");const s={...kn(),process:t};this.pendingUpdates.push(s);try{await this.writer.write(this.codec.encode(e))}catch(e){const t=this.pendingUpdates.indexOf(s);throw-1!==t&&this.pendingUpdates.splice(t,1),e}return s.promise}async writeMessage(e){await this.writer.write(this.codec.encode(e))}async finish(){try{await this.writer.close()}catch{}}async terminate(){if(!this.aborted){this.aborted=!0,this.rejectPendingUpdates(new Error("inbound request stream terminated"));try{await this.writer.close()}catch{}try{await this.reader.cancel()}catch{}}}async abort(){if(!this.aborted){this.aborted=!0,this.rejectPendingUpdates(new Error("inbound request stream aborted"));try{await this.reader.cancel()}catch{}try{await this.writer.abort()}catch{}}}rejectPendingUpdates(e){for(const t of this.pendingUpdates.splice(0))t.reject(e)}async readLoop(){try{for(;;){for(const{message:e}of this.framer.drain()){if(this.aborted)return;await this.dispatch(e)}if(this.aborted)return;const{value:e,done:t}=await this.reader.read();if(this.aborted)return;if(e&&this.framer.push(e),t){for(const{message:e}of this.framer.drain())await this.dispatch(e);if(this.pendingUpdates.length>0)throw new ze("inbound request stream ended with pending REQUEST_UPDATE responses");return void this.handlers.onClosed(this)}}}catch(e){if(this.aborted)return;const t=e instanceof Error?e:new Error(String(e));for(const e of this.pendingUpdates.splice(0))e.reject(t);this.handlers.onFailure(t,this)}}async dispatch(e){if(this.sealed)throw new ze("message received after the inbound request stream was sealed");if("REQUEST_OK"===e.type||"REQUEST_ERROR"===e.type){const t=this.pendingUpdates.shift();if(!t)throw new ze("unsolicited REQUEST_OK/REQUEST_ERROR on inbound request stream");if(t.process)try{await t.process(e)}catch(e){const s=e instanceof Error?e:new Error(String(e));throw t.reject(s),s}return void t.resolve(e)}await this.handlers.onMessage(e,this)}}class Pn extends Error{errorSource;protocolCode;streamId;isFatal;constructor(e,t){super(e,t.cause?{cause:t.cause}:void 0),this.name="MoqtConnectionError",this.errorSource=t.errorSource,this.protocolCode=t.protocolCode,this.streamId=t.streamId,this.isFatal=t.isFatal??function(e){switch(e){case"control":case"transport":return!0;case"data":case"datagram":return!1}}(t.errorSource)}}class Nn{session;get draftVersion(){return this.session.draftVersion}codec;dataCodec;uniPair=null;framer;controlWriter=null;transport=null;nextStreamId=0n;namespaceStreams=new Map;dataStreamReaders=new Map;fetchStreams=new Map;recentlyCancelledFetches=new Set;fetchGroupOrder=new Map;rawSubscriptions=new Map;rawAliasMaps=new Map;inboundRequestContexts=new Map;publishAliasMaps=new Map;inboundFetchGroupOrder=new Map;pendingJoinFetches=new Map;joiningFetchTimeoutMs;deferredUpdateResponses=new Map;static MAX_DEFERRED_UPDATE_RESPONSES=4;fetchOutgoingStreams=new Map;onMessage;onClose;onError;reportedStreamErrors=new WeakSet;_terminated=!1;_terminalReport=null;_closeEmitted=!1;_closeReportTimer;closeReportFallbackMs;terminate(e,t,s={}){if(this._terminated)!this._closeEmitted&&s.authoritative&&this._terminalReport&&!this._terminalReport.authoritative&&(this._terminalReport={code:e,reason:t,authoritative:!0},void 0!==this._closeReportTimer&&(clearTimeout(this._closeReportTimer),this._closeReportTimer=void 0),this.emitClose());else if(this._terminated=!0,this.session.state!==Pr&&(s.closeSession?this.executeActions(this.session.close(Ve.PROTOCOL_VIOLATION,t)):this.session.handleTransportClosed()),this.failPendingRawSubscriptions(t),this.clearTerminalState(),this._terminalReport={code:e,reason:t,authoritative:s.authoritative??!1},s.authoritative)this.emitClose();else if(s.preliminary){const e=setTimeout(()=>{this._closeReportTimer=void 0,this.emitClose()},this.closeReportFallbackMs);e.unref?.(),this._closeReportTimer=e}else queueMicrotask(()=>this.emitClose())}emitClose(){!this._closeEmitted&&this._terminalReport&&(this._closeEmitted=!0,void 0!==this._closeReportTimer&&(clearTimeout(this._closeReportTimer),this._closeReportTimer=void 0),this.onClose?.(this._terminalReport.code,this._terminalReport.reason))}clearTerminalState(){for(const e of this.pendingJoinFetches.values())for(const t of e)clearTimeout(t.timer);this.pendingJoinFetches.clear();for(const e of[...this.terminatedAliases.keys()])this.clearTerminatedAlias(e);this.aliasStreamsSeen.clear(),this.aliasDeliveryTimeoutMs.clear(),this.aliasPublisherTimeout.clear(),this.inboundPublishTimeouts.clear(),this.publisherAliasRequests.clear(),this.retiredPublisherAliases.clear(),this.openSubgroupsByRequest.clear(),this.pendingPublishOps.clear(),this.publisherGeneration.clear(),this.incomingSubgroupAliases.clear(),this.deferredUpdateResponses.clear();const e=new Error("session terminated");for(const e of this.inboundRequestContexts.values())this.swallow(()=>e.abort());this.inboundRequestContexts.clear(),this.publishAliasMaps.clear(),this.fetchGroupOrder.clear(),this.inboundFetchGroupOrder.clear(),this.fetchServeReserved.clear(),this.fetchStreams.clear(),this.recentlyCancelledFetches.clear();for(const t of this.dataStreamReaders.values())this.swallow(()=>t.cancel(e));this.dataStreamReaders.clear();for(const t of this.outgoingStreams.values())this.swallow(()=>t.writer.abort(e));this.outgoingStreams.clear();for(const t of this.fetchOutgoingStreams.values())this.swallow(()=>t.writer.abort(e));this.fetchOutgoingStreams.clear();for(const t of this.namespaceStreams.values())this.swallow(()=>t.abort(e));this.namespaceStreams.clear(),this.uniPair?.shutdown()}swallow(e){try{Promise.resolve(e()).catch(()=>{})}catch{}}closeSessionFatal(e,t=3){this.terminate(t,e,{closeSession:!0})}async watchTransportClosed(e){try{const t=await e.closed;if(this.transport!==e)return;const s="number"==typeof t?.closeCode?t.closeCode:0;this.terminate(s,t?.reason??"",{authoritative:!0})}catch(t){if(this.transport!==e)return;const s=t instanceof Error?t.message:String(t);this._terminated||this.onError?.(new Pn(s,{errorSource:"transport",isFatal:!0,...t instanceof Error?{cause:t}:{}})),this.terminate(2,s,{authoritative:!0})}}reportStreamError(e){this.reportedStreamErrors.has(e)||(this.reportedStreamErrors.add(e),this.onError?.(e),e instanceof ze&&this.closeSessionFatal(e.message))}onDataStream;onObject;onStreamClosed;onDatagram;onNamespaceMessage;onPublishBlocked;onSubscribe;onSubscribeClosed;onPublish;onFetch;onTrackStatus;onPublishNamespace;onPublishNamespaceClosed;onSubscribeNamespace;onSubscribeNamespaceClosed;onSubscribeTracks;onSubscribeTracksClosed;onQlogEvent;static CONTROL_STREAM_QLOG_ID=0n;outgoingStreams=new Map;nextOutgoingStreamId=0n;publisherAliasRequests=new Map;retiredPublisherAliases=new Map;static MAX_RETIRED_PUBLISHER_ALIASES=256;openSubgroupsByRequest=new Map;incomingSubgroupAliases=new Map;pendingPublishOps=new Map;publisherGeneration=new Map;aliasStreamsSeen=new Map;terminatedAliases=new Map;terminatedAliasTtlMs;aliasDeliveryTimeoutMs=new Map;aliasPublisherTimeout=new Map;inboundPublishTimeouts=new Map;fetchServeReserved=new Set;static STREAM_COUNT_UNKNOWN=(1n<<62n)-1n;static MAX_TIMER_MS=2147483647;_requestedVersion;_role;constructor(e,t){this._requestedVersion=e,this._role="server"===t?.role?Ur:Nr,this.joiningFetchTimeoutMs=t?.joiningFetchTimeoutMs??1e4,this.terminatedAliasTtlMs=t?.terminatedAliasTtlMs??1e4,this.closeReportFallbackMs=t?.closeReportFallbackMs??2e3,this.configureForVersion(e??16)}configureForVersion(e){if(this.session=new bn(this._role,e,{webtransport:!0}),18===e)this.codec=Ii(18),this.framer=new Sn(this.codec),this.dataCodec=vr(18),this.uniPair=(t=this.session,new yn(t)),this.uniPair.onStreamError=e=>this.reportStreamError(e),this.uniPair.onPeerRequestUpdate=(e,t)=>this.handleOutboundPublishPeerUpdate(e,t),this.uniPair.onRequestClosed=(e,t)=>this.handleOutboundRequestClosed(e,t),this.uniPair.onRequestGoaway=e=>this.handleRequestStreamGoaway(e),this.uniPair.onControlMessage=e=>this.handleControlStreamMessage(e),this.uniPair.onControlStreamViolation=e=>this.handleControlStreamViolation(e);else{const t=function(e=16){if(18===e)throw new Error("createBidiControlTopology: draft-18 uses the uni-pair topology, not single-bidi control");const t=Ii(e);return{version:e,control:t,data:vr(e),framer:new Sn(t)}}(e);this.codec=t.control,this.dataCodec=t.data,this.framer=t.framer,this.uniPair=null}var t}async connect(e,t={}){if(this.transport=e,this.watchTransportClosed(e),void 0===this._requestedVersion&&e.protocol){const t=function(e){if(!e)return;if("moq-00"===e)return 14;const t=e.match(/^moqt-(\d+)$/);if(!t)return;const s=parseInt(t[1],10);return 14===s||16===s||18===s?s:void 0}(e.protocol);void 0!==t&&t!==this.session.draftVersion&&this.configureForVersion(t)}if(18===this.session.draftVersion){const{path:s,...i}=t;return await this.uniPair.establish(e,i),this.runIncomingStreamLoop(e),this.runDatagramLoop(e),void this.runIncomingBidiLoop(e)}const{path:s,...i}=t;let r;if(this._role===Ur){const t=e.incomingBidirectionalStreams;if(!t)throw new ze("server connect: transport has no incomingBidirectionalStreams");const s=t.getReader(),{value:n,done:a}=await s.read();if(s.releaseLock(),a||!n)throw new ze("server connect: no control stream from client");this.controlWriter=n.writable.getWriter(),r=n.readable.getReader();let o=!1;for(;!o;){const{value:e,done:t}=await r.read();if(t)throw new ze("Control stream closed before CLIENT_SETUP");this.framer.push(e);for(const{message:e}of this.framer.drain())await this.executeActions(this.session.handleControlMessage(e)),"CLIENT_SETUP"===e.type&&(o=!0)}await this.executeActions(this.session.completeSetup(i))}else{const t=await e.createBidirectionalStream();for(this.controlWriter=t.writable.getWriter(),r=t.readable.getReader(),await this.executeActions(this.session.initiateSetup(i));this.session.state===Ar;){const{value:e,done:t}=await r.read();if(t)throw new ze("Control stream closed before setup complete");this.framer.push(e);for(const{message:e}of this.framer.drain())await this.executeActions(this.session.handleControlMessage(e))}}if(this.session.state!==kr)throw new Error(`Setup failed: session in state "${this.session.state}" (expected "established")`);this.runControlReadLoop(r),this.runIncomingStreamLoop(e),this.runDatagramLoop(e)}async subscribe(e,t,s){const{requestId:i,actions:r}=this.session.subscribe(e,t,s);return await this.sendSubscribeActions(r),i}async sendSubscribeActions(e){if(18===this.session.draftVersion){const t=e.find(e=>"send_control"===e.type).message,s=t.requestId;return void await this.openD18Request(s,t)}await this.executeActions(e)}async openD18Request(e,t,s){try{const s=await this.uniPair.openRequest(this.transport,t,t=>this.deliverRequestResponse(t,e));this.routeRequestResponse(s)}catch(t){throw s?.(),await this.executeActions(this.session.handleOutboundRequestClosed(e)),t instanceof Error?t:new Error(String(t))}}async publish(e,t,s,i){const{requestId:r,actions:n}=this.session.publish(e,t,s,i);if(this.publisherAliasRequests.set(s,r),18===this.session.draftVersion){const e=n.find(e=>"send_control"===e.type).message;return await this.openD18Request(r,e,()=>this.publisherAliasRequests.delete(s)),r}return await this.executeActions(n),r}routeRequestResponse(e){this.consumeRequestStream(e)}async consumeRequestStream(e){try{await e.response}catch(t){if(t instanceof _n)return;if(t instanceof vn)return;const s=t instanceof Error?t:new Error(String(t)),i=this.rawSubscriptions.get(e.requestId);i?.reject&&(i.reject(s),i.resolve=null,i.reject=null,this.rawSubscriptions.delete(e.requestId)),this.reportStreamError(s)}}handleRequestStreamGoaway(e){const t=this.rawSubscriptions.get(e.requestId);t?.reject&&(t.reject(new Pn(`Request ${e.requestId} received GOAWAY on its request stream; re-issue is application policy (automatic reissue not implemented)`,{errorSource:"control"})),t.resolve=null,t.reject=null,this.rawSubscriptions.delete(e.requestId)),this.onMessage?.(e.goaway)}trackPropsOf(e){const t=e;return t.trackProperties??t.trackExtensions??new Map}trackPropMs(e,t){const s=e.get(t)?.[0];return"bigint"==typeof s?Number(s):void 0}static minNonzeroMs(e,t){return e>0&&t>0?Math.min(e,t):Math.max(e,t)}combineDeliveryTimeoutMs(e,t,s,i){return Math.max(Nn.minNonzeroMs(e,s),Nn.minNonzeroMs(t,i))}paramTimeoutMs(e,t){const s=e?.get(t)?.[0];return"bigint"==typeof s?Number(s):0}effectiveDeliveryTimeoutMs(e,t){const s=this.trackPropsOf(t);return this.combineDeliveryTimeoutMs(this.trackPropMs(s,0x02n)??0,this.trackPropMs(s,0x06n)??0,e??0,0)}refreshAliasDeliveryTimeout(e){const t=this.rawAliasMaps.get(e)?.requestId??[...this.publishAliasMaps].find(([t])=>t===e)?.[1]?.requestId;if(null==t)return;const s=this.session.getSubscription(t)??this.session.getIncomingSubscription(t);if(!s)return;const i=this.aliasPublisherTimeout.get(e)??{obj:0,sub:0},r=this.combineDeliveryTimeoutMs(i.obj,i.sub,s.requestedDeliveryTimeoutMs??0,s.requestedSubgroupDeliveryTimeoutMs??0);r>0?this.aliasDeliveryTimeoutMs.set(e,r):this.aliasDeliveryTimeoutMs.delete(e)}trackPropertyFault(e){const t=this.trackPropsOf(e);return function(e){for(const t of e.keys())if(t>=16384n&&t<=32767n)return!0;return!1}(t)?{code:Ke.UNSUPPORTED_EXTENSION,reason:"an unsupported Mandatory Track Property (§2.5.1)"}:function(e){for(const t of e.keys())if(Lt.has(t))return!0;return!1}(t)?{code:Ke.MALFORMED_TRACK,reason:"a data-Object-only Property in Track Properties (§2.5)"}:null}async deliverRequestResponse(e,t){const s={...e,requestId:t};if(this.onQlogEvent?.({type:"control_message_parsed",stream_id:Nn.CONTROL_STREAM_QLOG_ID,message:s}),"SUBSCRIBE_OK"===e.type||"FETCH_OK"===e.type){const s=this.trackPropertyFault(e);if(s)return void await this.failRejectedTrack(e.type,t,s.reason)}if("SUBSCRIBE_OK"===e.type)return void await this.handleSubscribeOkOrdered(e,t);this.handleRawSubControlMessage(s)||this.session.isCancelledRequest(t)||this.onMessage?.(s),await this.executeActions(this.session.handleControlMessage(e,{requestId:t})),"FETCH_OK"===e.type&&await this.closeCompletedFetchRequest(t)}async closeCompletedFetchRequest(e){void 0===this.session.getFetch(e)&&this.uniPair?.hasRequestStream(e)&&await this.uniPair.finishRequest(e)}async handleSubscribeOkOrdered(e,t){const s=this.session.handleControlMessage(e,{requestId:t}),i=s.find(e=>"close_connection"===e.type);if(i)return await this.executeActions(s),void this.notifyClose(i,"SUBSCRIBE_OK rejected");if(void 0===this.session.getSubscription(t))return void await this.executeActions(s);const r=BigInt(e.trackAlias);if(!this.aliasReuseSafe(r))return void await this.refuseAliasReuse(t,`track alias ${r} is still guarded by a terminating prior subscription (§11.1) — reuse refused`);const n={...e,requestId:t};this.clearTerminatedAlias(r);this.handleRawSubControlMessage(n)||this.onMessage?.(n),await this.executeActions(s)}async refuseAliasReuse(e,t){const s=new Pn(t,{errorSource:"control",isFatal:!1}),i=this.rawSubscriptions.get(e);i&&(this.rawSubscriptions.delete(e),i.reject?.(s),i.resolve=null,i.reject=null),await this.executeActions(this.session.unsubscribe(e)),18===this.session.draftVersion&&await this.uniPair.cancelRequest(e),this.onError?.(s)}aliasReuseSafe(e){const t=this.terminatedAliases.get(e);return!t||t.strict&&0n===t.remaining}async failRejectedTrack(e,t,s){const i=new Pn(`Track rejected: ${e} carried ${s} — request reset`,{errorSource:"control",isFatal:!1}),r=this.rawSubscriptions.get(t);r?.reject&&(r.reject(i),r.resolve=null,r.reject=null,this.rawSubscriptions.delete(t)),await this.executeActions(this.session.handleMalformedTrack(t)),await this.uniPair.cancelRequest(t),this.onError?.(i)}failPendingRawSubscriptions(e){for(const t of this.rawSubscriptions.values())t.reject&&(t.reject(new Pn(e,{errorSource:"control",isFatal:!0})),t.resolve=null,t.reject=null);this.rawSubscriptions.clear(),this.rawAliasMaps.clear()}async handleOutboundPublishPeerUpdate(e,t){if("PUBLISH_DONE"===t.type){const s=this.session.getSubscription(e)?.trackAlias,i=t.streamCount??0n,r={...t,requestId:e};this.onMessage?.(r);const n=void 0!==s?this.applyTerminalStreamCount(s,BigInt(i),e):Promise.resolve();return await this.executeActions(this.session.handleControlMessage(r)),void await n}const s=t.requestId,i={...t,existingRequestId:e};this.onMessage?.(i);const r=this.session.handleControlMessage(i,{requestId:s,existingRequestId:e}),n=r.find(e=>"close_connection"===e.type);if(n)return await this.executeActions(r),void this.notifyClose(n,"REQUEST_UPDATE on PUBLISH rejected");const a=r.find(e=>"send_control"===e.type);a&&await this.uniPair.writeOnRequest(e,a.message),await this.executeActions(r.filter(e=>"send_control"!==e.type))}async handleOutboundRequestClosed(e,t){const s=this.session.getFetch(e);if(void 0!==s&&!s.isFetcherComplete&&"fin"===t&&s.responseReceived)return;const i=this.rawSubscriptions.get(e),r=i&&null!==i.trackAlias&&this.rawAliasMaps.get(i.trackAlias)===i?i.trackAlias:null;null!==r&&this.armSubscriberAliasTeardown(r),await this.executeActions(this.session.handleOutboundRequestClosed(e)),i&&(null!==r&&await this.discardOpenStreamsForAlias(r),this.rawSubscriptions.delete(e),i.reject?.(new Pn(`Request ${e} stream closed before completion`,{errorSource:"control"}))),await this.abortPublisherStreamsForRequest(e),this.fetchGroupOrder.delete(e)}async handleControlStreamMessage(e){this.onMessage?.(e);const t=this.session.handleControlMessage(e),s=t.find(e=>"close_connection"===e.type);await this.executeActions(t),s&&this.notifyClose(s,"control-stream GOAWAY violation")}handleControlStreamViolation(e){this.session.state!==Pr&&this.closeSessionFatal(e)}async subscribeTrack(e,t,s){const i={};s?.filter&&(i.subscriptionFilter=s.filter),void 0!==s?.deliveryTimeout&&(i.deliveryTimeout=s.deliveryTimeout);const{requestId:r,actions:n}=this.session.subscribe(e,t,i),a=BigInt(r),o={requestId:a,trackAlias:0n,onObject:s?.onObject??null,unsubscribe:async()=>{await this.unsubscribe(a)}},c=new Promise((e,t)=>{this.rawSubscriptions.set(a,{requestId:a,trackAlias:null,sub:o,resolve:e,reject:t})});try{await this.sendSubscribeActions(n)}catch(e){await this.executeActions(this.session.handleOutboundRequestClosed(a));const t=this.rawSubscriptions.get(a);t&&(this.rawSubscriptions.delete(a),t.reject?.(e instanceof Error?e:new Error(String(e))))}return c}routeToTrackSubscription(e){const t=BigInt(e.trackAlias),s=this.rawAliasMaps.get(t);if(s)return s.sub.onObject?.(e),!0;const i=this.publishAliasMaps.get(t);return!!i&&(i.onObject?.(e),!0)}async stopIncomingSubgroupStream(e){this.incomingSubgroupAliases.delete(e);const t=this.dataStreamReaders.get(e);if(t){try{await t.cancel(new Error("subscription terminated by PUBLISH_DONE — early discard"))}catch{}this.dataStreamReaders.delete(e)}}armSubscriberAliasTeardown(e){this.refreshAliasDeliveryTimeout(e),this.armTerminatedAlias(e,null,!1),this.rawAliasMaps.delete(e)}async discardOpenStreamsForAlias(e){for(const[t,s]of[...this.incomingSubgroupAliases])s===e&&await this.stopIncomingSubgroupStream(t)}clearTerminatedAlias(e){const t=this.terminatedAliases.get(e);t&&(t.cancelTimer(),this.terminatedAliases.delete(e)),this.aliasStreamsSeen.delete(e),this.aliasDeliveryTimeoutMs.delete(e),this.aliasPublisherTimeout.delete(e)}armGuardTimer(e,t){let s,i=Math.max(0,Math.min(e,Number.MAX_SAFE_INTEGER));const r=()=>{if(i<=0)return void t();const e=Math.min(i,Nn.MAX_TIMER_MS);i-=e,s=setTimeout(r,e),s.unref?.()};return r(),()=>clearTimeout(s)}armTerminatedAlias(e,t,s){this.publishAliasMaps.delete(e),this.rawAliasMaps.delete(e);const i=this.terminatedAliases.get(e);if(i?.strict&&!s)return;i&&i.cancelTimer();const r=Math.max(this.terminatedAliasTtlMs,this.aliasDeliveryTimeoutMs.get(e)??0),n=this.armGuardTimer(r,()=>this.clearTerminatedAlias(e));this.terminatedAliases.set(e,{remaining:t,cancelTimer:n,strict:s})}async applyTerminalStreamCount(e,t,s){const i=this.rawAliasMaps.get(e)?.requestId??this.publishAliasMaps.get(e)?.requestId;if(void 0!==i&&i!==s)return;this.refreshAliasDeliveryTimeout(e);const r=this.aliasStreamsSeen.get(e)??0n,n=t===Nn.STREAM_COUNT_UNKNOWN?null:t-r>0n?t-r:0n;this.armTerminatedAlias(e,n,!0);for(const[t,s]of[...this.incomingSubgroupAliases])s===e&&await this.stopIncomingSubgroupStream(t)}handleRawSubControlMessage(e){if("SUBSCRIBE_OK"===e.type&&"requestId"in e&&"trackAlias"in e){const t=BigInt(e.requestId),s=this.rawSubscriptions.get(t);if(s){const i=BigInt(e.trackAlias);s.trackAlias=i,s.sub.trackAlias=i,this.rawAliasMaps.set(i,s);const r=this.trackPropsOf(e);this.aliasPublisherTimeout.set(i,{obj:this.trackPropMs(r,0x02n)??0,sub:this.trackPropMs(r,0x06n)??0});const n=this.effectiveDeliveryTimeoutMs(this.session.getSubscription(t)?.requestedDeliveryTimeoutMs,e);return n>0&&this.aliasDeliveryTimeoutMs.set(i,n),s.resolve?.(s.sub),s.resolve=null,s.reject=null,!0}}if("REQUEST_ERROR"===e.type&&"requestId"in e){const t=BigInt(e.requestId),s=this.rawSubscriptions.get(t);if(s){const i=e;return s.reject?.(new Error(`Subscribe failed: ${i.errorReason} (${i.errorCode})`)),s.resolve=null,s.reject=null,this.rawSubscriptions.delete(t),!0}}return!1}async requestUpdate(e,t){if(18===this.session.draftVersion){const s=this.inboundRequestContexts.get(e);if(s&&"publish"===s.openerKind){const{requestId:i,actions:r}=this.session.updateIncomingSubscription(e,t),n=r.find(e=>"send_control"===e.type).message;try{await s.sendUpdate(n,e=>this.deliverRequestResponse(e,i))}catch(t){this.session.rollbackRequestUpdate(i);const r=[...this.publishAliasMaps].find(([,t])=>t.requestId===e)?.[0];if(void 0!==r)await this.rollbackFailedAcceptance(e,r,!0);else{await this.executeActions(this.session.handleInboundRequestClosed(e)),this.inboundRequestContexts.delete(e);try{await s.abort()}catch{}}throw t instanceof Error?t:new Error(String(t))}return i}if(this.uniPair.hasContinuingRequest(e)){const{requestId:s,actions:i}=this.session.requestUpdate(e,t),r=i.find(e=>"send_control"===e.type).message;try{await this.uniPair.sendUpdateOnContinuing(e,r,e=>this.deliverRequestResponse(e,s))}catch(e){throw this.session.rollbackRequestUpdate(s),e instanceof Error?e:new Error(String(e))}return s}if(!this.uniPair.hasRequestStream(e))throw new Error(`requestUpdate: no open draft-18 request stream for request ${e}`);const{requestId:i,actions:r}=this.session.requestUpdate(e,t),n=r.find(e=>"send_control"===e.type).message;let a;try{a=await this.uniPair.sendUpdate(e,n,e=>this.deliverRequestResponse(e,i))}catch(e){throw this.session.rollbackRequestUpdate(i),e instanceof Error?e:new Error(String(e))}return this.routeRequestResponse(a),i}const{requestId:s,actions:i}=this.session.requestUpdate(e,t);return await this.executeActions(i),s}async unsubscribe(e){const t=this.rawSubscriptions.get(e);t&&null!==t.trackAlias&&this.rawAliasMaps.get(t.trackAlias)===t&&this.armSubscriberAliasTeardown(t.trackAlias);const s=this.session.unsubscribe(e);if(await this.executeActions(s),18===this.session.draftVersion){await this.uniPair.cancelRequest(e);const s=this.rawSubscriptions.get(e)??t;s&&null!==s.trackAlias&&await this.discardOpenStreamsForAlias(s.trackAlias)}this.rawSubscriptions.delete(e)}async close(e,t){this._terminated=!0,this._closeEmitted=!0;const s=this.session.close(e,t);await this.executeActions(s),this.failPendingRawSubscriptions(t??"Session closed"),this.clearTerminalState()}async sendGoaway(e={}){const t=e.newSessionUri??"";if(18===this.session.draftVersion){if(void 0===e.requestId)throw new Pn("sendGoaway (draft-18): a control-stream GOAWAY requires a Request ID",{errorSource:"control"});if(this._role===Nr&&t.length>0)throw new Pn("sendGoaway (draft-18): a client MUST send a zero-length New Session URI",{errorSource:"control"});const s=this._role===Ur?0n:1n;if((1n&e.requestId)!==s)throw new Pn(`sendGoaway (draft-18): Request ID ${e.requestId} has the wrong parity for the peer (expected ${0n===s?"even":"odd"})`,{errorSource:"control"});const i={type:"GOAWAY",newSessionUri:t,timeout:e.timeout??0n,requestId:e.requestId};return void await this.uniPair.sendControl(i)}const s={type:"GOAWAY",newSessionUri:t,...void 0!==e.requestId?{requestId:e.requestId}:{}};await this.executeActions([{type:"send_control",message:s}])}async subscribeNamespace(e,t){const{requestId:s,actions:i}=this.session.subscribeNamespace(e,t);if(18===this.session.draftVersion){const e=i.find(e=>"open_namespace_stream"===e.type);let t;try{({closed:t}=await this.uniPair.openContinuingRequest(this.transport,e.message,(e,t,s)=>"first"===s?this.deliverRequestResponse(t,e):(this.onNamespaceMessage?.(e,t),this.executeActions(this.session.handleNamespaceStreamMessage(e,t)))))}catch(e){throw await this.executeActions(this.session.handleNamespaceStreamClosed(s)),e instanceof Error?e:new Error(String(e))}return this.handleNamespaceStreamClosed(s,t),s}return await this.executeActions(i),s}async handleNamespaceStreamClosed(e,t){try{await t,await this.executeActions(this.session.handleNamespaceStreamClosed(e))}catch(e){if(e instanceof ze)return void this.closeSessionFatal(e.message);this.onError?.(new Pn(e instanceof Error?e.message:String(e),{errorSource:"control",...e instanceof Error?{cause:e}:{}}))}}async subscribeTracks(e){const{requestId:t,actions:s}=this.session.subscribeTracks(e),i=s.find(e=>"send_control"===e.type).message;let r;try{({closed:r}=await this.uniPair.openContinuingRequest(this.transport,i,(e,t,s)=>"first"===s?this.deliverRequestResponse(t,e):(this.onPublishBlocked?.(e,t),this.executeActions(this.session.handleSubscribeTracksStreamMessage(e,t)))))}catch(e){throw await this.executeActions(this.session.handleSubscribeTracksStreamClosed(t)),e instanceof Error?e:new Error(String(e))}return this.handleSubscribeTracksStreamClosed(t,r),t}async handleSubscribeTracksStreamClosed(e,t){try{await t,await this.executeActions(this.session.handleSubscribeTracksStreamClosed(e))}catch(e){if(e instanceof ze)return void this.closeSessionFatal(e.message);this.onError?.(new Pn(e instanceof Error?e.message:String(e),{errorSource:"control",...e instanceof Error?{cause:e}:{}}))}}async cancelNamespace(e){if(14===this.codec.version){const t=this.session.cancelNamespace(e);return void await this.executeActions(t)}if(18===this.session.draftVersion)return void await this.uniPair.closeContinuingRequest(e);const t=this.namespaceStreams.get(e);if(t){try{await t.close()}catch{}this.namespaceStreams.delete(e)}}async cancelTracks(e){18===this.session.draftVersion&&await this.uniPair.closeContinuingRequest(e)}async fetch(e,t,s){const{requestId:i,actions:r}=this.session.fetch(e,t,s);if(18===this.session.draftVersion){this.fetchGroupOrder.set(i,s.groupOrder??"ascending");const e=r.find(e=>"send_control"===e.type).message;return await this.openD18Request(i,e,()=>this.fetchGroupOrder.delete(i)),i}return await this.executeActions(r),i}async joiningFetch(e){const{requestId:t,actions:s}=this.session.joiningFetch(e);if(18===this.session.draftVersion){this.fetchGroupOrder.set(t,e.groupOrder??"ascending");const i=s.find(e=>"send_control"===e.type).message;return await this.openD18Request(t,i,()=>this.fetchGroupOrder.delete(t)),t}return await this.executeActions(s),t}resolveJoiningFetch(e,t){return this.session.resolveIncomingJoiningFetch(e,t)}async fetchCancel(e){if(void 0===this.session.getFetch(e))return;this.recentlyCancelledFetches.add(e);const t=this.session.fetchCancel(e);await this.executeActions(t),18===this.session.draftVersion&&await this.uniPair.cancelRequest(e);const s=this.fetchStreams.get(e);if(void 0!==s){const t=this.dataStreamReaders.get(s);if(t){try{await t.cancel(new Error("FETCH cancelled"))}catch{}this.dataStreamReaders.delete(s)}this.fetchStreams.delete(e),this.recentlyCancelledFetches.delete(e)}this.fetchGroupOrder.delete(e)}async trackStatus(e,t){const{requestId:s,actions:i}=this.session.trackStatus(e,t);if(18===this.session.draftVersion){const e=i.find(e=>"send_control"===e.type).message;return await this.openD18Request(s,e),s}return await this.executeActions(i),s}async stopSending(e,t){await this.executeActions([{type:"stop_sending",streamId:e,error:t}])}async publishNamespace(e){const{requestId:t,actions:s}=this.session.publishNamespace(e);if(18===this.session.draftVersion){const e=s.find(e=>"send_control"===e.type).message;return await this.openD18Request(t,e),t}return await this.executeActions(s),t}async publishNamespaceDone(e){const t=this.session.publishNamespaceDone(e);if(18===this.session.draftVersion)return await this.executeActions(t),void await this.uniPair.cancelRequest(e);await this.executeActions(t)}async acceptSubscribe(e,t,s){const i=this.session.getIncomingSubscription(e),r=i?.isPublishInitiated??!1;if(r&&void 0!==i?.trackAlias&&t!==i.trackAlias)throw new Pn(`acceptSubscribe alias ${t} does not match the PUBLISH's advertised alias ${i.trackAlias}`,{errorSource:"control"});const n=this.session.acceptSubscribe(e,t,s),a=n.find(e=>"close_connection"===e.type);if(a)throw await this.executeActions(n),this.notifyClose(a,"acceptSubscribe forced a session close"),await this.settleParkedJoins(e,!1),new Pn(`acceptSubscribe closed the session: ${a.reason}`,{errorSource:"control",isFatal:!0});let o;if(r||this.publisherAliasRequests.set(t,e),r){const i=this.inboundPublishTimeouts.get(e);if(this.inboundPublishTimeouts.delete(e),i){const e=this.paramTimeoutMs(s?.parameters,0x02n),r=this.paramTimeoutMs(s?.parameters,0x06n),n=this.combineDeliveryTimeoutMs(i.obj,i.sub,e,r);o=()=>{n>0?this.aliasDeliveryTimeoutMs.set(t,n):this.aliasDeliveryTimeoutMs.delete(t)}}}const c=n.filter(e=>"send_control"!==e.type);let d;c.length>0&&await this.executeActions(c);try{d=await this.writeInboundRequestResponse(e,n)}catch(s){throw await this.rollbackFailedAcceptance(e,t,r),s instanceof Error?s:new Error(String(s))}if(d)return o?.(),await this.flushDeferredUpdateResponses(e),void await this.settleParkedJoins(e,!0);await this.executeActions(n.filter(e=>"send_control"===e.type)),o?.(),await this.flushDeferredUpdateResponses(e),await this.settleParkedJoins(e,!0)}async rollbackFailedAcceptance(e,t,s){this.publisherAliasRequests.delete(t);const i=s&&this.publishAliasMaps.get(t)?.requestId===e;i&&this.armTerminatedAlias(t,null,!1),this.inboundPublishTimeouts.delete(e),await this.executeActions(this.session.handleInboundRequestClosed(e));const r=this.inboundRequestContexts.get(e);if(this.inboundRequestContexts.delete(e),i&&await this.discardOpenStreamsForAlias(t),r)try{await r.abort()}catch{}}async flushDeferredUpdateResponses(e){const t=this.deferredUpdateResponses.get(e);if(!t)return;this.deferredUpdateResponses.delete(e);const s=this.inboundRequestContexts.get(e);if(s)for(const e of t)try{await s.writeMessage(e)}catch{break}}async writeInboundRequestResponse(e,t,s=!1){if(18!==this.session.draftVersion)return!1;const i=this.inboundRequestContexts.get(e);if(!i)return!1;const r=t.find(e=>"send_control"===e.type);return!!r&&(await i.writeMessage(r.message),s&&(i.seal(),await i.terminate(),this.inboundRequestContexts.delete(e)),!0)}async rejectSubscribe(e,t,s){const i=this.inboundRequestContexts.get(e),r=this.session.getIncomingSubscription(e),n=r?.isPublishInitiated?r.trackAlias:void 0,a=void 0!==n&&this.publishAliasMaps.get(n)?.requestId===e;a&&this.armTerminatedAlias(n,null,!1);const o=this.session.rejectSubscribe(e,t,s);if(await this.writeInboundRequestResponse(e,o)){if(await this.flushDeferredUpdateResponses(e),a&&await this.discardOpenStreamsForAlias(n),i){i.seal();try{await i.terminate()}catch{}this.inboundRequestContexts.delete(e)}await this.settleParkedJoins(e,!1)}else await this.executeActions(o),a&&await this.discardOpenStreamsForAlias(n),await this.flushDeferredUpdateResponses(e),await this.settleParkedJoins(e,!1)}async acceptFetch(e,t){const s=this.session.acceptFetch(e,t);try{if(await this.writeInboundRequestResponse(e,s))return}catch(t){throw await this.rollbackFailedFetchAcceptance(e),t instanceof Error?t:new Error(String(t))}await this.executeActions(s)}async rollbackFailedFetchAcceptance(e){this.inboundFetchGroupOrder.delete(e),this.fetchServeReserved.delete(e),await this.abortFetchStreamsForRequest(e,"fetch acceptance failed"),await this.executeActions(this.session.handleInboundRequestClosed(e));const t=this.inboundRequestContexts.get(e);if(this.inboundRequestContexts.delete(e),t)try{await t.abort()}catch{}}detachFetchStreamsForRequest(e){const t=[];for(const[s,i]of[...this.fetchOutgoingStreams])i.requestId===e&&(this.fetchOutgoingStreams.delete(s),t.push(i.writer));return t}async abortFetchStreamsForRequest(e,t){for(const s of this.detachFetchStreamsForRequest(e))try{await s.abort(t)}catch{}}async rejectFetch(e,t,s){const i=this.session.rejectFetch(e,t,s);this.inboundFetchGroupOrder.delete(e),this.fetchServeReserved.delete(e),await this.abortFetchStreamsForRequest(e,"fetch rejected"),await this.writeInboundRequestResponse(e,i,!0)||await this.executeActions(i)}async acceptTrackStatus(e,t=new Map){const s=this.session.acceptTrackStatus(e,t);await this.writeInboundRequestResponse(e,s,!0)||await this.executeActions(s)}async rejectTrackStatus(e,t,s){const i=this.session.rejectTrackStatus(e,t,s);await this.writeInboundRequestResponse(e,i,!0)||await this.executeActions(i)}async acceptSubscribeNamespace(e,t=new Map){const s=this.session.acceptSubscribeNamespace(e,t);await this.writeInboundRequestResponse(e,s)||await this.executeActions(s)}async rejectSubscribeNamespace(e,t,s){const i=this.session.rejectSubscribeNamespace(e,t,s);await this.writeInboundRequestResponse(e,i,!0)||await this.executeActions(i)}async sendNamespace(e,t){const s=this.session.sendNamespace(e,t);await this.writeInboundRequestResponse(e,s)||await this.executeActions(s)}async sendNamespaceDone(e,t){const s=this.session.sendNamespaceDone(e,t);await this.writeInboundRequestResponse(e,s)||await this.executeActions(s)}async acceptSubscribeTracks(e,t=new Map){const s=this.session.acceptSubscribeTracks(e,t);await this.writeInboundRequestResponse(e,s)||await this.executeActions(s)}async rejectSubscribeTracks(e,t,s){const i=this.session.rejectSubscribeTracks(e,t,s);await this.writeInboundRequestResponse(e,i,!0)||await this.executeActions(i)}async sendPublishBlocked(e,t,s){const i=this.session.sendPublishBlocked(e,t,s);await this.writeInboundRequestResponse(e,i)||await this.executeActions(i)}async publishDone(e,t,s){const i=this.openSubgroupsByRequest.get(e),r=this.pendingPublishOps.get(e)??0;if(i&&i.size>0||r>0)throw new Pn(`publishDone: ${i?.size??0} open + ${r} in-flight data operation(s) for request ${e} — finish them before PUBLISH_DONE (§10.11)`,{errorSource:"control"});const n=this.session.publishDone(e,t,s);if(this.openSubgroupsByRequest.delete(e),this.retirePublisherRequest(e),18===this.session.draftVersion){const t=this.inboundRequestContexts.get(e);if(t){const s=n.find(e=>"send_control"===e.type);return s&&await t.writeMessage(s.message),t.seal(),await t.terminate(),void this.inboundRequestContexts.delete(e)}if(this.uniPair.hasRequestStream(e)){const t=n.find(e=>"send_control"===e.type);return void await this.uniPair.finishRequest(e,t?.message)}}await this.executeActions(n)}publisherSubscriptionForAlias(e){const t=this.publisherAliasRequests.get(e);if(void 0===t){const t=this.retiredPublisherAliases.get(e);return void 0!==t?{requestId:t,sub:void 0}:void 0}const s=this.session.getIncomingSubscription(t)??this.session.getOutgoingPublish(t);return s&&s.state===Dr?{requestId:t,sub:void 0}:{requestId:t,sub:s}}retirePublisherRequest(e){for(const[t,s]of this.publisherAliasRequests)if(s===e){if(this.publisherAliasRequests.delete(t),this.retiredPublisherAliases.size>=Nn.MAX_RETIRED_PUBLISHER_ALIASES){const e=this.retiredPublisherAliases.keys().next().value;void 0!==e&&this.retiredPublisherAliases.delete(e)}this.retiredPublisherAliases.set(t,e);break}}boundPublisherGeneration(){if(!(this.publisherGeneration.size<=Nn.MAX_RETIRED_PUBLISHER_ALIASES))for(const e of this.publisherGeneration.keys())if(!this.pendingPublishOps.has(e)){this.publisherGeneration.delete(e);break}}beginPublishOp(e,t){const s=this.publisherSubscriptionForAlias(e);if(!s)throw new Pn(`${t}: unknown track alias ${e} — not from acceptSubscribe()/publish()`,{errorSource:"data"});if(!s.sub)throw new Pn(`${t}: the subscription for track alias ${e} is terminated — no further objects (§10.11)`,{errorSource:"data"});this.pendingPublishOps.set(s.requestId,(this.pendingPublishOps.get(s.requestId)??0)+1);const i=this.publisherGeneration.get(s.requestId)??0;return{requestId:s.requestId,sub:s.sub,generation:i}}publisherOpCurrent(e,t){return(this.publisherGeneration.get(e)??0)===t}endPublishOp(e){if(void 0===e)return;const t=(this.pendingPublishOps.get(e)??0)-1;t>0?this.pendingPublishOps.set(e,t):(this.pendingPublishOps.delete(e),this.boundPublisherGeneration())}async abortPublisherStreamsForRequest(e){this.publisherGeneration.set(e,(this.publisherGeneration.get(e)??0)+1);const t=this.openSubgroupsByRequest.get(e);if(t){for(const e of[...t]){const t=this.outgoingStreams.get(e);if(t){try{await t.writer.abort(new Error("subscription cancelled — RESET_STREAM (§5.1.1)"))}catch{}this.outgoingStreams.delete(e)}}this.openSubgroupsByRequest.delete(e)}this.retirePublisherRequest(e),this.boundPublisherGeneration()}async openSubgroup(e,t,s,i){if(i?.firstObject&&18!==this.session.draftVersion)throw new Pn("openSubgroup: firstObject is a draft-18-only option",{errorSource:"data"});if(!this.transport?.createUnidirectionalStream)throw new Pn("Transport does not support createUnidirectionalStream",{errorSource:"transport"});const r=this.beginPublishOp(e,"openSubgroup");try{let n;try{n=await this.transport.createUnidirectionalStream()}catch(e){throw new Pn(`Failed to open unidirectional stream for group ${t}: ${e.message??e}. The relay may not be granting enough stream credits (MAX_STREAMS / WT_MAX_STREAMS).`,{errorSource:"transport",isFatal:!1,...e instanceof Error?{cause:e}:{}})}const a=n.getWriter();if(r&&!this.publisherOpCurrent(r.requestId,r.generation)){try{await a.abort(new Error("subgroup open cancelled before header (§5.1.1)"))}catch{}throw new Pn(`openSubgroup: subscription for track alias ${e} was cancelled while opening the stream (§5.1.1)`,{errorSource:"data"})}const o=this.nextOutgoingStreamId++;if(this.outgoingStreams.set(o,{writer:a,hasExtensions:i?.hasExtensions??!1,previousObjectId:0n,isFirstObject:!0,...r?{subscriptionRequestId:r.requestId}:{}}),r?.sub){r.sub.incrementStreamCount();let e=this.openSubgroupsByRequest.get(r.requestId);e||(e=new Set,this.openSubgroupsByRequest.set(r.requestId,e)),e.add(o)}const c=async e=>{try{await a.abort(e instanceof Error?e:new Error(String(e)))}catch{}if(r){const e=this.openSubgroupsByRequest.get(r.requestId);e&&(e.delete(o),0===e.size&&this.openSubgroupsByRequest.delete(r.requestId))}this.outgoingStreams.delete(o)};try{const n=i?.subgroupIdMode??Bi,d=18===this.session.draftVersion;let h=Mi|n<<1;i?.hasExtensions&&(h|=d?Ae:Pi),i?.endOfGroup&&(h|=d?Oe:Ui),i?.defaultPriority&&(h|=d?Pe:Li),i?.firstObject&&(h|=Ne);const u={typeByte:h,trackAlias:e,groupId:t,subgroupId:s,publisherPriority:i?.defaultPriority?void 0:i?.publisherPriority??128,hasExtensions:i?.hasExtensions??!1,isEndOfGroup:i?.endOfGroup??!1,isFirstObjectInSubgroup:i?.firstObject??!1},l=d?function(e){const t=2===xe(e.typeByte),s=0!==(e.typeByte&Pe);if(!t&&0n!==e.subgroupId)throw new Error("SUBGROUP_HEADER: a non-explicit subgroup-ID mode must not carry a meaningful subgroupId (use 0n)");if(s===(void 0!==e.publisherPriority))throw new Error("SUBGROUP_HEADER: publisherPriority presence must match the DEFAULT_PRIORITY (0x20) flag (set ⇒ omit, clear ⇒ provide)");const i=!s;let r=Z(BigInt(e.typeByte));r+=Z(e.trackAlias),r+=Z(e.groupId),t&&(r+=Z(e.subgroupId)),i&&(r+=1);const n=new Uint8Array(r);let a=te(BigInt(e.typeByte),n,0);return a+=te(e.trackAlias,n,a),a+=te(e.groupId,n,a),t&&(a+=te(e.subgroupId,n,a)),i&&(n[a++]=e.publisherPriority),n}(u):function(e){let t=z(Q(e.typeByte));t+=z(e.trackAlias),t+=z(e.groupId);const s=(e.typeByte&Ni)>>1;s===Bi&&(t+=z(e.subgroupId)),void 0!==e.publisherPriority&&(t+=1);const i=new Uint8Array(t);let r=0;return r+=J(Q(e.typeByte),i,r),r+=J(e.trackAlias,i,r),r+=J(e.groupId,i,r),s===Bi&&(r+=J(e.subgroupId,i,r)),void 0!==e.publisherPriority&&(i[r++]=e.publisherPriority),i}(u);if(await a.write(l),r&&!this.publisherOpCurrent(r.requestId,r.generation))throw await c(new Error("subgroup open cancelled during header write (§5.1.1)")),new Pn(`openSubgroup: subscription for track alias ${e} was cancelled while writing the header (§5.1.1)`,{errorSource:"data"});return o}catch(e){throw this.outgoingStreams.has(o)&&await c(e),e}}finally{this.endPublishOp(r?.requestId)}}async sendObject(e,t,s,i){const r=this.outgoingStreams.get(e);if(!r)throw new Pn(`Unknown outgoing stream ${e}`,{errorSource:"data"});const n={objectId:t,extensions:i,payload:s,status:void 0},a=18===this.session.draftVersion?function(e,t,s,i=!0){if(void 0!==e.status&&e.payload.length>0)throw new Error("SubgroupObject: status is only valid on empty payloads");if(!t&&void 0!==e.extensions&&e.extensions.length>0)throw new Error("SubgroupObject: extensions provided but the stream PROPERTIES bit is not set");const r=i?e.objectId:e.objectId-s-1n,n=t?e.extensions??new Uint8Array(0):void 0,a=e.payload.length,o=0===a?e.status??0n:void 0;let c=Z(r);void 0!==n&&(c+=Z(BigInt(n.length))+n.length),c+=Z(BigInt(a)),c+=void 0!==o?Z(o):a;const d=new Uint8Array(c);let h=te(r,d,0);return void 0!==n&&(h+=te(BigInt(n.length),d,h),d.set(n,h),h+=n.length),h+=te(BigInt(a),d,h),void 0!==o?h+=te(o,d,h):(d.set(e.payload,h),h+=a),d}(n,r.hasExtensions,r.previousObjectId,r.isFirstObject):function(e,t,s,i=!0){if(void 0!==e.status&&e.payload.length>0)throw new Error(`SubgroupObject: status (0x${e.status.toString(16)}) is only valid on empty payloads; got payload.length=${e.payload.length}`);let r;r=i?e.objectId:Q(e.objectId-s-1n);let n=z(r);if(t){const t=e.extensions?.length??0;n+=z(Q(t)),n+=t}const a=e.payload.length;n+=z(Q(a));const o=0===a?e.status??ki.NORMAL:e.status;n+=0===a&&void 0!==o?z(o):a;const c=new Uint8Array(n);let d=0;if(d+=J(r,c,d),t){const t=e.extensions?.length??0;d+=J(Q(t),c,d),t>0&&e.extensions&&(c.set(e.extensions,d),d+=t)}return d+=J(Q(a),c,d),0===a&&void 0!==o?d+=J(o,c,d):a>0&&(c.set(e.payload,d),d+=a),c}(n,r.hasExtensions,Q(r.previousObjectId),r.isFirstObject);await r.writer.write(a),r.previousObjectId=t,r.isFirstObject=!1}async sendDatagram(e,t,s,i,r){if(18!==this.session.draftVersion)throw new Pn("sendDatagram is draft-18 only",{errorSource:"data"});if(!this.transport?.datagrams)throw new Pn("Transport does not support datagrams",{errorSource:"transport"});const n=this.beginPublishOp(e,"sendDatagram");try{const n=function(e){const t=e.typeByte,s=0!==(t&Le),i=0!==(t&De),r=0!==(t&Ue),n=0!==(t&Be);if(n&&e.payload.length>0)throw new Error("OBJECT_DATAGRAM: a STATUS object MUST have an empty payload");if(!n&&void 0!==e.status)throw new Error("OBJECT_DATAGRAM: status provided without the STATUS (0x20) type flag");if(s&&0n!==e.objectId)throw new Error("OBJECT_DATAGRAM: ZERO_OBJECT_ID (0x04) requires objectId === 0n");if(i===(void 0!==e.publisherPriority))throw new Error("OBJECT_DATAGRAM: publisherPriority presence must match the DEFAULT_PRIORITY (0x08) flag (set ⇒ omit, clear ⇒ provide)");if(!r&&void 0!==e.extensions&&e.extensions.length>0)throw new Error("OBJECT_DATAGRAM: extensions provided without the PROPERTIES (0x01) type flag");if(r&&(void 0===e.extensions||0===e.extensions.length))throw new Error("OBJECT_DATAGRAM: PROPERTIES (0x01) flag set but extensions are empty");const a=!i,o=r?e.extensions??new Uint8Array(0):void 0;let c=Z(BigInt(t));c+=Z(e.trackAlias),c+=Z(e.groupId),s||(c+=Z(e.objectId)),a&&(c+=1),void 0!==o&&(c+=Z(BigInt(o.length))+o.length),c+=n?Z(e.status??0n):e.payload.length;const d=new Uint8Array(c);let h=te(BigInt(t),d,0);return h+=te(e.trackAlias,d,h),h+=te(e.groupId,d,h),s||(h+=te(e.objectId,d,h)),a&&(d[h++]=e.publisherPriority),void 0!==o&&(h+=te(BigInt(o.length),d,h),d.set(o,h),h+=o.length),n?h+=te(e.status??0n,d,h):(d.set(e.payload,h),h+=e.payload.length),d}({typeByte:0,trackAlias:e,groupId:t,objectId:s,publisherPriority:r?.publisherPriority??128,isEndOfGroup:!1,extensions:void 0,payload:i,status:void 0}),a=this.transport.datagrams.writable?.getWriter();if(!a)throw new Pn("Transport datagrams are not writable",{errorSource:"transport"});try{await a.write(n)}finally{a.releaseLock()}}finally{this.endPublishOp(n?.requestId)}}async closeSubgroup(e){const t=this.outgoingStreams.get(e);if(t){try{await t.writer.close()}catch{}if(this.outgoingStreams.delete(e),void 0!==t.subscriptionRequestId){const s=this.openSubgroupsByRequest.get(t.subscriptionRequestId);s&&(s.delete(e),0===s.size&&this.openSubgroupsByRequest.delete(t.subscriptionRequestId))}}}async openFetchStream(e){if(18!==this.session.draftVersion)throw new Pn("openFetchStream is draft-18 only",{errorSource:"data"});const t=this.inboundFetchGroupOrder.get(e);if(void 0===t)throw new Pn(`No admitted inbound FETCH for request ${e}`,{errorSource:"data"});if(!this.transport?.createUnidirectionalStream)throw new Pn("Transport does not support createUnidirectionalStream",{errorSource:"transport"});if(this.fetchServeReserved.has(e))throw new Pn(`FETCH ${e} already has its one response stream (§11.4.4)`,{errorSource:"data"});this.fetchServeReserved.add(e);const s=(await this.transport.createUnidirectionalStream()).getWriter();if(!this.inboundFetchGroupOrder.has(e)){this.fetchServeReserved.delete(e);try{await s.abort(new Error("inbound FETCH deauthorized during stream open"))}catch{}throw new Pn(`No admitted inbound FETCH for request ${e}`,{errorSource:"data"})}try{await s.write(function(e){const t=new Uint8Array(Z(BigInt(Re))+Z(e));let s=te(BigInt(Re),t,0);return te(e,t,s),t}(e))}catch(t){this.fetchServeReserved.delete(e);try{await s.abort(t instanceof Error?t:new Error(String(t)))}catch{}throw t instanceof Error?t:new Error(String(t))}if(!this.inboundFetchGroupOrder.has(e)){this.fetchServeReserved.delete(e);try{await s.abort(new Error("inbound FETCH deauthorized during stream open"))}catch{}throw new Pn(`No admitted inbound FETCH for request ${e}`,{errorSource:"data"})}const i=this.nextOutgoingStreamId++;return this.fetchOutgoingStreams.set(i,{requestId:e,writer:s,groupOrder:t,prior:void 0,isFirstObject:!0}),i}async sendFetchObject(e,t){const s=this.fetchOutgoingStreams.get(e);if(!s)throw new Pn(`Unknown fetch stream ${e}`,{errorSource:"data"});const{bytes:i,nextPrior:r}=function(e,t,s,i){const{groupId:r,subgroupId:n,objectId:a,publisherPriority:o,payload:c}=e,d=s||r!==t.groupId;let h,u,l=Zi|ji|Wi;if(d){if(l|=Ki,h=s?r:"ascending"===i?r-t.groupId-1n:t.groupId-r-1n,h<0n||h>X)throw new Error(`fetch Group ID Delta out of range for ${i} order`);u=a}else if(u=a-t.objectId,u<0n)throw new Error("fetch Object ID must not decrease within a group");const p=c.length;let m=Z(BigInt(l));void 0!==h&&(m+=Z(h)),m+=Z(n),m+=Z(u),m+=1,m+=Z(BigInt(p)),m+=p;const g=new Uint8Array(m);let f=te(BigInt(l),g,0);return void 0!==h&&(f+=te(h,g,f)),f+=te(n,g,f),f+=te(u,g,f),g[f++]=o,f+=te(BigInt(p),g,f),g.set(c,f),f+=p,{bytes:g,nextPrior:{groupId:r,objectId:a,lastObjectSubgroupId:n,lastObjectPriority:o}}}(t,s.prior,s.isFirstObject,s.groupOrder);await s.writer.write(i),s.prior=r,s.isFirstObject=!1}async sendFetchEndOfRange(e,t,s,i){const r=this.fetchOutgoingStreams.get(e);if(!r)throw new Pn(`Unknown fetch stream ${e}`,{errorSource:"data"});const{bytes:n,nextPrior:a}=function(e,t,s,i){const r=BigInt(e?er:tr),n=Z(r)+Z(t)+Z(s)+Z(0n),a=new Uint8Array(n);let o=te(r,a,0);return o+=te(t,a,o),o+=te(s,a,o),te(0n,a,o),{bytes:a,nextPrior:{groupId:t,objectId:s,lastObjectSubgroupId:i?.lastObjectSubgroupId,lastObjectPriority:i?.lastObjectPriority}}}(t,s,i,r.prior);await r.writer.write(n),r.prior=a,r.isFirstObject=!1}async closeFetchStream(e){const t=this.fetchOutgoingStreams.get(e);if(t){try{await t.writer.close()}catch{}this.fetchOutgoingStreams.delete(e),this.session.reclaimServedFetch(t.requestId)}}async executeActions(e){for(const t of e)switch(t.type){case"send_control":{const e=this.codec.encode(t.message);this.onQlogEvent?.({type:"control_message_created",stream_id:Nn.CONTROL_STREAM_QLOG_ID,length:e.byteLength,message:t.message}),await this.controlWriter.write(e);break}case"close_connection":try{const e=this.transport?.close({closeCode:Number(t.error),reason:t.reason});Promise.resolve(e).catch(()=>{})}catch{}break;case"open_namespace_stream":this.openNamespaceStream(t.requestId,t.message);break;case"stop_sending":{const e=this.dataStreamReaders.get(t.streamId);if(e){try{await e.cancel(new Error(`STOP_SENDING: ${t.error}`))}catch{}this.dataStreamReaders.delete(t.streamId)}break}case"notify_namespace":this.onNamespaceMessage?.(t.requestId,t.message);break;case"cancel_request":{const e=this.rawSubscriptions.get(t.requestId);e&&(this.rawSubscriptions.delete(t.requestId),e.reject?.(new Pn(t.reason,{errorSource:"control",isFatal:!1})),e.resolve=null,e.reject=null);for(const[e,s]of this.rawAliasMaps)s.requestId===t.requestId&&this.rawAliasMaps.delete(e);18===this.session.draftVersion&&await(this.uniPair?.cancelRequest(t.requestId));break}case"close_stream":case"reset_stream":case"open_data_stream":case"send_object":this.onError?.(new Pn(`Unhandled session action type: "${t.type}"`,{errorSource:"control"}))}}async runControlReadLoop(e){try{for(;;){const{value:t,done:s}=await e.read();if(s){this.closeSessionFatal("Control stream closed unexpectedly");break}let i;this.framer.push(t);try{i=this.framer.drain()}catch(e){const t=e instanceof Error?e.message:String(e);return void this.closeSessionFatal(`Malformed control message: ${t}`)}for(const e of i){const t=e.message;if("SUBSCRIBE_OK"===t.type){this.onQlogEvent?.({type:"control_message_parsed",stream_id:Nn.CONTROL_STREAM_QLOG_ID,message:t}),await this.handleSubscribeOkOrdered(t,t.requestId);continue}this.onQlogEvent?.({type:"control_message_parsed",stream_id:Nn.CONTROL_STREAM_QLOG_ID,message:t});const s="PUBLISH_DONE"===t.type?this.session.getSubscription(t.requestId)?.trackAlias:void 0,i="requestId"in t&&this.session.isCancelledRequest(t.requestId);this.handleRawSubControlMessage(t)||i||this.onMessage?.(t);const r="PUBLISH_DONE"===t.type&&void 0!==s?this.applyTerminalStreamCount(s,BigInt(t.streamCount??0n),t.requestId):Promise.resolve(),n="SUBSCRIBE"===t.type?this.session.getIncomingSubscription(t.requestId):void 0,a=this.session.handleControlMessage(t);if(await this.executeActions(a),await r,"SUBSCRIBE"===t.type&&this.onSubscribe){const e=t,s=this.session.getIncomingSubscription(e.requestId);void 0!==s&&s!==n&&this.session.state!==Pr&&this.onSubscribe(e.requestId,e.trackNamespace,e.trackName,e.parameters)}"UNSUBSCRIBE"===t.type&&await this.abortPublisherStreamsForRequest(t.requestId),"FETCH_CANCEL"===t.type&&await this.abortFetchStreamsForRequest(t.requestId,"inbound FETCH_CANCEL")}}}catch(e){const t=e instanceof Error?e.message:String(e);this._terminated||this.onError?.(new Pn(t,{errorSource:"control",...e instanceof Error?{cause:e}:{}})),this.terminate(2,t,{preliminary:!0})}}async runIncomingStreamLoop(e){try{const t=e.incomingUnidirectionalStreams.getReader();for(;;){const{value:e,done:s}=await t.read();if(s)break;const i=this.nextStreamId++;this.processDataStream(e,i)}}catch(e){if(this.session.state===Pr)return;this.onError?.(new Pn(e instanceof Error?e.message:String(e),{errorSource:"transport",isFatal:!0,...e instanceof Error?{cause:e}:{}}))}}async runDatagramLoop(e){try{const t=e.datagrams.readable.getReader();for(;;){const{value:e,done:s}=await t.read();if(s)break;try{if("padding"===this.dataCodec.classifyDatagram(e,0))continue;const{datagram:t}=this.dataCodec.decodeObjectDatagram(e,0);if(this.terminatedAliases.has(t.trackAlias))continue;this.onQlogEvent?.({type:"object_datagram_parsed",track_alias:t.trackAlias,group_id:t.groupId,object_id:t.objectId,...void 0!==t.publisherPriority?{publisher_priority:t.publisherPriority}:{},...t.extensions?{extension_headers_length:t.extensions.byteLength}:{},...void 0!==t.status?{object_status:t.status}:{},...t.payload.byteLength>0?{object_payload:{payload_length:t.payload.byteLength}}:{},end_of_group:t.isEndOfGroup}),this.onDatagram?.(t)}catch(e){if(e instanceof ze)return void this.closeSessionFatal(e.message);if(!(e instanceof RangeError)){const t=e instanceof Error?e.message:String(e);this.onError?.(new Pn(t,{errorSource:"datagram",...e instanceof Error?{cause:e}:{}}))}}}}catch(e){if(this._terminated||this.session.state===Pr)return;this.onError?.(new Pn(e instanceof Error?e.message:String(e),{errorSource:"transport",...e instanceof Error?{cause:e}:{}}))}}async runIncomingBidiLoop(e){if(e.incomingBidirectionalStreams)try{const t=e.incomingBidirectionalStreams.getReader();for(;;){const{value:e,done:s}=await t.read();if(s)break;this.handleIncomingBidiStream(e)}}catch(e){if(this.session.state===Pr)return;this.onError?.(new Pn(e instanceof Error?e.message:String(e),{errorSource:"transport",isFatal:!0,...e instanceof Error?{cause:e}:{}}))}}handleIncomingBidiStream(e){const t=new On(e,this.codec,{onMessage:(e,t)=>this.dispatchInboundRequestMessage(e,t),onFailure:(e,t)=>{this.onInboundStreamClosed(t,e)},onClosed:e=>{this.onInboundStreamClosed(e,null)}});t.start()}async onInboundStreamClosed(e,t){if(t instanceof ze)await this.failInboundRequest(t);else{if(null!==e.requestId&&"publish-namespace"===e.openerKind){const t=e.requestId;return await this.executeActions(this.session.handleInboundPublishNamespaceClosed(t)),this.inboundRequestContexts.delete(t),await e.terminate(),void this.onPublishNamespaceClosed?.(t)}if(null!==e.requestId&&"subscribe-namespace"===e.openerKind){const t=e.requestId;return await this.executeActions(this.session.handleInboundSubscribeNamespaceClosed(t)),this.inboundRequestContexts.delete(t),await e.terminate(),void this.onSubscribeNamespaceClosed?.(t)}if(null!==e.requestId&&"subscribe-tracks"===e.openerKind){const t=e.requestId;return await this.executeActions(this.session.handleInboundSubscribeTracksClosed(t)),this.inboundRequestContexts.delete(t),await e.terminate(),void this.onSubscribeTracksClosed?.(t)}if(null===e.requestId||"track-status"!==e.openerKind||null!==t){if(null!==e.requestId){const t=e.requestId,s="subscribe"===e.openerKind,i="publish"===e.openerKind?[...this.publishAliasMaps].find(([,e])=>e.requestId===t)?.[0]:void 0;void 0!==i&&this.armTerminatedAlias(i,null,!1),this.inboundFetchGroupOrder.delete(t),this.fetchServeReserved.delete(t),this.inboundPublishTimeouts.delete(t);const r=this.detachFetchStreamsForRequest(t);await this.executeActions(this.session.handleInboundRequestClosed(t)),this.inboundRequestContexts.delete(t),void 0!==i&&await this.discardOpenStreamsForAlias(i),s&&await this.abortPublisherStreamsForRequest(t),await e.terminate();for(const e of r)try{await e.abort("inbound FETCH request stream closed")}catch{}if("fetch"===e.openerKind)for(const[e,s]of this.pendingJoinFetches){const i=s.findIndex(e=>e.requestId===t);if(!(i<0)){clearTimeout(s[i].timer),s.splice(i,1),0===s.length&&this.pendingJoinFetches.delete(e);break}}return s&&(this.deferredUpdateResponses.delete(t),await this.settleParkedJoins(t,!1)),void(s&&this.onSubscribeClosed?.(t))}t&&await this.failInboundRequest(t)}}}async failInboundRequest(e){e instanceof ze?this.closeSessionFatal(e.message):this.onError?.(new Pn(e.message,{errorSource:"control",cause:e}))}async dispatchInboundRequestMessage(e,t){if(null===t.requestId){if("PUBLISH"===e.type)return void await this.bindInboundPublish(e,t);if("SUBSCRIBE"===e.type)return void await this.bindInboundSubscribe(e,t);if("FETCH"===e.type)return void await this.bindInboundFetch(e,t);if("TRACK_STATUS"===e.type)return void await this.bindInboundTrackStatus(e,t);if("PUBLISH_NAMESPACE"===e.type)return void await this.bindInboundPublishNamespace(e,t);if("SUBSCRIBE_NAMESPACE"===e.type)return void await this.bindInboundSubscribeNamespace(e,t);if("SUBSCRIBE_TRACKS"===e.type)return void await this.bindInboundSubscribeTracks(e,t);throw new ze(`first inbound bidi message must be PUBLISH, SUBSCRIBE, FETCH, TRACK_STATUS, PUBLISH_NAMESPACE, SUBSCRIBE_NAMESPACE, or SUBSCRIBE_TRACKS, got ${e.type}`)}const s=t.requestId;if("PUBLISH_DONE"===e.type){if("publish"!==t.openerKind)throw new ze(`PUBLISH_DONE is not valid on a ${t.openerKind} request stream`);const i=[...this.publishAliasMaps].find(([,e])=>e.requestId===s)?.[0],r=e.streamCount??0n,n={...e,requestId:s};this.onMessage?.(n);const a=void 0!==i?this.applyTerminalStreamCount(i,BigInt(r),s):Promise.resolve();return await this.executeActions(this.session.handleInboundPublishDone(s)),t.seal(),this.inboundRequestContexts.delete(s),void await a}if("REQUEST_UPDATE"===e.type){if("track-status"===t.openerKind)throw new ze("REQUEST_UPDATE is not valid on a TRACK_STATUS request stream");const i=e.requestId,r={...e,existingRequestId:s};this.onMessage?.(r);const n=this.session.handleControlMessage(r,{requestId:i,existingRequestId:s}),a=n.find(e=>"close_connection"===e.type);if(a)return await this.executeActions(n),void this.notifyClose(a,"REQUEST_UPDATE rejected");const o=n.find(e=>"send_control"===e.type);if(o&&"subscribe"===t.openerKind&&this.session.getIncomingSubscription(s)?.state===Mr){const e=this.deferredUpdateResponses.get(s)??[];return e.length>=Nn.MAX_DEFERRED_UPDATE_RESPONSES?(e.push(o.message),this.deferredUpdateResponses.set(s,e),await this.executeActions(n.filter(e=>"send_control"!==e.type)),void await this.rejectSubscribe(s,Ke.EXCESSIVE_LOAD,"too many REQUEST_UPDATEs on a pending subscription")):(e.push(o.message),this.deferredUpdateResponses.set(s,e),void await this.executeActions(n.filter(e=>"send_control"!==e.type)))}o&&await t.writeMessage(o.message),await this.executeActions(n.filter(e=>"send_control"!==e.type));const c="subscribe-namespace"===t.openerKind||"subscribe-tracks"===t.openerKind||"publish-namespace"===t.openerKind;return void("REQUEST_ERROR"===o?.message.type&&c&&(t.seal(),await t.terminate(),this.inboundRequestContexts.delete(s)))}throw new ze(`unexpected ${e.type} on inbound request stream`)}notifyClose(e,t){this.terminate(Number(e.error),e.reason??t)}async bindInboundPublish(e,t){const s=e.requestId;this.onMessage?.(e);const i=this.session.handleControlMessage(e),r=i.find(e=>"close_connection"===e.type);if(r)return await this.executeActions(i),await t.abort(),void this.notifyClose(r,"PUBLISH rejected");if(await this.autoRejectInboundRequest(i,t))return;await this.executeActions(i),t.bind(s,"publish"),this.inboundRequestContexts.set(s,t);const n=this.trackPropertyFault(e);if(n){const e=this.session.rejectSubscribe(s,n.code,n.reason);return void await this.writeInboundRequestResponse(s,e,!0)}const a=e.trackAlias;if(!this.aliasReuseSafe(a)){const e=this.session.rejectSubscribe(s,Ke.DUPLICATE_SUBSCRIPTION,`track alias ${a} is still guarded by a terminating prior subscription (§11.1)`);return void await this.writeInboundRequestResponse(s,e,!0)}this.clearTerminatedAlias(a);const o={requestId:s,trackNamespace:e.trackNamespace,trackName:e.trackName,trackAlias:a,onObject:null};this.publishAliasMaps.set(o.trackAlias,o);const c=this.trackPropsOf(e),d=this.trackPropMs(c,0x02n)??0,h=this.trackPropMs(c,0x06n)??0;this.inboundPublishTimeouts.set(s,{obj:d,sub:h}),this.aliasPublisherTimeout.set(a,{obj:d,sub:h});const u=this.combineDeliveryTimeoutMs(d,h,0,0);u>0&&this.aliasDeliveryTimeoutMs.set(a,u),this.onPublish?.(o)}async autoRejectInboundRequest(e,t){const s=e.find(e=>"send_control"===e.type&&"REQUEST_ERROR"===e.message.type);return!!s&&(await t.writeMessage(s.message),await this.executeActions(e.filter(e=>e!==s)),await t.finish(),t.seal(),!0)}async bindInboundSubscribe(e,t){const s=e.requestId;this.onMessage?.(e);const i=this.session.handleControlMessage(e),r=i.find(e=>"close_connection"===e.type);if(r)return await this.executeActions(i),await t.abort(),void this.notifyClose(r,"SUBSCRIBE rejected");await this.autoRejectInboundRequest(i,t)||(await this.executeActions(i),t.bind(s,"subscribe"),this.inboundRequestContexts.set(s,t),this.onSubscribe?.(s,e.trackNamespace,e.trackName,e.parameters))}async bindInboundFetch(e,t){const s=e.requestId;this.onMessage?.(e);const i=this.session.handleControlMessage(e),r=i.find(e=>"close_connection"===e.type);if(r)return await this.executeActions(i),await t.abort(),void this.notifyClose(r,"FETCH rejected");if(await this.autoRejectInboundRequest(i,t))return;await this.executeActions(i),t.bind(s,"fetch"),this.inboundRequestContexts.set(s,t);const n=e.parameters.get(0x22n)?.[0];if(this.inboundFetchGroupOrder.set(s,2n===n?"descending":"ascending"),1!==e.fetch.fetchType){const t=e.fetch.joiningRequestId,i=this.session.getIncomingSubscription(t);if(i&&i.state===Mr){const i={requestId:s,fetch:e,timer:setTimeout(()=>{this.expireParkedJoin(t,s)},this.joiningFetchTimeoutMs)},r=this.pendingJoinFetches.get(t)??[];return r.push(i),void this.pendingJoinFetches.set(t,r)}}this.onFetch?.(s,e)}async expireParkedJoin(e,t){const s=this.pendingJoinFetches.get(e);if(!s)return;const i=s.findIndex(e=>e.requestId===t);if(!(i<0)){s.splice(i,1),0===s.length&&this.pendingJoinFetches.delete(e);try{await this.rejectFetch(t,Ke.TIMEOUT,"joining fetch timed out waiting for the subscription to establish (§10.12.2)")}catch{}}}async settleParkedJoins(e,t){const s=this.pendingJoinFetches.get(e);if(s){this.pendingJoinFetches.delete(e);for(const i of s){if(clearTimeout(i.timer),!t){try{await this.rejectFetch(i.requestId,Ke.INVALID_JOINING_REQUEST_ID,"the joined subscription was rejected (§10.12.2)")}catch{}continue}const s=this.session.getIncomingSubscription(e);if(s&&s.forwardState===xr)this.onFetch?.(i.requestId,i.fetch);else try{await this.rejectFetch(i.requestId,Ke.INVALID_RANGE,"Joining Fetch on a subscription with Forward State 0 at establish (§10.12.2)")}catch{}}}}async bindInboundTrackStatus(e,t){const s=e.requestId;this.onMessage?.(e);const i=this.session.handleControlMessage(e),r=i.find(e=>"close_connection"===e.type);if(r)return await this.executeActions(i),await t.abort(),void this.notifyClose(r,"TRACK_STATUS rejected");await this.autoRejectInboundRequest(i,t)||(await this.executeActions(i),t.bind(s,"track-status"),this.inboundRequestContexts.set(s,t),this.onTrackStatus?.(s,e))}async bindInboundPublishNamespace(e,t){const s=e.requestId;this.onMessage?.(e);const i=this.session.handleControlMessage(e),r=i.find(e=>"close_connection"===e.type);if(r)return await this.executeActions(i),await t.abort(),void this.notifyClose(r,"PUBLISH_NAMESPACE rejected");if(await this.autoRejectInboundRequest(i,t))return;t.bind(s,"publish-namespace"),this.inboundRequestContexts.set(s,t);const n=i.find(e=>"send_control"===e.type);n&&await t.writeMessage(n.message),await this.executeActions(i.filter(e=>"send_control"!==e.type)),this.onPublishNamespace?.(s,e)}async bindInboundSubscribeNamespace(e,t){const s=e.requestId;this.onMessage?.(e);const i=this.session.handleControlMessage(e),r=i.find(e=>"close_connection"===e.type);if(r)return await this.executeActions(i),await t.abort(),void this.notifyClose(r,"SUBSCRIBE_NAMESPACE rejected");const n=i.find(e=>"send_control"===e.type);if(n)return await t.writeMessage(n.message),await this.executeActions(i.filter(e=>"send_control"!==e.type)),t.seal(),void await t.terminate();t.bind(s,"subscribe-namespace"),this.inboundRequestContexts.set(s,t),await this.executeActions(i),this.onSubscribeNamespace?.(s,e)}async bindInboundSubscribeTracks(e,t){const s=e.requestId;this.onMessage?.(e);const i=this.session.handleControlMessage(e),r=i.find(e=>"close_connection"===e.type);if(r)return await this.executeActions(i),await t.abort(),void this.notifyClose(r,"SUBSCRIBE_TRACKS rejected");const n=i.find(e=>"send_control"===e.type);if(n)return await t.writeMessage(n.message),await this.executeActions(i.filter(e=>"send_control"!==e.type)),t.seal(),void await t.terminate();t.bind(s,"subscribe-tracks"),this.inboundRequestContexts.set(s,t),await this.executeActions(i),this.onSubscribeTracks?.(s,e)}async processDataStream(e,t){const s=e.getReader();this.dataStreamReaders.set(t,s);let i=new Uint8Array(0);try{const e=await this.readStreamHeader(s,i);if(!e)return void this.onStreamClosed?.(t);if("discard"===e.type){for(;;){const{done:e}=await s.read();if(e)break}return void this.onStreamClosed?.(t)}if(i=e.remaining,"subgroup"===e.type){const r=e.header,n=r.trackAlias,a=this.terminatedAliases.get(n);if(a){null!==a.remaining&&(a.remaining-=1n,a.remaining<=0n&&this.clearTerminatedAlias(n));try{await s.cancel(new Error("late stream on a terminated alias — early discard (§10.11)"))}catch{}return this.dataStreamReaders.delete(t),void this.onStreamClosed?.(t)}this.aliasStreamsSeen.set(n,(this.aliasStreamsSeen.get(n)??0n)+1n),this.incomingSubgroupAliases.set(t,n),this.onQlogEvent?.({type:"stream_type_set",owner:"remote",stream_id:t,stream_type:"subgroup_header"}),this.onQlogEvent?.({type:"subgroup_header_parsed",stream_id:t,track_alias:r.trackAlias,group_id:r.groupId,subgroup_id_mode:rr(r.typeByte),...void 0!==r.subgroupId?{subgroup_id:r.subgroupId}:{},...void 0!==r.publisherPriority?{publisher_priority:r.publisherPriority}:{},contains_end_of_group:r.isEndOfGroup,extensions_present:r.hasExtensions}),this.onDataStream?.(t,{type:"subgroup",header:r}),await this.readSubgroupObjects(s,i,t,r)}else{const r=e.header,n=r.requestId;if(this.recentlyCancelledFetches.has(n))return this.recentlyCancelledFetches.delete(n),void await s.cancel(new Error("FETCH cancelled — late data stream discarded")).catch(()=>{});if(this.fetchStreams.has(n))throw new ze(`second FETCH response stream for request ${n} while one is open (§11.4.4: exactly one)`);this.fetchStreams.set(n,t),this.onQlogEvent?.({type:"stream_type_set",owner:"remote",stream_id:t,stream_type:"fetch_header"}),this.onQlogEvent?.({type:"fetch_header_parsed",stream_id:t,request_id:r.requestId}),this.onDataStream?.(t,{type:"fetch",header:r}),18===this.dataCodec.version?await this.readFetchObjects18(s,i,t,r):await this.readFetchObjects(s,i,t)}this.onStreamClosed?.(t)}catch(e){if(e instanceof ze)return void this.closeSessionFatal(e.message);const s="number"==typeof e?.streamErrorCode?e.streamErrorCode:void 0,i=this._terminated||this.session.state===Pr;void 0!==s||i||this.onError?.(new Pn(e instanceof Error?e.message:String(e),{errorSource:"data",streamId:BigInt(t),...e instanceof Error?{cause:e}:{}})),this.onStreamClosed?.(t,s)}finally{this.dataStreamReaders.delete(t),this.incomingSubgroupAliases.delete(t);for(const[e,s]of this.fetchStreams)if(s===t){this.fetchStreams.delete(e),this.fetchGroupOrder.delete(e),this.session.handleFetchStreamFinished(e),this.closeCompletedFetchRequest(e);break}}}async readStreamHeader(e,t){for(;;){if(t.length>0){const e=t[0];let s;try{s=this.dataCodec.classifyStream(t,0)}catch(e){if(!(e instanceof RangeError))throw e;s=void 0}if("subgroup"===s)try{const{header:e,bytesRead:s}=this.dataCodec.decodeSubgroupHeader(t,0);return{type:"subgroup",header:e,remaining:t.subarray(s)}}catch(e){if(!(e instanceof RangeError))throw e}else if("fetch"===s)try{const{header:e,bytesRead:s}=this.dataCodec.decodeFetchHeader(t,0);return{type:"fetch",header:e,remaining:t.subarray(s)}}catch(e){if(!(e instanceof RangeError))throw e}else{if("padding"===s)return{type:"discard"};if(void 0!==s)throw new ze(`Unknown data stream type (leading byte 0x${e.toString(16)}) — expected SUBGROUP_HEADER or FETCH_HEADER (0x05)`)}}const{value:s,done:i}=await e.read();if(i)return void(t.length>0&&this.closeSessionFatal("Stream FIN received mid-header"));t=this.appendBuffer(t,s)}}async readSubgroupObjects(e,t,s,i){let r=0n,n=!0;for(;;){if(t.length>0)try{const{object:e,bytesRead:a}=this.dataCodec.decodeSubgroupObject(t,0,i.hasExtensions,r,n);t=t.subarray(a),n&&rr(i.typeByte)===Di&&(i={...i,subgroupId:e.objectId});const o=0===e.payload.length&&void 0!==e.status&&0n!==e.status?{kind:"gap",trackAlias:i.trackAlias,groupId:i.groupId,subgroupId:i.subgroupId,objectId:e.objectId,status:e.status}:{kind:"data",trackAlias:i.trackAlias,groupId:i.groupId,subgroupId:i.subgroupId,objectId:e.objectId,publisherPriority:i.publisherPriority,extensions:e.extensions,properties:e.extensions,payload:e.payload},c=n?e.objectId:e.objectId-r-1n;this.onQlogEvent?.({type:"subgroup_object_parsed",stream_id:s,object_id_delta:c,object_payload_length:e.payload.byteLength,...e.extensions&&e.extensions.byteLength>0?{extension_headers:[]}:{},...void 0!==e.status?{object_status:e.status}:{}}),this.routeToTrackSubscription(o)||this.onObject?.(s,o),r=e.objectId,n=!1;continue}catch(e){if(!(e instanceof RangeError))throw e}const{value:a,done:o}=await e.read();if(o){if(t.length>0)return void this.closeSessionFatal("Stream FIN received mid-object");if(i.isEndOfGroup){const e={kind:"gap",trackAlias:i.trackAlias,groupId:i.groupId,subgroupId:i.subgroupId,objectId:r+1n,status:ki.END_OF_GROUP};this.routeToTrackSubscription(e)||this.onObject?.(s,e)}return}t=this.appendBuffer(t,a)}}async readFetchObjects(e,t,s){let i,r=!0;for(;;){if(t.length>0)try{const{item:e,bytesRead:n}=this.dataCodec.decodeFetchObject(t,0,i,r);if(t=t.subarray(n),"payload"in e){this.onQlogEvent?.({type:"fetch_object_parsed",stream_id:s,datagram:e.isDatagram??!1,end_of_nonexistent_range:!1,end_of_unknown_range:!1,...void 0!==e.groupId?{group_id:e.groupId}:{},...void 0!==e.subgroupId?{subgroup_id:e.subgroupId}:{},...void 0!==e.objectId?{object_id:e.objectId}:{},...void 0!==e.publisherPriority?{publisher_priority:e.publisherPriority}:{},...e.extensions?{extension_headers_length:e.extensions.byteLength}:{},object_payload_length:e.payload.byteLength});const t={kind:"data",trackAlias:Q(0),groupId:e.groupId,subgroupId:e.subgroupId,objectId:e.objectId,publisherPriority:e.publisherPriority,extensions:e.extensions,properties:e.extensions,payload:e.payload};this.routeToTrackSubscription(t)||this.onObject?.(s,t),i={groupId:e.groupId,subgroupId:e.subgroupId,objectId:e.objectId,...void 0!==e.publisherPriority?{priority:e.publisherPriority}:{}}}else{const t=e.rawStatus??Q(e.nonExistent?3:0),i={kind:"gap",trackAlias:Q(0),groupId:e.groupId,subgroupId:Q(0),objectId:e.objectId,status:t};this.routeToTrackSubscription(i)||this.onObject?.(s,i)}r=!1;continue}catch(e){if(!(e instanceof RangeError))throw e}const{value:n,done:a}=await e.read();if(a)return void(t.length>0&&this.closeSessionFatal("Fetch stream FIN received mid-object"));t=this.appendBuffer(t,n)}}async readFetchObjects18(e,t,s,i){const r=this.fetchGroupOrder.get(i.requestId);if(void 0===r)throw new ze(`FETCH_HEADER for request ${i.requestId} that is not a live FETCH (unknown, wrong request kind, or a second response stream for a completed fetch)`);let n,a=!0;for(;;){if(this.recentlyCancelledFetches.has(i.requestId))return this.recentlyCancelledFetches.delete(i.requestId),void await e.cancel(new Error("FETCH cancelled — open stream stopped")).catch(()=>{});if(t.length>0)try{const{item:e,bytesRead:i,nextPrior:o}=this.dataCodec.decodeFetchObject18(t,0,n,a,r);if(t=t.subarray(i),n=o,a=!1,"payload"in e){this.onQlogEvent?.({type:"fetch_object_parsed",stream_id:s,datagram:e.isDatagram??!1,end_of_nonexistent_range:!1,end_of_unknown_range:!1,group_id:e.groupId,subgroup_id:e.subgroupId,object_id:e.objectId,...void 0!==e.publisherPriority?{publisher_priority:e.publisherPriority}:{},...e.extensions?{extension_headers_length:e.extensions.byteLength}:{},object_payload_length:e.payload.byteLength});const t={kind:"data",trackAlias:0n,groupId:e.groupId,subgroupId:e.subgroupId,objectId:e.objectId,publisherPriority:e.publisherPriority,extensions:e.extensions,properties:e.extensions,payload:e.payload};this.onObject?.(s,t)}else{const t={kind:"gap",trackAlias:0n,groupId:e.groupId,subgroupId:0n,objectId:e.objectId,status:Q(e.nonExistent?3:0)};this.onObject?.(s,t)}continue}catch(e){if(!(e instanceof RangeError))throw e}const{value:o,done:c}=await e.read();if(c)return void(t.length>0&&this.closeSessionFatal("Fetch stream FIN received mid-object"));t=this.appendBuffer(t,o)}}async openNamespaceStream(e,t){try{const s=await this.transport.createBidirectionalStream(),i=s.writable.getWriter();this.namespaceStreams.set(e,i);const r=this.codec.encode(t);await i.write(r);const n=s.readable.getReader();this.runNamespaceStreamReadLoop(n,e)}catch(e){this.onError?.(new Pn(e instanceof Error?e.message:String(e),{errorSource:"control",...e instanceof Error?{cause:e}:{}}))}}async runNamespaceStreamReadLoop(e,t){const s=new Sn(this.codec);try{for(;;){const{value:i,done:r}=await e.read();if(r)break;s.push(i);const n=s.drain();for(const e of n){const s=e.message;this.onNamespaceMessage?.(t,s);const i=this.session.handleNamespaceStreamMessage(t,s);await this.executeActions(i)}}}catch(e){this._terminated||this.session.state===Pr||this.onError?.(new Pn(e instanceof Error?e.message:String(e),{errorSource:"control",...e instanceof Error?{cause:e}:{}}))}finally{this.namespaceStreams.delete(t)}}appendBuffer(e,t){if(0===e.length)return t;const s=new Uint8Array(e.length+t.length);return s.set(e,0),s.set(t,e.length),s}}function Un(e,t){return e.groupIdt.groupId?1:e.objectIdt.objectId?1:0}class Mn{heap=[];maxDepth;constructor(e){this.maxDepth=e}get size(){return this.heap.length}insert(e){return!(this.heap.length>=this.maxDepth)&&(this.heap.push(e),this.bubbleUp(this.heap.length-1),!0)}peek(){return this.heap[0]}extract(){if(0===this.heap.length)return;const e=this.heap[0],t=this.heap.pop();return this.heap.length>0&&(this.heap[0]=t,this.sinkDown(0)),e}hasContiguous(e,t){if(0===this.heap.length)return!1;const s=this.heap[0];return s.groupId===e&&s.objectId===t}drainGroup(e){const t=[],s=[];for(const i of this.heap)i.groupId===e?t.push(i):s.push(i);t.sort(Un),this.heap.length=0;for(const e of s)this.heap.push(e);return this.rebuild(),t}discardBefore(e){const t=[];let s=0;for(const i of this.heap)i.groupIdt||n===t&&r.groupId0;){const t=e-1>>1;if(Un(this.heap[e],this.heap[t])>=0)break;this.swap(e,t),e=t}}sinkDown(e){const t=this.heap.length;for(;;){let s=e;const i=2*e+1,r=2*e+2;if(i>1)-1;e>=0;e--)this.sinkDown(e)}}const Ln="wait",Dn="skip_forward",Bn="track_ended";class xn{_gapTimeoutUs;clock;endedGroups=new Set;trackEnded=!1;groupFirstSeenUs=new Map;constructor(e){this._gapTimeoutUs=e.gapTimeoutUs,this.clock=e.clock}get gapTimeoutUs(){return this._gapTimeoutUs}set gapTimeoutUs(e){this._gapTimeoutUs=e}observeGroup(e){this.groupFirstSeenUs.has(e)||this.groupFirstSeenUs.set(e,this.clock.now())}observeEndOfGroup(e){this.endedGroups.add(e)}observeEndOfTrack(){this.trackEnded=!0}get isTrackEnded(){return this.trackEnded}reset(){this.endedGroups.clear(),this.trackEnded=!1,this.groupFirstSeenUs.clear()}evaluate(e,t){if(this.trackEnded)return{action:Bn};if(0===t.length)return{action:Ln};const s=e+1n,i=[...t].sort((e,t)=>et?1:0),r=i[0];if(r<=s)return{action:Ln};let n=!0;for(let e=s;e=this.gapTimeoutUs)return{action:Dn,targetGroupId:r}}return{action:Ln}}}const Fn="idle",qn="needs_keyframe",$n="decoding",Hn="ended";class Vn{_state=Fn;_mediaType;lastConfig=null;constructor(e){this._mediaType=e}get state(){return this._state}get mediaType(){return this._mediaType}configure(e){return null!==this.lastConfig&&this.configEquals(this.lastConfig,e)?{action:"skip",reason:"config unchanged"}:(this.lastConfig=e,"audio"===this._mediaType?this._state=$n:this._state=qn,{action:"configure",config:e})}configEquals(e,t){if(e.length!==t.length)return!1;for(let s=0;s1e3*Date.now()};class jn{_driftThresholdUs;dropThresholdUs;clock;localBaselineUs;captureBaselineUs;_currentDriftUs=0;_videoJoinOffsetUs=0;wallClock;targetLatencyMs;maxCatchUpRate;catchUpThresholdMs;catchUpRecoveryMs;_catchUpActive=!1;_currentRate=1;_lastLatencyUs=0;constructor(e){this._driftThresholdUs=e.driftThresholdUs,this.dropThresholdUs=e.dropThresholdUs??5e5,this.clock=e.clock,this.wallClock=e.wallClock??Gn,this.targetLatencyMs=e.targetLatencyMs,this.maxCatchUpRate=e.maxCatchUpRate??1,this.catchUpThresholdMs=e.catchUpThresholdMs??500,this.catchUpRecoveryMs=e.catchUpRecoveryMs??50}get hasReference(){return void 0!==this.localBaselineUs}get currentDriftUs(){return this._currentDriftUs}get driftThresholdUs(){return this._driftThresholdUs}set driftThresholdUs(e){this._driftThresholdUs=e}get needsResync(){return!(this._videoJoinOffsetUs>0)&&Math.abs(this._currentDriftUs)>=this._driftThresholdUs}get catchUpActive(){return this._catchUpActive}get currentRate(){return this._currentRate}get latencyUs(){return this._lastLatencyUs}setAudioReference(e){this.localBaselineUs=this.clock.now(),this.captureBaselineUs=e,this._currentDriftUs=0}setVideoReference(e){this.hasReference||(this.localBaselineUs=this.clock.now(),this.captureBaselineUs=e,this._currentDriftUs=0)}get videoJoinOffsetUs(){return this._videoJoinOffsetUs}onVideoJoin(e,t=16e3){if(void 0===this.localBaselineUs||void 0===this.captureBaselineUs)return;const s=this.localBaselineUs+Number(e-this.captureBaselineUs),i=this.clock.now()+t-s;i>0&&(this._videoJoinOffsetUs=i)}computeVideoRenderTime(e){const t=this.computeRenderTime(e);if(null===t)return null;if(this._videoJoinOffsetUs>0){const e=t.renderTimeUs+this._videoJoinOffsetUs,s=this.clock.now();if(t.renderTimeUs>s)return this._videoJoinOffsetUs=0,t;const i=e-s;return{renderTimeUs:e,offsetUs:i,shouldDrop:i<-this.dropThresholdUs}}return t}computeAudioRenderTime(e){return this.computeRenderTime(e)}reportActualRenderTime(e,t){if(void 0===this.localBaselineUs||void 0===this.captureBaselineUs)return;const s=this.localBaselineUs+Number(e-this.captureBaselineUs);this._currentDriftUs=t-s}measureLatency(e){return 0n===e?null:this.wallClock.now()-Number(e)}evaluateCatchUp(e){const t=this.measureLatency(e);if(null===t)return null;if(this._lastLatencyUs=t,void 0===this.targetLatencyMs||this.maxCatchUpRate<=1)return null;const s=t/1e3,i=this.targetLatencyMs;if(!this._catchUpActive&&s>i+this.catchUpThresholdMs)this._catchUpActive=!0;else if(this._catchUpActive&&s<=i+this.catchUpRecoveryMs)return this._catchUpActive=!1,this._currentRate=1,{active:!1,currentRate:1,latencyMs:s,targetMs:i};if(this._catchUpActive){const e=s-i,t=Math.min(Math.max(e/this.catchUpThresholdMs,0),1),r=1+(this.maxCatchUpRate-1)*t,n=Math.round(20*r)/20;this._currentRate=Math.min(Math.max(n,1),this.maxCatchUpRate)}return{active:this._catchUpActive,currentRate:this._currentRate,latencyMs:s,targetMs:i}}reset(){this.localBaselineUs=void 0,this.captureBaselineUs=void 0,this._currentDriftUs=0,this._videoJoinOffsetUs=0,this._catchUpActive=!1,this._currentRate=1}computeRenderTime(e){if(void 0===this.localBaselineUs||void 0===this.captureBaselineUs)return null;const t=this.clock.now(),s=this.localBaselineUs+Number(e-this.captureBaselineUs),i=s-t;return{renderTimeUs:s,offsetUs:i,shouldDrop:i<-this.dropThresholdUs}}}class Kn{gapEscalationThreshold;maxDecodeErrors;windowedThreshold;windowedWindowUs;stallThresholdMs;clock;consecutiveGaps=0;qualityReductionPending=!1;decodeErrorCount=0;gapTimestamps=[];constructor(e){this.gapEscalationThreshold=e?.gapEscalationThreshold??3,this.maxDecodeErrors=e?.maxDecodeErrors??2,this.windowedThreshold=e?.windowedEscalationThreshold??5,this.windowedWindowUs=1e3*(e?.windowedEscalationWindowMs??3e4),this.stallThresholdMs=e?.stallThresholdMs??300,this.clock=null}setClock(e){this.clock=e}evaluate(e){switch(e.type){case"gap":return this.handleGap();case"stall":return this.handleStall(e.durationMs);case"buffer_overflow":return this.escalateOrSkip("jitter buffer overflow");case"too_far_behind":return this.escalateOrSkip("server reported TOO_FAR_BEHIND");case"delivery_timeout":return{type:"resubscribe"};case"decode_error":return this.handleDecodeError(e.message)}}notifySuccess(){this.consecutiveGaps=0,this.qualityReductionPending=!1}reset(){this.consecutiveGaps=0,this.qualityReductionPending=!1,this.decodeErrorCount=0,this.gapTimestamps.length=0}escalateOrSkip(e){return this.qualityReductionPending?{type:"skip_forward"}:(this.qualityReductionPending=!0,{type:"reduce_quality",reason:e})}handleGap(){if(this.consecutiveGaps++,this.consecutiveGaps>=this.gapEscalationThreshold)return this.consecutiveGaps=0,this.gapTimestamps.length=0,this.escalateOrSkip("repeated gaps detected");if(this.clock){const e=this.clock.now();this.gapTimestamps.push(e);const t=e-this.windowedWindowUs;for(;this.gapTimestamps.length>0&&this.gapTimestamps[0]=this.windowedThreshold)return this.gapTimestamps.length=0,this.consecutiveGaps=0,this.escalateOrSkip("repeated stalls within window")}return{type:"skip_forward"}}handleStall(e){if(e0&&this.gapTimestamps[0]=this.windowedThreshold)return this.gapTimestamps.length=0,this.escalateOrSkip("sustained stalls within window")}return{type:"skip_forward"}}handleDecodeError(e){return this.decodeErrorCount++,this.decodeErrorCount>=this.maxDecodeErrors?{type:"terminate",reason:`repeated decode error: ${e}`}:{type:"resubscribe"}}}const Wn="normal",Qn="monitoring",zn="extended_wait",Yn={emaAlpha:.125,varianceAlpha:.25,slidingWindowSize:128,jitterMultiplier:4,minGapTimeoutMs:50,maxGapTimeoutMs:2e3,minDriftThresholdMs:80,driftThresholdMultiplier:3,stallIncrementMs:33,maxStallIncrements:3,monitorWindowMs:500,monitorCleanFrames:60,monitorCleanDurationMs:1e3,maxExtendedWaitMs:2e3,skipFrequencyThreshold:3,skipFrequencyWindowMs:3e4,decayMinCleanFrames:120,decayMinCleanDurationMs:2e3,decayFactor:.9},Jn={shouldSkip:!1},Xn={shouldSkip:!0};class Zn{buf;deq;capacity;writePos=0;count=0;dHead=0;dTail=0;constructor(e){this.capacity=e,this.buf=new Float64Array(e),this.deq=new Uint32Array(e)}push(e){const t=this.capacity,s=this.writePos%t;for(this.count===t&&this.dHead!==this.dTail&&this.deq[this.dHead%t]===s&&this.dHead++;this.dHead!==this.dTail&&this.buf[this.deq[(this.dTail-1)%t]%t]<=e;)this.dTail--;this.deq[this.dTail%t]=s,this.dTail++,this.buf[s]=e,this.writePos++,this.count0&&(t=Math.min(t,this._deliveryTimeoutMs)),t}get effectiveDriftThresholdMs(){return this._hasCaptureRef&&0!==this._captureJitterEma?Math.max(this.cfg.minDriftThresholdMs,this._captureJitterEma*this.cfg.driftThresholdMultiplier):this.cfg.minDriftThresholdMs}onFrameArrived(e,t,s){const i=s-.001*t;if(this._hasLastTransit){const e=i-this._lastTransitMs,t=e<0?-e:e,s=t-this._jitterEma;this._jitterEma+=this.cfg.emaAlpha*s,this._jitterVar+=this.cfg.varianceAlpha*(t-this._jitterVar),this._slidingMax.push(t)}if(this._lastTransitMs=i,this._hasLastTransit=!0,this._hasCaptureRef){const e=t-this._lastCaptureUs,s=.001*Math.abs(e);0===this._captureJitterEma?this._captureJitterEma=s:this._captureJitterEma+=this.cfg.emaAlpha*(s-this._captureJitterEma)}this._lastCaptureUs=t,this._hasCaptureRef=!0,this._cleanFrameCount++,1===this._cleanFrameCount&&(this._cleanStreakStartMs=e)}onGapDetected(e,t){switch(this._cleanFrameCount=0,this._phase){case Wn:this._phase=Qn,this._phaseEnteredMs=e,this._monitorGapCount=1;break;case Qn:this._monitorGapCount++,this._monitorGapCount>=2&&e-this._phaseEnteredMs<=this.cfg.monitorWindowMs&&(this._phase=zn,this._phaseEnteredMs=e)}}tick(e){switch(this._phase){case Qn:if(e-this._phaseEnteredMs>this.cfg.monitorWindowMs&&this._cleanFrameCount>=this.cfg.monitorCleanFrames&&e-this._cleanStreakStartMs>=this.cfg.monitorCleanDurationMs)return this._phase=Wn,Jn;break;case zn:if(e-this._phaseEnteredMs>=this.cfg.maxExtendedWaitMs)return this._stallCount++,this._stallEscalationMs=Math.min(this._stallCount*this.cfg.stallIncrementMs,this.cfg.maxStallIncrements*this.cfg.stallIncrementMs),this._skipTimestamps.push(e),this._pruneSkipTimestamps(e),this._skipTimestamps.length>=this.cfg.skipFrequencyThreshold&&(this._shouldReduceQuality=!0),this._phase=Wn,this._cleanFrameCount=0,Xn;break;case Wn:this._stallEscalationMs>0&&this._cleanFrameCount>=this.cfg.decayMinCleanFrames&&this._cleanStreakStartMs>0&&e-this._cleanStreakStartMs>=this.cfg.decayMinCleanDurationMs&&(this._stallEscalationMs*=this.cfg.decayFactor,this._stallEscalationMs<1&&(this._stallEscalationMs=0,this._stallCount=0),this._cleanFrameCount=0,this._cleanStreakStartMs=e),this._shouldReduceQuality&&(this._pruneSkipTimestamps(e),this._skipTimestamps.lengthe>=t)}}function ta(e,t){switch(e.split(".")[0].toLowerCase()){case"avc1":case"avc3":return function(e){if(e.length<5)return null;let t=0,s=0;for(;t+4sa)return null;const i=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];if(t+=4,i<=0||t>=e.length)break;const r=31&e[t];if(5===r)return!0;if(7===r)return!0;if(6!==r&&8!==r&&9!==r)return!1;t+=i}return null}(t);case"hvc1":case"hev1":return function(e){if(e.length<6)return null;let t=0,s=0;for(;t+4sa)return null;const i=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];if(t+=4,i<=0||t+1>=e.length)break;const r=e[t]>>1&63;if(19===r||20===r)return!0;if(21===r)return!0;if(32!==r&&33!==r&&34!==r){if(35!==r&&39!==r&&40!==r)return!1;t+=i}else t+=i}return null}(t);case"av01":return function(e){if(e.length<2)return null;const t=e[0]>>3&15;if(1===t)return!0;if(2===t&&e.length>=3){if(1===(e[2]>>3&15))return!0}return 3!==t&&6!==t&&null}(t);default:return null}}const sa=256;const ia=4,ra=6,na=13;function aa(e){const t=Number(e),s=t>=256,i=s?t>>8&255:255&t,r={startOfFrame:!!(128&i),endOfFrame:!!(64&i),independent:!!(32&i),discardable:!!(16&i),baseLayerSync:!!(8&i),temporalId:7&i};return s&&(r.layerId=255&t),r}function oa(e){let t=0;if(e.startOfFrame&&(t|=128),e.endOfFrame&&(t|=64),e.independent&&(t|=32),e.discardable&&(t|=16),e.baseLayerSync&&(t|=8),t|=7&e.temporalId,void 0!==e.layerId){const s=255&e.layerId;return BigInt(t<<8|s)}return BigInt(t)}function ca(e){const t=255&Number(e);return{voiceActivity:!!(128&t),level:127&t}}function da(e){let t=127&e.level;return e.voiceActivity&&(t|=128),BigInt(t)}const ha=BigInt(2),ua=BigInt(ia),la=BigInt(ra),pa=BigInt(na);function ma(e){return e?.wireProfile?e.wireProfile:!1===e?.deltaEncoded?"d14-absolute-varint":"d16-delta-varint"}function ga(e){switch(e){case 14:return"d14-absolute-varint";case 18:return"d18-delta-vi64";default:return"d16-delta-varint"}}function fa(e,t){if(!e||0===e.length)return{};const{entries:s}=At(e,0,{profile:ma(t)});return function(e){let t,s,i,r,n;for(const{id:a,value:o}of e)if("bigint"==typeof o)switch(a){case ha:t=o;break;case ua:s=aa(o);break;case la:i=ca(o);break;default:(n??=new Map).set(a,o)}else a===pa?r=o:(n??=new Map).set(a,o);const a={};return void 0!==t&&(a.captureTimestamp=t),void 0!==s&&(a.videoFrameMarking=s),void 0!==i&&(a.audioLevel=i),void 0!==r&&(a.videoConfig=r),void 0!==n&&(a.unknown=n),a}(s)}function ba(e,t){const s=function(e){const t=[];if(void 0!==e.captureTimestamp&&t.push({id:ha,value:e.captureTimestamp}),void 0!==e.videoFrameMarking&&t.push({id:ua,value:oa(e.videoFrameMarking)}),void 0!==e.audioLevel&&t.push({id:la,value:da(e.audioLevel)}),void 0!==e.videoConfig&&t.push({id:pa,value:e.videoConfig}),e.unknown)for(const[s,i]of e.unknown)t.push({id:s,value:i});return t}(e);if(0!==s.length)return Nt(s,ma(t))}class Sa{mediaType;clock;sync;onCommand;onEvent;recovery;buffer;gapDetector;decoderState;headerMap=new Map;bufferedGroupCounts=new Map;nextExpectedObjectId=0n;lastConsumedGroupId=-1n;endedGroups=new Set;activeGroupWaitStartUs=null;minAcceptGroupId=-1n;lastKeyframeWaitingGroupId=-1n;resetPending=!0;_trackEnded=!1;_lastEmittedRate=1;_throttled=!1;adaptiveTolerance;maxReleasePerTick;maxBacklogGroups;_videoCodec;_videoOnly;constructor(e){this.mediaType=e.mediaType,this.clock=e.clock,this.sync=e.sync,this.onCommand=e.onCommand,this.onEvent=e.onEvent,this.recovery=e.recovery,this._videoOnly=e.videoOnly??!1;const t="video"===e.mediaType&&(e.isLive??!0);this.maxReleasePerTick=t?e.config.maxReleasePerTick??5:0,this.maxBacklogGroups=t?e.config.maxBacklogGroups??3:0,this.buffer=new Mn(e.config.maxBufferDepth),this.gapDetector=new xn({gapTimeoutUs:e.config.gapTimeoutUs,clock:e.clock}),this.decoderState=new Vn(e.mediaType),this.adaptiveTolerance=e.config.adaptiveTolerance?new ea(Yn):null}setCodec(e){this._videoCodec=e}get effectiveGapTimeoutUs(){return this.adaptiveTolerance?1e3*this.adaptiveTolerance.effectiveGapTimeoutMs:this.gapDetector.gapTimeoutUs}get currentGroupId(){return this.lastConsumedGroupId}get bufferedGroupCount(){return this.bufferedGroupCounts.size}get throttled(){return this._throttled}handleFeedback(e){switch(e.type){case"queue_pressure":this._throttled=e.depth>=e.maxRecommended;break;case"decode_error":this._throttled=!1;{const e=this.decoderState.notifyGap();this.emitFsmDecision(e)}if(this.recovery){const t=this.recovery.evaluate({type:"decode_error",message:e.message});this.onEvent({type:"recovery",action:t})}break;case"frame_rendered":if(e.captureTimestampUs>0n){this.sync.reportActualRenderTime(e.captureTimestampUs,e.actualRenderUs);const t=this.sync.currentDriftUs;this.sync.needsResync&&Math.abs(t)<5e6&&this.onEvent({type:"sync_drift",driftUs:t})}}}configure(e){"configure"===this.decoderState.configure(e).action&&this.onCommand({type:"configure",mediaType:this.mediaType,config:e})}pushObject(e,t){if("gap"===e.kind)return void(e.status===ki.END_OF_GROUP?(this.gapDetector.observeEndOfGroup(e.groupId),this.endedGroups.add(e.groupId)):e.status===ki.END_OF_TRACK&&this.gapDetector.observeEndOfTrack());if(e.groupId=0n&&e.groupId0){const e=this.buffer.peek();if(0n!==e.objectId)return this.buffer.extract(),void this.decrementGroupCount(e.groupId);this.lastConsumedGroupId=e.groupId-1n,this.endedGroups.add(this.lastConsumedGroupId),this.resetPending=!1}const e=[...this.bufferedGroupCounts.keys()],t=this.gapDetector.evaluate(this.lastConsumedGroupId,e);if(t.action===Bn){if(!this._trackEnded){this._trackEnded=!0;const e=this.decoderState.notifyTrackEnded();this.emitFsmDecision(e),this.onEvent({type:"track_ended"})}return}if(t.action===Dn&&void 0!==t.targetGroupId){const e=t.targetGroupId;"video"===this.mediaType&&this.lastConsumedGroupId>=0n&&!this.endedGroups.has(this.lastConsumedGroupId)&&this.onEvent({type:"partial_group_abandoned",fromGroupId:this.lastConsumedGroupId,toGroupId:e,reason:"gap timeout"});for(const t of this.endedGroups)t0&&this.bufferedGroupCounts.size>this.maxBacklogGroups&&this.shedBacklog(),this._throttled)return;if("video"===this.mediaType&&null!==this.activeGroupWaitStartUs){if(this.clock.now()-this.activeGroupWaitStartUs>this.gapDetector.gapTimeoutUs){const e=this.lastConsumedGroupId+1n;this.onEvent({type:"partial_group_abandoned",fromGroupId:this.lastConsumedGroupId,toGroupId:e,reason:"intra-group timeout"}),this.endedGroups.add(this.lastConsumedGroupId);const t=this.decoderState.notifyGap();this.emitFsmDecision(t),this.activeGroupWaitStartUs=null}}let s=0;const i=this.maxReleasePerTick;for(;this.buffer.size>0&&!(i>0&&s>=i)&&!this._throttled;){const e=this.buffer.peek();if(!e)break;const t=this.lastConsumedGroupId+1n;if(e.groupId>t)break;if(e.groupId>this.lastConsumedGroupId&&this.lastConsumedGroupId>=0n){if("video"===this.mediaType&&!this.endedGroups.has(this.lastConsumedGroupId)){null===this.activeGroupWaitStartUs&&(this.activeGroupWaitStartUs=this.clock.now());break}this.activeGroupWaitStartUs=null,this.endedGroups.delete(this.lastConsumedGroupId)}if(e.groupId>this.lastConsumedGroupId&&(this.nextExpectedObjectId=0n),"video"===this.mediaType&&e.objectId>this.nextExpectedObjectId){const t=e.groupId;for(;this.buffer.size>0;){const e=this.buffer.peek();if(!e||e.groupId!==t)break;this.buffer.extract(),this.decrementGroupCount(t)}this.lastConsumedGroupId=t,this.nextExpectedObjectId=0n;const s=this.decoderState.notifyGap();this.emitFsmDecision(s);break}const i=this.buffer.extract();this.decrementGroupCount(i.groupId),"data"===i.kind&&this.processDataObject(i),this.nextExpectedObjectId=i.objectId+1n,s++,i.groupId>this.lastConsumedGroupId&&(this.lastConsumedGroupId=i.groupId)}}shedBacklog(){const e=[...this.bufferedGroupCounts.keys()].sort((e,t)=>et?1:0),t=e.length-this.maxBacklogGroups;if(t<=0)return;const s=e.slice(0,t),i=s[s.length-1]+1n;this.buffer.discardBefore(i);for(const e of s)this.bufferedGroupCounts.delete(e);for(const e of this.headerMap.keys()){BigInt(e.split(":")[0])=this.lastConsumedGroupId&&(this.lastConsumedGroupId=r),this.minAcceptGroupId=r+1n;const n=this.decoderState.notifyGap();this.emitFsmDecision(n),this.onEvent({type:"backlog_shed",droppedGroups:t,remainingGroups:this.bufferedGroupCounts.size,reason:`backlog exceeded ${this.maxBacklogGroups} groups`})}tryEvictAndInsert(e,t){const s=this.buffer.evictLowestImportance();if(!s)return!1;if(s.publisherPriority>e.publisherPriority){this.decrementGroupCount(s.groupId);const i=`${s.groupId}:${s.objectId}`;this.headerMap.delete(i),this.buffer.insert(e);const r=`${e.groupId}:${e.objectId}`;this.headerMap.set(r,t??{});const n=this.bufferedGroupCounts.get(e.groupId)??0;return this.bufferedGroupCounts.set(e.groupId,n+1),!0}return this.buffer.insert(s),!1}processDataObject(e){const t=`${e.groupId}:${e.objectId}`,s=this.headerMap.get(t)??{};if(this.headerMap.delete(t),s.videoConfig){"configure"===this.decoderState.configure(s.videoConfig).action&&this.onCommand({type:"configure",mediaType:this.mediaType,config:s.videoConfig})}let i;if(void 0===s.captureTimestamp||this.sync.hasReference||("audio"===this.mediaType?this.sync.setAudioReference(s.captureTimestamp):this._videoOnly&&this.sync.setVideoReference(s.captureTimestamp)),void 0!==s.captureTimestamp){const e="video"===this.mediaType?this.sync.computeVideoRenderTime(s.captureTimestamp):this.sync.computeAudioRenderTime(s.captureTimestamp);if(null===e)i=0;else if(e.shouldDrop){if(!(e.offsetUs<-5e6))return;i=this.clock.now()}else i=e.offsetUs>5e6?this.clock.now():e.renderTimeUs}else i=this.clock.now();if(void 0!==s.captureTimestamp){const e=this.sync.evaluateCatchUp(s.captureTimestamp);null!==e&&e.currentRate!==this._lastEmittedRate&&(this._lastEmittedRate=e.currentRate,this.onEvent({type:"catch_up_changed",state:e}),this.onCommand({type:"set_playback_rate",rate:e.currentRate}))}if("video"===this.mediaType){const t=s.videoFrameMarking??(0n===e.objectId?{independent:!0,startOfFrame:!0,endOfFrame:!0,discardable:!1,baseLayerSync:!1,temporalId:0}:void 0);if(t?.independent&&this._videoCodec&&e.payload.length>5){!1===ta(this._videoCodec,e.payload)&&this.onEvent({type:"keyframe_validation_failed",groupId:e.groupId,objectId:e.objectId,codec:this._videoCodec})}const r=void 0!==t?{...s,videoFrameMarking:t}:s,n=function(e,t){return{type:!0===t.videoFrameMarking?.independent?"key":"delta",timestamp:void 0!==t.captureTimestamp?Number(t.captureTimestamp):0,data:e}}(e.payload,r),a=this.decoderState.state,o=this.decoderState.processVideoChunk(n,t);if("needs_keyframe"===a&&"decoding"===this.decoderState.state&&void 0!==s.captureTimestamp){this.sync.onVideoJoin(s.captureTimestamp);const e=this.sync.computeVideoRenderTime(s.captureTimestamp);e&&(i=e.renderTimeUs)}"decode"===o.action?this.onCommand({type:"decode_video",chunk:o.chunk,renderTimeUs:i,...void 0!==s.captureTimestamp?{captureTimestampUs:s.captureTimestamp}:{}}):"skip"===o.action&&"waiting for keyframe"===o.reason&&e.groupId!==this.lastKeyframeWaitingGroupId&&(this.lastKeyframeWaitingGroupId=e.groupId,this.onEvent({type:"keyframe_waiting",groupId:e.groupId}))}else{const t=function(e,t){return{type:"key",timestamp:void 0!==t.captureTimestamp?Number(t.captureTimestamp):0,data:e}}(e.payload,s),r=this.decoderState.processAudioChunk(t);"decode"===r.action&&this.onCommand({type:"decode_audio",chunk:r.chunk,renderTimeUs:i})}}emitFsmDecision(e){"reset"===e.action?this.onCommand({type:"reset",mediaType:this.mediaType,reason:e.reason??"gap"}):"flush"===e.action&&this.onCommand({type:"flush",mediaType:this.mediaType})}discardBefore(e){this.buffer.discardBefore(e);for(const[t]of this.bufferedGroupCounts)t0){this.sampleCount++;const t=8*e/(s/1e6);null===this.estimateBps?this.estimateBps=t:this.estimateBps=this.alpha*t+(1-this.alpha)*this.estimateBps}}this.lastTimestampUs=t,this.lastGroupBytes=e}getEstimateKbps(){return null===this.estimateBps||this.sampleCount0&&e.bufferDepthUs>=this.highThresholdUs){const t=this.ladder[this.currentIndex-1];if(e.bandwidthEstimateKbps>t.bitrateKbps*this.upshiftMultiple)return{action:"upshift",targetIndex:this.currentIndex-1}}return{action:"hold"}}commitDownshift(){this.currentIndex0&&this.currentIndex--}setIndex(e){this.currentIndex=Math.max(0,Math.min(e,this.ladder.length-1))}}const ya="catalog";function Ea(e){Ta(e,"Catalog",0)}function Ta(e,t,s){if(!(s>8||null===e))if("number"!=typeof e){if(Array.isArray(e))e.forEach((e,i)=>Ta(e,`${t}[${i}]`,s+1));else if("object"==typeof e)for(const[i,r]of Object.entries(e))Ta(r,`${t}.${i}`,s+1)}else if(!Number.isFinite(e))throw new Error(`${t} must be a finite number, got ${String(e)}`)}const wa=new Set(["loc","mediatimeline","eventtimeline","cmaf"]);function Ra(e,t){const s="string"==typeof e?e:(new TextDecoder).decode(e),i=JSON.parse(s);if("object"!=typeof i||null===i||Array.isArray(i))throw new Error("Catalog must be a JSON object");const r=i;if(!("version"in r))throw new Error("Catalog version is required (§5.1.1)");const n=function(e){return"number"==typeof e?1===e?1:null:"string"!=typeof e||"1"!==e&&"draft-01"!==e?null:1}(r.version);if(null===n)throw new Error(`Unsupported catalog version ${JSON.stringify(r.version)}; expected 1, "1", or "draft-01" (§5.1.1)`);if(!("tracks"in r)||!Array.isArray(r.tracks))throw new Error("Catalog tracks field is required and must be an array (§5.1.8)");const a="number"==typeof r.version,o=r.tracks.map((e,s)=>Aa(e,s,t,a));if(function(e){const t=new Set;for(const s of e){const e=`${s.namespace??""}\0${s.name}`;if(t.has(e))throw new Error(`Duplicate track name "${s.name}" in namespace "${s.namespace??"(inherited)"}" (§5.1.11)`);t.add(e)}} /*! * https://github.com/Starcounter-Jack/JSON-Patch * (c) 2017-2022 Joachim Wester * MIT licensed - */(r),function(e){Ps(e,"renderGroup"),Ps(e,"altGroup")}(r),"isComplete"in n&&!0!==n.isComplete)throw new Error("isComplete MUST NOT be included if false (§5.1.7)");return{version:1,tracks:r,..."number"==typeof n.generatedAt?{generatedAt:n.generatedAt}:{},...!0===n.isComplete?{isComplete:!0}:{}}}function Ps(e,t){const i=new Map;for(const s of e){const e=s[t];if(void 0!==e)if(i.has(e)){if(i.get(e)!==s.targetLatency)throw new Error(`Tracks in ${t} ${e} have inconsistent targetLatency values (§5.1.16)`)}else i.set(e,s.targetLatency)}}const Ls=/^[A-Za-z0-9+/]*={0,2}$/;const Us=/^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{1,8})*$/;var Ds,Ms=(Ds=function(e,t){return Ds=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},Ds(e,t)},function(e,t){function i(){this.constructor=e}Ds(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),Bs=Object.prototype.hasOwnProperty;function xs(e,t){return Bs.call(e,t)}function Hs(e){if(Array.isArray(e)){for(var t=new Array(e.length),i=0;i=48&&t<=57))return!1;i++}return!0}function Vs(e){return-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function qs(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Gs(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(var t=0,i=e.length;t0&&"constructor"==o[d-1]))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(i&&void 0===l&&(void 0===c[u]?l=o.slice(0,d).join("/"):d==h-1&&(l=t.path),void 0!==l&&p(t,0,e,l)),d++,Array.isArray(c)){if("-"===u)u=c.length;else{if(i&&!Fs(u))throw new Qs("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",r,t,e);Fs(u)&&(u=~~u)}if(d>=h){if(i&&"add"===t.op&&u>c.length)throw new Qs("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",r,t,e);if(!1===(a=Ys[t.op].call(t,c,u,e)).test)throw new Qs("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return a}}else if(d>=h){if(!1===(a=zs[t.op].call(t,c,u,e)).test)throw new Qs("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return a}if(c=c[u],i&&d0)throw new Qs('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,i);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new Qs("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,i);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new Qs("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,i);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&Gs(e.value))throw new Qs("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,i);if(i)if("add"==e.op){var n=e.path.split("/").length,r=s.split("/").length;if(n!==r+1&&n!==r)throw new Qs("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,i)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==s)throw new Qs("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,i)}else if("move"===e.op||"copy"===e.op){var a=tn([{op:"_get",path:e.from,value:void 0}],i);if(a&&"OPERATION_PATH_UNRESOLVABLE"===a.name)throw new Qs("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,i)}}function tn(e,t,i){try{if(!Array.isArray(e))throw new Qs("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Zs($s(t),$s(e),i||!0);else{i=i||en;for(var s=0;sAa(e,s,t,a)):void 0,d="initDataList"in r?function(e){if(!Array.isArray(e))throw new Error("initDataList must be an array (§5.1.7)");const t=new Set;return e.map((e,s)=>{if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`initDataList[${s}] must be a JSON object (§5.1.7)`);const i=e;if("string"!=typeof i.id||"string"!=typeof i.type||"string"!=typeof i.data)throw new Error(`initDataList[${s}] requires string id, type, and data (§5.1.7)`);if(t.has(i.id))throw new Error(`Duplicate initDataList id "${i.id}" — ids MUST be unique within the catalog (§5.1.7)`);return t.add(i.id),{id:i.id,type:i.type,data:i.data}})}(r.initDataList):void 0,h="contentProtections"in r?function(e){if(!Array.isArray(e))throw new Error("contentProtections must be an array (CMSF §4.1.1)");const t=new Set;return e.map((e,s)=>{if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`contentProtections[${s}] must be a JSON object (CMSF §4.1.1)`);const i=e;if("string"!=typeof i.refID)throw new Error(`contentProtections[${s}]: refID is required and must be a string (CMSF §4.1.1.1)`);if(t.has(i.refID))throw new Error(`Duplicate contentProtections refID "${i.refID}" — refIDs MUST be unique across the array (CMSF §4.1.1.1)`);if(t.add(i.refID),!Array.isArray(i.defaultKID))throw new Error(`contentProtections[${s}]: defaultKID is required and must be an array (CMSF §4.1.1.2)`);if("string"!=typeof i.scheme)throw new Error(`contentProtections[${s}]: scheme is required and must be a string (CMSF §4.1.1.3)`);return{refID:i.refID,defaultKID:Pa(`contentProtections[${s}]`,"defaultKID",i.defaultKID),scheme:i.scheme,drmSystem:Ca(s,i.drmSystem)}})}(r.contentProtections):void 0,u={version:n,tracks:o,..."number"==typeof r.generatedAt?{generatedAt:r.generatedAt}:{},...!0===r.isComplete?{isComplete:!0}:{},...void 0!==d?{initDataList:d}:{},...void 0!==h?{contentProtections:h}:{},...void 0!==c?{publishTracks:c}:{}};return Ia(u),Ea(u),u}function Ca(e,t){if("object"!=typeof t||null===t||Array.isArray(t))throw new Error(`contentProtections[${e}]: drmSystem is required and must be a JSON object (CMSF §4.1.1.4)`);const s=t;if("string"!=typeof s.systemID)throw new Error(`contentProtections[${e}].drmSystem: systemID is required and must be a string (CMSF §4.1.1.4.1)`);const i=t=>{const i=s[t];if(void 0===i)return;if("object"!=typeof i||null===i||Array.isArray(i)||"string"!=typeof i.url)throw new Error(`contentProtections[${e}].drmSystem.${t} must be an object with a string url (CMSF §4.1.1.4)`);const r=i;return{url:r.url,..."string"==typeof r.type?{type:r.type}:{}}};return{systemID:s.systemID,...void 0!==i("laURL")?{laURL:i("laURL")}:{},...void 0!==i("certURL")?{certURL:i("certURL")}:{},...void 0!==i("authorizationURL")?{authorizationURL:i("authorizationURL")}:{},..."string"==typeof s.pssh?{pssh:s.pssh}:{},..."string"==typeof s.robustness?{robustness:s.robustness}:{}}}function Ia(e){const t=new Set((e.initDataList??[]).map(e=>e.id)),s=new Set((e.contentProtections??[]).map(e=>e.refID)),i=e=>{for(const i of e){if(void 0!==i.initRef&&!t.has(i.initRef))throw new Error(`Track "${i.name}": initRef "${i.initRef}" references unknown initDataList id (dangling init reference) (§5.2.13)`);for(const e of i.contentProtectionRefIDs??[])if(!s.has(e))throw new Error(`Track "${i.name}": contentProtectionRefIDs "${e}" references unknown contentProtections refID (dangling content protection reference) (CMSF §4.1.2)`)}};i(e.tracks),i(e.publishTracks??[])}function Aa(e,t,s,i){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`Track at index ${t} must be a JSON object`);const r=e;if("string"!=typeof r.name)throw new Error(`Track at index ${t}: name is required and must be a string (§5.1.11)`);const n=r.name;if("string"!=typeof r.packaging||!wa.has(r.packaging))throw new Error(`Track "${n}" at index ${t}: packaging is required and must be one of ${[...wa].join(", ")} (§5.1.12)`);const a=r.packaging;if("boolean"!=typeof r.isLive)throw new Error(`Track "${n}" at index ${t}: isLive is required and must be a boolean (§5.1.15)`);const o=r.isLive;if(!o&&void 0!==r.targetLatency)throw new Error(`Track "${n}": targetLatency MUST NOT be included when isLive is false (§5.1.16)`);if(o&&void 0!==r.trackDuration)throw new Error(`Track "${n}": trackDuration MUST NOT be included when isLive is true (§5.1.37)`);if("eventtimeline"===a&&"string"!=typeof r.eventType)throw new Error(`Track "${n}": eventType is required when packaging is "eventtimeline" (§5.1.13)`);if("eventtimeline"!==a&&void 0!==r.eventType)throw new Error(`Track "${n}": eventType MUST NOT be used when packaging is not "eventtimeline" (§5.1.13)`);if("mediatimeline"===a||"eventtimeline"===a){const e="mediatimeline"===a?"§7.2":"§8.2";if(!Array.isArray(r.depends)||0===r.depends.length)throw new Error(`Track "${n}": depends is required for packaging "${a}" (${e})`);if(i&&"application/json"!==r.mimeType)throw new Error(`Track "${n}": mimeType MUST be "application/json" for packaging "${a}" (${e})`)}if("string"==typeof r.initData&&""!==r.initData&&((c=r.initData).length%4!=0||!Ua.test(c)))throw new Error(`Track "${n}" at index ${t}: initData is not valid Base64 (§5.1.20)`);var c,d;if("string"==typeof r.lang&&(d=r.lang,!Ma.test(d)))throw new Error(`Track "${n}" at index ${t}: lang "${r.lang}" is not a valid BCP 47 language tag (§5.1.35)`);if("parentName"in r)throw new Error(`Track "${n}" at index ${t}: parentName MUST only appear in clone context (§5.1.36)`);const h="string"==typeof r.namespace?r.namespace:s;return{name:n,packaging:a,isLive:o,...void 0!==h?{namespace:h}:{},...ka(r,n)}}function ka(e,t){return{..."string"==typeof e.role?{role:e.role}:{},..."number"==typeof e.renderGroup?{renderGroup:e.renderGroup}:{},..."number"==typeof e.altGroup?{altGroup:e.altGroup}:{},..."string"==typeof e.codec?{codec:e.codec}:{},..."string"==typeof e.mimeType?{mimeType:e.mimeType}:{},..."number"==typeof e.framerate?{framerate:e.framerate}:{},..."number"==typeof e.timescale?{timescale:e.timescale}:{},..."number"==typeof e.bitrate?{bitrate:e.bitrate}:{},..."number"==typeof e.width?{width:e.width}:{},..."number"==typeof e.height?{height:e.height}:{},..."number"==typeof e.samplerate?{samplerate:e.samplerate}:{},..."string"==typeof e.channelConfig?{channelConfig:e.channelConfig}:{},..."number"==typeof e.displayWidth?{displayWidth:e.displayWidth}:{},..."number"==typeof e.displayHeight?{displayHeight:e.displayHeight}:{},..."string"==typeof e.lang?{lang:e.lang}:{},..."string"==typeof e.label?{label:e.label}:{},..."string"==typeof e.initData?{initData:e.initData}:{},..."string"==typeof e.initTrack?{initTrack:e.initTrack}:{},...Array.isArray(e.depends)?{depends:e.depends}:{},..."number"==typeof e.temporalId?{temporalId:e.temporalId}:{},..."number"==typeof e.spatialId?{spatialId:e.spatialId}:{},..."number"==typeof e.targetLatency?{targetLatency:e.targetLatency}:{},..."number"==typeof e.trackDuration?{trackDuration:e.trackDuration}:{},..."string"==typeof e.eventType?{eventType:e.eventType}:{},..."number"==typeof e.maxGrpSapStartingType?{maxGrpSapStartingType:e.maxGrpSapStartingType}:{},..."number"==typeof e.maxObjSapStartingType?{maxObjSapStartingType:e.maxObjSapStartingType}:{},..."string"==typeof e.initRef?{initRef:e.initRef}:{},...void 0!==e.template?{template:Oa(t,e.template)}:{},...Array.isArray(e.contentProtectionRefIDs)?{contentProtectionRefIDs:Pa(t,"contentProtectionRefIDs",e.contentProtectionRefIDs)}:{}}}function Oa(e,t){const s=()=>{throw new Error(`Track "${e}": template must be a 6-item array [startMedia, deltaMedia, [startGroup,startObject], [deltaGroup,deltaObject], startWallclock, deltaWallclock] (§5.2.15)`)};Array.isArray(t)&&6===t.length||s();const i=t,r=e=>"number"==typeof e&&Number.isInteger(e)&&e>=0?e:s(),n=e=>(Array.isArray(e)&&2===e.length||s(),[r(e[0]),r(e[1])]);return[r(i[0]),r(i[1]),n(i[2]),n(i[3]),r(i[4]),r(i[5])]}function Pa(e,t,s){return s.map((s,i)=>{if("string"!=typeof s)throw new Error(`Track "${e}": ${t}[${i}] must be a string`);return s})}function Na(e,t){const s=new Map;for(const i of e){const e=i[t];if(void 0!==e)if(s.has(e)){if(s.get(e)!==i.targetLatency)throw new Error(`Tracks in ${t} ${e} have inconsistent targetLatency values (§5.1.16)`)}else s.set(e,i.targetLatency)}}const Ua=/^[A-Za-z0-9+/]*={0,2}$/;const Ma=/^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{1,8})*$/;var La,Da=(La=function(e,t){return La=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)t.hasOwnProperty(s)&&(e[s]=t[s])},La(e,t)},function(e,t){function s(){this.constructor=e}La(e,t),e.prototype=null===t?Object.create(t):(s.prototype=t.prototype,new s)}),Ba=Object.prototype.hasOwnProperty;function xa(e,t){return Ba.call(e,t)}function Fa(e){if(Array.isArray(e)){for(var t=new Array(e.length),s=0;s=48&&t<=57))return!1;s++}return!0}function Ha(e){return-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Va(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Ga(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(var t=0,s=e.length;t0&&"constructor"==o[d-1]))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(s&&void 0===u&&(void 0===c[l]?u=o.slice(0,d).join("/"):d==h-1&&(u=t.path),void 0!==u&&p(t,0,e,u)),d++,Array.isArray(c)){if("-"===l)l=c.length;else{if(s&&!$a(l))throw new Wa("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",n,t,e);$a(l)&&(l=~~l)}if(d>=h){if(s&&"add"===t.op&&l>c.length)throw new Wa("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",n,t,e);if(!1===(a=Ya[t.op].call(t,c,l,e)).test)throw new Wa("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a}}else if(d>=h){if(!1===(a=za[t.op].call(t,c,l,e)).test)throw new Wa("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a}if(c=c[l],s&&d0)throw new Wa('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,s);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new Wa("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,s);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new Wa("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,s);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&Ga(e.value))throw new Wa("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,s);if(s)if("add"==e.op){var r=e.path.split("/").length,n=i.split("/").length;if(r!==n+1&&r!==n)throw new Wa("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,s)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==i)throw new Wa("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,s)}else if("move"===e.op||"copy"===e.op){var a=to([{op:"_get",path:e.from,value:void 0}],s);if(a&&"OPERATION_PATH_UNRESOLVABLE"===a.name)throw new Wa("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,s)}}function to(e,t,s){try{if(!Array.isArray(e))throw new Wa("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Za(qa(t),qa(e),s||!0);else{s=s||eo;for(var i=0;i0&&(e.patches=[],e.callback&&e.callback(s)),s}function dn(e,t,i,s,n){if(t!==e){"function"==typeof t.toJSON&&(t=t.toJSON());for(var r=Hs(t),a=Hs(e),o=!1,c=a.length-1;c>=0;c--){var d=e[l=a[c]];if(!xs(t,l)||void 0===t[l]&&void 0!==d&&!1===Array.isArray(t))Array.isArray(e)===Array.isArray(t)?(n&&i.push({op:"test",path:s+"/"+Vs(l),value:$s(d)}),i.push({op:"remove",path:s+"/"+Vs(l)}),o=!0):(n&&i.push({op:"test",path:s,value:e}),i.push({op:"replace",path:s,value:t}));else{var h=t[l];"object"==typeof d&&null!=d&&"object"==typeof h&&null!=h&&Array.isArray(d)===Array.isArray(h)?dn(d,h,i,s+"/"+Vs(l),n):d!==h&&(n&&i.push({op:"test",path:s+"/"+Vs(l),value:$s(d)}),i.push({op:"replace",path:s+"/"+Vs(l),value:$s(h)}))}}if(o||r.length!=a.length)for(c=0;cfunction(e,t,i,s,n,r){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`Track at index ${t} must be a JSON object`);const a=e,o={...s,...i,...a},c=i.selectionParams,d=a.selectionParams;let h;if(c||d){if(h={..."object"!=typeof c||null===c||Array.isArray(c)?{}:c,..."object"!=typeof d||null===d||Array.isArray(d)?{}:d},0===Object.keys(h).length)throw new Error(`Track at index ${t}: selectionParams MUST NOT be empty (§3.2.17)`)}if("string"!=typeof o.name)throw new Error(`Track at index ${t}: name is required (§3.2.10)`);const l=o.name,u="string"==typeof o.namespace?o.namespace:n;let p;if("string"==typeof o.packaging&&mn.has(o.packaging))p=o.packaging;else{if("string"==typeof o.packaging)throw new Error(`Track "${l}" at index ${t}: unknown packaging "${o.packaging}" (§3.2.11)`);if(r?.strict)throw new Error(`Track "${l}" at index ${t}: packaging is required (§3.2.11)`);p="cmaf"}const m="boolean"!=typeof o.isLive||o.isLive;let g;g="string"==typeof o.role?o.role:function(e){if(!e)return;const t=e.mimeType;if("string"==typeof t){if(t.startsWith("video/"))return"video";if(t.startsWith("audio/"))return"audio"}const i=e.codec;if("string"==typeof i){const e=i.split(".")[0];if(gn.includes(e))return"video";if(fn.includes(e))return"audio"}return}(h);return{name:l,packaging:p,isLive:m,...void 0!==u?{namespace:u}:{},...void 0!==g?{role:g}:{},..."number"==typeof o.renderGroup?{renderGroup:o.renderGroup}:{},..."number"==typeof o.altGroup?{altGroup:o.altGroup}:{},..."string"==typeof o.label?{label:o.label}:{},..."string"==typeof o.initData?{initData:o.initData}:{},..."string"==typeof o.initTrack?{initTrack:o.initTrack}:{},...Array.isArray(o.depends)?{depends:o.depends}:{},..."number"==typeof o.temporalId?{temporalId:o.temporalId}:{},..."number"==typeof o.spatialId?{spatialId:o.spatialId}:{},..."number"==typeof o.targetLatency?{targetLatency:o.targetLatency}:{},..."number"==typeof o.trackDuration?{trackDuration:o.trackDuration}:{},...h?Sn(h):{}}}(e,s,r,a,t,i));return function(e){const t=new Set;for(const i of e){const e=`${i.namespace??""}\0${i.name}`;if(t.has(e))throw new Error(`Duplicate track name "${i.name}" in namespace "${i.namespace??"(inherited)"}" (§3.2.10)`);t.add(e)}}(o),function(e){const t=new Set(e.map(e=>e.name));for(const i of e)if(i.initTrack&&t.has(i.initTrack))throw new Error(`initTrack "${i.initTrack}" on track "${i.name}" must not appear in the tracks array (§3.2.16)`)}(o),{catalog:{version:1,tracks:o},supportsDeltaUpdates:n,rawDocument:e}}function Sn(e){const t={};return"string"==typeof e.codec&&(t.codec=e.codec),"string"==typeof e.mimeType&&(t.mimeType=e.mimeType),"number"==typeof e.framerate&&(t.framerate=e.framerate),"number"==typeof e.bitrate&&(t.bitrate=e.bitrate),"number"==typeof e.width&&(t.width=e.width),"number"==typeof e.height&&(t.height=e.height),"number"==typeof e.samplerate&&(t.samplerate=e.samplerate),"string"==typeof e.channelConfig&&(t.channelConfig=e.channelConfig),"number"==typeof e.displayWidth&&(t.displayWidth=e.displayWidth),"number"==typeof e.displayHeight&&(t.displayHeight=e.displayHeight),"string"==typeof e.lang&&(t.lang=e.lang),t}const En=/^\/tracks\/\d+\/(name|namespace)(\/|$)/,yn=/^\/tracks\/(\d+)$/,Tn=/^\/(commonTrackFields\/)?(name|namespace)$/,Cn=/^\/commonTrackFields$/;const wn=["codec","mimeType","framerate","bitrate","width","height","samplerate","channelConfig","displayWidth","displayHeight","lang"];function Rn(e){const t=new Map;for(const i of e){const e=i.namespace??"",s=`${e}\0${i.name}`,n={};for(const e of wn)void 0!==i[e]&&(n[e]=i[e]);t.set(s,{name:i.name,namespace:e,selectionJson:JSON.stringify(n,Object.keys(n).sort())})}return t}const In=new Set(["name","namespace"]);function An(e){const t="string"==typeof e?e:(new TextDecoder).decode(e),i=JSON.parse(t);if("object"!=typeof i||null===i||Array.isArray(i))throw new Error("Delta update must be a JSON object");const s=i;if(!0!==s.deltaUpdate)throw new Error("Delta update must have deltaUpdate set to true (§5.2)");if("version"in s)throw new Error("Delta update MUST NOT contain a version field (§5.2)");if("tracks"in s)throw new Error("Delta update MUST NOT contain a tracks field (§5.2)");const n=Array.isArray(s.addTracks),r=Array.isArray(s.removeTracks),a=Array.isArray(s.cloneTracks);if(!n&&!r&&!a)throw new Error("Delta update must contain at least one of addTracks, removeTracks, or cloneTracks (§5.2)");let o,c,d;r&&(o=s.removeTracks.map((e,t)=>function(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`removeTracks[${t}] must be a JSON object`);const i=e;if("string"!=typeof i.name)throw new Error(`removeTracks[${t}]: name is required (§5.1.4)`);for(const e of Object.keys(i))if(!In.has(e))throw new Error(`removeTracks[${t}]: field "${e}" is not allowed; only name and namespace are permitted (§5.1.4)`);return{name:i.name,..."string"==typeof i.namespace?{namespace:i.namespace}:{}}}(e,t))),a&&(c=s.cloneTracks.map((e,t)=>function(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`cloneTracks[${t}] must be a JSON object`);const i=e;if("string"!=typeof i.parentName)throw new Error(`cloneTracks[${t}]: parentName is required (§5.1.5)`);if("string"!=typeof i.name)throw new Error(`cloneTracks[${t}]: name is required`);return Pn(e,`cloneTracks[${t}]`,!0)}(e,t))),n&&(d=s.addTracks.map((e,t)=>Pn(e,`addTracks[${t}]`)));return{deltaUpdate:!0,..."number"==typeof s.generatedAt?{generatedAt:s.generatedAt}:{},...d?{addTracks:d}:{},...o?{removeTracks:o}:{},...c?{cloneTracks:c}:{}}}function kn(e,t,i){let s=[...e.tracks];if(t.addTracks)for(const e of t.addTracks){const t=Nn(e,i),n=On(t);if(s.some(e=>On(e)===n))throw new Error(`Cannot add track "${t.name}" in namespace "${t.namespace??""}": track already exists (§5.1.11, §5.2)`);s.push(t)}if(t.removeTracks)for(const e of t.removeTracks){const t=e.namespace??i??"",n=`${t}\0${e.name}`;if(!s.some(e=>On(e)===n))throw new Error(`Cannot remove track "${e.name}" in namespace "${t}": track not found in current catalog state (§5.2)`);s=s.filter(e=>On(e)!==n)}if(t.cloneTracks)for(const e of t.cloneTracks){const t=e.parentName,n=s.find(e=>e.name===t);if(!n)throw new Error(`Cannot clone track "${e.name}": parent track "${t}" not found (§5.1.5)`);const r=Ln(n,e,i),a=On(r);if(s.some(e=>On(e)===a))throw new Error(`Cannot clone track "${r.name}" in namespace "${r.namespace??""}": track already exists (§5.1.11, §5.2)`);s.push(r)}const n=t.generatedAt??e.generatedAt;return{version:e.version,tracks:s,...void 0!==n?{generatedAt:n}:{},...void 0!==e.isComplete?{isComplete:e.isComplete}:{}}}function On(e){return`${e.namespace??""}\0${e.name}`}function Nn(e,t){return void 0!==e.namespace||void 0===t?e:{...e,namespace:t}}function Pn(e,t,i=!1){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`${t} must be a JSON object`);const s=e;if("string"!=typeof s.name)throw new Error(`${t}: name is required`);return{name:s.name,packaging:"string"==typeof s.packaging?s.packaging:"loc",isLive:"boolean"!=typeof s.isLive||s.isLive,..."string"==typeof s.namespace?{namespace:s.namespace}:{},..."string"==typeof s.role?{role:s.role}:{},..."number"==typeof s.renderGroup?{renderGroup:s.renderGroup}:{},..."number"==typeof s.altGroup?{altGroup:s.altGroup}:{},..."string"==typeof s.codec?{codec:s.codec}:{},..."string"==typeof s.mimeType?{mimeType:s.mimeType}:{},..."number"==typeof s.framerate?{framerate:s.framerate}:{},..."number"==typeof s.timescale?{timescale:s.timescale}:{},..."number"==typeof s.bitrate?{bitrate:s.bitrate}:{},..."number"==typeof s.width?{width:s.width}:{},..."number"==typeof s.height?{height:s.height}:{},..."number"==typeof s.samplerate?{samplerate:s.samplerate}:{},..."string"==typeof s.channelConfig?{channelConfig:s.channelConfig}:{},..."number"==typeof s.displayWidth?{displayWidth:s.displayWidth}:{},..."number"==typeof s.displayHeight?{displayHeight:s.displayHeight}:{},..."string"==typeof s.lang?{lang:s.lang}:{},..."string"==typeof s.label?{label:s.label}:{},..."string"==typeof s.initData?{initData:s.initData}:{},...Array.isArray(s.depends)?{depends:s.depends}:{},..."number"==typeof s.temporalId?{temporalId:s.temporalId}:{},..."number"==typeof s.spatialId?{spatialId:s.spatialId}:{},..."number"==typeof s.targetLatency?{targetLatency:s.targetLatency}:{},..."number"==typeof s.trackDuration?{trackDuration:s.trackDuration}:{},..."string"==typeof s.eventType?{eventType:s.eventType}:{},..."string"==typeof s.parentName?{parentName:s.parentName}:{}}}function Ln(e,t,i){const s={...{...e}};return s.name=t.name,delete s.parentName,void 0!==t.namespace&&(s.namespace=t.namespace),void 0!==t.packaging&&(s.packaging=t.packaging),void 0!==t.isLive&&(s.isLive=t.isLive),void 0!==t.role&&(s.role=t.role),void 0!==t.renderGroup&&(s.renderGroup=t.renderGroup),void 0!==t.altGroup&&(s.altGroup=t.altGroup),void 0!==t.codec&&(s.codec=t.codec),void 0!==t.mimeType&&(s.mimeType=t.mimeType),void 0!==t.framerate&&(s.framerate=t.framerate),void 0!==t.timescale&&(s.timescale=t.timescale),void 0!==t.bitrate&&(s.bitrate=t.bitrate),void 0!==t.width&&(s.width=t.width),void 0!==t.height&&(s.height=t.height),void 0!==t.samplerate&&(s.samplerate=t.samplerate),void 0!==t.channelConfig&&(s.channelConfig=t.channelConfig),void 0!==t.displayWidth&&(s.displayWidth=t.displayWidth),void 0!==t.displayHeight&&(s.displayHeight=t.displayHeight),void 0!==t.lang&&(s.lang=t.lang),void 0!==t.label&&(s.label=t.label),void 0!==t.initData&&(s.initData=t.initData),void 0!==t.depends&&(s.depends=t.depends),void 0!==t.temporalId&&(s.temporalId=t.temporalId),void 0!==t.spatialId&&(s.spatialId=t.spatialId),void 0!==t.targetLatency&&(s.targetLatency=t.targetLatency),void 0!==t.trackDuration&&(s.trackDuration=t.trackDuration),void 0!==t.eventType&&(s.eventType=t.eventType),void 0===s.namespace&&void 0!==i&&(s.namespace=i),s}function Un(e,t){let i=[...e];if(void 0!==t.codec&&(i=i.filter(e=>e.codec===t.codec)),void 0!==t.lang&&(i=i.filter(e=>e.lang===t.lang)),void 0!==t.role&&(i=i.filter(e=>e.role===t.role)),void 0!==t.maxWidth&&(i=i.filter(e=>void 0===e.width||e.width<=t.maxWidth)),void 0!==t.maxHeight&&(i=i.filter(e=>void 0===e.height||e.height<=t.maxHeight)),void 0!==t.minBitrate&&(i=i.filter(e=>void 0!==e.bitrate&&e.bitrate>=t.minBitrate)),void 0!==t.maxBitrate&&(i=i.filter(e=>void 0===e.bitrate||e.bitrate<=t.maxBitrate)),0!==i.length)return i.sort((e,t)=>(t.bitrate??0)-(e.bitrate??0)),i[0]}function Dn(e){const t="string"==typeof e?e:(new TextDecoder).decode(e),i=JSON.parse(t);if(!Array.isArray(i))throw new Error("Event timeline must be a JSON array (§8.1)");return i.map((e,t)=>{if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`Event timeline record[${t}]: must be a JSON object (§8.1)`);const i=e,s="t"in i,n="l"in i;if(1!==(s?1:0)+(n?1:0)+("m"in i?1:0))throw new Error(`Event timeline record[${t}]: must have exactly one index field ('t', 'l', or 'm') (§8.1)`);if(!("data"in i))throw new Error(`Event timeline record[${t}]: 'data' field is required (§8.1)`);let r;if(s){if("number"!=typeof i.t)throw new Error(`Event timeline record[${t}]: 't' index must be a number (§8.1)`);r={t:i.t}}else if(n){const e=i.l;if(!Array.isArray(e)||2!==e.length||"number"!=typeof e[0]||"number"!=typeof e[1])throw new Error(`Event timeline record[${t}]: 'l' location index must be [groupId, objectId] (§8.1)`);r={l:[e[0],e[1]]}}else{if("number"!=typeof i.m)throw new Error(`Event timeline record[${t}]: 'm' index must be a number (§8.1)`);r={m:i.m}}return{index:r,data:i.data}})}function Mn(e,t){if(0===t.length)return[...e];const i=new Set;for(const t of e)i.add(`${t.location[0]},${t.location[1]}`);const s=[...e];for(const e of t){const t=`${e.location[0]},${e.location[1]}`;i.has(t)||(i.add(t),s.push(e))}return s}class Bn{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{i.delete(t)}}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){const i=this.listeners.get(e);if(i)for(const e of i)e(t)}removeAllListeners(){this.listeners.clear()}}class xn{hooks=[];add(e){this.hooks.push(e)}remove(e){const t=this.hooks.indexOf(e);-1!==t&&this.hooks.splice(t,1)}run(e){let t=e;for(const e of this.hooks)if(t=e(t),null===t)return null;return t}}class Hn{onTimeout;onWarning;expectations=new Map;constructor(e){this.onTimeout=e.onTimeout,this.onWarning=e.onWarning}expect(e,t){this.cancel(e);const i=Date.now(),s=setTimeout(()=>{this.expectations.delete(e),this.onTimeout?.({event:e,timeoutMs:t,elapsedMs:Date.now()-i})},t);let n=null;if(this.onWarning){const i=Math.floor(t/2);n=setTimeout(()=>{this.onWarning?.({event:e,elapsedMs:i,timeoutMs:t})},i)}this.expectations.set(e,{timeoutMs:t,startedAt:i,timeoutTimer:s,warningTimer:n})}fulfill(e){this.cancel(e)}get activeExpectations(){return[...this.expectations.keys()]}destroy(){for(const[,e]of this.expectations)clearTimeout(e.timeoutTimer),e.warningTimer&&clearTimeout(e.warningTimer);this.expectations.clear()}cancel(e){const t=this.expectations.get(e);t&&(clearTimeout(t.timeoutTimer),t.warningTimer&&clearTimeout(t.warningTimer),this.expectations.delete(e))}}const $n="idle",Fn="loading",Vn="playing",qn="paused",Gn="ended",jn="error",Wn={[$n]:[Fn,Gn,jn],[Fn]:[Vn,Gn,jn],[Vn]:[qn,Gn,jn],[qn]:[Vn,Gn,jn],[Gn]:[],[jn]:[Gn]};class Qn{_state=$n;get state(){return this._state}transition(e){if(!Wn[this._state].includes(e))throw new Error(`Invalid state transition: ${this._state} → ${e}`);this._state=e}}const Kn={maxRequestId:1e4,connectionTimeoutMs:1e4,reconnectAttempts:3,reconnectDelayMs:1e3,reconnectBackoff:"exponential",moqtImplementation:"proto-moq",gapTimeoutMs:500,driftThresholdMs:200,maxBufferDepth:500,maxCatchUpRate:1,catchUpThresholdMs:500,catchUpRecoveryMs:50,lateFrameThresholdMs:100,maxDriftMs:500,autoQuality:!0,startLevel:"auto",qualitySwitchCooldownMs:5e3,maxConsecutiveGaps:5,maxDecodeErrors:10,gapEscalationWindowMs:1e4,audioScheduleAheadMs:200,logLevel:"none"};const zn=4096,Yn=4097,Jn=4098,Xn=4099,Zn=4100,er=4352,tr=4353,ir=4608,sr=4609,nr=4864,rr=4865,ar=4866,or=4867;function cr(e,t,i,s,n){return{severity:e,source:t,code:i,message:s,...n?.cause?{cause:n.cause}:{},timestampMs:Date.now(),...n?.context?{context:n.context}:{}}}const dr={none:0,error:1,warn:2,info:3,debug:4};class hr{prefix;level;constructor(e,t="moqt"){this.prefix=t,this.level=dr[e]}error(e,...t){this.level>=1&&console.error(`[${this.prefix}]`,e,...t)}warn(e,...t){this.level>=2&&console.warn(`[${this.prefix}]`,e,...t)}info(e,...t){this.level>=3&&console.info(`[${this.prefix}]`,e,...t)}debug(e,...t){this.level>=4&&console.debug(`[${this.prefix}]`,e,...t)}}const lr={error(){},warn(){},info(){},debug(){}};function ur(){const e=void 0!==globalThis.WebTransport,t=void 0!==globalThis.WebSocket,i=void 0!==globalThis.VideoDecoder,s=void 0!==globalThis.AudioDecoder,n=void 0!==globalThis.MediaSource||void 0!==globalThis.ManagedMediaSource,r=void 0!==globalThis.HTMLCanvasElement,a=void 0!==globalThis.OffscreenCanvas,o=void 0!==globalThis.AudioContext||void 0!==globalThis.webkitAudioContext,c="boolean"==typeof globalThis.isSecureContext&&globalThis.isSecureContext,d=e&&c?"webtransport":t?"websocket":"none",h=i?"webcodecs":n?"mse":"none";let l;return"none"===d?l="Neither WebTransport nor WebSocket is available":"none"===h&&(l="Neither WebCodecs nor MediaSource Extensions are available"),{supported:"none"!==d&&"none"!==h,webTransport:e,webSocket:t,videoDecoder:i,audioDecoder:s,mediaSource:n,canvas:r,offscreenCanvas:a,audioContext:o,isSecureContext:c,transport:d,decoder:h,...void 0!==l?{reason:l}:{}}}class pr{catalogNamespace;state=null;_objectCount=0;cf01DeltaSupport=!1;lastRawDocument=null;constructor(e){this.catalogNamespace=e}get currentState(){return this.state}get objectCount(){return this._objectCount}processCatalogObject(e){const t=(new TextDecoder).decode(e),i=JSON.parse(t);if(Array.isArray(i)){if(!this.cf01DeltaSupport||!this.lastRawDocument)throw new Error("Received JSON Patch delta but initial catalog did not advertise supportsDeltaUpdates (catalogformat-01 §4)");const e=vn(this.lastRawDocument,i,this.catalogNamespace);this.lastRawDocument=e.rawDocument,this.state={version:1,tracks:[...e.catalog.tracks]}}else if("object"==typeof i&&null!==i&&"deltaUpdate"in i&&!0===i.deltaUpdate){if(!this.state)throw new Error("Delta catalog update received before initial catalog (§9.1: publisher MUST publish catalog before media)");const t=An(e);this.state=kn(this.state,t,this.catalogNamespace)}else{if("streamingFormat"in i){const t=_n(e,this.catalogNamespace);this.cf01DeltaSupport=t.supportsDeltaUpdates,this.lastRawDocument=t.rawDocument,this.state={version:t.catalog.version,tracks:[...t.catalog.tracks]}}else{const t=Ns(e,this.catalogNamespace);this.cf01DeltaSupport=!1,this.lastRawDocument=null,this.state={version:t.version,tracks:[...t.tracks],...void 0!==t.generatedAt?{generatedAt:t.generatedAt}:{},...void 0!==t.isComplete?{isComplete:t.isComplete}:{}}}}return this._objectCount++,this.state}}class mr{autoQuality;startLevel;capLevelToResolution;qualitySwitchCooldownMs;clock;videoAlternatives=[];allVideoAlternatives=[];videoIndex=0;_audioTrack;lastSwitchTimeUs;constructor(e){this.autoQuality=e?.autoQuality??!0,this.startLevel=e?.startLevel??"auto",this.capLevelToResolution=e?.capLevelToResolution,this.qualitySwitchCooldownMs=e?.qualitySwitchCooldownMs??0,this.clock=e?.clock??{now:()=>1e3*performance.now()}}get currentVideoTrack(){return this.videoAlternatives[this.videoIndex]}get currentAudioTrack(){return this._audioTrack}selectInitialTracks(e,t){const i=e.tracks.filter(e=>"video"===e.role),s=e.tracks.filter(e=>"audio"===e.role);let n;const{groups:r}=function(e){const t=new Map,i=[];for(const s of e)if(void 0!==s.altGroup){let e=t.get(s.altGroup);e||(e=[],t.set(s.altGroup,e)),e.push(s)}else i.push(s);const s=[];for(const[e,i]of t)s.push({altGroup:e,tracks:i});return{groups:s,ungrouped:i}}(i);if(n=r.length>0?[...r[0].tracks]:[...i],n.sort((e,t)=>(t.bitrate??0)-(e.bitrate??0)),this.capLevelToResolution){const e=this.capLevelToResolution;n=n.filter(t=>(t.width??0)<=e.width&&(t.height??0)<=e.height)}let a;if(this.allVideoAlternatives=n,"lowest"===this.startLevel)a=n[n.length-1];else if("number"==typeof this.startLevel){a=n[Math.min(this.startLevel,n.length-1)]}else a=t?.videoConstraints?Un(n,t.videoConstraints):n[Math.floor(n.length/2)];if(a?.codec){const e=a.codec.split(".")[0];this.videoAlternatives=n.filter(t=>t.codec?.split(".")[0]===e)}else this.videoAlternatives=n;this.videoIndex=a?this.videoAlternatives.indexOf(a):0,-1===this.videoIndex&&(this.videoIndex=0);const o=t?.audioConstraints?Un(s,t.audioConstraints):s[0];return this._audioTrack=o,{video:t?.disableVideo?void 0:a,audio:t?.disableAudio?void 0:o}}reduceVideoQuality(e=!1){if(!this.autoQuality)return null;if(!e){const e=this.clock.now(),t=1e3*this.qualitySwitchCooldownMs;if(void 0!==this.lastSwitchTimeUs&&e-this.lastSwitchTimeUs=this.videoAlternatives.length-1?null:(this.videoIndex++,this.lastSwitchTimeUs=this.clock.now(),this.videoAlternatives[this.videoIndex]??null)}increaseVideoQuality(){if(!this.autoQuality)return null;const e=this.clock.now(),t=1e3*this.qualitySwitchCooldownMs;return void 0!==this.lastSwitchTimeUs&&e-this.lastSwitchTimeUs=this.videoAlternatives.length-1?null:this.videoAlternatives[this.videoIndex+1]??null}peekHigherVideoQuality(){if(!this.autoQuality)return null;const e=this.clock.now(),t=1e3*this.qualitySwitchCooldownMs;return void 0!==this.lastSwitchTimeUs&&e-this.lastSwitchTimeUst.name===e);t>=0&&(this.videoIndex=t,this.lastSwitchTimeUs=this.clock.now())}lockManual(){this.autoQuality=!1}unlockAuto(){this.autoQuality=!0}get isAutoQuality(){return this.autoQuality}get alternatives(){return this.videoAlternatives}get allAlternatives(){return this.allVideoAlternatives}get currentIndex(){return this.videoIndex}get nextHigherTrack(){if(!(this.videoIndex<=0))return this.videoAlternatives[this.videoIndex-1]}}class gr{tracks=new Map;objectTransform=null;draftVersion;extensionParser=null;onObject=null;onCmafObject=null;onTimelineObject=null;onEventTimelineObject=null;onInitObject=null;onMalformedTrack=null;get activeCount(){return this.tracks.size}registerTrack(e,t,i,s="loc"){this.tracks.set(e,{trackName:t,mediaType:i,packaging:s})}unregisterTrack(e){this.tracks.delete(e)}getMediaType(e){return this.tracks.get(e)?.mediaType}async routeObject(e,t){const i=BigInt(t.trackAlias),s=this.tracks.get(i);if(s)try{if("mediatimeline"===s.packaging)return void this.onTimelineObject?.(s.trackName,t);if("eventtimeline"===s.packaging)return void this.onEventTimelineObject?.(s.trackName,t);if("init"===s.packaging)return void this.onInitObject?.(s.trackName,t);const e=s.mediaType;let i=t;if(this.objectTransform){const e=this.objectTransform(t);if(i=e instanceof Promise?await e:e,!i)return}if("cmaf"===s.packaging)this.onCmafObject?.(e,s.trackName,i);else{const t="data"===i.kind?i.extensions:void 0,n=14===this.draftVersion?{deltaEncoded:!1}:void 0,r=this.extensionParser??(e=>function(e,t){if(!e||0===e.length)return{};let i,s,n,r,a;const o=!1!==t?.deltaEncoded;let c=0,d=0n;for(;c{const r=BigInt(e.timestamp);if(!(this._hasSyncReference?.()??!0)){if(this.videoHoldQueue.length>=fr.MAX_HOLD_QUEUE){const e=this.videoHoldQueue.shift();e.frame.close?.()}return this.videoHoldQueue.push({frame:e,captureTimestampUs:r}),void this.checkQueuePressure("video",i)}this.drainVideoHoldQueue(t);const a=s?s(r):n;t.enqueue(e,a),this.checkQueuePressure("video",i)}}if(this.audioDecoder&&this.audioOutput){const e=this.audioOutput,t=this.audioDecoder;this.audioDecoder.onData=(i,s)=>{e.schedule(i,s),this.checkQueuePressure("audio",t)}}if(this.videoDecoder&&(this.videoDecoder.onError=t=>{e.onError?.("video",t),this.onFeedback?.({type:"decode_error",mediaType:"video",message:t.message})}),this.audioDecoder&&(this.audioDecoder.onError=t=>{e.onError?.("audio",t),this.onFeedback?.({type:"decode_error",mediaType:"audio",message:t.message})}),this.renderer){if(e.onFirstFrame){const t=e.onFirstFrame;this.renderer.onFirstFrame=()=>t()}if(e.onStall){const t=e.onStall;this.renderer.onStall=e=>t(e)}this.renderer.onFrameRendered=(t,i)=>{e.onFrameRendered?.(t,i),this.onFeedback?.({type:"frame_rendered",mediaType:"video",captureTimestampUs:t,actualRenderUs:i})}}}updateVideoCodec(e,t,i){this.videoCodec=e,this.videoWidth=t,this.videoHeight=i}dispatch(e){switch(e.type){case"configure":"video"===e.mediaType?this.videoDecoder?.configure(e.config,this.videoCodec,this.videoWidth,this.videoHeight):this.audioDecoder?.configure(e.config,this.audioCodec,this.audioSampleRate,this.audioChannels);break;case"decode_video":try{this.videoDecoder?.decode(e.chunk,e.renderTimeUs)}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onError?.("video",t),this.onFeedback?.({type:"decode_error",mediaType:"video",message:t.message})}this.videoDecoder&&this.checkQueuePressure("video",this.videoDecoder);break;case"decode_audio":try{this.audioDecoder?.decode(e.chunk,e.renderTimeUs)}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onError?.("audio",t),this.onFeedback?.({type:"decode_error",mediaType:"audio",message:t.message})}this.audioDecoder&&this.checkQueuePressure("audio",this.audioDecoder);break;case"flush":if("video"===e.mediaType){const e=this.videoDecoder?.flush();e&&e.then(()=>this.onFeedback?.({type:"flush_complete",mediaType:"video"}))}else{const e=this.audioDecoder?.flush();e&&e.then(()=>this.onFeedback?.({type:"flush_complete",mediaType:"audio"}))}break;case"reset":"video"===e.mediaType?(this.closeVideoHoldQueue(),this.renderer?.flush(),this.videoDecoder?.reset(),this.videoQueuePressureHigh=!1):(this.audioDecoder?.reset(),this.audioOutput?.flush?.(),this.audioQueuePressureHigh=!1);break;case"set_playback_rate":this.audioOutput?.setPlaybackRate?.(e.rate)}}checkQueuePressure(e,t){if(!this.onFeedback)return;const i=t.queueDepth,s="video"===e,n=s?this.videoQueuePressureHigh:this.audioQueuePressureHigh;!n&&i>=8?(s?this.videoQueuePressureHigh=!0:this.audioQueuePressureHigh=!0,this.onFeedback({type:"queue_pressure",mediaType:e,depth:i,maxRecommended:8})):n&&i<=4&&(s?this.videoQueuePressureHigh=!1:this.audioQueuePressureHigh=!1,this.onFeedback({type:"queue_pressure",mediaType:e,depth:i,maxRecommended:8}))}drainVideoHoldQueue(e){for(const t of this.videoHoldQueue){const i=this._recomputeVideoRenderTime?this._recomputeVideoRenderTime(t.captureTimestampUs):0;e.enqueue(t.frame,i)}this.videoHoldQueue.length=0}closeVideoHoldQueue(){for(const e of this.videoHoldQueue)e.frame.close?.();this.videoHoldQueue.length=0}flush(){this.closeVideoHoldQueue(),this.renderer?.flush(),this.audioOutput?.flush()}destroy(){this.closeVideoHoldQueue(),this.videoDecoder?.destroy(),this.audioDecoder?.destroy(),this.renderer?.destroy(),this.audioOutput?.destroy()}}class _r{_loadStartMs=null;_transportConnectedMs=null;_setupCompleteMs=null;_catalogReceivedMs=null;_firstObjectReceivedMs=null;_decoderConfiguredMs=null;_firstFrameRenderedMs=null;_currentBitrate=0;_currentResolution=null;_currentVideoCodec=null;_currentAudioCodec=null;_qualitySwitchCount=0;_targetLatencyMs=0;_framesDecoded=0;_framesDropped=0;_framesRendered=0;_objectsReceived=0;_bytesReceived=0;_gapsReceived=0;_gapCount=0;_stallCount=0;_totalStallDurationMs=0;_decodeErrorCount=0;_recoveryActionCount=0;_reconnectCount=0;_currentLatencyMs=0;_playing=!1;_accumulatedPlayMs=0;_playSegmentStartMs=null;recordLoadStart(){null===this._loadStartMs&&(this._loadStartMs=Date.now())}recordTransportConnected(){null===this._transportConnectedMs&&(this._transportConnectedMs=Date.now())}recordSetupComplete(){null===this._setupCompleteMs&&(this._setupCompleteMs=Date.now())}recordCatalogReceived(){null===this._catalogReceivedMs&&(this._catalogReceivedMs=Date.now())}recordFirstObjectReceived(){null===this._firstObjectReceivedMs&&(this._firstObjectReceivedMs=Date.now())}recordDecoderConfigured(){null===this._decoderConfiguredMs&&(this._decoderConfiguredMs=Date.now())}recordFirstFrameRendered(){null===this._firstFrameRenderedMs&&(this._firstFrameRenderedMs=Date.now())}setTrackInfo(e,t){e&&(this._currentVideoCodec=e.codec??null,this._currentBitrate=e.bitrate??0,void 0!==e.width&&void 0!==e.height&&(this._currentResolution={width:e.width,height:e.height})),t&&(this._currentAudioCodec=t.codec??null)}recordQualitySwitch(e){this._qualitySwitchCount++,this._currentVideoCodec=e.codec??this._currentVideoCodec,this._currentBitrate=e.bitrate??this._currentBitrate,void 0!==e.width&&void 0!==e.height&&(this._currentResolution={width:e.width,height:e.height})}setTargetLatency(e){this._targetLatencyMs=e}recordFrameDecoded(){this._framesDecoded++}recordFrameRendered(){this._framesRendered++}recordMediaObject(e){this._objectsReceived++,this._bytesReceived+=e}recordGapObject(){this._gapsReceived++}recordGapDetected(){this._gapCount++}recordStall(e){this._stallCount++,this._totalStallDurationMs+=e}recordDecodeError(){this._decodeErrorCount++}recordRecoveryAction(){this._recoveryActionCount++}recordReconnect(){this._reconnectCount++}recordLatency(e){this._currentLatencyMs=e}recordPlayStart(){this._playing||(this._playing=!0,this._playSegmentStartMs=Date.now())}recordPlayStop(){this._playing&&null!==this._playSegmentStartMs&&(this._accumulatedPlayMs+=Date.now()-this._playSegmentStartMs,this._playSegmentStartMs=null,this._playing=!1)}snapshot(){const e=Date.now(),t=this._loadStartMs,i=e=>null!==e&&null!==t?e-t:null,s=null!==t?{loadCalledMs:0,transportConnectedMs:i(this._transportConnectedMs),setupCompleteMs:i(this._setupCompleteMs),catalogReceivedMs:i(this._catalogReceivedMs),firstObjectReceivedMs:i(this._firstObjectReceivedMs),decoderConfiguredMs:i(this._decoderConfiguredMs),firstFrameRenderedMs:i(this._firstFrameRenderedMs)}:null;let n=this._accumulatedPlayMs;this._playing&&null!==this._playSegmentStartMs&&(n+=e-this._playSegmentStartMs);const r=null!==t?e-t:0,a=this._framesDecoded+this._framesDropped,o=a>0?this._framesDropped/a:0;return{timeToFirstFrameMs:i(this._firstFrameRenderedMs),ttffBreakdown:s,currentLatencyMs:this._currentLatencyMs,targetLatencyMs:this._targetLatencyMs,playbackDurationMs:n,sessionAgeMs:r,currentBitrate:this._currentBitrate,currentResolution:this._currentResolution,currentVideoCodec:this._currentVideoCodec,currentAudioCodec:this._currentAudioCodec,qualitySwitchCount:this._qualitySwitchCount,framesDecoded:this._framesDecoded,framesDropped:this._framesDropped,framesRendered:this._framesRendered,dropRatio:o,videoBufferDepth:0,audioBufferDepth:0,videoDecoderQueueDepth:0,objectsReceived:this._objectsReceived,bytesReceived:this._bytesReceived,gapsReceived:this._gapsReceived,gapCount:this._gapCount,stallCount:this._stallCount,totalStallDurationMs:this._totalStallDurationMs,decodeErrorCount:this._decodeErrorCount,recoveryActionCount:this._recoveryActionCount,reconnectCount:this._reconnectCount}}}function vr(e,t){return t??e.url}function br(e){const t={maxRequestId:K(e.maxRequestId)};return e.moqtImplementation&&(t.implementation=e.moqtImplementation),e.authTokens&&(t.authTokens=e.authTokens),t}function Sr(e){const t=void 0!==e.deliveryTimeoutMs,i=void 0!==e.subscriberPriority,s=void 0!==e.groupOrder,n=void 0!==e.subscriptionFilter;if(!(t||i||s||n))return;const r={};if(t&&(r.deliveryTimeout=K(BigInt(e.deliveryTimeoutMs))),i&&(r.subscriberPriority=K(BigInt(e.subscriberPriority))),s){const t="ascending"===e.groupOrder?0x1n:0x2n;r.groupOrder=K(t)}if(n){const t=e.subscriptionFilter;switch(t.type){case"NextGroupStart":r.subscriptionFilter={type:"NextGroupStart"};break;case"LargestObject":case"LatestObject":r.subscriptionFilter={type:"LargestObject"};break;case"AbsoluteStart":r.subscriptionFilter={type:"AbsoluteStart",startGroup:K(BigInt(t.startGroup??0)),startObject:K(BigInt(t.startObject??0))};break;case"AbsoluteRange":r.subscriptionFilter={type:"AbsoluteRange",startGroup:K(BigInt(t.startGroup??0)),startObject:K(BigInt(t.startObject??0)),endGroup:K(BigInt(t.endGroup??0))}}}return r}function Er(e){const t={};for(const[i,s]of Object.entries(e))void 0!==s&&(t[i]=s);return t}function yr(e,t){if(e.videoPipeline&&t.video&&(t.video.codec&&e.videoPipeline.setCodec(t.video.codec),t.video.initData||t.video.codec)){const i=t.video.initData?Uint8Array.from(atob(t.video.initData),e=>e.charCodeAt(0)):new Uint8Array(0);e.videoPipeline.configure(i)}if(e.audioPipeline&&t.audio&&(t.audio.initData||t.audio.codec)){const i=t.audio.initData?Uint8Array.from(atob(t.audio.initData),e=>e.charCodeAt(0)):new Uint8Array(0);e.audioPipeline.configure(i)}}function Tr(e,t,i,s,n){switch(e.type){case"skip_forward":s.warn("Recovery: skip forward %s — flush pipeline and resubscribe from live edge",t),n.onResubscribe(t);break;case"reduce_quality":if(i){const e=i.peekLowerVideoQuality();e?(n.onQualityReduced(e),s.warn("Quality reduced to %s (%dkbps)",e.name,(e.bitrate??0)/1e3)):s.warn("Quality reduction requested but already at lowest")}break;case"resubscribe":s.warn("Recovery: request fresh %s subscription at next group boundary",t),n.onResubscribe(t,e.startGroup);break;case"terminate":s.error("Recovery: terminate — %s","reason"in e?e.reason:"unknown"),n.onTerminate("reason"in e?e.reason:"unknown")}}function Cr(e,t){const i=function(e){const t="string"==typeof e?e:(new TextDecoder).decode(e),i=JSON.parse(t);if(!Array.isArray(i))throw new Error("Media timeline must be a JSON array (§7.1)");return i.map((e,t)=>{if(!Array.isArray(e)||3!==e.length)throw new Error(`Media timeline entry[${t}]: must be a 3-element array [mediaPts, [groupId, objectId], wallclockTime] (§7.1)`);const[i,s,n]=e;if("number"!=typeof i)throw new Error(`Media timeline entry[${t}]: mediaPts must be a number (§7.1)`);if(!Array.isArray(s)||2!==s.length||"number"!=typeof s[0]||"number"!=typeof s[1])throw new Error(`Media timeline entry[${t}]: location must be [groupId, objectId] (§7.1)`);if("number"!=typeof n)throw new Error(`Media timeline entry[${t}]: wallclockTime must be a number (§7.1)`);return{mediaPts:i,location:[s[0],s[1]],wallclockTime:n}})}(t);return{...e,entries:Mn(e.entries,i)}}function wr(e){if(void 0!==e.trackDuration)return e.trackDuration;if(0===e.entries.length)return;const t=e.entries[e.entries.length-1];return t?.mediaPts}const Rr=100,Ir=3e3;function Ar(e,t){return("string"==typeof e?e.split("/"):Array.from(e)).map(e=>t.encode(e))}function kr(e){return"string"==typeof e?e:e.join("/")}function Or(e,t){return e===t}function Nr(e){return e?{subscriptionFilter:{type:"NextGroupStart"}}:{subscriptionFilter:{type:"AbsoluteStart",startGroup:K(0n),startObject:K(0n)}}}function Pr(e){const t={};for(const[i,s]of Object.entries(e))void 0!==s&&(t[i]=s);return t}class Lr{config;emitter=new Bn;stateMachine=new Qn;_stats=new _r;log;watchdog;hooks={beforeSubscribe:new xn,beforeQualitySwitch:new xn,onRecovery:new xn};connection=null;_adapterOwned=!0;catalogManager=null;qualityController=null;bandwidthEstimator=null;bufferAbrController=null;bwEstimatorGroupId=-1n;bwEstimatorGroupBytes=0;estimatedGopDurationUs=2e6;subscriptionManager=null;videoPipeline=null;audioPipeline=null;syncController=null;recoveryController=null;commandDispatcher=null;mediaSource=null;cmafInitialized=!1;cmafVideoSynced=!1;cmafAssembler=null;initSegmentByTrack=new Map;pendingInitTrackSubs=new Map;initTrackRequestIds=new Map;currentVideoCodec=null;pendingObjectsByAlias=new Map;static MAX_PENDING_PER_ALIAS=256;tickInterval=null;syncResetThisTick=!1;clock;_handshakeRttMs;catalogRequestId=null;catalogTrackAlias=null;catalogReceived=!1;_catalogState=null;announcedNamespaces=new Map;pendingVideoSwitch=null;switchStagingBuffer=[];cmafSwitchStagingBuffer=[];switchStagingTimeout=null;switchInProgress=!1;pipelinesCreated=!1;_destroyed=!1;activeSubscriptions=new Map;pendingMediaSubs=new Map;_mediaSubsExpected=0;_mediaSubsOk=0;_mediaSubsFailed=0;activeFetches=new Map;pendingTrackStatuses=new Map;pendingCatalogFetches=new Map;catalogFetchStreams=new Map;fetchStreamAliases=new Map;timelineState=null;timelineRequestId=null;enc=new TextEncoder;constructor(e){!function(e){if(void 0!==e.subscriberPriority&&(!Number.isInteger(e.subscriberPriority)||e.subscriberPriority<0||e.subscriberPriority>255))throw new RangeError(`subscriberPriority must be 0–255, got ${e.subscriberPriority}`);if(void 0!==e.maxCatchUpRate&&e.maxCatchUpRate<1)throw new RangeError(`maxCatchUpRate must be >= 1.0, got ${e.maxCatchUpRate}`);if(void 0!==e.reconnectAttempts&&(e.reconnectAttempts<0||!Number.isInteger(e.reconnectAttempts)))throw new RangeError(`reconnectAttempts must be a non-negative integer, got ${e.reconnectAttempts}`);const t=[["connectionTimeoutMs",e.connectionTimeoutMs],["reconnectDelayMs",e.reconnectDelayMs],["gapTimeoutMs",e.gapTimeoutMs],["driftThresholdMs",e.driftThresholdMs],["catchUpThresholdMs",e.catchUpThresholdMs],["catchUpRecoveryMs",e.catchUpRecoveryMs],["lateFrameThresholdMs",e.lateFrameThresholdMs],["maxDriftMs",e.maxDriftMs],["qualitySwitchCooldownMs",e.qualitySwitchCooldownMs],["gapEscalationWindowMs",e.gapEscalationWindowMs],["audioScheduleAheadMs",e.audioScheduleAheadMs]];for(const[e,i]of t)if(void 0!==i&&i<=0)throw new RangeError(`${e} must be > 0, got ${i}`);if(void 0!==e.deliveryTimeoutMs&&e.deliveryTimeoutMs<=0)throw new RangeError(`deliveryTimeoutMs must be > 0, got ${e.deliveryTimeoutMs}`);if(void 0!==e.targetLatencyMs&&e.targetLatencyMs<=0)throw new RangeError(`targetLatencyMs must be > 0, got ${e.targetLatencyMs}`);if(void 0!==e.maxBufferDepth&&(e.maxBufferDepth<=0||!Number.isInteger(e.maxBufferDepth)))throw new RangeError(`maxBufferDepth must be a positive integer, got ${e.maxBufferDepth}`);if(void 0!==e.maxRequestId&&(e.maxRequestId<=0||!Number.isInteger(e.maxRequestId)))throw new RangeError(`maxRequestId must be a positive integer, got ${e.maxRequestId}`);if(void 0!==e.startLevel)if("number"==typeof e.startLevel){if(e.startLevel<0||!Number.isInteger(e.startLevel))throw new RangeError(`startLevel must be >= 0 (integer), 'lowest', or 'auto', got ${e.startLevel}`)}else if("lowest"!==e.startLevel&&"auto"!==e.startLevel)throw new RangeError(`startLevel must be >= 0 (integer), 'lowest', or 'auto', got '${e.startLevel}'`);if(void 0!==e.maxConsecutiveGaps&&(e.maxConsecutiveGaps<=0||!Number.isInteger(e.maxConsecutiveGaps)))throw new RangeError(`maxConsecutiveGaps must be a positive integer, got ${e.maxConsecutiveGaps}`);if(void 0!==e.maxDecodeErrors&&(e.maxDecodeErrors<=0||!Number.isInteger(e.maxDecodeErrors)))throw new RangeError(`maxDecodeErrors must be a positive integer, got ${e.maxDecodeErrors}`);if(void 0!==e.capLevelToResolution&&(e.capLevelToResolution.width<=0||e.capLevelToResolution.height<=0))throw new RangeError(`capLevelToResolution dimensions must be > 0, got ${e.capLevelToResolution.width}x${e.capLevelToResolution.height}`)}(e),this.config={...Kn,...e},this.clock=this.config.clock??{now:()=>1e3*performance.now()},this.log=function(e){return e.logger?e.logger:e.logLevel&&"none"!==e.logLevel?new hr(e.logLevel):lr}({...void 0!==this.config.logLevel?{logLevel:this.config.logLevel}:{},...void 0!==this.config.logger?{logger:this.config.logger}:{}}),this.watchdog=new Hn({onTimeout:e=>{this.log.warn("Watchdog timeout: %s after %dms",e.event,e.elapsedMs),this.emitter.emit("state_changed",{type:"state_changed",from:this.state,to:this.state})},onWarning:e=>{this.log.info("Watchdog waiting: %s (%dms/%dms)",e.event,e.elapsedMs,e.timeoutMs)}})}static isSupported(){return ur().supported}static checkSupport(){return ur()}get state(){return this.stateMachine.state}get readyState(){return this._stats.snapshot().objectsReceived>0?2:this.catalogReceived?1:0}get readyStateLabel(){switch(this.readyState){case 0:return"HAVE_NOTHING";case 1:return"HAVE_CATALOG";case 2:return"HAVE_MEDIA";default:return"UNKNOWN"}}get stats(){return Object.freeze(this._stats.snapshot())}get duration(){return this.timelineState?wr(this.timelineState):void 0}get seekable(){return null!==this.timelineState&&this.timelineState.entries.length>0}get availableVideoTracks(){if(!this.qualityController)return[];return[...this.qualityController.allAlternatives].map(e=>Pr({name:e.name,width:e.width,height:e.height,bitrate:e.bitrate,codec:e.codec}))}setAutoQuality(e){this.qualityController&&(e?this.qualityController.unlockAuto():this.qualityController.lockManual())}async ensureInitTrack(e){const t=this.initSegmentByTrack.get(e);if(t)return t;const i=this.pendingInitTrackSubs.get(e);if(i)return i.promise;let s;const n=new Promise(e=>{s=e});if(this.pendingInitTrackSubs.set(e,{promise:n,resolve:s}),!this.connection||!this.subscriptionManager)throw new Error("ensureInitTrack: player not loaded");const r=Ar(this.config.namespace,this.enc),a=this.enc.encode(e),o={subscriptionFilter:{type:"AbsoluteStart",startGroup:K(0n),startObject:K(0n)}},c=await this.connection.subscribe(r,a,o),d=BigInt(c);return this.initTrackRequestIds.set(e,d),this.subscriptionManager&&(this.activeSubscriptions.set(d,{trackName:e,mediaType:"video",trackAlias:d}),this.subscriptionManager.registerTrack(d,e,"video","init"),this.pendingMediaSubs.set(d,{trackName:e,mediaType:"video",packaging:"init"})),n}async selectVideoTrack(e,t="manual",i){if(!this._catalogState||!this.connection||!this.subscriptionManager)throw new Error("Cannot switch track: player not loaded");"manual"===t&&this.qualityController&&this.qualityController.lockManual();const s=this._catalogState.tracks.find(t=>t.name===e&&"video"===t.role);if(!s)throw new Error(`Unknown video track: "${e}"`);let n=null,r=null;for(const[e,t]of this.activeSubscriptions)if("video"===t.mediaType){n=e,r=t.trackName;break}if(r===e)return;if("cmaf"===s.packaging&&void 0!==s.codec&&(null===this.currentVideoCodec||!Or(s.codec,this.currentVideoCodec))){if(!s.initData&&!s.initTrack)throw new Error(`Cannot switch to "${e}": catalog provides no initData or initTrack for codec "${s.codec}"`);if(this.log.info('[SWITCH] codec change "%s" → "%s" (codec "%s" → "%s"): prefetching init',r,e,this.currentVideoCodec??"(unknown)",s.codec),!s.initData&&s.initTrack)try{await this.ensureInitTrack(s.initTrack)}catch(e){throw this.log.warn("[SWITCH] init prefetch failed: %s",e instanceof Error?e.message:String(e)),e}}const a=Ar(this.config.namespace,this.enc),o=this.enc.encode(e),c=this.videoPipeline?.currentGroupId??-1n,d=c>=0n?c+1n:void 0,h=!0===s?.isLive,l=void 0!==d?{subscriptionFilter:{type:"AbsoluteStart",startGroup:K(d),startObject:K(0n)}}:Sr(this.config)??Nr(h);this.log.info("[SWITCH] subscribing at group=%s (current=%s)",d??"latest",c);const u=await this.connection.subscribe(a,o,l),p=BigInt(u);if(!this.subscriptionManager)return;const m="cmaf"===s.packaging?"cmaf":"loc";this.activeSubscriptions.set(p,{trackName:e,mediaType:"video",trackAlias:p}),this.pendingMediaSubs.set(p,{trackName:e,mediaType:"video",packaging:m}),this.log.info('[SWITCH] start: "%s" → "%s" (newReqId=%s, oldReqId=%s)',r,e,p,n),null!==n&&(this.pendingVideoSwitch={oldRequestId:n,oldTrackName:r??"",newTrackName:e,newTrackAlias:p,newTrackPackaging:m,reason:t,...i?{abrAction:i}:{}}),this.emitter.emit("quality_switching",{type:"quality_switching",fromTrackName:r??"",toTrackName:e,reason:t})}completePendingVideoSwitch(){if(this.switchInProgress)return;const e=this.pendingVideoSwitch;if(!e)return;if(this.switchInProgress=!0,null!==this.switchStagingTimeout&&(clearTimeout(this.switchStagingTimeout),this.switchStagingTimeout=null),!this.connection||!this.subscriptionManager)return this.pendingVideoSwitch=null,this.switchInProgress=!1,this.switchStagingBuffer=[],void(this.cmafSwitchStagingBuffer=[]);const t=this._catalogState?.tracks.find(t=>t.name===e.newTrackName&&"video"===t.role);if("cmaf"===t?.packaging&&void 0!==t.codec&&(null===this.currentVideoCodec||!Or(t.codec,this.currentVideoCodec))&&t&&this.mediaSource?.changeType){const i=t.initData?Uint8Array.from(atob(t.initData),e=>e.charCodeAt(0)):t.initTrack?this.initSegmentByTrack.get(t.initTrack):void 0;return i?(this.log.info('[SWITCH] codec change → calling MSE changeType: "%s" → "%s"',this.currentVideoCodec??"(unknown)",t.codec),void this.mediaSource.changeType("video",t.codec??"",i).then(()=>{this.unsubscribeOldVideoTrack(e),this.currentVideoCodec=t.codec??null,this.flushCmafStagedBuffer(e)}).catch(t=>{this.log.warn("[SWITCH] changeType failed: %s — aborting switch, old track stays active",t instanceof Error?t.message:String(t)),this.abortPendingVideoSwitch(e,t instanceof Error?t:new Error(String(t)))})):(this.log.warn('[SWITCH] init bytes missing for codec change → "%s" — aborting switch, old track stays active',t.codec),void this.abortPendingVideoSwitch(e,new Error(`Cannot switch to "${e.newTrackName}": init bytes missing for codec "${t.codec??""}"`)))}this.unsubscribeOldVideoTrack(e);const i=this.switchStagingBuffer.find(e=>0n===BigInt(e.obj.objectId)),s=i?BigInt(i.obj.groupId):this.switchStagingBuffer.length>0?BigInt(this.switchStagingBuffer[0].obj.groupId):0n;if(this.videoPipeline?.resetForTrackSwitch(s),t&&this.videoPipeline){this.commandDispatcher?.updateVideoCodec(t.codec??"",t.width,t.height);const e={video:Pr({codec:t.codec??"",initData:t.initData,width:t.width,height:t.height}),audio:void 0};yr({videoPipeline:this.videoPipeline,audioPipeline:null,syncController:this.syncController,recoveryController:this.recoveryController,commandDispatcher:this.commandDispatcher,mediaSource:null},e)}const n=this.switchStagingBuffer;this.switchStagingBuffer=[];const r=n.findIndex(e=>0n===BigInt(e.obj.objectId)),a=r>=0?n.slice(r):n;for(const{obj:e,headers:t}of a)this.videoPipeline?.pushObject(e,t);this.flushCmafStagedBuffer(e),this.syncController?.reset(),this.log.info('[SWITCH] complete (sync): "%s" → "%s" (LOC staged=%d, firstGroup=%s)',e.oldTrackName,e.newTrackName,n.length,s)}unsubscribeOldVideoTrack(e){if(!this.connection||!this.subscriptionManager)return;const t=this.activeSubscriptions.get(e.oldRequestId)?.trackAlias??e.oldRequestId;this.subscriptionManager.unregisterTrack(t),this.connection.unsubscribe(K(e.oldRequestId)),this.activeSubscriptions.delete(e.oldRequestId),this.pendingMediaSubs.delete(e.oldRequestId),this.pendingObjectsByAlias.delete(t)}flushCmafStagedBuffer(e){const t=this.cmafSwitchStagingBuffer;this.cmafSwitchStagingBuffer=[];for(const{trackName:e,mediaType:i,groupId:s,payload:n}of t)this.cmafAssembler?.push(i,e,s,n);t.length>0&&this.log.info('[SWITCH] CMAF flush: "%s" → "%s" (staged=%d)',e.oldTrackName,e.newTrackName,t.length),this.pendingVideoSwitch=null,this.switchInProgress=!1;const i=this._catalogState?.tracks.find(t=>t.name===e.newTrackName&&"video"===t.role);i&&this._stats.recordQualitySwitch(Pr({codec:i.codec,bitrate:i.bitrate,width:i.width,height:i.height})),this.qualityController?.commitVideoTrack(e.newTrackName),"downshift"===e.abrAction?this.bufferAbrController?.commitDownshift():"upshift"===e.abrAction&&this.bufferAbrController?.commitUpshift(),this.emitter.emit("quality_switched",{type:"quality_switched",fromTrackName:e.oldTrackName,toTrackName:e.newTrackName,reason:e.reason})}abortPendingVideoSwitch(e,t){if(this.connection&&this.subscriptionManager){const t=this.activeSubscriptions.get(e.newTrackAlias)?.trackAlias??e.newTrackAlias;this.subscriptionManager.unregisterTrack(t);try{this.connection.unsubscribe(K(e.newTrackAlias))}catch{}this.activeSubscriptions.delete(e.newTrackAlias),this.pendingMediaSubs.delete(e.newTrackAlias),this.pendingObjectsByAlias.delete(t)}this.cmafSwitchStagingBuffer=[],this.switchStagingBuffer=[],this.pendingVideoSwitch=null,this.switchInProgress=!1,this.emitter.emit("quality_switch_failed",{type:"quality_switch_failed",fromTrackName:e.oldTrackName,toTrackName:e.newTrackName,reason:e.reason,error:t}),this.emitError(cr("degraded","decoder",er,`Track switch to "${e.newTrackName}" failed: ${t.message}`,{cause:t,context:{newTrackName:e.newTrackName,oldTrackName:e.oldTrackName}}))}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async load(){let e;if(this.transitionState(Fn),this._stats.recordLoadStart(),this.log.info("Connecting to %s",this.config.url),this.emitter.emit("session_connecting",{type:"session_connecting",url:this.config.url}),this.config.connection?(e=this.config.connection,this._adapterOwned=!1):(e=this.config.createConnection?this.config.createConnection():this.createDefaultConnection(),this._adapterOwned=!0),this.connection=e,this.wireConnection(e),this.catalogManager=new pr(kr(this.config.namespace)),this.qualityController=new mr({autoQuality:this.config.autoQuality,startLevel:this.config.startLevel,...this.config.capLevelToResolution?{capLevelToResolution:this.config.capLevelToResolution}:{},qualitySwitchCooldownMs:this.config.qualitySwitchCooldownMs,clock:this.clock}),this.subscriptionManager=new gr,this.bandwidthEstimator=new Is,this.config.draftVersion&&(this.subscriptionManager.draftVersion=this.config.draftVersion),this.config.objectTransform&&(this.subscriptionManager.objectTransform=this.config.objectTransform),this.config.extensionParser&&(this.subscriptionManager.extensionParser=this.config.extensionParser),this.subscriptionManager.onObject=(e,t,i,s)=>{if(this.pendingVideoSwitch&&"video"===e&&t===this.pendingVideoSwitch.newTrackName)return this.switchStagingBuffer.push({obj:i,headers:s}),1===this.switchStagingBuffer.length&&(this.switchStagingTimeout=setTimeout(()=>{this.log.warn("[SWITCH] keyframe timeout — force-completing after %dms",Ir),this.completePendingVideoSwitch()},Ir)),void(0n===i.objectId?this.completePendingVideoSwitch():this.switchStagingBuffer.length>=Rr&&(this.log.warn("[SWITCH] staging overflow (%d objects) — force-completing",Rr),this.completePendingVideoSwitch()));if("video"===e?this.log.info('[OBJ] %s "%s" group=%s obj=%s alias=%s %dB',e,t,i.groupId,i.objectId,i.trackAlias,"data"===i.kind&&i.payload?i.payload.byteLength:0):this.log.debug("Object %s group=%s obj=%s (%s, %dB)",e,i.groupId,i.objectId,i.kind,"data"===i.kind&&i.payload?i.payload.byteLength:0),this._stats.recordFirstObjectReceived(),"data"===i.kind){const t=i.payload?i.payload.byteLength:0;if(this._stats.recordMediaObject(t),"video"===e&&t>0){const e=BigInt(i.groupId);e!==this.bwEstimatorGroupId?(this.bwEstimatorGroupBytes>0&&this.bandwidthEstimator?.recordGroup(this.bwEstimatorGroupBytes,this.clock.now()),this.bwEstimatorGroupId=e,this.bwEstimatorGroupBytes=t):this.bwEstimatorGroupBytes+=t}}else this._stats.recordGapObject();if(this.emitter.emit("media_object",{type:"media_object",mediaType:e,trackName:t,groupId:BigInt(i.groupId),objectId:BigInt(i.objectId),kind:i.kind,..."data"===i.kind&&i.payload?{payload:i.payload}:{},..."data"===i.kind&&i.extensions?{extensions:i.extensions}:{},..."gap"===i.kind?{status:BigInt(i.status??0n)}:{},...void 0!==s.captureTimestamp?{captureTimestamp:s.captureTimestamp}:{},...void 0!==s.videoFrameMarking?.independent?{isKeyframe:s.videoFrameMarking.independent}:{}}),this.switchInProgress&&this.pendingVideoSwitch&&"video"===e&&t===this.pendingVideoSwitch.oldTrackName)return;if(this.stateMachine.state===qn)return;const n="video"===e?this.videoPipeline:this.audioPipeline;n?.pushObject(i,s)},this.subscriptionManager.onCmafObject=(e,t,i)=>{if(this._stats.recordFirstObjectReceived(),"data"===i.kind){const t=i.payload?i.payload.byteLength:0;this._stats.recordMediaObject(t),"video"===e&&t>0&&this.bandwidthEstimator?.recordGroup(t,this.clock.now())}else this._stats.recordGapObject();if(this.emitter.emit("media_object",{type:"media_object",mediaType:e,trackName:t,groupId:BigInt(i.groupId),objectId:BigInt(i.objectId),kind:i.kind,..."data"===i.kind&&i.payload?{payload:i.payload}:{},..."gap"===i.kind?{status:BigInt(i.status??0n)}:{}}),"data"!==i.kind||!i.payload)return;if(this.stateMachine.state===qn)return;if(!this.cmafInitialized)return void("video"===e&&0n===BigInt(i.objectId)&&this.log.debug("[CMAF] gate: cmafInitialized=false, dropping %s g=%s o=%s %dB (assembler=%s, mediaSource=%s)",e,String(i.groupId),String(i.objectId),i.payload.byteLength,this.cmafAssembler?"exists":"null",this.mediaSource?"exists":"null"));if("video"===e&&!this.cmafVideoSynced){if(!(BigInt(i.objectId)<=1n))return;this.cmafVideoSynced=!0,this.log.debug("[CMAF] video synced at g=%s o=%s",String(i.groupId),String(i.objectId))}if(this.pendingVideoSwitch&&"video"===e&&t===this.pendingVideoSwitch.newTrackName)return this.cmafSwitchStagingBuffer.push({trackName:t,mediaType:e,groupId:BigInt(i.groupId),payload:i.payload}),null===this.switchStagingTimeout&&(this.switchStagingTimeout=setTimeout(()=>{this.log.warn("[SWITCH] CMAF keyframe timeout — force-completing after %dms",Ir),this.completePendingVideoSwitch()},Ir)),void(0n===BigInt(i.objectId)?this.completePendingVideoSwitch():this.cmafSwitchStagingBuffer.length>=Rr&&(this.log.warn("[SWITCH] CMAF staging overflow (%d objects) — force-completing",Rr),this.completePendingVideoSwitch()));const s=BigInt(i.groupId);if(this.mediaSource&&"getCommittedGroupFloor"in this.mediaSource){const i=this.mediaSource.getCommittedGroupFloor(e,t);if(void 0!==i&&s{this.handleMalformedTrack(e,i,s)},this.subscriptionManager.onTimelineObject=(e,t)=>{if("data"!==t.kind||!t.payload)return;if(!this.timelineState)return;const i=this.timelineState.entries.length;this.timelineState=Cr(this.timelineState,t.payload);const s=wr(this.timelineState);0===i?(this.emitter.emit("timeline_loaded",{type:"timeline_loaded",trackName:e,entryCount:this.timelineState.entries.length,...void 0!==s?{duration:s}:{}}),void 0!==s&&this.emitter.emit("duration_changed",{type:"duration_changed",durationMs:s})):this.emitter.emit("timeline_updated",{type:"timeline_updated",trackName:e,entryCount:this.timelineState.entries.length,...void 0!==s?{duration:s}:{}})},this.subscriptionManager.onEventTimelineObject=(e,t)=>{if("data"!==t.kind||!t.payload)return;const i=this.catalogManager?.currentState,s=i?.tracks.find(t=>t.name===e),n=s?.eventType??"";try{if("org.ietf.moq.cmsf.sap"===n){const i=Dn(t.payload).map((e,t)=>{if(!("l"in e.index))throw new Error(`SAP timeline record[${t}]: index MUST be 'l' (location), not '${"t"in e.index?"t":"m"}' (CMSF §3.6.1)`);const i=e.data;if(!Array.isArray(i)||2!==i.length||"number"!=typeof i[0]||"number"!=typeof i[1])throw new Error(`SAP timeline record[${t}]: data MUST be an array of two integers [sapType, ept] (CMSF §3.6.1)`);const s=i[0],n=i[1];if(s<0||s>3||!Number.isInteger(s))throw new Error(`SAP timeline record[${t}]: SAP type must be 0, 1, 2, or 3; got ${s} (CMSF §3.6.1)`);return{location:e.index.l,sapType:s,earliestPresentationTimeMs:n}});this.emitter.emit("sap_event",{type:"sap_event",trackName:e,entries:i})}else{const i=Dn(t.payload);this.emitter.emit("event_timeline",{type:"event_timeline",trackName:e,eventType:n,records:i})}}catch(t){this.log.warn('Failed to parse eventtimeline object for track "%s": %s',e,t instanceof Error?t.message:String(t))}},this.subscriptionManager.onInitObject=(e,t)=>{if(this.log.debug("[INIT] onInitObject: track=%s kind=%s payloadLen=%d mediaSource=%s",e,t.kind,"data"===t.kind&&t.payload?t.payload.byteLength:0,this.mediaSource?"exists":"null"),"data"!==t.kind||!t.payload)return;if(!this.mediaSource)return;const i=this.catalogManager?.currentState;if(!i)return;const s=i.tracks.find(t=>"video"===t.role&&t.initTrack===e),n=i.tracks.find(t=>"audio"===t.role&&t.initTrack===e),r={};s?.codec&&(r.video={codec:s.codec,initData:t.payload}),n?.codec&&(r.audio={codec:n.codec,initData:t.payload}),this.initSegmentByTrack.set(e,t.payload);const a=this.pendingInitTrackSubs.get(e);a&&(this.pendingInitTrackSubs.delete(e),a.resolve(t.payload));const o=this.initTrackRequestIds.get(e);if(void 0!==o){this.initTrackRequestIds.delete(e);const t=this.activeSubscriptions.get(o),i=t?.trackAlias??o;this.activeSubscriptions.delete(o),this.pendingMediaSubs.delete(o),this.subscriptionManager?.unregisterTrack(i),this.connection?.unsubscribe(K(o)).catch(()=>{})}const c=this.cmafInitialized;if(c||(this.mediaSource.initialize(r),this.cmafInitialized=!0,this.cmafVideoSynced=!1,s?.codec&&(this.currentVideoCodec=s.codec)),c)return;const d=this.mediaSource,h={video:!1,audio:!1};if(!this.config.createCmafAssembler)throw new Error("CMAF tracks require createCmafAssembler in MoqtPlayerConfig");this.cmafAssembler=this.config.createCmafAssembler({onSegment:(e,t,i,s)=>{h[e]||(h[e]=!0,"setTimestampOffset"in d&&d.setTimestampOffset(e,0)),d.appendChunk(e,t,i,s)},onDiscontinuity:(e,t)=>{"clearTimeline"in d&&d.clearTimeline(e,t)}}),s?.codec&&this.cmafAssembler.setInitSegment?.("video",t.payload),n?.codec&&this.cmafAssembler.setInitSegment?.("audio",t.payload),this._stats.recordDecoderConfigured(),this.log.info('Init track "%s" received (%d bytes), MediaSource initialized',e,t.payload.byteLength)},this._adapterOwned){const t=br(this.config),i=await this.config.createTransport(vr(this.config));if(this._handshakeRttMs=i.handshakeRttMs,void 0!==this._handshakeRttMs){const e=this._handshakeRttMs<1?"LAN (2 frames)":this._handshakeRttMs<5?"near-LAN (3 frames)":this._handshakeRttMs<50?"WAN (8 frames)":"long-haul (12 frames)";this.log.info("Handshake RTT: %.1fms → startup buffer: %s",this._handshakeRttMs,e)}const s=e.connect(i,t);if(this.config.connectionTimeoutMs){const e=this.config.connectionTimeoutMs;await Promise.race([s,new Promise((t,i)=>setTimeout(()=>i(new Error(`Connection timeout after ${e}ms`)),e))])}else await s;const n=e.session?.peerMaxRequestId??"unknown";this.log.info("Session established (peer MAX_REQUEST_ID=%s)",n)}else this.log.info("Using externally owned adapter (already connected)");this._stats.recordTransportConnected(),this._stats.recordSetupComplete(),this.emitter.emit("session_established",{type:"session_established",selectedVersion:0n}),this.config.catalog||this.config.knownTracks||this.watchdog.expect("catalog_received",1e4);const t=Ar(this.config.namespace,this.enc);{const e=new TextDecoder,i=t.map(t=>`"${e.decode(t)}"(${t.length}b)`).join(", ");this.log.info('Subscribe: namespace fields=[%s], catalog track="%s"',i,"catalog")}if(this.config.catalog){const e={version:1,tracks:[...this.config.catalog.tracks]};this.catalogReceived=!0,this._catalogState=e,this._stats.recordCatalogReceived(),this.emitter.emit("catalog_received",{type:"catalog_received",catalog:e}),await this.subscribeToMediaTracks(e)}else if(this.config.knownTracks){const i=this.config.knownTracks,s=i.video&&!this.config.disableVideo,n=i.audio&&!this.config.disableAudio;this._stats.setTrackInfo(s?Pr({codec:i.video.codec,width:i.video.width,height:i.video.height}):void 0,n?Pr({codec:i.audio.codec}):void 0),this.createPipelinesFromTrackInfo({video:s?Pr({codec:i.video.codec,width:i.video.width,height:i.video.height,initData:i.video.initData}):void 0,audio:n?Pr({codec:i.audio.codec,samplerate:i.audio.samplerate,channels:i.audio.channels,initData:i.audio.initData}):void 0,isLive:!0});const r=Sr(this.config),a=[],o={subscriptionFilter:{type:"AbsoluteStart",startGroup:K(0n),startObject:K(0n)}};a.push((async()=>{const i=await e.subscribe(t,this.enc.encode("catalog"),o);this.catalogRequestId=BigInt(i)})()),this._mediaSubsExpected=0,this._mediaSubsOk=0,this._mediaSubsFailed=0;for(const[o,c]of[["video",s?i.video:void 0],["audio",n?i.audio:void 0]])c&&a.push((async()=>{if(!this.hooks.beforeSubscribe.run({trackName:c.name,mediaType:o}))return;this._mediaSubsExpected++;const i=r??Nr(!0),s=await e.subscribe(t,this.enc.encode(c.name),i),n=BigInt(s);this.subscriptionManager&&(this.activeSubscriptions.set(n,{trackName:c.name,mediaType:o,trackAlias:n}),this.subscriptionManager.registerTrack(n,c.name,o),this.pendingMediaSubs.set(n,{trackName:c.name,mediaType:o}),this.log.info('Subscribe %s "%s" requestId=%s (pre-known)',o,c.name,n),this.emitter.emit("track_subscribed",{type:"track_subscribed",trackName:c.name,mediaType:o,requestId:n}))})());await Promise.all(a)}else{const i=this.enc.encode("catalog"),s=await e.subscribe(t,i,{subscriptionFilter:{type:"AbsoluteStart",startGroup:K(0n),startObject:K(0n)}});this.catalogRequestId=BigInt(s)}}play(){this.log.info("play()");const e=this.stateMachine.state;this.transitionState(Vn),this._stats.recordPlayStart(),e===qn&&(this.videoPipeline?.reset(),this.audioPipeline?.reset(),this.syncController?.reset(),this.recoveryController?.reset?.()),this.startTicking(),e===qn&&this.connection&&this.sendForwardUpdate(1)}pause(){this.log.info("pause()"),this.transitionState(qn),this._stats.recordPlayStop(),this.stopTicking(),this.commandDispatcher?.flush(),this.connection&&this.sendForwardUpdate(0)}sendForwardUpdate(e){if(this.connection)for(const[t]of this.activeSubscriptions)this.connection.requestUpdate(K(t),{forward:e}).catch(i=>{const s=i instanceof Error?i:new Error(String(i));this.log.warn("REQUEST_UPDATE forward:%d failed for reqId=%s: %s",e,t,s.message),this.emitError(cr("degraded","connection",Zn,`REQUEST_UPDATE forward:${e} failed: ${s.message}`,{cause:s,context:{requestId:t,forward:e}}))})}async seek(e){const t=this.stateMachine.state;if(t!==Vn&&t!==qn)throw new Error(`Cannot seek in state ${t}; expected playing or paused`);if(!this.timelineState||0===this.timelineState.entries.length)throw new Error("Cannot seek: no media timeline loaded");const i=function(e,t){const i=function(e,t){if(0===e.length)return;let i=0,s=e.length-1;if(!(t>>1;e[n].mediaPts<=t?i=n+1:s=n-1}return e[s].location}}(e.entries,t);if(i)return{groupId:i[0],objectId:i[1]}}(this.timelineState,e);if(!i)return void this.emitError(cr("degraded","player",nr,`Seek target ${e}ms is before the start of the timeline`,{context:{timeMs:e}}));this.emitter.emit("seeking",{type:"seeking",targetTimeMs:e});const s=BigInt(i.groupId);if(this.videoPipeline?.reset(s),this.audioPipeline?.reset(s),this.syncController?.reset(),this.commandDispatcher?.flush(),this.connection)for(const[t]of this.activeSubscriptions)t!==this.timelineRequestId&&this.connection.requestUpdate(K(t),{subscriptionFilter:{type:"AbsoluteStart",startGroup:K(BigInt(i.groupId)),startObject:K(BigInt(i.objectId))}}).catch(s=>{const n=s instanceof Error?s:new Error(String(s));this.log.warn("REQUEST_UPDATE seek failed for reqId=%s: %s",t,n.message),this.emitError(cr("degraded","connection",nr,`Seek REQUEST_UPDATE failed: ${n.message}`,{cause:n,context:{requestId:t,timeMs:e,groupId:i.groupId}}))});this.emitter.emit("seeked",{type:"seeked",actualTimeMs:e,groupId:i.groupId,objectId:i.objectId})}async migrate(e){const t=this.connection;if(this.connection=e,this.wireConnection(e),this.catalogReceived=!1,this.catalogTrackAlias=null,this.catalogRequestId=null,this.activeFetches.clear(),this.fetchStreamAliases.clear(),this.rejectPendingCatalogFetches("Session migrated — fetchCatalog cancelled"),!this.config.createTransport)throw new Error("Cannot migrate: createTransport not configured (external adapter mode)");const i=br(this.config),s=await this.config.createTransport(vr(this.config));await e.connect(s,i);const n=Ar(this.config.namespace,this.enc),r=this.enc.encode("catalog"),a=await e.subscribe(n,r,{subscriptionFilter:{type:"AbsoluteStart",startGroup:K(0n),startObject:K(0n)}});this.catalogRequestId=BigInt(a),t&&await t.close(),this._stats.recordReconnect(),this.log.info("Session migrated"),this.emitter.emit("session_migrated",{type:"session_migrated"})}async migrateToUrl(e,t){const i=this.connection;this.connection=e,this.wireConnection(e),this.catalogReceived=!1,this.catalogTrackAlias=null,this.catalogRequestId=null,this.activeFetches.clear(),this.fetchStreamAliases.clear(),this.rejectPendingCatalogFetches("Session migrated — fetchCatalog cancelled");const s=br(this.config),n=await this.config.createTransport(vr(this.config,t));await e.connect(n,s);const r=Ar(this.config.namespace,this.enc),a=this.enc.encode("catalog"),o=await e.subscribe(r,a,{subscriptionFilter:{type:"AbsoluteStart",startGroup:K(0n),startObject:K(0n)}});this.catalogRequestId=BigInt(o),i&&await i.close(),this._stats.recordReconnect(),this.log.info("Session migrated to %s",t),this.emitter.emit("session_migrated",{type:"session_migrated"})}async fetch(e,t){if(!this.connection)throw new Error("Player not loaded");const i=Ar(this.config.namespace,this.enc),s=this.enc.encode(e),n={startGroup:K(BigInt(t.startGroup)),startObject:K(BigInt(t.startObject)),endGroup:K(BigInt(t.endGroup)),endObject:K(BigInt(t.endObject))},r=await this.connection.fetch(i,s,n),a=BigInt(r);let o="video",c=a;for(const[,t]of this.activeSubscriptions)if(t.trackName===e&&"mediatimeline"!==t.mediaType&&"eventtimeline"!==t.mediaType){o=t.mediaType,c=t.trackAlias;break}return this.activeFetches.set(a,{trackName:e,mediaType:o,trackAlias:c}),r}async fetchCancel(e){if(!this.connection)throw new Error("Player not loaded");await this.connection.fetchCancel(K(e)),this.activeFetches.delete(BigInt(e))}async fetchCatalog(e){if(!this.connection)throw new Error("Player not loaded");const t=e?.group??0n,i=e?.object??0n,s=e?.timeoutMs??5e3,n=Ar(this.config.namespace,this.enc),r=this.enc.encode("catalog"),a={startGroup:K(t),startObject:K(i),endGroup:K(t),endObject:K(i)},o=await this.connection.fetch(n,r,a),c=BigInt(o);return new Promise((e,t)=>{const i=setTimeout(()=>{const e=this.pendingCatalogFetches.get(c);e&&(this.cleanupCatalogFetch(c),this.connection?.fetchCancel(K(c)).catch(()=>{}),e.reject(new Error(`fetchCatalog timed out after ${s}ms`)))},s);this.pendingCatalogFetches.set(c,{resolve:e,reject:t,timeout:i})})}handleCatalogFetchObject(e,t){if(this.pendingCatalogFetches.get(e))if("gap"!==t.kind)if(t.payload&&0!==t.payload.byteLength)try{const i=new pr(kr(this.config.namespace)).processCatalogObject(t.payload);this.settleCatalogFetch(e,{ok:!0,state:i})}catch(t){this.settleCatalogFetch(e,{ok:!1,error:t instanceof Error?t:new Error(String(t))})}else this.settleCatalogFetch(e,{ok:!1,error:new Error("fetchCatalog: empty payload")});else this.settleCatalogFetch(e,{ok:!1,error:new Error("fetchCatalog: server returned gap (object not found in requested range)")})}rejectPendingCatalogFetches(e){for(const[,t]of this.pendingCatalogFetches)clearTimeout(t.timeout),t.reject(new Error(e));this.pendingCatalogFetches.clear(),this.catalogFetchStreams.clear()}cleanupCatalogFetch(e){const t=this.pendingCatalogFetches.get(e);t&&(clearTimeout(t.timeout),this.pendingCatalogFetches.delete(e));for(const[t,i]of this.catalogFetchStreams)i===e&&this.catalogFetchStreams.delete(t)}settleCatalogFetch(e,t){const i=this.pendingCatalogFetches.get(e);i&&(this.cleanupCatalogFetch(e),t.ok?i.resolve(t.state):i.reject(t.error))}async subscribeNamespace(e){if(!this.connection)throw new Error("Player not loaded");const t=Ar(e,this.enc),i=await this.connection.subscribeNamespace(t);return BigInt(i)}async cancelNamespace(e){if(!this.connection)throw new Error("Player not loaded");await this.connection.cancelNamespace(K(e))}async queryTrackStatus(e){if(!this.connection)throw new Error("Player not loaded");const t=Ar(this.config.namespace,this.enc),i=this.enc.encode(e),s=await this.connection.trackStatus(t,i),n=BigInt(s);return new Promise((e,t)=>{this.pendingTrackStatuses.set(n,{resolve:e,reject:t})})}tick(){this.syncResetThisTick=!1,this.audioPipeline?.tick(),this.videoPipeline?.tick(),this.checkBandwidthAdaptation()}lastAbrDownshiftUs=0;lastLocStallUs=0;lastLocDecodeErrorUs=0;lastLocPartialAbandonUs=0;lastLocQueuePressureUs=0;locHealthyRenderCount=0;static LOC_MIN_HEALTHY_RENDERS=5;consecutiveStallCount=0;videoRecoveryActive=!1;videoRecoveryHealthyRenders=0;static RECOVERY_HEALTHY_THRESHOLD=3;static ABR_UPSHIFT_STABILITY_US=15e6;isLocDeliveryHealthy(){const e=this.clock.now(),t=Lr.ABR_UPSHIFT_STABILITY_US;return!(e-Math.max(this.lastLocStallUs,this.lastLocDecodeErrorUs,this.lastLocPartialAbandonUs,this.lastLocQueuePressureUs,this.lastAbrDownshiftUs)1.5*(s?s.bitrateKbps:0)?this.bufferAbrController.lowThresholdUs:t}else e=t}else e=this.bufferAbrController.lowThresholdUs;const t=this.bandwidthEstimator?.getEstimateKbps()??0,i=this.bufferAbrController.evaluate({bufferDepthUs:e,bandwidthEstimateKbps:t});if("hold"===i.action)return;if("upshift"===i.action){if(this.clock.now()-this.lastAbrDownshiftUs{this.log.warn('ABR %s to "%s" failed: %s',i,r.name,e)})}}async destroy(){if(!this._destroyed){this._destroyed=!0,this.log.info("destroy()"),this._stats.recordPlayStop(),this.stopTicking(),this.pendingMediaSubs.clear(),this.activeFetches.clear(),this.fetchStreamAliases.clear(),this.pendingObjectsByAlias.clear(),this.pendingVideoSwitch=null,this.switchInProgress=!1,this.switchStagingBuffer=[],this.cmafSwitchStagingBuffer=[],null!==this.switchStagingTimeout&&(clearTimeout(this.switchStagingTimeout),this.switchStagingTimeout=null);for(const[,e]of this.pendingTrackStatuses)e.reject(new Error("Player destroyed"));if(this.pendingTrackStatuses.clear(),this.rejectPendingCatalogFetches("Player destroyed"),this.announcedNamespaces.clear(),this.commandDispatcher?.destroy(),this.commandDispatcher=null,this.watchdog.destroy(),this.cmafAssembler?.destroy(),this.cmafAssembler=null,this.mediaSource?.destroy(),this.mediaSource=null,this.videoPipeline=null,this.audioPipeline=null,this.syncController=null,this.recoveryController=null,this.pipelinesCreated=!1,this.subscriptionManager=null,this.catalogManager=null,this.qualityController=null,this.bandwidthEstimator=null,this.connection){if(this._adapterOwned)await this.connection.close();else{for(const[e]of this.activeSubscriptions)try{await this.connection.unsubscribe(K(e))}catch{}if(null!==this.catalogRequestId)try{await this.connection.unsubscribe(K(this.catalogRequestId))}catch{}delete this.connection.onMessage,delete this.connection.onObject,delete this.connection.onClose,delete this.connection.onError,delete this.connection.onDataStream,delete this.connection.onStreamClosed,delete this.connection.onDatagram,delete this.connection.onNamespaceMessage,delete this.connection.onQlogEvent}this.connection=null}this.activeSubscriptions.clear(),this.stateMachine.state!==Gn&&this.transitionState(Gn),this.emitter.removeAllListeners()}}requestSubscribe(e,t){const i={trackName:e,mediaType:t};return this.hooks.beforeSubscribe.run(i)}transitionState(e){const t=this.stateMachine.state;this.stateMachine.transition(e),this.emitter.emit("state_changed",{type:"state_changed",from:t,to:e})}emitError(e){const t=this.config.errorFilter?this.config.errorFilter(e):e;if(!t)return;"fatal"===t.severity?this.log.error("Error [%s/%s] 0x%s: %s",t.severity,t.source,t.code.toString(16),t.message):this.log.warn("Error [%s/%s] 0x%s: %s",t.severity,t.source,t.code.toString(16),t.message),this.emitter.emit("error",{type:"error",error:t});const i=t.cause??new Error(t.message);this.emitter.emit("session_error",{type:"session_error",error:i})}classifyMoqtConnectionError(e){if(e instanceof ji){const t=e.isFatal?"fatal":"degraded",i=this.connectionErrorSourceToCode(e.errorSource),s={};return void 0!==e.protocolCode&&(s.protocolCode=e.protocolCode),void 0!==e.streamId&&(s.streamId=e.streamId),{severity:t,code:i,...Object.keys(s).length>0?{context:s}:{}}}return{severity:"fatal",code:zn}}connectionErrorSourceToCode(e){switch(e){case"control":default:return zn;case"data":return Yn;case"datagram":return Jn;case"transport":return Xn}}wireConnection(e){!function(e,t){e.onMessage=e=>{t.onControlMessage(e)},e.onClose=(e,i)=>{t.onClose(e,i)},e.onError=e=>{t.onError(e)},e.onObject=(e,i)=>{t.onObject(e,i)},e.onStreamClosed=(e,i)=>{t.onStreamClosed(e,i)},e.onDataStream=(e,i)=>{t.onDataStream(e,i)},e.onNamespaceMessage=(e,i)=>{t.onNamespaceMessage(e,i)},e.onDatagram=e=>{t.onDatagram(e)},t.onQlogEvent&&(e.onQlogEvent=t.onQlogEvent)}(e,{onControlMessage:e=>this.handleControlMessage(e),onClose:(e,t)=>{this.log.info("[SESSION] closed: error=0x%s reason=%s",e?.toString(16)??"none",t??"clean"),this.rejectPendingCatalogFetches(void 0!==t?`Session closed: ${t}`:"Session closed"),this.emitter.emit("session_closed",Pr({type:"session_closed",error:e,reason:t}))},onError:e=>{const t=this.classifyMoqtConnectionError(e);this.emitError(cr(t.severity,"connection",t.code,e.message,Pr({cause:e,context:t.context})))},onObject:(e,t)=>{const i=this.catalogFetchStreams.get(e);if(void 0!==i)return void this.handleCatalogFetchObject(i,t);const s=this.fetchStreamAliases.get(e);if(void 0!==s){if(void 0!==this.subscriptionManager?.getMediaType(s)){const i={...t,trackAlias:K(s)};this.subscriptionManager.routeObject(e,i)}return}const n=BigInt(t.trackAlias);if(void 0!==this.subscriptionManager?.getMediaType(n))return this.watchdog.fulfill("first_media_object"),void this.subscriptionManager.routeObject(e,t);if(null!==this.catalogTrackAlias&&n===this.catalogTrackAlias)return void this.handleCatalogObject(t);const r=this.pendingObjectsByAlias.get(n)??[];r.length{const i=this.catalogFetchStreams.get(e);void 0!==i&&this.settleCatalogFetch(i,{ok:!1,error:new Error(void 0!==t?`fetchCatalog: stream reset (code 0x${t.toString(16)})`:"fetchCatalog: stream closed without object")}),void 0!==t&&this.log.debug("Data stream %s reset with code 0x%s",e,t.toString(16))},onDataStream:(e,t)=>{if("fetch"===t.type){const i=BigInt(t.header.requestId);if(this.pendingCatalogFetches.has(i))return void this.catalogFetchStreams.set(e,i);const s=this.activeFetches.get(i);s&&this.fetchStreamAliases.set(e,s.trackAlias)}},onNamespaceMessage:(e,t)=>{switch(t.type){case"NAMESPACE":this.emitter.emit("namespace_discovered",{type:"namespace_discovered",requestId:e,namespaceSuffix:t.trackNamespaceSuffix});break;case"NAMESPACE_DONE":this.emitter.emit("namespace_done",{type:"namespace_done",requestId:e,namespaceSuffix:t.trackNamespaceSuffix});break;case"PUBLISH_NAMESPACE":{const i=t.trackNamespace;this.announcedNamespaces.set(e,i),this.emitter.emit("namespace_announced",{type:"namespace_announced",requestId:e,trackNamespace:i});break}case"PUBLISH_NAMESPACE_DONE":this.announcedNamespaces.delete(e),this.emitter.emit("namespace_announcement_done",{type:"namespace_announcement_done",requestId:e,...t.trackNamespace?{trackNamespace:t.trackNamespace}:{}})}},onDatagram:e=>{const t=BigInt(e.trackAlias);if(void 0===this.subscriptionManager?.getMediaType(t))return;this.log.debug("Datagram alias=%s group=%s obj=%s",t,e.groupId,e.objectId);const i=void 0!==e.status?{kind:"gap",trackAlias:e.trackAlias,groupId:e.groupId,subgroupId:K(0n),objectId:e.objectId,status:e.status}:{kind:"data",trackAlias:e.trackAlias,groupId:e.groupId,subgroupId:K(0n),objectId:e.objectId,publisherPriority:e.publisherPriority,extensions:e.extensions,payload:e.payload};this.subscriptionManager.routeObject(0n,i)},...this.config.onQlogEvent?{onQlogEvent:this.config.onQlogEvent}:{}})}handleControlMessage(e){!function(e,t){if("undefined"!=typeof console){const i="requestId"in e?e.requestId:void 0,s=void 0!==i?String(i):"N/A",n=void 0!==i?t.activeSubscriptions.get(BigInt(i)):void 0,r=n?` track=${n.trackName}`:"",a="SUBSCRIBE_OK"===e.type?` alias=${String(e.trackAlias)}`:"PUBLISH_DONE"===e.type?` reason="${e.errorReason??""}"`:"REQUEST_ERROR"===e.type?` code=0x${BigInt(e.errorCode).toString(16)} reason="${e.errorReason??""}"`:"";t.log.debug("[CTRL] %s reqId=%s%s%s",e.type,s,r,a)}switch(e.type){case"GOAWAY":t.log.info("GOAWAY received, uri=%s",e.newSessionUri??"(none)");for(const[e]of t.activeSubscriptions)t.adapter?.unsubscribe(K(e));t.activeSubscriptions.clear(),t.emitEvent({type:"session_goaway",newSessionUri:e.newSessionUri}),t.onGoaway(e.newSessionUri);break;case"SUBSCRIBE_OK":{const i=BigInt(e.requestId),s=BigInt(e.trackAlias);t.log.debug("SUBSCRIBE_OK reqId=%s alias=%s",i,s),null!==t.catalogRequestId&&i===t.catalogRequestId&&(t.setCatalogTrackAlias(s),void 0!==t.subscriptionManager?.getMediaType(s)&&(t.log.debug("Catalog alias=%s collides with optimistic media registration — evicting",s),t.subscriptionManager.unregisterTrack(s)));const n=t.pendingMediaSubs.get(i);if(n){if(t.pendingMediaSubs.delete(i),"video"!==n.mediaType&&"audio"!==n.mediaType||t.onMediaSubscribeOk?.(i,n.trackName,n.mediaType),s!==i){const e=t.subscriptionManager?.getMediaType(s);if(void 0!==e)t.log.warn("SUBSCRIBE_OK alias collision: alias=%s already registered (type=%s), keeping original for track=%s",s,e,n.trackName);else{t.log.debug("SUBSCRIBE_OK alias remap: reqId=%s → alias=%s track=%s",i,s,n.trackName),t.subscriptionManager?.unregisterTrack(i),t.subscriptionManager?.registerTrack(s,n.trackName,n.mediaType,n.packaging);const e=t.activeSubscriptions.get(i);e&&(e.trackAlias=s)}}t.onAliasResolved?.(s),s!==i&&t.onAliasResolved?.(i)}break}case"PUBLISH_DONE":{const i=BigInt(e.requestId),s=t.activeSubscriptions.get(i);t.log.debug("PUBLISH_DONE reqId=%s sub=%s",i,s?s.trackName:"(none)"),s&&(t.log.info('PUBLISH_DONE "%s": %s',s.trackName,e.errorReason??"(no reason)"),t.activeSubscriptions.delete(i),t.subscriptionManager?.unregisterTrack(s.trackAlias),t.onPublishDone?t.onPublishDone(i,s.trackName,s.trackAlias,BigInt(e.statusCode),e.errorReason??""):t.emitEvent({type:"track_unsubscribed",trackName:s.trackName,reason:e.errorReason??""}));break}case"REQUEST_OK":{const i=BigInt(e.requestId),s=t.pendingTrackStatuses.get(i);s&&(t.pendingTrackStatuses.delete(i),s.resolve({requestId:i,parameters:e.parameters}));break}case"REQUEST_ERROR":{const i=BigInt(e.requestId);null!==t.catalogRequestId&&i===t.catalogRequestId&&(t.log.warn("Catalog subscription rejected: %s (code=0x%s)",e.errorReason,BigInt(e.errorCode).toString(16)),t.clearCatalogState());const s=t.pendingTrackStatuses.get(i);s&&(t.pendingTrackStatuses.delete(i),s.reject(new Error(`TRACK_STATUS failed: ${e.errorReason} (code=0x${BigInt(e.errorCode).toString(16)})`)));const n=t.pendingMediaSubs.get(i);if(n&&("video"===n.mediaType||"audio"===n.mediaType)){t.pendingMediaSubs.delete(i);const s=t.activeSubscriptions.get(i),r=s?.trackAlias??i;t.activeSubscriptions.delete(i),t.subscriptionManager?.unregisterTrack(r),t.onMediaSubscribeError?.(i,n.trackName,n.mediaType,e.errorReason??"",BigInt(e.errorCode))}t.onCatalogFetchError?.(i,e.errorReason,BigInt(e.errorCode));break}}}(e,{adapter:this.connection,activeSubscriptions:this.activeSubscriptions,pendingMediaSubs:this.pendingMediaSubs,pendingTrackStatuses:this.pendingTrackStatuses,catalogRequestId:this.catalogRequestId,catalogTrackAlias:this.catalogTrackAlias,subscriptionManager:this.subscriptionManager,log:this.log,emitEvent:e=>this.emitter.emit(e.type,e),setCatalogTrackAlias:e=>{this.catalogTrackAlias=e,this.replayPendingObjects(e)},clearCatalogState:()=>{this.catalogTrackAlias=null,this.catalogRequestId=null},onAliasResolved:e=>{this.replayPendingObjects(e)},onGoaway:e=>{if(this.config.createConnection){const t=e||this.config.url,i=this.config.createConnection();this.migrateToUrl(i,t)}},onPublishDone:(e,t,i,s,n)=>{if(s===BigInt(ee.TOO_FAR_BEHIND))return this.log.warn('PUBLISH_DONE(TOO_FAR_BEHIND) "%s": resubscribing from live edge',t),void this.resubscribeAfterPublishDone(t);this.emitter.emit("track_unsubscribed",{type:"track_unsubscribed",trackName:t,reason:n})},onMediaSubscribeOk:(e,t,i)=>{this._mediaSubsOk++},onMediaSubscribeError:(e,t,i,s,n)=>{this._mediaSubsFailed++,this.emitter.emit("track_subscribe_failed",{type:"track_subscribe_failed",trackName:t,mediaType:i,requestId:e,errorCode:n,reason:s}),this.emitError(cr("degraded","subscription",ar,`Track "${t}" refused: ${s} (code=0x${n.toString(16)})`)),this._mediaSubsFailed===this._mediaSubsExpected&&0===this._mediaSubsOk&&this._mediaSubsExpected>0&&this.emitError(cr("fatal","subscription",or,"All media track subscriptions refused — no playable content"))},onCatalogFetchError:(e,t,i)=>{this.settleCatalogFetch(e,{ok:!1,error:new Error(`fetchCatalog failed: ${t} (code=0x${i.toString(16)})`)})}})}replayPendingObjects(e){const t=this.pendingObjectsByAlias.get(e);if(t&&0!==t.length){this.pendingObjectsByAlias.delete(e);for(const{streamId:e,obj:i}of t){const t=BigInt(i.trackAlias);void 0!==this.subscriptionManager?.getMediaType(t)?this.subscriptionManager.routeObject(e,i):null!==this.catalogTrackAlias&&t===this.catalogTrackAlias&&this.handleCatalogObject(i)}}}handleCatalogObject(e){if("gap"!==e.kind){if(e.payload&&e.payload.byteLength>0){let t=null;try{t=(new TextDecoder).decode(e.payload)}catch{}this.emitter.emit("catalog_raw",{type:"catalog_raw",payload:e.payload,text:t})}try{const t=this.catalogManager.processCatalogObject(e.payload);this.catalogReceived?(this.log.info("Catalog updated"),this.emitter.emit("catalog_updated",{type:"catalog_updated",catalog:t})):(this.catalogReceived=!0,this._catalogState=t,this._stats.recordCatalogReceived(),this.watchdog.fulfill("catalog_received"),this.watchdog.expect("first_media_object",2e4),this.log.info("Catalog received: %d tracks",t.tracks.length),this.emitter.emit("catalog_received",{type:"catalog_received",catalog:t}),this.pipelinesCreated?(this.qualityController=new mr({autoQuality:this.config.autoQuality,startLevel:this.config.startLevel,...this.config.capLevelToResolution?{capLevelToResolution:this.config.capLevelToResolution}:{},qualitySwitchCooldownMs:this.config.qualitySwitchCooldownMs,clock:this.clock}),this.qualityController.selectInitialTracks(t,Pr({videoConstraints:this.config.videoConstraints,audioConstraints:this.config.audioConstraints,...this.config.disableVideo?{disableVideo:!0}:{},...this.config.disableAudio?{disableAudio:!0}:{}})),this.validateKnownTracks(t)):this.subscribeToMediaTracks(t).catch(e=>{this.log.error("subscribeToMediaTracks failed: %s",e?.message??e),this.emitError(cr("fatal","player",rr,`Media subscription failed: ${e?.message??e}`,e instanceof Error?{cause:e}:{}))}))}catch(e){const t=this.catalogReceived?"degraded":"fatal",i=this.catalogReceived?sr:ir,s=e instanceof Error?e:new Error(String(e));this.emitError(cr(t,"catalog",i,s.message,{cause:s}))}}}validateKnownTracks(e){this.config.knownTracks&&function(e,t,i){if(e.video){const s=t.tracks.find(t=>t.name===e.video.name);s?s.codec&&e.video.codec!==s.codec&&i.warn('knownTracks: video codec mismatch — known="%s" catalog="%s"',e.video.codec,s.codec):i.warn('knownTracks: video track "%s" not found in catalog',e.video.name)}if(e.audio){const s=t.tracks.find(t=>t.name===e.audio.name);s?s.codec&&e.audio.codec!==s.codec&&i.warn('knownTracks: audio codec mismatch — known="%s" catalog="%s"',e.audio.codec,s.codec):i.warn('knownTracks: audio track "%s" not found in catalog',e.audio.name)}}(this.config.knownTracks,e,this.log)}createPipelinesFromTrackInfo(e){if(this.pipelinesCreated)return;const t=function(e,t,i,s,n){let r=null;const a="cmaf"===i.video?.packaging,o="cmaf"===i.audio?.packaging;if((a||o)&&e.createMediaSource){if(r=e.createMediaSource(),!(a&&i.video?.initTrack&&!i.video?.initData||o&&i.audio?.initTrack&&!i.audio?.initData)){const e={};a&&i.video?.codec&&(e.video={codec:i.video.codec,initData:i.video.initData?Uint8Array.from(atob(i.video.initData),e=>e.charCodeAt(0)):new Uint8Array(0)}),o&&i.audio?.codec&&(e.audio={codec:i.audio.codec,initData:i.audio.initData?Uint8Array.from(atob(i.audio.initData),e=>e.charCodeAt(0)):new Uint8Array(0)}),r.initialize(e)}r.onFirstFrame=()=>s.onFirstFrame(),r.onStall=e=>s.onStall(e),r.onError=e=>s.onDecodeError("video",e)}const c={gapTimeoutUs:1e3*e.gapTimeoutMs,driftThresholdUs:1e3*e.driftThresholdMs,maxBufferDepth:e.maxBufferDepth,adaptiveTolerance:!0,...void 0!==n?{handshakeRttMs:n}:{}},d=new rs(Er({driftThresholdUs:c.driftThresholdUs,dropThresholdUs:1e3*e.lateFrameThresholdMs,clock:t,targetLatencyMs:e.targetLatencyMs,maxCatchUpRate:e.maxCatchUpRate,catchUpThresholdMs:e.catchUpThresholdMs,catchUpRecoveryMs:e.catchUpRecoveryMs})),h=e.createRecoveryController?.(t)??new as({gapEscalationThreshold:e.maxConsecutiveGaps,maxDecodeErrors:e.maxDecodeErrors}),l=a?void 0:e.createVideoDecoder?.(),u=o?void 0:e.createAudioDecoder?.(),p=a?void 0:e.createRenderer?.(),m=o?void 0:e.createAudioOutput?.();let g=null;(l||u)&&(g=new fr(Er({videoDecoder:l,audioDecoder:u,renderer:p,audioOutput:m,videoCodec:i.video?.codec,videoWidth:i.video?.width,videoHeight:i.video?.height,audioCodec:i.audio?.codec,audioSampleRate:i.audio?.samplerate,audioChannels:i.audio?.channels,onFirstFrame:()=>s.onFirstFrame(),onStall:e=>s.onStall(e),onError:(e,t)=>s.onDecodeError(e,t),onFrameRendered:(e,t)=>s.onFrameRendered(e,t),onFeedback:e=>s.onFeedback(e),recomputeVideoRenderTime:e=>{const i=f?.effectiveGapTimeoutUs??0,s=void 0!==n&&n<5?5e4:2e5,r=Math.max(i,s),a=d.computeVideoRenderTime(e);return a?a.shouldDrop?t.now():a.renderTimeUs+r:t.now()+r},hasSyncReference:()=>d.hasReference,getPlaybackDelayUs:()=>{const e=f?.effectiveGapTimeoutUs??0,t=void 0!==n&&n<5?5e4:2e5;return Math.max(e,t)}})));let f=null;i.video&&!a&&(f=new Rs({mediaType:"video",config:c,clock:t,sync:d,onCommand:e=>s.onCommand(e),onEvent:e=>s.onEvent("video",e),recovery:h,videoOnly:!i.audio,...void 0!==i.isLive?{isLive:i.isLive}:{}}));let _=null;return i.audio&&!o&&(_=new Rs({mediaType:"audio",config:c,clock:t,sync:d,onCommand:e=>s.onCommand(e),onEvent:e=>s.onEvent("audio",e),recovery:h})),{videoPipeline:f,audioPipeline:_,syncController:d,recoveryController:h,commandDispatcher:g,mediaSource:r}}(this.config,this.clock,e,{onFirstFrame:()=>{this._stats.recordFirstFrameRendered(),this.log.info("First frame rendered"),this.emitter.emit("first_frame",{type:"first_frame"})},onStall:e=>{this._stats.recordStall(e),this.emitter.emit("stall",{type:"stall",durationMs:e}),this.lastLocStallUs=this.clock.now(),this.locHealthyRenderCount=0,this.consecutiveStallCount++,this.videoRecoveryActive=!0,this.videoRecoveryHealthyRenders=0;const t=(this.videoPipeline?.currentGroupId??-1n)+1n;if(this.videoPipeline?.reset(t),this.syncController?.reset(),this.consecutiveStallCount>=3)return this.consecutiveStallCount=0,this.log.warn("Jump to live: %d consecutive stalls — flushing and resubscribing",3),this.requestFreshSubscriptionStart("video"),void this.emitter.emit("recovery_action",{type:"recovery_action",action:{type:"jump_to_live"}});if(this.recoveryController){const t=this.recoveryController.evaluate({type:"stall",durationMs:e});this.emitter.emit("recovery_action",{type:"recovery_action",action:t}),Tr(t,"video",this.qualityController,this.log,{onQualityReduced:e=>{this.selectVideoTrack(e.name,"recovery","downshift").catch(t=>{this.log.warn('Quality switch to "%s" failed: %s',e.name,t)})},onResubscribe:(e,t)=>this.requestFreshSubscriptionStart(e,t),onTerminate:e=>{this.stateMachine.state!==jn&&this.transitionState(jn),this.stopTicking()}})}},onDecodeError:(e,t)=>{if(this.stateMachine.state===jn)return;this._stats.recordDecodeError(),"video"===e&&(this.lastLocDecodeErrorUs=this.clock.now(),this.locHealthyRenderCount=0);const i="audio"===e?tr:er;this.emitError(cr("degraded","decoder",i,t.message,{cause:t,context:{mediaType:e}})),"video"===e&&this.videoPipeline&&(this.videoPipeline.reset(),this.syncController?.reset())},onFrameRendered:(e,t)=>{if(this._stats.recordFrameRendered(),this.videoRecoveryActive)return this.videoRecoveryHealthyRenders++,void(this.videoRecoveryHealthyRenders>=Lr.RECOVERY_HEALTHY_THRESHOLD&&(this.videoRecoveryActive=!1,this.videoRecoveryHealthyRenders=0,this.recoveryController?.notifySuccess?.(),this.consecutiveStallCount=0));this.recoveryController?.notifySuccess?.(),this.consecutiveStallCount=0},onFeedback:e=>this.handleFeedback(e),onCommand:e=>this.handlePipelineCommand(e),onEvent:(e,t)=>this.handlePipelineEvent(e,t)},this._handshakeRttMs);if(this.videoPipeline=t.videoPipeline,this.audioPipeline=t.audioPipeline,this.syncController=t.syncController,this.recoveryController=t.recoveryController,this.commandDispatcher=t.commandDispatcher,this.mediaSource=t.mediaSource,this.mediaSource&&(this.mediaSource.onStall=e=>{if(this._stats.recordStall(e),this.emitter.emit("stall",{type:"stall",durationMs:e}),!this.pendingVideoSwitch&&!this.switchInProgress&&this.qualityController&&this.bufferAbrController){const t=this.qualityController.peekLowerVideoQuality(!0);t&&(this.lastAbrDownshiftUs=this.clock.now(),this.log.warn("MSE stall %dms → emergency downshift to %s",e,t.name),this.selectVideoTrack(t.name,"recovery","downshift").catch(e=>{this.log.warn('Stall downshift to "%s" failed: %s',t.name,e)}))}}),yr(t,e),this.mediaSource&&!this.cmafInitialized){if(!(e.video?.initTrack&&!e.video?.initData||e.audio?.initTrack&&!e.audio?.initData)){this.cmafInitialized=!0,e.video?.codec&&(this.currentVideoCodec=e.video.codec);const t=this.mediaSource,i={video:!1,audio:!1};if(!this.config.createCmafAssembler)throw new Error("CMAF tracks require createCmafAssembler in MoqtPlayerConfig");this.cmafAssembler=this.config.createCmafAssembler({onSegment:(e,s,n,r)=>{i[e]||(i[e]=!0,"setTimestampOffset"in t&&t.setTimestampOffset(e,0)),t.appendChunk(e,s,n,r)},onDiscontinuity:(e,i)=>{t&&"clearTimeline"in t&&t.clearTimeline(e,i)}});const s=e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0));e.video?.initData&&this.cmafAssembler.setInitSegment?.("video",s(e.video.initData)),e.audio?.initData&&this.cmafAssembler.setInitSegment?.("audio",s(e.audio.initData))}}this.pipelinesCreated=!0}async subscribeToMediaTracks(e){this._mediaSubsExpected=0,this._mediaSubsOk=0,this._mediaSubsFailed=0;const t=this.qualityController.selectInitialTracks(e,Pr({videoConstraints:this.config.videoConstraints,audioConstraints:this.config.audioConstraints,...this.config.disableVideo?{disableVideo:!0}:{},...this.config.disableAudio?{disableAudio:!0}:{}})),i=this.qualityController.alternatives;if(i.length>1){const e=i.map(e=>({name:e.name,bitrateKbps:(e.bitrate??0)/1e3}));this.bufferAbrController=new As({clock:this.clock,ladder:e,initialIndex:this.qualityController.currentIndex,lowThresholdUs:5e5,highThresholdUs:4e6})}this._stats.setTrackInfo(t.video?Pr({codec:t.video.codec,bitrate:t.video.bitrate,width:t.video.width,height:t.video.height}):void 0,t.audio?Pr({codec:t.audio.codec}):void 0),void 0!==t.video?.targetLatency&&this._stats.setTargetLatency(t.video.targetLatency);const s=Sr(this.config),n="cmaf"===t.video?.packaging?"cmaf":"loc",r="cmaf"===t.audio?.packaging?"cmaf":"loc";this.createPipelinesFromTrackInfo({video:t.video?Pr({codec:t.video.codec,width:t.video.width,height:t.video.height,initData:t.video.initData,initTrack:t.video.initTrack,packaging:n}):void 0,audio:t.audio?Pr({codec:t.audio.codec,samplerate:t.audio.samplerate,channels:t.audio.channelConfig?Number(t.audio.channelConfig):void 0,initData:t.audio.initData,initTrack:t.audio.initTrack,packaging:r}):void 0,isLive:!0===t.video?.isLive||!0===t.audio?.isLive});const a=[];t.video&&a.push({name:t.video.name,mediaType:"video",packaging:n}),t.audio&&a.push({name:t.audio.name,mediaType:"audio",packaging:r}),await Promise.all(a.map(async({name:e,mediaType:i,packaging:n})=>{if(!this.subscriptionManager||!this.connection)return;if(!this.hooks.beforeSubscribe.run({trackName:e,mediaType:i}))return;this._mediaSubsExpected++;const r=Ar(this.config.namespace,this.enc),a=this.enc.encode(e),o="video"===i?t.video:t.audio,c=s??Nr(!0===o?.isLive),d=await this.connection.subscribe(r,a,c),h=BigInt(d);this.subscriptionManager&&(this.activeSubscriptions.set(h,{trackName:e,mediaType:i,trackAlias:h}),this.subscriptionManager.registerTrack(h,e,i,n),this.pendingMediaSubs.set(h,{trackName:e,mediaType:i,packaging:n}),this.log.info('Subscribe %s "%s" requestId=%s',i,e,h),this.emitter.emit("track_subscribed",{type:"track_subscribed",trackName:e,mediaType:i,requestId:h}))}));const o=e.tracks.find(e=>"mediatimeline"===e.packaging);if(o&&this.connection&&this.subscriptionManager){this.timelineState={entries:[],trackDuration:(c=o).trackDuration,isLive:c.isLive,trackName:c.name,depends:c.depends??[]};const e=Ar(this.config.namespace,this.enc),t=this.enc.encode(o.name),i=await this.connection.subscribe(e,t,s),n=BigInt(i);this.subscriptionManager&&(this.timelineRequestId=n,this.activeSubscriptions.set(n,{trackName:o.name,mediaType:"mediatimeline",trackAlias:n}),this.subscriptionManager.registerTrack(n,o.name,"mediatimeline","mediatimeline"),this.pendingMediaSubs.set(n,{trackName:o.name,mediaType:"mediatimeline",packaging:"mediatimeline"}),this.log.info('Subscribe mediatimeline "%s" requestId=%s',o.name,n))}var c;const d=new Set;t.video?.initTrack&&d.add(t.video.initTrack),t.audio?.initTrack&&d.add(t.audio.initTrack);for(const e of d){if(!this.connection||!this.subscriptionManager)break;const t=Ar(this.config.namespace,this.enc),i=this.enc.encode(e),s={subscriptionFilter:{type:"AbsoluteStart",startGroup:K(0n),startObject:K(0n)}},n=await this.connection.subscribe(t,i,s),r=BigInt(n);this.initTrackRequestIds.set(e,r),this.subscriptionManager&&(this.activeSubscriptions.set(r,{trackName:e,mediaType:"video",trackAlias:r}),this.subscriptionManager.registerTrack(r,e,"video","init"),this.pendingMediaSubs.set(r,{trackName:e,mediaType:"video",packaging:"init"}),this.log.info('Subscribe init track "%s" requestId=%s',e,r))}const h=new Set;t.video&&h.add(t.video.name),t.audio&&h.add(t.audio.name);const l=e.tracks.filter(e=>"eventtimeline"===e.packaging&&Array.isArray(e.depends)&&e.depends.some(e=>h.has(e)));for(const e of l){if(!this.connection||!this.subscriptionManager)break;const t=Ar(this.config.namespace,this.enc),i=this.enc.encode(e.name),n=s??{subscriptionFilter:{type:"LargestObject"}},r=await this.connection.subscribe(t,i,n),a=BigInt(r);this.subscriptionManager&&(this.activeSubscriptions.set(a,{trackName:e.name,mediaType:"eventtimeline",trackAlias:a}),this.subscriptionManager.registerTrack(a,e.name,"eventtimeline","eventtimeline"),this.pendingMediaSubs.set(a,{trackName:e.name,mediaType:"eventtimeline",packaging:"eventtimeline"}),this.log.info('Subscribe eventtimeline "%s" (eventType=%s) requestId=%s',e.name,e.eventType??"(none)",a))}}handleFeedback(e){"video"===e.mediaType&&("queue_pressure"===e.type&&e.depth>=e.maxRecommended&&(this.lastLocQueuePressureUs=this.clock.now(),this.locHealthyRenderCount=0),"frame_rendered"===e.type&&this.locHealthyRenderCount++);const t="video"===e.mediaType?this.videoPipeline:this.audioPipeline;t?.handleFeedback(e)}handlePipelineCommand(e){!function(e,t,i,s,n){const r=t?t(e):e;r&&(n({type:"decoder_command",command:r}),i?.dispatch(r))}(e,this.config.commandTransform,this.commandDispatcher,this.mediaSource,e=>{e.command&&"configure"===e.command.type?this._stats.recordDecoderConfigured():e.command&&"decode_video"===e.command.type&&this._stats.recordFrameDecoded(),this.emitter.emit(e.type,e)})}handlePipelineEvent(e,t){"gap_detected"===t.type&&this._stats.recordGapDetected(),"recovery"===t.type&&this._stats.recordRecoveryAction(),"catch_up_changed"===t.type&&this._stats.recordLatency(t.state.latencyMs),"partial_group_abandoned"===t.type&&"video"===e&&(this.lastLocPartialAbandonUs=this.clock.now(),this.locHealthyRenderCount=0),function(e,t,i){switch(t.type){case"gap_detected":i.log.warn("Gap detected %s group=%s",e,t.groupId),i.emitEvent({type:"gap_detected",mediaType:e,groupId:t.groupId});break;case"skip_forward":i.log.warn("Skip forward %s group=%s→%s",e,t.fromGroupId,t.toGroupId),!i.syncResetThisTick&&i.syncController&&(i.syncController.reset(),i.setSyncResetThisTick(!0)),i.emitEvent({type:"skip_forward",mediaType:e,fromGroupId:t.fromGroupId,toGroupId:t.toGroupId});break;case"keyframe_waiting":i.emitEvent({type:"keyframe_waiting",mediaType:e,groupId:t.groupId});break;case"track_ended":i.emitEvent({type:"track_ended",mediaType:e});break;case"sync_drift":i.log.warn("A/V sync drift: %dms",t.driftUs/1e3),i.emitEvent({type:"sync_drift",driftMs:t.driftUs/1e3});break;case"recovery":{const e=i.recoveryHook(t.action);e&&i.emitEvent({type:"recovery_action",action:e});break}case"catch_up_changed":i.log.debug("Catch-up %s rate=%.2f latency=%dms target=%dms",t.state.active?"active":"inactive",t.state.currentRate,t.state.latencyMs,t.state.targetMs),i.emitEvent({type:"catch_up_changed",active:t.state.active,rate:t.state.currentRate,latencyMs:t.state.latencyMs,targetMs:t.state.targetMs});break;case"keyframe_validation_failed":i.log.warn("Keyframe validation failed %s group=%s object=%s codec=%s",e,t.groupId,t.objectId,t.codec),i.emitEvent({type:"keyframe_validation_failed",mediaType:e,groupId:t.groupId,objectId:t.objectId,codec:t.codec});break;case"partial_group_abandoned":i.log.warn("Partial group abandoned %s group=%s→%s reason=%s",e,t.fromGroupId,t.toGroupId,t.reason),i.emitEvent({type:"partial_group_abandoned",mediaType:e,fromGroupId:t.fromGroupId,toGroupId:t.toGroupId,reason:t.reason});break;case"backlog_shed":i.log.warn("Backlog shed %s: dropped=%d remaining=%d reason=%s",e,t.droppedGroups,t.remainingGroups,t.reason),i.emitEvent({type:"backlog_shed",mediaType:e,droppedGroups:t.droppedGroups,remainingGroups:t.remainingGroups,reason:t.reason})}}(e,t,{emitEvent:e=>this.emitter.emit(e.type,e),log:this.log,syncController:this.syncController,syncResetThisTick:this.syncResetThisTick,setSyncResetThisTick:e=>{this.syncResetThisTick=e},recoveryHook:t=>{const i=this.hooks.onRecovery.run(t);return i&&Tr(i,e,this.qualityController,this.log,{onQualityReduced:e=>{this.selectVideoTrack(e.name,"recovery","downshift").catch(t=>{this.log.warn('Quality switch to "%s" failed: %s',e.name,t)})},onResubscribe:(e,t)=>{this.requestFreshSubscriptionStart(e,t)},onTerminate:e=>{this.stateMachine.state!==jn&&this.transitionState(jn),this.stopTicking()}}),i}})}requestFreshSubscriptionStart(e,t){if(!this.connection)return;const i=[...this.activeSubscriptions.entries()].filter(([t,i])=>i.mediaType===e&&t!==this.timelineRequestId);for(const[s,n]of i)this.connection.requestUpdate(K(s),{subscriptionFilter:void 0!==t?{type:"AbsoluteStart",startGroup:K(t),startObject:K(0n)}:{type:"NextGroupStart"}}).then(()=>{this.log.info('Recovery REQUEST_UPDATE %s "%s" reqId=%s filter=%s',e,n.trackName,s,void 0!==t?`AbsoluteStart(${t})`:"NextGroupStart")}).catch(t=>{const i=t instanceof Error?t:new Error(String(t));this.log.warn("Recovery REQUEST_UPDATE failed for %s reqId=%s: %s",e,s,i.message),this.emitError(cr("degraded","connection",Zn,`Recovery REQUEST_UPDATE failed: ${i.message}`,{cause:i,context:{requestId:s,mediaType:e}}))})}resubscribeAfterPublishDone(e){if(!this.connection||!this.subscriptionManager||!this._catalogState)return;if(this.pendingVideoSwitch?.oldTrackName===e)return void this.log.info('Ignoring TOO_FAR_BEHIND for "%s" — pending switch to "%s"',e,this.pendingVideoSwitch.newTrackName);const t=this._catalogState.tracks.find(t=>t.name===e);if(!t)return void this.log.warn('Cannot resubscribe "%s": track not found in catalog',e);const i="audio"===t.role?"audio":"video",s="cmaf"===t.packaging?"cmaf":"loc",n=!0===t.isLive;"video"===i?this.videoPipeline?.reset():this.audioPipeline?.reset(),this.syncController?.reset();const r=Ar(this.config.namespace,this.enc),a=this.enc.encode(e),o=Nr(n);this.connection.subscribe(r,a,o).then(t=>{const n=BigInt(t);this.subscriptionManager&&(this.activeSubscriptions.set(n,{trackName:e,mediaType:i,trackAlias:n}),this.subscriptionManager.registerTrack(n,e,i,s),this.pendingMediaSubs.set(n,{trackName:e,mediaType:i,packaging:s}),this.log.info('Resubscribed %s "%s" requestId=%s after PUBLISH_DONE',i,e,n),this.emitter.emit("track_subscribed",{type:"track_subscribed",trackName:e,mediaType:i,requestId:n}))}).catch(t=>{const s=t instanceof Error?t:new Error(String(t));this.log.warn('Resubscribe "%s" failed: %s',e,s.message),this.emitError(cr("degraded","connection",Xn,`Resubscribe after TOO_FAR_BEHIND failed: ${s.message}`,{cause:s,context:{trackName:e,mediaType:i}})),this.emitter.emit("track_unsubscribed",{type:"track_unsubscribed",trackName:e,reason:`TOO_FAR_BEHIND resubscribe failed: ${s.message}`})})}startTicking(){this.tickInterval||(this.tickInterval=setInterval(()=>this.tick(),16))}stopTicking(){this.tickInterval&&(clearInterval(this.tickInterval),this.tickInterval=null)}handleMalformedTrack(e,t,i){let s;this.log.warn('Malformed track "%s": %s',t,i.message);for(const[t,i]of this.activeSubscriptions)if(i.trackAlias===e){s=t;break}void 0!==s&&(this.connection?.unsubscribe(K(s)),this.activeSubscriptions.delete(s),this.subscriptionManager?.unregisterTrack(e),this.emitter.emit("track_unsubscribed",{type:"track_unsubscribed",trackName:t,reason:`Malformed track: ${i.message}`}))}createDefaultConnection(){throw new Error("No createConnection provided in config. Provide a factory function or use a default browser adapter.")}}function Ur(e,t){if(e.byteLengthe.byteLength)return!1;let s=0;for(let n=0;ne.byteLength)return!1;i+=s}return i===e.byteLength}function Dr(e){return!(e.byteLength<3)&&(0===e[0]&&0===e[1]&&1===e[2]||e.byteLength>=4&&0===e[0]&&0===e[1]&&0===e[2]&&1===e[3])}function Mr(e,t){const i=[];let s=Br(e,0);if(s<0)return e;for(;s>=0;){const t=s+(1===e[s+2]?3:4);let n=Br(e,t);n<0&&(n=e.byteLength);let r=n;for(;r>t&&0===e[r-1];)r--;r>t&&i.push(e.subarray(t,r)),s=ne+t+i.byteLength,0),r=new Uint8Array(n);let a=0;for(const e of i)xr(r,a,e.byteLength,t),a+=t,r.set(e,a),a+=e.byteLength;return r}function Br(e,t){for(let i=t;i<=e.byteLength-3;i++)if(0===e[i]&&0===e[i+1]){if(1===e[i+2])return i;if(i+3=0;n--)e[t+n]=255&i,i>>>=8}class Hr{gatesAfterReset=!0;usesDescription=!0;supportsSoftwarePreference=!0;optimizeForLatency=!0;prepareChunkData(e,t){const i=$r(t);let s;return s=Ur(e,i)?e:Dr(e)?Mr(e,i):e,function(e,t){const i=[],s=[];let n=!1,r=0;for(;r+t<=e.byteLength;){let a=0;for(let i=0;ie.byteLength)return{data:e,droppedReason:null};const o=e.subarray(r,r+a),c=31&o[0];0===c||c>=2&&c<=4?s.push(c):(i.push(o),1!==c&&5!==c||(n=!0)),r+=a}if(!n)return null;if(0===s.length)return{data:e,droppedReason:null};const a=i.reduce((e,i)=>e+t+i.byteLength,0),o=new Uint8Array(a);let c=0;for(const e of i)xr(o,c,e.byteLength,t),c+=t,o.set(e,c),c+=e.byteLength;const d=Array.from(new Set(s)).map(e=>`nal-type-${e}`).join(",");return{data:o,droppedReason:d}}(s,i)}async checkSupport(e,t,i,s){if("undefined"==typeof VideoDecoder||!VideoDecoder.isConfigSupported)return!0;const n={codec:e,optimizeForLatency:!0};void 0!==t&&(n.codedWidth=t),void 0!==i&&(n.codedHeight=i),s&&s.byteLength>0&&(n.description=s);try{return!0===(await VideoDecoder.isConfigSupported(n)).supported}catch{return!0}}isAcceptableSyncPoint(e,t,i){if("key"!==t)return!1;return Fr(e,$r(i)).hasKeyframe}describeChunk(e,t,i){const s=Fr(e,$r(i));if(!s.valid)return`type=${t}|invalid-avcc(offset=${s.invalidOffset},bytes=${e.byteLength})`;const n=s.nalTypes.map(e=>function(e){switch(e){case 1:return"non-idr";case 5:return"idr";case 6:return"sei";case 7:return"sps";case 8:return"pps";case 9:return"aud";default:return`nal${e}`}}(e)).join(",");return`type=${t}|bytes=${e.byteLength}|idr=${s.hasKeyframe}|nals=[${n}]`}describeConfig(e){if(!e||e.byteLength<7||1!==e[0])return e?`non-avcc(bytes=${e.byteLength})`:"none";const t=e[1],i=e[3],s=$r(e),n=31&e[5];return`avcc|profile=0x${t.toString(16)}|level=0x${i.toString(16)}|len=${s}|sps=${n}`}}function $r(e){return!e||e.byteLength<5||1!==e[0]?4:1+(3&e[4])}function Fr(e,t){const i=[];let s=0;for(;s+t<=e.byteLength;){let n=0;for(let i=0;ie.byteLength)return{valid:!1,hasKeyframe:!1,nalTypes:i,invalidOffset:s-t};i.push(31&e[s]),s+=n}return{valid:!0,hasKeyframe:i.includes(5),nalTypes:i}}class Vr{gatesAfterReset=!0;usesDescription=!0;supportsSoftwarePreference=!1;optimizeForLatency=!1;discardRasl=!0;async checkSupport(e,t,i,s){if("undefined"==typeof VideoDecoder||!VideoDecoder.isConfigSupported)return!0;const n={codec:e,optimizeForLatency:!0};void 0!==t&&(n.codedWidth=t),void 0!==i&&(n.codedHeight=i),s&&s.byteLength>0&&(n.description=s);try{return!0===(await VideoDecoder.isConfigSupported(n)).supported}catch{return!0}}prepareChunkData(e,t){const i=qr(t);let s;return s=Ur(e,i)?e:Dr(e)?Mr(e,i):e,this.sanitizeChunk(s,i)}isAcceptableSyncPoint(e,t,i){if("key"!==t)return!1;return function(e,t){let i=0;for(;i+t<=e.byteLength;){let s=0;for(let n=0;ne.byteLength)break;const n=Gr(e[i]);if(jr(n))return!0;if(32!==n&&33!==n&&34!==n&&35!==n&&39!==n&&40!==n&&n<=31&&!jr(n))return!1;i+=s}return!1}(e,qr(i))}describeChunk(e,t,i){const s=function(e,t){const i=[];let s=0;for(;s+t<=e.byteLength;){let n=0;for(let i=0;ie.byteLength)break;i.push(Gr(e[s])),s+=n}return i}(e,qr(i)),n=s.map(e=>Wr(e)).join(","),r=s.some(e=>jr(e));return`type=${t}|bytes=${e.byteLength}|irap=${r}|nals=[${n}]`}describeConfig(e){if(!e||e.byteLength<23||1!==e[0])return e?`non-hvcc(bytes=${e.byteLength})`:"none";return`hvcc|profile=${31&e[1]}|level=${e[12]}|len=${qr(e)}`}sanitizeChunk(e,t){const i=[],s=[];let n=!1,r=0;for(;r+t<=e.byteLength;){let a=0;for(let i=0;ie.byteLength)return{data:e,droppedReason:null};const o=e.subarray(r,r+a),c=o[0]>>1&63;35===c||36===c||37===c||38===c?s.push(c):!this.discardRasl||8!==c&&9!==c?(i.push(o),c<=31&&(n=!0,jr(c)?this.discardRasl=!0:8!==c&&9!==c&&(this.discardRasl=!1))):s.push(c),r+=a}if(!n)return null;if(0===s.length)return{data:e,droppedReason:null};const a=i.reduce((e,i)=>e+t+i.byteLength,0),o=new Uint8Array(a);let c=0;for(const e of i)xr(o,c,e.byteLength,t),c+=t,o.set(e,c),c+=e.byteLength;return{data:o,droppedReason:Array.from(new Set(s)).map(e=>`hevc-nal-${e}(${Wr(e)})`).join(",")}}}function qr(e){return!e||e.byteLength<23||1!==e[0]?4:1+(3&e[21])}function Gr(e){return e>>1&63}function jr(e){return e>=16&&e<=21}function Wr(e){switch(e){case 0:return"trail_n";case 1:return"trail_r";case 6:return"radl_n";case 7:return"radl_r";case 8:return"rasl_n";case 9:return"rasl_r";case 16:return"bla_w_lp";case 17:return"bla_w_radl";case 18:return"bla_n_lp";case 19:return"idr_w_radl";case 20:return"idr_n_lp";case 21:return"cra";case 32:return"vps";case 33:return"sps";case 34:return"pps";case 35:return"aud";case 36:return"eos";case 37:return"eob";case 38:return"fd";case 39:return"sei_prefix";case 40:return"sei_suffix";default:return`nal${e}`}}const Qr=new Set([2,7,8,15]);class Kr{gatesAfterReset=!0;usesDescription=!1;supportsSoftwarePreference=!1;optimizeForLatency=!0;async checkSupport(e,t,i){if("undefined"==typeof VideoDecoder||!VideoDecoder.isConfigSupported)return!0;const s={codec:e,optimizeForLatency:!0};void 0!==t&&(s.codedWidth=t),void 0!==i&&(s.codedHeight=i);try{return!0===(await VideoDecoder.isConfigSupported(s)).supported}catch{return!0}}prepareChunkData(e){return function(e){let t=!1,i=0;for(;ie+t.byteLength,0),a=new Uint8Array(r);let o=0;for(const e of s)a.set(e,o),o+=e.byteLength;return{data:a,droppedReason:Yr(n)}}(e)}isAcceptableSyncPoint(e,t){return"key"===t&&function(e){let t=0;for(;tJr(e)).join(","),n=i.includes(1);return`type=${t}|bytes=${e.byteLength}|seqhdr=${n}|obus=[${s}]`}}function zr(e,t){if(t>=e.byteLength)return null;const i=e[t],s=i>>3&15,n=i>>1&1;let r,a=1;if(i>>2&1&&(a+=1),t+a>e.byteLength)return null;if(n){const i=function(e,t){let i=0,s=0;for(let n=0;n<8;n++){if(t+n>=e.byteLength)return null;const r=e[t+n];if(i|=(127&r)<<7*n,s++,!(128&r))break}return{value:i>>>0,bytesRead:s}}(e,t+a);if(null===i)return null;a+=i.bytesRead,r=i.value}else r=e.byteLength-t-a;return{obuType:s,headerSize:a,payloadSize:r,hasSizeField:1===n}}function Yr(e){return Array.from(new Set(e)).map(e=>`obu-${e}(${Jr(e)})`).join(",")}function Jr(e){switch(e){case 1:return"seq_hdr";case 2:return"td";case 3:return"frame_hdr";case 4:return"tile_grp";case 5:return"metadata";case 6:return"frame";case 7:return"redundant_hdr";case 8:return"tile_list";case 15:return"padding";default:return`obu${e}`}}class Xr{gatesAfterReset=!1;usesDescription=!0;supportsSoftwarePreference=!1;optimizeForLatency=!0;async checkSupport(){return!0}prepareChunkData(e){return{data:e,droppedReason:null}}isAcceptableSyncPoint(e,t){return"key"===t}}function Zr(e){switch(e.split(".")[0].toLowerCase()){case"avc1":case"avc3":return new Hr;case"hvc1":case"hev1":return new Vr;case"av01":return new Kr;default:return new Xr}}class ea{decoder=null;preferSoftwareDecoder;constructor(e){this.preferSoftwareDecoder=e?.preferSoftwareDecoder??!1}lastCodec="";lastWidth;lastHeight;lastDescription;strategy=Zr("");awaitingKeyframe=!1;debug=!1;configLikelyUnsupported=!1;lastObservedChunkSummary="none";lastSubmittedChunkSummary="none";observedChunkCount=0;submittedChunkCount=0;recentObservedChunkSummaries=[];recentSubmittedChunkSummaries=[];lastObservedChunkHex="none";lastSubmittedChunkHex="none";lastSubmittedKeyChunkSummary="none";lastSubmittedKeyChunkHex="none";lastSubmittedKeyChunkBytes=null;lastSubmittedChunkBytes=null;renderTimeMap=new Map;onFrame=null;onError=null;configure(e,t,i,s){const n=t!==this.lastCodec;if(this.lastCodec=t,this.lastWidth=i,this.lastHeight=s,this.lastDescription=e.byteLength>0?e:void 0,n&&(this.strategy=Zr(t)),this.awaitingKeyframe=this.strategy.gatesAfterReset,this.configLikelyUnsupported=!1,this.observedChunkCount=0,this.submittedChunkCount=0,this.lastObservedChunkSummary="none",this.lastSubmittedChunkSummary="none",this.lastObservedChunkHex="none",this.lastSubmittedChunkHex="none",this.lastSubmittedKeyChunkSummary="none",this.lastSubmittedKeyChunkHex="none",this.lastSubmittedKeyChunkBytes=null,this.lastSubmittedChunkBytes=null,this.recentObservedChunkSummaries.length=0,this.recentSubmittedChunkSummaries.length=0,n&&this.decoder&&"configured"===this.decoder.state){const e=this.decoder;this.decoder=null,this.renderTimeMap.clear(),e.flush().then(()=>{"closed"!==e.state&&e.close()},()=>{"closed"!==e.state&&e.close()})}this.createDecoder(),this.applyConfig(),n&&this.checkConfigSupport()}decode(e,t){if(!this.lastCodec||!this.decoder||"configured"!==this.decoder.state)return;if(this.decoder.decodeQueueSize>=16)return this.reset(),void this.onError?.(new Error("decode queue overflow — reset to keyframe"));const i=this.strategy.prepareChunkData(e.data,this.lastDescription);if(!i)return;const{data:s,droppedReason:n}=i;if(this.observedChunkCount++,this.lastObservedChunkSummary=this.strategy.describeChunk?this.strategy.describeChunk(s,e.type,this.lastDescription):`#${this.observedChunkCount}|type=${e.type}|bytes=${s.byteLength}`,this.recentObservedChunkSummaries.push(this.lastObservedChunkSummary),this.recentObservedChunkSummaries.length>8&&this.recentObservedChunkSummaries.shift(),this.lastObservedChunkHex=ta(s),n&&this.debug&&console.warn(`[WebCodecsVideoDecoder] Dropped NAL/OBU units: ${n}`),this.awaitingKeyframe){if(!this.strategy.isAcceptableSyncPoint(s,e.type,this.lastDescription))return void(this.debug&&console.debug("[WebCodecsVideoDecoder] Awaiting keyframe, dropping chunk type=%s",e.type));this.awaitingKeyframe=!1}this.submittedChunkCount++,this.lastSubmittedChunkSummary=this.lastObservedChunkSummary,this.lastSubmittedChunkHex=ta(s),this.lastSubmittedChunkBytes=s.slice(),this.recentSubmittedChunkSummaries.push(this.lastSubmittedChunkSummary),this.recentSubmittedChunkSummaries.length>8&&this.recentSubmittedChunkSummaries.shift(),"key"===e.type&&(this.lastSubmittedKeyChunkSummary=this.lastSubmittedChunkSummary,this.lastSubmittedKeyChunkHex=this.lastSubmittedChunkHex,this.lastSubmittedKeyChunkBytes=s.slice()),this.renderTimeMap.set(e.timestamp,t);try{this.decoder.decode(new EncodedVideoChunk({...e,data:s}))}catch(e){throw this.enrichError(e,`Video decode submit failed (${this.describeDecoderContext()})`)}}async flush(){this.decoder&&"configured"===this.decoder.state&&await this.decoder.flush()}reset(){this.lastCodec&&(this.renderTimeMap.clear(),this.awaitingKeyframe=this.strategy.gatesAfterReset,this.decoder&&"configured"===this.decoder.state&&this.decoder.reset(),this.decoder&&"closed"!==this.decoder.state||this.createDecoder(),this.applyConfig())}get queueDepth(){return this.decoder?.decodeQueueSize??0}destroy(){this.renderTimeMap.clear(),this.decoder&&"closed"!==this.decoder.state&&this.decoder.close(),this.decoder=null,this.onFrame=null,this.onError=null}createDecoder(){this.decoder&&"closed"!==this.decoder.state&&this.decoder.close(),this.decoder=new VideoDecoder({output:e=>{if(!this.onFrame)return void e.close();const t=this.renderTimeMap.get(e.timestamp)??0;this.renderTimeMap.delete(e.timestamp),this.onFrame(e,t)},error:e=>{if(this.configLikelyUnsupported)return this.decoder&&"closed"!==this.decoder.state&&this.decoder.close(),this.decoder=null,void this.onError?.(new Error(`Codec not supported: ${this.lastCodec} (${this.lastWidth??"?"}x${this.lastHeight??"?"}). VideoDecoder.isConfigSupported() returned false and decode failed.`));this.publishDebugBundle(),this.recoverAfterDecodeError(),this.onError?.(this.enrichError(e,`Video decoder error: ${e.message} (${this.describeDecoderContext()})`))}})}buildConfig(){const e={codec:this.lastCodec,optimizeForLatency:this.strategy.optimizeForLatency};return this.preferSoftwareDecoder&&this.strategy.supportsSoftwarePreference&&(e.hardwareAcceleration="prefer-software"),void 0!==this.lastWidth&&(e.codedWidth=this.lastWidth),void 0!==this.lastHeight&&(e.codedHeight=this.lastHeight),this.strategy.usesDescription&&this.lastDescription&&(e.description=this.lastDescription),e}applyConfig(){this.decoder&&this.lastCodec&&this.decoder.configure(this.buildConfig())}checkConfigSupport(){this.lastCodec&&this.strategy.checkSupport(this.lastCodec,this.lastWidth,this.lastHeight,this.lastDescription).then(e=>{e||(this.configLikelyUnsupported=!0)})}recoverAfterDecodeError(){this.renderTimeMap.clear(),this.awaitingKeyframe=this.strategy.gatesAfterReset,this.debug&&console.warn("[VideoDecoder] decode error → recreating decoder (%s %dx%d)",this.lastCodec,this.lastWidth??0,this.lastHeight??0),this.createDecoder(),this.applyConfig()}describeDecoderContext(){const e=this.strategy.describeConfig?this.strategy.describeConfig(this.lastDescription):`initDataBytes=${this.lastDescription?.byteLength??0}`;return[`codec=${this.lastCodec||"unknown"}`,`size=${this.lastWidth??"?"}x${this.lastHeight??"?"}`,`config=${e}`,`lastObserved=${this.lastObservedChunkSummary}`,`lastObservedHex=${this.lastObservedChunkHex}`,`recentObserved=[${this.recentObservedChunkSummaries.join(", ")}]`,`lastSubmitted=${this.lastSubmittedChunkSummary}`,`lastSubmittedHex=${this.lastSubmittedChunkHex}`,`lastSubmittedKey=${this.lastSubmittedKeyChunkSummary}`,`lastSubmittedKeyHex=${this.lastSubmittedKeyChunkHex}`,`recentSubmitted=[${this.recentSubmittedChunkSummaries.join(", ")}]`].join(", ")}enrichError(e,t){const i=e instanceof Error?e:new Error(String(e)),s=new Error(t);return s.cause=i,s}publishDebugBundle(){globalThis.__MOQT_LAST_VIDEO_DEBUG__={codec:this.lastCodec,width:this.lastWidth,height:this.lastHeight,initDataBase64:ia(this.lastDescription),keyframeSampleBase64:ia(this.lastSubmittedKeyChunkBytes),failingSampleBase64:ia(this.lastSubmittedChunkBytes),lastObservedSummary:this.lastObservedChunkSummary,lastSubmittedSummary:this.lastSubmittedChunkSummary,lastSubmittedKeySummary:this.lastSubmittedKeyChunkSummary}}}function ta(e){const t=Array.from(e.subarray(0,24),e=>e.toString(16).padStart(2,"0")),i=e.byteLength>24?"+":"";return`${t.join("")}${i}`}function ia(e){if(!e||0===e.byteLength)return"";let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t)}const sa={96e3:0,88200:1,64e3:2,48e3:3,44100:4,32e3:5,24e3:6,22050:7,16e3:8,12e3:9,11025:10,8e3:11};class na{decoder=null;lastCodec="";lastSampleRate=48e3;lastChannels=2;isAAC=!1;renderTimeQueue=[];errorCount=0;onData=null;onError=null;configure(e,t,i,s){this.lastCodec=t,this.lastSampleRate=i??48e3,this.lastChannels=s??2,this.isAAC=t.startsWith("mp4a."),this.errorCount=0,this.createDecoder()}decode(e,t){if(!this.lastCodec||!this.decoder||"configured"!==this.decoder.state)return;if(this.decoder.decodeQueueSize>=32)return;let i=e.data;this.isAAC&&(i=function(e,t,i){const s=sa[t]??3,n=e.byteLength+7,r=new Uint8Array(7);r[0]=255,r[1]=241,r[2]=64|s<<2|i>>2,r[3]=(3&i)<<6|n>>11&3,r[4]=n>>3&255,r[5]=(7&n)<<5|31,r[6]=252;const a=new Uint8Array(n);return a.set(r),a.set(e,7),a}(i,this.lastSampleRate,this.lastChannels)),this.renderTimeQueue.push(t);const s={type:e.type,timestamp:e.timestamp,data:i};void 0!==e.duration&&(s.duration=e.duration),this.decoder.decode(new EncodedAudioChunk(s))}async flush(){this.decoder&&"configured"===this.decoder.state&&await this.decoder.flush()}reset(){this.renderTimeQueue.length=0,this.lastCodec&&this.createDecoder()}get queueDepth(){return this.decoder?.decodeQueueSize??0}destroy(){this.renderTimeQueue.length=0,this.decoder&&"closed"!==this.decoder.state&&this.decoder.close(),this.decoder=null,this.onData=null,this.onError=null}createDecoder(){this.decoder&&"closed"!==this.decoder.state&&this.decoder.close(),this.decoder=new AudioDecoder({output:e=>{if(!this.onData)return void e.close();const t=this.renderTimeQueue.shift()??0;this.onData(e,t)},error:e=>{this.errorCount++,this.onError?.(new Error(e.message)),this.createDecoder()}});const e={codec:this.lastCodec,sampleRate:this.lastSampleRate,numberOfChannels:this.lastChannels};this.decoder.configure(e)}}class ra{audioCtx=null;anchorOffsetUs=0;anchored=!1;outputLatencyUs=0;lastNowUs=0;now(){if(this.audioCtx&&"running"===this.audioCtx.state){const e=this.audioCtx.getOutputTimestamp(),t=e.contextTime??0,i=e.performanceTime??0;if(i>0&&t>0){this.anchored||this.anchor(t,i);const e=1e6*t+1e3*(performance.now()-i);return this.lastNowUs=Math.max(this.lastNowUs,e+this.anchorOffsetUs),this.lastNowUs}}return this.lastNowUs=Math.max(this.lastNowUs,1e3*performance.now()),this.lastNowUs}attachAudioContext(e){this.audioCtx=e,this.anchored=!1,this.outputLatencyUs=1e6*(e.outputLatency??0)}detachAudioContext(){this.audioCtx=null,this.anchored=!1,this.outputLatencyUs=0}get speakerLatencyUs(){return this.outputLatencyUs}get isAudioBacked(){return this.anchored}anchor(e,t){const i=1e3*t,s=1e6*e;this.anchorOffsetUs=i-s,this.anchored=!0}}class aa{ctx;queue=[];stallThresholdMs;clock;firstFrameRendered=!1;lastRenderTimeMs=0;stallReported=!1;renderDiagCount=0;lastActualRenderUs=0;renderDiagEnabled="undefined"!=typeof location&&"render"===new URLSearchParams(location.search).get("debug");rafId=null;intervalId=null;running=!1;destroyed=!1;onFirstFrame=null;onFrameRendered=null;onStall=null;constructor(e,t){this.ctx=e.getContext("2d"),this.stallThresholdMs=t?.stallThresholdMs??500,this.clock=t?.clock??{now:()=>1e3*performance.now()}}enqueue(e,t){this.destroyed?e.close():this.queue.push({frame:e,renderTimeUs:t})}renderTick(e){if(this.destroyed)return;let t=!1;for(;this.queue.length>0;){const i=this.queue[0];if(i.renderTimeUs1)this.queue.shift(),i.frame.close();else{if(!(i.renderTimeUs<=e))break;{this.queue.shift();const s=BigInt(i.frame.timestamp);if(this.ctx.drawImage(i.frame,0,0,this.ctx.canvas.width,this.ctx.canvas.height),i.frame.close(),t=!0,this.stallReported=!1,this.firstFrameRendered||(this.firstFrameRendered=!0,this.onFirstFrame?.()),this.onFrameRendered?.(s,e),this.renderDiagCount++,this.renderDiagEnabled&&this.renderDiagCount%30==0){const t=this.lastActualRenderUs>0?e-this.lastActualRenderUs:0,s=e-i.renderTimeUs;console.log("[render] frame=%d scheduled=%d actual=%d jitter=%dµs delta=%dµs",this.renderDiagCount,Math.round(i.renderTimeUs),Math.round(e),Math.round(s),Math.round(t))}this.lastActualRenderUs=e,this.lastRenderTimeMs=performance.now()}}}if(!t&&this.firstFrameRendered&&!this.stallReported&&this.lastRenderTimeMs>0&&!document.hidden){const e=performance.now()-this.lastRenderTimeMs;e>this.stallThresholdMs&&(this.stallReported=!0,this.onStall?.(e))}}start(){this.destroyed||this.running||(this.running=!0,this.scheduleLoop(),document.addEventListener("visibilitychange",this.onVisibilityChange))}stop(){this.running=!1,this.cancelLoop(),document.removeEventListener("visibilitychange",this.onVisibilityChange)}flush(){for(const e of this.queue)e.frame.close();this.queue.length=0,this.lastRenderTimeMs=0,this.stallReported=!1}destroy(){this.destroyed=!0,this.stop(),this.flush(),this.onFirstFrame=null,this.onFrameRendered=null,this.onStall=null}onVisibilityChange=()=>{this.running&&(this.cancelLoop(),this.scheduleLoop())};scheduleLoop(){if(document.hidden)this.intervalId=setInterval(()=>{this.renderTick(this.clock.now())},16);else{const e=()=>{this.running&&!this.destroyed&&(this.renderTick(this.clock.now()),this.rafId=requestAnimationFrame(e))};this.rafId=requestAnimationFrame(e)}}cancelLoop(){null!==this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}}class oa{real=null;pendingRate=1;_enabled=!0;get isActive(){return null!==this.real}set enabled(e){this._enabled=e}get enabled(){return this._enabled}activate(e){this.real=e,1!==this.pendingRate&&e.setPlaybackRate?.(this.pendingRate)}schedule(e,t){this.real&&this._enabled?this.real.schedule(e,t):e?.close?.()}flush(){this.real?.flush()}get currentPlayoutTimeUs(){return this.real?.currentPlayoutTimeUs??0}setPlaybackRate(e){this.pendingRate=e,this.real?.setPlaybackRate?.(e)}destroy(){this.real?.destroy()}}class ca{audioCtx;destination;nextScheduledTime=0;activeSources=[];_playbackRate=1;playbackDelaySec;clock;constructor(e,t,i=200,s){this.audioCtx=e,this.destination=t??e.destination,this.playbackDelaySec=i/1e3,this.clock=s??{now:()=>1e3*performance.now()}}toAudioCtxTime(e){const t=(e-this.clock.now())/1e6;return this.audioCtx.currentTime+t}schedule(e,t){const i=e,s=this.audioCtx.createBuffer(i.numberOfChannels,i.numberOfFrames,i.sampleRate);for(let e=0;e=n?this.nextScheduledTime:t>0?Math.max(this.toAudioCtxTime(t)+this.playbackDelaySec,n):n+this.playbackDelaySec;const a=this.audioCtx.createBufferSource();a.buffer=s,a.playbackRate.value=this._playbackRate,a.connect(this.destination),a.start(r),this.nextScheduledTime=r+s.duration/this._playbackRate,this.activeSources.push(a),a.onended=()=>{const e=this.activeSources.indexOf(a);-1!==e&&this.activeSources.splice(e,1)}}setPlaybackRate(e){this._playbackRate=e}flush(){for(const e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources.length=0,this.nextScheduledTime=0}get currentPlayoutTimeUs(){return 1e6*this.audioCtx.currentTime}destroy(){this.flush()}}function da(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function ha(e,t,i){e[t]=i>>>24&255,e[t+1]=i>>>16&255,e[t+2]=i>>>8&255,e[t+3]=255&i}function la(e,t){return String.fromCharCode(e[t+4],e[t+5],e[t+6],e[t+7])}function ua(e,t){return da(e,t)}function pa(e,t,i){let s=t+8;for(;s+8<=i;){const t=ua(e,s);if(t<8)break;if("mdia"===la(e,s)){let i=s+8;const n=s+t;for(;i+8<=n;){const t=ua(e,i);if(t<8)break;if("hdlr"===la(e,i)&&i+16<=n)return String.fromCharCode(e[i+16],e[i+17],e[i+18],e[i+19]);i+=t}}s+=t}return null}function ma(e,t,i){let s=t+8;for(;s+8<=i;){const t=ua(e,s);if(t<8)break;if("tkhd"===la(e,s)){const t=1===e[s+8]?s+32:s+20;if(t+4<=i)return da(e,t)}s+=t}return null}function ga(e,t){const i=t.reduce((e,t)=>e+t.byteLength,0),s=new Uint8Array(8+i);ha(s,0,8+i),s[4]=e.charCodeAt(0),s[5]=e.charCodeAt(1),s[6]=e.charCodeAt(2),s[7]=e.charCodeAt(3);let n=8;for(const e of t)s.set(e,n),n+=e.byteLength;return s}function fa(e,t,i,s){const n=[];let r=t+8;for(;r+8<=i;){const t=ua(e,r);if(t<8)break;if("trex"===la(e,r)){if(r+16<=i){da(e,r+12)===s&&n.push(e.slice(r,r+t))}}else n.push(e.slice(r,r+t));r+=t}return ga("mvex",n)}function _a(e,t){let i=-1,s=0,n=0;for(;n+8<=e.byteLength;){const t=ua(e,n);if(t<8)break;if("moov"===la(e,n)){i=n,s=t;break}n+=t}if(i<0)return e;const r=i+s;let a=null,o=0;for(n=i+8;n+8<=r;){const i=ua(e,n);if(i<8)break;if("trak"===la(e,n)){o++;pa(e,n,n+i)===t&&(a=ma(e,n,n+i))}n+=i}if(o<=1||null===a)return e;const c=[];for(n=i+8;n+8<=r;){const i=ua(e,n);if(i<8)break;const s=la(e,n);if("trak"===s){pa(e,n,n+i)===t&&c.push(e.slice(n,n+i))}else"mvex"===s?c.push(fa(e,n,n+i,a)):c.push(e.slice(n,n+i));n+=i}const d=e.slice(0,i),h=e.slice(r),l=ga("moov",c),u=new Uint8Array(d.byteLength+l.byteLength+h.byteLength);let p=0;return u.set(d,p),p+=d.byteLength,u.set(l,p),p+=l.byteLength,u.set(h,p),u}function va(e){const t=[];let i=0;for(;i+8<=e.byteLength;){const s=ua(e,i);if(s<8)break;const n=la(e,i);if(t.push(`${n}(${s})`),"moov"===n){let n=i+8;for(;n+8<=i+s;){const i=ua(e,n);if(i<8)break;t.push(` ${la(e,n)}(${i})`),n+=i}}i+=s}return t.join(", ")}function ba(e){if(e.byteLength<8||"moof"!==la(e,0))return null;const t=ua(e,0);let i=8;for(;i+8<=t;){const t=ua(e,i);if(t<8)break;if("traf"===la(e,i)){let s=i+8;const n=i+t;for(;s+8<=n;){const t=ua(e,s);if(t<8)break;if("tfdt"===la(e,s)){return{offset:s,version:e[s+8]}}s+=t}}i+=t}return null}function Sa(e){const t=ba(e);if(!t)return null;const i=new DataView(e.buffer,e.byteOffset,e.byteLength),s=t.offset+12;return 0===t.version?BigInt(i.getUint32(s)):i.getBigUint64(s)}function Ea(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}const ya=256,Ta=1024,Ca=2048;function wa(e){if(e.byteLength<16)return{};const t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=t.getUint8(9)<<16|t.getUint8(10)<<8|t.getUint8(11);let s=16;return 1&i&&(s+=8),2&i&&(s+=4),8&i?s+4>e.byteLength?{}:{defaultSampleDuration:t.getUint32(s)}:{}}function Ra(e,t,i){if(e.byteLength<16)return{totalDuration:0n,sampleCount:0,scored:!1};const s=new DataView(e.buffer,e.byteOffset,e.byteLength),n=s.getUint8(9)<<16|s.getUint8(10)<<8|s.getUint8(11),r=s.getUint32(12);let a=16;1&n&&(a+=4),4&n&&(a+=4);if(0!==(n&ya)){const t=4+(!!(512&n)?4:0)+(0!==(n&Ta)?4:0)+(0!==(n&Ca)?4:0);if(a+r*t>e.byteLength)return{totalDuration:0n,sampleCount:0,scored:!1};let i=0n,o=a;for(let e=0;e0?i:void 0);return void 0===o?{totalDuration:0n,sampleCount:r,scored:!1}:{totalDuration:BigInt(r)*BigInt(o),sampleCount:r,scored:!0}}function Ia(e){const t=new Map;let i=0;for(;i+8<=e.byteLength;){const s=la(e,i),n=ua(e,i);if(n<8)break;if("moov"!==s){i+=n;continue}const r=i+n;let a=i+8;for(;a+8<=r;){const i=ua(e,a);if(i<8)break;if("mvex"!==la(e,a)){a+=i;continue}const s=a+i;let n=a+8;for(;n+8<=s;){const i=ua(e,n);if(i<8)break;if("trex"===la(e,n)&&i>=32){const s=new DataView(e.buffer,e.byteOffset+n,i),r=s.getUint32(12),a=s.getUint32(20),o=s.getUint32(24),c=s.getUint32(28);t.set(r,{trackId:r,defaultSampleDuration:a,defaultSampleSize:o,defaultSampleFlags:c})}n+=i}a+=i}i+=n}return t}const Aa=8,ka=9,Oa=21;function Na(e){return e.byteLength<1?-1:e[0]>>1&63}function Pa(e){return e>=0&&e<=31}function La(e,t,i){const s=function(e){let t=0,i=-1,s=0,n=-1,r=0;for(;t+8<=e.byteLength;){const a=la(e,t),o=ua(e,t);if(o<8)return null;"moof"===a&&-1===i?(i=t,s=o):"mdat"===a&&-1!==i&&-1===n&&(n=t,r=o),t+=o}return-1===i||-1===n?null:{moofOffset:i,moofSize:s,mdatOffset:n,mdatSize:r}}(e);if(!s)return null;const n=e.subarray(s.moofOffset,s.moofOffset+s.moofSize),r=e.subarray(s.mdatOffset+8,s.mdatOffset+s.mdatSize),a=function(e){let t=-1,i=0,s=0,n=8;for(;n+8<=e.byteLength;){const r=ua(e,n);if(r<8)return null;"traf"===la(e,n)&&(s++,-1===t&&(t=n,i=r)),n+=r}if(1!==s||-1===t)return null;let r=-1,a=0,o=-1,c=0,d=0;n=t+8;const h=t+i;for(;n+8<=h;){const t=ua(e,n);if(t<8)return null;const i=la(e,n);"tfhd"===i&&-1===r?(r=n,a=t):"trun"===i&&(d++,-1===o&&(o=n,c=t)),n+=t}return-1===r||-1===o||1!==d?null:{trafOffset:t,trafSize:i,tfhdOffset:r,tfhdSize:a,trunOffset:o,trunSize:c}}(n);if(!a)return null;const o=new DataView(n.buffer,n.byteOffset+a.tfhdOffset,a.tfhdSize);if(1&(o.getUint8(9)<<16|o.getUint8(10)<<8|o.getUint8(11)))return null;const c=n.subarray(a.tfhdOffset,a.tfhdOffset+a.tfhdSize),d=n.subarray(a.trunOffset,a.trunOffset+a.trunSize),h=function(e){if(e.byteLength<16)return{};const t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=t.getUint8(9)<<16|t.getUint8(10)<<8|t.getUint8(11);let s=16;1&i&&(s+=8),2&i&&(s+=4);const n={};if(8&i){if(s+4>e.byteLength)return n;n.defaultSampleDuration=t.getUint32(s),s+=4}if(16&i){if(s+4>e.byteLength)return n;n.defaultSampleSize=t.getUint32(s),s+=4}if(32&i){if(s+4>e.byteLength)return n;n.defaultSampleFlags=t.getUint32(s),s+=4}return n}(c),l=function(e,t,i){if(e.byteLength<16)return null;const s=new DataView(e.buffer,e.byteOffset,e.byteLength),n=s.getUint8(8),r=s.getUint8(9)<<16|s.getUint8(10)<<8|s.getUint8(11),a=s.getUint32(12);let o=16;1&r&&(o+=4);let c=0,d=!1;if(4&r){if(o+4>e.byteLength)return null;c=s.getUint32(o),d=!0,o+=4}const h=0!==(r&ya),l=!!(512&r),u=0!==(r&Ta),p=0!==(r&Ca),m=(h?4:0)+(l?4:0)+(u?4:0)+(p?4:0);if(o+a*m>e.byteLength)return null;const g=t.defaultSampleDuration??(i&&i.defaultSampleDuration>0?i.defaultSampleDuration:void 0),f=t.defaultSampleSize??(i&&i.defaultSampleSize>0?i.defaultSampleSize:void 0),_=t.defaultSampleFlags??(i&&i.defaultSampleFlags>0?i.defaultSampleFlags:void 0),v=[];let b=0;for(let e=0;er.byteLength)return null;const p=new Array(l.length);let m=0,g=0,f=0;for(let e=0;e>16&255,b[10]=p>>8&255,b[11]=255&p,ha(b,12,g),a&&0!==v){const e=n.getInt32(16);S.setInt32(16,e+v)}let E=l;for(let n=0;n=t)return!1;for(const i of this.ranges)if(e=t)return;let i=e,s=t;const n=[];let r=!1;for(const e of this.ranges)e.ends?(r||(n.push({start:i,end:s}),r=!0),n.push(e)):(e.starts&&(s=e.end));r||n.push({start:i,end:s}),this.ranges.length=0;for(const e of n)this.ranges.push(e)}getRanges(){return this.ranges.map(e=>({start:e.start,end:e.end}))}clear(){this.ranges.length=0}toString(){return 0===this.ranges.length?"empty":this.ranges.map(e=>`[${e.start}-${e.end})`).join(", ")}}class Da{ms;videoBuffer=null;audioBuffer=null;videoQueue=[];audioQueue=[];committedGroupFloor=new Map;video;objectUrl=null;destroyed=!1;initialized=!1;onFirstFrame=null;onError=null;onStall=null;firstFrameFired=!1;playTriggered=!1;stallStartTime=null;videoRing=[];audioRing=[];appendSeq=0;lastAppendWallMs={video:null,audio:null};videoInitSummary=null;audioInitSummary=null;videoErrorDumped=!1;videoTimelines=new Map;audioTimelines=new Map;videoTrex;audioTrex;pendingVideoRanges=[];pendingAudioRanges=[];pendingVideoTrackName=null;pendingAudioTrackName=null;pendingVideoGroupId;pendingAudioGroupId;appendErrored={video:!1,audio:!1};changingType={video:!1,audio:!1};seenDiagnostics=new Set;debug=!1;logDebug(e,...t){this.debug&&console.log(e,...t)}logWarn(e,...t){this.debug&&console.warn(e,...t)}constructor(e){this.video=e;const t=globalThis.ManagedMediaSource,i="undefined"!=typeof MediaSource?MediaSource:void 0,s=t??i;if(!s)throw new Error("Neither MediaSource nor ManagedMediaSource is available");this.ms=new s,t?(this.video.disableRemotePlayback=!0,this.video.srcObject=this.ms,this.objectUrl=null):(this.objectUrl=URL.createObjectURL(this.ms),this.video.src=this.objectUrl),this.video.addEventListener("playing",this.handlePlaying),this.video.addEventListener("waiting",this.handleWaiting),this.video.addEventListener("timeupdate",this.handleTimeUpdate),this.video.addEventListener("error",this.handleVideoError)}get mediaElement(){return this.video}initialize(e){if(this.initialized)return;this.initialized=!0;const t=()=>{try{if(e.video){const t=`video/mp4; codecs="${e.video.codec}"`;if(this.logDebug("[MSE] Creating video SourceBuffer:",t),this.videoBuffer=this.ms.addSourceBuffer(t),this.videoBuffer.mode="segments",this.videoBuffer.addEventListener("error",()=>{const e=this.video.error;this.appendErrored.video=!0,this.pendingVideoRanges=[],this.dumpRingOnFailure("video SourceBuffer error"),this.onError?.(new Error(`Video SourceBuffer error (code=${e?.code}, ${e?.message??"unknown"})`))}),this.videoBuffer.addEventListener("updateend",()=>this.handleUpdateEnd("video")),e.video.initData.byteLength>0){const t=_a(e.video.initData,"vide"),i=va(t),s=Array.from(t.slice(0,64)).map(e=>e.toString(16).padStart(2,"0")).join(" ");this.videoInitSummary=`codec=${e.video.codec} bytes=${t.byteLength} boxes=[${i}] head=[${s}]`,this.logDebug("[MSE] Video init: %s",this.videoInitSummary);const n=Ia(t).values().next();n.done||(this.videoTrex=n.value),this.videoBuffer.appendBuffer(t.buffer)}}if(e.audio){const t=`audio/mp4; codecs="${e.audio.codec}"`;if(this.logDebug("[MSE] Creating audio SourceBuffer:",t),this.audioBuffer=this.ms.addSourceBuffer(t),this.audioBuffer.mode="segments",this.audioBuffer.addEventListener("error",()=>{const e=this.video.error;this.appendErrored.audio=!0,this.pendingAudioRanges=[],this.dumpRingOnFailure("audio SourceBuffer error"),this.onError?.(new Error(`Audio SourceBuffer error (code=${e?.code}, ${e?.message??"unknown"})`))}),this.audioBuffer.addEventListener("updateend",()=>this.handleUpdateEnd("audio")),e.audio.initData.byteLength>0){const t=_a(e.audio.initData,"soun"),i=va(t),s=Array.from(t.slice(0,64)).map(e=>e.toString(16).padStart(2,"0")).join(" ");this.audioInitSummary=`codec=${e.audio.codec} bytes=${t.byteLength} boxes=[${i}] head=[${s}]`,this.logDebug("[MSE] Audio init: %s",this.audioInitSummary);const n=Ia(t).values().next();n.done||(this.audioTrex=n.value),this.audioBuffer.appendBuffer(t.buffer)}}}catch(e){this.onError?.(e instanceof Error?e:new Error(String(e)))}};"open"===this.ms.readyState?t():this.ms.addEventListener("sourceopen",t,{once:!0})}appendChunk(e,t,i,s){if(this.destroyed)return;const n="video"===e?this.videoBuffer:this.audioBuffer;if(!n)return;if(void 0!==s){const t=`${e}:${i}`,n=this.committedGroupFloor.get(t);if(void 0!==n&&s0?r.push(void 0!==s?{data:t,trackName:i,groupId:s}:{data:t,trackName:i}):this.doAppend(e,n,t,i,s)}async changeType(e,t,i){if(this.destroyed)return;const s="video"===e?this.videoBuffer:this.audioBuffer;if(!s)throw new Error(`MseMediaSource.changeType: ${e} SourceBuffer not initialized`);const n=s;if("function"!=typeof n.changeType)throw new Error("MseMediaSource.changeType: SourceBuffer.changeType not supported");if(this.changingType[e])throw new Error(`MseMediaSource.changeType: ${e} already in changing-type state`);this.changingType[e]=!0;try{for(("video"===e?this.videoQueue:this.audioQueue).length=0;s.updating;)await this.waitForBufferEvent(s);const r=_a(i,"video"===e?"vide":"soun"),a=`${e}/mp4; codecs="${t}"`;this.logDebug("[MSE] changeType %s → %s (init=%dB)",e,a,r.byteLength),n.changeType(a),s.appendBuffer(r.buffer),await this.waitForBufferEvent(s);const o=Ia(r),c=Array.from(o.values())[0];"video"===e?this.videoTrex=c:this.audioTrex=c;const d=va(r),h=`codec=${t} bytes=${r.byteLength} (post-changeType) boxes=[${d}]`;"video"===e?this.videoInitSummary=h:this.audioInitSummary=h,s.updating||(s.timestampOffset=this.video.currentTime,this.logDebug("[MSE] changeType timestampOffset set to %.2f",this.video.currentTime));("video"===e?this.videoTimelines:this.audioTimelines).clear()}finally{this.changingType[e]=!1}this.drainQueue(e),this.playTriggered&&this.video.paused&&this.video.play().catch(()=>{})}waitForBufferEvent(e){return new Promise((t,i)=>{const s=()=>{e.removeEventListener("updateend",s),e.removeEventListener("error",n),t()},n=()=>{e.removeEventListener("updateend",s),e.removeEventListener("error",n),i(new Error("SourceBuffer error during changeType"))};e.addEventListener("updateend",s),e.addEventListener("error",n)})}setTimestampOffset(e,t){const i="video"===e?this.videoBuffer:this.audioBuffer;if(i)try{i.updating||(i.timestampOffset=t)}catch(e){this.onError?.(e instanceof Error?e:new Error(String(e)))}}endOfStream(){if("open"===this.ms.readyState)try{this.ms.endOfStream()}catch{}}getBufferAheadUs(){const e=this.video;if(!e.buffered.length)return this.playTriggered?0:null;for(let t=0;t=e.buffered.start(t)&&e.currentTime<=e.buffered.end(t))return 1e6*Math.max(0,e.buffered.end(t)-e.currentTime);return this.playTriggered?0:null}getCommittedGroupFloor(e,t){return this.committedGroupFloor.get(`${e}:${t}`)}clearTimeline(e,t){("video"===e?this.videoTimelines:this.audioTimelines).delete(t)&&this.logWarn('[MSE] timeline cleared for %s track "%s" (discontinuity)',e,t)}reset(){try{this.videoBuffer&&!this.videoBuffer.updating&&this.ms.removeSourceBuffer(this.videoBuffer),this.audioBuffer&&!this.audioBuffer.updating&&this.ms.removeSourceBuffer(this.audioBuffer)}catch{}this.videoBuffer=null,this.audioBuffer=null,this.videoQueue.length=0,this.audioQueue.length=0,this.initialized=!1,this.videoTimelines.clear(),this.audioTimelines.clear(),this.committedGroupFloor.clear(),this.pendingVideoRanges=[],this.pendingAudioRanges=[],this.pendingVideoTrackName=null,this.pendingAudioTrackName=null,this.pendingVideoGroupId=void 0,this.pendingAudioGroupId=void 0,this.appendErrored={video:!1,audio:!1},this.changingType.video=!1,this.changingType.audio=!1,this.videoTrex=void 0,this.audioTrex=void 0,this.seenDiagnostics.clear()}destroy(){this.destroyed=!0,this.video.removeEventListener("playing",this.handlePlaying),this.video.removeEventListener("waiting",this.handleWaiting),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.video.removeEventListener("error",this.handleVideoError),this.reset(),this.objectUrl&&(URL.revokeObjectURL(this.objectUrl),this.objectUrl=null),this.video.removeAttribute("src"),this.video.srcObject=null,this.video.load(),this.onFirstFrame=null,this.onError=null,this.onStall=null}drainQueue(e){const t="video"===e?this.videoBuffer:this.audioBuffer,i="video"===e?this.videoQueue:this.audioQueue;if(this.changingType[e])return;if(!t||t.updating||0===i.length){if((null!==this.videoBuffer?"video"===e:"audio"===e)&&!this.playTriggered&&this.video.buffered.length>0){let e=this.video.buffered.start(0),t=this.video.buffered.end(0)-e;for(let i=1;it&&(e=s,t=n)}(this.video.currentTime=e+t)&&(this.video.currentTime=e),this.video.play().then(()=>{this.playTriggered=!0}).catch(()=>{this.video.muted=!0,this.video.play().then(()=>{this.playTriggered=!0}).catch(()=>{})})}return}for(;i.length>0;){const t=i[0];if(void 0!==t.groupId){const s=`${e}:${t.trackName}`,n=this.committedGroupFloor.get(s);if(void 0!==n&&t.groupId{i?.(e,t),r=!0};let o=0;for(;o+8<=e.byteLength;){const i=la(e,o),r=ua(e,o);if(r<8)break;if("moof"!==i){o+=r;continue}n++;const c=o,d=e.subarray(o,o+r);o+=r;const h=[];let l=8,u=!1;for(;l+8<=d.byteLength;){const e=ua(d,l);if(e<8){a("malformed-moof",`moof at ${c}: inner box size ${e} at ${l}`),u=!0;break}"traf"===la(d,l)&&h.push(d.subarray(l,l+e)),l+=e}if(u)continue;if(0===h.length){a("no-trun",`moof at ${c}: no traf`);continue}if(h.length>1){a("multi-traf",`moof at ${c}: ${h.length} traf boxes (only first supported)`);continue}const p=h[0];let m=null,g=null;const f=[];let _=8,v=!1;for(;_+8<=p.byteLength;){const e=ua(p,_);if(e<8){a("malformed-moof",`traf at moof ${c}: inner box size ${e} at ${_}`),v=!0;break}const t=la(p,_),i=p.subarray(_,_+e);"tfhd"===t?m=i:"tfdt"===t?g=i:"trun"===t&&f.push(i),_+=e}if(v)continue;if(!g){a("no-tfdt",`moof at ${c}: traf has no tfdt`);continue}if(0===f.length){a("no-trun",`moof at ${c}: traf has no trun`);continue}const b=new DataView(g.buffer,g.byteOffset,g.byteLength);let S;if(0===g[8]){if(g.byteLength<16){a("malformed-moof",`moof at ${c}: tfdt v0 too short`);continue}S=BigInt(b.getUint32(12))}else{if(g.byteLength<20){a("malformed-moof",`moof at ${c}: tfdt v1 too short`);continue}S=b.getBigUint64(12)}const E=m?wa(m):{},y=t?.defaultSampleDuration;let T=0n,C=0,w=!0;for(const e of f){const t=Ra(e,E.defaultSampleDuration,y);if(!t.scored){w=!1;break}T+=t.totalDuration,C+=t.sampleCount}w?s.push({startTime:S,endTime:S+T,sampleCount:C}):a("no-duration",`moof at ${c}: no duration resolvable from trun/tfhd/trex`)}return 0===n?[]:r?null:s}(i,"video"===e?this.videoTrex:this.audioTrex,(t,i)=>{const s=`${e}:${t}`;this.seenDiagnostics.has(s)||(this.seenDiagnostics.add(s),this.logWarn(`[MSE] ${e} parse skipped (${t}): ${i}`))});null===r&&this.logWarn(`[MSE] ${e} payload analysis incomplete — appending anyway (fail open)`);const a=("video"===e?this.videoTimelines:this.audioTimelines).get(s);if(null!==r&&r.length>0&&a){if(void 0!==r.find(e=>a.overlaps(e.startTime,e.endTime)))return void this.logWarn(`[MSE] drop overlapping ${e} payload on track "${s}": ranges=${r.map(e=>`[${e.startTime}-${e.endTime})`).join(",")} timeline=${a.toString()}`)}if(this.recordAppend(e,i),!this.playTriggered){const t=Array.from(i.slice(0,24)).map(e=>e.toString(16).padStart(2,"0")).join(" ");this.logDebug("[MSE] appendBuffer %s: %dB head=[%s]",e,i.byteLength,t)}this.appendErrored[e]=!1;const o=r??[];"video"===e?(this.pendingVideoRanges=o,this.pendingVideoTrackName=s,this.pendingVideoGroupId=n):(this.pendingAudioRanges=o,this.pendingAudioTrackName=s,this.pendingAudioGroupId=n);try{t.appendBuffer(i.buffer)}catch(t){"video"===e?(this.pendingVideoRanges=[],this.pendingVideoTrackName=null):(this.pendingAudioRanges=[],this.pendingAudioTrackName=null),this.dumpRingOnFailure(`appendBuffer throw on ${e}`,t),this.onError?.(t instanceof Error?t:new Error(String(t)))}}handleUpdateEnd(e){if(!this.appendErrored[e]){const t="video"===e?this.pendingVideoRanges:this.pendingAudioRanges,i="video"===e?this.pendingVideoTrackName:this.pendingAudioTrackName,s="video"===e?this.pendingVideoGroupId:this.pendingAudioGroupId,n="video"===e?this.videoTimelines:this.audioTimelines;if(null!==i){let r=n.get(i);r||(r=new Ua,n.set(i,r));for(const e of t)r.insert(e.startTime,e.endTime);if(void 0!==s){const t=`${e}:${i}`,n=this.committedGroupFloor.get(t);(void 0===n||s>n)&&this.committedGroupFloor.set(t,s)}}}"video"===e?(this.pendingVideoRanges=[],this.pendingVideoTrackName=null,this.pendingVideoGroupId=void 0):(this.pendingAudioRanges=[],this.pendingAudioTrackName=null,this.pendingAudioGroupId=void 0),this.appendErrored[e]=!1,this.drainQueue(e)}recordAppend(e,t){const i="video"===e?this.videoRing:this.audioRing,s=performance.now(),n=this.lastAppendWallMs[e],r=function(e){if(e.byteLength<8)return null;let t=null,i=0,s=null,n=0;for(;n+8<=e.byteLength;){const r=la(e,n),a=ua(e,n);if(a<8)break;"moof"===r&&null===t?(t=n,i=a):"mdat"===r&&null===s&&(s=a),n+=a}return null===t?{bmd:null,mdatSize:s}:{bmd:Sa(e.subarray(t,t+i)),mdatSize:s}}(t),{nalTypes:a,mdatHead:o}=function(e){const t=[];let i="",s=0;for(;s+8<=e.byteLength;){const n=(e[s]<<24|e[s+1]<<16|e[s+2]<<8|e[s+3])>>>0;if("mdat"===String.fromCharCode(e[s+4],e[s+5],e[s+6],e[s+7])){const r=s+8,a=Math.min(s+n,e.byteLength),o=Math.min(48,a-r);i=Array.from(e.subarray(r,r+o)).map(e=>e.toString(16).padStart(2,"0")).join(" ");let c=r,d=0;for(;c+4>>0;if(c+=4,0===i||c>=a)break;const s=e[c]>>1&63;t.push(s),d++,c+=i}return{nalTypes:t,mdatHead:i}}if(n<8)break;s+=n}return{nalTypes:t,mdatHead:i}}(t),c={mediaType:e,seq:this.appendSeq++,totalSize:t.byteLength,bmd:r?.bmd??null,mdatSize:r?.mdatSize??null,nalTypes:a,mdatHead:o,appendWallMs:s,deltaFromPrevMs:null===n?null:s-n};for(i.push(c);i.length>8;)i.shift();this.lastAppendWallMs[e]=s}dumpRingOnFailure(e,t){if(this.videoErrorDumped)return;if(this.videoErrorDumped=!0,!this.debug)return;const i=this.video.error;console.error("[MSE] pipeline failure — source: %s",e),t&&console.error("[MSE] thrown:",t),i&&console.error("[MSE] video.error: code=%d message=%s",i.code,i.message),this.videoInitSummary&&console.error(`[MSE] video init: ${this.videoInitSummary}`),this.audioInitSummary&&console.error(`[MSE] audio init: ${this.audioInitSummary}`);const s=e=>0===e.size?"empty":Array.from(e.entries()).map(([e,t])=>`"${e}": ${t.toString()}`).join("; ");console.error(`[MSE] video timelines: ${s(this.videoTimelines)}`),console.error(`[MSE] audio timelines: ${s(this.audioTimelines)}`),console.error("[MSE] last 8 appends (oldest → newest):");for(const e of[...this.videoRing,...this.audioRing].sort((e,t)=>e.seq-t.seq)){const t=null===e.deltaFromPrevMs?"n/a":`${e.deltaFromPrevMs.toFixed(1)}ms`,i=null===e.bmd?"n/a":e.bmd.toString();console.error(`[MSE] #${e.seq} ${e.mediaType}: total=${e.totalSize}B mdat=${e.mdatSize??"n/a"} bmd=${i} Δ=${t} wall=${e.appendWallMs.toFixed(1)} nal=[${e.nalTypes.join(",")}]`),e.mdatHead&&console.error(`[MSE] mdat head: ${e.mdatHead}`)}try{if(this.videoBuffer)for(let e=0;e{null!==this.stallStartTime&&(this.stallStartTime=null),this.firstFrameFired||(this.firstFrameFired=!0,this.onFirstFrame?.())};handleWaiting=()=>{this.stallStartTime=performance.now()};handleTimeUpdate=()=>{if(!this.firstFrameFired&&this.video.currentTime>0&&(this.firstFrameFired=!0,this.onFirstFrame?.()),null!==this.stallStartTime){const e=performance.now()-this.stallStartTime;this.stallStartTime=null,this.onStall?.(e)}};handleVideoError=()=>{this.appendErrored.video=!0,this.appendErrored.audio=!0,this.pendingVideoRanges=[],this.pendingAudioRanges=[],this.dumpRingOnFailure("