@crosslink/webrtc-adapter 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.
- package/LICENSE +163 -0
- package/README.md +11 -0
- package/dist/index.d.ts +194 -0
- package/dist/index.js +260 -0
- package/package.json +30 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by the
|
|
13
|
+
copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other
|
|
16
|
+
entities that control, are controlled by, or are under common control
|
|
17
|
+
with that entity. For the purposes of this definition, "control" means
|
|
18
|
+
(i) the power, direct or indirect, to cause the direction or management
|
|
19
|
+
of such entity, whether by contract or otherwise, or (ii) ownership of
|
|
20
|
+
fifty percent (50%) or more of the outstanding shares, or (iii) beneficial
|
|
21
|
+
ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
|
24
|
+
permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation source,
|
|
28
|
+
and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical transformation
|
|
31
|
+
or translation of a Source form, including but not limited to compiled
|
|
32
|
+
object code, generated documentation, and conversions to other media types.
|
|
33
|
+
|
|
34
|
+
"Work" shall mean the work of authorship, whether in Source or Object
|
|
35
|
+
form, made available under the License, as indicated by a copyright notice
|
|
36
|
+
that is included in or attached to the work.
|
|
37
|
+
|
|
38
|
+
"Derivative Works" shall mean any work, whether in Source or Object form,
|
|
39
|
+
that is based on (or derived from) the Work and for which the editorial
|
|
40
|
+
revisions, annotations, elaborations, or other modifications represent, as
|
|
41
|
+
a whole, an original work of authorship. For the purposes of this License,
|
|
42
|
+
Derivative Works shall not include works that remain separable from, or
|
|
43
|
+
merely link (or bind by name) to the interfaces of, the Work and Derivative
|
|
44
|
+
Works thereof.
|
|
45
|
+
|
|
46
|
+
"Contribution" shall mean any work of authorship, including the original
|
|
47
|
+
version of the Work and any modifications or additions to that Work or
|
|
48
|
+
Derivative Works thereof, that is intentionally submitted to the Licensor
|
|
49
|
+
for inclusion in the Work by the copyright owner or by an individual or
|
|
50
|
+
Legal Entity authorized to submit on behalf of the copyright owner. For the
|
|
51
|
+
purposes of this definition, "submitted" means any form of electronic,
|
|
52
|
+
verbal, or written communication sent to the Licensor or its representatives,
|
|
53
|
+
including but not limited to communication on electronic mailing lists,
|
|
54
|
+
source code control systems, and issue tracking systems that are managed by,
|
|
55
|
+
or on behalf of, the Licensor for the purpose of discussing and improving
|
|
56
|
+
the Work, but excluding communication that is conspicuously marked or
|
|
57
|
+
otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
58
|
+
|
|
59
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on
|
|
60
|
+
behalf of whom a Contribution has been received by the Licensor and
|
|
61
|
+
subsequently incorporated within the Work.
|
|
62
|
+
|
|
63
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this
|
|
64
|
+
License, each Contributor hereby grants to You a perpetual, worldwide,
|
|
65
|
+
non-exclusive, no-charge, royalty-free, irrevocable copyright license to
|
|
66
|
+
reproduce, prepare Derivative Works of, publicly display, publicly perform,
|
|
67
|
+
sublicense, and distribute the Work and such Derivative Works in Source or
|
|
68
|
+
Object form.
|
|
69
|
+
|
|
70
|
+
3. Grant of Patent License. Subject to the terms and conditions of this
|
|
71
|
+
License, each Contributor hereby grants to You a perpetual, worldwide,
|
|
72
|
+
non-exclusive, no-charge, royalty-free, irrevocable (except as stated in
|
|
73
|
+
this section) patent license to make, have made, use, offer to sell, sell,
|
|
74
|
+
import, and otherwise transfer the Work, where such license applies only to
|
|
75
|
+
those patent claims licensable by such Contributor that are necessarily
|
|
76
|
+
infringed by their Contribution(s) alone or by combination of their
|
|
77
|
+
Contribution(s) with the Work to which such Contribution(s) was submitted.
|
|
78
|
+
If You institute patent litigation against any entity (including a
|
|
79
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
|
80
|
+
Contribution incorporated within the Work constitutes direct or contributory
|
|
81
|
+
patent infringement, then any patent licenses granted to You under this
|
|
82
|
+
License for that Work shall terminate as of the date such litigation is filed.
|
|
83
|
+
|
|
84
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or
|
|
85
|
+
Derivative Works thereof in any medium, with or without modifications, and
|
|
86
|
+
in Source or Object form, provided that You meet the following conditions:
|
|
87
|
+
|
|
88
|
+
(a) You must give any other recipients of the Work or Derivative Works
|
|
89
|
+
a copy of this License; and
|
|
90
|
+
|
|
91
|
+
(b) You must cause any modified files to carry prominent notices stating
|
|
92
|
+
that You changed the files; and
|
|
93
|
+
|
|
94
|
+
(c) You must retain, in the Source form of any Derivative Works that You
|
|
95
|
+
distribute, all copyright, patent, trademark, and attribution notices
|
|
96
|
+
from the Source form of the Work, excluding those notices that do not
|
|
97
|
+
pertain to any part of the Derivative Works; and
|
|
98
|
+
|
|
99
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution,
|
|
100
|
+
then any Derivative Works that You distribute must include a readable
|
|
101
|
+
copy of the attribution notices contained within such NOTICE file,
|
|
102
|
+
excluding any notices that do not pertain to any part of the Derivative
|
|
103
|
+
Works, in at least one of the following places: within a NOTICE text
|
|
104
|
+
file distributed as part of the Derivative Works; within the Source
|
|
105
|
+
form or documentation, if provided along with the Derivative Works; or,
|
|
106
|
+
within a display generated by the Derivative Works, if and wherever
|
|
107
|
+
such third-party notices normally appear. The contents of the NOTICE
|
|
108
|
+
file are for informational purposes only and do not modify the License.
|
|
109
|
+
You may add Your own attribution notices within Derivative Works that
|
|
110
|
+
You distribute, alongside or as an addendum to the NOTICE text from
|
|
111
|
+
the Work, provided that such additional attribution notices cannot be
|
|
112
|
+
construed as modifying the License.
|
|
113
|
+
|
|
114
|
+
You may add Your own copyright statement to Your modifications and may
|
|
115
|
+
provide additional or different license terms and conditions for use,
|
|
116
|
+
reproduction, or distribution of Your modifications, or for any such
|
|
117
|
+
Derivative Works as a whole, provided Your use, reproduction, and
|
|
118
|
+
distribution of the Work otherwise complies with the conditions stated
|
|
119
|
+
in this License.
|
|
120
|
+
|
|
121
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any
|
|
122
|
+
Contribution intentionally submitted for inclusion in the Work by You to
|
|
123
|
+
the Licensor shall be under the terms and conditions of this License,
|
|
124
|
+
without any additional terms or conditions. Notwithstanding the above,
|
|
125
|
+
nothing herein shall supersede or modify the terms of any separate license
|
|
126
|
+
agreement you may have executed with Licensor regarding such Contributions.
|
|
127
|
+
|
|
128
|
+
6. Trademarks. This License does not grant permission to use the trade names,
|
|
129
|
+
trademarks, service marks, or product names of the Licensor, except as
|
|
130
|
+
required for reasonable and customary use in describing the origin of the
|
|
131
|
+
Work and reproducing the content of the NOTICE file.
|
|
132
|
+
|
|
133
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
|
|
134
|
+
writing, Licensor provides the Work (and each Contributor provides its
|
|
135
|
+
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
136
|
+
KIND, either express or implied, including, without limitation, any warranties
|
|
137
|
+
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
138
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
139
|
+
appropriateness of using or redistributing the Work and assume any risks
|
|
140
|
+
associated with Your exercise of permissions under this License.
|
|
141
|
+
|
|
142
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in
|
|
143
|
+
tort (including negligence), contract, or otherwise, unless required by
|
|
144
|
+
applicable law (such as deliberate and grossly negligent acts) or agreed to
|
|
145
|
+
in writing, shall any Contributor be liable to You for damages, including
|
|
146
|
+
any direct, indirect, special, incidental, or consequential damages of any
|
|
147
|
+
character arising as a result of this License or out of the use or inability
|
|
148
|
+
to use the Work (including but not limited to damages for loss of goodwill,
|
|
149
|
+
work stoppage, computer failure or malfunction, or any and all other
|
|
150
|
+
commercial damages or losses), even if such Contributor has been advised of
|
|
151
|
+
the possibility of such damages.
|
|
152
|
+
|
|
153
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work
|
|
154
|
+
or Derivative Works thereof, You may choose to offer, and charge a fee for,
|
|
155
|
+
acceptance of support, warranty, indemnity, or other liability obligations
|
|
156
|
+
and/or rights consistent with this License. However, in accepting such
|
|
157
|
+
obligations, You may act only on Your own behalf and on Your sole
|
|
158
|
+
responsibility, not on behalf of any other Contributor, and only if You
|
|
159
|
+
agree to indemnify, defend, and hold each Contributor harmless for any
|
|
160
|
+
liability incurred by, or claims asserted against, such Contributor by reason
|
|
161
|
+
of your accepting any such warranty or additional liability.
|
|
162
|
+
|
|
163
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# @crosslink/webrtc-adapter
|
|
2
|
+
|
|
3
|
+
<p align="center"><img src="https://crosslink.mintlify.site/crosslink.svg" alt="Crosslink" width="320" /></p>
|
|
4
|
+
|
|
5
|
+
WebRTC data-channel transport support for Crosslink connections.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @crosslink/webrtc-adapter
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
See the [Crosslink documentation](https://crosslink.mintlify.site) and [repository](https://github.com/jacobpowaza/crosslink).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { TransportCandidate, CrosslinkTransport, ConnectionKind } from '@crosslink/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* SDP exchange over an existing Crosslink session.
|
|
5
|
+
*
|
|
6
|
+
* The transport primitives in `./index.js` deliberately know nothing about
|
|
7
|
+
* signaling: they take an `exchange` callback and leave the question of how an
|
|
8
|
+
* offer reaches the other side to the embedder. This module answers that
|
|
9
|
+
* question the obvious way - by sending the offer down a Crosslink session the
|
|
10
|
+
* two devices already share.
|
|
11
|
+
*
|
|
12
|
+
* That makes the exchange inherit everything the session already provides:
|
|
13
|
+
* it is end-to-end encrypted, it is authenticated to a specific paired device,
|
|
14
|
+
* and it is capability-gated like any other method. No third party sees the
|
|
15
|
+
* SDP, and no separate signaling channel has to be stood up, authenticated or
|
|
16
|
+
* kept alive.
|
|
17
|
+
*
|
|
18
|
+
* The shape is:
|
|
19
|
+
*
|
|
20
|
+
* 1. Client and host are connected over whatever worked first - typically
|
|
21
|
+
* the relay, which is reliable but pays for every byte in latency.
|
|
22
|
+
* 2. The client calls `crosslink.webrtc.offer` over that session with its
|
|
23
|
+
* SDP offer. The host answers with its SDP answer.
|
|
24
|
+
* 3. Both sides now hold a DataChannel. The client asks its `ClientLink` to
|
|
25
|
+
* upgrade onto it, which runs a fresh CLX1 handshake over the channel and
|
|
26
|
+
* swaps transports only once that succeeds.
|
|
27
|
+
* 4. If any of this fails, nothing happens: the relayed session carries on.
|
|
28
|
+
*
|
|
29
|
+
* The relayed session is the fallback, not a stepping stone to be torn down
|
|
30
|
+
* optimistically.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/** The default method name for the SDP exchange. */
|
|
34
|
+
declare const WEBRTC_OFFER_METHOD = "crosslink.webrtc.offer";
|
|
35
|
+
/** Minimal session description, matching the browser's shape. */
|
|
36
|
+
interface SdpLike {
|
|
37
|
+
type: "offer" | "answer" | "pranswer" | "rollback";
|
|
38
|
+
sdp: string;
|
|
39
|
+
}
|
|
40
|
+
interface PeerConnectionLike {
|
|
41
|
+
createDataChannel(label: string, opts?: {
|
|
42
|
+
ordered?: boolean;
|
|
43
|
+
}): DataChannelLike;
|
|
44
|
+
createOffer(): Promise<SdpLike>;
|
|
45
|
+
createAnswer(): Promise<SdpLike>;
|
|
46
|
+
setLocalDescription(d: SdpLike): Promise<void>;
|
|
47
|
+
setRemoteDescription(d: SdpLike): Promise<void>;
|
|
48
|
+
close(): void;
|
|
49
|
+
localDescription?: SdpLike | null;
|
|
50
|
+
iceGatheringState?: string;
|
|
51
|
+
onicegatheringstatechange?: (() => void) | null;
|
|
52
|
+
ondatachannel?: ((ev: {
|
|
53
|
+
channel: DataChannelLike;
|
|
54
|
+
}) => void) | null;
|
|
55
|
+
}
|
|
56
|
+
interface DataChannelLike {
|
|
57
|
+
readyState: string;
|
|
58
|
+
binaryType: string;
|
|
59
|
+
send(data: ArrayBuffer | Uint8Array): void;
|
|
60
|
+
close(): void;
|
|
61
|
+
onmessage: ((ev: {
|
|
62
|
+
data: unknown;
|
|
63
|
+
}) => void) | null;
|
|
64
|
+
onopen: (() => void) | null;
|
|
65
|
+
onclose: (() => void) | null;
|
|
66
|
+
onerror: (() => void) | null;
|
|
67
|
+
}
|
|
68
|
+
interface WebrtcHostOptions {
|
|
69
|
+
/** e.g. `() => new RTCPeerConnection({ iceServers })`. */
|
|
70
|
+
createPeer(): PeerConnectionLike;
|
|
71
|
+
/**
|
|
72
|
+
* Called with the DataChannel transport once it opens. Feed it to the same
|
|
73
|
+
* place your LAN and relay transports go - `CrosslinkServer` does this for
|
|
74
|
+
* you via `enableWebrtcUpgrades`.
|
|
75
|
+
*/
|
|
76
|
+
onTransport(transport: CrosslinkTransport, deviceId: string): void;
|
|
77
|
+
/**
|
|
78
|
+
* Capability required to request an upgrade. Defaults to undefined (any
|
|
79
|
+
* paired device may). Set one if you want the upgrade itself gated.
|
|
80
|
+
*/
|
|
81
|
+
capability?: string;
|
|
82
|
+
/** Method name; override only if it collides with your own namespace. */
|
|
83
|
+
method?: string;
|
|
84
|
+
timeoutMs?: number;
|
|
85
|
+
/** Maximum concurrent half-open peer connections, to bound memory. */
|
|
86
|
+
maxPending?: number;
|
|
87
|
+
}
|
|
88
|
+
/** The subset of a host server this module needs, so it can be unit-tested. */
|
|
89
|
+
interface ExposeTarget {
|
|
90
|
+
expose(method: string, handler: (input: unknown, ctx: {
|
|
91
|
+
deviceId: string;
|
|
92
|
+
}) => unknown, options?: {
|
|
93
|
+
capability?: string;
|
|
94
|
+
timeoutMs?: number;
|
|
95
|
+
}): unknown;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Registers the host half of the exchange: an RPC method that accepts an SDP
|
|
99
|
+
* offer from an authenticated device and returns the answer.
|
|
100
|
+
*
|
|
101
|
+
* The resulting DataChannel is handed to `onTransport`, which must run the
|
|
102
|
+
* normal `HostAcceptor` handshake over it - the WebRTC channel is just a pipe
|
|
103
|
+
* and carries no authority of its own. A device that reaches the host over
|
|
104
|
+
* WebRTC still proves its identity exactly as it does over the relay.
|
|
105
|
+
*/
|
|
106
|
+
declare function exposeWebrtcOffer(target: ExposeTarget, options: WebrtcHostOptions): void;
|
|
107
|
+
interface WebrtcClientOptions {
|
|
108
|
+
createPeer(): PeerConnectionLike;
|
|
109
|
+
method?: string;
|
|
110
|
+
timeoutMs?: number;
|
|
111
|
+
label?: string;
|
|
112
|
+
}
|
|
113
|
+
/** The subset of a client link this module needs. */
|
|
114
|
+
interface CallTarget {
|
|
115
|
+
call<T>(method: string, input?: unknown, opts?: {
|
|
116
|
+
timeoutMs?: number;
|
|
117
|
+
}): Promise<T>;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Builds a transport candidate that negotiates a DataChannel by exchanging SDP
|
|
121
|
+
* over `link` - i.e. over the Crosslink session that is already up.
|
|
122
|
+
*
|
|
123
|
+
* Pass the result to `ClientLink.upgrade()`, not to the initial candidate
|
|
124
|
+
* list: it can only work once a session exists to carry the offer.
|
|
125
|
+
*/
|
|
126
|
+
declare function webrtcUpgradeCandidate(link: CallTarget, options: WebrtcClientOptions): TransportCandidate;
|
|
127
|
+
interface UpgradeTarget extends CallTarget {
|
|
128
|
+
upgrade(candidate: TransportCandidate): Promise<boolean>;
|
|
129
|
+
readonly transportKind?: string;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Convenience wrapper: try to move `link` onto a direct WebRTC connection,
|
|
133
|
+
* returning whether it worked. Never throws - a failed upgrade leaves the
|
|
134
|
+
* existing (relayed or LAN) session running, which is the whole point.
|
|
135
|
+
*/
|
|
136
|
+
declare function tryUpgradeToWebrtc(link: UpgradeTarget, options: WebrtcClientOptions): Promise<boolean>;
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* WebRTC direct transport (DataChannel).
|
|
140
|
+
*
|
|
141
|
+
* Crosslink frames travel over a single reliable/ordered DataChannel. SDP
|
|
142
|
+
* exchange happens OUT of band: the embedder supplies an `exchange` callback
|
|
143
|
+
* (e.g. over an existing Crosslink session, QR, or push notification) - this
|
|
144
|
+
* module never talks to signaling services itself.
|
|
145
|
+
*
|
|
146
|
+
* For the common case - upgrading an existing relayed session to a direct one
|
|
147
|
+
* by exchanging SDP over that very session - use `./over-crosslink.js`, which
|
|
148
|
+
* wires the callback for you.
|
|
149
|
+
*/
|
|
150
|
+
|
|
151
|
+
type RTCPC = {
|
|
152
|
+
createDataChannel(label: string, opts?: {
|
|
153
|
+
ordered?: boolean;
|
|
154
|
+
}): RTCDC & Record<string, unknown>;
|
|
155
|
+
createOffer(): Promise<RTCSdpLike>;
|
|
156
|
+
createAnswer(): Promise<RTCSdpLike>;
|
|
157
|
+
setLocalDescription(d: RTCSdpLike): Promise<void>;
|
|
158
|
+
setRemoteDescription(d: RTCSdpLike): Promise<void>;
|
|
159
|
+
close(): void;
|
|
160
|
+
connectionState?: string;
|
|
161
|
+
onconnectionstatechange?: (() => void) | null;
|
|
162
|
+
};
|
|
163
|
+
type RTCDC = {
|
|
164
|
+
readyState: string;
|
|
165
|
+
binaryType: string;
|
|
166
|
+
send(data: ArrayBuffer | Uint8Array): void;
|
|
167
|
+
close(): void;
|
|
168
|
+
onmessage: ((ev: {
|
|
169
|
+
data: unknown;
|
|
170
|
+
}) => void) | null;
|
|
171
|
+
onopen: (() => void) | null;
|
|
172
|
+
onclose: (() => void) | null;
|
|
173
|
+
onerror: (() => void) | null;
|
|
174
|
+
};
|
|
175
|
+
interface RTCSdpLike {
|
|
176
|
+
type: "offer" | "answer" | "pranswer" | "rollback";
|
|
177
|
+
sdp: string;
|
|
178
|
+
}
|
|
179
|
+
interface WebRtcDeps {
|
|
180
|
+
/** e.g. (cfg) => new RTCPeerConnection({ iceServers }) */
|
|
181
|
+
createPeer(): RTCPC;
|
|
182
|
+
}
|
|
183
|
+
/** Wraps one side of an established DataChannel as a CrosslinkTransport. */
|
|
184
|
+
declare function dataChannelTransport(dc: RTCDC, kind?: ConnectionKind): CrosslinkTransport;
|
|
185
|
+
interface WebrtcOffererOptions {
|
|
186
|
+
label?: string;
|
|
187
|
+
timeoutMs?: number;
|
|
188
|
+
}
|
|
189
|
+
/** Candidate for the side that PRODUCES the offer. */
|
|
190
|
+
declare function webrtcOfferCandidate(deps: WebRtcDeps, exchange: (offer: RTCSdpLike) => Promise<RTCSdpLike>, options?: WebrtcOffererOptions): TransportCandidate;
|
|
191
|
+
/** Candidate for the side that ANSWERS. */
|
|
192
|
+
declare function webrtcAnswerCandidate(deps: WebRtcDeps, acceptOffer: () => Promise<RTCSdpLike>, publishAnswer: (answer: RTCSdpLike) => Promise<void>, options?: WebrtcOffererOptions): TransportCandidate;
|
|
193
|
+
|
|
194
|
+
export { type CallTarget, type ExposeTarget, type SdpLike, type UpgradeTarget, WEBRTC_OFFER_METHOD, type WebRtcDeps, type WebrtcClientOptions, type WebrtcHostOptions, type WebrtcOffererOptions, dataChannelTransport, exposeWebrtcOffer, tryUpgradeToWebrtc, webrtcAnswerCandidate, webrtcOfferCandidate, webrtcUpgradeCandidate };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
// src/over-crosslink.ts
|
|
2
|
+
var WEBRTC_OFFER_METHOD = "crosslink.webrtc.offer";
|
|
3
|
+
var MAX_SDP_BYTES = 64 * 1024;
|
|
4
|
+
var DEFAULT_TIMEOUT_MS = 15e3;
|
|
5
|
+
var CHANNEL_LABEL = "crosslink";
|
|
6
|
+
function exposeWebrtcOffer(target, options) {
|
|
7
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
8
|
+
const maxPending = options.maxPending ?? 8;
|
|
9
|
+
let pending = 0;
|
|
10
|
+
target.expose(
|
|
11
|
+
options.method ?? WEBRTC_OFFER_METHOD,
|
|
12
|
+
async (input, ctx) => {
|
|
13
|
+
const offer = readSdp(input, "offer");
|
|
14
|
+
if (pending >= maxPending) {
|
|
15
|
+
throw Object.assign(new Error("too many pending WebRTC upgrades"), {
|
|
16
|
+
code: "rate_limited"
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
pending += 1;
|
|
20
|
+
const pc = options.createPeer();
|
|
21
|
+
let settled = false;
|
|
22
|
+
try {
|
|
23
|
+
const channelPromise = new Promise((resolve, reject) => {
|
|
24
|
+
const timer = setTimeout(
|
|
25
|
+
() => reject(new Error("no datachannel arrived")),
|
|
26
|
+
timeoutMs
|
|
27
|
+
);
|
|
28
|
+
pc.ondatachannel = (ev) => {
|
|
29
|
+
clearTimeout(timer);
|
|
30
|
+
resolve(ev.channel);
|
|
31
|
+
};
|
|
32
|
+
});
|
|
33
|
+
await pc.setRemoteDescription(offer);
|
|
34
|
+
await pc.setLocalDescription(await pc.createAnswer());
|
|
35
|
+
await gatherSettled(pc, timeoutMs);
|
|
36
|
+
const answerSdp = pc.localDescription?.sdp;
|
|
37
|
+
if (!answerSdp) throw new Error("no local description after createAnswer");
|
|
38
|
+
void channelPromise.then(async (channel) => {
|
|
39
|
+
await waitOpen(channel, timeoutMs);
|
|
40
|
+
settled = true;
|
|
41
|
+
options.onTransport(dataChannelTransport(channel), ctx.deviceId);
|
|
42
|
+
}).catch(() => {
|
|
43
|
+
if (!settled) pc.close();
|
|
44
|
+
});
|
|
45
|
+
return { type: "answer", sdp: answerSdp };
|
|
46
|
+
} catch (err) {
|
|
47
|
+
pc.close();
|
|
48
|
+
throw err;
|
|
49
|
+
} finally {
|
|
50
|
+
pending -= 1;
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
...options.capability ? { capability: options.capability } : {},
|
|
55
|
+
timeoutMs: timeoutMs + 1e3
|
|
56
|
+
}
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
function webrtcUpgradeCandidate(link, options) {
|
|
60
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
61
|
+
return {
|
|
62
|
+
kind: "webrtc-direct",
|
|
63
|
+
connect: async () => {
|
|
64
|
+
const pc = options.createPeer();
|
|
65
|
+
try {
|
|
66
|
+
const channel = pc.createDataChannel(options.label ?? CHANNEL_LABEL, { ordered: true });
|
|
67
|
+
const opened = waitOpen(channel, timeoutMs);
|
|
68
|
+
await pc.setLocalDescription(await pc.createOffer());
|
|
69
|
+
await gatherSettled(pc, timeoutMs);
|
|
70
|
+
const offerSdp = pc.localDescription?.sdp;
|
|
71
|
+
if (!offerSdp) throw new Error("no local description after createOffer");
|
|
72
|
+
const answer = await link.call(
|
|
73
|
+
options.method ?? WEBRTC_OFFER_METHOD,
|
|
74
|
+
{ type: "offer", sdp: offerSdp },
|
|
75
|
+
{ timeoutMs }
|
|
76
|
+
);
|
|
77
|
+
await pc.setRemoteDescription(readSdp(answer, "answer"));
|
|
78
|
+
await opened;
|
|
79
|
+
return dataChannelTransport(channel);
|
|
80
|
+
} catch (err) {
|
|
81
|
+
pc.close();
|
|
82
|
+
throw err;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
async function tryUpgradeToWebrtc(link, options) {
|
|
88
|
+
if (link.transportKind === "webrtc-direct") return true;
|
|
89
|
+
try {
|
|
90
|
+
return await link.upgrade(webrtcUpgradeCandidate(link, options));
|
|
91
|
+
} catch {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function readSdp(input, expected) {
|
|
96
|
+
const value = input;
|
|
97
|
+
if (!value || typeof value.sdp !== "string" || value.type !== expected) {
|
|
98
|
+
throw Object.assign(new Error(`expected an SDP ${expected}`), {
|
|
99
|
+
code: "validation_failed"
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (value.sdp.length > MAX_SDP_BYTES) {
|
|
103
|
+
throw Object.assign(new Error("SDP too large"), { code: "payload_too_large" });
|
|
104
|
+
}
|
|
105
|
+
return { type: expected, sdp: value.sdp };
|
|
106
|
+
}
|
|
107
|
+
function waitOpen(dc, timeoutMs) {
|
|
108
|
+
if (dc.readyState === "open") return Promise.resolve();
|
|
109
|
+
return new Promise((resolve, reject) => {
|
|
110
|
+
const timer = setTimeout(() => reject(new Error("datachannel open timeout")), timeoutMs);
|
|
111
|
+
dc.onopen = () => {
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
resolve();
|
|
114
|
+
};
|
|
115
|
+
dc.onerror = () => {
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
reject(new Error("datachannel error"));
|
|
118
|
+
};
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
function gatherSettled(pc, timeoutMs) {
|
|
122
|
+
if (pc.iceGatheringState === "complete") return Promise.resolve();
|
|
123
|
+
return new Promise((resolve) => {
|
|
124
|
+
const done = () => {
|
|
125
|
+
pc.onicegatheringstatechange = null;
|
|
126
|
+
resolve();
|
|
127
|
+
};
|
|
128
|
+
pc.onicegatheringstatechange = () => {
|
|
129
|
+
if (pc.iceGatheringState === "complete") done();
|
|
130
|
+
};
|
|
131
|
+
setTimeout(done, Math.min(2e3, timeoutMs));
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// src/index.ts
|
|
136
|
+
function dataChannelTransport(dc, kind = "webrtc-direct") {
|
|
137
|
+
let dataHandler;
|
|
138
|
+
let closeHandler;
|
|
139
|
+
let closed = false;
|
|
140
|
+
dc.binaryType = "arraybuffer";
|
|
141
|
+
dc.onmessage = async (ev) => {
|
|
142
|
+
if (closed) return;
|
|
143
|
+
const data = ev.data;
|
|
144
|
+
const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
145
|
+
dataHandler?.(bytes);
|
|
146
|
+
};
|
|
147
|
+
const die = () => {
|
|
148
|
+
if (closed) return;
|
|
149
|
+
closed = true;
|
|
150
|
+
closeHandler?.("dc-closed");
|
|
151
|
+
};
|
|
152
|
+
dc.onclose = die;
|
|
153
|
+
dc.onerror = die;
|
|
154
|
+
return {
|
|
155
|
+
kind,
|
|
156
|
+
onData(cb) {
|
|
157
|
+
dataHandler = cb;
|
|
158
|
+
},
|
|
159
|
+
onClose(cb) {
|
|
160
|
+
closeHandler = cb;
|
|
161
|
+
},
|
|
162
|
+
async send(bytes) {
|
|
163
|
+
if (closed || dc.readyState !== "open") throw new Error("datachannel closed");
|
|
164
|
+
dc.send(bytes);
|
|
165
|
+
},
|
|
166
|
+
close(reason) {
|
|
167
|
+
if (closed) return;
|
|
168
|
+
try {
|
|
169
|
+
dc.close();
|
|
170
|
+
} catch {
|
|
171
|
+
}
|
|
172
|
+
closed = true;
|
|
173
|
+
closeHandler?.(typeof reason === "string" ? reason : "closed");
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function webrtcOfferCandidate(deps, exchange, options = {}) {
|
|
178
|
+
return {
|
|
179
|
+
kind: "webrtc-direct",
|
|
180
|
+
connect: async () => {
|
|
181
|
+
const pc = deps.createPeer();
|
|
182
|
+
const channel = pc.createDataChannel(options.label ?? "crosslink", { ordered: true });
|
|
183
|
+
const opened = waitOpen2(channel, options.timeoutMs ?? 1e4);
|
|
184
|
+
await pc.setLocalDescription(await pc.createOffer());
|
|
185
|
+
await gatherSettled2(pc);
|
|
186
|
+
const answer = await exchange({
|
|
187
|
+
type: "offer",
|
|
188
|
+
sdp: pc.localDescription.sdp
|
|
189
|
+
});
|
|
190
|
+
await pc.setRemoteDescription(answer);
|
|
191
|
+
await opened;
|
|
192
|
+
return dataChannelTransport(channel);
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
function webrtcAnswerCandidate(deps, acceptOffer, publishAnswer, options = {}) {
|
|
197
|
+
return {
|
|
198
|
+
kind: "webrtc-direct",
|
|
199
|
+
connect: async () => {
|
|
200
|
+
const pc = deps.createPeer();
|
|
201
|
+
const offer = await acceptOffer();
|
|
202
|
+
await pc.setRemoteDescription(offer);
|
|
203
|
+
const channelPromise = new Promise((resolve, reject) => {
|
|
204
|
+
const t = setTimeout(() => reject(new Error("no datachannel")), options.timeoutMs ?? 1e4);
|
|
205
|
+
pc.ondatachannel = (ev) => {
|
|
206
|
+
clearTimeout(t);
|
|
207
|
+
resolve(ev.channel);
|
|
208
|
+
};
|
|
209
|
+
});
|
|
210
|
+
await pc.setLocalDescription(await pc.createAnswer());
|
|
211
|
+
await gatherSettled2(pc);
|
|
212
|
+
await publishAnswer({
|
|
213
|
+
type: "answer",
|
|
214
|
+
sdp: pc.localDescription.sdp
|
|
215
|
+
});
|
|
216
|
+
const channel = await channelPromise;
|
|
217
|
+
await waitOpen2(channel, options.timeoutMs ?? 1e4);
|
|
218
|
+
return dataChannelTransport(channel);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
function waitOpen2(dc, timeoutMs) {
|
|
223
|
+
if (dc.readyState === "open") return Promise.resolve();
|
|
224
|
+
return new Promise((resolve, reject) => {
|
|
225
|
+
const timer = setTimeout(() => reject(new Error("datachannel open timeout")), timeoutMs);
|
|
226
|
+
dc.onopen = () => {
|
|
227
|
+
clearTimeout(timer);
|
|
228
|
+
resolve();
|
|
229
|
+
};
|
|
230
|
+
const prevError = dc.onerror;
|
|
231
|
+
dc.onerror = () => {
|
|
232
|
+
clearTimeout(timer);
|
|
233
|
+
reject(new Error("datachannel error"));
|
|
234
|
+
prevError?.();
|
|
235
|
+
};
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
function gatherSettled2(pc) {
|
|
239
|
+
const anyPc = pc;
|
|
240
|
+
if (anyPc.iceGatheringState === "complete") return Promise.resolve();
|
|
241
|
+
return new Promise((resolve) => {
|
|
242
|
+
const done = () => resolve();
|
|
243
|
+
anyPc.onicegatheringstatechange = () => {
|
|
244
|
+
if (anyPc.iceGatheringState === "complete") {
|
|
245
|
+
anyPc.onicegatheringstatechange = null;
|
|
246
|
+
done();
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
setTimeout(done, 1500);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
export {
|
|
253
|
+
WEBRTC_OFFER_METHOD,
|
|
254
|
+
dataChannelTransport,
|
|
255
|
+
exposeWebrtcOffer,
|
|
256
|
+
tryUpgradeToWebrtc,
|
|
257
|
+
webrtcAnswerCandidate,
|
|
258
|
+
webrtcOfferCandidate,
|
|
259
|
+
webrtcUpgradeCandidate
|
|
260
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@crosslink/webrtc-adapter",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Crosslink WebRTC data-channel transport adapter (interface + roadmap)",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": { "type": "git", "url": "git+https://github.com/jacobpowaza/crosslink.git", "directory": "adapters/webrtc" },
|
|
7
|
+
"homepage": "https://crosslink.mintlify.site",
|
|
8
|
+
"bugs": { "url": "https://github.com/jacobpowaza/crosslink/issues" },
|
|
9
|
+
"publishConfig": { "access": "public" },
|
|
10
|
+
"type": "module",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": ["dist"],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsup src/index.ts --format esm --dts --clean",
|
|
20
|
+
"typecheck": "tsc --noEmit"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@crosslink/core": "^0.1.0",
|
|
24
|
+
"@crosslink/protocol": "^0.1.0"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"tsup": "^8.3.6",
|
|
28
|
+
"typescript": "^5.6.3"
|
|
29
|
+
}
|
|
30
|
+
}
|