peer-by-ip 1.0.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.
@@ -0,0 +1,850 @@
1
+ import $hSjDC$express from "express";
2
+ import $hSjDC$nodehttp from "node:http";
3
+ import $hSjDC$nodehttps from "node:https";
4
+ import $hSjDC$nodepath from "node:path";
5
+ import {randomUUID as $hSjDC$randomUUID} from "node:crypto";
6
+ import {EventEmitter as $hSjDC$EventEmitter} from "node:events";
7
+ import {WebSocketServer as $hSjDC$WebSocketServer} from "ws";
8
+ import $hSjDC$cors from "cors";
9
+
10
+
11
+ function $parcel$interopDefault(a) {
12
+ return a && a.__esModule ? a.default : a;
13
+ }
14
+
15
+
16
+
17
+ const $0781b93c08f2d25d$var$defaultConfig = {
18
+ host: "::",
19
+ port: 9000,
20
+ expire_timeout: 5000,
21
+ alive_timeout: 90000,
22
+ key: "peerjs",
23
+ path: "/",
24
+ concurrent_limit: 5000,
25
+ allow_discovery: false,
26
+ proxied: false,
27
+ cleanup_out_msgs: 1000,
28
+ corsOptions: {
29
+ origin: true
30
+ }
31
+ };
32
+ var $0781b93c08f2d25d$export$2e2bcd8739ae039 = $0781b93c08f2d25d$var$defaultConfig;
33
+
34
+
35
+
36
+ class $2bde1ad4812d1cc1$export$eb4c623330d4cbcc {
37
+ getLastReadAt() {
38
+ return this.lastReadAt;
39
+ }
40
+ addMessage(message) {
41
+ this.messages.push(message);
42
+ }
43
+ readMessage() {
44
+ if (this.messages.length > 0) {
45
+ this.lastReadAt = new Date().getTime();
46
+ return this.messages.shift();
47
+ }
48
+ return undefined;
49
+ }
50
+ getMessages() {
51
+ return this.messages;
52
+ }
53
+ constructor(){
54
+ this.lastReadAt = new Date().getTime();
55
+ this.messages = [];
56
+ }
57
+ }
58
+
59
+
60
+
61
+ class $2932b43293655a3d$export$3ee29d34e33d9116 {
62
+ getClientsIds() {
63
+ return [
64
+ ...this.clients.keys()
65
+ ];
66
+ }
67
+ getClientById(clientId) {
68
+ return this.clients.get(clientId);
69
+ }
70
+ getClientsIdsWithQueue() {
71
+ return [
72
+ ...this.messageQueues.keys()
73
+ ];
74
+ }
75
+ setClient(client, id) {
76
+ this.clients.set(id, client);
77
+ // Add to IP-based grouping
78
+ const ip = client.getIpAddress();
79
+ if (ip) {
80
+ let ipGroup = this.clientsByIp.get(ip);
81
+ if (!ipGroup) {
82
+ ipGroup = new Map();
83
+ this.clientsByIp.set(ip, ipGroup);
84
+ }
85
+ ipGroup.set(id, client);
86
+ }
87
+ }
88
+ removeClientById(id) {
89
+ const client = this.getClientById(id);
90
+ if (!client) return false;
91
+ // Remove from IP-based grouping
92
+ const ip = client.getIpAddress();
93
+ if (ip) {
94
+ const ipGroup = this.clientsByIp.get(ip);
95
+ if (ipGroup) {
96
+ ipGroup.delete(id);
97
+ if (ipGroup.size === 0) this.clientsByIp.delete(ip);
98
+ }
99
+ }
100
+ this.clients.delete(id);
101
+ return true;
102
+ }
103
+ getMessageQueueById(id) {
104
+ return this.messageQueues.get(id);
105
+ }
106
+ addMessageToQueue(id, message) {
107
+ if (!this.getMessageQueueById(id)) this.messageQueues.set(id, new (0, $2bde1ad4812d1cc1$export$eb4c623330d4cbcc)());
108
+ this.getMessageQueueById(id)?.addMessage(message);
109
+ }
110
+ clearMessageQueue(id) {
111
+ this.messageQueues.delete(id);
112
+ }
113
+ generateClientId(generateClientId) {
114
+ const generateId = generateClientId ? generateClientId : (0, $hSjDC$randomUUID);
115
+ let clientId = generateId();
116
+ while(this.getClientById(clientId))clientId = generateId();
117
+ return clientId;
118
+ }
119
+ getClientsByIp(ipAddress) {
120
+ return this.clientsByIp.get(ipAddress);
121
+ }
122
+ getAllIpGroups() {
123
+ return this.clientsByIp;
124
+ }
125
+ constructor(){
126
+ this.clients = new Map();
127
+ this.messageQueues = new Map();
128
+ this.clientsByIp = new Map();
129
+ }
130
+ }
131
+
132
+
133
+ const $718f873d59565529$var$DEFAULT_CHECK_INTERVAL = 300;
134
+ class $718f873d59565529$export$6fa53df6b5b88df7 {
135
+ constructor({ realm: realm, config: config, checkInterval: checkInterval = $718f873d59565529$var$DEFAULT_CHECK_INTERVAL, onClose: onClose }){
136
+ this.timeoutId = null;
137
+ this.realm = realm;
138
+ this.config = config;
139
+ this.onClose = onClose;
140
+ this.checkInterval = checkInterval;
141
+ }
142
+ start() {
143
+ if (this.timeoutId) clearTimeout(this.timeoutId);
144
+ this.timeoutId = setTimeout(()=>{
145
+ this.checkConnections();
146
+ this.timeoutId = null;
147
+ this.start();
148
+ }, this.checkInterval);
149
+ }
150
+ stop() {
151
+ if (this.timeoutId) {
152
+ clearTimeout(this.timeoutId);
153
+ this.timeoutId = null;
154
+ }
155
+ }
156
+ checkConnections() {
157
+ const clientsIds = this.realm.getClientsIds();
158
+ const now = new Date().getTime();
159
+ const { alive_timeout: aliveTimeout } = this.config;
160
+ for (const clientId of clientsIds){
161
+ const client = this.realm.getClientById(clientId);
162
+ if (!client) continue;
163
+ const timeSinceLastPing = now - client.getLastPing();
164
+ if (timeSinceLastPing < aliveTimeout) continue;
165
+ try {
166
+ client.getSocket()?.close();
167
+ } finally{
168
+ this.realm.clearMessageQueue(clientId);
169
+ this.realm.removeClientById(clientId);
170
+ client.setSocket(null);
171
+ this.onClose?.(client);
172
+ }
173
+ }
174
+ }
175
+ }
176
+
177
+
178
+ var $cbd6629f9f078570$export$b8e9cd941e8016ac = /*#__PURE__*/ function(Errors) {
179
+ Errors["INVALID_KEY"] = "Invalid key provided";
180
+ Errors["INVALID_TOKEN"] = "Invalid token provided";
181
+ Errors["INVALID_WS_PARAMETERS"] = "No id, token, or key supplied to websocket server";
182
+ Errors["CONNECTION_LIMIT_EXCEED"] = "Server has reached its concurrent user limit";
183
+ return Errors;
184
+ }({});
185
+ var $cbd6629f9f078570$export$80edbf15fa61a4db = /*#__PURE__*/ function(MessageType) {
186
+ MessageType["OPEN"] = "OPEN";
187
+ MessageType["LEAVE"] = "LEAVE";
188
+ MessageType["CANDIDATE"] = "CANDIDATE";
189
+ MessageType["OFFER"] = "OFFER";
190
+ MessageType["ANSWER"] = "ANSWER";
191
+ MessageType["EXPIRE"] = "EXPIRE";
192
+ MessageType["HEARTBEAT"] = "HEARTBEAT";
193
+ MessageType["ID_TAKEN"] = "ID-TAKEN";
194
+ MessageType["ERROR"] = "ERROR";
195
+ MessageType["PEER_JOINED_IP_GROUP"] = "PEER-JOINED-IP-GROUP";
196
+ MessageType["PEER_LEFT_IP_GROUP"] = "PEER-LEFT-IP-GROUP";
197
+ return MessageType;
198
+ }({});
199
+
200
+
201
+ class $c0c9bbac2b277489$export$a13b411d0e88b1af {
202
+ constructor({ realm: realm, config: config, messageHandler: messageHandler }){
203
+ this.timeoutId = null;
204
+ this.realm = realm;
205
+ this.config = config;
206
+ this.messageHandler = messageHandler;
207
+ }
208
+ startMessagesExpiration() {
209
+ if (this.timeoutId) clearTimeout(this.timeoutId);
210
+ // Clean up outstanding messages
211
+ this.timeoutId = setTimeout(()=>{
212
+ this.pruneOutstanding();
213
+ this.timeoutId = null;
214
+ this.startMessagesExpiration();
215
+ }, this.config.cleanup_out_msgs);
216
+ }
217
+ stopMessagesExpiration() {
218
+ if (this.timeoutId) {
219
+ clearTimeout(this.timeoutId);
220
+ this.timeoutId = null;
221
+ }
222
+ }
223
+ pruneOutstanding() {
224
+ const destinationClientsIds = this.realm.getClientsIdsWithQueue();
225
+ const now = new Date().getTime();
226
+ const maxDiff = this.config.expire_timeout;
227
+ const seen = {};
228
+ for (const destinationClientId of destinationClientsIds){
229
+ const messageQueue = this.realm.getMessageQueueById(destinationClientId);
230
+ if (!messageQueue) continue;
231
+ const lastReadDiff = now - messageQueue.getLastReadAt();
232
+ if (lastReadDiff < maxDiff) continue;
233
+ const messages = messageQueue.getMessages();
234
+ for (const message of messages){
235
+ const seenKey = `${message.src}_${message.dst}`;
236
+ if (!seen[seenKey]) {
237
+ this.messageHandler.handle(undefined, {
238
+ type: (0, $cbd6629f9f078570$export$80edbf15fa61a4db).EXPIRE,
239
+ src: message.dst,
240
+ dst: message.src
241
+ });
242
+ seen[seenKey] = true;
243
+ }
244
+ }
245
+ this.realm.clearMessageQueue(destinationClientId);
246
+ }
247
+ }
248
+ }
249
+
250
+
251
+
252
+
253
+ class $43c46f58aa0c70c3$export$1f2bb630327ac4b6 {
254
+ constructor({ id: id, token: token }){
255
+ this.socket = null;
256
+ this.lastPing = new Date().getTime();
257
+ this.ipAddress = "";
258
+ this.alias = "";
259
+ this.id = id;
260
+ this.token = token;
261
+ }
262
+ getId() {
263
+ return this.id;
264
+ }
265
+ getToken() {
266
+ return this.token;
267
+ }
268
+ getSocket() {
269
+ return this.socket;
270
+ }
271
+ setSocket(socket) {
272
+ this.socket = socket;
273
+ }
274
+ getLastPing() {
275
+ return this.lastPing;
276
+ }
277
+ setLastPing(lastPing) {
278
+ this.lastPing = lastPing;
279
+ }
280
+ getIpAddress() {
281
+ return this.ipAddress;
282
+ }
283
+ setIpAddress(ip) {
284
+ this.ipAddress = ip;
285
+ }
286
+ getAlias() {
287
+ return this.alias;
288
+ }
289
+ setAlias(alias) {
290
+ this.alias = alias;
291
+ }
292
+ send(data) {
293
+ this.socket?.send(JSON.stringify(data));
294
+ }
295
+ }
296
+
297
+
298
+
299
+ const $25f5d9d01a3c23a8$var$adjectives = [
300
+ "Bright",
301
+ "Great",
302
+ "Smart",
303
+ "Swift",
304
+ "Bold",
305
+ "Calm",
306
+ "Cool",
307
+ "Warm",
308
+ "Happy",
309
+ "Lucky",
310
+ "Noble",
311
+ "Proud",
312
+ "Quick",
313
+ "Witty",
314
+ "Brave",
315
+ "Cheerful",
316
+ "Daring",
317
+ "Elegant",
318
+ "Fancy",
319
+ "Gentle",
320
+ "Jolly",
321
+ "Keen",
322
+ "Lively",
323
+ "Merry",
324
+ "Polite",
325
+ "Shiny",
326
+ "Stellar",
327
+ "Talented",
328
+ "Vibrant",
329
+ "Wise",
330
+ // Funny additions
331
+ "Silly",
332
+ "Funky",
333
+ "Zany",
334
+ "Goofy",
335
+ "Wobbly",
336
+ "Glittery",
337
+ "Bouncy",
338
+ "Pickled",
339
+ "Sneaky",
340
+ "Nerdy",
341
+ "Fluffy",
342
+ "Spicy",
343
+ "Crispy",
344
+ "Snazzy",
345
+ "Quirky",
346
+ "Cheeky",
347
+ "Giggly",
348
+ "Breezy",
349
+ "Slippery"
350
+ ];
351
+ const $25f5d9d01a3c23a8$var$nouns = [
352
+ "Banana",
353
+ "Cherry",
354
+ "Apple",
355
+ "Orange",
356
+ "Grape",
357
+ "Mango",
358
+ "Peach",
359
+ "Lemon",
360
+ "Melon",
361
+ "Berry",
362
+ "Pear",
363
+ "Plum",
364
+ "Kiwi",
365
+ "Lime",
366
+ "Papaya",
367
+ "Apricot",
368
+ "Fig",
369
+ "Coconut",
370
+ "Avocado",
371
+ "Dragon",
372
+ "Phoenix",
373
+ "Tiger",
374
+ "Eagle",
375
+ "Lion",
376
+ "Wolf",
377
+ "Bear",
378
+ "Hawk",
379
+ "Falcon",
380
+ "Panda",
381
+ // Funny additions
382
+ "Noodle",
383
+ "Unicorn",
384
+ "Tofu",
385
+ "Pickle",
386
+ "Marshmallow",
387
+ "Wombat",
388
+ "RubberDuck",
389
+ "Taco",
390
+ "Waffle",
391
+ "Bubble",
392
+ "Squid",
393
+ "Hippo",
394
+ "Muffin",
395
+ "Nacho",
396
+ "Ginger",
397
+ "Squirrel",
398
+ "Penguin",
399
+ "Turtle",
400
+ "Otter",
401
+ "Dumpling"
402
+ ];
403
+ function $25f5d9d01a3c23a8$export$65b9416602f2db62() {
404
+ const adjective = $25f5d9d01a3c23a8$var$adjectives[Math.floor(Math.random() * $25f5d9d01a3c23a8$var$adjectives.length)];
405
+ const noun = $25f5d9d01a3c23a8$var$nouns[Math.floor(Math.random() * $25f5d9d01a3c23a8$var$nouns.length)];
406
+ return `${adjective} ${noun}`;
407
+ }
408
+
409
+
410
+ const $9cd36c423c7aa5b9$var$WS_PATH = "peerjs";
411
+ class $9cd36c423c7aa5b9$export$f47674b57e51ee3b extends (0, $hSjDC$EventEmitter) {
412
+ constructor({ server: server, realm: realm, config: config }){
413
+ super();
414
+ this.setMaxListeners(0);
415
+ this.realm = realm;
416
+ this.config = config;
417
+ const path = this.config.path;
418
+ this.path = `${path}${path.endsWith("/") ? "" : "/"}${$9cd36c423c7aa5b9$var$WS_PATH}`;
419
+ const options = {
420
+ path: this.path,
421
+ server: server
422
+ };
423
+ this.socketServer = config.createWebSocketServer ? config.createWebSocketServer(options) : new (0, $hSjDC$WebSocketServer)(options);
424
+ this.socketServer.on("connection", (socket, req)=>{
425
+ this._onSocketConnection(socket, req);
426
+ });
427
+ this.socketServer.on("error", (error)=>{
428
+ this._onSocketError(error);
429
+ });
430
+ }
431
+ _onSocketConnection(socket, req) {
432
+ // An unhandled socket error might crash the server. Handle it first.
433
+ socket.on("error", (error)=>{
434
+ this._onSocketError(error);
435
+ });
436
+ // Extract IP address (handle proxied requests)
437
+ const forwardedFor = req.headers["x-forwarded-for"];
438
+ let ip = req.socket.remoteAddress ?? "unknown";
439
+ if (forwardedFor) {
440
+ const forwardedIp = Array.isArray(forwardedFor) ? forwardedFor[0] ?? "" : forwardedFor;
441
+ const firstIp = forwardedIp.split(",")[0];
442
+ if (firstIp) ip = firstIp.trim();
443
+ }
444
+ // We are only interested in the query, the base url is therefore not relevant
445
+ const { searchParams: searchParams } = new URL(req.url ?? "", "https://peerjs");
446
+ const { id: id, token: token, key: key } = Object.fromEntries(searchParams.entries());
447
+ if (!id || !token || !key) {
448
+ this._sendErrorAndClose(socket, (0, $cbd6629f9f078570$export$b8e9cd941e8016ac).INVALID_WS_PARAMETERS);
449
+ return;
450
+ }
451
+ if (key !== this.config.key) {
452
+ this._sendErrorAndClose(socket, (0, $cbd6629f9f078570$export$b8e9cd941e8016ac).INVALID_KEY);
453
+ return;
454
+ }
455
+ const client = this.realm.getClientById(id);
456
+ if (client) {
457
+ if (token !== client.getToken()) {
458
+ // ID-taken, invalid token
459
+ socket.send(JSON.stringify({
460
+ type: (0, $cbd6629f9f078570$export$80edbf15fa61a4db).ID_TAKEN,
461
+ payload: {
462
+ msg: "ID is taken"
463
+ }
464
+ }));
465
+ socket.close();
466
+ return;
467
+ }
468
+ this._configureWS(socket, client);
469
+ return;
470
+ }
471
+ this._registerClient({
472
+ socket: socket,
473
+ id: id,
474
+ token: token,
475
+ ip: ip
476
+ });
477
+ }
478
+ _onSocketError(error) {
479
+ // handle error
480
+ this.emit("error", error);
481
+ }
482
+ _registerClient({ socket: socket, id: id, token: token, ip: ip }) {
483
+ // Check concurrent limit
484
+ const clientsCount = this.realm.getClientsIds().length;
485
+ if (clientsCount >= this.config.concurrent_limit) {
486
+ this._sendErrorAndClose(socket, (0, $cbd6629f9f078570$export$b8e9cd941e8016ac).CONNECTION_LIMIT_EXCEED);
487
+ return;
488
+ }
489
+ const newClient = new (0, $43c46f58aa0c70c3$export$1f2bb630327ac4b6)({
490
+ id: id,
491
+ token: token
492
+ });
493
+ newClient.setIpAddress(ip);
494
+ newClient.setAlias((0, $25f5d9d01a3c23a8$export$65b9416602f2db62)());
495
+ this.realm.setClient(newClient, id);
496
+ socket.send(JSON.stringify({
497
+ type: (0, $cbd6629f9f078570$export$80edbf15fa61a4db).OPEN
498
+ }));
499
+ this._configureWS(socket, newClient);
500
+ // Notify other clients in the same IP group about the new peer
501
+ this._notifyIpGroup(ip, newClient.getId(), {
502
+ type: (0, $cbd6629f9f078570$export$80edbf15fa61a4db).PEER_JOINED_IP_GROUP,
503
+ payload: {
504
+ id: newClient.getId(),
505
+ alias: newClient.getAlias(),
506
+ ip: ip
507
+ }
508
+ });
509
+ }
510
+ _configureWS(socket, client) {
511
+ client.setSocket(socket);
512
+ // Cleanup after a socket closes.
513
+ socket.on("close", ()=>{
514
+ if (client.getSocket() === socket) {
515
+ const clientIp = client.getIpAddress();
516
+ const clientId = client.getId();
517
+ const clientAlias = client.getAlias();
518
+ this.realm.removeClientById(clientId);
519
+ // Notify other clients in the same IP group about the peer leaving
520
+ if (clientIp) this._notifyIpGroup(clientIp, clientId, {
521
+ type: (0, $cbd6629f9f078570$export$80edbf15fa61a4db).PEER_LEFT_IP_GROUP,
522
+ payload: {
523
+ id: clientId,
524
+ alias: clientAlias,
525
+ ip: clientIp
526
+ }
527
+ });
528
+ this.emit("close", client);
529
+ }
530
+ });
531
+ // Handle messages from peers.
532
+ socket.on("message", (data)=>{
533
+ try {
534
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
535
+ const message = JSON.parse(data.toString());
536
+ message.src = client.getId();
537
+ this.emit("message", client, message);
538
+ } catch (e) {
539
+ this.emit("error", e);
540
+ }
541
+ });
542
+ this.emit("connection", client);
543
+ }
544
+ _sendErrorAndClose(socket, msg) {
545
+ socket.send(JSON.stringify({
546
+ type: (0, $cbd6629f9f078570$export$80edbf15fa61a4db).ERROR,
547
+ payload: {
548
+ msg: msg
549
+ }
550
+ }));
551
+ socket.close();
552
+ }
553
+ /**
554
+ * Notify all clients in the same IP group about a peer event
555
+ * @param ip - The IP address of the group
556
+ * @param excludeClientId - Client ID to exclude from notification (usually the one triggering the event)
557
+ * @param message - The message to send
558
+ */ _notifyIpGroup(ip, excludeClientId, message) {
559
+ const ipGroup = this.realm.getClientsByIp(ip);
560
+ if (!ipGroup) return;
561
+ for (const [clientId, client] of ipGroup){
562
+ // Don't notify the client that triggered the event
563
+ if (clientId === excludeClientId) continue;
564
+ const socket = client.getSocket();
565
+ if (socket && socket.readyState === 1) // WebSocket.OPEN = 1
566
+ try {
567
+ socket.send(JSON.stringify(message));
568
+ } catch (e) {
569
+ // Ignore send errors for now
570
+ }
571
+ }
572
+ }
573
+ }
574
+
575
+
576
+
577
+ const $165a2ba012e308a4$export$65302b915833a46d = (client)=>{
578
+ if (client) {
579
+ const nowTime = new Date().getTime();
580
+ client.setLastPing(nowTime);
581
+ }
582
+ return true;
583
+ };
584
+
585
+
586
+
587
+ const $1d7e4ce8db21d489$export$809c011ea942310 = ({ realm: realm })=>{
588
+ const handle = (client, message)=>{
589
+ const type = message.type;
590
+ const srcId = message.src;
591
+ const dstId = message.dst;
592
+ const destinationClient = realm.getClientById(dstId);
593
+ // User is connected!
594
+ if (destinationClient) {
595
+ const socket = destinationClient.getSocket();
596
+ try {
597
+ if (socket) {
598
+ const data = JSON.stringify(message);
599
+ socket.send(data);
600
+ } else // Neither socket no res available. Peer dead?
601
+ throw new Error("Peer dead");
602
+ } catch (e) {
603
+ // This happens when a peer disconnects without closing connections and
604
+ // the associated WebSocket has not closed.
605
+ // Tell other side to stop trying.
606
+ if (socket) socket.close();
607
+ else realm.removeClientById(destinationClient.getId());
608
+ handle(client, {
609
+ type: (0, $cbd6629f9f078570$export$80edbf15fa61a4db).LEAVE,
610
+ src: dstId,
611
+ dst: srcId
612
+ });
613
+ }
614
+ } else {
615
+ // Wait for this client to connect/reconnect (XHR) for important
616
+ // messages.
617
+ const ignoredTypes = [
618
+ (0, $cbd6629f9f078570$export$80edbf15fa61a4db).LEAVE,
619
+ (0, $cbd6629f9f078570$export$80edbf15fa61a4db).EXPIRE
620
+ ];
621
+ if (!ignoredTypes.includes(type) && dstId) realm.addMessageToQueue(dstId, message);
622
+ else if (type === (0, $cbd6629f9f078570$export$80edbf15fa61a4db).LEAVE && !dstId) realm.removeClientById(srcId);
623
+ }
624
+ return true;
625
+ };
626
+ return handle;
627
+ };
628
+
629
+
630
+
631
+
632
+ class $7f4e22eb76800fde$export$cfe4a96645b0bbcf {
633
+ registerHandler(messageType, handler) {
634
+ if (this.handlers.has(messageType)) return;
635
+ this.handlers.set(messageType, handler);
636
+ }
637
+ handle(client, message) {
638
+ const { type: type } = message;
639
+ const handler = this.handlers.get(type);
640
+ if (!handler) return false;
641
+ return handler(client, message);
642
+ }
643
+ constructor(){
644
+ this.handlers = new Map();
645
+ }
646
+ }
647
+
648
+
649
+ class $ab67c22d5ac89466$export$3deceafe0aaeaa95 {
650
+ constructor(realm, handlersRegistry = new (0, $7f4e22eb76800fde$export$cfe4a96645b0bbcf)()){
651
+ this.handlersRegistry = handlersRegistry;
652
+ const transmissionHandler = (0, $1d7e4ce8db21d489$export$809c011ea942310)({
653
+ realm: realm
654
+ });
655
+ const heartbeatHandler = (0, $165a2ba012e308a4$export$65302b915833a46d);
656
+ const handleTransmission = (client, { type: type, src: src, dst: dst, payload: payload })=>{
657
+ return transmissionHandler(client, {
658
+ type: type,
659
+ src: src,
660
+ dst: dst,
661
+ payload: payload
662
+ });
663
+ };
664
+ const handleHeartbeat = (client, message)=>heartbeatHandler(client, message);
665
+ this.handlersRegistry.registerHandler((0, $cbd6629f9f078570$export$80edbf15fa61a4db).HEARTBEAT, handleHeartbeat);
666
+ this.handlersRegistry.registerHandler((0, $cbd6629f9f078570$export$80edbf15fa61a4db).OFFER, handleTransmission);
667
+ this.handlersRegistry.registerHandler((0, $cbd6629f9f078570$export$80edbf15fa61a4db).ANSWER, handleTransmission);
668
+ this.handlersRegistry.registerHandler((0, $cbd6629f9f078570$export$80edbf15fa61a4db).CANDIDATE, handleTransmission);
669
+ this.handlersRegistry.registerHandler((0, $cbd6629f9f078570$export$80edbf15fa61a4db).LEAVE, handleTransmission);
670
+ this.handlersRegistry.registerHandler((0, $cbd6629f9f078570$export$80edbf15fa61a4db).EXPIRE, handleTransmission);
671
+ }
672
+ handle(client, message) {
673
+ return this.handlersRegistry.handle(client, message);
674
+ }
675
+ }
676
+
677
+
678
+
679
+
680
+ var $f0fa23adc7d5c081$exports = {};
681
+ $f0fa23adc7d5c081$exports = JSON.parse("{\"name\":\"PeerJS Server\",\"description\":\"A server side element to broker connections between PeerJS clients.\",\"website\":\"https://peerjs.com/\"}");
682
+
683
+
684
+
685
+ var $057aefedeb5b7763$export$2e2bcd8739ae039 = ({ config: config, realm: realm })=>{
686
+ const app = (0, $hSjDC$express).Router();
687
+ // Retrieve guaranteed random ID.
688
+ app.get("/id", (_, res)=>{
689
+ res.contentType("html");
690
+ res.send(realm.generateClientId(config.generateClientId));
691
+ });
692
+ // Get a list of all peers for a key, enabled by the `allowDiscovery` flag.
693
+ app.get("/peers", (_, res)=>{
694
+ if (config.allow_discovery) {
695
+ const clientsIds = realm.getClientsIds();
696
+ return res.send(clientsIds);
697
+ }
698
+ return res.sendStatus(401);
699
+ });
700
+ // Get all peers from the same IP as the requesting client
701
+ app.get("/by-ip", (req, res)=>{
702
+ if (config.allow_discovery) {
703
+ // Extract client's IP address from request
704
+ const forwardedFor = req.headers["x-forwarded-for"];
705
+ let clientIp = req.socket.remoteAddress ?? "unknown";
706
+ if (forwardedFor) {
707
+ const forwardedIp = Array.isArray(forwardedFor) ? forwardedFor[0] ?? "" : forwardedFor;
708
+ const firstIp = forwardedIp.split(",")[0];
709
+ if (firstIp) clientIp = firstIp.trim();
710
+ }
711
+ const ipGroup = realm.getClientsByIp(clientIp);
712
+ if (!ipGroup) return res.send([]);
713
+ const peers = Array.from(ipGroup.values()).map((client)=>({
714
+ id: client.getId(),
715
+ alias: client.getAlias()
716
+ }));
717
+ return res.send(peers);
718
+ }
719
+ return res.sendStatus(401);
720
+ });
721
+ // Get all IP groups (admin/debugging endpoint)
722
+ app.get("/groups", (_, res)=>{
723
+ if (config.allow_discovery) {
724
+ const result = {};
725
+ const ipGroups = Array.from(realm.getAllIpGroups().entries());
726
+ for (const [ip, clients] of ipGroups)result[ip] = Array.from(clients.values()).map((client)=>({
727
+ id: client.getId(),
728
+ alias: client.getAlias()
729
+ }));
730
+ return res.send(result);
731
+ }
732
+ return res.sendStatus(401);
733
+ });
734
+ return app;
735
+ };
736
+
737
+
738
+ const $bcf67422c1702ef9$export$bf71da7aebe9ddc1 = ({ config: config, realm: realm, corsOptions: corsOptions })=>{
739
+ const app = (0, $hSjDC$express).Router();
740
+ app.use((0, $hSjDC$cors)(corsOptions));
741
+ app.get("/", (_, res)=>{
742
+ res.send((0, (/*@__PURE__*/$parcel$interopDefault($f0fa23adc7d5c081$exports))));
743
+ });
744
+ app.use("/:key", (0, $057aefedeb5b7763$export$2e2bcd8739ae039)({
745
+ config: config,
746
+ realm: realm
747
+ }));
748
+ return app;
749
+ };
750
+
751
+
752
+ const $9b23765526be336a$export$99152e8d49ca4e7d = ({ app: app, server: server, options: options })=>{
753
+ const config = options;
754
+ const realm = new (0, $2932b43293655a3d$export$3ee29d34e33d9116)();
755
+ const messageHandler = new (0, $ab67c22d5ac89466$export$3deceafe0aaeaa95)(realm);
756
+ const api = (0, $bcf67422c1702ef9$export$bf71da7aebe9ddc1)({
757
+ config: config,
758
+ realm: realm,
759
+ corsOptions: options.corsOptions
760
+ });
761
+ const messagesExpire = new (0, $c0c9bbac2b277489$export$a13b411d0e88b1af)({
762
+ realm: realm,
763
+ config: config,
764
+ messageHandler: messageHandler
765
+ });
766
+ const checkBrokenConnections = new (0, $718f873d59565529$export$6fa53df6b5b88df7)({
767
+ realm: realm,
768
+ config: config,
769
+ onClose: (client)=>{
770
+ app.emit("disconnect", client);
771
+ }
772
+ });
773
+ app.use(options.path, api);
774
+ //use mountpath for WS server
775
+ const customConfig = {
776
+ ...config,
777
+ path: (0, $hSjDC$nodepath).posix.join(app.path(), options.path, "/")
778
+ };
779
+ const wss = new (0, $9cd36c423c7aa5b9$export$f47674b57e51ee3b)({
780
+ server: server,
781
+ realm: realm,
782
+ config: customConfig
783
+ });
784
+ wss.on("connection", (client)=>{
785
+ const messageQueue = realm.getMessageQueueById(client.getId());
786
+ if (messageQueue) {
787
+ let message;
788
+ while(message = messageQueue.readMessage())messageHandler.handle(client, message);
789
+ realm.clearMessageQueue(client.getId());
790
+ }
791
+ app.emit("connection", client);
792
+ });
793
+ wss.on("message", (client, message)=>{
794
+ app.emit("message", client, message);
795
+ messageHandler.handle(client, message);
796
+ });
797
+ wss.on("close", (client)=>{
798
+ app.emit("disconnect", client);
799
+ });
800
+ wss.on("error", (error)=>{
801
+ app.emit("error", error);
802
+ });
803
+ messagesExpire.startMessagesExpiration();
804
+ checkBrokenConnections.start();
805
+ };
806
+
807
+
808
+ function $eb17f609fec572d7$export$8c57434a18c696c9(server, options) {
809
+ const app = (0, $hSjDC$express)();
810
+ const newOptions = {
811
+ ...(0, $0781b93c08f2d25d$export$2e2bcd8739ae039),
812
+ ...options
813
+ };
814
+ if (newOptions.proxied) app.set("trust proxy", newOptions.proxied === "false" ? false : !!newOptions.proxied);
815
+ app.on("mount", ()=>{
816
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
817
+ if (!server) throw new Error("Server is not passed to constructor - can't start PeerServer");
818
+ (0, $9b23765526be336a$export$99152e8d49ca4e7d)({
819
+ app: app,
820
+ server: server,
821
+ options: newOptions
822
+ });
823
+ });
824
+ return app;
825
+ }
826
+ function $eb17f609fec572d7$export$f99d31af51f48b1e(options = {}, callback) {
827
+ const app = (0, $hSjDC$express)();
828
+ let newOptions = {
829
+ ...(0, $0781b93c08f2d25d$export$2e2bcd8739ae039),
830
+ ...options
831
+ };
832
+ const port = newOptions.port;
833
+ const host = newOptions.host;
834
+ let server;
835
+ const { ssl: ssl, ...restOptions } = newOptions;
836
+ if (ssl && Object.keys(ssl).length) {
837
+ server = (0, $hSjDC$nodehttps).createServer(ssl, app);
838
+ newOptions = restOptions;
839
+ } else server = (0, $hSjDC$nodehttp).createServer(app);
840
+ // Increase max listeners to prevent warning when multiple services attach listeners
841
+ server.setMaxListeners(0);
842
+ const peerjs = $eb17f609fec572d7$export$8c57434a18c696c9(server, newOptions);
843
+ app.use(peerjs);
844
+ server.listen(port, host, ()=>callback?.(server));
845
+ return peerjs;
846
+ }
847
+
848
+
849
+ export {$eb17f609fec572d7$export$8c57434a18c696c9 as ExpressPeerServer, $eb17f609fec572d7$export$f99d31af51f48b1e as PeerServer};
850
+ //# sourceMappingURL=module.mjs.map