moqtail 0.12.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.cts CHANGED
@@ -1,49 +1,110 @@
1
- import { c as ControlMessage, U as MoqtObject, y as Location, u as FullTrackName, au as TrackExtension, ao as Subscribe, a4 as PublishDoneStatusCode, ae as RequestUpdate, F as Fetch, a2 as Publish, ad as RequestOk, aa as RequestError, a5 as PublishNamespace, p as FetchOk, aq as SubscribeOk, R as MessageParameter, ap as SubscribeNamespace, a8 as PublishOk, v as GroupOrder, q as FetchType, ak as SetupParameters, D as Datagram, r as FilterType, ay as Tuple, ac as RequestIdMap, a7 as PublishNamespaceDone, G as GoAway, an as SubgroupObject, al as SubgroupHeader, n as FetchObject, l as FetchHeader, a3 as PublishDone, ah as ServerSetup, a6 as PublishNamespaceCancel, X as NamespaceSubscribeOptions, aC as UnsubscribeNamespace, aw as TrackStatus, H as Header } from './setup_parameter-BgNrJRDS.cjs';
2
- import { L as LogLevel } from './logger-C6QS408Z.cjs';
1
+ import { A as RequestError, B as GoAway, En as FetchObject, F as RequestUpdate, H as FetchOk, Hn as ObjectStatus, I as SubscribeOk, In as FetchHeader, Jn as Location, Kn as Tuple, L as Publish, Ln as Datagram, Lt as LocationFilter, M as SubscribeTracks, N as SubscribeNamespace, O as StreamResetCode, On as ControlMessageType, P as TrackStatus, Pn as SwitchMode, R as PublishDone, Sn as FullTrackName, X as TrackProperty, _n as Header, at as Setup, bn as MoqtObject, ct as PublishNamespace, it as Fetch, j as RequestOk, jn as PublishDoneStatusCode, k as ControlMessage, kn as GroupOrder, lt as MessageParameter, pn as PublishSkipped, r as SetupOptions, vn as RequestIdMap, xn as SubgroupObject, yn as SubgroupHeader, z as Subscribe } from "./index-DBbxKcc1.cjs";
2
+ import { t as LogLevel } from "./logger-dEoueCj7.cjs";
3
3
 
4
+ //#region src/client/control_stream.d.ts
4
5
  /**
5
- * Copyright 2025 The MOQtail Authors
6
- *
7
- * Licensed under the Apache License, Version 2.0 (the "License");
8
- * you may not use this file except in compliance with the License.
9
- * You may obtain a copy of the License at
10
- *
11
- * http://www.apache.org/licenses/LICENSE-2.0
12
- *
13
- * Unless required by applicable law or agreed to in writing, software
14
- * distributed under the License is distributed on an "AS IS" BASIS,
15
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
- * See the License for the specific language governing permissions and
17
- * limitations under the License.
6
+ * Send half of the control plane: a unidirectional stream this endpoint opens and
7
+ * whose first message must be SETUP.
8
+ */
9
+ declare class ControlSendStream {
10
+ #private;
11
+ onMessageSent?: (msg: ControlMessage) => void;
12
+ constructor(writeStream: WritableStream<Uint8Array>, onMessageSent?: (msg: ControlMessage) => void);
13
+ send(message: ControlMessage): Promise<void>;
14
+ close(): Promise<void>;
15
+ }
16
+ /**
17
+ * Receive half of the control plane: the unidirectional stream the peer opens,
18
+ * whose first message must be SETUP.
19
+ */
20
+ declare class ControlRecvStream {
21
+ #private;
22
+ readonly stream: ReadableStream<ControlMessage>;
23
+ onMessageReceived?: (msg: ControlMessage) => void;
24
+ constructor(readStream: ReadableStream<Uint8Array>, partialMessageTimeoutMs?: number, onMessageReceived?: (msg: ControlMessage) => void);
25
+ close(): Promise<void>;
26
+ }
27
+ /**
28
+ * The control plane as a whole: the two independent unidirectional halves opened by
29
+ * each endpoint.
18
30
  */
19
-
20
31
  declare class ControlStream {
21
- #private;
22
- readonly stream: ReadableStream<ControlMessage>;
23
- onMessageSent?: (msg: ControlMessage) => void;
24
- onMessageReceived?: (msg: ControlMessage) => void;
25
- private constructor();
26
- static new(bidirectionalStream: WebTransportBidirectionalStream, partialMessageTimeoutMs?: number, onMessageSent?: (msg: ControlMessage) => void, onMessageReceived?: (msg: ControlMessage) => void): ControlStream;
27
- send(message: ControlMessage): Promise<void>;
28
- close(): Promise<void>;
32
+ #private;
33
+ readonly stream: ReadableStream<ControlMessage>;
34
+ constructor(sendHalf: ControlSendStream, recvHalf: ControlRecvStream);
35
+ send(message: ControlMessage): Promise<void>;
36
+ close(): Promise<void>;
29
37
  }
30
-
38
+ //#endregion
39
+ //#region src/client/data_event.d.ts
40
+ /** `in` for a stream the peer opened, `out` for one this client opened. */
41
+ type DataDirection = 'in' | 'out';
42
+ /** What every data event carries. */
43
+ type DataEventBase = {
44
+ direction: DataDirection; /** Local to this client, unique per data stream; every later event on the stream carries it. */
45
+ streamId: number;
46
+ /**
47
+ * When the client wrote or read it, as `performance.now()` in ms: high resolution and
48
+ * monotonic, so differences between events are exact. Add `performance.timeOrigin` for
49
+ * wall-clock time.
50
+ */
51
+ at: number;
52
+ };
53
+ /** A data stream opened: what its header says. */
54
+ type DataHeaderEvent = DataEventBase & {
55
+ kind: 'header';
56
+ stream: 'subgroup' | 'fetch'; /** Subgroup streams only. */
57
+ trackAlias?: bigint; /** Subgroup streams only. */
58
+ groupId?: bigint; /** Subgroup streams only; unknown here when the header defers it to the first Object ID. */
59
+ subgroupId?: bigint; /** Fetch streams only. */
60
+ requestId?: bigint; /** The track the stream belongs to, when the client knows it at header time. */
61
+ fullTrackName?: FullTrackName;
62
+ };
63
+ /** One object written or read. Only its identity and size are reported, never its payload. */
64
+ type DataObjectEvent = DataEventBase & {
65
+ kind: 'object';
66
+ groupId: bigint;
67
+ subgroupId?: bigint;
68
+ objectId: bigint;
69
+ payloadLength: number; /** Set for an object that carries a status instead of a payload. */
70
+ objectStatus?: ObjectStatus;
71
+ /**
72
+ * The object's LOC Timestamp property, when it carries one: the sender's media time,
73
+ * in whatever unit and clock the sender chose.
74
+ */
75
+ locTimestamp?: bigint;
76
+ };
77
+ /** A data stream ended: `fin` when it closed cleanly, `reset` when either side reset it. */
78
+ type DataStreamEndEvent = DataEventBase & {
79
+ kind: 'end';
80
+ reason: 'fin' | 'reset' | 'error';
81
+ resetCode?: StreamResetCode;
82
+ };
83
+ type DataEvent = DataHeaderEvent | DataObjectEvent | DataStreamEndEvent;
84
+ type DataEventObserver = (event: DataEvent) => void;
85
+ /** What a data stream is handed so it can report itself. */
86
+ type DataStreamObserver = {
87
+ onDataEvent: DataEventObserver; /** Names the track a header belongs to, if known. */
88
+ fullTrackNameOf?: (header: Header) => FullTrackName | undefined;
89
+ };
31
90
  /**
32
- * Copyright 2025 The MOQtail Authors
33
- *
34
- * Licensed under the Apache License, Version 2.0 (the "License");
35
- * you may not use this file except in compliance with the License.
36
- * You may obtain a copy of the License at
37
- *
38
- * http://www.apache.org/licenses/LICENSE-2.0
39
- *
40
- * Unless required by applicable law or agreed to in writing, software
41
- * distributed under the License is distributed on an "AS IS" BASIS,
42
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
43
- * See the License for the specific language governing permissions and
44
- * limitations under the License.
91
+ * Turns one data stream's activity into {@link DataEvent}s. A throwing observer is
92
+ * logged and otherwise ignored, so it can never break the stream it watches.
45
93
  */
46
-
94
+ declare class DataStreamReporter {
95
+ #private;
96
+ private readonly direction;
97
+ private readonly observer?;
98
+ readonly streamId: number;
99
+ constructor(direction: DataDirection, observer?: DataStreamObserver | undefined);
100
+ header(header: Header): void;
101
+ /** `header` is the stream's own: a subgroup object takes its group and subgroup from it. */
102
+ object(header: Header, object: SubgroupObject | FetchObject): void;
103
+ /** Reports how the stream ended. Only the first call counts. */
104
+ end(reason: DataStreamEndEvent['reason'], resetCode?: StreamResetCode): void;
105
+ }
106
+ //#endregion
107
+ //#region src/client/track/object_cache.d.ts
47
108
  /**
48
109
  * In‑memory index of {@link MoqtObject} instances keyed by their {@link Location} (group/subgroup/object),
49
110
  * providing ordered insertion and range queries.
@@ -63,56 +124,41 @@ declare class ControlStream {
63
124
  * Concurrency: Implementations here are not thread‑safe; callers avoid concurrent mutation from workers.
64
125
  */
65
126
  interface ObjectCache {
66
- /** Insert a new {@link MoqtObject}, preserving sorted order (duplicates allowed or replaced impl‑defined). */
67
- add(obj: MoqtObject): void;
68
- /** Return a shallow copy array of objects whose Location is \>= start and \< end (end exclusive). */
69
- getRange(start?: Location, end?: Location): MoqtObject[];
70
- /** Return the object whose Location exactly matches (group & object) or undefined if absent. */
71
- getByLocation(location: Location): MoqtObject | undefined;
72
- /** Current number of cached objects. */
73
- size(): number;
74
- /** Remove all cached objects. */
75
- clear(): void;
127
+ /** Insert a new {@link MoqtObject}, preserving sorted order (duplicates allowed or replaced impl‑defined). */
128
+ add(obj: MoqtObject): void;
129
+ /** Return a shallow copy array of objects whose Location is \>= start and \< end (end exclusive). */
130
+ getRange(start?: Location, end?: Location): MoqtObject[];
131
+ /** Return the object whose Location exactly matches (group & object) or undefined if absent. */
132
+ getByLocation(location: Location): MoqtObject | undefined;
133
+ /** Current number of cached objects. */
134
+ size(): number;
135
+ /** Remove all cached objects. */
136
+ clear(): void;
76
137
  }
77
138
  declare class MemoryObjectCache implements ObjectCache {
78
- private objects;
79
- add(obj: MoqtObject): void;
80
- getRange(start?: Location, end?: Location): MoqtObject[];
81
- getByLocation(location: Location): MoqtObject | undefined;
82
- size(): number;
83
- clear(): void;
84
- private _findInsertIndex;
85
- private _findIndex;
139
+ private objects;
140
+ add(obj: MoqtObject): void;
141
+ getRange(start?: Location, end?: Location): MoqtObject[];
142
+ getByLocation(location: Location): MoqtObject | undefined;
143
+ size(): number;
144
+ clear(): void;
145
+ private _findInsertIndex;
146
+ private _findIndex;
86
147
  }
87
148
  declare class RingBufferObjectCache implements ObjectCache {
88
- private buffer;
89
- private maxSize;
90
- constructor(maxSize?: number);
91
- add(obj: MoqtObject): void;
92
- getRange(start?: Location, end?: Location): MoqtObject[];
93
- getByLocation(location: Location): MoqtObject | undefined;
94
- size(): number;
95
- clear(): void;
96
- private _findInsertIndex;
97
- private _findIndex;
149
+ private buffer;
150
+ private maxSize;
151
+ constructor(maxSize?: number);
152
+ add(obj: MoqtObject): void;
153
+ getRange(start?: Location, end?: Location): MoqtObject[];
154
+ getByLocation(location: Location): MoqtObject | undefined;
155
+ size(): number;
156
+ clear(): void;
157
+ private _findInsertIndex;
158
+ private _findIndex;
98
159
  }
99
-
100
- /**
101
- * Copyright 2025 The MOQtail Authors
102
- *
103
- * Licensed under the Apache License, Version 2.0 (the "License");
104
- * you may not use this file except in compliance with the License.
105
- * You may obtain a copy of the License at
106
- *
107
- * http://www.apache.org/licenses/LICENSE-2.0
108
- *
109
- * Unless required by applicable law or agreed to in writing, software
110
- * distributed under the License is distributed on an "AS IS" BASIS,
111
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
112
- * See the License for the specific language governing permissions and
113
- * limitations under the License.
114
- */
115
-
160
+ //#endregion
161
+ //#region src/client/track/content_source.d.ts
116
162
  /**
117
163
  * Source of already-produced (historical) objects for a track.
118
164
  * Backed by an {@link ObjectCache} allowing range retrieval using protocol {@link Location}s.
@@ -120,29 +166,29 @@ declare class RingBufferObjectCache implements ObjectCache {
120
166
  * if the requested window is outside the cached range.
121
167
  */
122
168
  interface PastObjectSource {
123
- /** Underlying cache from which objects are served */
124
- readonly cache: ObjectCache;
125
- /**
126
- * Fetch a (closed) range of objects. `start`/`end` are inclusive when provided.
127
- * Omitted bounds mean: from earliest cached (when `start` undefined) or up to latest cached (when `end` undefined).
128
- */
129
- getRange(start?: Location, end?: Location): Promise<MoqtObject[]>;
169
+ /** Underlying cache from which objects are served */
170
+ readonly cache: ObjectCache;
171
+ /**
172
+ * Fetch a (closed) range of objects. `start`/`end` are inclusive when provided.
173
+ * Omitted bounds mean: from earliest cached (when `start` undefined) or up to latest cached (when `end` undefined).
174
+ */
175
+ getRange(start?: Location, end?: Location): Promise<MoqtObject[]>;
130
176
  }
131
177
  /**
132
178
  * Push-oriented live object feed. Wraps a {@link https://developer.mozilla.org/docs/Web/API/ReadableStream | ReadableStream} plus lightweight event subscription helpers.
133
179
  * Implementations advance {@link LiveObjectSource.largestLocation | largestLocation} monotonically as objects arrive.
134
180
  */
135
181
  interface LiveObjectSource {
136
- /** Continuous stream yielding objects as they are produced */
137
- readonly stream: ReadableStream<MoqtObject>;
138
- /** Highest (latest) location observed so far; undefined until first object */
139
- readonly largestLocation: Location | undefined;
140
- /** Register a listener invoked (async) for each new object. Returns an unsubscribe function. */
141
- onNewObject(listener: (obj: MoqtObject) => void): () => void;
142
- /** Register a listener invoked when the live stream ends (normal or error). Returns an unsubscribe function. */
143
- onDone(listener: () => void): () => void;
144
- /** Stop ingestion and release underlying reader (idempotent). */
145
- stop(): void;
182
+ /** Continuous stream yielding objects as they are produced */
183
+ readonly stream: ReadableStream<MoqtObject>;
184
+ /** Highest (latest) location observed so far; undefined until first object */
185
+ readonly largestLocation: Location | undefined;
186
+ /** Register a listener invoked (async) for each new object. Returns an unsubscribe function. */
187
+ onNewObject(listener: (obj: MoqtObject) => void): () => void;
188
+ /** Register a listener invoked when the live stream ends (normal or error). Returns an unsubscribe function. */
189
+ onDone(listener: () => void): () => void;
190
+ /** Stop ingestion and release underlying reader (idempotent). */
191
+ stop(): void;
146
192
  }
147
193
  /**
148
194
  * Aggregates optional historical (`past`) and (`live`) sources for a single track.
@@ -156,47 +202,32 @@ interface LiveObjectSource {
156
202
  * expresses what content is available, independent of priority semantics.
157
203
  */
158
204
  interface TrackSource {
159
- /** Historical object access (optional) */
160
- readonly past?: PastObjectSource;
161
- /** Live object feed (optional) */
162
- readonly live?: LiveObjectSource;
205
+ /** Historical object access (optional) */
206
+ readonly past?: PastObjectSource;
207
+ /** Live object feed (optional) */
208
+ readonly live?: LiveObjectSource;
163
209
  }
164
210
  declare class StaticTrackSource implements PastObjectSource {
165
- readonly cache: ObjectCache;
166
- constructor(cache: ObjectCache);
167
- getRange(start?: Location, end?: Location): Promise<MoqtObject[]>;
211
+ readonly cache: ObjectCache;
212
+ constructor(cache: ObjectCache);
213
+ getRange(start?: Location, end?: Location): Promise<MoqtObject[]>;
168
214
  }
169
215
  declare class LiveTrackSource implements LiveObjectSource {
170
- #private;
171
- readonly stream: ReadableStream<MoqtObject>;
172
- constructor(stream: ReadableStream<MoqtObject>);
173
- get largestLocation(): Location | undefined;
174
- onNewObject(listener: (obj: MoqtObject) => Promise<void> | void): () => void;
175
- onDone(listener: () => void): () => void;
176
- stop(): void;
216
+ #private;
217
+ readonly stream: ReadableStream<MoqtObject>;
218
+ constructor(stream: ReadableStream<MoqtObject>);
219
+ get largestLocation(): Location | undefined;
220
+ onNewObject(listener: (obj: MoqtObject) => Promise<void> | void): () => void;
221
+ onDone(listener: () => void): () => void;
222
+ stop(): void;
177
223
  }
178
224
  declare class HybridTrackSource implements TrackSource {
179
- readonly past: PastObjectSource;
180
- readonly live: LiveObjectSource;
181
- constructor(cache: ObjectCache, stream: ReadableStream<MoqtObject>);
225
+ readonly past: PastObjectSource;
226
+ readonly live: LiveObjectSource;
227
+ constructor(cache: ObjectCache, stream: ReadableStream<MoqtObject>);
182
228
  }
183
-
184
- /**
185
- * Copyright 2025 The MOQtail Authors
186
- *
187
- * Licensed under the Apache License, Version 2.0 (the "License");
188
- * you may not use this file except in compliance with the License.
189
- * You may obtain a copy of the License at
190
- *
191
- * http://www.apache.org/licenses/LICENSE-2.0
192
- *
193
- * Unless required by applicable law or agreed to in writing, software
194
- * distributed under the License is distributed on an "AS IS" BASIS,
195
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
196
- * See the License for the specific language governing permissions and
197
- * limitations under the License.
198
- */
199
-
229
+ //#endregion
230
+ //#region src/client/track/track.d.ts
200
231
  /**
201
232
  * Describes a media/data track known to the client (either published locally or subscribed to).
202
233
  *
@@ -237,349 +268,111 @@ declare class HybridTrackSource implements TrackSource {
237
268
  * ```
238
269
  */
239
270
  type Track = {
240
- /**
241
- * Globally unique identifier for the track.
242
- */
243
- fullTrackName: FullTrackName;
244
- /**
245
- * Accessors for live and/or past objects belonging to this track.
246
- */
247
- trackSource: TrackSource;
248
- /**
249
- * 0 (highest) .. 255 (lowest) priority advertised with objects.
250
- * Values are rounded to nearest integer then clamped between 0 and 255.
251
- */
252
- publisherPriority: number;
253
- /**
254
- * Optional compact numeric alias assigned during protocol negotiation.
255
- */
256
- trackAlias?: bigint;
257
- /**
258
- * Track extensions advertised by the publisher.
259
- * Set before calling `publish()` to include extensions in the PUBLISH message.
260
- * Populated automatically on the subscriber side when SUBSCRIBE_OK or FETCH_OK is received.
261
- */
262
- trackExtensions?: TrackExtension[];
271
+ /**
272
+ * Globally unique identifier for the track.
273
+ */
274
+ fullTrackName: FullTrackName;
275
+ /**
276
+ * Accessors for live and/or past objects belonging to this track.
277
+ */
278
+ trackSource: TrackSource;
279
+ /**
280
+ * 0 (highest) .. 255 (lowest) priority advertised with objects.
281
+ * Values are rounded to nearest integer then clamped between 0 and 255.
282
+ */
283
+ publisherPriority: number;
284
+ /**
285
+ * Optional compact numeric alias assigned during protocol negotiation.
286
+ */
287
+ trackAlias?: bigint;
288
+ /**
289
+ * Track properties advertised by the publisher.
290
+ * Set before calling `publish()` to include properties in the PUBLISH message.
291
+ * Populated automatically on the subscriber side when SUBSCRIBE_OK or FETCH_OK is received.
292
+ */
293
+ trackProperties?: TrackProperty[];
263
294
  };
