@caprid/relay 0.0.0 → 0.1.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.
Files changed (103) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +160 -1
  3. package/dist/connect-session.d.ts +125 -0
  4. package/dist/connect-session.d.ts.map +1 -0
  5. package/dist/connect-session.js +300 -0
  6. package/dist/connect-session.js.map +1 -0
  7. package/dist/connect.d.ts +143 -0
  8. package/dist/connect.d.ts.map +1 -0
  9. package/dist/connect.js +129 -0
  10. package/dist/connect.js.map +1 -0
  11. package/dist/delivery-timeouts.d.ts +37 -0
  12. package/dist/delivery-timeouts.d.ts.map +1 -0
  13. package/dist/delivery-timeouts.js +48 -0
  14. package/dist/delivery-timeouts.js.map +1 -0
  15. package/dist/document-service.d.ts +58 -0
  16. package/dist/document-service.d.ts.map +1 -0
  17. package/dist/document-service.js +166 -0
  18. package/dist/document-service.js.map +1 -0
  19. package/dist/errors.d.ts +71 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/errors.js +99 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/frame-reader.d.ts +81 -0
  24. package/dist/frame-reader.d.ts.map +1 -0
  25. package/dist/frame-reader.js +110 -0
  26. package/dist/frame-reader.js.map +1 -0
  27. package/dist/frame-writer.d.ts +109 -0
  28. package/dist/frame-writer.d.ts.map +1 -0
  29. package/dist/frame-writer.js +409 -0
  30. package/dist/frame-writer.js.map +1 -0
  31. package/dist/index.d.ts +19 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +9 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/media-track-properties.d.ts +59 -0
  36. package/dist/media-track-properties.d.ts.map +1 -0
  37. package/dist/media-track-properties.js +120 -0
  38. package/dist/media-track-properties.js.map +1 -0
  39. package/dist/media.d.ts +28 -0
  40. package/dist/media.d.ts.map +1 -0
  41. package/dist/media.js +28 -0
  42. package/dist/media.js.map +1 -0
  43. package/dist/namespace-events.d.ts +44 -0
  44. package/dist/namespace-events.d.ts.map +1 -0
  45. package/dist/namespace-events.js +107 -0
  46. package/dist/namespace-events.js.map +1 -0
  47. package/dist/node.d.ts +75 -0
  48. package/dist/node.d.ts.map +1 -0
  49. package/dist/node.js +114 -0
  50. package/dist/node.js.map +1 -0
  51. package/dist/payload.d.ts +8 -0
  52. package/dist/payload.d.ts.map +1 -0
  53. package/dist/payload.js +23 -0
  54. package/dist/payload.js.map +1 -0
  55. package/dist/publish.d.ts +209 -0
  56. package/dist/publish.d.ts.map +1 -0
  57. package/dist/publish.js +123 -0
  58. package/dist/publish.js.map +1 -0
  59. package/dist/room-endpoint.d.ts +21 -0
  60. package/dist/room-endpoint.d.ts.map +1 -0
  61. package/dist/room-endpoint.js +47 -0
  62. package/dist/room-endpoint.js.map +1 -0
  63. package/dist/send-order.d.ts +14 -0
  64. package/dist/send-order.d.ts.map +1 -0
  65. package/dist/send-order.js +11 -0
  66. package/dist/send-order.js.map +1 -0
  67. package/dist/settling-groups.d.ts +35 -0
  68. package/dist/settling-groups.d.ts.map +1 -0
  69. package/dist/settling-groups.js +73 -0
  70. package/dist/settling-groups.js.map +1 -0
  71. package/dist/subscription-events.d.ts +51 -0
  72. package/dist/subscription-events.d.ts.map +1 -0
  73. package/dist/subscription-events.js +125 -0
  74. package/dist/subscription-events.js.map +1 -0
  75. package/dist/subscription.d.ts +207 -0
  76. package/dist/subscription.d.ts.map +1 -0
  77. package/dist/subscription.js +283 -0
  78. package/dist/subscription.js.map +1 -0
  79. package/dist/supervised-publisher.d.ts +92 -0
  80. package/dist/supervised-publisher.d.ts.map +1 -0
  81. package/dist/supervised-publisher.js +839 -0
  82. package/dist/supervised-publisher.js.map +1 -0
  83. package/dist/supervised-subscriber.d.ts +201 -0
  84. package/dist/supervised-subscriber.d.ts.map +1 -0
  85. package/dist/supervised-subscriber.js +1420 -0
  86. package/dist/supervised-subscriber.js.map +1 -0
  87. package/dist/supervision.d.ts +78 -0
  88. package/dist/supervision.d.ts.map +1 -0
  89. package/dist/supervision.js +149 -0
  90. package/dist/supervision.js.map +1 -0
  91. package/dist/switchable.d.ts +164 -0
  92. package/dist/switchable.d.ts.map +1 -0
  93. package/dist/switchable.js +327 -0
  94. package/dist/switchable.js.map +1 -0
  95. package/dist/validation.d.ts +64 -0
  96. package/dist/validation.d.ts.map +1 -0
  97. package/dist/validation.js +137 -0
  98. package/dist/validation.js.map +1 -0
  99. package/dist/write-slot.d.ts +87 -0
  100. package/dist/write-slot.d.ts.map +1 -0
  101. package/dist/write-slot.js +519 -0
  102. package/dist/write-slot.js.map +1 -0
  103. package/package.json +82 -4
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,162 @@
1
1
  # @caprid/relay
