---
url: https://docs.moqtail.dev/ts/api/client/classes/MOQtailClient.md
---
# Class: MOQtailClient

Represents a Media Over QUIC Transport (MOQT) client session.

Construct it, attach listeners with `on()`, then call [MOQtailClient.init](#init) to open the
session. Once initialized, the client provides high-level methods for MOQT requests and publishing. If a protocol
violation occurs, the client terminates; a new client is needed to reconnect.

## Usage

### Connect and Subscribe to a Track

```ts
const client = new MOQtailClient({ url });
client.on('sessionterminated', (reason) => console.warn('Session ended:', reason));
await client.init();
const result = await client.subscribe({
  fullTrackName,
  locationFilter: new LocationFilter(LocationFilterType.NextObject),
  forward: true,
  groupOrder: GroupOrder.Original,
  priority: 0
});
if (!(result instanceof RequestError)) {
  for await (const object of result.stream) {
    // Consume MOQT objects
  }
}
```

### Publish a namespace for Publishing

```ts
const client = new MOQtailClient({ url });
await client.init();
const publishNamespaceResult = await client.publishNamespace(Tuple.fromUtf8Path('camera/main'));
if (!(publishNamespaceResult instanceof RequestError)) {
  // Ready to publish objects under this namespace
}
```

### Graceful Shutdown

```ts
await client.disconnect();
```

## Extends

* [`Emitter`](../../util/classes/Emitter.md)<[`ClientEvents`](../interfaces/ClientEvents.md)>

## Constructors

### Constructor

> **new MOQtailClient**(`options`): `MOQtailClient`

Stores `options`; nothing happens on the network until [MOQtailClient.init](#init), so
listeners attached in between see everything, the handshake included.

#### Parameters

##### options

[`MOQtailClientOptions`](../type-aliases/MOQtailClientOptions.md)

#### Returns

`MOQtailClient`

#### Overrides

[`Emitter`](../../util/classes/Emitter.md).[`constructor`](../../util/classes/Emitter.md#constructor)

## Properties

### aliasFullTrackNameMap

> `readonly` **aliasFullTrackNameMap**: `Map`<`bigint`, [`FullTrackName`](../../model/classes/FullTrackName.md)>

Maps track aliases to full track names for quick resolution during data handling.

***

### controlStream

> **controlStream**: [`ControlStream`](ControlStream.md)

Outgoing / incoming control message stream pair.

***

### controlStreamTimeoutMs?

> `optional` **controlStreamTimeoutMs?**: `number`

Timeout (ms) for control stream read operations; undefined => no explicit timeout.

***

### dataStreamTimeoutMs?

> `optional` **dataStreamTimeoutMs?**: `number`

Timeout (ms) applied to reading incoming data streams; undefined => no explicit timeout.

***

### fillOpenTimeoutMs

> **fillOpenTimeoutMs**: `number` = `DEFAULT_FILL_OPEN_TIMEOUT_MS`

How long (ms) after SUBSCRIBE_OK a fill fetch stream may take to open before ordering stops waiting for it.

***

### goawayReceived

> **goawayReceived**: `boolean` = `false`

Whether the peer has sent a GOAWAY on the control stream. Once it has, this side
should not start new requests; a second one closes the session with
PROTOCOL_VIOLATION.

***

### peerSubscribeNamespace

> `readonly` **peerSubscribeNamespace**: `Set`<[`Tuple`](../../model/classes/Tuple.md)>

Namespace prefixes (tuples) the peer has requested announce notifications for via SUBSCRIBE_NAMESPACE.
Used to decide which locally issued ANNOUNCE messages should be forwarded (future optimization: prefix trie).

***

### publications

> `readonly` **publications**: `Map`<`bigint`, [`SubscribePublication`](SubscribePublication.md) | [`FetchPublication`](FetchPublication.md) | [`PublishPublication`](PublishPublication.md)>

Active publications (SUBSCRIBE or FETCH) keyed by requestId to manage object stream controllers and lifecycle.
Subset / specialization view of `requests`.

***

### publishedNamespaces

> `readonly` **publishedNamespaces**: `Set`<[`Tuple`](../../model/classes/Tuple.md)>

Track namespaces this client has successfully published (received REQUEST_OK). Source of truth for
deciding what to withdraw on teardown or targeted removal (future optimization: prefix trie).

***

### receivedDatagramObjects

> `readonly` **receivedDatagramObjects**: `ReadableStream`<[`MoqtObject`](../../model/classes/MoqtObject.md)>

Stream of all received MoqtObjects from datagrams across all tracks
Consumer should filter by fullTrackName as needed

WARNING: Only one reader should be active. For multiple subscribers,
use subscribeToTrackDatagrams() instead

***

### requestIdMap

> `readonly` **requestIdMap**: [`RequestIdMap`](../../model/classes/RequestIdMap.md)

Bidirectional requestId <-> full track name mapping to reconstruct metadata for incoming objects.

***

### requests

> `readonly` **requests**: `Map`<`bigint`, [`MOQtailRequest`](../type-aliases/MOQtailRequest.md)>

All in‑flight request objects keyed by requestId (SUBSCRIBE, FETCH, ANNOUNCE, etc). Facilitates lookup
when responses / data arrive. Entries are removed on completion or error.

***

### subscribedNamespaces

> `readonly` **subscribedNamespaces**: `Set`<[`Tuple`](../../model/classes/Tuple.md)>

Namespace prefixes this client has subscribed to (issued SUBSCRIBE_NAMESPACE). Enables automatic filtering
of incoming NAMESPACE / NAMESPACE_DONE. Maintained locally; no dedupe of overlapping / shadowing prefixes yet.

***

### subscribedTracks

> `readonly` **subscribedTracks**: `Set`<[`Tuple`](../../model/classes/Tuple.md)>

***

### subscriptionAliasMap

> `readonly` **subscriptionAliasMap**: `Map`<`bigint`, `bigint`>

Bidirectional track alias <-> subscription requestId mapping

***

### subscriptions

> `readonly` **subscriptions**: `Map`<`bigint`, `any`>

Active SUBSCRIBE request wrappers keyed by track alias for rapid alias -> subscription resolution during
incoming unidirectional data handling.

***

### switchDrainTimeoutMs

> **switchDrainTimeoutMs**: `number` = `DEFAULT_SWITCH_DRAIN_TIMEOUT_MS`

How long (ms) a track a soft switch handed over from may stay quiet before it is
retired anyway, if no PUBLISH_DONE ends its drain first.

***

### trackAliasResolutionTimeoutMs

> **trackAliasResolutionTimeoutMs**: `number` = `DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS`

How long (ms) an incoming data stream waits for the control message that establishes
its track alias before the stream is abandoned.

***

### trackSources

> `readonly` **trackSources**: `Map`<`string`, [`Track`](../type-aliases/Track.md)>

Locally registered track definitions keyed by full track name string. Populated via addOrUpdateTrack.
Does not imply the track has been announced or has active publications.

***

### webTransport

> **webTransport**: `WebTransport`

Underlying WebTransport session (set by [MOQtailClient.init](#init)).

## Accessors

### clientSetup

#### Get Signature

> **get** **clientSetup**(): [`Setup`](../../model/classes/Setup.md)

Gets the setup this client sent during handshake.

##### Returns

[`Setup`](../../model/classes/Setup.md)

The [Setup](../../model/classes/Setup.md) instance written first on the control stream.

***

### isDatagramsEnabled

#### Get Signature

> **get** **isDatagramsEnabled**(): `boolean`

Returns true if datagram support is currently active

##### Returns

`boolean`

***

### maxFilterRanges

#### Get Signature

> **get** **maxFilterRanges**(): `bigint`

How many filter ranges this client allows the server in one request: the
MAX_FILTER_RANGES it advertised, [DEFAULT_MAX_FILTER_RANGES](../variables/DEFAULT_MAX_FILTER_RANGES.md) unless the
caller's setup options set one.

##### Returns

`bigint`

***

### peerMaxFilterRanges

#### Get Signature

> **get** **peerMaxFilterRanges**(): `bigint`

How many filter ranges the server allows in one request: its MAX_FILTER_RANGES,
or 0 when it sent none, which allows no Range Filter at all.

##### Returns

`bigint`

***

### serverSetup

#### Get Signature

> **get** **serverSetup**(): [`Setup`](../../model/classes/Setup.md)

Gets the current server setup configuration.

##### Returns

[`Setup`](../../model/classes/Setup.md)

The [Setup](../../model/classes/Setup.md) instance the server sent back during handshake.

## Methods

### acceptPushedTrack()

> **acceptPushedTrack**(`msg`): `ReadableStream`<[`MoqtObject`](../../model/classes/MoqtObject.md)>

Registers an incoming PUBLISH announcement as a valid data receiver.
This prepares the client to ingest pushed data streams matching the published alias.
\*

#### Parameters

##### msg

[`Publish`](../../model/classes/Publish.md)

The incoming Publish control message

#### Returns

`ReadableStream`<[`MoqtObject`](../../model/classes/MoqtObject.md)>

* A stream of MoqtObjects being pushed by the publisher

***

### addOrUpdateTrack()

> **addOrUpdateTrack**(`track`): `void`

Registers or updates a [Track](../type-aliases/Track.md) definition for local publishing or serving.

A [Track](../type-aliases/Track.md) describes a logical media/data stream, identified by a unique name and namespace.

* If `trackSource.live` is present, the track can be served to subscribers in real-time.
* If `trackSource.past` is present, the track can be fetched for historical data.
* If both are present, the track supports both live and historical access.

#### Parameters

##### track

[`Track`](../type-aliases/Track.md)

The [Track](../type-aliases/Track.md) instance to add or update. See [TrackSource](../interfaces/TrackSource.md) for live/past source options.

#### Returns

`void`

void

#### Throws

: [MOQtailError](../../model/classes/MOQtailError.md) If the client has been destroyed.

#### Example

**Create a live video track from getUserMedia**

```ts
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
const videoTrack = stream.getVideoTracks()[0];

// Convert video frames to MoqtObject instances using your chosen scheme (e.g. MSF, CMAF, etc.)
// This part is application-specific and not provided by MOQtail:
const liveReadableStream: ReadableStream<MoqtObject> = ...

// Register the track for live subscription
client.addOrUpdateTrack({
  fullTrackName: FullTrackName.tryNew('camera', 'main'),
  trackSource: { live: new LiveTrackSource(liveReadableStream) },
  publisherPriority: 0 // highest priority
});

// For a hybrid track (live + past), add each object to the cache as you write it:
const cache = new RingBufferObjectCache(300);
client.addOrUpdateTrack({
  fullTrackName: FullTrackName.tryNew('camera', 'main'),
  trackSource: new HybridTrackSource(cache, liveReadableStream),
  publisherPriority: 8
});
```

***

### completeSubscription()

> **completeSubscription**(`request`, `force?`): `boolean`

Ends a subscription whose publisher has said how many streams it opened and has
now delivered all of them, and reports whether that happened.

Both halves of that arrive on their own: a PUBLISH_DONE carries the count, and
the streams finish whenever they finish. Either can be last, so this is checked
from both -- a drained switch target has usually finished its streams well
before the PUBLISH_DONE that ends it.

#### Parameters

##### request

[`SubscribeRequest`](SubscribeRequest.md)

##### force?

`boolean` = `false`

#### Returns

`boolean`

***

### createDatagramSender()

> **createDatagramSender**(`trackAlias`): [`SendDatagramStream`](SendDatagramStream.md)

Create a datagram sender for a specific track.

#### Parameters

##### trackAlias

`bigint`

Track alias for outgoing datagrams

#### Returns

[`SendDatagramStream`](SendDatagramStream.md)

SendDatagramStream for writing MoqtObjects as datagrams

#### Throws

MOQtailError if datagram writer not initialized (call startDatagrams() first)

#### Example

```ts
const sender = client.createDatagramSender(trackAlias);
await sender.write(moqtObject);
```

***

### disconnect()

> **disconnect**(`reason?`): `Promise`<`void`>

Gracefully terminates this MOQtailClient session and releases underlying [WebTransport](https://developer.mozilla.org/docs/Web/API/WebTransport) resources.

#### Parameters

##### reason?

`unknown`

Optional application-level reason (string or error) recorded and wrapped in an [InternalError](../../model/classes/InternalError.md)
passed to `sessionterminated` listeners. Before [MOQtailClient.init](#init) it only marks the client destroyed.

#### Returns

`Promise`<`void`>

Promise that resolves once shutdown logic completes. Subsequent calls are safe no-ops.

#### Examples

**Basic usage**

```ts
await client.disconnect();
```

**With reason**

```ts
await client.disconnect('user logout');
```

**Idempotent double call**

```ts
await client.disconnect();
await client.disconnect(); // no error
```

**Page unload safety**

```ts
window.addEventListener('beforeunload', () => {
  client.disconnect('page unload');
});
```

***

### emit()

> **emit**<`K`>(`event`, ...`args`): `void`

Calls every listener of `event` with `args`. Allocates nothing when there are none.

#### Type Parameters

##### K

`K` *extends* `"goaway"` | `"sessionterminated"` | `"messagesent"` | `"messagereceived"` | `"datareceived"` | `"datasent"` | `"dataevent"` | `"datagramreceived"` | `"datagramsent"` | `"orderinggap"` | `"namespacepublished"` | `"forwardstatechange"` | `"peerpublish"` | `"peerpublishdone"` | `"peerpublishskipped"` | `"peersubscribenamespace"` | `"peersubscribetracks"` | `"peernamespace"` | `"peernamespacedone"`

#### Parameters

##### event

`K`

##### args

...`Parameters`<[`ClientEvents`](../interfaces/ClientEvents.md)\[`K`]>

#### Returns

`void`

#### Inherited from

[`Emitter`](../../util/classes/Emitter.md).[`emit`](../../util/classes/Emitter.md#emit)

***

### fetch()

> **fetch**(`args`): `Promise`<[`RequestError`](../../model/classes/RequestError.md) | [`FetchResult`](../interfaces/FetchResult.md)>

One-shot retrieval of a bounded object span of a track, returning a stream of [MoqtObject](../../model/classes/MoqtObject.md)s.

Field highlights (in [FetchOptions](../type-aliases/FetchOptions.md)):

* priority: 0 (highest) .. 255 (lowest); out-of-range rejected.
* groupOrder: `GroupOrder.Original` to preserve publisher order; or reorder ascending/descending if supported by server.
* locationFilter: Which Objects to fetch. An absolute filter names groups; a relative one counts back from the Largest Object.
* parameters: Optional version-specific extension block.

Returns either a [RequestError](../../model/classes/RequestError.md) (refusal / invalid request at protocol level) or `{ requestId, fetchOk, stream }` whose `stream`
ends naturally after the bounded range completes (no explicit cancel needed for normal completion).

Use cases:

* Grab a historical window for scrubbing UI while a separate live subscription tails.
* Late joiner fetching a short back-buffer then discarding the stream.
* Analytics batch job pulling a fixed slice without subscribing long-term.

#### Parameters

##### args

[`FetchOptions`](../type-aliases/FetchOptions.md)

#### Returns

`Promise`<[`RequestError`](../../model/classes/RequestError.md) | [`FetchResult`](../interfaces/FetchResult.md)>

#### Throws

MOQtailError If client is destroyed.

#### Throws

ProtocolViolationError Priority out of \[0-255].

#### Throws

InternalError Transport/control failure (the client disconnects first) then rethrows original error.

#### Remarks

* Result stream is finite; reader close occurs automatically when last object delivered.
* Use [MOQtailClient.fetchCancel](#fetchcancel) only for early termination; objects already in flight may still arrive.

#### Examples

**Groups 10 through 12, inclusive**

```ts
const r = await client.fetch({
  fullTrackName,
  priority: 64,
  groupOrder: GroupOrder.Original,
  locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, 10n, 0n, 12n)
})
if (!(r instanceof RequestError)) {
  for await (const obj of r.stream) {
    // consume objects then stream ends automatically
  }
}
```

**The last 5 groups, counting the current one**

```ts
const slice = await client.fetch({
  fullTrackName,
  priority: 32,
  groupOrder: GroupOrder.Original,
  locationFilter: new LocationFilter(LocationFilterType.RelativeStart, 5n)
})
```

***

### fetchCancel()

> **fetchCancel**(`requestId`): `Promise`<`void`>

Request early termination of an in‑flight FETCH identified by its `requestId`.

Use when the consumer no longer needs the remaining objects (user scrubbed away, UI panel closed, replaced by a new fetch).
Resets the fetch's request stream with `CANCELLED` if the id currently maps to an active fetch; otherwise silent no-op (idempotent).

Parameter semantics:

* requestId: bigint returned from [MOQtailClient.fetch](#fetch). Numbers auto-converted to bigint.

Current behavior / limitations:

* Data stream closure after cancel is TODO (objects may still arrive briefly).
* Unknown / already finished request: ignored without error.
* Only targets FETCH requests (not subscriptions).

#### Parameters

##### requestId

`number` | `bigint`

#### Returns

`Promise`<`void`>

#### Throws

MOQtailError If client is destroyed.

#### Throws

InternalError Failure while sending the cancel (client disconnects first).

#### Remarks

Follow-up improvement planned: actively close associated readable stream controller immediately upon acknowledgment.

#### Examples

**Cancel shortly after starting**

```ts
const r = await client.fetch({ fullTrackName, priority: 32, groupOrder: GroupOrder.Original, locationFilter })
if (!(r instanceof RequestError)) {
  // user navigated away
  await client.fetchCancel(r.requestId)
}
```

**Idempotent double cancel**

```ts
await client.fetchCancel(456n)
await client.fetchCancel(456n) // no error
```

***

### init()

> **init**(): `Promise`<`void`>

Opens the WebTransport session and performs the MOQT setup handshake. Runs once: a
second call throws, and a failed one leaves the client unusable, so a retry needs a
new client.

#### Returns

`Promise`<`void`>

#### Throws

:[MOQtailError](../../model/classes/MOQtailError.md) If called more than once, or after [MOQtailClient.disconnect](#disconnect).

#### Throws

:[ProtocolViolationError](../../model/classes/ProtocolViolationError.md) If the server sends an unexpected or invalid message during setup.

#### Example

```ts
const client = new MOQtailClient({ url: 'moqt://relay.moqtail.dev' })
client.on('messagesent', (msg) => console.log('Sent:', msg))
await client.init()
```

***

### migrateRequest()

> **migrateRequest**(`requestId`, `goAway`): `Promise`<`boolean`>

**`Internal`**

Re-issues one request on a fresh stream after the peer sent a GOAWAY on its request
stream (§10.4). Only that request moves: the session, and every other request on it,
are left alone.

The re-issued request consumes a new Request ID (§10.1), so the opening message is
re-stamped with it. The id the caller holds keeps naming the request; only the id on
the wire changes.

#### Parameters

##### requestId

`bigint`

##### goAway

[`GoAway`](../../model/classes/GoAway.md)

#### Returns

`Promise`<`boolean`>

True if the request was re-issued here. A GOAWAY naming a new session URI
is not: opening a session is the application's call, so it is surfaced as a
`goaway` event and the request stream is closed.

***

### off()

> **off**<`K`>(`event`, `listener`): `void`

Removes `listener`, the same function given to `on()`, from `event`.

#### Type Parameters

##### K

`K` *extends* `"goaway"` | `"sessionterminated"` | `"messagesent"` | `"messagereceived"` | `"datareceived"` | `"datasent"` | `"dataevent"` | `"datagramreceived"` | `"datagramsent"` | `"orderinggap"` | `"namespacepublished"` | `"forwardstatechange"` | `"peerpublish"` | `"peerpublishdone"` | `"peerpublishskipped"` | `"peersubscribenamespace"` | `"peersubscribetracks"` | `"peernamespace"` | `"peernamespacedone"`

#### Parameters

##### event

`K`

##### listener

[`ClientEvents`](../interfaces/ClientEvents.md)\[`K`]

#### Returns

`void`

#### Inherited from

[`Emitter`](../../util/classes/Emitter.md).[`off`](../../util/classes/Emitter.md#off)

***

### on()

> **on**<`K`>(`event`, `listener`): `void`

Adds `listener` for `event`. Adding the same function twice has no effect.

#### Type Parameters

##### K

`K` *extends* `"goaway"` | `"sessionterminated"` | `"messagesent"` | `"messagereceived"` | `"datareceived"` | `"datasent"` | `"dataevent"` | `"datagramreceived"` | `"datagramsent"` | `"orderinggap"` | `"namespacepublished"` | `"forwardstatechange"` | `"peerpublish"` | `"peerpublishdone"` | `"peerpublishskipped"` | `"peersubscribenamespace"` | `"peersubscribetracks"` | `"peernamespace"` | `"peernamespacedone"`

#### Parameters

##### event

`K`

##### listener

[`ClientEvents`](../interfaces/ClientEvents.md)\[`K`]

#### Returns

`void`

#### Inherited from

[`Emitter`](../../util/classes/Emitter.md).[`on`](../../util/classes/Emitter.md#on)

***

### publish()

> **publish**(`fullTrackName`, `forward`, `trackAlias`, `parameters?`, `trackProperties?`): `Promise`<[`RequestError`](../../model/classes/RequestError.md) | { `requestId`: `bigint`; `trackAlias`: `bigint`; }>

Proactively push a track to the relay/peer.

#### Parameters

##### fullTrackName

[`FullTrackName`](../../model/classes/FullTrackName.md)

##### forward

`boolean`

##### trackAlias

`bigint`

##### parameters?

[`MessageParameter`](../../model/type-aliases/MessageParameter.md)\[]

##### trackProperties?

[`TrackProperty`](../../model/type-aliases/TrackProperty.md)\[]

#### Returns

`Promise`<[`RequestError`](../../model/classes/RequestError.md) | { `requestId`: `bigint`; `trackAlias`: `bigint`; }>

***

### publishDone()

> **publishDone**(`publishRequestId`, `statusCode?`, `reasonPhrase?`): `Promise`<`void`>

Signals the end of a published track to the peer/relay.
\*

#### Parameters

##### publishRequestId

`number` | `bigint`

The original requestId used when `publish()` was called.

##### statusCode?

`number` = `PublishDoneStatusCode.TrackEnded`

##### reasonPhrase?

`string` = `'Track Ended'`

#### Returns

`Promise`<`void`>

***

### publishNamespace()

> **publishNamespace**(`trackNamespace`, `parameters?`): `Promise`<[`RequestOk`](../../model/classes/RequestOk.md) | [`RequestError`](../../model/classes/RequestError.md)>

Declare (publish) a track namespace to the peer so subscribers using matching prefixes (via [MOQtailClient.subscribeNamespace](#subscribenamespace))
can discover and begin subscribing/fetching its tracks.

Typical flow (publisher side):

1. Prepare / register one or more [Track](../type-aliases/Track.md) objects locally (see [MOQtailClient.addOrUpdateTrack](#addorupdatetrack)).
2. Call `publishNamespace(namespace)` once per namespace prefix to expose those tracks.
3. Later, call [MOQtailClient.unpublishNamespace](#unpublishnamespace) when no longer publishing under that namespace.

Parameter semantics:

* trackNamespace: Tuple representing the namespace prefix (e.g. `Tuple.fromUtf8Path('camera/main')`). All tracks whose full names start with this tuple are considered within the announce scope.
* parameters: Optional `MessageParameter[]` appended to the PUBLISH_NAMESPACE message.

Returns: [RequestOk](../../model/classes/RequestOk.md) on success (namespace added to `publishedNamespaces`) or [RequestError](../../model/classes/RequestError.md) explaining refusal.

Use cases:

* Make a camera or sensor namespace available before any objects are pushed.
* Dynamically expose a newly created room / session namespace.
* Re-announce after reconnect to repopulate discovery state.

#### Parameters

##### trackNamespace

[`Tuple`](../../model/classes/Tuple.md)

##### parameters?

[`MessageParameter`](../../model/type-aliases/MessageParameter.md)\[]

#### Returns

`Promise`<[`RequestOk`](../../model/classes/RequestOk.md) | [`RequestError`](../../model/classes/RequestError.md)>

#### Throws

MOQtailError If client is destroyed.

#### Throws

InternalError Transport/control failure while sending or awaiting response (client disconnects first).

#### Remarks

* Duplicate announce detection is TODO (currently a second call will still send another PUBLISH_NAMESPACE; receiver behavior may vary).
* Successful announces are tracked in `publishedNamespaces`; manual removal occurs via [MOQtailClient.unpublishNamespace](#unpublishnamespace).
* Discovery subscribers (those who issued [MOQtailClient.subscribeNamespace](#subscribenamespace)) will receive the resulting [PublishNamespace](../../model/classes/PublishNamespace.md) message.

#### Examples

**Minimal announce**

```ts
const res = await client.publishNamespace(Tuple.fromUtf8Path('camera/main'))
if (res instanceof RequestOk) {
  // ready to publish objects under tracks with this namespace prefix
}
```

**PublishNamespace with an authorization token**

```ts
const token = AuthorizationToken.newUseValue(tokenType, tokenValue)
const resp = await client.publishNamespace(Tuple.fromUtf8Path('room/1234'), [token])
```

***

### removeTrack()

> **removeTrack**(`track`): `void`

Removes a previously registered [Track](../type-aliases/Track.md) from this client's local catalog.

This deletes the in-memory entry inserted via [MOQtailClient.addOrUpdateTrack](#addorupdatetrack), so future lookups by its [Track.fullTrackName](../type-aliases/Track.md#fulltrackname) will fail.
Does **not** automatically:

* Withdraw the namespace announcement (call [MOQtailClient.unpublishNamespace](#unpublishnamespace) separately if you want to inform peers)
* Cancel active subscriptions or fetches (they continue until normal completion)
* Affect already-sent objects.

If the track was not present, the call is a silent no-op (idempotent removal).

#### Parameters

##### track

[`Track`](../type-aliases/Track.md)

The exact [Track](../type-aliases/Track.md) instance (its canonical name is used as the key).

#### Returns

`void`

#### Throws

: [MOQtailError](../../model/classes/MOQtailError.md) If the client has been destroyed.

#### Example

```ts
// Register a track
client.addOrUpdateTrack(track);

// Later, when no longer publishing:
client.removeTrack(track);

// Optionally, inform peers that the namespace is no longer available:
await client.unpublishNamespace(track.fullTrackName.namespace);
```

***

### sendDatagram()

> **sendDatagram**(`trackAlias`, `object`): `Promise`<`void`>

Send a single MoqtObject as a datagram.
Convenience method for one-off datagram sends.

#### Parameters

##### trackAlias

`bigint`

Track alias for this object

##### object

[`MoqtObject`](../../model/classes/MoqtObject.md)

MoqtObject to send

#### Returns

`Promise`<`void`>

#### Throws

MOQtailError if datagram writer not initialized

#### Example

```ts
await client.sendDatagram(trackAlias, moqtObject);
```

***

### setEarlyDiscardPolicy()

> **setEarlyDiscardPolicy**(`config`): `void`

Sets (or replaces) the client-level default early discard policy for incoming subgroup streams.

When set, each incoming subgroup QUIC stream is given a deadline of `subgroupReceiveTimeout` ms to
complete. If the stream has not finished within that window it is cancelled — objects already
delivered to the subscription are kept, but no further objects arrive from that stream.

This is a client-wide default. Individual subscriptions can override it via the `earlyDiscardPolicy`
field in [SubscribeOptions](../type-aliases/SubscribeOptions.md), which takes precedence over this setting.

The policy takes effect on the next stream accepted after this call. Passing a new config
replaces the previous one. Pass `undefined` to remove the default.

#### Parameters

##### config

[`EarlyDiscardPolicyConfig`](../type-aliases/EarlyDiscardPolicyConfig.md) | `undefined`

#### Returns

`void`

#### Example

```ts
client.setEarlyDiscardPolicy({ subgroupReceiveTimeout: 2000 })
```

***

### startDatagrams()

> **startDatagrams**(): `Promise`<`void`>

Start receiving datagrams from the WebTransport connection.
Must be called before datagrams can be received (unless enableDatagrams: true was set in options).

#### Returns

`Promise`<`void`>

#### Throws

MOQtailError if client is destroyed or datagrams already started

***

### stopDatagrams()

> **stopDatagrams**(): `Promise`<`void`>

Stop receiving datagrams and release resources.
Idempotent - safe to call multiple times.

#### Returns

`Promise`<`void`>

***

### subscribe()

> **subscribe**(`args`): `Promise`<[`RequestError`](../../model/classes/RequestError.md) | [`SubscribeResult`](../interfaces/SubscribeResult.md)>

Subscribes to a track and returns a stream of [MoqtObject](../../model/classes/MoqtObject.md)s matching the requested window and relay forwarding mode.

* `forward: true` tells the relay to forward objects to this subscriber as they arrive.
* `forward: false` means the relay subscribes upstream but buffers objects locally, not forwarding them to you.
* `locationFilter` selects which Objects are delivered; omitted, the subscription is unfiltered. An absolute start in the
  future waits for that object.
* A [FillParameters](../../model/classes/FillParameters.md) in `parameters` also retrieves Objects already published, on a fill fetch stream.

The method returns either a [RequestError](../../model/classes/RequestError.md) (on refusal) or a [SubscribeResult](../interfaces/SubscribeResult.md): the subscription `requestId`, its
SUBSCRIBE_OK, a `ReadableStream` of [MoqtObject](../../model/classes/MoqtObject.md)s, and a `done` promise carrying the PUBLISH_DONE that ends it.
Use the `requestId` for [MOQtailClient.unsubscribe](#unsubscribe) or [MOQtailClient.subscribeUpdate](#subscribeupdate). Use the `stream` to decode and display objects.

#### Parameters

##### args

[`SubscribeOptions`](../type-aliases/SubscribeOptions.md)

[SubscribeOptions](../type-aliases/SubscribeOptions.md) describing the subscription window and relay forwarding behavior.

#### Returns

`Promise`<[`RequestError`](../../model/classes/RequestError.md) | [`SubscribeResult`](../interfaces/SubscribeResult.md)>

Either a [RequestError](../../model/classes/RequestError.md) or `{ requestId, subscribeOk, stream, done }`.

#### Throws

: [MOQtailError](../../model/classes/MOQtailError.md) If the client is destroyed.

#### Throws

: [ProtocolViolationError](../../model/classes/ProtocolViolationError.md) If required fields are missing or inconsistent.

#### Throws

: `InvalidFilterError` If the Range Filters exceed the server's MAX_FILTER_RANGES; nothing is sent.

#### Throws

: [InternalError](../../model/classes/InternalError.md) On transport/protocol failure (disconnect is triggered before rethrow).

#### Examples

**Subscribe to the latest object and receive future objects as they arrive**

```ts
const result = await client.subscribe({
  fullTrackName,
  locationFilter: new LocationFilter(LocationFilterType.NextObject),
  forward: true,
  groupOrder: GroupOrder.Original,
  priority: 32
});
if (!(result instanceof RequestError)) {
  for await (const obj of result.stream) {
    // decode and display obj
  }
}
```

**Subscribe to a future range of groups (waits for those objects to arrive)**

```ts
const result = await client.subscribe({
  fullTrackName,
  locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, startGroup, 0n, endGroup),
  forward: true,
  groupOrder: GroupOrder.Original,
  priority: 128
});
```

***

### subscribeNamespace()

> **subscribeNamespace**(`trackNamespacePrefix`, `parameters?`): `Promise`<{ `cancel`: () => `Promise`<`void`>; `response`: [`RequestOk`](../../model/classes/RequestOk.md) | [`RequestError`](../../model/classes/RequestError.md); }>

Subscribes to namespace announcements under a prefix (§10.18). Discovery only: the
peer answers NAMESPACE and NAMESPACE_DONE for matching namespaces, and nothing is
subscribed to. To be sent the tracks themselves, use
[MOQtailClient.subscribeTracks](#subscribetracks).

#### Parameters

##### trackNamespacePrefix

[`Tuple`](../../model/classes/Tuple.md)

##### parameters?

[`MessageParameter`](../../model/type-aliases/MessageParameter.md)\[]

#### Returns

`Promise`<{ `cancel`: () => `Promise`<`void`>; `response`: [`RequestOk`](../../model/classes/RequestOk.md) | [`RequestError`](../../model/classes/RequestError.md); }>

***

### subscribeToTrackDatagrams()

> **subscribeToTrackDatagrams**(`trackAlias`, `handler`): () => `void`

Subscribe to receive datagrams for a specific track.
Multiple tracks can have separate handlers that run concurrently.

#### Parameters

##### trackAlias

`bigint`

Track alias to subscribe to

##### handler

(`obj`) => `void`

Function called for each received MoqtObject on this track

#### Returns

Unsubscribe function to remove the handler

() => `void`

#### Example

```ts
const unsubscribe = client.subscribeToTrackDatagrams(trackAlias, (obj) => {
  console.log('Received datagram:', obj.payload);
});
// Later: unsubscribe();
```

***

### subscribeTracks()

> **subscribeTracks**(`trackNamespacePrefix`, `parameters?`): `Promise`<{ `cancel`: () => `Promise`<`void`>; `response`: [`RequestOk`](../../model/classes/RequestOk.md) | [`RequestError`](../../model/classes/RequestError.md); }>

#### Parameters

##### trackNamespacePrefix

[`Tuple`](../../model/classes/Tuple.md)

##### parameters?

[`MessageParameter`](../../model/type-aliases/MessageParameter.md)\[]

#### Returns

`Promise`<{ `cancel`: () => `Promise`<`void`>; `response`: [`RequestOk`](../../model/classes/RequestOk.md) | [`RequestError`](../../model/classes/RequestError.md); }>

***

### subscribeUpdate()

> **subscribeUpdate**(`args`): `Promise`<`void`>

Narrows or updates an active subscription window and/or relay forwarding behavior.

Use this to:

* Move the start of the subscription forward (trim history or future window).
* Move the end group earlier (shorten the window).
* Change relay forwarding (`forward: false` stops forwarding new objects, `true` resumes).
* Adjust subscriber priority.

Only narrowing is allowed: you cannot move the start earlier or the end group later than the original subscription.
Forwarding and priority can be changed at any time.

#### Parameters

##### args

[`SubscribeUpdateOptions`](../type-aliases/SubscribeUpdateOptions.md)

[SubscribeUpdateOptions](../type-aliases/SubscribeUpdateOptions.md) referencing the original subscription `requestId` and new bounds.

#### Returns

`Promise`<`void`>

Promise that resolves when the update control frame is sent.

#### Throws

:[MOQtailError](../../model/classes/MOQtailError.md) If the client is destroyed.

#### Throws

:[ProtocolViolationError](../../model/classes/ProtocolViolationError.md) If the update would widen the window (earlier start, later end group, or invalid ordering).

#### Throws

:[InternalError](../../model/classes/InternalError.md) On transport/control failure (disconnect is triggered before rethrow).

#### Remarks

* Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
* Omitting a parameter (e.g. `priority`) leaves the previous value unchanged.
* Setting `forward: false` stops relay forwarding new objects after the current window drains.
* Safe to call multiple times; extra calls with unchanged bounds have no effect.

#### Examples

**Trim start forward**

```ts
await client.subscribeUpdate({ subscriptionRequestId, locationFilter: new LocationFilter(LocationFilterType.AbsoluteStart, laterGroup, 0n), forward: true, priority });
```

**Convert tailing subscription into bounded slice**

```ts
await client.subscribeUpdate({ subscriptionRequestId, locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, startGroup, 0n, cutoffGroup), forward: false, priority });
```

**Lower priority only**

```ts
await client.subscribeUpdate({ subscriptionRequestId, forward: true, priority: 200 });
```

***

### switch()

> **switch**(`args`): `Promise`<[`RequestError`](../../model/classes/RequestError.md) | [`SubscribeResult`](../interfaces/SubscribeResult.md)>

Switches an active subscription to a different track while retaining the same subscription's
output stream.

Sends a fresh SUBSCRIBE carrying a SwitchFrom parameter referencing `switchFromRequestId`. A soft
switch may keep delivering objects from the old track for a while after SUBSCRIBE_OK, and this can
be called again before the previous target has produced anything; only the first object actually
delivered by the newest switch target retires everything older.

#### Parameters

##### args

[`SwitchOptions`](../type-aliases/SwitchOptions.md)

[SwitchOptions](../type-aliases/SwitchOptions.md) referencing the subscription to switch from and the new subscription options.

#### Returns

`Promise`<[`RequestError`](../../model/classes/RequestError.md) | [`SubscribeResult`](../interfaces/SubscribeResult.md)>

Either a [RequestError](../../model/classes/RequestError.md) (refusal) or the new request's [SubscribeResult](../interfaces/SubscribeResult.md), where `stream`
is the same [ReadableStream](https://developer.mozilla.org/docs/Web/API/ReadableStream) object returned by the
original `subscribe()` call and `done` that subscription's, which resolves once the whole switched chain is over.

#### Throws

:[MOQtailError](../../model/classes/MOQtailError.md) If the client is destroyed.

#### Throws

:[ProtocolViolationError](../../model/classes/ProtocolViolationError.md) If `switchFromRequestId` does not name an active subscription.

#### Throws

:[InternalError](../../model/classes/InternalError.md) On transport/control failure (disconnect is triggered before rethrow).

#### Example

**Switch to a different track**

```ts
await client.switch({
  switchFromRequestId,
  switchMode: SwitchMode.Soft,
  newSubscribeOptions: { fullTrackName: newTrackName, priority: 0, groupOrder: GroupOrder.Original, locationFilter: new LocationFilter(LocationFilterType.NextObject) },
  onDrainDecision: (request) => true
});
```

***

### trackNameOf()

> **trackNameOf**(`header`): [`FullTrackName`](../../model/classes/FullTrackName.md) | `undefined`

The track a data stream carries. A subgroup stream can open before the response
that names its alias, so its header event may lack `fullTrackName`: ask again on a
later event of the same stream.

#### Parameters

##### header

[`DataHeaderEvent`](../type-aliases/DataHeaderEvent.md)

#### Returns

[`FullTrackName`](../../model/classes/FullTrackName.md) | `undefined`

***

### trackStatus()

> **trackStatus**(`fullTrackName`, `trackAlias`, `parameters?`): `Promise`<[`RequestOk`](../../model/classes/RequestOk.md) | [`RequestError`](../../model/classes/RequestError.md)>

Asks the peer for the current status of a track.

TRACK_STATUS is the seventh `First`-marked type: it opens its own bidi stream and
the REQUEST_OK answering it comes back there, after which the stream is closed.

#### Parameters

##### fullTrackName

[`FullTrackName`](../../model/classes/FullTrackName.md)

The track to report on.

##### trackAlias

`bigint`

Alias to carry in the request.

##### parameters?

[`MessageParameter`](../../model/type-aliases/MessageParameter.md)\[]

Optional message parameters.

#### Returns

`Promise`<[`RequestOk`](../../model/classes/RequestOk.md) | [`RequestError`](../../model/classes/RequestError.md)>

A [RequestOk](../../model/classes/RequestOk.md) on success or a [RequestError](../../model/classes/RequestError.md) on refusal.

#### Example

```ts
const status = await client.trackStatus(fullTrackName, trackAlias)
if (!(status instanceof RequestError)) {
  // track exists
}
```

***

### unpublishNamespace()

> **unpublishNamespace**(`trackNamespace`): `Promise`<`void`>

Withdraw a previously announced namespace so new subscribers no longer discover its tracks.

Use when shutting down publishing for a logical scope (camera offline, room closed, session ended).
Removes the namespace from `publishedNamespaces` locally and closes the stream its PUBLISH_NAMESPACE opened,
which is what withdraws the announcement (§3.3.2). This is also how an announce is retracted before the peer
has finished processing it.

Parameter semantics:

* trackNamespace: Exact tuple used during [MOQtailClient.publishNamespace](#publishnamespace). Must match to be removed from internal set.

Behavior:

* Does not delete locally registered [Track](../type-aliases/Track.md) objects (they remain in `trackSources`).
* Does not forcibly end active subscriptions that were already established; peers simply stop discovering it for new ones.
* Silent if the namespace was not currently recorded (idempotent style).

#### Parameters

##### trackNamespace

[`Tuple`](../../model/classes/Tuple.md)

#### Returns

`Promise`<`void`>

#### Throws

MOQtailError If client is destroyed before sending.

#### Throws

(rethrows original error) Any lower-level failure while sending results in a disconnect (unwrapped TODO: future wrap with InternalError for consistency).

#### Remarks

Peers that issued [MOQtailClient.subscribeNamespace](#subscribenamespace) for a matching prefix should receive the resulting NAMESPACE_DONE.
Consider calling this before [MOQtailClient.disconnect](#disconnect) to give consumers prompt notice.

#### Examples

**Basic usage**

```ts
await client.unpublishNamespace(namespace)
```

**Idempotent**

```ts
await client.unpublishNamespace(namespace) // first time
await client.unpublishNamespace(namespace) // no error, already removed
```

***

### unsubscribe()

> **unsubscribe**(`requestId`): `Promise`<`void`>

Stops an active subscription identified by its original SUBSCRIBE `requestId`.

Resets the subscription's request stream with `CANCELLED` if it is still active. If the id is unknown or already
cleaned up, the call is a silent no-op (hence multiple calls are idempotent).

Use this when you no longer want incoming objects for a track (e.g. user navigated away, switching quality).
Canceling the consumer stream reader does **not** auto-unsubscribe; call this explicitly for prompt cleanup.

#### Parameters

##### requestId

`number` | `bigint`

The id returned from [MOQtailClient.subscribe](#subscribe).

#### Returns

`Promise`<`void`>

Promise that resolves once the request stream has been reset.

#### Throws

:[MOQtailError](../../model/classes/MOQtailError.md) If the client is destroyed.

#### Throws

:[InternalError](../../model/classes/InternalError.md) Wrapped lower-level failure while attempting to send (session will be disconnected first).

#### Remarks

* Only targets SUBSCRIBE requests, not fetches. Passing a fetch request id is ignored (no-op).
* Safe to call multiple times; extra calls have no effect.

#### Examples

**Subscribe and later unsubscribe**

```ts
const sub = await client.subscribe({ fullTrackName, locationFilter: new LocationFilter(LocationFilterType.NextObject), forward: true, groupOrder: GroupOrder.Original, priority: 0 });
if (!(sub instanceof RequestError)) {
  // ...consume objects...
  await client.unsubscribe(sub.requestId);
}
```

**Idempotent usage**

```ts
await client.unsubscribe(123n);
await client.unsubscribe(123n); // no error
```

***

### unsubscribeFromTrackDatagrams()

> **unsubscribeFromTrackDatagrams**(`trackAlias`): `void`

Unsubscribe from datagram delivery for a specific track.

#### Parameters

##### trackAlias

`bigint`

Track alias to unsubscribe from

#### Returns

`void`

***

### unsubscribeNamespace()

> **unsubscribeNamespace**(`trackNamespacePrefix`): `Promise`<`void`>

Ends a prefix subscription started with [MOQtailClient.subscribeNamespace](#subscribenamespace).

#### Parameters

##### trackNamespacePrefix

[`Tuple`](../../model/classes/Tuple.md)

The prefix that subscription was opened with.

#### Returns

`Promise`<`void`>

***

### setLogEnabledModules()

> `static` **setLogEnabledModules**(`modules`): `void`

Restricts log output to the specified module names. Pass `null` to allow all modules.

#### Parameters

##### modules

`string`\[] | `null`

Array of module name strings, or `null` to enable all modules.

#### Returns

`void`

***

### setLogLevel()

> `static` **setLogLevel**(`level`): `void`

Sets the global log level for all moqtail-ts loggers.

#### Parameters

##### level

[`LogLevel`](../../util/enumerations/LogLevel.md)

The minimum [LogLevel](../../util/enumerations/LogLevel.md) to output. Use `LogLevel.NONE` to silence all logs.

#### Returns

`void`