264
-
265
- /**
266
- * Copyright 2025 The MOQtail Authors
267
- *
268
- * Licensed under the Apache License, Version 2.0 (the "License");
269
- * you may not use this file except in compliance with the License.
270
- * You may obtain a copy of the License at
271
- *
272
- * http://www.apache.org/licenses/LICENSE-2.0
273
- *
274
- * Unless required by applicable law or agreed to in writing, software
275
- * distributed under the License is distributed on an "AS IS" BASIS,
276
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
277
- * See the License for the specific language governing permissions and
278
- * limitations under the License.
279
- */
280
-
281
- /**
282
- * @public
283
- * Manages the publication of MOQT objects to a subscriber for a specific track.
284
- * Handles live object streaming, subscription lifecycle, and stream management.
285
- */
286
- declare class SubscribePublication {
287
- #private;
288
- private readonly client;
289
- readonly track: Track;
290
- private readonly subscribeMsg;
291
- /**
292
- * The latest location that was published to the subscriber.
293
- */
294
- latestLocation: Location | undefined;
295
- /**
296
- * Creates a new SubscribePublication instance.
297
- * @param client - The MOQT client managing the subscription.
298
- * @param track - The track being published.
299
- * @param subscribeMsg - The subscribe message containing subscription details.
300
- * @param largestLocation - The largest location seen so far, used for determining start location.
301
- */
302
- constructor(client: MOQtailClient, track: Track, subscribeMsg: Subscribe, largestLocation?: Location);
303
- /**
304
- * Cancels the publication and cleans up resources.
305
- * Removes the publication from the client's publication map.
306
- */
307
- cancel(): void;
308
- /**
309
- * Marks the publication as done and sends a PublishDone message to the client.
310
- * @param statusCode - The status code indicating why the publication ended.
311
- * @throws :{@link InternalError} If sending the message fails.
312
- */
313
- done(statusCode: PublishDoneStatusCode): Promise<void>;
314
- /**
315
- * Updates the subscription parameters and locations based on a RequestUpdate message.
316
- * @param msg - The update message containing new request details.
317
- */
318
- update(msg: RequestUpdate): void;
319
- /**
320
- * Publishes MOQT objects to the subscriber as they become available.
321
- * Handles stream creation, object writing, and stream closure based on subscription parameters.
322
- * @throws :{@link InternalError} If the track does not support live content.
323
- */
324
- publish(): Promise<void>;
325
- }
326
-
327
- /**
328
- * Copyright 2025 The MOQtail Authors
329
- *
330
- * Licensed under the Apache License, Version 2.0 (the "License");
331
- * you may not use this file except in compliance with the License.
332
- * You may obtain a copy of the License at
333
- *
334
- * http://www.apache.org/licenses/LICENSE-2.0
335
- *
336
- * Unless required by applicable law or agreed to in writing, software
337
- * distributed under the License is distributed on an "AS IS" BASIS,
338
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
339
- * See the License for the specific language governing permissions and
340
- * limitations under the License.
341
- */
342
-
343
- declare class FetchPublication {
344
- #private;
345
- constructor(client: MOQtailClient, track: Track, fetchRequest: Fetch);
346
- cancel(): void;
347
- publish(): Promise<void>;
348
- }
349
-
350
- /**
351
- * Copyright 2025 The MOQtail Authors
352
- *
353
- * Licensed under the Apache License, Version 2.0 (the "License");
354
- * you may not use this file except in compliance with the License.
355
- * You may obtain a copy of the License at
356
- *
357
- * http://www.apache.org/licenses/LICENSE-2.0
358
- *
359
- * Unless required by applicable law or agreed to in writing, software
360
- * distributed under the License is distributed on an "AS IS" BASIS,
361
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
362
- * See the License for the specific language governing permissions and
363
- * limitations under the License.
364
- */
365
-
366
- /**
367
- * @public
368
- * Manages the proactive publication of MOQT objects from a publisher to the relay.
369
- * Handles live object streaming and stream management.
370
- */
371
- declare class PublishPublication {
372
- #private;
373
- private readonly client;
374
- readonly track: Track;
375
- private readonly publishMsg;
376
- /**
377
- * The latest location that was published to the relay.
378
- */
379
- latestLocation: Location | undefined;
380
- /**
381
- * Creates a new PublishPublication instance.
382
- * @param client - The MOQT client managing the connection.
383
- * @param track - The track being proactively published.
384
- * @param publishMsg - The publish message that initiated this session.
385
- */
386
- constructor(client: MOQtailClient, track: Track, publishMsg: Publish);
387
- /**
388
- * Cancels the publication and cleans up resources.
389
- * Removes the publication from the client's publication map.
390
- */
391
- cancel(): void;
392
- /**
393
- * Publishes MOQT objects to the relay as they become available.
394
- * Handles stream creation, object writing, and stream closure.
395
- * @throws :{@link InternalError} If the track does not support live content.
396
- */
397
- publishToRelay(): Promise<void>;
398
- }
399
-
400
- /**
401
- * Copyright 2026 The MOQtail Authors
402
- *
403
- * Licensed under the Apache License, Version 2.0 (the "License");
404
- * you may not use this file except in compliance with the License.
405
- * You may obtain a copy of the License at
406
- *
407
- * http://www.apache.org/licenses/LICENSE-2.0
408
- *
409
- * Unless required by applicable law or agreed to in writing, software
410
- * distributed under the License is distributed on an "AS IS" BASIS,
411
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
412
- * See the License for the specific language governing permissions and
413
- * limitations under the License.
414
- */
415
-
295
+ //#endregion
296
+ //#region src/client/request/publish_namespace.d.ts
416
297
  declare class PublishNamespaceRequest implements PromiseLike<RequestOk | RequestError> {
417
- readonly requestId: bigint;
418
- readonly message: PublishNamespace;
419
- private _resolve;
420
- private _reject;
421
- private promise;
422
- constructor(requestId: bigint, message: PublishNamespace);
423
- resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
424
- reject(reason?: any): void;
425
- then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
426
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
427
- finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
298
+ readonly requestId: bigint;
299
+ readonly message: PublishNamespace;
300
+ private _resolve;
301
+ private _reject;
302
+ private promise;
303
+ constructor(requestId: bigint, message: PublishNamespace);
304
+ resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
305
+ reject(reason?: any): void;
306
+ then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
307
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
308
+ finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
428
309
  }
