Class: MOQtailClient
Represents a Media Over QUIC Transport (MOQT) client session.
Construct it, attach listeners with on(), then call MOQtailClient.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
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
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
await client.disconnect();Extends
Constructors
Constructor
new MOQtailClient(
options):MOQtailClient
Stores options; nothing happens on the network until MOQtailClient.init, so listeners attached in between see everything, the handshake included.
Parameters
options
Returns
MOQtailClient
Overrides
Properties
aliasFullTrackNameMap
readonlyaliasFullTrackNameMap:Map<bigint,FullTrackName>
Maps track aliases to full track names for quick resolution during data handling.
controlStream
controlStream:
ControlStream
Outgoing / incoming control message stream pair.
controlStreamTimeoutMs?
optionalcontrolStreamTimeoutMs?:number
Timeout (ms) for control stream read operations; undefined => no explicit timeout.
dataStreamTimeoutMs?
optionaldataStreamTimeoutMs?: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
readonlypeerSubscribeNamespace:Set<Tuple>
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
readonlypublications:Map<bigint,SubscribePublication|FetchPublication|PublishPublication>
Active publications (SUBSCRIBE or FETCH) keyed by requestId to manage object stream controllers and lifecycle. Subset / specialization view of requests.
publishedNamespaces
readonlypublishedNamespaces:Set<Tuple>
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
readonlyreceivedDatagramObjects:ReadableStream<MoqtObject>
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
readonlyrequestIdMap:RequestIdMap
Bidirectional requestId <-> full track name mapping to reconstruct metadata for incoming objects.
requests
readonlyrequests:Map<bigint,MOQtailRequest>
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
readonlysubscribedNamespaces:Set<Tuple>
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
readonlysubscribedTracks:Set<Tuple>
subscriptionAliasMap
readonlysubscriptionAliasMap:Map<bigint,bigint>
Bidirectional track alias <-> subscription requestId mapping
subscriptions
readonlysubscriptions: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
readonlytrackSources:Map<string,Track>
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).
Accessors
clientSetup
Get Signature
get clientSetup():
Setup
Gets the setup this client sent during handshake.
Returns
The Setup 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 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
Gets the current server setup configuration.
Returns
The Setup instance the server sent back during handshake.
Methods
acceptPushedTrack()
acceptPushedTrack(
msg):ReadableStream<MoqtObject>
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
The incoming Publish control message
Returns
ReadableStream<MoqtObject>
- A stream of MoqtObjects being pushed by the publisher
addOrUpdateTrack()
addOrUpdateTrack(
track):void
Registers or updates a Track definition for local publishing or serving.
A Track describes a logical media/data stream, identified by a unique name and namespace.
- If
trackSource.liveis present, the track can be served to subscribers in real-time. - If
trackSource.pastis present, the track can be fetched for historical data. - If both are present, the track supports both live and historical access.
Parameters
track
The Track instance to add or update. See TrackSource for live/past source options.
Returns
void
void
Throws
: MOQtailError If the client has been destroyed.
Example
Create a live video track from getUserMedia
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
force?
boolean = false
Returns
boolean
createDatagramSender()
createDatagramSender(
trackAlias):SendDatagramStream
Create a datagram sender for a specific track.
Parameters
trackAlias
bigint
Track alias for outgoing datagrams
Returns
SendDatagramStream for writing MoqtObjects as datagrams
Throws
MOQtailError if datagram writer not initialized (call startDatagrams() first)
Example
const sender = client.createDatagramSender(trackAlias);
await sender.write(moqtObject);disconnect()
disconnect(
reason?):Promise<void>
Gracefully terminates this MOQtailClient session and releases underlying WebTransport resources.
Parameters
reason?
unknown
Optional application-level reason (string or error) recorded and wrapped in an InternalError passed to sessionterminated listeners. Before MOQtailClient.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
await client.disconnect();With reason
await client.disconnect('user logout');Idempotent double call
await client.disconnect();
await client.disconnect(); // no errorPage unload safety
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[K]>
Returns
void
Inherited from
fetch()
fetch(
args):Promise<RequestError|FetchResult>
One-shot retrieval of a bounded object span of a track, returning a stream of MoqtObjects.
Field highlights (in FetchOptions):
- priority: 0 (highest) .. 255 (lowest); out-of-range rejected.
- groupOrder:
GroupOrder.Originalto 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 (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
Returns
Promise<RequestError | FetchResult>
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 only for early termination; objects already in flight may still arrive.
Examples
Groups 10 through 12, inclusive
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
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. 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
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
await client.fetchCancel(456n)
await client.fetchCancel(456n) // no errorinit()
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 If called more than once, or after MOQtailClient.disconnect.
Throws
:ProtocolViolationError If the server sends an unexpected or invalid message during setup.
Example
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
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[K]
Returns
void
Inherited from
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[K]
Returns
void
Inherited from
publish()
publish(
fullTrackName,forward,trackAlias,parameters?,trackProperties?):Promise<RequestError| {requestId:bigint;trackAlias:bigint; }>
Proactively push a track to the relay/peer.
Parameters
fullTrackName
forward
boolean
trackAlias
bigint
parameters?
trackProperties?
Returns
Promise<RequestError | { 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|RequestError>
Declare (publish) a track namespace to the peer so subscribers using matching prefixes (via MOQtailClient.subscribeNamespace) can discover and begin subscribing/fetching its tracks.
Typical flow (publisher side):
- Prepare / register one or more Track objects locally (see MOQtailClient.addOrUpdateTrack).
- Call
publishNamespace(namespace)once per namespace prefix to expose those tracks. - Later, call MOQtailClient.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 on success (namespace added to publishedNamespaces) or RequestError 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
parameters?
Returns
Promise<RequestOk | RequestError>
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. - Discovery subscribers (those who issued MOQtailClient.subscribeNamespace) will receive the resulting PublishNamespace message.
Examples
Minimal announce
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
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 from this client's local catalog.
This deletes the in-memory entry inserted via MOQtailClient.addOrUpdateTrack, so future lookups by its Track.fullTrackName will fail. Does not automatically:
- Withdraw the namespace announcement (call MOQtailClient.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
The exact Track instance (its canonical name is used as the key).
Returns
void
Throws
: MOQtailError If the client has been destroyed.
Example
// 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 to send
Returns
Promise<void>
Throws
MOQtailError if datagram writer not initialized
Example
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, 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 | undefined
Returns
void
Example
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|SubscribeResult>
Subscribes to a track and returns a stream of MoqtObjects matching the requested window and relay forwarding mode.
forward: truetells the relay to forward objects to this subscriber as they arrive.forward: falsemeans the relay subscribes upstream but buffers objects locally, not forwarding them to you.locationFilterselects which Objects are delivered; omitted, the subscription is unfiltered. An absolute start in the future waits for that object.- A FillParameters in
parametersalso retrieves Objects already published, on a fill fetch stream.
The method returns either a RequestError (on refusal) or a SubscribeResult: the subscription requestId, its SUBSCRIBE_OK, a ReadableStream of MoqtObjects, and a done promise carrying the PUBLISH_DONE that ends it. Use the requestId for MOQtailClient.unsubscribe or MOQtailClient.subscribeUpdate. Use the stream to decode and display objects.
Parameters
args
SubscribeOptions describing the subscription window and relay forwarding behavior.
Returns
Promise<RequestError | SubscribeResult>
Either a RequestError or { requestId, subscribeOk, stream, done }.
Throws
: MOQtailError If the client is destroyed.
Throws
: ProtocolViolationError 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 On transport/protocol failure (disconnect is triggered before rethrow).
Examples
Subscribe to the latest object and receive future objects as they arrive
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)
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|RequestError; }>
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.
Parameters
trackNamespacePrefix
parameters?
Returns
Promise<{ cancel: () => Promise<void>; response: RequestOk | RequestError; }>
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
const unsubscribe = client.subscribeToTrackDatagrams(trackAlias, (obj) => {
console.log('Received datagram:', obj.payload);
});
// Later: unsubscribe();subscribeTracks()
subscribeTracks(
trackNamespacePrefix,parameters?):Promise<{cancel: () =>Promise<void>;response:RequestOk|RequestError; }>
Parameters
trackNamespacePrefix
parameters?
Returns
Promise<{ cancel: () => Promise<void>; response: RequestOk | RequestError; }>
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: falsestops forwarding new objects,trueresumes). - 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 referencing the original subscription requestId and new bounds.
Returns
Promise<void>
Promise that resolves when the update control frame is sent.
Throws
:MOQtailError If the client is destroyed.
Throws
:ProtocolViolationError If the update would widen the window (earlier start, later end group, or invalid ordering).
Throws
:InternalError 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: falsestops 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
await client.subscribeUpdate({ subscriptionRequestId, locationFilter: new LocationFilter(LocationFilterType.AbsoluteStart, laterGroup, 0n), forward: true, priority });Convert tailing subscription into bounded slice
await client.subscribeUpdate({ subscriptionRequestId, locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, startGroup, 0n, cutoffGroup), forward: false, priority });Lower priority only
await client.subscribeUpdate({ subscriptionRequestId, forward: true, priority: 200 });switch()
switch(
args):Promise<RequestError|SubscribeResult>
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 referencing the subscription to switch from and the new subscription options.
Returns
Promise<RequestError | SubscribeResult>
Either a RequestError (refusal) or the new request's SubscribeResult, where stream is the same ReadableStream object returned by the original subscribe() call and done that subscription's, which resolves once the whole switched chain is over.
Throws
:MOQtailError If the client is destroyed.
Throws
:ProtocolViolationError If switchFromRequestId does not name an active subscription.
Throws
:InternalError On transport/control failure (disconnect is triggered before rethrow).
Example
Switch to a different track
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|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
Returns
FullTrackName | undefined
trackStatus()
trackStatus(
fullTrackName,trackAlias,parameters?):Promise<RequestOk|RequestError>
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
The track to report on.
trackAlias
bigint
Alias to carry in the request.
parameters?
Optional message parameters.
Returns
Promise<RequestOk | RequestError>
A RequestOk on success or a RequestError on refusal.
Example
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. Must match to be removed from internal set.
Behavior:
- Does not delete locally registered Track 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
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 for a matching prefix should receive the resulting NAMESPACE_DONE. Consider calling this before MOQtailClient.disconnect to give consumers prompt notice.
Examples
Basic usage
await client.unpublishNamespace(namespace)Idempotent
await client.unpublishNamespace(namespace) // first time
await client.unpublishNamespace(namespace) // no error, already removedunsubscribe()
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.
Returns
Promise<void>
Promise that resolves once the request stream has been reset.
Throws
:MOQtailError If the client is destroyed.
Throws
:InternalError 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
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
await client.unsubscribe(123n);
await client.unsubscribe(123n); // no errorunsubscribeFromTrackDatagrams()
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.
Parameters
trackNamespacePrefix
The prefix that subscription was opened with.
Returns
Promise<void>
setLogEnabledModules()
staticsetLogEnabledModules(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()
staticsetLogLevel(level):void
Sets the global log level for all moqtail-ts loggers.
Parameters
level
The minimum LogLevel to output. Use LogLevel.NONE to silence all logs.
Returns
void