@trystero-p2p/torrent 0.23.0 β†’ 0.23.1

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/README.md ADDED
@@ -0,0 +1,1071 @@
1
+ # ✨🀝✨ Trystero
2
+
3
+ **Build instant multiplayer web apps, no server required**
4
+
5
+ πŸ‘‰ **[Try it live on trystero.dev](https://trystero.dev)** πŸ‘ˆ
6
+
7
+ Trystero makes browsers discover each other and communicate directly. No
8
+ accounts. No deploying infrastructure. Just import and connect.
9
+
10
+ Peers can connect via 🌊 BitTorrent, 🐦 Nostr, πŸ“‘ MQTT, ⚑️ Supabase, πŸ”₯Firebase,
11
+ or πŸͺ IPFS – all using the same API.
12
+
13
+ Besides making peer matching automatic, Trystero offers some nice abstractions
14
+ on top of WebRTC:
15
+
16
+ - πŸ‘‚πŸ“£ Rooms / broadcasting
17
+ - πŸ”’πŸ“© Automatic serialization / deserialization of data
18
+ - πŸŽ₯🏷 Attach metadata to binary data and media streams
19
+ - βœ‚οΈβ³ Automatic chunking and throttling of large data
20
+ - ⏱🀞 Progress events and promises for data transfers
21
+ - πŸ”πŸ“ Session data encryption
22
+ - 🏭⚑ Can run peers server-side on Node and Bun
23
+ - βš›οΈπŸͺ React hooks
24
+
25
+ You can see what people are building with Trystero
26
+ [here](https://github.com/jeremyckahn/awesome-trystero).
27
+
28
+ ---
29
+
30
+ ## Contents
31
+
32
+ - [How it works](#how-it-works)
33
+ - [Get started](#get-started)
34
+ - [Listen for events](#listen-for-events)
35
+ - [Broadcast events](#broadcast-events)
36
+ - [Audio and video](#audio-and-video)
37
+ - [Advanced](#advanced)
38
+ - [Binary metadata](#binary-metadata)
39
+ - [Action promises](#action-promises)
40
+ - [Progress updates](#progress-updates)
41
+ - [Encryption](#encryption)
42
+ - [React hooks](#react-hooks)
43
+ - [Troubleshooting connection issues](#troubleshooting-connection-issues)
44
+ - [Running server-side (Node, Bun)](#running-server-side-node-bun)
45
+ - [Write your own strategy](#write-your-own-strategy)
46
+ - [Supabase setup](#supabase-setup)
47
+ - [Firebase setup](#firebase-setup)
48
+ - [API](#api)
49
+ - [`joinRoom(config, roomId, [callbacks])`](#joinroomconfig-roomid-callbacks)
50
+ - [`selfId`](#selfid)
51
+ - [`getRelaySockets()`](#getrelaysockets)
52
+ - [`pauseRelayReconnection()`](#pauserelayreconnection)
53
+ - [`resumeRelayReconnection()`](#resumerelayreconnection)
54
+ - [Which strategy should I choose?](#which-strategy-should-i-choose)
55
+
56
+ ---
57
+
58
+ ## How it works
59
+
60
+ πŸ‘‰ **If you just want to try out Trystero, you can skip this explainer and
61
+ [jump into using it](#get-started).**
62
+
63
+ To establish a direct peer-to-peer connection with WebRTC, a signalling channel
64
+ is needed to exchange peer information
65
+ ([SDP](https://en.wikipedia.org/wiki/Session_Description_Protocol)). Typically
66
+ this involves running your own matchmaking server but Trystero abstracts this
67
+ away for you and offers multiple "serverless" strategies for connecting peers
68
+ (currently BitTorrent, Nostr, MQTT, Supabase, Firebase, and IPFS).
69
+
70
+ The important point to remember is this:
71
+
72
+ > πŸ”’
73
+ >
74
+ > Beyond peer discovery, your app's data never touches the strategy medium and
75
+ > is sent directly peer-to-peer and end-to-end encrypted between users.
76
+ >
77
+ > πŸ‘†
78
+
79
+ You can [compare strategies here](#which-strategy-should-i-choose).
80
+
81
+ ## Get started
82
+
83
+ Install Trystero with your preferred package manager, then import it in your
84
+ code:
85
+
86
+ ```sh
87
+ npm i trystero
88
+ ```
89
+
90
+ ```js
91
+ import {joinRoom} from 'trystero'
92
+ ```
93
+
94
+ No package manager? You can also use a CDN:
95
+
96
+ ```html
97
+ <script type="module">
98
+ import {joinRoom} from 'https://esm.run/trystero'
99
+ </script>
100
+ ```
101
+
102
+ The default Trystero package runs on the Nostr network, but you can swap in any
103
+ other stategy by changing which package you import:
104
+
105
+ ```js
106
+ import {joinRoom} from '@trystero-p2p/mqtt'
107
+ // or
108
+ import {joinRoom} from '@trystero-p2p/torrent'
109
+ // or
110
+ import {joinRoom} from '@trystero-p2p/supabase'
111
+ // or
112
+ import {joinRoom} from '@trystero-p2p/firebase'
113
+ // or
114
+ import {joinRoom} from '@trystero-p2p/ipfs'
115
+ ```
116
+
117
+ Next, join the user to a room with an ID:
118
+
119
+ ```js
120
+ const config = {appId: 'san_narciso_3d'}
121
+ const room = joinRoom(config, 'yoyodyne')
122
+ ```
123
+
124
+ The first argument is a configuration object that requires an `appId`. This
125
+ should be a completely unique identifier for your appΒΉ. The second argument is
126
+ the room ID.
127
+
128
+ > Why rooms? Browsers can only handle a limited amount of WebRTC connections at
129
+ > a time so it's recommended to design your app such that users are divided into
130
+ > groups (or rooms, or namespaces, or channels... whatever you'd like to call
131
+ > them).
132
+
133
+ ΒΉ When using Firebase, `appId` should be your `databaseURL` and when using
134
+ Supabase, it should be your project URL.
135
+
136
+ ## Listen for events
137
+
138
+ Listen for peers joining the room:
139
+
140
+ ```js
141
+ room.onPeerJoin(peerId => console.log(`${peerId} joined`))
142
+ ```
143
+
144
+ Listen for peers leaving the room:
145
+
146
+ ```js
147
+ room.onPeerLeave(peerId => console.log(`${peerId} left`))
148
+ ```
149
+
150
+ Listen for peers sending their audio/video streams:
151
+
152
+ ```js
153
+ room.onPeerStream(
154
+ (stream, peerId) => (peerElements[peerId].video.srcObject = stream)
155
+ )
156
+ ```
157
+
158
+ To unsubscribe from events, leave the room:
159
+
160
+ ```js
161
+ room.leave()
162
+ ```
163
+
164
+ You can access the local user's peer ID by importing `selfId` like so:
165
+
166
+ ```js
167
+ import {selfId} from 'trystero'
168
+
169
+ console.log(`my peer ID is ${selfId}`)
170
+ ```
171
+
172
+ ## Broadcast events
173
+
174
+ Send peers your video stream:
175
+
176
+ ```js
177
+ const stream = await navigator.mediaDevices.getUserMedia({
178
+ audio: true,
179
+ video: true
180
+ })
181
+ room.addStream(stream)
182
+ ```
183
+
184
+ Send and subscribe to custom peer-to-peer actions:
185
+
186
+ ```js
187
+ const [sendDrink, getDrink] = room.makeAction('drink')
188
+
189
+ // buy drink for a friend
190
+ sendDrink({drink: 'negroni', withIce: true}, friendId)
191
+
192
+ // buy round for the house (second argument omitted)
193
+ sendDrink({drink: 'mezcal', withIce: false})
194
+
195
+ // listen for drinks sent to you
196
+ getDrink((data, peerId) =>
197
+ console.log(
198
+ `got a ${data.drink} with${data.withIce ? '' : 'out'} ice from ${peerId}`
199
+ )
200
+ )
201
+ ```
202
+
203
+ If you're using TypeScript, you can add a type hint to the action:
204
+
205
+ ```typescript
206
+ type CursorMove = {x: number; y: number}
207
+
208
+ const [sendCursor, getCursor] = room.makeAction<CursorMove>('cursor-move')
209
+ ```
210
+
211
+ You can also use actions to send binary data, like images:
212
+
213
+ ```js
214
+ const [sendPic, getPic] = room.makeAction('pic')
215
+
216
+ // blobs are automatically handled, as are any form of TypedArray
217
+ canvas.toBlob(blob => sendPic(blob))
218
+
219
+ // binary data is received as raw ArrayBuffers so your handling code should
220
+ // interpret it in a way that makes sense
221
+ getPic(
222
+ (data, peerId) => (imgs[peerId].src = URL.createObjectURL(new Blob([data])))
223
+ )
224
+ ```
225
+
226
+ Let's say we want users to be able to name themselves:
227
+
228
+ ```js
229
+ const idsToNames = {}
230
+ const [sendName, getName] = room.makeAction('name')
231
+
232
+ // tell new peers your name when they connect
233
+ room.onPeerJoin(peerId => sendName('Oedipa', peerId))
234
+
235
+ // listen for peers naming themselves
236
+ getName((name, peerId) => (idsToNames[peerId] = name))
237
+
238
+ // tell all peers at once when your name changes
239
+ nameInput.addEventListener('change', e => sendName(e.target.value))
240
+
241
+ room.onPeerLeave(peerId =>
242
+ console.log(`${idsToNames[peerId] || 'a weird stranger'} left`)
243
+ )
244
+ ```
245
+
246
+ > Actions are smart and handle serialization and chunking for you behind the
247
+ > scenes. This means you can send very large files and whatever data you send
248
+ > will be received on the other side as the same type (a number as a number, a
249
+ > string as a string, an object as an object, binary as binary, etc.).
250
+
251
+ ## Audio and video
252
+
253
+ Here's a simple example of how you could create an audio chatroom:
254
+
255
+ ```js
256
+ // this object can store audio instances for later
257
+ const peerAudios = {}
258
+
259
+ // get a local audio stream from the microphone
260
+ const selfStream = await navigator.mediaDevices.getUserMedia({
261
+ audio: true,
262
+ video: false
263
+ })
264
+
265
+ // send stream to peers currently in the room
266
+ room.addStream(selfStream)
267
+
268
+ // send stream to peers who join later
269
+ room.onPeerJoin(peerId => room.addStream(selfStream, peerId))
270
+
271
+ // handle streams from other peers
272
+ room.onPeerStream((stream, peerId) => {
273
+ // create an audio instance and set the incoming stream
274
+ const audio = new Audio()
275
+ audio.srcObject = stream
276
+ audio.autoplay = true
277
+
278
+ // add the audio to peerAudios object if you want to address it for something
279
+ // later (volume, etc.)
280
+ peerAudios[peerId] = audio
281
+ })
282
+ ```
283
+
284
+ Doing the same with video is similar, just be sure to add incoming streams to
285
+ video elements in the DOM:
286
+
287
+ ```js
288
+ const peerVideos = {}
289
+ const videoContainer = document.getElementById('videos')
290
+
291
+ room.onPeerStream((stream, peerId) => {
292
+ let video = peerVideos[peerId]
293
+
294
+ // if this peer hasn't sent a stream before, create a video element
295
+ if (!video) {
296
+ video = document.createElement('video')
297
+ video.autoplay = true
298
+
299
+ // add video element to the DOM
300
+ videoContainer.appendChild(video)
301
+ }
302
+
303
+ video.srcObject = stream
304
+ peerVideos[peerId] = video
305
+ })
306
+ ```
307
+
308
+ ## Advanced
309
+
310
+ ### Binary metadata
311
+
312
+ Let's say your app supports sending various types of files and you want to
313
+ annotate the raw bytes being sent with metadata about how they should be
314
+ interpreted. Instead of manually adding metadata bytes to the buffer you can
315
+ simply pass a metadata argument in the sender action for your binary payload:
316
+
317
+ ```js
318
+ const [sendFile, getFile] = room.makeAction('file')
319
+
320
+ getFile((data, peerId, metadata) =>
321
+ console.log(
322
+ `got a file (${metadata.name}) from ${peerId} with type ${metadata.type}`,
323
+ data
324
+ )
325
+ )
326
+
327
+ // to send metadata, pass a third argument
328
+ // to broadcast to the whole room, set the second peer ID argument to null
329
+ sendFile(buffer, null, {name: 'The CourierΚΌs Tragedy', type: 'application/pdf'})
330
+ ```
331
+
332
+ ### Action promises
333
+
334
+ Action sender functions return a promise that resolves when they're done
335
+ sending. You can optionally use this to indicate to the user when a large
336
+ transfer is done.
337
+
338
+ ```js
339
+ await sendFile(amplePayload)
340
+ console.log('done sending to all peers')
341
+ ```
342
+
343
+ ### Progress updates
344
+
345
+ Action sender functions also take an optional callback function that will be
346
+ continuously called as the transmission progresses. This can be used for showing
347
+ a progress bar to the sender for large transfers. The callback is called with a
348
+ percentage value between 0 and 1 and the receiving peer's ID:
349
+
350
+ ```js
351
+ sendFile(
352
+ payload,
353
+ // notice the peer target argument for any action sender can be a single peer
354
+ // ID, an array of IDs, or null (meaning send to all peers in the room)
355
+ [peerIdA, peerIdB, peerIdC],
356
+ // metadata, which can also be null if you're only interested in the
357
+ // progress handler
358
+ {filename: 'paranoids.flac'},
359
+ // assuming each peer has a loading bar added to the DOM, its value is
360
+ // updated here
361
+ (percent, peerId) => (loadingBars[peerId].value = percent)
362
+ )
363
+ ```
364
+
365
+ Similarly you can listen for progress events as a receiver like this:
366
+
367
+ ```js
368
+ const [sendFile, getFile, onFileProgress] = room.makeAction('file')
369
+
370
+ onFileProgress((percent, peerId, metadata) =>
371
+ console.log(
372
+ `${percent * 100}% done receiving ${metadata.filename} from ${peerId}`
373
+ )
374
+ )
375
+ ```
376
+
377
+ Notice that any metadata is sent with progress events so you can show the
378
+ receiving user that there is a transfer in progress with perhaps the name of the
379
+ incoming file.
380
+
381
+ Since a peer can send multiple transmissions in parallel, you can also use
382
+ metadata to differentiate between them, e.g. by sending a unique ID.
383
+
384
+ ### Encryption
385
+
386
+ Once peers are connected to each other all of their communications are
387
+ end-to-end encrypted. During the initial connection / discovery process, peers'
388
+ [SDPs](https://en.wikipedia.org/wiki/Session_Description_Protocol) are sent via
389
+ the chosen peering strategy medium. By default the SDP is encrypted using a key
390
+ derived from your app ID and room ID to prevent plaintext session data from
391
+ appearing in logs. This is fine for most use cases, however a relay strategy
392
+ operator can reverse engineer the key using the room and app IDs. A more secure
393
+ option is to pass a `password` parameter in the app configuration object which
394
+ will be used to derive the encryption key:
395
+
396
+ ```js
397
+ joinRoom({appId: 'kinneret', password: 'MuchoMaa$'}, 'w_a_s_t_e__v_i_p')
398
+ ```
399
+
400
+ This is a shared secret that must be known ahead of time and the password must
401
+ match for all peers in the room for them to be able to connect. An example use
402
+ case might be a private chat room where users learn the password via external
403
+ means.
404
+
405
+ ### React hooks
406
+
407
+ Trystero functions are idempotent so they already work out of the box as React
408
+ hooks.
409
+
410
+ Here's a simple example component where each peer syncs their favorite color to
411
+ everyone else:
412
+
413
+ ```jsx
414
+ import {joinRoom} from 'trystero'
415
+ import {useState} from 'react'
416
+
417
+ const trysteroConfig = {appId: 'thurn-und-taxis'}
418
+
419
+ export default function App({roomId}) {
420
+ const room = joinRoom(trysteroConfig, roomId)
421
+ const [sendColor, getColor] = room.makeAction('color')
422
+ const [myColor, setMyColor] = useState('#c0ffee')
423
+ const [peerColors, setPeerColors] = useState({})
424
+
425
+ // whenever new peers join the room, send my color to them:
426
+ room.onPeerJoin(peer => sendColor(myColor, peer))
427
+
428
+ // listen for peers sending their colors and update the state accordingly:
429
+ getColor((color, peer) =>
430
+ setPeerColors(peerColors => ({...peerColors, [peer]: color}))
431
+ )
432
+
433
+ const updateColor = e => {
434
+ const {value} = e.target
435
+
436
+ // when updating my own color, broadcast it to all peers:
437
+ sendColor(value)
438
+ setMyColor(value)
439
+ }
440
+
441
+ return (
442
+ <>
443
+ <h1>Trystero + React</h1>
444
+
445
+ <h2>My color:</h2>
446
+ <input type="color" value={myColor} onChange={updateColor} />
447
+
448
+ <h2>Peer colors:</h2>
449
+ <ul>
450
+ {Object.entries(peerColors).map(([peerId, color]) => (
451
+ <li key={peerId} style={{backgroundColor: color}}>
452
+ {peerId}: {color}
453
+ </li>
454
+ ))}
455
+ </ul>
456
+ </>
457
+ )
458
+ }
459
+ ```
460
+
461
+ Astute readers may notice the above example is simple and doesn't consider if we
462
+ want to change the component's room ID or unmount it. For those scenarios you
463
+ can use this simple `useRoom()` hook that unsubscribes from room events
464
+ accordingly:
465
+
466
+ ```js
467
+ import {joinRoom} from 'trystero'
468
+ import {useEffect, useRef} from 'react'
469
+
470
+ export const useRoom = (roomConfig, roomId) => {
471
+ const roomRef = useRef(joinRoom(roomConfig, roomId))
472
+ const lastRoomIdRef = useRef(roomId)
473
+
474
+ useEffect(() => {
475
+ if (roomId !== lastRoomIdRef.current) {
476
+ roomRef.current.leave()
477
+ roomRef.current = joinRoom(roomConfig, roomId)
478
+ lastRoomIdRef.current = roomId
479
+ }
480
+
481
+ return () => roomRef.current.leave()
482
+ }, [roomConfig, roomId])
483
+
484
+ return roomRef.current
485
+ }
486
+ ```
487
+
488
+ ### Troubleshooting connection issues
489
+
490
+ WebRTC is powerful but some networks simply don't allow direct P2P connections
491
+ using it. If you find that certain user pairings aren't working in Trystero,
492
+ you're likely encountering an issue at the network provider level. To solve this
493
+ you can configure a TURN server which will act as a proxy layer for peers that
494
+ aren't able to connect directly to one another.
495
+
496
+ 1. If you can, confirm that the issue is specific to particular network
497
+ conditions (e.g. user with ISP X cannot connect to a user with ISP Y). If
498
+ other user pairings are working (like those between two browsers on the same
499
+ machine), this likely confirms that Trystero is working correctly.
500
+ 2. Sign up for a TURN service or host your own. There are various hosted TURN
501
+ services you can find online like
502
+ [Cloudflare](https://developers.cloudflare.com/calls/turn/) (which offers a
503
+ free tier with 1,000 GB traffic per month) or
504
+ [Open Relay](https://www.metered.ca/stun-turn). You can also host an open
505
+ source TURN server like [coturn](https://github.com/coturn/coturn),
506
+ [Pion TURN](https://github.com/pion/turn),
507
+ [Violet](https://github.com/paullouisageneau/violet), or
508
+ [eturnal](https://github.com/processone/eturnal). Keep in mind data will only
509
+ go through the TURN server for peers that can't directly connect and will
510
+ still be end-to-end encrypted.
511
+ 3. Once you have a TURN server, configure Trystero with it like this:
512
+ ```js
513
+ const room = joinRoom(
514
+ {
515
+ // ...your app config
516
+ turnConfig: [
517
+ {
518
+ // single string or list of strings of URLs to access TURN server
519
+ urls: ['turn:your-turn-server.ok:1979'],
520
+ username: 'username',
521
+ credential: 'password'
522
+ }
523
+ ]
524
+ },
525
+ 'roomId'
526
+ )
527
+ ```
528
+
529
+ ### Running server-side (Node, Bun)
530
+
531
+ Trystero works outside browsers too, like in Node or Bun. Why would you want to
532
+ run something that helps you avoid servers on a server? One reason is if you
533
+ want an always-on peer which can be useful for remembering the last state of
534
+ data, broadcasting it to new users. Another reason might be to run peers that
535
+ are lighter weight and don't need a full browser running, like an embedded
536
+ device or Raspberry Pi.
537
+
538
+ Running server-side uses the same syntax as in the browser, but you need to
539
+ import a polyfill for WebRTC support:
540
+
541
+ ```js
542
+ import {joinRoom} from 'trystero'
543
+ import {RTCPeerConnection} from 'werift'
544
+
545
+ const room = joinRoom(
546
+ {appId: 'your-app-id', rtcPolyfill: RTCPeerConnection},
547
+ 'your-room-name'
548
+ )
549
+ ```
550
+
551
+ ### Write your own strategy
552
+
553
+ If you want to provide your own signaling backend, you can build a custom
554
+ strategy with `createStrategy`.
555
+
556
+ The example below assumes a WebSocket relay that does simple pub/sub routing:
557
+
558
+ - Client sends
559
+ `{"type": "subscribe" | "unsubscribe" | "publish", "topic", "payload"}`
560
+ - Server broadcasts `{"topic", "payload"}` to subscribers of each topic
561
+
562
+ ```js
563
+ import {createStrategy, selfId, toJson} from '@trystero-p2p/core'
564
+
565
+ export const joinRoom = createStrategy({
566
+ // Define init as a function that returns a promise of your signaling client.
567
+ // Resolve the promise when your client is ready to send messages.
568
+ // You can also return an array of client promises for redundancy.
569
+ // In this case, the client is a single WebSocket.
570
+ init: config =>
571
+ new Promise((resolve, reject) => {
572
+ const ws = new WebSocket(config.relayUrl)
573
+ ws.addEventListener('open', () => resolve(ws), {once: true})
574
+ ws.addEventListener('error', reject, {once: true})
575
+ }),
576
+
577
+ // Subscribe takes 5 arguments:
578
+ // 1. One of the relay clients you defined in init.
579
+ // 2. rootTopic is the channel where peers in a room announce their presence.
580
+ // 3. selfTopic is the current peer's own channel where messages specific to
581
+ // it should flow (i.e. offers and answers from external peers).
582
+ // 4. onMessage is a function that should be called when your relay client
583
+ // gets a message. Call it with the topic, data payload, and a callback
584
+ // function that takes another topic and payload.
585
+ // 5. getOffers is an optional helper for precomputed offers (only needed if
586
+ // the strategy needs to send offers in bulk, like torrents).
587
+ // It should return a cleanup function that unsubscribes
588
+ subscribe: (client, rootTopic, selfTopic, onMessage, _getOffers) => {
589
+ const topics = [rootTopic, selfTopic]
590
+ const onWsMessage = event => {
591
+ const {topic, payload} = JSON.parse(String(event.data))
592
+
593
+ if (!topics.includes(topic)) {
594
+ return
595
+ }
596
+
597
+ onMessage(topic, payload, (peerTopic, signal) =>
598
+ client.send(
599
+ toJson({type: 'publish', topic: peerTopic, payload: signal})
600
+ )
601
+ )
602
+ }
603
+
604
+ client.addEventListener('message', onWsMessage)
605
+ topics.forEach(topic => client.send(toJson({type: 'subscribe', topic})))
606
+
607
+ return () => {
608
+ topics.forEach(topic => client.send(toJson({type: 'unsubscribe', topic})))
609
+ client.removeEventListener('message', onWsMessage)
610
+ }
611
+ },
612
+
613
+ // announce takes a relay client and a rootTopic
614
+ announce: (client, rootTopic) =>
615
+ client.send(
616
+ toJson({
617
+ type: 'publish',
618
+ topic: rootTopic,
619
+ payload: toJson({peerId: selfId})
620
+ })
621
+ )
622
+ })
623
+
624
+ const room = joinRoom(
625
+ {appId: 'my-app-id', relayUrl: 'wss://my-relay.example'},
626
+ 'my-room-id'
627
+ )
628
+ ```
629
+
630
+ ### Supabase setup
631
+
632
+ To use the Supabase strategy:
633
+
634
+ 1. Create a [Supabase](https://supabase.com) project or use an existing one
635
+ 2. On the dashboard, go to Project Settings -> API
636
+ 3. Copy the Project URL and set that as the `appId` in the Trystero config, copy
637
+ the `anon public` API key and set it as `supabaseKey` in the Trystero config
638
+
639
+ ### Firebase setup
640
+
641
+ If you want to use the Firebase strategy and don't have an existing project:
642
+
643
+ 1. Create a [Firebase](https://firebase.google.com/) project
644
+ 2. Create a new Realtime Database
645
+ 3. Copy the `databaseURL` and use it as the `appId` in your Trystero config
646
+
647
+ <details>
648
+ <summary>
649
+ Optional: configure the database with security rules to limit activity:
650
+ </summary>
651
+
652
+ ```json
653
+ {
654
+ "rules": {
655
+ ".read": false,
656
+ ".write": false,
657
+ "__trystero__": {
658
+ ".read": false,
659
+ ".write": false,
660
+ "$room_id": {
661
+ ".read": true,
662
+ ".write": true
663
+ }
664
+ }
665
+ }
666
+ }
667
+ ```
668
+
669
+ These rules ensure room peer presence is only readable if the room namespace is
670
+ known ahead of time.
671
+
672
+ </details>
673
+
674
+ ## API
675
+
676
+ ### `joinRoom(config, roomId, [callbacks])`
677
+
678
+ Adds local user to room whereby other peers in the same namespace will open
679
+ communication channels and send events. Calling `joinRoom()` multiple times with
680
+ the same namespace will return the same room instance.
681
+
682
+ - `config` - Configuration object containing the following keys:
683
+ - `appId` - **(required)** A unique string identifying your app. When using
684
+ Supabase, this should be set to your project URL (see
685
+ [Supabase setup instructions](#supabase-setup)). If using Firebase, this
686
+ should be the `databaseURL` from your Firebase config (also see
687
+ `firebaseApp` below for an alternative way of configuring the Firebase
688
+ strategy).
689
+
690
+ - `password` - **(optional)** A string to encrypt session descriptions via
691
+ AES-GCM as they are passed through the peering medium. If not set, session
692
+ descriptions will be encrypted with a key derived from the app ID and room
693
+ name. A custom password must match between any peers in the room for them to
694
+ connect. See [encryption](#encryption) for more details.
695
+
696
+ - `relayUrls` - **(optional, 🌊 BitTorrent, 🐦 Nostr, πŸ“‘ MQTT only)** Custom
697
+ list of URLs for the strategy to use to bootstrap P2P connections. These
698
+ would be BitTorrent trackers, Nostr relays, and MQTT brokers, respectively.
699
+ They must support secure WebSocket connections.
700
+
701
+ - `relayRedundancy` - **(optional, 🌊 BitTorrent, 🐦 Nostr, πŸ“‘ MQTT only)**
702
+ Integer specifying how many relay endpoints to connect to simultaneously.
703
+ Passing a `relayUrls` option will cause this option to be ignored as the
704
+ entire list will be used.
705
+
706
+ - `rtcConfig` - **(optional)** Specifies a custom
707
+ [`RTCConfiguration`](https://developer.mozilla.org/en-US/docs/Web/API/RTCConfiguration)
708
+ for all peer connections.
709
+
710
+ - `trickleIce` - **(optional)** Boolean controlling whether ICE candidates are
711
+ sent incrementally (`true`) or bundled with SDP (`false`). Default is
712
+ strategy-dependent: `true` for most strategies, `false` for BitTorrent and
713
+ IPFS unless explicitly set.
714
+
715
+ - `turnConfig` - **(optional)** Specifies a custom list of TURN servers to use
716
+ (see
717
+ [Troubleshooting connection issues](#troubleshooting-connection-issues)).
718
+ Each item in the list should correspond to an
719
+ [ICE server config object](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection#iceservers).
720
+ When passing a TURN config like this, Trystero's default STUN servers will
721
+ also be used. To override this and use both custom STUN and TURN servers,
722
+ instead pass the config via the above `rtcConfig.iceServers` option as a
723
+ list of both STUN/TURN servers β€” this won't inherit Trystero's defaults.
724
+
725
+ - `rtcPolyfill` - **(optional)** Use this to pass a custom
726
+ [`RTCPeerConnection`](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection)-compatible
727
+ constructor. This is useful for running outside of a browser, such as in
728
+ Node (still experimental).
729
+
730
+ - `supabaseKey` - **(required, ⚑️ Supabase only)** Your Supabase project's
731
+ `anon public` API key.
732
+
733
+ - `firebaseApp` - **(optional, πŸ”₯ Firebase only)** You can pass an already
734
+ initialized Firebase app instance instead of an `appId`. Normally Trystero
735
+ will initialize a Firebase app based on the `appId` but this will fail if
736
+ you've already initialized it for use elsewhere.
737
+
738
+ - `rootPath` - **(optional, πŸ”₯ Firebase only)** String specifying path where
739
+ Trystero writes its matchmaking data in your database (`'__trystero__'` by
740
+ default). Changing this is useful if you want to run multiple apps using the
741
+ same database and don't want to worry about namespace collisions.
742
+
743
+ - `manualRelayReconnection` - **(optional, 🐦 Nostr and 🌊 BitTorrent only)**
744
+ Boolean (default: `false`) that when set to `true` disables automatically
745
+ pausing and resuming reconnection attempts when the browser goes offline and
746
+ comes back online. This is useful if you want to manage this behavior
747
+ yourself.
748
+
749
+ - `roomId` - A string to namespace peers and events within a room.
750
+
751
+ - `callbacks` - **(optional)** Callback config object containing:
752
+ - `onJoinError(details)` - Called when room join fails due to an incorrect
753
+ password or when handshake admission fails (including timeout). `details` is
754
+ an object containing `appId`, `roomId`, `peerId`, and `error` describing the
755
+ failure.
756
+
757
+ - `onPeerHandshake(peerId, send, receive, isInitiator)` - Async predicate that
758
+ runs after the transport connects but before the peer becomes active.
759
+ Return/resolve to accept the peer, throw/reject to deny the peer.
760
+ - `peerId` - ID of the pending peer.
761
+ - `send(data, [metadata])` - Sends handshake payloads to the pending peer.
762
+ - `receive()` - Resolves to the next handshake message from the peer as
763
+ `{data, metadata}`.
764
+ - `isInitiator` - Deterministic role flag for avoiding protocol deadlocks.
765
+
766
+ - `handshakeTimeoutMs` - Timeout for pending handshakes in milliseconds
767
+ (`10000` by default). If exceeded, the peer is denied and `onJoinError` is
768
+ called.
769
+
770
+ During handshake, the peer remains pending and is not included in `getPeers()`
771
+ and does not trigger Trystero API events (`onPeerJoin`, action receivers,
772
+ stream/track callbacks). Non-handshake data received while pending is dropped.
773
+
774
+ Minimal handshake example:
775
+
776
+ ```js
777
+ import {joinRoom} from 'trystero'
778
+
779
+ const room = joinRoom({appId: 'my-app'}, 'secure-room', {
780
+ onPeerHandshake: async (_, send, receive, isInitiator) => {
781
+ if (isInitiator) {
782
+ await send({challenge: 'prove-you-know-the-secret'})
783
+ const {data} = await receive()
784
+
785
+ if (data?.response !== 'shared-secret') {
786
+ throw new Error('handshake rejected')
787
+ }
788
+ } else {
789
+ const {data} = await receive()
790
+
791
+ if (data?.challenge !== 'prove-you-know-the-secret') {
792
+ throw new Error('handshake rejected')
793
+ }
794
+
795
+ await send({response: 'shared-secret'})
796
+ }
797
+ }
798
+ })
799
+ ```
800
+
801
+ Returns an object with the following methods:
802
+
803
+ - ### `leave()`
804
+
805
+ Remove local user from room and unsubscribe from room events.
806
+
807
+ - ### `getPeers()`
808
+
809
+ Returns a map of
810
+ [`RTCPeerConnection`](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection)s
811
+ for the peers present in room (not including the local user). The keys of this
812
+ object are the respective peers' IDs.
813
+
814
+ - ### `addStream(stream, [targetPeers], [metadata])`
815
+
816
+ Broadcasts media stream to other peers.
817
+ - `stream` - A `MediaStream` with audio and/or video to send to peers in the
818
+ room.
819
+
820
+ - `targetPeers` - **(optional)** If specified, the stream is sent only to the
821
+ target peer ID (string) or list of peer IDs (array).
822
+
823
+ - `metadata` - **(optional)** Additional metadata (any serializable type) to
824
+ be sent with the stream. This is useful when sending multiple streams so
825
+ recipients know which is which (e.g. a webcam versus a screen capture). If
826
+ you want to broadcast a stream to all peers in the room with a metadata
827
+ argument, pass `null` as the second argument.
828
+
829
+ - ### `removeStream(stream, [targetPeers])`
830
+
831
+ Stops sending previously sent media stream to other peers.
832
+ - `stream` - A previously sent `MediaStream` to stop sending.
833
+
834
+ - `targetPeers` - **(optional)** If specified, the stream is removed only from
835
+ the target peer ID (string) or list of peer IDs (array).
836
+
837
+ - ### `addTrack(track, stream, [targetPeers], [metadata])`
838
+
839
+ Adds a new media track to a stream.
840
+ - `track` - A `MediaStreamTrack` to add to an existing stream.
841
+
842
+ - `stream` - The target `MediaStream` to attach the new track to.
843
+
844
+ - `targetPeers` - **(optional)** If specified, the track is sent only to the
845
+ target peer ID (string) or list of peer IDs (array).
846
+
847
+ - `metadata` - **(optional)** Additional metadata (any serializable type) to
848
+ be sent with the track. See `metadata` notes for `addStream()` above for
849
+ more details.
850
+
851
+ - ### `removeTrack(track, [targetPeers])`
852
+
853
+ Removes a media track.
854
+ - `track` - The `MediaStreamTrack` to remove.
855
+
856
+ - `targetPeers` - **(optional)** If specified, the track is removed only from
857
+ the target peer ID (string) or list of peer IDs (array).
858
+
859
+ - ### `replaceTrack(oldTrack, newTrack, [targetPeers], [metadata])`
860
+
861
+ Replaces a media track with a new one.
862
+ - `oldTrack` - The `MediaStreamTrack` to remove.
863
+
864
+ - `newTrack` - A `MediaStreamTrack` to attach.
865
+
866
+ - `targetPeers` - **(optional)** If specified, the track is replaced only for
867
+ the target peer ID (string) or list of peer IDs (array).
868
+
869
+ - `metadata` - **(optional)** Additional metadata (any serializable type) to
870
+ be sent with the replacement track.
871
+
872
+ - ### `onPeerJoin(callback)`
873
+
874
+ Registers a callback function that will be called when a peer joins the room.
875
+ If called more than once, only the latest callback registered is ever called.
876
+ Existing active peers are immediately replayed to a newly registered callback.
877
+ - `callback(peerId)` - Function to run whenever a peer joins, called with the
878
+ peer's ID.
879
+
880
+ Example:
881
+
882
+ ```js
883
+ onPeerJoin(peerId => console.log(`${peerId} joined`))
884
+ ```
885
+
886
+ - ### `onPeerLeave(callback)`
887
+
888
+ Registers a callback function that will be called when a peer leaves the room.
889
+ If called more than once, only the latest callback registered is ever called.
890
+ - `callback(peerId)` - Function to run whenever a peer leaves, called with the
891
+ peer's ID.
892
+
893
+ Example:
894
+
895
+ ```js
896
+ onPeerLeave(peerId => console.log(`${peerId} left`))
897
+ ```
898
+
899
+ - ### `onPeerStream(callback)`
900
+
901
+ Registers a callback function that will be called when a peer sends a media
902
+ stream. If called more than once, only the latest callback registered is ever
903
+ called.
904
+ - `callback(stream, peerId, metadata)` - Function to run whenever a peer sends
905
+ a media stream, called with the the peer's stream, ID, and optional metadata
906
+ (see `addStream()` above for details).
907
+
908
+ Example:
909
+
910
+ ```js
911
+ onPeerStream((stream, peerId) =>
912
+ console.log(`got stream from ${peerId}`, stream)
913
+ )
914
+ ```
915
+
916
+ - ### `onPeerTrack(callback)`
917
+
918
+ Registers a callback function that will be called when a peer sends a media
919
+ track. If called more than once, only the latest callback registered is ever
920
+ called.
921
+ - `callback(track, stream, peerId, metadata)` - Function to run whenever a
922
+ peer sends a media track, called with the the peer's track, attached stream,
923
+ ID, and optional metadata (see `addTrack()` above for details).
924
+
925
+ Example:
926
+
927
+ ```js
928
+ onPeerTrack((track, stream, peerId) =>
929
+ console.log(`got track from ${peerId}`, track)
930
+ )
931
+ ```
932
+
933
+ - ### `makeAction(actionId)`
934
+
935
+ Listen for and send custom data actions.
936
+ - `actionId` - A string to register this action consistently among all peers.
937
+
938
+ Returns an array of three functions:
939
+ 1. #### Sender
940
+ - Sends data to peers and returns a promise that resolves when all target
941
+ peers are finished sending locally.
942
+
943
+ - `(data, [targetPeers], [metadata], [onProgress])`
944
+ - `data` - Any value to send (primitive, object, binary). Serialization
945
+ and chunking is handled automatically. Binary data (e.g. `Blob`,
946
+ `TypedArray`) is received by other peer as an agnostic `ArrayBuffer`.
947
+
948
+ - `targetPeers` - **(optional)** Either a peer ID (string), an array of
949
+ peer IDs, or `null` (indicating to send to all peers in the room).
950
+
951
+ - `metadata` - **(optional)** If the data is binary, you can send an
952
+ optional metadata object describing it (see
953
+ [Binary metadata](#binary-metadata)).
954
+
955
+ - `onProgress` - **(optional)** A callback function that will be called
956
+ as every chunk for every peer is transmitted. The function will be
957
+ called with a value between 0 and 1 and a peer ID. See
958
+ [Progress updates](#progress-updates) for an example.
959
+
960
+ 2. #### Receiver
961
+ - Registers a callback function that runs when data for this action is
962
+ received from other peers.
963
+
964
+ - `(data, peerId, metadata)`
965
+ - `data` - The value transmitted by the sending peer. Deserialization is
966
+ handled automatically, i.e. a number will be received as a number, an
967
+ object as an object, etc.
968
+
969
+ - `peerId` - The ID string of the sending peer.
970
+
971
+ - `metadata` - **(optional)** Optional metadata object supplied by the
972
+ sender if `data` is binary, e.g. a filename.
973
+
974
+ 3. #### Progress handler
975
+ - Registers a callback function that runs when partial data is received
976
+ from peers. You can use this for tracking large binary transfers. See
977
+ [Progress updates](#progress-updates) for an example.
978
+
979
+ - `(percent, peerId, metadata)`
980
+ - `percent` - A number between 0 and 1 indicating the percentage complete
981
+ of the transfer.
982
+
983
+ - `peerId` - The ID string of the sending peer.
984
+
985
+ - `metadata` - **(optional)** Optional metadata object supplied by the
986
+ sender.
987
+
988
+ Example:
989
+
990
+ ```js
991
+ const [sendCursor, getCursor] = room.makeAction('cursormove')
992
+
993
+ window.addEventListener('mousemove', e => sendCursor([e.clientX, e.clientY]))
994
+
995
+ getCursor(([x, y], peerId) => {
996
+ const peerCursor = cursorMap[peerId]
997
+ peerCursor.style.left = x + 'px'
998
+ peerCursor.style.top = y + 'px'
999
+ })
1000
+ ```
1001
+
1002
+ - ### `ping(peerId)`
1003
+
1004
+ Takes a peer ID and returns a promise that resolves to the milliseconds the
1005
+ round-trip to that peer took. Use this for measuring latency.
1006
+ - `peerId` - Peer ID string of the target peer.
1007
+
1008
+ Example:
1009
+
1010
+ ```js
1011
+ // log round-trip time every 2 seconds
1012
+ room.onPeerJoin(peerId =>
1013
+ setInterval(
1014
+ async () => console.log(`took ${await room.ping(peerId)}ms`),
1015
+ 2000
1016
+ )
1017
+ )
1018
+ ```
1019
+
1020
+ ### `selfId`
1021
+
1022
+ A unique ID string other peers will know the local user as globally across
1023
+ rooms.
1024
+
1025
+ ### `getRelaySockets()`
1026
+
1027
+ **(🌊 BitTorrent, 🐦 Nostr, πŸ“‘ MQTT only)** Returns an object of relay URL keys
1028
+ mapped to their WebSocket connections. This can be useful for determining the
1029
+ state of the user's connection to the relays and handling any connection
1030
+ failures.
1031
+
1032
+ Example:
1033
+
1034
+ ```js
1035
+ import {getRelaySockets} from '@trystero-p2p/torrent'
1036
+
1037
+ console.log(getRelaySockets())
1038
+ // => Object {
1039
+ // "wss://tracker.webtorrent.dev": WebSocket,
1040
+ // "wss://tracker.openwebtorrent.com": WebSocket
1041
+ // }
1042
+ ```
1043
+
1044
+ ### `pauseRelayReconnection()`
1045
+
1046
+ **(🐦 Nostr, 🌊 BitTorrent only)** Normally Trystero will try to automatically
1047
+ reconnect to relay sockets unless `manualRelayReconnection: true` is set in the
1048
+ room config. Calling this function stops relay reconnection attempts until
1049
+ `resumeRelayReconnection()` is called.
1050
+
1051
+ ### `resumeRelayReconnection()`
1052
+
1053
+ **(🐦 Nostr, 🌊 BitTorrent only)** Allows relay reconnection attempts to resume.
1054
+ (See `pauseRelayReconnection()` above).
1055
+
1056
+ ## Which strategy should I choose?
1057
+
1058
+ By default Trystero uses the Nostr network which is highly decentralized with
1059
+ hundreds of active relays running. This is a good choice if you're interested in
1060
+ decentralization and high redundancy. The other decentralized strategies are
1061
+ recommended in the order of MQTT, BitTorrent, and IPFS, based on robustness.
1062
+ These networks have far less relay redundancy than Nostr, but you might prefer
1063
+ them for other reasons. You can of course host your own relay server for any of
1064
+ these strategies.
1065
+
1066
+ For a middleground between using public relays and self-hosting, the built-in
1067
+ Supabase and Firebase strategies are a good option.
1068
+
1069
+ ---
1070
+
1071
+ Trystero by [Dan Motzenbecker](https://oxism.com)
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;KA+CY,iBAAA,GAAoB,cAAA,GAAiB,WAAA;AAAA,cAoVpC,QAAA,EAAU,QAAA,CAAS,iBAAA;AAAA,cAcnB,eAAA;AAAA,cAIA,gBAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;KA+CY,iBAAA,GAAoB,cAAA,GAAiB,WAAA;AAAA,cA6VpC,QAAA,EAAU,QAAA,CAAS,iBAAA;AAAA,cAcnB,eAAA;AAAA,cAIA,gBAAA"}
package/dist/index.mjs CHANGED
@@ -135,18 +135,21 @@ const joinRoomStrategy = createStrategy({
135
135
  roomSubscriberCounts[rootTopic] = (roomSubscriberCounts[rootTopic] ?? 0) + 1;
136
136
  const topicHandler = (data) => {
137
137
  if (data.offer && data.peer_id && data.offer_id) onMessage(rootTopic, {
138
- offer: data.offer,
138
+ offer: data.offer.sdp,
139
139
  peerId: data.peer_id,
140
140
  hasOutgoingOffer: keys(getRoomOutstandingOffers(rootTopic)).length > 0
141
141
  }, (_, signal) => void send(client, rootTopic, {
142
- answer: fromJson(signal)["answer"],
142
+ answer: {
143
+ type: "answer",
144
+ sdp: fromJson(signal).answer
145
+ },
143
146
  offer_id: data.offer_id,
144
147
  to_peer_id: data.peer_id
145
148
  }));
146
149
  else if (data.answer && data.offer_id && data.peer_id) {
147
150
  const offer = claimOutstandingOffer(rootTopic, data.offer_id);
148
151
  if (offer) onMessage(rootTopic, {
149
- answer: data.answer,
152
+ answer: data.answer.sdp,
150
153
  peerId: data.peer_id,
151
154
  peer: offer.peer
152
155
  }, () => {});
@@ -159,7 +162,10 @@ const joinRoomStrategy = createStrategy({
159
162
  numwant: offerPoolSize,
160
163
  offers: entries(await ensureOutstandingOffers(rootTopic, getOffers)).map(([id, { offer }]) => ({
161
164
  offer_id: id,
162
- offer
165
+ offer: {
166
+ type: "offer",
167
+ sdp: offer
168
+ }
163
169
  }))
164
170
  });
165
171
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import {\n createRelayManager,\n createStrategy,\n entries,\n fromJson,\n genId,\n getRelays,\n keys,\n libName,\n makeSocket,\n pauseRelayReconnection,\n resumeRelayReconnection,\n selfId,\n sha1,\n toJson,\n type BaseRoomConfig,\n type JoinRoom,\n type OfferRecord,\n type RelayConfig,\n type SocketClient\n} from '@trystero-p2p/core'\n\nconst relayManager = createRelayManager<SocketClient>(client => client.socket)\nconst topicToInfoHash: Record<string, string> = {}\nconst infoHashToTopic: Record<string, string> = {}\nconst announceIntervals = relayManager.scoped<ReturnType<typeof setInterval>>()\nconst announceFns = relayManager.scoped<() => void | Promise<void>>()\nconst subscriptionTokens = relayManager.scoped<symbol>()\nconst trackerAnnounceMs: Record<string, number> = {}\nconst handledSignals: Record<string, number> = {}\nconst msgHandlers = relayManager.scoped<(data: TrackerMessage) => void>()\nconst roomOutstandingOffers: Record<\n string,\n Record<string, OfferRecord & {createdAt: number}>\n> = {}\nconst roomOfferGenerationPromises: Record<string, Promise<void> | undefined> =\n {}\nconst roomSubscriberCounts: Record<string, number> = {}\nconst trackerAction = 'announce'\nconst hashLimit = 20\nconst offerPoolSize = 3\nconst defaultAnnounceMs = 10_000\nconst maxAnnounceMs = 20_000\nconst offerRetentionMs = 120_000\nconst signalDedupeWindowMs = 4_000\nconst defaultRedundancy = 3\n\nexport type TorrentRoomConfig = BaseRoomConfig & RelayConfig\n\ntype TrackerMessage = {\n offer?: unknown\n answer?: unknown\n offer_id?: string\n peer_id?: string\n info_hash?: string\n interval?: number\n ['failure reason']?: string\n ['warning message']?: string\n}\n\nconst getInfoHash = async (topic: string): Promise<string> => {\n if (topicToInfoHash[topic]) {\n return topicToInfoHash[topic]\n }\n\n const hash = (await sha1(topic)).slice(0, hashLimit)\n topicToInfoHash[topic] = hash\n infoHashToTopic[hash] = topic\n\n return hash\n}\n\nconst send = async (\n client: SocketClient,\n topic: string,\n payload: Record<string, unknown>\n): Promise<void> =>\n client.send(\n toJson({\n action: trackerAction,\n info_hash: await getInfoHash(topic),\n peer_id: selfId,\n ...payload\n })\n )\n\nconst warn = (url: string, msg: string, didFail = false): void =>\n console.warn(\n `${libName}: torrent tracker ${didFail ? 'failure' : 'warning'} from ${url} - ${msg}`\n )\n\nconst getRoomOutstandingOffers = (\n rootTopic: string\n): Record<string, OfferRecord & {createdAt: number}> =>\n (roomOutstandingOffers[rootTopic] ??= {})\n\nconst deleteRoomOfferBookkeeping = (rootTopic: string): void => {\n delete roomOutstandingOffers[rootTopic]\n delete roomOfferGenerationPromises[rootTopic]\n}\n\nconst claimOutstandingOffer = (\n rootTopic: string,\n offerId: string\n): OfferRecord | undefined => {\n const outstandingOffers = roomOutstandingOffers[rootTopic]\n const offer = outstandingOffers?.[offerId]\n\n if (!offer) {\n return\n }\n\n delete outstandingOffers[offerId]\n offer.claim?.()\n\n if (!keys(outstandingOffers).length && !roomSubscriberCounts[rootTopic]) {\n deleteRoomOfferBookkeeping(rootTopic)\n }\n\n return offer\n}\n\nconst reclaimOutstandingOffer = (rootTopic: string, offerId: string): void => {\n const outstandingOffers = roomOutstandingOffers[rootTopic]\n const offer = outstandingOffers?.[offerId]\n\n if (!offer) {\n return\n }\n\n delete outstandingOffers[offerId]\n offer.reclaim?.()\n\n if (!keys(outstandingOffers).length && !roomSubscriberCounts[rootTopic]) {\n deleteRoomOfferBookkeeping(rootTopic)\n }\n}\n\nconst reclaimAllOutstandingOffers = (rootTopic: string): void => {\n keys(getRoomOutstandingOffers(rootTopic)).forEach(offerId =>\n reclaimOutstandingOffer(rootTopic, offerId)\n )\n deleteRoomOfferBookkeeping(rootTopic)\n}\n\nconst pruneOutstandingOffers = (rootTopic: string): void => {\n const now = Date.now()\n\n entries(getRoomOutstandingOffers(rootTopic)).forEach(([offerId, offer]) => {\n if (now - offer.createdAt > offerRetentionMs) {\n reclaimOutstandingOffer(rootTopic, offerId)\n }\n })\n}\n\nconst ensureOutstandingOffers = async (\n rootTopic: string,\n getOffers: (n: number) => Promise<OfferRecord[]>\n): Promise<Record<string, OfferRecord & {createdAt: number}>> => {\n while (roomOfferGenerationPromises[rootTopic]) {\n await roomOfferGenerationPromises[rootTopic]\n }\n\n const nextPromise = (async () => {\n pruneOutstandingOffers(rootTopic)\n\n const outstandingOffers = getRoomOutstandingOffers(rootTopic)\n const outstandingCount = keys(outstandingOffers).length\n const missingOffers = Math.max(0, offerPoolSize - outstandingCount)\n\n if (missingOffers > 0) {\n ;(await getOffers(missingOffers)).forEach(peerAndOffer => {\n outstandingOffers[genId(hashLimit)] = {\n ...peerAndOffer,\n createdAt: Date.now()\n }\n })\n }\n })().finally(() => {\n if (roomOfferGenerationPromises[rootTopic] === nextPromise) {\n delete roomOfferGenerationPromises[rootTopic]\n }\n })\n\n roomOfferGenerationPromises[rootTopic] = nextPromise\n await nextPromise\n\n return getRoomOutstandingOffers(rootTopic)\n}\n\nconst joinRoomStrategy: JoinRoom<TorrentRoomConfig> = createStrategy({\n init: config =>\n getRelays(config, defaultRelayUrls, defaultRedundancy).map(rawUrl => {\n const client = relayManager.register(\n rawUrl,\n makeSocket(rawUrl, rawData => {\n const data = fromJson<TrackerMessage>(rawData)\n const errMsg = data['failure reason']\n const warnMsg = data['warning message']\n const {interval} = data\n const topic = data.info_hash\n ? infoHashToTopic[data.info_hash]\n : undefined\n\n if (errMsg) {\n warn(client.url, errMsg, true)\n return\n }\n\n if (warnMsg) {\n warn(client.url, warnMsg)\n }\n\n if (\n interval &&\n interval * 1000 >\n (trackerAnnounceMs[client.url] ?? defaultAnnounceMs) &&\n topic &&\n announceFns.forKey(rawUrl)[topic]\n ) {\n const nextInterval = Math.min(interval * 1000, maxAnnounceMs)\n const relayIntervals = announceIntervals.forKey(rawUrl)\n const relayFns = announceFns.forKey(rawUrl)\n\n if (relayIntervals[topic]) {\n clearInterval(relayIntervals[topic])\n }\n trackerAnnounceMs[client.url] = nextInterval\n const relayFn = relayFns[topic]\n\n if (relayFn) {\n relayIntervals[topic] = setInterval(() => {\n void relayFn()\n }, nextInterval)\n }\n }\n\n if ((data.offer || data.answer) && topic && data.offer_id) {\n if (data.peer_id === selfId) {\n return\n }\n\n const signalType = data.offer ? 'offer' : 'answer'\n const signalKey = `${topic}:${signalType}:${data.offer_id}:${data.peer_id ?? ''}`\n const nowMs = Date.now()\n const lastHandledMs = handledSignals[signalKey]\n\n if (\n typeof lastHandledMs === 'number' &&\n nowMs - lastHandledMs < signalDedupeWindowMs\n ) {\n return\n }\n\n handledSignals[signalKey] = nowMs\n\n entries(handledSignals).forEach(([key, handledAtMs]) => {\n if (nowMs - handledAtMs > signalDedupeWindowMs * 6) {\n delete handledSignals[key]\n }\n })\n\n msgHandlers.forKey(rawUrl)[topic]?.(data)\n }\n })\n )\n\n return client.ready\n }),\n\n subscribe: (client, rootTopic, _, onMessage, getOffers) => {\n const handlers = msgHandlers.forRelay(client)\n const relayFns = announceFns.forRelay(client)\n const relayIntervals = announceIntervals.forRelay(client)\n const activeTokens = subscriptionTokens.forRelay(client)\n const subscriptionToken = Symbol(rootTopic)\n\n activeTokens[rootTopic] = subscriptionToken\n roomSubscriberCounts[rootTopic] = (roomSubscriberCounts[rootTopic] ?? 0) + 1\n\n const topicHandler = (data: TrackerMessage): void => {\n if (data.offer && data.peer_id && data.offer_id) {\n void onMessage(\n rootTopic,\n {\n offer: data.offer,\n peerId: data.peer_id,\n hasOutgoingOffer:\n keys(getRoomOutstandingOffers(rootTopic)).length > 0\n },\n (_, signal) =>\n void send(client, rootTopic, {\n answer: fromJson<Record<string, unknown>>(signal)['answer'],\n offer_id: data.offer_id,\n to_peer_id: data.peer_id\n })\n )\n } else if (data.answer && data.offer_id && data.peer_id) {\n const offer = claimOutstandingOffer(rootTopic, data.offer_id)\n\n if (offer) {\n void onMessage(\n rootTopic,\n {\n answer: data.answer,\n peerId: data.peer_id,\n peer: offer.peer\n },\n () => {}\n )\n }\n }\n }\n\n handlers[rootTopic] = topicHandler\n\n const announce = async (): Promise<void> => {\n if (activeTokens[rootTopic] !== subscriptionToken) {\n return\n }\n\n const outstandingOffers = await ensureOutstandingOffers(\n rootTopic,\n getOffers\n )\n const offers = entries(outstandingOffers).map(([id, {offer}]) => ({\n offer_id: id,\n offer\n }))\n\n void send(client, rootTopic, {\n numwant: offerPoolSize,\n offers\n })\n }\n\n trackerAnnounceMs[client.url] = defaultAnnounceMs\n relayFns[rootTopic] = announce\n relayIntervals[rootTopic] = setInterval(\n announce,\n trackerAnnounceMs[client.url]\n )\n void announce()\n\n return () => {\n roomSubscriberCounts[rootTopic] = Math.max(\n 0,\n (roomSubscriberCounts[rootTopic] ?? 1) - 1\n )\n\n if (!roomSubscriberCounts[rootTopic]) {\n delete roomSubscriberCounts[rootTopic]\n }\n\n if (activeTokens[rootTopic] !== subscriptionToken) {\n if (!roomSubscriberCounts[rootTopic]) {\n reclaimAllOutstandingOffers(rootTopic)\n }\n\n return\n }\n\n const interval = relayIntervals[rootTopic]\n if (interval) {\n clearInterval(interval)\n delete relayIntervals[rootTopic]\n }\n\n if (handlers[rootTopic] === topicHandler) {\n delete handlers[rootTopic]\n }\n\n if (relayFns[rootTopic] === announce) {\n delete relayFns[rootTopic]\n }\n\n delete activeTokens[rootTopic]\n\n if (!roomSubscriberCounts[rootTopic]) {\n reclaimAllOutstandingOffers(rootTopic)\n }\n }\n },\n\n announce: client => trackerAnnounceMs[client.url]\n})\n\nexport const joinRoom: JoinRoom<TorrentRoomConfig> = (\n config,\n roomId,\n callbacks\n) =>\n joinRoomStrategy(\n {\n ...config,\n trickleIce: config.trickleIce ?? false\n },\n roomId,\n callbacks\n )\n\nexport const getRelaySockets = relayManager.getSockets\n\nexport {pauseRelayReconnection, resumeRelayReconnection, selfId}\n\nexport const defaultRelayUrls = [\n 'tracker.webtorrent.dev',\n 'tracker.openwebtorrent.com',\n 'tracker.btorrent.xyz',\n 'tracker.files.fm:7073/announce'\n].map(url => 'wss://' + url)\n\nexport type * from '@trystero-p2p/core'\n"],"mappings":";;AAsBA,MAAM,eAAe,oBAAiC,WAAU,OAAO,OAAO;AAC9E,MAAM,kBAA0C,EAAE;AAClD,MAAM,kBAA0C,EAAE;AAClD,MAAM,oBAAoB,aAAa,QAAwC;AAC/E,MAAM,cAAc,aAAa,QAAoC;AACrE,MAAM,qBAAqB,aAAa,QAAgB;AACxD,MAAM,oBAA4C,EAAE;AACpD,MAAM,iBAAyC,EAAE;AACjD,MAAM,cAAc,aAAa,QAAwC;AACzE,MAAM,wBAGF,EAAE;AACN,MAAM,8BACJ,EAAE;AACJ,MAAM,uBAA+C,EAAE;AACvD,MAAM,gBAAgB;AACtB,MAAM,YAAY;AAClB,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AACtB,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AAC7B,MAAM,oBAAoB;AAe1B,MAAM,cAAc,OAAO,UAAmC;AAC5D,KAAI,gBAAgB,OAClB,QAAO,gBAAgB;CAGzB,MAAM,QAAQ,MAAM,KAAK,MAAM,EAAE,MAAM,GAAG,UAAU;AACpD,iBAAgB,SAAS;AACzB,iBAAgB,QAAQ;AAExB,QAAO;;AAGT,MAAM,OAAO,OACX,QACA,OACA,YAEA,OAAO,KACL,OAAO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AQ,KAAK;KACb,QAAQ,KAAK;KACb,MAAM,MAAM;KACb,QACK,GACP;;;AAKP,WAAS,aAAa;EAEtB,MAAM,WAAW,YAA2B;AAC1C,OAAI,aAAa,eAAe,kBAC9B;AAYG,QAAK,QAAQ,WAAW;IAC3B,SAAS;IACT,QAPa,QAJW,MAAM,wBAC9B,WACA,UACD,CACwC,CAAC,KAAK,CAAC,IAAI,EAAC,cAAa;KAChE,UAAU;KACV;KACD,EAAE;IAKF,CAAC;;AAGJ,oBAAkB,OAAO,OAAO;AAChC,WAAS,aAAa;AACtB,iBAAe,aAAa,YAC1B,UACA,kBAAkB,OAAO,KAC1B;AACI,YAAU;AAEf,eAAa;AACX,wBAAqB,aAAa,KAAK,IACrC,IACC,qBAAqB,cAAc,KAAK,EAC1C;AAED,OAAI,CAAC,qBAAqB,WACxB,QAAO,qBAAqB;AAG9B,OAAI,aAAa,eAAe,mBAAmB;AACjD,QAAI,CAAC,qBAAqB,WACxB,6BAA4B,UAAU;AAGxC;;GAGF,MAAM,WAAW,eAAe;AAChC,OAAI,UAAU;AACZ,kBAAc,SAAS;AACvB,WAAO,eAAe;;AAGxB,OAAI,SAAS,eAAe,aAC1B,QAAO,SAAS;AAGlB,OAAI,SAAS,eAAe,SAC1B,QAAO,SAAS;AAGlB,UAAO,aAAa;AAEpB,OAAI,CAAC,qBAAqB,WACxB,6BAA4B,UAAU;;;CAK5C,WAAU,WAAU,kBAAkB,OAAO;CAC9C,CAAC;AAEF,MAAa,YACX,QACA,QACA,cAEA,iBACE;CACE,GAAG;CACH,YAAY,OAAO,cAAc;CAClC,EACD,QACA,UACD;AAEH,MAAa,kBAAkB,aAAa;AAI5C,MAAa,mBAAmB;CAC9B;CACA;CACA;CACA;CACD,CAAC,KAAI,QAAO,WAAW,IAAI"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import {\n createRelayManager,\n createStrategy,\n entries,\n fromJson,\n genId,\n getRelays,\n keys,\n libName,\n makeSocket,\n pauseRelayReconnection,\n resumeRelayReconnection,\n selfId,\n sha1,\n toJson,\n type BaseRoomConfig,\n type JoinRoom,\n type OfferRecord,\n type RelayConfig,\n type SocketClient\n} from '@trystero-p2p/core'\n\nconst relayManager = createRelayManager<SocketClient>(client => client.socket)\nconst topicToInfoHash: Record<string, string> = {}\nconst infoHashToTopic: Record<string, string> = {}\nconst announceIntervals = relayManager.scoped<ReturnType<typeof setInterval>>()\nconst announceFns = relayManager.scoped<() => void | Promise<void>>()\nconst subscriptionTokens = relayManager.scoped<symbol>()\nconst trackerAnnounceMs: Record<string, number> = {}\nconst handledSignals: Record<string, number> = {}\nconst msgHandlers = relayManager.scoped<(data: TrackerMessage) => void>()\nconst roomOutstandingOffers: Record<\n string,\n Record<string, OfferRecord & {createdAt: number}>\n> = {}\nconst roomOfferGenerationPromises: Record<string, Promise<void> | undefined> =\n {}\nconst roomSubscriberCounts: Record<string, number> = {}\nconst trackerAction = 'announce'\nconst hashLimit = 20\nconst offerPoolSize = 3\nconst defaultAnnounceMs = 10_000\nconst maxAnnounceMs = 20_000\nconst offerRetentionMs = 120_000\nconst signalDedupeWindowMs = 4_000\nconst defaultRedundancy = 3\n\nexport type TorrentRoomConfig = BaseRoomConfig & RelayConfig\n\ntype TrackerMessage = {\n offer?: {\n type: 'offer'\n sdp: string\n }\n answer?: {\n type: 'answer'\n sdp: string\n }\n offer_id?: string\n peer_id?: string\n info_hash?: string\n interval?: number\n ['failure reason']?: string\n ['warning message']?: string\n}\n\nconst getInfoHash = async (topic: string): Promise<string> => {\n if (topicToInfoHash[topic]) {\n return topicToInfoHash[topic]\n }\n\n const hash = (await sha1(topic)).slice(0, hashLimit)\n topicToInfoHash[topic] = hash\n infoHashToTopic[hash] = topic\n\n return hash\n}\n\nconst send = async (\n client: SocketClient,\n topic: string,\n payload: Record<string, unknown>\n): Promise<void> =>\n client.send(\n toJson({\n action: trackerAction,\n info_hash: await getInfoHash(topic),\n peer_id: selfId,\n ...payload\n })\n )\n\nconst warn = (url: string, msg: string, didFail = false): void =>\n console.warn(\n `${libName}: torrent tracker ${didFail ? 'failure' : 'warning'} from ${url} - ${msg}`\n )\n\nconst getRoomOutstandingOffers = (\n rootTopic: string\n): Record<string, OfferRecord & {createdAt: number}> =>\n (roomOutstandingOffers[rootTopic] ??= {})\n\nconst deleteRoomOfferBookkeeping = (rootTopic: string): void => {\n delete roomOutstandingOffers[rootTopic]\n delete roomOfferGenerationPromises[rootTopic]\n}\n\nconst claimOutstandingOffer = (\n rootTopic: string,\n offerId: string\n): OfferRecord | undefined => {\n const outstandingOffers = roomOutstandingOffers[rootTopic]\n const offer = outstandingOffers?.[offerId]\n\n if (!offer) {\n return\n }\n\n delete outstandingOffers[offerId]\n offer.claim?.()\n\n if (!keys(outstandingOffers).length && !roomSubscriberCounts[rootTopic]) {\n deleteRoomOfferBookkeeping(rootTopic)\n }\n\n return offer\n}\n\nconst reclaimOutstandingOffer = (rootTopic: string, offerId: string): void => {\n const outstandingOffers = roomOutstandingOffers[rootTopic]\n const offer = outstandingOffers?.[offerId]\n\n if (!offer) {\n return\n }\n\n delete outstandingOffers[offerId]\n offer.reclaim?.()\n\n if (!keys(outstandingOffers).length && !roomSubscriberCounts[rootTopic]) {\n deleteRoomOfferBookkeeping(rootTopic)\n }\n}\n\nconst reclaimAllOutstandingOffers = (rootTopic: string): void => {\n keys(getRoomOutstandingOffers(rootTopic)).forEach(offerId =>\n reclaimOutstandingOffer(rootTopic, offerId)\n )\n deleteRoomOfferBookkeeping(rootTopic)\n}\n\nconst pruneOutstandingOffers = (rootTopic: string): void => {\n const now = Date.now()\n\n entries(getRoomOutstandingOffers(rootTopic)).forEach(([offerId, offer]) => {\n if (now - offer.createdAt > offerRetentionMs) {\n reclaimOutstandingOffer(rootTopic, offerId)\n }\n })\n}\n\nconst ensureOutstandingOffers = async (\n rootTopic: string,\n getOffers: (n: number) => Promise<OfferRecord[]>\n): Promise<Record<string, OfferRecord & {createdAt: number}>> => {\n while (roomOfferGenerationPromises[rootTopic]) {\n await roomOfferGenerationPromises[rootTopic]\n }\n\n const nextPromise = (async () => {\n pruneOutstandingOffers(rootTopic)\n\n const outstandingOffers = getRoomOutstandingOffers(rootTopic)\n const outstandingCount = keys(outstandingOffers).length\n const missingOffers = Math.max(0, offerPoolSize - outstandingCount)\n\n if (missingOffers > 0) {\n ;(await getOffers(missingOffers)).forEach(peerAndOffer => {\n outstandingOffers[genId(hashLimit)] = {\n ...peerAndOffer,\n createdAt: Date.now()\n }\n })\n }\n })().finally(() => {\n if (roomOfferGenerationPromises[rootTopic] === nextPromise) {\n delete roomOfferGenerationPromises[rootTopic]\n }\n })\n\n roomOfferGenerationPromises[rootTopic] = nextPromise\n await nextPromise\n\n return getRoomOutstandingOffers(rootTopic)\n}\n\nconst joinRoomStrategy: JoinRoom<TorrentRoomConfig> = createStrategy({\n init: config =>\n getRelays(config, defaultRelayUrls, defaultRedundancy).map(rawUrl => {\n const client = relayManager.register(\n rawUrl,\n makeSocket(rawUrl, rawData => {\n const data = fromJson<TrackerMessage>(rawData)\n const errMsg = data['failure reason']\n const warnMsg = data['warning message']\n const {interval} = data\n const topic = data.info_hash\n ? infoHashToTopic[data.info_hash]\n : undefined\n\n if (errMsg) {\n warn(client.url, errMsg, true)\n return\n }\n\n if (warnMsg) {\n warn(client.url, warnMsg)\n }\n\n if (\n interval &&\n interval * 1000 >\n (trackerAnnounceMs[client.url] ?? defaultAnnounceMs) &&\n topic &&\n announceFns.forKey(rawUrl)[topic]\n ) {\n const nextInterval = Math.min(interval * 1000, maxAnnounceMs)\n const relayIntervals = announceIntervals.forKey(rawUrl)\n const relayFns = announceFns.forKey(rawUrl)\n\n if (relayIntervals[topic]) {\n clearInterval(relayIntervals[topic])\n }\n trackerAnnounceMs[client.url] = nextInterval\n const relayFn = relayFns[topic]\n\n if (relayFn) {\n relayIntervals[topic] = setInterval(() => {\n void relayFn()\n }, nextInterval)\n }\n }\n\n if ((data.offer || data.answer) && topic && data.offer_id) {\n if (data.peer_id === selfId) {\n return\n }\n\n const signalType = data.offer ? 'offer' : 'answer'\n const signalKey = `${topic}:${signalType}:${data.offer_id}:${data.peer_id ?? ''}`\n const nowMs = Date.now()\n const lastHandledMs = handledSignals[signalKey]\n\n if (\n typeof lastHandledMs === 'number' &&\n nowMs - lastHandledMs < signalDedupeWindowMs\n ) {\n return\n }\n\n handledSignals[signalKey] = nowMs\n\n entries(handledSignals).forEach(([key, handledAtMs]) => {\n if (nowMs - handledAtMs > signalDedupeWindowMs * 6) {\n delete handledSignals[key]\n }\n })\n\n msgHandlers.forKey(rawUrl)[topic]?.(data)\n }\n })\n )\n\n return client.ready\n }),\n\n subscribe: (client, rootTopic, _, onMessage, getOffers) => {\n const handlers = msgHandlers.forRelay(client)\n const relayFns = announceFns.forRelay(client)\n const relayIntervals = announceIntervals.forRelay(client)\n const activeTokens = subscriptionTokens.forRelay(client)\n const subscriptionToken = Symbol(rootTopic)\n\n activeTokens[rootTopic] = subscriptionToken\n roomSubscriberCounts[rootTopic] = (roomSubscriberCounts[rootTopic] ?? 0) + 1\n\n const topicHandler = (data: TrackerMessage): void => {\n if (data.offer && data.peer_id && data.offer_id) {\n void onMessage(\n rootTopic,\n {\n offer: data.offer.sdp,\n peerId: data.peer_id,\n hasOutgoingOffer:\n keys(getRoomOutstandingOffers(rootTopic)).length > 0\n },\n (_, signal) =>\n void send(client, rootTopic, {\n answer: {\n type: 'answer',\n sdp: fromJson<{answer: string}>(signal).answer\n },\n offer_id: data.offer_id,\n to_peer_id: data.peer_id\n })\n )\n } else if (data.answer && data.offer_id && data.peer_id) {\n const offer = claimOutstandingOffer(rootTopic, data.offer_id)\n\n if (offer) {\n void onMessage(\n rootTopic,\n {\n answer: data.answer.sdp,\n peerId: data.peer_id,\n peer: offer.peer\n },\n () => {}\n )\n }\n }\n }\n\n handlers[rootTopic] = topicHandler\n\n const announce = async (): Promise<void> => {\n if (activeTokens[rootTopic] !== subscriptionToken) {\n return\n }\n\n const outstandingOffers = await ensureOutstandingOffers(\n rootTopic,\n getOffers\n )\n const offers = entries(outstandingOffers).map(([id, {offer}]) => ({\n offer_id: id,\n offer: {type: 'offer', sdp: offer}\n }))\n\n void send(client, rootTopic, {\n numwant: offerPoolSize,\n offers\n })\n }\n\n trackerAnnounceMs[client.url] = defaultAnnounceMs\n relayFns[rootTopic] = announce\n relayIntervals[rootTopic] = setInterval(\n announce,\n trackerAnnounceMs[client.url]\n )\n void announce()\n\n return () => {\n roomSubscriberCounts[rootTopic] = Math.max(\n 0,\n (roomSubscriberCounts[rootTopic] ?? 1) - 1\n )\n\n if (!roomSubscriberCounts[rootTopic]) {\n delete roomSubscriberCounts[rootTopic]\n }\n\n if (activeTokens[rootTopic] !== subscriptionToken) {\n if (!roomSubscriberCounts[rootTopic]) {\n reclaimAllOutstandingOffers(rootTopic)\n }\n\n return\n }\n\n const interval = relayIntervals[rootTopic]\n if (interval) {\n clearInterval(interval)\n delete relayIntervals[rootTopic]\n }\n\n if (handlers[rootTopic] === topicHandler) {\n delete handlers[rootTopic]\n }\n\n if (relayFns[rootTopic] === announce) {\n delete relayFns[rootTopic]\n }\n\n delete activeTokens[rootTopic]\n\n if (!roomSubscriberCounts[rootTopic]) {\n reclaimAllOutstandingOffers(rootTopic)\n }\n }\n },\n\n announce: client => trackerAnnounceMs[client.url]\n})\n\nexport const joinRoom: JoinRoom<TorrentRoomConfig> = (\n config,\n roomId,\n callbacks\n) =>\n joinRoomStrategy(\n {\n ...config,\n trickleIce: config.trickleIce ?? false\n },\n roomId,\n callbacks\n )\n\nexport const getRelaySockets = relayManager.getSockets\n\nexport {pauseRelayReconnection, resumeRelayReconnection, selfId}\n\nexport const defaultRelayUrls = [\n 'tracker.webtorrent.dev',\n 'tracker.openwebtorrent.com',\n 'tracker.btorrent.xyz',\n 'tracker.files.fm:7073/announce'\n].map(url => 'wss://' + url)\n\nexport type * from '@trystero-p2p/core'\n"],"mappings":";;AAsBA,MAAM,eAAe,oBAAiC,WAAU,OAAO,OAAO;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wBAAqB,aAAa,KAAK,IACrC,IACC,qBAAqB,cAAc,KAAK,EAC1C;AAED,OAAI,CAAC,qBAAqB,WACxB,QAAO,qBAAqB;AAG9B,OAAI,aAAa,eAAe,mBAAmB;AACjD,QAAI,CAAC,qBAAqB,WACxB,6BAA4B,UAAU;AAGxC;;GAGF,MAAM,WAAW,eAAe;AAChC,OAAI,UAAU;AACZ,kBAAc,SAAS;AACvB,WAAO,eAAe;;AAGxB,OAAI,SAAS,eAAe,aAC1B,QAAO,SAAS;AAGlB,OAAI,SAAS,eAAe,SAC1B,QAAO,SAAS;AAGlB,UAAO,aAAa;AAEpB,OAAI,CAAC,qBAAqB,WACxB,6BAA4B,UAAU;;;CAK5C,WAAU,WAAU,kBAAkB,OAAO;CAC9C,CAAC;AAEF,MAAa,YACX,QACA,QACA,cAEA,iBACE;CACE,GAAG;CACH,YAAY,OAAO,cAAc;CAClC,EACD,QACA,UACD;AAEH,MAAa,kBAAkB,aAAa;AAI5C,MAAa,mBAAmB;CAC9B;CACA;CACA;CACA;CACD,CAAC,KAAI,QAAO,WAAW,IAAI"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trystero-p2p/torrent",
3
- "version": "0.23.0",
3
+ "version": "0.23.1",
4
4
  "description": "Torrent tracker strategy for Trystero",
5
5
  "keywords": [
6
6
  "bittorrent",
@@ -34,6 +34,6 @@
34
34
  "./package.json": "./package.json"
35
35
  },
36
36
  "dependencies": {
37
- "@trystero-p2p/core": "0.23.0"
37
+ "@trystero-p2p/core": "0.23.1"
38
38
  }
39
39
  }