2
2
 
3
- Placeholder so the name can be set up for trusted publishing. Install 0.1.0 or later.
3
+ The Relay TypeScript SDK. `connectRelaySubscriber` subscribes to track objects and
4
+ `connectRelayPublisher` publishes them, through Relay, Mux's Media over QUIC (MoQ) relay service.
5
+ Payloads are bytes the SDK does not interpret; no player, media catalog, or Video.js is needed.
6
+
7
+ ## Requirements
8
+
9
+ - Browser WebTransport in a secure context (HTTPS or localhost). This is the default transport.
10
+ It needs WebTransport protocol negotiation, which the live tests verify against the Relay in
11
+ Chromium and in Firefox 155 or later (Playwright's builds). WebKit cannot open a WebTransport
12
+ session to the Relay yet.
13
+ - Node 24+: import from `@caprid/relay/node`, which connects over native QUIC through
14
+ `@caprid/relay-quic` ([Node](#node)). Other runtimes must pass a compatible `createTransport`
15
+ factory.
16
+ - Where UDP is blocked, or the browser has no usable WebTransport (Safari): pass
17
+ [`@caprid/relay-websocket`](packages/relay-websocket/README.md)'s `withWebSocketFallback()` or
18
+ `createWebSocketTransport()` as `createTransport` to connect over QMux over WebSocket on TCP 443
19
+ ([networks without UDP](GUIDE.md#networks-without-udp-qmux-over-websocket)).
20
+ - A Relay endpoint and a short-lived Relay JWT authorized for the namespace you use. The SDK
21
+ consumes tokens; it does not issue them.
22
+
23
+ ## Install
24
+
25
+ The package is unpublished and its name is provisional. Build it from a checkout of this repository
26
+ and serve it with its `@caprid/moq-core` dependency, as described in
27
+ [Use the local packages in your application](GUIDE.md#use-the-local-packages-in-your-application).
28
+
29
+ ## Publish and subscribe
30
+
31
+ ```ts
32
+ import { connectRelayPublisher, connectRelaySubscriber, readText, roomEndpoint } from '@caprid/relay';
33
+
34
+ const url = roomEndpoint('https://relay.mux.global', ['team']); // your token's root as the path
35
+ const namespace = ['quickstart', 'unique-run']; // relative to that root
36
+ const getToken = () => token; // a Relay JWT allowed to publish and subscribe there
37
+
38
+ const publisher = await connectRelayPublisher({ url, namespace, getToken });
39
+ const ticker = publisher.registerTrack({ track: 'ticker' });
40
+ await publisher.announced;
41
+
42
+ const subscriber = await connectRelaySubscriber({ url, getToken });
43
+ let received: (text: string) => void;
44
+ const arrived = new Promise<string>((resolve) => { received = resolve; });
45
+ const subscription = subscriber.subscribe(
46
+ { namespace, track: 'ticker' },
47
+ { onObject: (object) => { if (object.status === 'normal') received(readText(object)); } },
48
+ );
49
+ await subscription.subscribed; // a fresh namespace can briefly reject this with error 16; retry it
50
+
51
+ await ticker.writeText('hello from @caprid/relay'); // waits for the subscriber's demand
52
+ console.log(await arrived);
53
+ subscriber.close();
54
+ await publisher.close();
55
+ ```
56
+
57
+ The [guide's first round trip](GUIDE.md#first-round-trip) runs the complete version of this in a
58
+ browser, with credential handling, the subscribe retry, a deadline, and cleanup on failure.
59
+
60
+ These connections never reconnect. For a live application, `connectSupervisedPublisher` and
61
+ `connectSupervisedSubscriber` reconnect with backoff, and keep tracks registered and subscribed
62
+ across connections and publisher restarts ([stay connected](GUIDE.md#stay-connected-supervised-connections)).
63
+
64
+ ## Node
65
+
66
+ `@caprid/relay/node` exports everything `@caprid/relay` does. Its `connectRelayPublisher`,
67
+ `connectRelaySubscriber` and both `connectSupervised*` functions connect over native QUIC (MOQT on QUIC, ALPN `moqt-22`, falling back to `moqt-20`) through
68
+ [`@caprid/relay-quic`](packages/relay-quic/README.md), Mux's transport adapter for Node. Pass the same
69
+ `https://` endpoint you pass in a browser.
70
+
71
+ ### Install
72
+
73
+ Add `@caprid/relay-quic` next to `@caprid/relay`. It is an optional peer dependency, needed only by
74
+ `@caprid/relay/node`, and it needs a native binary for your platform:
75
+ [its README](packages/relay-quic/README.md) says how to get one. Without the package or the
76
+ binary, a connect call fails with `RelayError` code `TRANSPORT_UNAVAILABLE`.
77
+
78
+ ### Publish and subscribe
79
+
80
+ The code is the browser example's, with a different import:
81
+
82
+ ```ts
83
+ import { connectRelayPublisher, connectRelaySubscriber, readText, roomEndpoint } from '@caprid/relay/node';
84
+
85
+ const url = roomEndpoint('https://relay.mux.global', ['team']);
86
+ const namespace = ['quickstart', 'unique-run'];
87
+ const getToken = () => process.env.RELAY_TOKEN;
88
+
89
+ const publisher = await connectRelayPublisher({ url, namespace, getToken });
90
+ const ticker = publisher.registerTrack({ track: 'ticker' });
91
+ await publisher.announced;
92
+
93
+ const subscriber = await connectRelaySubscriber({ url, getToken });
94
+ const subscription = subscriber.subscribe(
95
+ { namespace, track: 'ticker' },
96
+ { onObject: (object) => { if (object.status === 'normal') console.log(readText(object)); } },
97
+ );
98
+ await subscription.subscribed;
99
+
100
+ await ticker.writeText('hello from Node');
101
+ ```
102
+
103
+ ### Trust
104
+
105
+ By default a connection trusts the platform's root certificates. Two options change that, on
106
+ either connect function:
107
+
108
+ - `ca`: extra trust anchors, PEM, as a string, bytes, or an array of either, added to the
109
+ platform's roots. Use it for a relay behind a private certificate authority.
110
+ - `serverCertificateHashes`: `[{ algorithm: 'sha-256', value }]`, in the W3C WebTransport shape.
111
+ The server's certificate must match one hash, and its chain is not validated.
112
+
113
+ ```ts
114
+ import { readFile } from 'node:fs/promises';
115
+
116
+ const subscriber = await connectRelaySubscriber({ url, getToken, ca: await readFile('relay-ca.pem') });
117
+ ```
118
+
119
+ Connections without trust options share one adapter. Passing `createTransport` replaces the adapter
120
+ entirely; passing it together with `ca` or `serverCertificateHashes` is a `TypeError`. To combine
121
+ them, build the factory yourself with `nativeQuicTransport({ ca })` from `@caprid/relay-quic`.
122
+
123
+ ### Process lifetime
124
+
125
+ An open connection keeps the Node process alive, from the start of the dial until the connection
126
+ has closed. After that the adapter holds nothing, so a script exits by itself once it has closed
127
+ its publisher and subscriber ([TA-25, TA-26](../spec/transport-adapter.md)). A script that stops
128
+ early without closing them keeps running.
129
+
130
+ ### Native WebTransport
131
+
132
+ `@caprid/relay/node` uses `@caprid/relay-quic` even where a global `WebTransport` exists. If Node gains
133
+ a `WebTransport` that can negotiate protocols, the first connect emits a `DeprecationWarning`
134
+ (code `CAPRID_RELAY_NODE_NATIVE_WEBTRANSPORT`) through `process.emitWarning`, once per process: at
135
+ that point `@caprid/relay` connects on its own, and this entry point will be retired.
136
+
137
+ ### Deno
138
+
139
+ Best effort, and untested: Deno can load the entry as `npm:@caprid/relay/node` and the addon through
140
+ its npm compatibility layer. Deno's own `WebTransport` cannot negotiate protocols, so plain
141
+ `@caprid/relay` fails there with `TRANSPORT_UNAVAILABLE`.
142
+
143
+ ## Stability
144
+
145
+ Before 1.0, a minor version can break the API, and [CHANGELOG.md](CHANGELOG.md) says what changed.
146
+ `@caprid/relay`, `@caprid/moq-core`, `@caprid/moq-media`, `@caprid/moq-mediabunny` and `@caprid/relay-quic` always
147
+ release together at the same version, so install matching versions. A release supports:
148
+
149
+ - browsers with WebTransport, and Node 24 or later on the platforms `@caprid/relay-quic` ships
150
+ binaries for (Linux x64 and arm64 with glibc or musl, macOS arm64 and x64, Windows x64);
151
+ - MOQT draft 22 (`moqt-22`), with draft 20 (`moqt-20`) as an offered fallback, against moq-relay
152
+ 0.15.4 or later.
153
+
154
+ ## Documentation
155
+
156
+ - [TypeScript guide](GUIDE.md): the quickstart, subscription and publishing lifecycles, async
157
+ consumption, and publishing media.
158
+ - API reference: run `mise run ts:docs` to build it from the source.
159
+ - [Errors and recovery](GUIDE.md#errors-and-recovery): stable `RelayError` codes and phases, and
160
+ recovering without assuming delivery or safe replay.
161
+ - [Shared specification](../spec/README.md): the protocol pins, behavior contract, and test vectors
162
+ every Relay SDK implements.
@@ -0,0 +1,125 @@
1
+ import { type KeyValuePair, type MoqtProtocolId, type MoqtSessionCallbacks, type MoqtTransport } from '@caprid/moq-core';
2
+ /** setTimeout stores its delay in a signed 32-bit integer; a larger one wraps and fires at once. */
3
+ export declare const MAX_TIMEOUT_MS = 2147483647;
4
+ /**
5
+ * Reject a deadline a timer cannot hold, so a larger number never means a shorter wait. A value
6
+ * that is not a number is a TypeError; a number outside (0, 2147483647] is a RangeError.
7
+ */
8
+ export declare function assertTimeoutMs(name: string, value: unknown): void;
9
+ /**
10
+ * Supply a browser transport or a compatible implementation in another runtime. Called once per
11
+ * connection with the endpoint URL (the token already in its `jwt` query parameter) and the MOQT
12
+ * protocol IDs to offer, in preference order: `moqt-22`, then `moqt-20` as a fallback.
13
+ */
14
+ export type RelayTransportFactory = (url: string, protocols: string[]) => {
15
+ /** The transport the MOQT session runs on. */
16
+ transport: MoqtTransport;
17
+ /** Resolves once the transport can open streams; a rejection fails the connect call. */
18
+ ready: Promise<void>;
19
+ /**
20
+ * What the transport carries. `'webtransport'` (the default) is a WebTransport session, whose
21
+ * CONNECT request carries the URL. `'native-quic'` is MOQT directly on a QUIC connection: the
22
+ * adapter dials only the URL's host and port, and the core sends the path, query and authority
23
+ * in SETUP. `'websocket'` is QMux over a WebSocket (`@caprid/relay-websocket`), whose upgrade
24
+ * request carries the URL as a CONNECT does. Read once `ready` has resolved.
25
+ */
26
+ framing?: 'webtransport' | 'native-quic' | 'websocket';
27
+ };
28
+ /**
29
+ * A token together with when the relay stops honoring it. moq-relay ends a session at its grant's deadline, which is
30
+ * the token's expiry, and a live session cannot take a new token; supervised connections replace theirs before then.
31
+ */
32
+ export interface RelayCredential {
33
+ /** The token, carried in the endpoint's jwt query parameter. An empty one sends no token. */
34
+ token: string;
35
+ /** When the relay ends a session the token admitted: the JWT's `exp`, or the grant's deadline if it is earlier. */
36
+ expiresAt: Date;
37
+ }
38
+ /**
39
+ * Connection options shared by connectRelaySubscriber and connectRelayPublisher: endpoint, token,
40
+ * lifetime signal, connection deadline, and transport injection. Each role's options extend this
41
+ * with what only that role uses: {@link ConnectRelaySubscriberOptions} and
42
+ * `ConnectRelayPublisherOptions`.
43
+ */
44
+ export interface ConnectRelayOptions {
45
+ /** Relay's HTTPS WebTransport endpoint, including any endpoint path. */
46
+ url: string;
47
+ /**
48
+ * Resolve a connection token. Relay carries it in the endpoint's jwt query parameter.
49
+ * An explicit jwt in the URL wins, and the provider is not called in that case. An empty jwt
50
+ * in the URL is a RangeError, raised before the provider or the transport is used. Return a
51
+ * {@link RelayCredential} to say when the token expires; for a bare token the connection reads
52
+ * the JWT's `exp` claim, without verifying it. The provider runs once per connection: a live
53
+ * session keeps the token it connected with until the relay ends it at that expiry.
54
+ */
55
+ getToken?: () => string | RelayCredential | undefined | Promise<string | RelayCredential | undefined>;
56
+ /** Aborting closes the connection, including after the connect call has resolved. */
57
+ signal?: AbortSignal;
58
+ /** Deadline for token resolution, transport connection, and protocol SETUP. Default 10 seconds, maximum 2147483647. */
59
+ connectTimeoutMs?: number;
60
+ /**
61
+ * Create the transport. Defaults to the browser's WebTransport; a runtime without it, or whose
62
+ * WebTransport cannot negotiate protocols, fails with `TRANSPORT_UNAVAILABLE` unless this is
63
+ * supplied.
64
+ */
65
+ createTransport?: RelayTransportFactory;
66
+ }
67
+ /** Options for connectRelaySubscriber: the shared connection options plus the request deadline. */
68
+ export interface ConnectRelaySubscriberOptions extends ConnectRelayOptions {
69
+ /** Deadline for an initial subscription response, not for silence on an accepted track. Default 10 seconds, maximum 2147483647. */
70
+ requestTimeoutMs?: number;
71
+ }
72
+ interface Session {
73
+ ready: Promise<void>;
74
+ destroy(error?: unknown): void;
75
+ }
76
+ /** A connected session together with the connection lifetime its public handle exposes. */
77
+ interface RelaySessionLifetime<T extends Session> {
78
+ session: T;
79
+ /** Settles once the connection has ended, carrying the error that ended it if any. */
80
+ closed: Promise<{
81
+ error?: unknown;
82
+ }>;
83
+ /**
84
+ * Observe the closure in the turn it happens, before the session tears its requests down; an
85
+ * observer added after the end is told at once. The returned function removes the observer.
86
+ */
87
+ observeClosed(observer: (error?: unknown) => void): () => void;
88
+ transportClosed: MoqtTransport['closed'];
89
+ /** The MOQT version the transport negotiated, which selects the core's parameter codec. */
90
+ protocol: MoqtProtocolId;
91
+ /** When the relay ends the session for the credential's expiry, if known. */
92
+ expiresAt: Date | undefined;
93
+ /** Throws the closing error once the connection has ended. */
94
+ assertOpen(): void;
95
+ /** Close the connection. Idempotent. */
96
+ close(): void;
97
+ }
98
+ /**
99
+ * Internal to the SDK's entry points, never part of the public options: resolves the transport factory in place of
100
+ * `createTransport`, inside the connection's deadline and signal and after the token. `@caprid/relay/node` loads its
101
+ * adapter here. A failure is passed through as it is thrown.
102
+ */
103
+ export declare const resolveTransport: unique symbol;
104
+ /** The options {@link openRelaySession} reads: the public ones, plus an entry point's {@link resolveTransport}. */
105
+ export type RelaySessionOptions = ConnectRelayOptions & {
106
+ [resolveTransport]?: () => Promise<RelayTransportFactory>;
107
+ };
108
+ /**
109
+ * Check an endpoint by the Endpoint rule in spec/behavior.md and return it parsed. Not a string, or
110
+ * not a URL at all (including an https URL with no host), is a TypeError: the wrong shape. A URL
111
+ * that parses but is not one Relay accepts is a RangeError: a disallowed value.
112
+ */
113
+ export declare function endpointUrl(endpoint: unknown): URL;
114
+ /**
115
+ * Shared transport/auth lifetime for the subscribe and publish session drivers. It validates only
116
+ * the shared options; each role checks its own options before calling it.
117
+ */
118
+ export declare function openRelaySession<T extends Session>(options: RelaySessionOptions, createSession: (transport: MoqtTransport, callbacks: Pick<MoqtSessionCallbacks, 'onReady' | 'onClosed' | 'onGoaway'>, setupOptions: KeyValuePair[]) => T): Promise<RelaySessionLifetime<T>>;
119
+ /**
120
+ * The `exp` claim of a JWT, read without verifying the token: the relay verifies it, and the SDK only needs to know
121
+ * when the session will end. Anything that is not a JWT with a numeric `exp` has no known expiry.
122
+ */
123
+ export declare function jwtExpiry(token: string): Date | undefined;
124
+ export {};
125
+ //# sourceMappingURL=connect-session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect-session.d.ts","sourceRoot":"","sources":["../src/connect-session.ts"],"names":[],"mappings":"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"}