429
-
430
- /**
431
- * Copyright 2025 The MOQtail Authors
432
- *
433
- * Licensed under the Apache License, Version 2.0 (the "License");
434
- * you may not use this file except in compliance with the License.
435
- * You may obtain a copy of the License at
436
- *
437
- * http://www.apache.org/licenses/LICENSE-2.0
438
- *
439
- * Unless required by applicable law or agreed to in writing, software
440
- * distributed under the License is distributed on an "AS IS" BASIS,
441
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
442
- * See the License for the specific language governing permissions and
443
- * limitations under the License.
444
- */
445
-
310
+ //#endregion
311
+ //#region src/client/request/fetch.d.ts
446
312
  declare class FetchRequest implements PromiseLike<FetchOk | RequestError> {
447
- readonly requestId: bigint;
448
- readonly message: Fetch;
449
- private _resolve;
450
- private _reject;
451
- private promise;
452
- controller?: ReadableStreamDefaultController<MoqtObject>;
453
- stream: ReadableStream<MoqtObject>;
454
- isActive: boolean;
455
- isResolved: boolean;
456
- constructor(message: Fetch);
457
- resolve(value: FetchOk | RequestError | PromiseLike<FetchOk | RequestError>): void;
458
- reject(reason?: any): void;
459
- then<TResult1 = FetchOk | RequestError, TResult2 = never>(onfulfilled?: ((value: FetchOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
460
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<FetchOk | RequestError | TResult>;
461
- finally(onfinally?: (() => void) | undefined | null): Promise<FetchOk | RequestError>;
313
+ readonly requestId: bigint;
314
+ readonly message: Fetch;
315
+ private _resolve;
316
+ private _reject;
317
+ private promise;
318
+ controller?: ReadableStreamDefaultController<MoqtObject>;
319
+ stream: ReadableStream<MoqtObject>;
320
+ isActive: boolean;
321
+ isResolved: boolean;
322
+ constructor(message: Fetch);
323
+ resolve(value: FetchOk | RequestError | PromiseLike<FetchOk | RequestError>): void;
324
+ reject(reason?: any): void;
325
+ then<TResult1 = FetchOk | RequestError, TResult2 = never>(onfulfilled?: ((value: FetchOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
326
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<FetchOk | RequestError | TResult>;
327
+ finally(onfinally?: (() => void) | undefined | null): Promise<FetchOk | RequestError>;
462
328
  }
463
-
464
- /**
465
- * Copyright 2025 The MOQtail Authors
466
- *
467
- * Licensed under the Apache License, Version 2.0 (the "License");
468
- * you may not use this file except in compliance with the License.
469
- * You may obtain a copy of the License at
470
- *
471
- * http://www.apache.org/licenses/LICENSE-2.0
472
- *
473
- * Unless required by applicable law or agreed to in writing, software
474
- * distributed under the License is distributed on an "AS IS" BASIS,
475
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
476
- * See the License for the specific language governing permissions and
477
- * limitations under the License.
478
- */
479
-
480
- declare class SubscribeRequest implements PromiseLike<SubscribeOk | RequestError> {
481
- #private;
482
- requestId: bigint;
483
- fullTrackName: FullTrackName;
484
- isCanceled: boolean;
485
- startLocation: Location | undefined;
486
- endGroup: bigint | undefined;
487
- priority: number;
488
- forward: boolean;
489
- subscribeParameters: MessageParameter[];
490
- earlyDiscardPolicy: EarlyDiscardPolicyConfig | undefined;
491
- largestLocation: Location | undefined;
492
- streamsAccepted: bigint;
493
- expectedStreams: bigint | undefined;
494
- readonly controller: ReadableStreamDefaultController<MoqtObject>;
495
- readonly stream: ReadableStream<MoqtObject>;
496
- constructor(msg: Subscribe);
497
- update(msg: RequestUpdate): void;
498
- switch(newTrackName: FullTrackName, newParameters: MessageParameter[]): void;
499
- unsubscribe(): void;
500
- resolve(value: SubscribeOk | RequestError | PromiseLike<SubscribeOk | RequestError>): void;
501
- reject(reason?: any): void;
502
- then<TResult1 = SubscribeOk | RequestError, TResult2 = never>(onfulfilled?: ((value: SubscribeOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
503
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<SubscribeOk | RequestError | TResult>;
504
- finally(onfinally?: (() => void) | undefined | null): Promise<SubscribeOk | RequestError>;
505
- }
506
-
507
- /**
508
- * Copyright 2026 The MOQtail Authors
509
- *
510
- * Licensed under the Apache License, Version 2.0 (the "License");
511
- * you may not use this file except in compliance with the License.
512
- * You may obtain a copy of the License at
513
- *
514
- * http://www.apache.org/licenses/LICENSE-2.0
515
- *
516
- * Unless required by applicable law or agreed to in writing, software
517
- * distributed under the License is distributed on an "AS IS" BASIS,
518
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
519
- * See the License for the specific language governing permissions and
520
- * limitations under the License.
521
- */
522
-
329
+ //#endregion
330
+ //#region src/client/request/subscribe_namespace.d.ts
523
331
  declare class SubscribeNamespaceRequest implements PromiseLike<RequestOk | RequestError> {
524
- readonly requestId: bigint;
525
- readonly message: SubscribeNamespace;
526
- private _resolve;
527
- private _reject;
528
- private promise;
529
- constructor(msg: SubscribeNamespace);
530
- resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
531
- reject(reason?: any): void;
532
- then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
533
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
534
- finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
332
+ readonly requestId: bigint;
333
+ readonly message: SubscribeNamespace;
334
+ private _resolve;
335
+ private _reject;
336
+ private promise;
337
+ constructor(msg: SubscribeNamespace);
338
+ resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
339
+ reject(reason?: any): void;
340
+ then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
341
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
342
+ finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
535
343
  }
536
-
537
- /**
538
- * Copyright 2025 The MOQtail Authors
539
- *
540
- * Licensed under the Apache License, Version 2.0 (the "License");
541
- * you may not use this file except in compliance with the License.
542
- * You may obtain a copy of the License at
543
- *
544
- * http://www.apache.org/licenses/LICENSE-2.0
545
- *
546
- * Unless required by applicable law or agreed to in writing, software
547
- * distributed under the License is distributed on an "AS IS" BASIS,
548
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
549
- * See the License for the specific language governing permissions and
550
- * limitations under the License.
551
- */
552
-
553
- declare class PublishRequest implements PromiseLike<PublishOk | RequestError> {
554
- readonly requestId: bigint;
555
- readonly message: Publish;
556
- private _resolve;
557
- private _reject;
558
- private promise;
559
- constructor(msg: Publish);
560
- resolve(value: PublishOk | RequestError | PromiseLike<PublishOk | RequestError>): void;
561
- reject(reason?: any): void;
562
- then<TResult1 = PublishOk | RequestError, TResult2 = never>(onfulfilled?: ((value: PublishOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
563
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<PublishOk | RequestError | TResult>;
564
- finally(onfinally?: (() => void) | undefined | null): Promise<PublishOk | RequestError>;
344
+ //#endregion
345
+ //#region src/client/request/publish.d.ts
346
+ declare class PublishRequest implements PromiseLike<RequestOk | RequestError> {
347
+ readonly requestId: bigint;
348
+ readonly message: Publish;
349
+ private _resolve;
350
+ private _reject;
351
+ private promise;
352
+ constructor(msg: Publish);
353
+ resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
354
+ reject(reason?: any): void;
355
+ then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
356
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
357
+ finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
565
358
  }
566
-
567
- /**
568
- * Copyright 2025 The MOQtail Authors
569
- *
570
- * Licensed under the Apache License, Version 2.0 (the "License");
571
- * you may not use this file except in compliance with the License.
572
- * You may obtain a copy of the License at
573
- *
574
- * http://www.apache.org/licenses/LICENSE-2.0
575
- *
576
- * Unless required by applicable law or agreed to in writing, software
577
- * distributed under the License is distributed on an "AS IS" BASIS,
578
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
579
- * See the License for the specific language governing permissions and
580
- * limitations under the License.
581
- */
582
-
359
+ //#endregion
360
+ //#region src/client/request/track_status.d.ts
361
+ declare class TrackStatusRequest implements PromiseLike<RequestOk | RequestError> {
362
+ readonly requestId: bigint;
363
+ readonly message: TrackStatus;
364
+ private _resolve;
365
+ private _reject;
366
+ private promise;
367
+ constructor(msg: TrackStatus);
368
+ resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
369
+ reject(reason?: any): void;
370
+ then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
371
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
372
+ finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
373
+ }
374
+ //#endregion
375
+ //#region src/client/types.d.ts
583
376
  /**
584
377
  * Discriminated union of every in‑flight MOQ‑tail control request tracked by the {@link MOQtailClient}.
585
378
  *
@@ -610,7 +403,40 @@ declare class PublishRequest implements PromiseLike<PublishOk | RequestError> {
610
403
  * }
611
404
  * ```
612
405
  */
613
- type MOQtailRequest = PublishRequest | PublishNamespaceRequest | SubscribeNamespaceRequest | FetchRequest | SubscribeRequest;
406
+ type MOQtailRequest = PublishRequest | PublishNamespaceRequest | SubscribeNamespaceRequest | FetchRequest | SubscribeRequest | TrackStatusRequest;
407
+ /**
408
+ * Whatever holds a track alias in the client's routing table: a {@link SubscribeRequest},
409
+ * or the receiver {@link MOQtailClient.acceptPushedTrack} stands up for a track the peer
410
+ * pushes. Incoming objects are named after the holder of the alias their stream carries.
411
+ */
412
+ type TrackAliasHolder = {
413
+ requestId: bigint;
414
+ fullTrackName: FullTrackName;
415
+ };
416
+ /**
417
+ * Default for {@link MOQtailClientOptions.trackAliasResolutionTimeoutMs}: how long a
418
+ * data stream waits for the control message that establishes its track alias.
419
+ *
420
+ * A subscription's data streams and the SUBSCRIBE_OK naming their alias travel on
421
+ * separate streams, so nothing orders them; the data can arrive first. Waiting costs
422
+ * a stalled reader, giving up costs the whole subgroup, so the wait is generous.
423
+ */
424
+ declare const DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS = 2000;
425
+ /**
426
+ * Default for {@link MOQtailClientOptions.switchDrainTimeoutMs}: how long a track a
427
+ * soft switch handed over from may stay quiet before it is retired anyway.
428
+ *
429
+ * A soft switch leaves that track delivering up to the group the new one starts at,
430
+ * so the two meet without a hole, and a PUBLISH_DONE normally ends it. This is the
431
+ * backstop for a publisher that never sends one.
432
+ */
433
+ declare const DEFAULT_SWITCH_DRAIN_TIMEOUT_MS = 2000;
434
+ /**
435
+ * @public
436
+ * The MAX_FILTER_RANGES a client advertises when its setup options set none: how
437
+ * many Range Filter ranges it applies, in total, for one subscription or fetch.
438
+ */
439
+ declare const DEFAULT_MAX_FILTER_RANGES = 32n;
614
440
  /**
615
441
  * Options for {@link MOQtailClient.new} controlling connection target, protocol negotiation, timeouts,
616
442
  * and lifecycle callbacks.
@@ -639,225 +465,451 @@ type MOQtailRequest = PublishRequest | PublishNamespaceRequest | SubscribeNamesp
639
465
  * ```
640
466
  */
641
467
  type MOQtailClientOptions = {
642
- /** Relay / server endpoint for the underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} session (can be absolute {@link https://developer.mozilla.org/en-US/docs/Web/API/URL | URL} or string).*/
643
- url: string | URL;
644
- /** {@link SetupParameters} customizations; if omitted a default instance is built.*/
645
- setupParameters?: SetupParameters;
646
- /** Passed directly to the browser's {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} constructor for {@link https://developer.mozilla.org/docs/Web/API/WebTransportOptions | WebTransportOptions}. */
647
- transportOptions?: WebTransportOptions & {
648
- protocols?: string[];
649
- };
650
- /** Per *data* uni-stream idle timeout in milliseconds. */
651
- dataStreamTimeoutMs?: number;
652
- /** Control stream read timeout in milliseconds. */
653
- controlStreamTimeoutMs?: number;
654
- /** If true, enables datagram support for the session. */
655
- enableDatagrams?: boolean;
656
- /** callbacks for observability and logging purposes: */
657
- callbacks?: {
658
- /** Called after a control message is successfully written to the {@link ControlStream}. */
659
- onMessageSent?: (msg: ControlMessage) => void;
660
- /** Called for each incoming control message before protocol handling. */
661
- onMessageReceived?: (msg: ControlMessage) => void;
662
- /** Fired once when the session ends (normal or error). Receives the reason passed to {@link MOQtailClient.disconnect | disconnect}. */
663
- onSessionTerminated?: (reason?: unknown) => void;
664
- /** Invoked for each decoded datagram object/status arriving. */
665
- onDatagramReceived?: (data: Datagram) => void;
666
- /** Invoked after enqueuing each outbound datagram object/status. */
667
- onDatagramSent?: (data: Datagram) => void;
668
- };
468
+ /** Relay / server endpoint for the underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} session (can be absolute {@link https://developer.mozilla.org/en-US/docs/Web/API/URL | URL} or string).*/url: string | URL; /** {@link SetupOptions} customizations; if omitted a default instance is built.*/
469
+ setupOptions?: SetupOptions; /** Passed directly to the browser's {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} constructor for {@link https://developer.mozilla.org/docs/Web/API/WebTransportOptions | WebTransportOptions}. */
470
+ transportOptions?: WebTransportOptions & {
471
+ protocols?: string[];
472
+ }; /** Per *data* uni-stream idle timeout in milliseconds. */
473
+ dataStreamTimeoutMs?: number; /** Control stream read timeout in milliseconds. */
474
+ controlStreamTimeoutMs?: number;
475
+ /**
476
+ * How long a data stream waits for the control message that establishes its track
477
+ * alias before the stream is abandoned, in milliseconds. Defaults to
478
+ * {@link DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS}.
479
+ */
480
+ trackAliasResolutionTimeoutMs?: number;
481
+ /**
482
+ * How long a track a soft switch handed over from may stay quiet before it is
483
+ * retired anyway, in milliseconds. Defaults to
484
+ * {@link DEFAULT_SWITCH_DRAIN_TIMEOUT_MS}.
485
+ */
486
+ switchDrainTimeoutMs?: number; /** If true, enables datagram support for the session. */
487
+ enableDatagrams?: boolean; /** callbacks for observability and logging purposes: */
488
+ callbacks?: {
489
+ /** Called after a control message is successfully written to the {@link ControlStream}. */onMessageSent?: (msg: ControlMessage) => void; /** Called for each incoming control message before protocol handling. */
490
+ onMessageReceived?: (msg: ControlMessage) => void; /** Fired once when the session ends (normal or error). Receives the reason passed to {@link MOQtailClient.disconnect | disconnect}. */
491
+ onSessionTerminated?: (reason?: unknown) => void; /** Invoked for each decoded datagram object/status arriving. */
492
+ onDatagramReceived?: (data: Datagram) => void; /** Invoked after enqueuing each outbound datagram object/status. */
493
+ onDatagramSent?: (data: Datagram) => void; /** Invoked for each data stream's header, each of its objects, and its end. See {@link MOQtailClient.onDataEvent}. */
494
+ onDataEvent?: DataEventObserver;
495
+ };
669
496
  };
670
497
  /**
671
498
  * Parameters for {@link MOQtailClient.subscribe | subscribing} to a track's live objects.
672
499
  *
673
- * @example Latest object
500
+ * @example From the next object
674
501
  * ```ts
675
502
  * await client.subscribe({
676
503
  * fullTrackName,
677
504
  * priority: 0,
678
505
  * groupOrder: GroupOrder.Original,
679
506
  * forward: true,
680
- * filterType: FilterType.LatestObject
507
+ * locationFilter: new LocationFilter(LocationFilterType.NextObject)
681
508
  * })
682
509
  * ```
683
- * @example Absolute range
510
+ * @example Groups 100 through 120
684
511
  * ```ts
685
512
  * await client.subscribe({
686
513
  * fullTrackName,
687
514
  * priority: 32,
688
515
  * groupOrder: GroupOrder.Original,
689
516
  * forward: true,
690
- * filterType: FilterType.AbsoluteRange,
691
- * startLocation: { group: 100n, subgroup: 0n, object: 0n },
692
- * endGroup: 120n
517
+ * locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, 100n, 0n, 120n)
518
+ * })
519
+ * ```
520
+ * @example From the next object, filling the current group from its start
521
+ * ```ts
522
+ * await client.subscribe({
523
+ * fullTrackName,
524
+ * priority: 0,
525
+ * groupOrder: GroupOrder.Original,
526
+ * locationFilter: new LocationFilter(LocationFilterType.NextObject),
527
+ * parameters: [new FillParameters([new LocationFilter(LocationFilterType.RelativeStart, 1n)])]
693
528
  * })
694
529
  * ```
695
530
  */
696
531
  type SubscribeOptions = {
697
- /** Fully qualified track identifier ({@link FullTrackName}). */
698
- fullTrackName: FullTrackName;
699
- /** Subscriber priority (0 = highest, 255 = lowest). Values outside range are clamped. Fractional values are rounded. */
700
- priority: number;
701
- /** Desired {@link GroupOrder} (e.g. {@link GroupOrder.Original}) specifying delivery ordering semantics. */
702
- groupOrder: GroupOrder;
703
- /** If true, deliver objects forward (ascending); if false, reverse/backward semantics (implementation dependent). */
704
- forward: boolean;
705
- /** {@link FilterType} variant controlling starting subset (e.g. {@link FilterType.LatestObject}). */
706
- filterType: FilterType;
707
- /** Optional extension parameters appended to the SUBSCRIBE control message. */
708
- parameters?: MessageParameter[];
709
- /** Required for {@link FilterType.AbsoluteStart} / {@link FilterType.AbsoluteRange}; earliest {@link Location} to include. */
710
- startLocation?: Location;
711
- /** Required for {@link FilterType.AbsoluteRange}; exclusive upper group boundary (coerced to bigint if number provided). */
712
- endGroup?: bigint | number;
713
- /** Per-subscription early discard policy. Overrides the client-level default set via {@link MOQtailClient.setEarlyDiscardPolicy}. */
714
- earlyDiscardPolicy?: EarlyDiscardPolicyConfig;
532
+ /** Fully qualified track identifier ({@link FullTrackName}). */fullTrackName: FullTrackName; /** Subscriber priority (0 = highest, 255 = lowest). Values outside range are clamped. Fractional values are rounded. */
533
+ priority: number; /** Desired {@link (GroupOrder:enum)} (e.g. {@link (GroupOrder:enum).Original}) specifying delivery ordering semantics. */
534
+ groupOrder: GroupOrder; /** If present, forward parameter (0x10) is sent with the provided value */
535
+ forward?: boolean; /** The {@link LocationFilter} selecting which Objects to deliver. Omitted, the subscription is unfiltered. */
536
+ locationFilter?: LocationFilter;
537
+ /**
538
+ * Optional extension parameters appended to the SUBSCRIBE control message. A
539
+ * FILL_PARAMETERS here also retrieves already-published Objects on a fill fetch stream.
540
+ */
541
+ parameters?: MessageParameter[]; /** Per-subscription early discard policy. Overrides the client-level default set via {@link MOQtailClient.setEarlyDiscardPolicy}. */
542
+ earlyDiscardPolicy?: EarlyDiscardPolicyConfig;
715
543
  };
716
544
  /**
717
- * Narrowing update constraints applied to an existing SUBSCRIBE via {@link MOQtailClient.subscribeUpdate}.
718
- *
719
- * Rules: start can only move forward (increase) and endGroup can only move backward (decrease) narrowing the window.
545
+ * Changes applied to an existing SUBSCRIBE via {@link MOQtailClient.subscribeUpdate}.
720
546
  *
721
- * @example Narrowing a live window
547
+ * @example Narrowing a live window to groups 200 through 210
722
548
  * ```ts
723
549
  * await client.subscribeUpdate({
724
- * requestId,
725
- * startLocation: { group: 200n, subgroup: 0n, object: 0n },
726
- * endGroup: 210n,
550
+ * subscriptionRequestId,
551
+ * locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, 200n, 0n, 210n),
727
552
  * priority: 16,
728
553
  * forward: true
729
554
  * })
730
555
  * ```
731
556
  */
732
557
  type SubscribeUpdateOptions = {
733
- /** The original SUBSCRIBE request id (bigint) being updated. */
734
- subscriptionRequestId: bigint;
735
- /** New narrowed {@link Location} start. */
736
- startLocation: Location;
737
- /** New narrowed end group (inclusive / protocol defined) must be \> start group. */
738
- endGroup: bigint;
739
- /** Updated subscriber priority (same constraints as initial subscribe). 0 is highest, 255 is lowest. */
740
- priority: number;
741
- /** Updated direction flag. */
742
- forward: boolean;
743
- /** Optional additional parameters; existing parameters persist if omitted. */
744
- parameters?: MessageParameter[];
558
+ /** The original SUBSCRIBE request id (bigint) being updated. */subscriptionRequestId: bigint; /** The new {@link LocationFilter}. Omitted, the subscription keeps its own. */
559
+ locationFilter?: LocationFilter; /** Updated subscriber priority (same constraints as initial subscribe). 0 is highest, 255 is lowest. */
560
+ priority: number; /** Updated direction flag. */
561
+ forward: boolean; /** Optional additional parameters; existing parameters persist if omitted. */
562
+ parameters?: MessageParameter[];
745
563
  };
746
564
  /**
747
565
  * Parameters for {@link MOQtailClient.switch | switching} an existing SUBSCRIBE to a new track.
748
566
  *
749
- * @example Switching subscription to a new track
567
+ * @example Switching a subscription to a new track
750
568
  * ```ts
751
569
  * await client.switch({
752
- * fullTrackName: newFullTrackName,
753
- * subscriptionRequestId
570
+ * switchFromRequestId,
571
+ * switchMode: SwitchMode.Soft,
572
+ * newSubscribeOptions: {
573
+ * fullTrackName: newFullTrackName,
574
+ * priority: 0,
575
+ * groupOrder: GroupOrder.Original,
576
+ * forward: true,
577
+ * locationFilter: new LocationFilter(LocationFilterType.NextObject)
578
+ * }
754
579
  * })
755
580
  * ```
756
581
  */
757
582
  type SwitchOptions = {
758
- /** Fully qualified track identifier to switch to ({@link FullTrackName}). */
759
- fullTrackName: FullTrackName;
760
- /** The original SUBSCRIBE request id (bigint) being updated. */
761
- subscriptionRequestId: bigint;
762
- /** Optional additional parameters; existing parameters persist if omitted. */
763
- parameters?: MessageParameter[];
583
+ /** The original SUBSCRIBE request id (bigint) being switched from. */switchFromRequestId: bigint; /** {@link SwitchMode} controlling how the switch is applied. */
584
+ switchMode: SwitchMode; /** New subscription options to switch to. */
585
+ newSubscribeOptions: SubscribeOptions; /** Callback to determine whether to continue draining the superseded subscription. Returning true will reset the relevant stream. */
586
+ onDrainDecision?: (request: SubscribeRequest) => boolean;
587
+ };
588
+ /**
589
+ * Configuration for the early discard policy applied to incoming subgroup streams.
590
+ */
591
+ type EarlyDiscardPolicyConfig = {
592
+ /** Cancel a subgroup QUIC stream if it has not fully completed within this many milliseconds. */subgroupReceiveTimeout: number;
764
593
  };
765
594
  /**
766
- * Options for {@link MOQtailClient.fetch | performing a FETCH} operation for historical or relative object ranges.
595
+ * Options for {@link MOQtailClient.fetch | performing a FETCH} of Objects already published.
767
596
  *
768
- * @example Standalone fetch
597
+ * @example Groups 10 through 12, inclusive
769
598
  * ```ts
770
599
  * const { requestId, stream } = await client.fetch({
600
+ * fullTrackName,
771
601
  * priority: 64,
772
602
  * groupOrder: GroupOrder.Original,
773
- * typeAndProps: {
774
- * type: FetchType.Standalone,
775
- * props: { fullTrackName, startLocation, endLocation }
776
- * }
603
+ * locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, 10n, 0n, 12n)
777
604
  * })
778
605
  * ```
779
- * @example Relative fetch joining a subscription
606
+ * @example The current group and the one before it
780
607
  * ```ts
781
- * const { requestId: subId } = await client.subscribe({
608
+ * await client.fetch({
782
609
  * fullTrackName,
783
- * priority: 0,
784
- * groupOrder: GroupOrder.Original,
785
- * forward: true,
786
- * filterType: FilterType.LatestObject
787
- * })
788
- * const fetchRes = await client.fetch({
789
610
  * priority: 32,
790
611
  * groupOrder: GroupOrder.Original,
791
- * typeAndProps: {
792
- * type: FetchType.Relative,
793
- * props: { joiningRequestId: subId, joiningStart: 0n }
794
- * }
612
+ * locationFilter: new LocationFilter(LocationFilterType.RelativeStart, 2n)
795
613
  * })
796
614
  * ```
797
615
  */
616
+ type FetchOptions = {
617
+ /** Request priority (0 = highest, 255 = lowest). Rounded & clamped. */priority: number; /** {@link (GroupOrder:enum)} governing sequencing. */
618
+ groupOrder: GroupOrder; /** Fully qualified track identifier ({@link FullTrackName}). */
619
+ fullTrackName: FullTrackName;
620
+ /**
621
+ * Which Objects to fetch; the end, when the filter has one, is the last Object
622
+ * sent. Without a filter the whole track up to the Largest Object is fetched, and
623
+ * a filter without an end also stops at the Largest Object.
624
+ */
625
+ locationFilter?: LocationFilter; /** Optional parameters block. */
626
+ parameters?: MessageParameter[];
627
+ };
628
+ //#endregion
629
+ //#region src/client/request/subscribe.d.ts
798
630
  /**
799
- * Configuration for the early discard policy applied to incoming subgroup streams.
631
+ * Represents an active subscription request in MOQT, implementing `PromiseLike`
632
+ * for convenient async resolution when subscription setup succeeds or fails.
800
633
  */
801
- type EarlyDiscardPolicyConfig = {
802
- /** Cancel a subgroup QUIC stream if it has not fully completed within this many milliseconds. */
803
- subgroupReceiveTimeout: number;
804
- };
805
- type FetchOptions = {
806
- /** Request priority (0 = highest, 255 = lowest). Rounded & clamped. */
807
- priority: number;
808
- /** {@link GroupOrder} governing sequencing. */
809
- groupOrder: GroupOrder;
810
- /**
811
- * Discriminated union selecting the {@link FetchType} mode and its specific properties:
812
- * - Standalone: full explicit range on a {@link FullTrackName} with start/end {@link Location}s.
813
- * - Relative / Absolute: join an existing {@link SubscribeRequest} (identified by `joiningRequestId`) with starting position `joiningStart`.
814
- */
815
- typeAndProps: {
816
- /** Standalone historical/segment fetch for a specific {@link FullTrackName}. */
817
- type: FetchType.Standalone;
818
- /** Properties for standalone fetch: explicit track and range. */
819
- props: {
820
- fullTrackName: FullTrackName;
821
- startLocation: Location;
822
- endLocation: Location;
823
- };
824
- } | {
825
- /** Fetch a range relative to an existing {@link SubscribeRequest} identified by `joiningRequestId`. */
826
- type: FetchType.Relative;
827
- /** Properties for relative fetch: subscription id and starting position. */
828
- props: {
829
- joiningRequestId: bigint;
830
- joiningStart: bigint;
831
- };
832
- } | {
833
- /** Fetch an absolute group/object range relative to a {@link SubscribeRequest}. */
834
- type: FetchType.Absolute;
835
- /** Properties for absolute fetch: subscription id and starting position. */
836
- props: {
837
- joiningRequestId: bigint;
838
- joiningStart: bigint;
839
- };
840
- };
841
- /** Optional parameters block. */
842
- parameters?: MessageParameter[];
634
+ declare class SubscribeRequest implements PromiseLike<SubscribeOk | RequestError> {
635
+ #private;
636
+ requestId: bigint;
637
+ fullTrackName: FullTrackName;
638
+ isCanceled: boolean;
639
+ startLocation: Location | undefined;
640
+ endGroup: bigint | undefined;
641
+ priority: number;
642
+ forward: boolean;
643
+ subscribeParameters: MessageParameter[];
644
+ earlyDiscardPolicy: EarlyDiscardPolicyConfig | undefined;
645
+ largestLocation: Location | undefined;
646
+ /**
647
+ * The publisher's Largest Object as of the last SUBSCRIBE_OK or REQUEST_UPDATE_OK,
648
+ * which is where a fill fetch stream stops.
649
+ */
650
+ fillBoundary: Location | undefined;
651
+ /** EXPIRES from the last SUBSCRIBE_OK or REQUEST_UPDATE_OK, in milliseconds. */
652
+ expires: bigint | undefined;
653
+ streamsAccepted: bigint;
654
+ expectedStreams: bigint | undefined;
655
+ /** The Subscription managing this request's output stream once switching is involved. */
656
+ manager?: Subscription;
657
+ readonly controller: ReadableStreamDefaultController<MoqtObject>;
658
+ readonly stream: ReadableStream<MoqtObject>;
659
+ constructor(msg: Subscribe);
660
+ /**
661
+ * Updates subscription parameters in-place when a `RequestUpdate` message is received.
662
+ */
663
+ update(msg: RequestUpdate): void;
664
+ /**
665
+ * Marks this subscription request as canceled.
666
+ */
667
+ unsubscribe(): void;
668
+ /**
669
+ * Resolves the internal promise with a `SubscribeOk` or `RequestError`.
670
+ */
671
+ resolve(value: SubscribeOk | RequestError | PromiseLike<SubscribeOk | RequestError>): void;
672
+ /**
673
+ * Rejects the internal promise with an error/reason.
674
+ */
675
+ reject(reason?: any): void;
676
+ then<TResult1 = SubscribeOk | RequestError, TResult2 = never>(onfulfilled?: ((value: SubscribeOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
677
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<SubscribeOk | RequestError | TResult>;
678
+ finally(onfinally?: (() => void) | undefined | null): Promise<SubscribeOk | RequestError>;
679
+ }
680
+ /**
681
+ * Owns the single consumer-facing stream for a SUBSCRIBE that may be switched to a
682
+ * new track one or more times. A soft switch can keep producing from the old track
683
+ * for an unknown time after SUBSCRIBE_OK, and a second switch may be issued before the
684
+ * first target ever delivers anything, so only the first object actually delivered by
685
+ * the newest tracked request is the guarantee that nothing older will send again.
686
+ *
687
+ * That first delivery is the handover, not the end of the old track: a soft switch
688
+ * leaves it delivering up to the group the new one starts at, so the two meet without
689
+ * a hole. Those objects keep coming through here until the publisher says the
690
+ * subscription is done, or until it has been quiet long enough to say so itself.
691
+ */
692
+ declare class Subscription {
693
+ #private;
694
+ readonly controller: ReadableStreamDefaultController<MoqtObject>;
695
+ readonly stream: ReadableStream<MoqtObject>;
696
+ /** Set once by `MOQtailClient.switch`; invoked with everything older on cutover. */
697
+ onSuperseded?: (superseded: SubscribeRequest[]) => void;
698
+ /** Set by the client to decide whether draining a request should continue. */
699
+ onDrainDecision: (request: SubscribeRequest) => boolean;
700
+ /**
701
+ * How long a drained request may stay quiet before it is retired anyway, in
702
+ * milliseconds. The publisher normally ends the drain with a PUBLISH_DONE; this is
703
+ * what keeps a request that never gets one from being tracked forever.
704
+ */
705
+ drainTimeoutMs: number;
706
+ constructor(initial: SubscribeRequest);
707
+ /** Requests still tracked, oldest first, draining ones last. */
708
+ get requests(): readonly SubscribeRequest[];
709
+ /** The request most recently switched to; must deliver data to win the handover. */
710
+ get newest(): SubscribeRequest;
711
+ /**
712
+ * Track a newly issued switch target alongside whatever is still delivering.
713
+ *
714
+ * `drainSuperseded` says what its handover does to the requests it takes over from:
715
+ * a soft switch leaves them delivering to the end of what the publisher was told to
716
+ * finish, a hard one retires them on the spot.
717
+ */
718
+ addSwitchTarget(request: SubscribeRequest, drainSuperseded?: boolean): void;
719
+ /** Stop tracking `request` (e.g. it naturally completed without ever losing/winning a handover). */
720
+ drop(request: SubscribeRequest): void;
721
+ /** Stop tracking everything (used when the whole switch chain is torn down at once). */
722
+ clear(): void;
723
+ /**
724
+ * Delivers an object received for `request`. The first object delivered by the
725
+ * newest tracked request retires everything older — only then is it guaranteed no
726
+ * more data is coming from them.
727
+ *
728
+ * Returns `true` if the object was delivered to the caller,
729
+ * `false` if it was not consumed, and client should cancel the stream.
730
+ */
731
+ deliver(request: SubscribeRequest, obj: MoqtObject): boolean;
732
+ }
733
+ //#endregion
734
+ //#region src/client/request_stream.d.ts
735
+ /** Observers for the messages a request stream carries, for logging or debugging. */
736
+ type RequestStreamHooks = {
737
+ onMessageSent?: (msg: ControlMessage) => void;
738
+ onMessageReceived?: (msg: ControlMessage) => void;
843
739
  };
844
-
845
740
  /**
846
- * Copyright 2025 The MOQtail Authors
847
- *
848
- * Licensed under the Apache License, Version 2.0 (the "License");
849
- * you may not use this file except in compliance with the License.
850
- * You may obtain a copy of the License at
851
- *
852
- * http://www.apache.org/licenses/LICENSE-2.0
853
- *
854
- * Unless required by applicable law or agreed to in writing, software
855
- * distributed under the License is distributed on an "AS IS" BASIS,
856
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
857
- * See the License for the specific language governing permissions and
858
- * limitations under the License.
741
+ * Wraps a WebTransport bidirectional stream carrying one MOQT request.
742
+ * Because a response is correlated by the stream it arrives on, nothing here needs a
743
+ * request id.
859
744
  */
860
-
745
+ declare class RequestStream {
746
+ #private;
747
+ readonly stream: ReadableStream<ControlMessage>;
748
+ /**
749
+ * The message this side opened the stream with, kept so the request can be re-issued
750
+ * on a fresh stream when the peer migrates it with a GOAWAY (§10.4). Undefined on a
751
+ * peer-opened stream, which is the peer's request to re-issue, not ours.
752
+ */
753
+ first?: ControlMessage;
754
+ /**
755
+ * The type of the message that opened this stream, whichever side opened it. It is
756
+ * what the request on this stream *is*, which decides what may follow — a
757
+ * REQUEST_UPDATE is only valid for the types §10.9 lists.
758
+ */
759
+ openingType?: ControlMessageType;
760
+ /** Set when the request this stream carried has been re-issued on a new stream. */
761
+ migrated: boolean;
762
+ constructor(biStream: WebTransportBidirectionalStream, hooks?: RequestStreamHooks);
763
+ /**
764
+ * Opens a new bidi stream and writes `first` on it.
765
+ *
766
+ * @throws :{@link ProtocolViolationError} If `first` is not one of the seven types
767
+ * Table 5 marks `First`; those are the only ones allowed to open a request stream.
768
+ */
769
+ static open(webTransport: WebTransport, first: ControlMessage, hooks?: RequestStreamHooks): Promise<RequestStream>;
770
+ /**
771
+ * Reads the next control message off this stream, or `undefined` once the peer has
772
+ * closed or reset it.
773
+ *
774
+ * Takes ownership of {@link RequestStream.stream}'s reader on first use, so callers
775
+ * must not mix `next()` with `stream.getReader()`.
776
+ */
777
+ next(): Promise<ControlMessage | undefined>;
778
+ send(message: ControlMessage): Promise<void>;
779
+ close(): Promise<void>;
780
+ /**
781
+ * Cancels the request by resetting its stream with `code`.
782
+ */
783
+ reset(code: StreamResetCode): Promise<void>;
784
+ }
785
+ //#endregion
786
+ //#region src/client/publication/subscribe.d.ts
787
+ /**
788
+ * @public
789
+ * Manages the publication of MOQT objects to a subscriber for a specific track.
790
+ * Handles live object streaming, subscription lifecycle, and stream management.
791
+ */
792
+ declare class SubscribePublication {
793
+ #private;
794
+ private readonly client;
795
+ readonly track: Track;
796
+ private readonly subscribeMsg;
797
+ private readonly requestStream;
798
+ /**
799
+ * The latest location that was published to the subscriber.
800
+ */
801
+ latestLocation: Location | undefined;
802
+ /**
803
+ * Creates a new SubscribePublication instance.
804
+ * @param client - The MOQT client managing the subscription.
805
+ * @param track - The track being published.
806
+ * @param subscribeMsg - The subscribe message containing subscription details.
807
+ * @param requestStream - The bidi request stream the SUBSCRIBE arrived on. Every
808
+ * message this publication sends back to the subscriber goes on it.
809
+ * @param largestLocation - The largest location seen so far, used for determining start location.
810
+ */
811
+ constructor(client: MOQtailClient, track: Track, subscribeMsg: Subscribe, requestStream: RequestStream, largestLocation?: Location);
812
+ /**
813
+ * Cancels the publication and cleans up resources.
814
+ * Removes the publication from the client's publication map.
815
+ */
816
+ cancel(): void;
817
+ /**
818
+ * Marks the publication as done and sends a PublishDone message to the client.
819
+ * @param statusCode - The status code indicating why the publication ended.
820
+ * @throws :{@link InternalError} If sending the message fails.
821
+ */
822
+ done(statusCode: PublishDoneStatusCode): Promise<void>;
823
+ /**
824
+ * Updates the subscription parameters and locations based on a RequestUpdate message.
825
+ * @param msg - The update message containing new request details.
826
+ * @throws :{@link InvalidFilterError} If the Range Filters the subscription would be
827
+ * left with cannot be applied; nothing is updated.
828
+ */
829
+ update(msg: RequestUpdate): void;
830
+ /**
831
+ * Publishes MOQT objects to the subscriber as they become available.
832
+ * Handles stream creation, object writing, and stream closure based on subscription parameters.
833
+ * @throws :{@link InternalError} If the track does not support live content.
834
+ */
835
+ publish(): Promise<void>;
836
+ }
837
+ //#endregion
838
+ //#region src/client/publication/fetch.d.ts
839
+ declare class FetchPublication {
840
+ #private;
841
+ /** `start` and `end` are the FETCH's range resolved against the Largest Object, inclusive. */
842
+ constructor(client: MOQtailClient, track: Track, fetchRequest: Fetch, start: Location, end: Location);
843
+ cancel(): void;
844
+ /**
845
+ * Resets the data stream this fetch is being delivered on, which §10.9.1 requires when
846
+ * a REQUEST_UPDATE for a FETCH fails.
847
+ */
848
+ resetDataStream(code: StreamResetCode): Promise<void>;
849
+ publish(): Promise<void>;
850
+ }
851
+ //#endregion
852
+ //#region src/client/publication/publish.d.ts
853
+ /**
854
+ * @public
855
+ * Manages the proactive publication of MOQT objects from a publisher to the relay.
856
+ * Handles live object streaming and stream management.
857
+ */
858
+ declare class PublishPublication {
859
+ #private;
860
+ private readonly client;
861
+ readonly track: Track;
862
+ private readonly publishMsg;
863
+ /**
864
+ * The latest location that was published to the relay.
865
+ */
866
+ latestLocation: Location | undefined;
867
+ /**
868
+ * Creates a new PublishPublication instance.
869
+ * @param client - The MOQT client managing the connection.
870
+ * @param track - The track being proactively published.
871
+ * @param publishMsg - The publish message that initiated this session.
872
+ */
873
+ constructor(client: MOQtailClient, track: Track, publishMsg: Publish);
874
+ /**
875
+ * How many data streams this publication has opened, which is what a PUBLISH_DONE
876
+ * reports to the subscriber.
877
+ */
878
+ get streamsOpened(): bigint;
879
+ /**
880
+ * Whether Objects are being sent right now. False while the peer holds this
881
+ * publication at FORWARD=0.
882
+ */
883
+ get forwarding(): boolean;
884
+ /**
885
+ * Moves the Forward State: false parks the publication, true resumes it. The
886
+ * application hears about the move through {@link MOQtailClient.onForwardStateChange},
887
+ * which is where a publisher starts or stops the work behind the track -- a camera
888
+ * and an encoder cost the same whether or not anything is listening.
889
+ */
890
+ setForwardState(forward: boolean): void;
891
+ /**
892
+ * Applies a REQUEST_UPDATE the peer sent on this publication's request stream. It
893
+ * can move the Forward State and the Range Filters; what a publisher sends, and
894
+ * when, is otherwise its own to decide.
895
+ * @throws :{@link InvalidFilterError} If the Range Filters the publication would be
896
+ * left with cannot be applied; nothing is updated.
897
+ */
898
+ update(msg: RequestUpdate): void;
899
+ /**
900
+ * Cancels the publication and cleans up resources.
901
+ * Removes the publication from the client's publication map.
902
+ */
903
+ cancel(): void;
904
+ /**
905
+ * Publishes MOQT objects to the relay as they become available.
906
+ * Handles stream creation, object writing, and stream closure.
907
+ * @throws :{@link InternalError} If the track does not support live content.
908
+ */
909
+ publishToRelay(): Promise<void>;
910
+ }
911
+ //#endregion
912
+ //#region src/client/datagram_stream.d.ts
861
913
  /**
862
914
  * Sends MoqtObjects as WebTransport datagrams.
863
915
  * Parallel to SendStream but for datagram-based delivery.
@@ -869,43 +921,43 @@ type FetchOptions = {
869
921
  * ```
870
922
  */
871
923
  declare class SendDatagramStream {
872
- #private;
873
- readonly onDataSent?: (data: Datagram) => void;
874
- constructor(writer: WritableStreamDefaultWriter<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void);
875
- /**
876
- * Create a new datagram sender for a specific track.
877
- *
878
- * @param writeStream - WebTransport datagram writable stream
879
- * @param trackAlias - Track alias for this datagram stream
880
- * @param onDataSent - Optional callback fired when datagram is sent
881
- * @returns SendDatagramStream instance
882
- */
883
- static new(writeStream: WritableStream<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void): Promise<SendDatagramStream>;
884
- /**
885
- * Create a datagram sender using an existing shared writer.
886
- * Use this when multiple senders need to share a single writer.
887
- *
888
- * @param writer - Existing WritableStreamDefaultWriter
889
- * @param trackAlias - Track alias for this datagram stream
890
- * @param onDataSent - Optional callback fired when datagram is sent
891
- * @returns SendDatagramStream instance
892
- */
893
- static fromWriter(writer: WritableStreamDefaultWriter<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void): SendDatagramStream;
894
- /**
895
- * Write a MoqtObject as a datagram.
896
- * Converts to Datagram automatically based on object state.
897
- *
898
- * @param object - MoqtObject to send (must have Datagram forwarding preference)
899
- */
900
- write(object: MoqtObject): Promise<void>;
901
- /**
902
- * Close the datagram writer.
903
- */
904
- close(): Promise<void>;
905
- /**
906
- * Release the writer lock without closing.
907
- */
908
- releaseLock(): void;
924
+ #private;
925
+ readonly onDataSent?: (data: Datagram) => void;
926
+ constructor(writer: WritableStreamDefaultWriter<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void);
927
+ /**
928
+ * Create a new datagram sender for a specific track.
929
+ *
930
+ * @param writeStream - WebTransport datagram writable stream
931
+ * @param trackAlias - Track alias for this datagram stream
932
+ * @param onDataSent - Optional callback fired when datagram is sent
933
+ * @returns SendDatagramStream instance
934
+ */
935
+ static new(writeStream: WritableStream<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void): Promise<SendDatagramStream>;
936
+ /**
937
+ * Create a datagram sender using an existing shared writer.
938
+ * Use this when multiple senders need to share a single writer.
939
+ *
940
+ * @param writer - Existing WritableStreamDefaultWriter
941
+ * @param trackAlias - Track alias for this datagram stream
942
+ * @param onDataSent - Optional callback fired when datagram is sent
943
+ * @returns SendDatagramStream instance
944
+ */
945
+ static fromWriter(writer: WritableStreamDefaultWriter<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void): SendDatagramStream;
946
+ /**
947
+ * Write a MoqtObject as a datagram.
948
+ * Converts to Datagram automatically based on object state.
949
+ *
950
+ * @param object - MoqtObject to send (must have Datagram forwarding preference)
951
+ */
952
+ write(object: MoqtObject): Promise<void>;
953
+ /**
954
+ * Close the datagram writer.
955
+ */
956
+ close(): Promise<void>;
957
+ /**
958
+ * Release the writer lock without closing.
959
+ */
960
+ releaseLock(): void;
909
961
  }
910
962
  /**
911
963
  * Receives and parses WebTransport datagrams as MoqtObjects.
@@ -928,45 +980,30 @@ declare class SendDatagramStream {
928
980
  * ```
929
981
  */
930
982
  declare class RecvDatagramStream {
931
- #private;
932
- readonly stream: ReadableStream<MoqtObject>;
933
- readonly onDataReceived?: (data: Datagram) => void;
934
- private constructor();
935
- /**
936
- * Create a new datagram receiver.
937
- *
938
- * @param readStream - WebTransport datagram readable stream
939
- * @param trackAliasResolver - Function to resolve track alias to full track name
940
- * @param onDataReceived - Optional callback fired when datagram is received
941
- * @returns RecvDatagramStream instance
942
- */
943
- static new(readStream: ReadableStream<Uint8Array>, trackAliasResolver: (trackAlias: bigint) => FullTrackName, onDataReceived?: (data: Datagram) => void): Promise<RecvDatagramStream>;
944
- /**
945
- * Cancel the datagram reader.
946
- */
947
- cancel(): Promise<void>;
948
- /**
949
- * Release the reader lock without canceling.
950
- */
951
- releaseLock(): void;
983
+ #private;
984
+ readonly stream: ReadableStream<MoqtObject>;
985
+ readonly onDataReceived?: (data: Datagram) => void;
986
+ private constructor();
987
+ /**
988
+ * Create a new datagram receiver.
989
+ *
990
+ * @param readStream - WebTransport datagram readable stream
991
+ * @param trackAliasResolver - Function to resolve track alias to full track name
992
+ * @param onDataReceived - Optional callback fired when datagram is received
993
+ * @returns RecvDatagramStream instance
994
+ */
995
+ static new(readStream: ReadableStream<Uint8Array>, trackAliasResolver: (trackAlias: bigint) => FullTrackName, onDataReceived?: (data: Datagram) => void): Promise<RecvDatagramStream>;
996
+ /**
997
+ * Cancel the datagram reader.
998
+ */
999
+ cancel(): Promise<void>;
1000
+ /**
1001
+ * Release the reader lock without canceling.
1002
+ */
1003
+ releaseLock(): void;
952
1004
  }
953
-
954
- /**
955
- * Copyright 2025 The MOQtail Authors
956
- *
957
- * Licensed under the Apache License, Version 2.0 (the "License");
958
- * you may not use this file except in compliance with the License.
959
- * You may obtain a copy of the License at
960
- *
961
- * http://www.apache.org/licenses/LICENSE-2.0
962
- *
963
- * Unless required by applicable law or agreed to in writing, software
964
- * distributed under the License is distributed on an "AS IS" BASIS,
965
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
966
- * See the License for the specific language governing permissions and
967
- * limitations under the License.
968
- */
969
-
1005
+ //#endregion
1006
+ //#region src/client/client.d.ts
970
1007
  /**
971
1008
  * @public
972
1009
  * Represents a Media Over QUIC Transport (MOQT) client session.
@@ -984,7 +1021,7 @@ declare class RecvDatagramStream {
984
1021
  * const client = await MOQtailClient.new({ url });
985
1022
  * const result = await client.subscribe({
986
1023
  * fullTrackName,
987
- * filterType: FilterType.LatestObject,
1024
+ * locationFilter: new LocationFilter(LocationFilterType.NextObject),
988
1025
  * forward: true,
989
1026
  * groupOrder: GroupOrder.Original,
990
1027
  * priority: 0
@@ -1011,833 +1048,911 @@ declare class RecvDatagramStream {
1011
1048
  * ```
1012
1049
  */
1013
1050
  declare class MOQtailClient {
1014
- #private;
1015
- /**
1016
- * Namespace prefixes (tuples) the peer has requested announce notifications for via SUBSCRIBE_NAMESPACE.
1017
- * Used to decide which locally issued ANNOUNCE messages should be forwarded (future optimization: prefix trie).
1018
- */
1019
- readonly peerSubscribeNamespace: Set<Tuple>;
1020
- /**
1021
- * Namespace prefixes this client has subscribed to (issued SUBSCRIBE_NAMESPACE). Enables automatic filtering
1022
- * of incoming PUBLISH_NAMESPACE / PUBLISH_NAMESPACE_DONE. Maintained locally; no dedupe of overlapping / shadowing prefixes yet.
1023
- */
1024
- readonly subscribedAnnounces: Set<Tuple>;
1025
- /**
1026
- * Track namespaces this client has successfully announced (received ANNOUNCE_OK). Source of truth for
1027
- * deciding what to PUBLISH_NAMESPACE_DONE on teardown or targeted withdrawal.(future optimization: prefix trie).
1028
- */
1029
- readonly announcedNamespaces: Set<Tuple>;
1030
- /**
1031
- * Locally registered track definitions keyed by full track name string. Populated via addOrUpdateTrack.
1032
- * Does not imply the track has been announced or has active publications.
1033
- */
1034
- readonly trackSources: Map<string, Track>;
1035
- /**
1036
- * All in‑flight request objects keyed by requestId (SUBSCRIBE, FETCH, ANNOUNCE, etc). Facilitates lookup
1037
- * when responses / data arrive. Entries are removed on completion or error.
1038
- */
1039
- readonly requests: Map<bigint, MOQtailRequest>;
1040
- /**
1041
- * Active publications (SUBSCRIBE or FETCH) keyed by requestId to manage object stream controllers and lifecycle.
1042
- * Subset / specialization view of `requests`.
1043
- */
1044
- readonly publications: Map<bigint, SubscribePublication | FetchPublication | PublishPublication>;
1045
- /**
1046
- * Active SUBSCRIBE request wrappers keyed by track alias for rapid alias -\> subscription resolution during
1047
- * incoming unidirectional data handling.
1048
- */
1049
- readonly subscriptions: Map<bigint, any>;
1050
- /**
1051
- * Bidirectional track alias \<-\> subscription requestId mapping
1052
- */
1053
- readonly subscriptionAliasMap: Map<bigint, bigint>;
1054
- /**
1055
- * Bidirectional requestId \<-\> full track name mapping to reconstruct metadata for incoming objects.
1056
- */
1057
- readonly requestIdMap: RequestIdMap;
1058
- /**
1059
- * Maps track aliases to full track names for quick resolution during data handling.
1060
- */
1061
- readonly aliasFullTrackNameMap: Map<bigint, FullTrackName>;
1062
- /**
1063
- * Pending state updates keyed by requestId and applied once a new track alias is seen.
1064
- * Used to avoid premature state updates.
1065
- */
1066
- readonly pendingStateUpdates: Map<bigint, (newTrackAlias: bigint) => boolean>;
1067
- /** Underlying WebTransport session (set after successful construction in MOQtailClient.new). */
1068
- webTransport: WebTransport;
1069
- /** Outgoing / incoming control message bidirectional stream wrapper. */
1070
- controlStream: ControlStream;
1071
- /** Timeout (ms) applied to reading incoming data streams; undefined =\> no explicit timeout. */
1072
- dataStreamTimeoutMs?: number;
1073
- /** Timeout (ms) for control stream read operations; undefined =\> no explicit timeout. */
1074
- controlStreamTimeoutMs?: number;
1075
- /** Optional highest request id allowed (enforced externally / via configuration). */
1076
- maxRequestId?: bigint;
1077
- /**
1078
- * TODO: onNamespaceAnnounced may be a better name
1079
- * Fired when an PUBLISH_NAMESPACE control message is processed for a track namespace.
1080
- * Use to update UI or trigger discovery logic.
1081
- * Discovery event.
1082
- */
1083
- onNamespacePublished?: (msg: PublishNamespace) => void;
1084
- /**
1085
- * Fired when an PUBLISH_NAMESPACE_DONE control message is processed for a namespace.
1086
- * Use to remove tracks from UI or stop discovery.
1087
- * Discovery event.
1088
- */
1089
- onNamespaceDone?: (msg: PublishNamespaceDone) => void;
1090
- /**
1091
- * Fired on GOAWAY reception signaling graceful session wind-down.
1092
- * Use to prepare for disconnect or cleanup.
1093
- * Lifecycle handler.
1094
- */
1095
- onGoaway?: (msg: GoAway) => void;
1096
- /**
1097
- * Fired if the underlying WebTransport session fails (ready -\> closed prematurely).
1098
- * Use to log or alert on transport errors.
1099
- * Lifecycle/error handler.
1100
- */
1101
- onWebTransportFail?: () => void;
1102
- /**
1103
- * Fired exactly once when the client transitions to terminated (disconnect).
1104
- * Use to clean up resources or notify user.
1105
- * Lifecycle handler.
1106
- */
1107
- onSessionTerminated?: (reason?: unknown) => void;
1108
- /**
1109
- * Invoked after each outbound control message is sent.
1110
- * Use for logging or analytics.
1111
- * Informational event.
1112
- */
1113
- onMessageSent?: (msg: ControlMessage) => void;
1114
- /**
1115
- * Invoked upon receiving each inbound control message before handling.
1116
- * Use for logging or debugging.
1117
- * Informational event.
1118
- */
1119
- onMessageReceived?: (msg: ControlMessage) => void;
1120
- /**
1121
- * Invoked for each decoded data object/header arriving on a uni stream (fetch or subgroup).
1122
- * Use to process or display incoming media/data.
1123
- * Informational event.
1124
- */
1125
- onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1126
- /**
1127
- * Invoked after enqueuing each outbound data object/header.
1128
- * Reserved for future use.
1129
- * Informational event.
1130
- */
1131
- onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1132
- /**
1133
- * General-purpose error callback for surfaced exceptions not thrown to caller synchronously.
1134
- * Use to log or display errors.
1135
- * Error handler.
1136
- */
1137
- onError?: (er: unknown) => void;
1138
- /** Invoked for each decoded datagram object/status arriving. */
1139
- onDatagramReceived?: (data: Datagram) => void;
1140
- /** Invoked after enqueuing each outbound datagram object/status. */
1141
- onDatagramSent?: (data: Datagram) => void;
1142
- /** Fired when an inbound PUBLISH control message is received. */
1143
- onPeerPublish?: (msg: Publish, stream: ReadableStream<MoqtObject>) => void;
1144
- /** Fired when an inbound PUBLISH_DONE control message is received. */
1145
- onPeerPublishDone?: (msg: PublishDone) => void;
1146
- /** Fired when an inbound SUBSCRIBE_NAMESPACE control message is received. */
1147
- onPeerSubscribeNamespace?: (msg: SubscribeNamespace) => void;
1148
- /** Fired when a NAMESPACE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
1149
- onPeerNamespace?: (prefix: Tuple, suffix: Tuple) => void;
1150
- /** Fired when a NAMESPACE_DONE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
1151
- onPeerNamespaceDone?: (prefix: Tuple, suffix: Tuple) => void;
1152
- /**
1153
- * Stream of all received MoqtObjects from datagrams across all tracks
1154
- * Consumer should filter by fullTrackName as needed
1155
- *
1156
- * WARNING: Only one reader should be active. For multiple subscribers,
1157
- * use subscribeToTrackDatagrams() instead
1158
- */
1159
- readonly receivedDatagramObjects: ReadableStream<MoqtObject>;
1160
- /**
1161
- * Generates a safe, sequential local request ID for tracking pushed/incoming tracks.
1162
- */
1163
- allocatePseudoRequestId(): bigint;
1164
- /**
1165
- * Gets the current server setup configuration.
1166
- *
1167
- * @returns The {@link ServerSetup} instance associated with this client.
1168
- */
1169
- get serverSetup(): ServerSetup;
1170
- /**
1171
- * Returns true if datagram support is currently active
1172
- */
1173
- get isDatagramsEnabled(): boolean;
1174
- /**
1175
- * Sets the global log level for all moqtail-ts loggers.
1176
- * @param level - The minimum {@link LogLevel} to output. Use `LogLevel.NONE` to silence all logs.
1177
- */
1178
- static setLogLevel(level: LogLevel): void;
1179
- /**
1180
- * Restricts log output to the specified module names. Pass `null` to allow all modules.
1181
- * @param modules - Array of module name strings, or `null` to enable all modules.
1182
- */
1183
- static setLogEnabledModules(modules: string[] | null): void;
1184
- private constructor();
1185
- /**
1186
- * Establishes a new {@link MOQtailClient} session over WebTransport and performs the MOQT setup handshake.
1187
- *
1188
- * @param args - {@link MOQtailClientOptions}
1189
- *
1190
- * @returns Promise resolving to a ready {@link MOQtailClient} instance.
1191
- *
1192
- * @throws :{@link ProtocolViolationError} If the server sends an unexpected or invalid message during setup.
1193
- *
1194
- * @example Minimal connection
1195
- * ```ts
1196
- * const client = await MOQtailClient.new({
1197
- * url: 'https://relay.example.com/transport'
1198
- * });
1199
- * ```
1200
- *
1201
- * @example With callbacks and options
1202
- * ```ts
1203
- * const client = await MOQtailClient.new({
1204
- * url,
1205
- * setupParameters: new SetupParameters().addMaxRequestId(1000),
1206
- * transportOptions: { congestionControl: 'default' },
1207
- * dataStreamTimeoutMs: 5000,
1208
- * controlStreamTimeoutMs: 2000,
1209
- * enableDatagrams: true,
1210
- * callbacks: {
1211
- * onMessageSent: msg => console.log('Sent:', msg),
1212
- * onMessageReceived: msg => console.log('Received:', msg),
1213
- * onSessionTerminated: reason => console.warn('Session ended:', reason),
1214
- * onDatagramReceived: data => console.log('Datagram:', data),
1215
- * }
1216
- * });
1217
- * ```
1218
- */
1219
- static new(args: MOQtailClientOptions): Promise<MOQtailClient>;
1220
- /**
1221
- * Start receiving datagrams from the WebTransport connection.
1222
- * Must be called before datagrams can be received (unless enableDatagrams: true was set in options).
1223
- *
1224
- * @throws MOQtailError if client is destroyed or datagrams already started
1225
- */
1226
- startDatagrams(): Promise<void>;
1227
- /**
1228
- * Stop receiving datagrams and release resources.
1229
- * Idempotent - safe to call multiple times.
1230
- */
1231
- stopDatagrams(): Promise<void>;
1232
- /**
1233
- * Subscribe to receive datagrams for a specific track.
1234
- * Multiple tracks can have separate handlers that run concurrently.
1235
- *
1236
- * @param trackAlias - Track alias to subscribe to
1237
- * @param handler - Function called for each received MoqtObject on this track
1238
- * @returns Unsubscribe function to remove the handler
1239
- *
1240
- * @example
1241
- * ```ts
1242
- * const unsubscribe = client.subscribeToTrackDatagrams(trackAlias, (obj) => {
1243
- * console.log('Received datagram:', obj.payload);
1244
- * });
1245
- * // Later: unsubscribe();
1246
- * ```
1247
- */
1248
- subscribeToTrackDatagrams(trackAlias: bigint, handler: (obj: MoqtObject) => void): () => void;
1249
- /**
1250
- * Unsubscribe from datagram delivery for a specific track.
1251
- *
1252
- * @param trackAlias - Track alias to unsubscribe from
1253
- */
1254
- unsubscribeFromTrackDatagrams(trackAlias: bigint): void;
1255
- /**
1256
- * Create a datagram sender for a specific track.
1257
- *
1258
- * @param trackAlias - Track alias for outgoing datagrams
1259
- * @returns SendDatagramStream for writing MoqtObjects as datagrams
1260
- * @throws MOQtailError if datagram writer not initialized (call startDatagrams() first)
1261
- *
1262
- * @example
1263
- * ```ts
1264
- * const sender = client.createDatagramSender(trackAlias);
1265
- * await sender.write(moqtObject);
1266
- * ```
1267
- */
1268
- createDatagramSender(trackAlias: bigint): SendDatagramStream;
1269
- /**
1270
- * Send a single MoqtObject as a datagram.
1271
- * Convenience method for one-off datagram sends.
1272
- *
1273
- * @param trackAlias - Track alias for this object
1274
- * @param object - MoqtObject to send
1275
- * @throws MOQtailError if datagram writer not initialized
1276
- *
1277
- * @example
1278
- * ```ts
1279
- * await client.sendDatagram(trackAlias, moqtObject);
1280
- * ```
1281
- */
1282
- sendDatagram(trackAlias: bigint, object: MoqtObject): Promise<void>;
1283
- /**
1284
- * Sets (or replaces) the client-level default early discard policy for incoming subgroup streams.
1285
- *
1286
- * When set, each incoming subgroup QUIC stream is given a deadline of `subgroupReceiveTimeout` ms to
1287
- * complete. If the stream has not finished within that window it is cancelled — objects already
1288
- * delivered to the subscription are kept, but no further objects arrive from that stream.
1289
- *
1290
- * This is a client-wide default. Individual subscriptions can override it via the `earlyDiscardPolicy`
1291
- * field in {@link SubscribeOptions}, which takes precedence over this setting.
1292
- *
1293
- * The policy takes effect on the next stream accepted after this call. Passing a new config
1294
- * replaces the previous one. Pass `undefined` to remove the default.
1295
- *
1296
- * @example
1297
- * ```ts
1298
- * client.setEarlyDiscardPolicy({ subgroupReceiveTimeout: 2000 })
1299
- * ```
1300
- */
1301
- setEarlyDiscardPolicy(config: EarlyDiscardPolicyConfig | undefined): void;
1302
- /**
1303
- * Gracefully terminates this {@link MOQtailClient} session and releases underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} resources.
1304
- *
1305
- * @param reason - Optional application-level reason (string or error) recorded and wrapped in an {@link InternalError}
1306
- * passed to the {@link MOQtailClient.onSessionTerminated | onSessionTerminated} callback.
1307
- *
1308
- * @returns Promise that resolves once shutdown logic completes. Subsequent calls are safe no-ops.
1309
- *
1310
- * @example Basic usage
1311
- * ```ts
1312
- * await client.disconnect();
1313
- * ```
1314
- *
1315
- * @example With reason
1316
- * ```ts
1317
- * await client.disconnect('user logout');
1318
- * ```
1319
- *
1320
- * @example Idempotent double call
1321
- * ```ts
1322
- * await client.disconnect();
1323
- * await client.disconnect(); // no error
1324
- * ```
1325
- *
1326
- * @example Page unload safety
1327
- * ```ts
1328
- * window.addEventListener('beforeunload', () => {
1329
- * client.disconnect('page unload');
1330
- * });
1331
- * ```
1332
- */
1333
- disconnect(reason?: unknown): Promise<void>;
1334
- /**
1335
- * Registers or updates a {@link Track} definition for local publishing or serving.
1336
- *
1337
- * A {@link Track} describes a logical media/data stream, identified by a unique name and namespace.
1338
- * - If `trackSource.live` is present, the track can be served to subscribers in real-time.
1339
- * - If `trackSource.past` is present, the track can be fetched for historical data.
1340
- * - If both are present, the track supports both live and historical access.
1341
- *
1342
- * @param track - The {@link Track} instance to add or update. See {@link TrackSource} for live/past source options.
1343
- * @returns void
1344
- * @throws : {@link MOQtailError} If the client has been destroyed.
1345
- *
1346
- * @example Create a live video track from getUserMedia
1347
- * ```ts
1348
- * const stream = await navigator.mediaDevices.getUserMedia({ video: true });
1349
- * const videoTrack = stream.getVideoTracks()[0];
1350
- *
1351
- * // Convert video frames to MoqtObject instances using your chosen scheme (e.g. WARP, CMAF, etc.)
1352
- * // This part is application-specific and not provided by MOQtail:
1353
- * const liveReadableStream: ReadableStream<MoqtObject> = ...
1354
- *
1355
- * // Register the track for live subscription
1356
- * client.addOrUpdateTrack({
1357
- * fullTrackName: { namespace: ["camera"], name: "main" },
1358
- * trackSource: { live: liveReadableStream },
1359
- * publisherPriority: 0 // highest priority
1360
- * });
1361
- *
1362
- * // For a hybrid track (live + past):
1363
- * import { MemoryObjectCache } from './track/object_cache';
1364
- * const cache = new MemoryObjectCache(); // Caches are not yet fully supported
1365
- * client.addOrUpdateTrack({
1366
- * fullTrackName: { namespace: ["camera"], name: "main" },
1367
- * trackSource: { live: liveReadableStream, past: cache },
1368
- * publisherPriority: 8
1369
- * });
1370
- * ```
1371
- */
1372
- addOrUpdateTrack(track: Track): void;
1373
- /**
1374
- * Removes a previously registered {@link Track} from this client's local catalog.
1375
- *
1376
- * This deletes the in-memory entry inserted via {@link MOQtailClient.addOrUpdateTrack}, so future lookups by its {@link Track.fullTrackName} will fail.
1377
- * Does **not** automatically:
1378
- * - Send an {@link PublishNamespaceDone} (call {@link MOQtailClient.publishNamespaceDone} separately if you want to inform peers)
1379
- * - Cancel active subscriptions or fetches (they continue until normal completion)
1380
- * - Affect already-sent objects.
1381
- *
1382
- * If the track was not present, the call is a silent no-op (idempotent removal).
1383
- *
1384
- * @param track - The exact {@link Track} instance (its canonical name is used as the key).
1385
- * @throws : {@link MOQtailError} If the client has been destroyed.
1386
- *
1387
- * @example
1388
- * ```ts
1389
- * // Register a track
1390
- * client.addOrUpdateTrack(track);
1391
- *
1392
- * // Later, when no longer publishing:
1393
- * client.removeTrack(track);
1394
- *
1395
- * // Optionally, inform peers that the namespace is no longer available:
1396
- * await client.publishNamespaceDone(track.fullTrackName.namespace);
1397
- * ```
1398
- */
1399
- removeTrack(track: Track): void;
1400
- /**
1401
- * Subscribes to a track and returns a stream of {@link MoqtObject}s matching the requested window and relay forwarding mode.
1402
- *
1403
- * - `forward: true` tells the relay to forward objects to this subscriber as they arrive.
1404
- * - `forward: false` means the relay subscribes upstream but buffers objects locally, not forwarding them to you.
1405
- * - `filterType: AbsoluteStart` lets you specify a start position in the future; the stream waits for that object. If the start location is \< the latest object
1406
- * observed at the publisher then it behaves as `filterType: LatestObject`
1407
- * - `filterType: AbsoluteRange` lets you specify a start and end group, both of should be in the future; the stream waits for those objects. If the start location is \< the latest object
1408
- * observed at the publisher then it behaves as `filterType: LatestObject`.
1409
- *
1410
- * The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId` and a `ReadableStream` of {@link MoqtObject}s.
1411
- * Use the `requestId` for {@link MOQtailClient.unsubscribe} or {@link MOQtailClient.subscribeUpdate}. Use the `stream` to decode and display objects.
1412
- *
1413
- * @param args - {@link SubscribeOptions} describing the subscription window and relay forwarding behavior.
1414
- * @returns Either a {@link RequestError} or `{ requestId, stream }` for consuming objects.
1415
- * @throws : {@link MOQtailError} If the client is destroyed.
1416
- * @throws : {@link ProtocolViolationError} If required fields are missing or inconsistent.
1417
- * @throws : {@link InternalError} On transport/protocol failure (disconnect is triggered before rethrow).
1418
- *
1419
- * @example Subscribe to the latest object and receive future objects as they arrive
1420
- * ```ts
1421
- * const result = await client.subscribe({
1422
- * fullTrackName,
1423
- * filterType: FilterType.LatestObject,
1424
- * forward: true,
1425
- * groupOrder: GroupOrder.Original,
1426
- * priority: 32
1427
- * });
1428
- * if (!(result instanceof RequestError)) {
1429
- * for await (const obj of result.stream) {
1430
- * // decode and display obj
1431
- * }
1432
- * }
1433
- * ```
1434
- *
1435
- * @example Subscribe to a future range (waits for those objects to arrive)
1436
- * ```ts
1437
- * const result = await client.subscribe({
1438
- * fullTrackName,
1439
- * filterType: FilterType.AbsoluteRange,
1440
- * startLocation: futureStart,
1441
- * endGroup: futureEnd,
1442
- * forward: true,
1443
- * groupOrder: GroupOrder.Original,
1444
- * priority: 128
1445
- * });
1446
- * ```
1447
- */
1448
- subscribe(args: SubscribeOptions): Promise<RequestError | {
1449
- requestId: bigint;
1450
- stream: ReadableStream<MoqtObject>;
1451
- }>;
1452
- /**
1453
- * Stops an active subscription identified by its original SUBSCRIBE `requestId`.
1454
- *
1455
- * Sends an {@link Unsubscribe} control frame if the subscription is still active. If the id is unknown or already
1456
- * cleaned up, the call is a silent no-op (hence multiple calls are idempotent).
1457
- *
1458
- * Use this when you no longer want incoming objects for a track (e.g. user navigated away, switching quality).
1459
- * Canceling the consumer stream reader does **not** auto-unsubscribe; call this explicitly for prompt cleanup.
1460
- *
1461
- * @param requestId - The id returned from {@link MOQtailClient.subscribe}.
1462
- * @returns Promise that resolves when the unsubscribe control frame is sent.
1463
- * @throws :{@link MOQtailError} If the client is destroyed.
1464
- * @throws :{@link InternalError} Wrapped lower-level failure while attempting to send (session will be disconnected first).
1465
- *
1466
- * @remarks
1467
- * - Only targets SUBSCRIBE requests, not fetches. Passing a fetch request id is ignored (no-op).
1468
- * - Safe to call multiple times; extra calls have no effect.
1469
- *
1470
- * @example Subscribe and later unsubscribe
1471
- * ```ts
1472
- * const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 });
1473
- * if (!(sub instanceof RequestError)) {
1474
- * // ...consume objects...
1475
- * await client.unsubscribe(sub.requestId);
1476
- * }
1477
- * ```
1478
- *
1479
- * @example Idempotent usage
1480
- * ```ts
1481
- * await client.unsubscribe(123n);
1482
- * await client.unsubscribe(123n); // no error
1483
- * ```
1484
- */
1485
- unsubscribe(requestId: bigint | number): Promise<void>;
1486
- /**
1487
- * Narrows or updates an active subscription window and/or relay forwarding behavior.
1488
- *
1489
- * Use this to:
1490
- * - Move the start of the subscription forward (trim history or future window).
1491
- * - Move the end group earlier (shorten the window).
1492
- * - Change relay forwarding (`forward: false` stops forwarding new objects, `true` resumes).
1493
- * - Adjust subscriber priority.
1494
- *
1495
- * Only narrowing is allowed: you cannot move the start earlier or the end group later than the original subscription.
1496
- * Forwarding and priority can be changed at any time.
1497
- *
1498
- * @param args - {@link SubscribeUpdateOptions} referencing the original subscription `requestId` and new bounds.
1499
- * @returns Promise that resolves when the update control frame is sent.
1500
- * @throws :{@link MOQtailError} If the client is destroyed.
1501
- * @throws :{@link ProtocolViolationError} If the update would widen the window (earlier start, later end group, or invalid ordering).
1502
- * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
1503
- *
1504
- * @remarks
1505
- * - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
1506
- * - Omitting a parameter (e.g. `priority`) leaves the previous value unchanged.
1507
- * - Setting `forward: false` stops relay forwarding new objects after the current window drains.
1508
- * - Safe to call multiple times; extra calls with unchanged bounds have no effect.
1509
- *
1510
- * @example Trim start forward
1511
- * ```ts
1512
- * await client.subscribeUpdate({ requestId, startLocation: laterLoc, endGroup, forward: true, priority });
1513
- * ```
1514
- *
1515
- * @example Convert tailing subscription into bounded slice
1516
- * ```ts
1517
- * await client.subscribeUpdate({ requestId, startLocation: origStart, endGroup: cutoffGroup, forward: false, priority });
1518
- * ```
1519
- *
1520
- * @example Lower priority only
1521
- * ```ts
1522
- * await client.subscribeUpdate({ requestId, startLocation: currentStart, endGroup: currentEnd, forward: true, priority: 200 });
1523
- * ```
1524
- */
1525
- subscribeUpdate(args: SubscribeUpdateOptions): Promise<void>;
1526
- /**
1527
- * Switches an active subscription to a different track while retaining the same subscription parameters.
1528
- *
1529
- * Use this to change the subscribed track without tearing down and re-establishing a new subscription.
1530
- *
1531
- * @param args - {@link SwitchOptions} referencing the original subscription `requestId` and new track name.
1532
- * @returns Promise that resolves when the switch control frame is sent.
1533
- * @throws :{@link MOQtailError} If the client is destroyed.
1534
- * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
1535
- *
1536
- * @remarks
1537
- * - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
1538
- * - All other subscription parameters (window, forwarding, priority) remain unchanged.
1539
- *
1540
- * @example Switch to a different track
1541
- * ```ts
1542
- * await client.switch({ subscriptionRequestId, fullTrackName: newTrackName });
1543
- * ```
1544
- */
1545
- switch(args: SwitchOptions): Promise<RequestError | {
1546
- requestId: bigint;
1547
- stream: ReadableStream<MoqtObject>;
1548
- }>;
1549
- /**
1550
- * One-shot retrieval of a bounded object span, optionally anchored to an existing subscription, returning a stream of {@link MoqtObject}s.
1551
- *
1552
- * Choose a fetch type via `typeAndProps.type`:
1553
- * - Standalone: Historical slice of a specific {@link FullTrackName} independent of active subscriptions.
1554
- * - Relative: Range relative to the JOINING subscription's current (largest) location; use when you want "N groups back" from live.
1555
- * - Absolute: Absolute group/object offsets tied to an existing subscription (stable anchor) even if that subscription keeps forwarding.
1556
- *
1557
- * Field highlights (in {@link FetchOptions}):
1558
- * - priority: 0 (highest) .. 255 (lowest); out-of-range rejected; non-integers rounded by caller expectation.
1559
- * - groupOrder: {@link GroupOrder.Original} to preserve publisher order; or reorder ascending/descending if supported by server.
1560
- * - typeAndProps: Discriminated union carrying parameters specific to each fetch mode (see examples).
1561
- * - parameters: Optional version-specific extension block.
1562
- *
1563
- * Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, stream }` whose `stream`
1564
- * ends naturally after the bounded range completes (no explicit cancel needed for normal completion).
1565
- *
1566
- * Use cases:
1567
- * - Grab a historical window for scrubbing UI while a separate live subscription tails.
1568
- * - Late joiner fetching a short back-buffer then discarding the stream.
1569
- * - Analytics batch job pulling a fixed slice without subscribing long-term.
1570
- *
1571
- * @throws MOQtailError If client is destroyed.
1572
- * @throws ProtocolViolationError Priority out of [0-255] or missing/invalid joining subscription id for Relative/Absolute.
1573
- * @throws InternalError Transport/control failure (the client disconnects first) then rethrows original error.
1574
- *
1575
- * @remarks
1576
- * - Relative / Absolute require an existing active SUBSCRIBE `joiningRequestId`; if not found a {@link ProtocolViolationError} is thrown.
1577
- * - Result stream is finite; reader close occurs automatically when last object delivered.
1578
- * - Use {@link MOQtailClient.fetchCancel} only for early termination (not yet fully implemented: see TODO in code).
1579
- *
1580
- * @example Standalone window
1581
- * ```ts
1582
- * const r = await client.fetch({
1583
- * priority: 64,
1584
- * groupOrder: GroupOrder.Original,
1585
- * typeAndProps: {
1586
- * type: FetchType.Standalone,
1587
- * props: { fullTrackName, startLocation, endLocation }
1588
- * }
1589
- * })
1590
- * if (!(r instanceof RequestError)) {
1591
- * for await (const obj of r.stream as any) {
1592
- * // consume objects then stream ends automatically
1593
- * }
1594
- * }
1595
- * ```
1596
- *
1597
- * @example Relative to live subscription (e.g. last 5 groups)
1598
- * ```ts
1599
- * const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 })
1600
- * if (!(sub instanceof RequestError)) {
1601
- * const slice = await client.fetch({
1602
- * priority: 32,
1603
- * groupOrder: GroupOrder.Original,
1604
- * typeAndProps: { type: FetchType.Relative, props: { joiningRequestId: sub.requestId, joiningStart: 0n } }
1605
- * })
1606
- * }
1607
- * ```
1608
- */
1609
- fetch(args: FetchOptions): Promise<RequestError | {
1610
- requestId: bigint;
1611
- stream: ReadableStream<MoqtObject>;
1612
- }>;
1613
- /**
1614
- * Request early termination of an in‑flight FETCH identified by its `requestId`.
1615
- *
1616
- * Use when the consumer no longer needs the remaining objects (user scrubbed away, UI panel closed, replaced by a new fetch).
1617
- * Sends a {@link FetchCancel} control frame if the id currently maps to an active fetch; otherwise silent no-op (idempotent).
1618
- *
1619
- * Parameter semantics:
1620
- * - requestId: bigint returned from {@link MOQtailClient.fetch}. Numbers auto-converted to bigint.
1621
- *
1622
- * Current behavior / limitations:
1623
- * - Data stream closure after cancel is TODO (objects may still arrive briefly).
1624
- * - Unknown / already finished request: ignored without error.
1625
- * - Only targets FETCH requests (not subscriptions).
1626
- *
1627
- * @throws MOQtailError If client is destroyed.
1628
- * @throws InternalError Failure while sending the cancel (client disconnects first).
1629
- *
1630
- * @remarks
1631
- * Follow-up improvement planned: actively close associated readable stream controller immediately upon acknowledgment.
1632
- *
1633
- * @example Cancel shortly after starting
1634
- * ```ts
1635
- * const r = await client.fetch({ priority: 32, groupOrder: GroupOrder.Original, typeAndProps: { type: FetchType.Standalone, props: { fullTrackName, startLocation, endLocation } } })
1636
- * if (!(r instanceof RequestError)) {
1637
- * // user navigated away
1638
- * await client.fetchCancel(r.requestId)
1639
- * }
1640
- * ```
1641
- *
1642
- * @example Idempotent double cancel
1643
- * ```ts
1644
- * await client.fetchCancel(456n)
1645
- * await client.fetchCancel(456n) // no error
1646
- * ```
1647
- */
1648
- fetchCancel(requestId: bigint | number): Promise<void>;
1649
- /**
1650
- * Proactively push a track to the relay/peer.
1651
- */
1652
- publish(fullTrackName: FullTrackName, forward: boolean, trackAlias: bigint, parameters?: MessageParameter[], trackExtensions?: TrackExtension[]): Promise<RequestError | {
1653
- requestId: bigint;
1654
- trackAlias: bigint;
1655
- }>;
1656
- /**
1657
- * Signals the end of a published track to the peer/relay.
1658
- * * @param publishRequestId - The original requestId used when `publish()` was called.
1659
- */
1660
- publishDone(publishRequestId: bigint | number, statusCode?: number, reasonPhrase?: string): Promise<void>;
1661
- /**
1662
- * Registers an incoming PUBLISH announcement as a valid data receiver.
1663
- * This prepares the client to ingest pushed data streams matching the published alias.
1664
- * * @param msg - The incoming Publish control message
1665
- * @returns - A stream of MoqtObjects being pushed by the publisher
1666
- */
1667
- acceptPushedTrack(msg: Publish): ReadableStream<MoqtObject>;
1668
- /**
1669
- * Declare (publish) a track namespace to the peer so subscribers using matching prefixes (via {@link MOQtailClient.subscribeNamespace})
1670
- * can discover and begin subscribing/fetching its tracks.
1671
- *
1672
- * Typical flow (publisher side):
1673
- * 1. Prepare / register one or more {@link Track} objects locally (see {@link MOQtailClient.addOrUpdateTrack}).
1674
- * 2. Call `publishNamespace(namespace)` once per namespace prefix to expose those tracks.
1675
- * 3. Later, call {@link MOQtailClient.publishNamespaceDone} when no longer publishing under that namespace.
1676
- *
1677
- * Parameter semantics:
1678
- * - trackNamespace: Tuple representing the namespace prefix (e.g. ["camera","main"]). All tracks whose full names start with this tuple are considered within the announce scope.
1679
- * - parameters: Optional {@link MessageParameters}; omitted =\> default instance.
1680
- *
1681
- * Returns: {@link RequestOk} on success (namespace added to `announcedNamespaces`) or {@link RequestError} explaining refusal.
1682
- *
1683
- * Use cases:
1684
- * - Make a camera or sensor namespace available before any objects are pushed.
1685
- * - Dynamically expose a newly created room / session namespace.
1686
- * - Re-announce after reconnect to repopulate discovery state.
1687
- *
1688
- * @throws MOQtailError If client is destroyed.
1689
- * @throws InternalError Transport/control failure while sending or awaiting response (client disconnects first).
1690
- *
1691
- * @remarks
1692
- * - Duplicate announce detection is TODO (currently a second call will still send another PUBLISH_NAMESPACE; receiver behavior may vary).
1693
- * - Successful announces are tracked in `announcedNamespaces`; manual removal occurs via {@link MOQtailClient.publishNamespaceDone}.
1694
- * - Discovery subscribers (those who issued {@link MOQtailClient.subscribeNamespace}) will receive the resulting {@link PublishNamespace} message.
1695
- *
1696
- * @example Minimal announce
1697
- * ```ts
1698
- * const res = await client.publishNamespace(["camera","main"])
1699
- * if (res instanceof RequestOk) {
1700
- * // ready to publish objects under tracks with this namespace prefix
1701
- * }
1702
- * ```
1703
- *
1704
- * @example PublishNamespace with parameters block
1705
- * ```ts
1706
- * const params = new MessageParameters().setSomeExtensionFlag(true)
1707
- * const resp = await client.publishNamespace(["room","1234"], params)
1708
- * ```
1709
- */
1710
- publishNamespace(trackNamespace: Tuple, parameters?: MessageParameter[]): Promise<RequestOk | RequestError>;
1711
- /**
1712
- * Withdraw a previously announced namespace so new subscribers no longer discover its tracks.
1713
- *
1714
- * Use when shutting down publishing for a logical scope (camera offline, room closed, session ended).
1715
- * Removes the namespace from `announcedNamespaces` locally and sends an {@link PublishNamespaceDone} control frame.
1716
- *
1717
- * Parameter semantics:
1718
- * - trackNamespace: Exact tuple used during {@link MOQtailClient.publishNamespace}. Must match to be removed from internal set.
1719
- *
1720
- * Behavior:
1721
- * - Does not delete locally registered {@link Track} objects (they remain in `trackSources`).
1722
- * - Does not forcibly end active subscriptions that were already established; peers simply stop discovering it for new ones.
1723
- * - Silent if the namespace was not currently recorded (idempotent style).
1724
- *
1725
- * @throws MOQtailError If client is destroyed before sending.
1726
- * @throws (rethrows original error) Any lower-level failure while sending results in a disconnect (unwrapped TODO: future wrap with InternalError for consistency).
1727
- *
1728
- * @remarks
1729
- * Peers that issued {@link MOQtailClient.subscribeNamespace} for a matching prefix should receive the resulting {@link PublishNamespaceDone}.
1730
- * Consider calling this before {@link MOQtailClient.disconnect} to give consumers prompt notice.
1731
- *
1732
- * @example Basic usage
1733
- * ```ts
1734
- * await client.publishNamespaceDone(["camera","main"])
1735
- * ```
1736
- *
1737
- * @example Idempotent
1738
- * ```ts
1739
- * await client.publishNamespaceDone(["camera","main"]) // first time
1740
- * await client.publishNamespaceDone(["camera","main"]) // no error, already removed
1741
- * ```
1742
- */
1743
- publishNamespaceDone(trackNamespace: Tuple): Promise<void>;
1744
- /**
1745
- * Send an {@link PublishNamespaceCancel} to abort a previously issued ANNOUNCE before (or after) the peer fully processes it.
1746
- *
1747
- * Use when an announce was sent prematurely (e.g. validation failed locally, namespace no longer needed) and you want
1748
- * to retract it without waiting for normal announce lifecycle or before publishing any objects.
1749
- *
1750
- * Parameter semantics:
1751
- * - msg: Pre-constructed {@link PublishNamespaceCancel} referencing the original announce request id / namespace (builder provided elsewhere).
1752
- *
1753
- * Behavior:
1754
- * - Simply forwards the control frame; does not modify `announcedNamespaces` (call {@link MOQtailClient.publishNamespaceDone} for local bookkeeping removal).
1755
- * - Safe to send even if the announce already succeeded; peer may ignore duplicates per spec guidance.
1756
- *
1757
- * @throws MOQtailError If client is destroyed.
1758
- * @throws InternalError Wrapped transport/control send failure (client disconnects first) then rethrows.
1759
- *
1760
- * @remarks
1761
- * Use in tandem with internal tracking if you want to prevent subsequent object publication until a new announce is issued.
1762
- *
1763
- * @example Cancel immediately after a mistaken announce
1764
- * ```ts
1765
- * const publishNamespaceResp = await client.publishNamespace(["camera","temp"]) // wrong namespace
1766
- * // Assume you kept the original announce requestId (e.g. from PublishNamespaceRequest)
1767
- * const cancelMsg = new PublishNamespaceCancel(publishNamespaceResp.requestId as bigint)
1768
- * await client.publishNamespaceCancel(cancelMsg)
1769
- * ```
1770
- */
1771
- publishNamespaceCancel(msg: PublishNamespaceCancel): Promise<void>;
1772
- subscribeNamespace(trackNamespacePrefix: Tuple, subscribeOptions?: NamespaceSubscribeOptions, parameters?: MessageParameter[]): Promise<{
1773
- response: RequestOk | RequestError;
1774
- cancel: () => Promise<void>;
1775
- }>;
1776
- unsubscribeNamespace(msg: UnsubscribeNamespace): Promise<void>;
1777
- }
1778
-
1779
- /**
1780
- * Copyright 2026 The MOQtail Authors
1781
- *
1782
- * Licensed under the Apache License, Version 2.0 (the "License");
1783
- * you may not use this file except in compliance with the License.
1784
- * You may obtain a copy of the License at
1785
- *
1786
- * http://www.apache.org/licenses/LICENSE-2.0
1787
- *
1788
- * Unless required by applicable law or agreed to in writing, software
1789
- * distributed under the License is distributed on an "AS IS" BASIS,
1790
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1791
- * See the License for the specific language governing permissions and
1792
- * limitations under the License.
1793
- */
1794
-
1795
- declare class TrackStatusRequest implements PromiseLike<RequestOk | RequestError> {
1796
- readonly requestId: bigint;
1797
- readonly message: TrackStatus;
1798
- private _resolve;
1799
- private _reject;
1800
- private promise;
1801
- constructor(msg: TrackStatus);
1802
- resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
1803
- reject(reason?: any): void;
1804
- then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
1805
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
1806
- finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
1051
+ #private;
1052
+ /**
1053
+ * Namespace prefixes (tuples) the peer has requested announce notifications for via SUBSCRIBE_NAMESPACE.
1054
+ * Used to decide which locally issued ANNOUNCE messages should be forwarded (future optimization: prefix trie).
1055
+ */
1056
+ readonly peerSubscribeNamespace: Set<Tuple>;
1057
+ /**
1058
+ * Namespace prefixes this client has subscribed to (issued SUBSCRIBE_NAMESPACE). Enables automatic filtering
1059
+ * of incoming NAMESPACE / NAMESPACE_DONE. Maintained locally; no dedupe of overlapping / shadowing prefixes yet.
1060
+ */
1061
+ readonly subscribedNamespaces: Set<Tuple>;
1062
+ readonly subscribedTracks: Set<Tuple>;
1063
+ /**
1064
+ * Track namespaces this client has successfully published (received REQUEST_OK). Source of truth for
1065
+ * deciding what to withdraw on teardown or targeted removal (future optimization: prefix trie).
1066
+ */
1067
+ readonly publishedNamespaces: Set<Tuple>;
1068
+ /**
1069
+ * Locally registered track definitions keyed by full track name string. Populated via addOrUpdateTrack.
1070
+ * Does not imply the track has been announced or has active publications.
1071
+ */
1072
+ readonly trackSources: Map<string, Track>;
1073
+ /**
1074
+ * All in‑flight request objects keyed by requestId (SUBSCRIBE, FETCH, ANNOUNCE, etc). Facilitates lookup
1075
+ * when responses / data arrive. Entries are removed on completion or error.
1076
+ */
1077
+ readonly requests: Map<bigint, MOQtailRequest>;
1078
+ /**
1079
+ * Active publications (SUBSCRIBE or FETCH) keyed by requestId to manage object stream controllers and lifecycle.
1080
+ * Subset / specialization view of `requests`.
1081
+ */
1082
+ readonly publications: Map<bigint, SubscribePublication | FetchPublication | PublishPublication>;
1083
+ /**
1084
+ * Active SUBSCRIBE request wrappers keyed by track alias for rapid alias -\> subscription resolution during
1085
+ * incoming unidirectional data handling.
1086
+ */
1087
+ readonly subscriptions: Map<bigint, any>;
1088
+ /**
1089
+ * Bidirectional track alias \<-\> subscription requestId mapping
1090
+ */
1091
+ readonly subscriptionAliasMap: Map<bigint, bigint>;
1092
+ /**
1093
+ * Bidirectional requestId \<-\> full track name mapping to reconstruct metadata for incoming objects.
1094
+ */
1095
+ readonly requestIdMap: RequestIdMap;
1096
+ /**
1097
+ * Maps track aliases to full track names for quick resolution during data handling.
1098
+ */
1099
+ readonly aliasFullTrackNameMap: Map<bigint, FullTrackName>;
1100
+ /** Underlying WebTransport session (set after successful construction in MOQtailClient.new). */
1101
+ webTransport: WebTransport;
1102
+ /** Outgoing / incoming control message stream pair. */
1103
+ controlStream: ControlStream;
1104
+ /** Timeout (ms) applied to reading incoming data streams; undefined =\> no explicit timeout. */
1105
+ dataStreamTimeoutMs?: number;
1106
+ /** Timeout (ms) for control stream read operations; undefined =\> no explicit timeout. */
1107
+ controlStreamTimeoutMs?: number;
1108
+ /**
1109
+ * How long (ms) an incoming data stream waits for the control message that establishes
1110
+ * its track alias before the stream is abandoned.
1111
+ */
1112
+ trackAliasResolutionTimeoutMs: number;
1113
+ /**
1114
+ * How long (ms) a track a soft switch handed over from may stay quiet before it is
1115
+ * retired anyway, if no PUBLISH_DONE ends its drain first.
1116
+ */
1117
+ switchDrainTimeoutMs: number;
1118
+ /**
1119
+ * TODO: onNamespaceAnnounced may be a better name
1120
+ * Fired when an PUBLISH_NAMESPACE control message is processed for a track namespace.
1121
+ * Use to update UI or trigger discovery logic.
1122
+ * Discovery event.
1123
+ */
1124
+ onNamespacePublished?: (msg: PublishNamespace) => void;
1125
+ /**
1126
+ * Fired on GOAWAY reception signaling graceful session wind-down.
1127
+ * Use to prepare for disconnect or cleanup.
1128
+ * Lifecycle handler.
1129
+ */
1130
+ onGoaway?: (msg: GoAway) => void;
1131
+ /**
1132
+ * Whether the peer has sent a GOAWAY on the control stream. Once it has, this side
1133
+ * should not start new requests; a second one closes the session with
1134
+ * PROTOCOL_VIOLATION.
1135
+ */
1136
+ goawayReceived: boolean;
1137
+ /**
1138
+ * Fired if the underlying WebTransport session fails (ready -\> closed prematurely).
1139
+ * Use to log or alert on transport errors.
1140
+ * Lifecycle/error handler.
1141
+ */
1142
+ onWebTransportFail?: () => void;
1143
+ /**
1144
+ * Fired exactly once when the client transitions to terminated (disconnect).
1145
+ * Use to clean up resources or notify user.
1146
+ * Lifecycle handler.
1147
+ */
1148
+ onSessionTerminated?: (reason?: unknown) => void;
1149
+ /**
1150
+ * Invoked after each outbound control message is sent.
1151
+ * Use for logging or analytics.
1152
+ * Informational event.
1153
+ */
1154
+ onMessageSent?: (msg: ControlMessage) => void;
1155
+ /**
1156
+ * Invoked upon receiving each inbound control message before handling.
1157
+ * Use for logging or debugging.
1158
+ * Informational event.
1159
+ */
1160
+ onMessageReceived?: (msg: ControlMessage) => void;
1161
+ /**
1162
+ * Invoked for each decoded data object/header arriving on a uni stream (fetch or subgroup).
1163
+ * Use to process or display incoming media/data.
1164
+ * Informational event.
1165
+ */
1166
+ onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1167
+ /**
1168
+ * Invoked after enqueuing each outbound data object/header.
1169
+ * Reserved for future use.
1170
+ * Informational event.
1171
+ */
1172
+ onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1173
+ /**
1174
+ * Invoked for every data stream this client opens or accepts: once for its header, once
1175
+ * per object (identity and payload length only), and once when the stream ends.
1176
+ * Use for counters and diagnostics.
1177
+ * Informational event.
1178
+ */
1179
+ onDataEvent?: DataEventObserver;
1180
+ /**
1181
+ * General-purpose error callback for surfaced exceptions not thrown to caller synchronously.
1182
+ * Use to log or display errors.
1183
+ * Error handler.
1184
+ */
1185
+ onError?: (er: unknown) => void;
1186
+ /** Invoked for each decoded datagram object/status arriving. */
1187
+ onDatagramReceived?: (data: Datagram) => void;
1188
+ /** Invoked after enqueuing each outbound datagram object/status. */
1189
+ onDatagramSent?: (data: Datagram) => void;
1190
+ /** Fired when an inbound PUBLISH control message is received. */
1191
+ onPeerPublish?: (msg: Publish, stream: ReadableStream<MoqtObject>) => void;
1192
+ /**
1193
+ * Fired when an inbound PUBLISH_DONE control message is received. The message names
1194
+ * no request of its own, so `requestId` is the request the stream it arrived on
1195
+ * opened: for a track the peer pushed, the `requestId` of the {@link Publish} handed
1196
+ * to {@link MOQtailClient.onPeerPublish}. It is what says which track just ended.
1197
+ */
1198
+ onPeerPublishDone?: (msg: PublishDone, requestId: bigint) => void;
1199
+ /**
1200
+ * Fired when the peer moves the Forward State of a track this side is publishing,
1201
+ * either in its PUBLISH_OK or in a later REQUEST_UPDATE. `requestId` is the one
1202
+ * {@link MOQtailClient.publish} returned.
1203
+ *
1204
+ * A publication that declared FORWARD=0 sends nothing until this reports `true`, so
1205
+ * this is where the work behind the track starts and stops -- leaving a camera and
1206
+ * an encoder running for a track nobody is taking costs the same as publishing it.
1207
+ */
1208
+ onForwardStateChange?: (requestId: bigint, forward: boolean) => void;
1209
+ /** Fired when an inbound SUBSCRIBE_NAMESPACE control message is received. */
1210
+ onPeerSubscribeNamespace?: (msg: SubscribeNamespace) => void;
1211
+ /**
1212
+ * Fired when an inbound SUBSCRIBE_TRACKS control message is received. The PUBLISH
1213
+ * sent for each matching track:
1214
+ * - states the request's settings as its parameters, from
1215
+ * `MessageParameter.publishParametersFor(msg.parameters)`: FORWARD, GROUP_ORDER and
1216
+ * the LOCATION_FILTER the subscription starts from, but never the request's
1217
+ * AUTHORIZATION_TOKEN;
1218
+ * - goes without Track Properties when
1219
+ * `MessageParameter.includesProperties(msg.parameters)` is false.
1220
+ *
1221
+ * A request carrying FILL_PARAMETERS also asks for a fill of what each track has
1222
+ * already published. This client cannot open a fill for a pushed track, so such a
1223
+ * subscriber gets only the live Objects.
1224
+ */
1225
+ onPeerSubscribeTracks?: (msg: SubscribeTracks) => void;
1226
+ /**
1227
+ * Fired when a PUBLISH_SKIPPED arrives on a {@link MOQtailClient.subscribeTracks}
1228
+ * stream: the peer has a matching track but no bidi stream to send its PUBLISH on
1229
+ * until its stream limit lifts (§10.20). `prefix` is the prefix this side subscribed
1230
+ * with, which is what the message's suffix hangs off.
1231
+ */
1232
+ onPeerPublishSkipped?: (prefix: Tuple, msg: PublishSkipped) => void;
1233
+ /** Fired when a NAMESPACE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
1234
+ onPeerNamespace?: (prefix: Tuple, suffix: Tuple) => void;
1235
+ /** Fired when a NAMESPACE_DONE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
1236
+ onPeerNamespaceDone?: (prefix: Tuple, suffix: Tuple) => void;
1237
+ /**
1238
+ * Stream of all received MoqtObjects from datagrams across all tracks
1239
+ * Consumer should filter by fullTrackName as needed
1240
+ *
1241
+ * WARNING: Only one reader should be active. For multiple subscribers,
1242
+ * use subscribeToTrackDatagrams() instead
1243
+ */
1244
+ readonly receivedDatagramObjects: ReadableStream<MoqtObject>;
1245
+ /**
1246
+ * Generates a safe, sequential local request ID for tracking pushed/incoming tracks.
1247
+ */
1248
+ allocatePseudoRequestId(): bigint;
1249
+ /**
1250
+ * Gets the current server setup configuration.
1251
+ *
1252
+ * @returns The {@link Setup} instance the server sent back during handshake.
1253
+ */
1254
+ get serverSetup(): Setup;
1255
+ /**
1256
+ * How many filter ranges the server allows in one request: its MAX_FILTER_RANGES,
1257
+ * or 0 when it sent none, which allows no Range Filter at all.
1258
+ */
1259
+ /**
1260
+ * How many filter ranges this client allows the server in one request: the
1261
+ * MAX_FILTER_RANGES it advertised, {@link DEFAULT_MAX_FILTER_RANGES} unless the
1262
+ * caller's setup options set one.
1263
+ */
1264
+ get maxFilterRanges(): bigint;
1265
+ /**
1266
+ * How many filter ranges the server allows in one request: its MAX_FILTER_RANGES,
1267
+ * or 0 when it sent none, which allows no Range Filter at all.
1268
+ */
1269
+ get peerMaxFilterRanges(): bigint;
1270
+ /**
1271
+ * Returns true if datagram support is currently active
1272
+ */
1273
+ get isDatagramsEnabled(): boolean;
1274
+ /**
1275
+ * Sets the global log level for all moqtail-ts loggers.
1276
+ * @param level - The minimum {@link LogLevel} to output. Use `LogLevel.NONE` to silence all logs.
1277
+ */
1278
+ static setLogLevel(level: LogLevel): void;
1279
+ /**
1280
+ * Restricts log output to the specified module names. Pass `null` to allow all modules.
1281
+ * @param modules - Array of module name strings, or `null` to enable all modules.
1282
+ */
1283
+ static setLogEnabledModules(modules: string[] | null): void;
1284
+ private constructor();
1285
+ /**
1286
+ * Establishes a new {@link MOQtailClient} session over WebTransport and performs the MOQT setup handshake.
1287
+ *
1288
+ * @param args - {@link MOQtailClientOptions}
1289
+ *
1290
+ * @returns Promise resolving to a ready {@link MOQtailClient} instance.
1291
+ *
1292
+ * @throws :{@link ProtocolViolationError} If the server sends an unexpected or invalid message during setup.
1293
+ *
1294
+ * @example Minimal connection
1295
+ * ```ts
1296
+ * const client = await MOQtailClient.new({
1297
+ * url: 'https://relay.example.com/transport'
1298
+ * });
1299
+ * ```
1300
+ *
1301
+ * @example With callbacks and options
1302
+ * ```ts
1303
+ * const client = await MOQtailClient.new({
1304
+ * url,
1305
+ * setupOptions: new SetupOptions().addPath('/live'),
1306
+ * transportOptions: { congestionControl: 'default' },
1307
+ * dataStreamTimeoutMs: 5000,
1308
+ * controlStreamTimeoutMs: 2000,
1309
+ * trackAliasResolutionTimeoutMs: 2000,
1310
+ * enableDatagrams: true,
1311
+ * callbacks: {
1312
+ * onMessageSent: msg => console.log('Sent:', msg),
1313
+ * onMessageReceived: msg => console.log('Received:', msg),
1314
+ * onSessionTerminated: reason => console.warn('Session ended:', reason),
1315
+ * onDatagramReceived: data => console.log('Datagram:', data),
1316
+ * }
1317
+ * });
1318
+ * ```
1319
+ */
1320
+ static new(args: MOQtailClientOptions): Promise<MOQtailClient>;
1321
+ /**
1322
+ * Start receiving datagrams from the WebTransport connection.
1323
+ * Must be called before datagrams can be received (unless enableDatagrams: true was set in options).
1324
+ *
1325
+ * @throws MOQtailError if client is destroyed or datagrams already started
1326
+ */
1327
+ startDatagrams(): Promise<void>;
1328
+ /**
1329
+ * Stop receiving datagrams and release resources.
1330
+ * Idempotent - safe to call multiple times.
1331
+ */
1332
+ stopDatagrams(): Promise<void>;
1333
+ /**
1334
+ * Subscribe to receive datagrams for a specific track.
1335
+ * Multiple tracks can have separate handlers that run concurrently.
1336
+ *
1337
+ * @param trackAlias - Track alias to subscribe to
1338
+ * @param handler - Function called for each received MoqtObject on this track
1339
+ * @returns Unsubscribe function to remove the handler
1340
+ *
1341
+ * @example
1342
+ * ```ts
1343
+ * const unsubscribe = client.subscribeToTrackDatagrams(trackAlias, (obj) => {
1344
+ * console.log('Received datagram:', obj.payload);
1345
+ * });
1346
+ * // Later: unsubscribe();
1347
+ * ```
1348
+ */
1349
+ subscribeToTrackDatagrams(trackAlias: bigint, handler: (obj: MoqtObject) => void): () => void;
1350
+ /**
1351
+ * Unsubscribe from datagram delivery for a specific track.
1352
+ *
1353
+ * @param trackAlias - Track alias to unsubscribe from
1354
+ */
1355
+ unsubscribeFromTrackDatagrams(trackAlias: bigint): void;
1356
+ /**
1357
+ * Create a datagram sender for a specific track.
1358
+ *
1359
+ * @param trackAlias - Track alias for outgoing datagrams
1360
+ * @returns SendDatagramStream for writing MoqtObjects as datagrams
1361
+ * @throws MOQtailError if datagram writer not initialized (call startDatagrams() first)
1362
+ *
1363
+ * @example
1364
+ * ```ts
1365
+ * const sender = client.createDatagramSender(trackAlias);
1366
+ * await sender.write(moqtObject);
1367
+ * ```
1368
+ */
1369
+ createDatagramSender(trackAlias: bigint): SendDatagramStream;
1370
+ /**
1371
+ * Send a single MoqtObject as a datagram.
1372
+ * Convenience method for one-off datagram sends.
1373
+ *
1374
+ * @param trackAlias - Track alias for this object
1375
+ * @param object - MoqtObject to send
1376
+ * @throws MOQtailError if datagram writer not initialized
1377
+ *
1378
+ * @example
1379
+ * ```ts
1380
+ * await client.sendDatagram(trackAlias, moqtObject);
1381
+ * ```
1382
+ */
1383
+ sendDatagram(trackAlias: bigint, object: MoqtObject): Promise<void>;
1384
+ /**
1385
+ * Sets (or replaces) the client-level default early discard policy for incoming subgroup streams.
1386
+ *
1387
+ * When set, each incoming subgroup QUIC stream is given a deadline of `subgroupReceiveTimeout` ms to
1388
+ * complete. If the stream has not finished within that window it is cancelled — objects already
1389
+ * delivered to the subscription are kept, but no further objects arrive from that stream.
1390
+ *
1391
+ * This is a client-wide default. Individual subscriptions can override it via the `earlyDiscardPolicy`
1392
+ * field in {@link SubscribeOptions}, which takes precedence over this setting.
1393
+ *
1394
+ * The policy takes effect on the next stream accepted after this call. Passing a new config
1395
+ * replaces the previous one. Pass `undefined` to remove the default.
1396
+ *
1397
+ * @example
1398
+ * ```ts
1399
+ * client.setEarlyDiscardPolicy({ subgroupReceiveTimeout: 2000 })
1400
+ * ```
1401
+ */
1402
+ setEarlyDiscardPolicy(config: EarlyDiscardPolicyConfig | undefined): void;
1403
+ /**
1404
+ * Gracefully terminates this {@link MOQtailClient} session and releases underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} resources.
1405
+ *
1406
+ * @param reason - Optional application-level reason (string or error) recorded and wrapped in an {@link InternalError}
1407
+ * passed to the {@link MOQtailClient.onSessionTerminated | onSessionTerminated} callback.
1408
+ *
1409
+ * @returns Promise that resolves once shutdown logic completes. Subsequent calls are safe no-ops.
1410
+ *
1411
+ * @example Basic usage
1412
+ * ```ts
1413
+ * await client.disconnect();
1414
+ * ```
1415
+ *
1416
+ * @example With reason
1417
+ * ```ts
1418
+ * await client.disconnect('user logout');
1419
+ * ```
1420
+ *
1421
+ * @example Idempotent double call
1422
+ * ```ts
1423
+ * await client.disconnect();
1424
+ * await client.disconnect(); // no error
1425
+ * ```
1426
+ *
1427
+ * @example Page unload safety
1428
+ * ```ts
1429
+ * window.addEventListener('beforeunload', () => {
1430
+ * client.disconnect('page unload');
1431
+ * });
1432
+ * ```
1433
+ */
1434
+ disconnect(reason?: unknown): Promise<void>;
1435
+ /**
1436
+ * Registers or updates a {@link Track} definition for local publishing or serving.
1437
+ *
1438
+ * A {@link Track} describes a logical media/data stream, identified by a unique name and namespace.
1439
+ * - If `trackSource.live` is present, the track can be served to subscribers in real-time.
1440
+ * - If `trackSource.past` is present, the track can be fetched for historical data.
1441
+ * - If both are present, the track supports both live and historical access.
1442
+ *
1443
+ * @param track - The {@link Track} instance to add or update. See {@link TrackSource} for live/past source options.
1444
+ * @returns void
1445
+ * @throws : {@link MOQtailError} If the client has been destroyed.
1446
+ *
1447
+ * @example Create a live video track from getUserMedia
1448
+ * ```ts
1449
+ * const stream = await navigator.mediaDevices.getUserMedia({ video: true });
1450
+ * const videoTrack = stream.getVideoTracks()[0];
1451
+ *
1452
+ * // Convert video frames to MoqtObject instances using your chosen scheme (e.g. MSF, CMAF, etc.)
1453
+ * // This part is application-specific and not provided by MOQtail:
1454
+ * const liveReadableStream: ReadableStream<MoqtObject> = ...
1455
+ *
1456
+ * // Register the track for live subscription
1457
+ * client.addOrUpdateTrack({
1458
+ * fullTrackName: { namespace: ["camera"], name: "main" },
1459
+ * trackSource: { live: liveReadableStream },
1460
+ * publisherPriority: 0 // highest priority
1461
+ * });
1462
+ *
1463
+ * // For a hybrid track (live + past):
1464
+ * import { MemoryObjectCache } from './track/object_cache';
1465
+ * const cache = new MemoryObjectCache(); // Caches are not yet fully supported
1466
+ * client.addOrUpdateTrack({
1467
+ * fullTrackName: { namespace: ["camera"], name: "main" },
1468
+ * trackSource: { live: liveReadableStream, past: cache },
1469
+ * publisherPriority: 8
1470
+ * });
1471
+ * ```
1472
+ */
1473
+ addOrUpdateTrack(track: Track): void;
1474
+ /**
1475
+ * Removes a previously registered {@link Track} from this client's local catalog.
1476
+ *
1477
+ * This deletes the in-memory entry inserted via {@link MOQtailClient.addOrUpdateTrack}, so future lookups by its {@link Track.fullTrackName} will fail.
1478
+ * Does **not** automatically:
1479
+ * - Withdraw the namespace announcement (call {@link MOQtailClient.unpublishNamespace} separately if you want to inform peers)
1480
+ * - Cancel active subscriptions or fetches (they continue until normal completion)
1481
+ * - Affect already-sent objects.
1482
+ *
1483
+ * If the track was not present, the call is a silent no-op (idempotent removal).
1484
+ *
1485
+ * @param track - The exact {@link Track} instance (its canonical name is used as the key).
1486
+ * @throws : {@link MOQtailError} If the client has been destroyed.
1487
+ *
1488
+ * @example
1489
+ * ```ts
1490
+ * // Register a track
1491
+ * client.addOrUpdateTrack(track);
1492
+ *
1493
+ * // Later, when no longer publishing:
1494
+ * client.removeTrack(track);
1495
+ *
1496
+ * // Optionally, inform peers that the namespace is no longer available:
1497
+ * await client.unpublishNamespace(track.fullTrackName.namespace);
1498
+ * ```
1499
+ */
1500
+ removeTrack(track: Track): void;
1501
+ /**
1502
+ * Subscribes to a track and returns a stream of {@link MoqtObject}s matching the requested window and relay forwarding mode.
1503
+ *
1504
+ * - `forward: true` tells the relay to forward objects to this subscriber as they arrive.
1505
+ * - `forward: false` means the relay subscribes upstream but buffers objects locally, not forwarding them to you.
1506
+ * - `locationFilter` selects which Objects are delivered; omitted, the subscription is unfiltered. An absolute start in the
1507
+ * future waits for that object.
1508
+ * - A {@link FillParameters} in `parameters` also retrieves Objects already published, on a fill fetch stream.
1509
+ *
1510
+ * The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId`, the `trackAlias` and a `ReadableStream` of {@link MoqtObject}s.
1511
+ * Use the `requestId` for {@link MOQtailClient.unsubscribe} or {@link MOQtailClient.subscribeUpdate}. Use the `stream` to decode and display objects.
1512
+ *
1513
+ * @param args - {@link SubscribeOptions} describing the subscription window and relay forwarding behavior.
1514
+ * @returns Either a {@link RequestError} or `{ requestId, trackAlias, stream }` for consuming objects.
1515
+ * @throws : {@link MOQtailError} If the client is destroyed.
1516
+ * @throws : {@link ProtocolViolationError} If required fields are missing or inconsistent.
1517
+ * @throws : {@link InvalidFilterError} If the Range Filters exceed the server's MAX_FILTER_RANGES; nothing is sent.
1518
+ * @throws : {@link InternalError} On transport/protocol failure (disconnect is triggered before rethrow).
1519
+ *
1520
+ * @example Subscribe to the latest object and receive future objects as they arrive
1521
+ * ```ts
1522
+ * const result = await client.subscribe({
1523
+ * fullTrackName,
1524
+ * locationFilter: new LocationFilter(LocationFilterType.NextObject),
1525
+ * forward: true,
1526
+ * groupOrder: GroupOrder.Original,
1527
+ * priority: 32
1528
+ * });
1529
+ * if (!(result instanceof RequestError)) {
1530
+ * for await (const obj of result.stream) {
1531
+ * // decode and display obj
1532
+ * }
1533
+ * }
1534
+ * ```
1535
+ *
1536
+ * @example Subscribe to a future range of groups (waits for those objects to arrive)
1537
+ * ```ts
1538
+ * const result = await client.subscribe({
1539
+ * fullTrackName,
1540
+ * locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, startGroup, 0n, endGroup),
1541
+ * forward: true,
1542
+ * groupOrder: GroupOrder.Original,
1543
+ * priority: 128
1544
+ * });
1545
+ * ```
1546
+ */
1547
+ subscribe(args: SubscribeOptions): Promise<RequestError | {
1548
+ requestId: bigint;
1549
+ trackAlias: bigint;
1550
+ stream: ReadableStream<MoqtObject>;
1551
+ }>;
1552
+ /**
1553
+ * Stops an active subscription identified by its original SUBSCRIBE `requestId`.
1554
+ *
1555
+ * Resets the subscription's request stream with `CANCELLED` if it is still active. If the id is unknown or already
1556
+ * cleaned up, the call is a silent no-op (hence multiple calls are idempotent).
1557
+ *
1558
+ * Use this when you no longer want incoming objects for a track (e.g. user navigated away, switching quality).
1559
+ * Canceling the consumer stream reader does **not** auto-unsubscribe; call this explicitly for prompt cleanup.
1560
+ *
1561
+ * @param requestId - The id returned from {@link MOQtailClient.subscribe}.
1562
+ * @returns Promise that resolves once the request stream has been reset.
1563
+ * @throws :{@link MOQtailError} If the client is destroyed.
1564
+ * @throws :{@link InternalError} Wrapped lower-level failure while attempting to send (session will be disconnected first).
1565
+ *
1566
+ * @remarks
1567
+ * - Only targets SUBSCRIBE requests, not fetches. Passing a fetch request id is ignored (no-op).
1568
+ * - Safe to call multiple times; extra calls have no effect.
1569
+ *
1570
+ * @example Subscribe and later unsubscribe
1571
+ * ```ts
1572
+ * const sub = await client.subscribe({ fullTrackName, locationFilter: new LocationFilter(LocationFilterType.NextObject), forward: true, groupOrder: GroupOrder.Original, priority: 0 });
1573
+ * if (!(sub instanceof RequestError)) {
1574
+ * // ...consume objects...
1575
+ * await client.unsubscribe(sub.requestId);
1576
+ * }
1577
+ * ```
1578
+ *
1579
+ * @example Idempotent usage
1580
+ * ```ts
1581
+ * await client.unsubscribe(123n);
1582
+ * await client.unsubscribe(123n); // no error
1583
+ * ```
1584
+ */
1585
+ unsubscribe(requestId: bigint | number): Promise<void>;
1586
+ /**
1587
+ * Narrows or updates an active subscription window and/or relay forwarding behavior.
1588
+ *
1589
+ * Use this to:
1590
+ * - Move the start of the subscription forward (trim history or future window).
1591
+ * - Move the end group earlier (shorten the window).
1592
+ * - Change relay forwarding (`forward: false` stops forwarding new objects, `true` resumes).
1593
+ * - Adjust subscriber priority.
1594
+ *
1595
+ * Only narrowing is allowed: you cannot move the start earlier or the end group later than the original subscription.
1596
+ * Forwarding and priority can be changed at any time.
1597
+ *
1598
+ * @param args - {@link SubscribeUpdateOptions} referencing the original subscription `requestId` and new bounds.
1599
+ * @returns Promise that resolves when the update control frame is sent.
1600
+ * @throws :{@link MOQtailError} If the client is destroyed.
1601
+ * @throws :{@link ProtocolViolationError} If the update would widen the window (earlier start, later end group, or invalid ordering).
1602
+ * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
1603
+ *
1604
+ * @remarks
1605
+ * - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
1606
+ * - Omitting a parameter (e.g. `priority`) leaves the previous value unchanged.
1607
+ * - Setting `forward: false` stops relay forwarding new objects after the current window drains.
1608
+ * - Safe to call multiple times; extra calls with unchanged bounds have no effect.
1609
+ *
1610
+ * @example Trim start forward
1611
+ * ```ts
1612
+ * await client.subscribeUpdate({ subscriptionRequestId, locationFilter: new LocationFilter(LocationFilterType.AbsoluteStart, laterGroup, 0n), forward: true, priority });
1613
+ * ```
1614
+ *
1615
+ * @example Convert tailing subscription into bounded slice
1616
+ * ```ts
1617
+ * await client.subscribeUpdate({ subscriptionRequestId, locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, startGroup, 0n, cutoffGroup), forward: false, priority });
1618
+ * ```
1619
+ *
1620
+ * @example Lower priority only
1621
+ * ```ts
1622
+ * await client.subscribeUpdate({ subscriptionRequestId, forward: true, priority: 200 });
1623
+ * ```
1624
+ */
1625
+ subscribeUpdate(args: SubscribeUpdateOptions): Promise<void>;
1626
+ /**
1627
+ * Switches an active subscription to a different track while retaining the same subscription's
1628
+ * output stream.
1629
+ *
1630
+ * Sends a fresh SUBSCRIBE carrying a SwitchFrom parameter referencing `switchFromRequestId`. A soft
1631
+ * switch may keep delivering objects from the old track for a while after SUBSCRIBE_OK, and this can
1632
+ * be called again before the previous target has produced anything; only the first object actually
1633
+ * delivered by the newest switch target retires everything older.
1634
+ *
1635
+ * @param args - {@link SwitchOptions} referencing the subscription to switch from and the new subscription options.
1636
+ * @returns Either a {@link RequestError} (refusal) or `{ requestId, stream }`, where `stream` is the
1637
+ * same {@link https://developer.mozilla.org/docs/Web/API/ReadableStream | ReadableStream} object returned by the original `subscribe()` call.
1638
+ * @throws :{@link MOQtailError} If the client is destroyed.
1639
+ * @throws :{@link ProtocolViolationError} If `switchFromRequestId` does not name an active subscription.
1640
+ * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
1641
+ *
1642
+ * @example Switch to a different track
1643
+ * ```ts
1644
+ * await client.switch({
1645
+ * switchFromRequestId,
1646
+ * switchMode: SwitchMode.Soft,
1647
+ * newSubscribeOptions: { fullTrackName: newTrackName, priority: 0, groupOrder: GroupOrder.Original, forward: true, locationFilter: new LocationFilter(LocationFilterType.NextObject) },
1648
+ * onDrainDecision: (request) => true
1649
+ * });
1650
+ * ```
1651
+ */
1652
+ switch(args: SwitchOptions): Promise<RequestError | {
1653
+ requestId: bigint;
1654
+ stream: ReadableStream<MoqtObject>;
1655
+ }>;
1656
+ /**
1657
+ * Ends a subscription whose publisher has said how many streams it opened and has
1658
+ * now delivered all of them, and reports whether that happened.
1659
+ *
1660
+ * Both halves of that arrive on their own: a PUBLISH_DONE carries the count, and
1661
+ * the streams finish whenever they finish. Either can be last, so this is checked
1662
+ * from both -- a drained switch target has usually finished its streams well
1663
+ * before the PUBLISH_DONE that ends it.
1664
+ */
1665
+ completeSubscription(request: SubscribeRequest, force?: boolean): boolean;
1666
+ /**
1667
+ * One-shot retrieval of a bounded object span, optionally anchored to an existing subscription, returning a stream of {@link MoqtObject}s.
1668
+ *
1669
+ * Choose a fetch type via `typeAndProps.type`:
1670
+ * - Standalone: Historical slice of a specific {@link FullTrackName} independent of active subscriptions.
1671
+ * - Relative: Range relative to the JOINING subscription's current (largest) location; use when you want "N groups back" from live.
1672
+ * - Absolute: Absolute group/object offsets tied to an existing subscription (stable anchor) even if that subscription keeps forwarding.
1673
+ *
1674
+ * Field highlights (in {@link FetchOptions}):
1675
+ * - priority: 0 (highest) .. 255 (lowest); out-of-range rejected; non-integers rounded by caller expectation.
1676
+ * - groupOrder: {@link (GroupOrder:enum).Original} to preserve publisher order; or reorder ascending/descending if supported by server.
1677
+ * - typeAndProps: Discriminated union carrying parameters specific to each fetch mode (see examples).
1678
+ * - parameters: Optional version-specific extension block.
1679
+ *
1680
+ * Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, stream }` whose `stream`
1681
+ * ends naturally after the bounded range completes (no explicit cancel needed for normal completion).
1682
+ *
1683
+ * Use cases:
1684
+ * - Grab a historical window for scrubbing UI while a separate live subscription tails.
1685
+ * - Late joiner fetching a short back-buffer then discarding the stream.
1686
+ * - Analytics batch job pulling a fixed slice without subscribing long-term.
1687
+ *
1688
+ * @throws MOQtailError If client is destroyed.
1689
+ * @throws ProtocolViolationError Priority out of [0-255] or missing/invalid joining subscription id for Relative/Absolute.
1690
+ * @throws InternalError Transport/control failure (the client disconnects first) then rethrows original error.
1691
+ *
1692
+ * @remarks
1693
+ * - Relative / Absolute require an existing active SUBSCRIBE `joiningRequestId`; if not found a {@link ProtocolViolationError} is thrown.
1694
+ * - Result stream is finite; reader close occurs automatically when last object delivered.
1695
+ * - Use {@link MOQtailClient.fetchCancel} only for early termination (not yet fully implemented: see TODO in code).
1696
+ *
1697
+ * @example Groups 10 through 12, inclusive
1698
+ * ```ts
1699
+ * const r = await client.fetch({
1700
+ * fullTrackName,
1701
+ * priority: 64,
1702
+ * groupOrder: GroupOrder.Original,
1703
+ * locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, 10n, 0n, 12n)
1704
+ * })
1705
+ * if (!(r instanceof RequestError)) {
1706
+ * for await (const obj of r.stream as any) {
1707
+ * // consume objects then stream ends automatically
1708
+ * }
1709
+ * }
1710
+ * ```
1711
+ *
1712
+ * @example The last 5 groups, counting the current one
1713
+ * ```ts
1714
+ * const slice = await client.fetch({
1715
+ * fullTrackName,
1716
+ * priority: 32,
1717
+ * groupOrder: GroupOrder.Original,
1718
+ * locationFilter: new LocationFilter(LocationFilterType.RelativeStart, 5n)
1719
+ * })
1720
+ * ```
1721
+ */
1722
+ fetch(args: FetchOptions): Promise<RequestError | {
1723
+ requestId: bigint;
1724
+ stream: ReadableStream<MoqtObject>;
1725
+ }>;
1726
+ /**
1727
+ * Request early termination of an in‑flight FETCH identified by its `requestId`.
1728
+ *
1729
+ * Use when the consumer no longer needs the remaining objects (user scrubbed away, UI panel closed, replaced by a new fetch).
1730
+ * Resets the fetch's request stream with `CANCELLED` if the id currently maps to an active fetch; otherwise silent no-op (idempotent).
1731
+ *
1732
+ * Parameter semantics:
1733
+ * - requestId: bigint returned from {@link MOQtailClient.fetch}. Numbers auto-converted to bigint.
1734
+ *
1735
+ * Current behavior / limitations:
1736
+ * - Data stream closure after cancel is TODO (objects may still arrive briefly).
1737
+ * - Unknown / already finished request: ignored without error.
1738
+ * - Only targets FETCH requests (not subscriptions).
1739
+ *
1740
+ * @throws MOQtailError If client is destroyed.
1741
+ * @throws InternalError Failure while sending the cancel (client disconnects first).
1742
+ *
1743
+ * @remarks
1744
+ * Follow-up improvement planned: actively close associated readable stream controller immediately upon acknowledgment.
1745
+ *
1746
+ * @example Cancel shortly after starting
1747
+ * ```ts
1748
+ * const r = await client.fetch({ fullTrackName, priority: 32, groupOrder: GroupOrder.Original, locationFilter })
1749
+ * if (!(r instanceof RequestError)) {
1750
+ * // user navigated away
1751
+ * await client.fetchCancel(r.requestId)
1752
+ * }
1753
+ * ```
1754
+ *
1755
+ * @example Idempotent double cancel
1756
+ * ```ts
1757
+ * await client.fetchCancel(456n)
1758
+ * await client.fetchCancel(456n) // no error
1759
+ * ```
1760
+ */
1761
+ fetchCancel(requestId: bigint | number): Promise<void>;
1762
+ /**
1763
+ * Proactively push a track to the relay/peer.
1764
+ */
1765
+ publish(fullTrackName: FullTrackName, forward: boolean, trackAlias: bigint, parameters?: MessageParameter[], trackProperties?: TrackProperty[]): Promise<RequestError | {
1766
+ requestId: bigint;
1767
+ trackAlias: bigint;
1768
+ }>;
1769
+ /**
1770
+ * Signals the end of a published track to the peer/relay.
1771
+ * * @param publishRequestId - The original requestId used when `publish()` was called.
1772
+ */
1773
+ publishDone(publishRequestId: bigint | number, statusCode?: number, reasonPhrase?: string): Promise<void>;
1774
+ /**
1775
+ * Registers an incoming PUBLISH announcement as a valid data receiver.
1776
+ * This prepares the client to ingest pushed data streams matching the published alias.
1777
+ * * @param msg - The incoming Publish control message
1778
+ * @returns - A stream of MoqtObjects being pushed by the publisher
1779
+ */
1780
+ acceptPushedTrack(msg: Publish): ReadableStream<MoqtObject>;
1781
+ /**
1782
+ * Declare (publish) a track namespace to the peer so subscribers using matching prefixes (via {@link MOQtailClient.subscribeNamespace})
1783
+ * can discover and begin subscribing/fetching its tracks.
1784
+ *
1785
+ * Typical flow (publisher side):
1786
+ * 1. Prepare / register one or more {@link Track} objects locally (see {@link MOQtailClient.addOrUpdateTrack}).
1787
+ * 2. Call `publishNamespace(namespace)` once per namespace prefix to expose those tracks.
1788
+ * 3. Later, call {@link MOQtailClient.unpublishNamespace} when no longer publishing under that namespace.
1789
+ *
1790
+ * Parameter semantics:
1791
+ * - trackNamespace: Tuple representing the namespace prefix (e.g. ["camera","main"]). All tracks whose full names start with this tuple are considered within the announce scope.
1792
+ * - parameters: Optional {@link MessageParameters}; omitted =\> default instance.
1793
+ *
1794
+ * Returns: {@link RequestOk} on success (namespace added to `publishedNamespaces`) or {@link RequestError} explaining refusal.
1795
+ *
1796
+ * Use cases:
1797
+ * - Make a camera or sensor namespace available before any objects are pushed.
1798
+ * - Dynamically expose a newly created room / session namespace.
1799
+ * - Re-announce after reconnect to repopulate discovery state.
1800
+ *
1801
+ * @throws MOQtailError If client is destroyed.
1802
+ * @throws InternalError Transport/control failure while sending or awaiting response (client disconnects first).
1803
+ *
1804
+ * @remarks
1805
+ * - Duplicate announce detection is TODO (currently a second call will still send another PUBLISH_NAMESPACE; receiver behavior may vary).
1806
+ * - Successful announces are tracked in `publishedNamespaces`; manual removal occurs via {@link MOQtailClient.unpublishNamespace}.
1807
+ * - Discovery subscribers (those who issued {@link MOQtailClient.subscribeNamespace}) will receive the resulting {@link PublishNamespace} message.
1808
+ *
1809
+ * @example Minimal announce
1810
+ * ```ts
1811
+ * const res = await client.publishNamespace(["camera","main"])
1812
+ * if (res instanceof RequestOk) {
1813
+ * // ready to publish objects under tracks with this namespace prefix
1814
+ * }
1815
+ * ```
1816
+ *
1817
+ * @example PublishNamespace with parameters block
1818
+ * ```ts
1819
+ * const params = new MessageParameters().setSomeExtensionFlag(true)
1820
+ * const resp = await client.publishNamespace(["room","1234"], params)
1821
+ * ```
1822
+ */
1823
+ publishNamespace(trackNamespace: Tuple, parameters?: MessageParameter[]): Promise<RequestError | RequestOk>;
1824
+ /**
1825
+ * Withdraw a previously announced namespace so new subscribers no longer discover its tracks.
1826
+ *
1827
+ * Use when shutting down publishing for a logical scope (camera offline, room closed, session ended).
1828
+ * Removes the namespace from `publishedNamespaces` locally and closes the stream its PUBLISH_NAMESPACE opened,
1829
+ * which is what withdraws the announcement (§3.3.2). This is also how an announce is retracted before the peer
1830
+ * has finished processing it.
1831
+ *
1832
+ * Parameter semantics:
1833
+ * - trackNamespace: Exact tuple used during {@link MOQtailClient.publishNamespace}. Must match to be removed from internal set.
1834
+ *
1835
+ * Behavior:
1836
+ * - Does not delete locally registered {@link Track} objects (they remain in `trackSources`).
1837
+ * - Does not forcibly end active subscriptions that were already established; peers simply stop discovering it for new ones.
1838
+ * - Silent if the namespace was not currently recorded (idempotent style).
1839
+ *
1840
+ * @throws MOQtailError If client is destroyed before sending.
1841
+ * @throws (rethrows original error) Any lower-level failure while sending results in a disconnect (unwrapped TODO: future wrap with InternalError for consistency).
1842
+ *
1843
+ * @remarks
1844
+ * Peers that issued {@link MOQtailClient.subscribeNamespace} for a matching prefix should receive the resulting NAMESPACE_DONE.
1845
+ * Consider calling this before {@link MOQtailClient.disconnect} to give consumers prompt notice.
1846
+ *
1847
+ * @example Basic usage
1848
+ * ```ts
1849
+ * await client.unpublishNamespace(["camera","main"])
1850
+ * ```
1851
+ *
1852
+ * @example Idempotent
1853
+ * ```ts
1854
+ * await client.unpublishNamespace(["camera","main"]) // first time
1855
+ * await client.unpublishNamespace(["camera","main"]) // no error, already removed
1856
+ * ```
1857
+ */
1858
+ unpublishNamespace(trackNamespace: Tuple): Promise<void>;
1859
+ /**
1860
+ * Subscribes to namespace announcements under a prefix (§10.18). Discovery only: the
1861
+ * peer answers NAMESPACE and NAMESPACE_DONE for matching namespaces, and nothing is
1862
+ * subscribed to. To be sent the tracks themselves, use
1863
+ * {@link MOQtailClient.subscribeTracks}.
1864
+ */
1865
+ subscribeNamespace(trackNamespacePrefix: Tuple, parameters?: MessageParameter[]): Promise<{
1866
+ response: RequestOk | RequestError;
1867
+ cancel: () => Promise<void>;
1868
+ }>;
1869
+ subscribeTracks(trackNamespacePrefix: Tuple, parameters?: MessageParameter[]): Promise<{
1870
+ response: RequestOk | RequestError;
1871
+ cancel: () => Promise<void>;
1872
+ }>;
1873
+ /**
1874
+ * Ends a prefix subscription started with {@link MOQtailClient.subscribeNamespace}.
1875
+ *
1876
+ * @param trackNamespacePrefix - The prefix that subscription was opened with.
1877
+ */
1878
+ unsubscribeNamespace(trackNamespacePrefix: Tuple): Promise<void>;
1879
+ /**
1880
+ * Asks the peer for the current status of a track.
1881
+ *
1882
+ * TRACK_STATUS is the seventh `First`-marked type: it opens its own bidi stream and
1883
+ * the REQUEST_OK answering it comes back there, after which the stream is closed.
1884
+ *
1885
+ * @param fullTrackName - The track to report on.
1886
+ * @param trackAlias - Alias to carry in the request.
1887
+ * @param parameters - Optional message parameters.
1888
+ * @returns A {@link RequestOk} on success or a {@link RequestError} on refusal.
1889
+ *
1890
+ * @example
1891
+ * ```ts
1892
+ * const status = await client.trackStatus(fullTrackName, trackAlias)
1893
+ * if (!(status instanceof RequestError)) {
1894
+ * // track exists
1895
+ * }
1896
+ * ```
1897
+ */
1898
+ trackStatus(fullTrackName: FullTrackName, trackAlias: bigint, parameters?: MessageParameter[]): Promise<RequestOk | RequestError>;
1899
+ /**
1900
+ * Opens a bidi request stream for `first` and starts reading responses off it.
1901
+ *
1902
+ * @param requestId - The requestId carried by `first`; the key the stream is filed under.
1903
+ */
1904
+ /**
1905
+ * Hands a data stream {@link MOQtailClient.onDataEvent}, read at call time so an observer assigned
1906
+ * after connecting still sees streams that are already open.
1907
+ *
1908
+ * @internal
1909
+ */
1910
+ dataStreamObserver(fullTrackNameOf?: DataStreamObserver['fullTrackNameOf']): DataStreamObserver;
1911
+ /**
1912
+ * Re-issues one request on a fresh stream after the peer sent a GOAWAY on its request
1913
+ * stream (§10.4). Only that request moves: the session, and every other request on it,
1914
+ * are left alone.
1915
+ *
1916
+ * The re-issued request consumes a new Request ID (§10.1), so the opening message is
1917
+ * re-stamped with it. The id the caller holds keeps naming the request; only the id on
1918
+ * the wire changes.
1919
+ *
1920
+ * @returns True if the request was re-issued here. A GOAWAY naming a new session URI
1921
+ * is not: opening a session is the application's call, so it is surfaced through
1922
+ * {@link MOQtailClient.onGoaway} and the request stream is closed.
1923
+ *
1924
+ * @internal
1925
+ */
1926
+ migrateRequest(requestId: bigint, goAway: GoAway): Promise<boolean>;
1807
1927
  }
1808
-
1809
- /**
1810
- * Copyright 2025 The MOQtail Authors
1811
- *
1812
- * Licensed under the Apache License, Version 2.0 (the "License");
1813
- * you may not use this file except in compliance with the License.
1814
- * You may obtain a copy of the License at
1815
- *
1816
- * http://www.apache.org/licenses/LICENSE-2.0
1817
- *
1818
- * Unless required by applicable law or agreed to in writing, software
1819
- * distributed under the License is distributed on an "AS IS" BASIS,
1820
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1821
- * See the License for the specific language governing permissions and
1822
- * limitations under the License.
1823
- */
1824
-
1928
+ //#endregion
1929
+ //#region src/client/data_stream.d.ts
1825
1930
  declare class SendStream {
1826
- #private;
1827
- readonly header: Header;
1828
- readonly onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1829
- private constructor();
1830
- static new(writeStream: WritableStream<Uint8Array>, header: Header, onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void): Promise<SendStream>;
1831
- write(object: FetchObject | SubgroupObject): Promise<void>;
1832
- close(): Promise<void>;
1931
+ #private;
1932
+ readonly header: Header;
1933
+ readonly onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1934
+ private constructor();
1935
+ /** @param observer - Receives a {@link DataEvent} for the header, each object, and the stream's end. */
1936
+ static new(writeStream: WritableStream<Uint8Array>, header: Header, onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void, groupOrder?: GroupOrder, observer?: DataStreamObserver): Promise<SendStream>;
1937
+ write(object: FetchObject | SubgroupObject): Promise<void>;
1938
+ close(): Promise<void>;
1939
+ /** Abruptly tears the stream down, so the peer reads back `code` (§3.3.3). */
1940
+ reset(code: StreamResetCode): Promise<void>;
1833
1941
  }
1834
1942
  declare class RecvStream {
1835
- #private;
1836
- readonly header: Header;
1837
- readonly stream: ReadableStream<FetchObject | SubgroupObject>;
1838
- readonly onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1839
- private constructor();
1840
- static new(readStream: ReadableStream<Uint8Array>, partialDataTimeout?: number, onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void): Promise<RecvStream>;
1943
+ #private;
1944
+ readonly header: Header;
1945
+ readonly stream: ReadableStream<FetchObject | SubgroupObject>;
1946
+ readonly onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1947
+ private constructor();
1948
+ /**
1949
+ * @param resolveGroupOrder - Consulted once the FETCH header names its request, since
1950
+ * Group ID deltas on the stream are signed by the Group Order the request negotiated.
1951
+ * @param observer - Receives a {@link DataEvent} for the header, each object, and the stream's end.
1952
+ */
1953
+ static new(readStream: ReadableStream<Uint8Array>, partialDataTimeout?: number, onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void, resolveGroupOrder?: (header: Header) => GroupOrder, observer?: DataStreamObserver): Promise<RecvStream>;
1954
+ /** Asks the peer to stop sending on this stream, reporting `code` (§3.3.3). */
1955
+ stopSending(code: StreamResetCode): Promise<void>;
1841
1956
  }
1842
-
1843
- export { ControlStream, type EarlyDiscardPolicyConfig, type FetchOptions, FetchPublication, FetchRequest, HybridTrackSource, type LiveObjectSource, LiveTrackSource, MOQtailClient, type MOQtailClientOptions, type MOQtailRequest, MemoryObjectCache, type ObjectCache, type PastObjectSource, PublishNamespaceRequest, PublishPublication, PublishRequest, RecvDatagramStream, RecvStream, RingBufferObjectCache, SendDatagramStream, SendStream, StaticTrackSource, SubscribeNamespaceRequest, type SubscribeOptions, SubscribePublication, SubscribeRequest, type SubscribeUpdateOptions, type SwitchOptions, type Track, type TrackSource, TrackStatusRequest };
1957
+ //#endregion
1958
+ export { ControlRecvStream, ControlSendStream, ControlStream, DEFAULT_MAX_FILTER_RANGES, DEFAULT_SWITCH_DRAIN_TIMEOUT_MS, DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS, DataDirection, DataEvent, DataEventBase, DataEventObserver, DataHeaderEvent, DataObjectEvent, DataStreamEndEvent, DataStreamObserver, DataStreamReporter, EarlyDiscardPolicyConfig, FetchOptions, FetchPublication, FetchRequest, HybridTrackSource, LiveObjectSource, LiveTrackSource, MOQtailClient, MOQtailClientOptions, MOQtailRequest, MemoryObjectCache, ObjectCache, PastObjectSource, PublishNamespaceRequest, PublishPublication, PublishRequest, RecvDatagramStream, RecvStream, RequestStream, RequestStreamHooks, RingBufferObjectCache, SendDatagramStream, SendStream, StaticTrackSource, SubscribeNamespaceRequest, SubscribeOptions, SubscribePublication, SubscribeRequest, SubscribeUpdateOptions, Subscription, SwitchOptions, Track, TrackAliasHolder, TrackSource, TrackStatusRequest };