@4players/odin-common 4.0.2 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/mod.js CHANGED
@@ -1,1182 +1 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // src/mod.ts
30
- var mod_exports = {};
31
- __export(mod_exports, {
32
- Backend: () => Backend,
33
- ByteArraySchema: () => ByteArraySchema,
34
- ChannelSet: () => ChannelSet,
35
- ChannelSetSchema: () => ChannelSetSchema,
36
- DEFAULT_FORMATTER: () => DEFAULT_FORMATTER,
37
- JsonSchema: () => JsonSchema,
38
- LogFunctions: () => LogFunctions,
39
- LogHandler: () => LogHandler,
40
- LogLevelNames: () => LogLevelNames,
41
- LogLevels: () => LogLevels,
42
- LogSymbols: () => LogSymbols,
43
- LogVerbosity: () => LogVerbosity,
44
- Logger: () => Logger,
45
- MainCommandsRpc: () => MainCommandsRpc,
46
- MainNotificationSchema: () => MainNotificationSchema,
47
- MainNotificationsRpc: () => MainNotificationsRpc,
48
- MediaAudioPropertiesSchema: () => MediaAudioPropertiesSchema,
49
- MediaIdSchema: () => MediaIdSchema,
50
- MediaPropertiesSchema: () => MediaPropertiesSchema,
51
- MediaSchema: () => MediaSchema,
52
- MediaVideoPropertiesSchema: () => MediaVideoPropertiesSchema,
53
- MessagePackRpcSchema: () => MessagePackRpcSchema,
54
- MessageReceivedSchema: () => MessageReceivedSchema,
55
- MinDBFS: () => MinDBFS,
56
- PRETTY_FORMATTER: () => PRETTY_FORMATTER,
57
- PeerIdSchema: () => PeerIdSchema,
58
- PeerPositionSchema: () => PeerPositionSchema,
59
- PeerSchema: () => PeerSchema,
60
- PeerUpdateSchema: () => PeerUpdateSchema,
61
- RoomCommandsRpc: () => RoomCommandsRpc,
62
- RoomNotificationSchema: () => RoomNotificationSchema,
63
- RoomNotificationsRpc: () => RoomNotificationsRpc,
64
- RoomV1: () => RoomV1,
65
- RoomV2: () => RoomV2,
66
- Selector: () => Selector,
67
- Strand: () => Strand,
68
- TokenAudienceSchema: () => TokenAudienceSchema,
69
- TokenClaimsSchema: () => TokenClaimsSchema,
70
- TokenSubjectSchema: () => TokenSubjectSchema,
71
- VideoCodec: () => VideoCodec,
72
- WebRtcUpdateSchema: () => WebRtcUpdateSchema,
73
- abortableSleep: () => abortableSleep,
74
- assert: () => assert,
75
- debug: () => debug,
76
- error: () => error,
77
- extendUrl: () => extendUrl,
78
- fail: () => fail,
79
- failure: () => failure,
80
- find: () => find,
81
- fromBase64: () => fromBase64,
82
- fromBase64Url: () => fromBase64Url,
83
- fromBytes: () => fromBytes,
84
- generateUUID: () => generateUUID,
85
- getLevelByName: () => getLevelByName,
86
- getLevelName: () => getLevelName,
87
- getLogger: () => getLogger,
88
- info: () => info,
89
- isAudioCapable: () => isAudioCapable,
90
- isBlinkBrowser: () => isBlinkBrowser,
91
- isElectronBrowser: () => isElectronBrowser,
92
- isFailure: () => isFailure,
93
- isFirefoxBrowser: () => isFirefoxBrowser,
94
- isFunction: () => isFunction,
95
- isNull: () => isNull,
96
- isNumber: () => isNumber,
97
- isObject: () => isObject,
98
- isProperty: () => isProperty,
99
- isSafariBrowser: () => isSafariBrowser,
100
- isSharedArrayBufferCapable: () => isSharedArrayBufferCapable,
101
- isString: () => isString,
102
- isSuccess: () => isSuccess,
103
- isUndefined: () => isUndefined,
104
- nextTick: () => nextTick,
105
- normalizeUrl: () => normalizeUrl,
106
- oneOrMany: () => oneOrMany,
107
- sleep: () => sleep,
108
- success: () => success,
109
- toBytes: () => toBytes,
110
- toRaw: () => toRaw,
111
- unwrap: () => unwrap,
112
- unwrapOr: () => unwrapOr,
113
- validateUUID: () => validateUUID,
114
- warn: () => warn,
115
- zod: () => zod
116
- });
117
- module.exports = __toCommonJS(mod_exports);
118
- var zod = __toESM(require("zod"));
119
-
120
- // src/schema/serialization.ts
121
- var import_zod = require("zod");
122
- var ByteArraySchema = import_zod.z.custom(
123
- (value) => value instanceof Uint8Array
124
- );
125
- var LiteralSchema = import_zod.z.union([import_zod.z.string(), import_zod.z.number(), import_zod.z.boolean(), import_zod.z.null()]);
126
- var JsonSchema = import_zod.z.lazy(
127
- () => import_zod.z.union([LiteralSchema, import_zod.z.array(JsonSchema), import_zod.z.record(JsonSchema)])
128
- );
129
- var MessagePackRpcSchema = import_zod.z.union([
130
- // request with method call
131
- import_zod.z.tuple([import_zod.z.literal(0), import_zod.z.number(), import_zod.z.string(), import_zod.z.unknown()]),
132
- // response
133
- import_zod.z.tuple([import_zod.z.literal(1), import_zod.z.number(), import_zod.z.nullable(import_zod.z.string()), import_zod.z.unknown()]),
134
- // notification
135
- import_zod.z.tuple([import_zod.z.literal(2), import_zod.z.string(), import_zod.z.unknown()])
136
- ]);
137
-
138
- // src/schema/token.ts
139
- var import_zod2 = require("zod");
140
- var TokenAudienceSchema = import_zod2.z.enum(["sfu", "gateway"]);
141
- var TokenSubjectSchema = import_zod2.z.enum([
142
- "connect",
143
- "roomclose",
144
- "roomupdate",
145
- "roombanclient",
146
- "roomsendmessage"
147
- ]);
148
- var TokenClaimsSchema = import_zod2.z.object({
149
- uid: import_zod2.z.string(),
150
- cid: import_zod2.z.optional(import_zod2.z.string()),
151
- rid: oneOrMany(import_zod2.z.string()),
152
- nsp: import_zod2.z.optional(import_zod2.z.string()),
153
- adr: import_zod2.z.optional(import_zod2.z.string()),
154
- aud: import_zod2.z.optional(oneOrMany(TokenAudienceSchema)),
155
- sub: import_zod2.z.optional(oneOrMany(TokenSubjectSchema)),
156
- exp: import_zod2.z.optional(import_zod2.z.number()),
157
- nbf: import_zod2.z.optional(import_zod2.z.number()),
158
- ups: import_zod2.z.optional(import_zod2.z.string()),
159
- tgs: import_zod2.z.optional(oneOrMany(import_zod2.z.string())),
160
- tsp: import_zod2.z.optional(import_zod2.z.number()),
161
- internal: import_zod2.z.optional(
162
- import_zod2.z.object({
163
- server: import_zod2.z.optional(import_zod2.z.string())
164
- })
165
- )
166
- });
167
- function oneOrMany(type) {
168
- return import_zod2.z.union([type, import_zod2.z.array(type)]);
169
- }
170
-
171
- // src/schema/room.ts
172
- var z6 = __toESM(require("zod"));
173
-
174
- // src/schema/media.ts
175
- var z3 = __toESM(require("zod"));
176
- var MediaIdSchema = z3.number();
177
- var MediaAudioPropertiesSchema = z3.object({
178
- kind: z3.optional(z3.literal("audio")),
179
- uid: z3.optional(z3.string()),
180
- customType: z3.optional(z3.string())
181
- });
182
- var MediaVideoPropertiesSchema = z3.object({
183
- kind: z3.optional(z3.literal("video")),
184
- codec: z3.optional(z3.string()),
185
- uid: z3.optional(z3.string()),
186
- customType: z3.optional(z3.string())
187
- });
188
- var MediaPropertiesSchema = z3.union([
189
- MediaAudioPropertiesSchema,
190
- MediaVideoPropertiesSchema
191
- ]);
192
- var MediaSchema = z3.object({
193
- id: MediaIdSchema,
194
- properties: MediaPropertiesSchema,
195
- paused: z3.boolean()
196
- });
197
-
198
- // src/schema/peer.ts
199
- var z4 = __toESM(require("zod"));
200
- var PeerIdSchema = z4.number();
201
- var PeerPositionSchema = z4.union([
202
- z4.tuple([z4.number(), z4.number(), z4.number()]),
203
- z4.tuple([z4.number(), z4.number()])
204
- ]);
205
- var PeerSchema = z4.object({
206
- id: PeerIdSchema,
207
- user_id: z4.string(),
208
- user_data: ByteArraySchema,
209
- medias: z4.array(MediaSchema)
210
- });
211
- var PeerUpdateSchema = z4.discriminatedUnion("kind", [
212
- z4.object({
213
- kind: z4.literal("UserDataChanged"),
214
- peer_id: PeerIdSchema,
215
- user_data: ByteArraySchema
216
- }),
217
- z4.object({
218
- kind: z4.literal("MediaStarted"),
219
- peer_id: PeerIdSchema,
220
- media: MediaSchema
221
- }),
222
- z4.object({
223
- kind: z4.literal("MediaStopped"),
224
- peer_id: PeerIdSchema,
225
- media_id: MediaIdSchema
226
- })
227
- ]);
228
-
229
- // src/schema/channels.ts
230
- var z5 = __toESM(require("zod"));
231
- var ChannelSet = class _ChannelSet {
232
- constructor(value = BigInt(0)) {
233
- this.value = value;
234
- }
235
- from(...channels) {
236
- const value = channels.reduce(
237
- (value2, channel) => value2 | channel_mask(channel),
238
- BigInt(0)
239
- );
240
- return new _ChannelSet(value);
241
- }
242
- contains(channel) {
243
- return (this.value & channel_mask(channel)) !== BigInt(0);
244
- }
245
- insert(channel) {
246
- this.value |= channel_mask(channel);
247
- }
248
- remove(channel) {
249
- this.value &= ~channel_mask(channel);
250
- }
251
- [Symbol.iterator]() {
252
- let channel = -1;
253
- const self = new _ChannelSet(this.value);
254
- return {
255
- next() {
256
- while (channel < 63) {
257
- channel += 1;
258
- if (self.contains(channel)) {
259
- return { value: channel, done: false };
260
- }
261
- }
262
- return { value: void 0, done: true };
263
- }
264
- };
265
- }
266
- };
267
- var ChannelSetSchema = z5.bigint().transform((number5) => new ChannelSet(number5));
268
- function channel_mask(channel) {
269
- return BigInt(1) << BigInt(channel);
270
- }
271
-
272
- // src/schema/room.ts
273
- var RoomV1;
274
- ((RoomV12) => {
275
- RoomV12.RoomIdSchema = z6.string();
276
- RoomV12.RoomSchema = z6.object({
277
- id: RoomV12.RoomIdSchema,
278
- customer: z6.string(),
279
- user_data: ByteArraySchema,
280
- peers: z6.array(PeerSchema)
281
- });
282
- RoomV12.RoomUpdateSchema = z6.discriminatedUnion("kind", [
283
- z6.object({
284
- kind: z6.literal("Joined"),
285
- room: RoomV12.RoomSchema,
286
- media_ids: z6.array(MediaIdSchema),
287
- own_peer_id: PeerIdSchema
288
- }),
289
- z6.object({
290
- kind: z6.literal("Left"),
291
- reason: z6.enum(["RoomClosing", "ServerClosing", "PeerKicked"])
292
- }),
293
- z6.object({
294
- kind: z6.literal("UserDataChanged"),
295
- user_data: z6.optional(ByteArraySchema)
296
- }),
297
- z6.object({
298
- kind: z6.literal("PeerJoined"),
299
- peer: PeerSchema
300
- }),
301
- z6.object({
302
- kind: z6.literal("PeerLeft"),
303
- peer_id: PeerIdSchema
304
- })
305
- ]);
306
- RoomV12.RoomUpdatesSchema = z6.object({
307
- updates: z6.array(RoomV12.RoomUpdateSchema)
308
- });
309
- RoomV12.RoomStatusSchema = z6.enum(["Joining", "Joined", "Closed"]);
310
- RoomV12.RoomStatusChangedSchema = z6.object({
311
- status: RoomV12.RoomStatusSchema,
312
- message: z6.optional(z6.string())
313
- });
314
- })(RoomV1 || (RoomV1 = {}));
315
- var RoomV2;
316
- ((RoomV22) => {
317
- RoomV22.ParametersSchema = z6.record(JsonSchema);
318
- RoomV22.PeerProperties = z6.object({
319
- user_data: ByteArraySchema.optional(),
320
- tags: z6.array(z6.string()).optional(),
321
- audio_parameters: RoomV22.ParametersSchema.optional(),
322
- video_parameters: RoomV22.ParametersSchema.optional()
323
- });
324
- RoomV22.PingSchema = z6.object({
325
- Ping: z6.object({ id: z6.number() })
326
- });
327
- RoomV22.ChangeSelfSchema = z6.object({
328
- ChangeSelf: RoomV22.PeerProperties.omit({ tags: true })
329
- });
330
- RoomV22.SetAudioMaskSchema = z6.object({
331
- SetAudioMask: z6.object({
332
- peer_id: z6.number(),
333
- mask: ChannelSetSchema
334
- })
335
- });
336
- RoomV22.SendMessageSchema = z6.object({
337
- SendMessage: z6.object({
338
- peer_ids: z6.number().array().default([]),
339
- message: ByteArraySchema
340
- })
341
- });
342
- RoomV22.CallSchema = RoomV22.PingSchema.or(RoomV22.ChangeSelfSchema).or(RoomV22.SetAudioMaskSchema).or(RoomV22.SendMessageSchema);
343
- RoomV22.PongSchema = z6.object({
344
- Pong: z6.object({ id: z6.number() })
345
- });
346
- RoomV22.JoinedSchema = z6.object({
347
- Joined: z6.object({
348
- own_peer_id: z6.number(),
349
- room_id: z6.string(),
350
- customer: z6.string()
351
- })
352
- });
353
- RoomV22.LeftSchema = z6.object({
354
- Left: z6.object({
355
- reason: z6.enum(["room_closing", "server_closing", "peer_kicked"])
356
- })
357
- });
358
- RoomV22.PeerJoinedSchema = z6.object({
359
- PeerJoined: RoomV22.PeerProperties.extend({
360
- peer_id: z6.number(),
361
- user_id: z6.string()
362
- })
363
- });
364
- RoomV22.PeerLeftSchema = z6.object({
365
- PeerLeft: z6.object({
366
- peer_id: z6.number()
367
- })
368
- });
369
- RoomV22.PeerChangedSchema = z6.object({
370
- PeerChanged: RoomV22.PeerProperties.extend({
371
- peer_id: z6.number()
372
- })
373
- });
374
- RoomV22.NewReconnectTokenSchema = z6.object({
375
- NewReconnectToken: z6.object({
376
- token: z6.string()
377
- })
378
- });
379
- RoomV22.MessageReceivedSchema = z6.object({
380
- MessageReceived: z6.object({
381
- sender_peer_id: z6.number(),
382
- message: ByteArraySchema
383
- })
384
- });
385
- RoomV22.ErrorSchema = z6.object({
386
- Error: z6.object({
387
- message: ByteArraySchema
388
- })
389
- });
390
- RoomV22.EventSchema = RoomV22.PongSchema.or(RoomV22.JoinedSchema).or(RoomV22.LeftSchema).or(RoomV22.PeerJoinedSchema).or(RoomV22.PeerLeftSchema).or(RoomV22.PeerChangedSchema).or(RoomV22.NewReconnectTokenSchema).or(RoomV22.MessageReceivedSchema).or(RoomV22.ErrorSchema);
391
- })(RoomV2 || (RoomV2 = {}));
392
-
393
- // src/schema/message.ts
394
- var import_zod3 = require("zod");
395
- var MessageReceivedSchema = import_zod3.z.object({
396
- sender_peer_id: PeerIdSchema,
397
- message: ByteArraySchema
398
- });
399
-
400
- // src/schema/webrtc.ts
401
- var z8 = __toESM(require("zod"));
402
- var WebRtcUpdateSchema = z8.discriminatedUnion("kind", [
403
- z8.object({
404
- kind: z8.literal("Sdp"),
405
- type: z8.enum(["Answer", "Offer"]),
406
- sdp: z8.string(),
407
- media_map: z8.array(z8.tuple([MediaIdSchema, z8.string()]))
408
- }),
409
- z8.object({
410
- kind: z8.literal("Trickle"),
411
- candidate: z8.string(),
412
- spd_mid: z8.optional(z8.string()),
413
- spd_mline_index: z8.optional(z8.number()),
414
- username_fragment: z8.optional(z8.union([z8.string(), z8.null()]))
415
- }),
416
- z8.object({
417
- kind: z8.literal("TrickleFinished")
418
- })
419
- ]);
420
-
421
- // src/rpc/commands.ts
422
- var import_zod4 = require("zod");
423
- var MainCommandsRpc = {
424
- Hello: {
425
- request: import_zod4.z.object({
426
- stream: import_zod4.z.literal("main")
427
- }),
428
- response: import_zod4.z.null()
429
- },
430
- JoinRoom: {
431
- request: import_zod4.z.object({
432
- token: import_zod4.z.string(),
433
- room_id: RoomV1.RoomIdSchema,
434
- user_data: ByteArraySchema,
435
- position: PeerPositionSchema
436
- }),
437
- response: import_zod4.z.object({
438
- peer_id: PeerIdSchema,
439
- stream_id: import_zod4.z.optional(import_zod4.z.number()),
440
- token: import_zod4.z.optional(import_zod4.z.string())
441
- })
442
- },
443
- WebRtcUpdate: {
444
- request: WebRtcUpdateSchema,
445
- response: import_zod4.z.null()
446
- },
447
- RequestReconnectToken: {
448
- request: import_zod4.z.object({ peer_id: import_zod4.z.optional(PeerIdSchema) }),
449
- response: import_zod4.z.string()
450
- },
451
- Ping: {
452
- request: import_zod4.z.object({}),
453
- response: import_zod4.z.null()
454
- }
455
- };
456
- var RoomCommandsRpc = {
457
- Hello: {
458
- request: import_zod4.z.object({
459
- stream: import_zod4.z.literal("room"),
460
- token: import_zod4.z.string(),
461
- room_id: import_zod4.z.string(),
462
- user_data: ByteArraySchema,
463
- position: PeerPositionSchema
464
- }),
465
- response: import_zod4.z.null()
466
- },
467
- UpdatePeer: {
468
- request: import_zod4.z.object({ user_data: ByteArraySchema }),
469
- response: import_zod4.z.null()
470
- },
471
- StartMedia: {
472
- request: import_zod4.z.object({
473
- media_id: MediaIdSchema,
474
- properties: MediaPropertiesSchema
475
- }),
476
- response: import_zod4.z.null()
477
- },
478
- StopMedia: {
479
- request: import_zod4.z.object({
480
- media_id: MediaIdSchema
481
- }),
482
- response: import_zod4.z.null()
483
- },
484
- PauseMedia: {
485
- request: import_zod4.z.object({
486
- media_id: MediaIdSchema
487
- }),
488
- response: import_zod4.z.null()
489
- },
490
- ResumeMedia: {
491
- request: import_zod4.z.object({
492
- media_id: MediaIdSchema
493
- }),
494
- response: import_zod4.z.null()
495
- },
496
- SetPeerPosition: {
497
- request: import_zod4.z.object({
498
- position: PeerPositionSchema
499
- }),
500
- response: import_zod4.z.null()
501
- },
502
- SendMessage: {
503
- request: import_zod4.z.object({
504
- target_peer_ids: import_zod4.z.optional(import_zod4.z.array(PeerIdSchema)),
505
- message: ByteArraySchema
506
- }),
507
- response: import_zod4.z.null()
508
- }
509
- };
510
-
511
- // src/rpc/notifications.ts
512
- var z10 = __toESM(require("zod"));
513
- var MainNotificationSchema = z10.object({
514
- name: z10.literal("WebRtcUpdate"),
515
- properties: WebRtcUpdateSchema
516
- });
517
- var MainNotificationsRpc = {
518
- WebRtcUpdate: WebRtcUpdateSchema
519
- };
520
- var RoomNotificationSchema = z10.union([
521
- z10.object({
522
- name: z10.literal("RoomStatusChanged"),
523
- properties: RoomV1.RoomStatusChangedSchema
524
- }),
525
- z10.object({
526
- name: z10.literal("RoomUpdated"),
527
- properties: RoomV1.RoomUpdatesSchema
528
- }),
529
- z10.object({
530
- name: z10.literal("PeerUpdated"),
531
- properties: PeerUpdateSchema
532
- }),
533
- z10.object({
534
- name: z10.literal("MessageReceived"),
535
- properties: MessageReceivedSchema
536
- })
537
- ]);
538
- var RoomNotificationsRpc = {
539
- RoomStatusChanged: RoomV1.RoomStatusChangedSchema,
540
- RoomUpdated: RoomV1.RoomUpdatesSchema,
541
- PeerUpdated: PeerUpdateSchema,
542
- MessageReceived: MessageReceivedSchema
543
- };
544
-
545
- // src/utility/result.ts
546
- function assert(condition, message) {
547
- if (!condition) {
548
- fail(message);
549
- }
550
- }
551
- function fail(message) {
552
- throw new Error(message);
553
- }
554
- function success(value) {
555
- return { type: "Success", value };
556
- }
557
- function failure(reason) {
558
- return { type: "Failure", reason };
559
- }
560
- function unwrap(result) {
561
- if (result.type === "Failure") {
562
- fail(result.reason);
563
- }
564
- return result.value;
565
- }
566
- function unwrapOr(result, fallback) {
567
- return result.type === "Success" ? result.value : fallback;
568
- }
569
-
570
- // src/utility/base64.ts
571
- function fromBase64(base64) {
572
- try {
573
- const binString = atob(base64);
574
- const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
575
- const decoder = new TextDecoder("utf8");
576
- return success(decoder.decode(bytes));
577
- } catch (error2) {
578
- return failure(String(error2));
579
- }
580
- }
581
- function fromBase64Url(base64uri) {
582
- try {
583
- const binString = atob(base64uri.replace(/-/g, "+").replace(/_/g, "/"));
584
- const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
585
- const decoder = new TextDecoder("utf8");
586
- return success(decoder.decode(bytes));
587
- } catch (error2) {
588
- return failure(String(error2));
589
- }
590
- }
591
-
592
- // src/utility/bytearray.ts
593
- function toBytes(value) {
594
- try {
595
- assert(value !== void 0, "undefined cannot be converted to byte array");
596
- assert(value !== null, "null cannot be converted to byte array");
597
- const json = JSON.stringify(value);
598
- const decoder = new TextEncoder();
599
- return success(decoder.encode(json));
600
- } catch (error2) {
601
- return failure(String(error2));
602
- }
603
- }
604
- function fromBytes(bytes) {
605
- try {
606
- assert(bytes.length > 0, "empty byte array cannot be converted to value");
607
- const json = new TextDecoder().decode(bytes);
608
- const text = JSON.parse(json);
609
- return success(text);
610
- } catch (error2) {
611
- return failure(String(error2));
612
- }
613
- }
614
-
615
- // src/utility/codec.ts
616
- var validCodecs = ["VP8", "VP9", "AV1", "H264"];
617
- var VideoCodec = class {
618
- constructor(codec) {
619
- this.codec = codec;
620
- }
621
- channels = 0;
622
- clockRate = 9e4;
623
- isValid() {
624
- return validCodecs.includes(this.codec);
625
- }
626
- isSupported() {
627
- if (typeof RTCRtpReceiver === "undefined" || typeof RTCRtpReceiver.getCapabilities === "undefined") {
628
- return null;
629
- }
630
- const expectedMimeType = unwrapOr(this.getMimeType(), "").toLowerCase();
631
- const expectedFmtpLine = new Set(
632
- unwrapOr(this.getSdpFmtpLine(), "").split(";").map((arg) => arg.trim().toLowerCase())
633
- );
634
- return RTCRtpReceiver.getCapabilities("video")?.codecs?.find((c) => {
635
- const actualMimeType = c.mimeType.toLowerCase();
636
- const actualFmtpLine = new Set(
637
- (c.sdpFmtpLine ?? "").split(";").map((arg) => arg.trim().toLowerCase())
638
- );
639
- if (expectedMimeType !== actualMimeType) return false;
640
- if (expectedFmtpLine.size !== actualFmtpLine.size) return false;
641
- for (const item of expectedFmtpLine) {
642
- if (!actualFmtpLine.has(item)) return false;
643
- }
644
- return true;
645
- }) ?? null;
646
- }
647
- getPayloadType() {
648
- switch (this.codec) {
649
- case "VP8":
650
- return success(96);
651
- case "VP9":
652
- return success(98);
653
- case "AV1":
654
- return success(41);
655
- case "H264":
656
- return success(102);
657
- default:
658
- return failure("invalid video codec");
659
- }
660
- }
661
- getMimeType() {
662
- switch (this.codec) {
663
- case "VP8":
664
- return success("video/VP8");
665
- case "VP9":
666
- return success("video/VP9");
667
- case "AV1":
668
- return success("video/AV1");
669
- case "H264":
670
- return success("video/H264");
671
- default:
672
- return failure("invalid video codec");
673
- }
674
- }
675
- getSdpFmtpLine() {
676
- switch (this.codec) {
677
- case "VP8":
678
- return success("");
679
- case "VP9":
680
- return success(
681
- // using high-bit-depth variant profile
682
- "profile-id=2"
683
- );
684
- case "AV1":
685
- return success(
686
- // using baseline profile (https://aomediacodec.github.io/av1-rtp-spec/#72-sdp-parameters)
687
- "level-idx=5;profile=0;tier=0"
688
- );
689
- case "H264":
690
- return success(
691
- // using baseline profile
692
- "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"
693
- );
694
- default:
695
- return failure("invalid video codec");
696
- }
697
- }
698
- };
699
-
700
- // src/utility/iterable.ts
701
- function find(entries, predicate) {
702
- for (const entry of entries) {
703
- if (predicate(entry)) return entry;
704
- }
705
- return void 0;
706
- }
707
-
708
- // src/utility/environment.ts
709
- function isAudioCapable() {
710
- return typeof AudioContext !== "undefined" && typeof Worker !== "undefined";
711
- }
712
- function isSharedArrayBufferCapable() {
713
- return typeof SharedArrayBuffer !== "undefined";
714
- }
715
- function isBlinkBrowser() {
716
- const pattern = /(apple)?webkit\/537\.36/i;
717
- return pattern.test(globalThis.navigator.userAgent);
718
- }
719
- function isElectronBrowser() {
720
- const pattern = /electron/i;
721
- return pattern.test(globalThis.navigator.userAgent);
722
- }
723
- function isFirefoxBrowser() {
724
- const pattern = /firefox|iceweasel|fxios/i;
725
- return pattern.test(globalThis.navigator.userAgent);
726
- }
727
- function isSafariBrowser() {
728
- if (isBlinkBrowser()) return false;
729
- const pattern = /safari|applewebkit/i;
730
- return pattern.test(globalThis.navigator.userAgent);
731
- }
732
-
733
- // src/utility/json.ts
734
- function toRaw(value) {
735
- return JSON.parse(JSON.stringify(value));
736
- }
737
-
738
- // src/utility/selector.ts
739
- var Selector = class _Selector {
740
- constructor(_Generators) {
741
- this._Generators = _Generators;
742
- this._Futures = _Generators.map(_Selector.addIndex);
743
- }
744
- _Futures;
745
- async next() {
746
- const [result, index] = await Promise.race(this._Futures);
747
- this._Futures[index] = _Selector.addIndex(this._Generators[index], index);
748
- return result;
749
- }
750
- static async addIndex(generator, index) {
751
- return [await generator(), index];
752
- }
753
- };
754
-
755
- // src/utility/sleep.ts
756
- function sleep(ms, value) {
757
- if (ms <= 0) {
758
- return Promise.resolve(value);
759
- }
760
- return new Promise((resolve) => setTimeout(() => resolve(value), ms));
761
- }
762
- function abortableSleep(ms, signal) {
763
- if (signal.aborted) {
764
- return Promise.resolve("aborted");
765
- }
766
- return new Promise((resolve) => {
767
- const onAbort = () => resolve("aborted");
768
- signal.addEventListener("abort", onAbort, { once: true });
769
- setTimeout(() => {
770
- signal.removeEventListener("abort", onAbort);
771
- resolve(void 0);
772
- }, ms);
773
- });
774
- }
775
- function nextTick() {
776
- return new Promise((resolve) => setTimeout(resolve, 0));
777
- }
778
-
779
- // src/utility/strand.ts
780
- var Strand = class {
781
- _Tasks = [];
782
- _Running = false;
783
- _Values;
784
- constructor(...values) {
785
- this._Values = values;
786
- }
787
- enqueue(task) {
788
- return new Promise((resolve, reject) => {
789
- const wrapped = async () => {
790
- try {
791
- const result = await task(...this._Values);
792
- resolve(result);
793
- } catch (error2) {
794
- reject(error2);
795
- }
796
- };
797
- this._Tasks.push(wrapped);
798
- if (!this._Running) {
799
- this.execute();
800
- }
801
- });
802
- }
803
- async execute() {
804
- this._Running = true;
805
- while (true) {
806
- const task = this._Tasks.shift();
807
- if (task === void 0) break;
808
- await task();
809
- }
810
- this._Running = false;
811
- }
812
- };
813
-
814
- // src/utility/url.ts
815
- function normalizeUrl(url) {
816
- let normalized = url.trim();
817
- if (url.indexOf("://") === -1) normalized = `https://${normalized}`;
818
- try {
819
- return success(new URL(normalized));
820
- } catch (error2) {
821
- return failure(String(error2));
822
- }
823
- }
824
- function extendUrl(base, path) {
825
- let pathname = base.pathname;
826
- if (pathname.endsWith("/") === false) pathname += "/";
827
- try {
828
- return success(new URL(pathname + path, base));
829
- } catch (error2) {
830
- return failure(String(error2));
831
- }
832
- }
833
-
834
- // src/utility/uuid.ts
835
- var SCHEMA = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
836
- function generateUUID() {
837
- return crypto.randomUUID();
838
- }
839
- function validateUUID(uuid) {
840
- return SCHEMA.test(uuid);
841
- }
842
-
843
- // src/utility/validation.ts
844
- function isProperty(object6, name) {
845
- return name in object6;
846
- }
847
- function isFunction(value) {
848
- return typeof value === "function";
849
- }
850
- function isNull(value) {
851
- return typeof value === "object" && value === null;
852
- }
853
- function isNumber(value) {
854
- return typeof value === "number";
855
- }
856
- function isObject(value) {
857
- return typeof value === "object";
858
- }
859
- function isString(value) {
860
- return typeof value === "string";
861
- }
862
- function isUndefined(value) {
863
- return typeof value === "undefined";
864
- }
865
- function isFailure(result) {
866
- return result.type === "Failure";
867
- }
868
- function isSuccess(result) {
869
- return result.type === "Success";
870
- }
871
-
872
- // src/utility/log.ts
873
- var LogVerbosity = /* @__PURE__ */ ((LogVerbosity2) => {
874
- LogVerbosity2[LogVerbosity2["NONE"] = 0] = "NONE";
875
- LogVerbosity2[LogVerbosity2["ERROR"] = 1] = "ERROR";
876
- LogVerbosity2[LogVerbosity2["WARN"] = 2] = "WARN";
877
- LogVerbosity2[LogVerbosity2["INFO"] = 3] = "INFO";
878
- LogVerbosity2[LogVerbosity2["DEBUG"] = 4] = "DEBUG";
879
- return LogVerbosity2;
880
- })(LogVerbosity || {});
881
- var LogLevels = Object.values(LogVerbosity).filter(
882
- (key) => !isNaN(Number(key))
883
- );
884
- var LogLevelNames = Object.keys(LogVerbosity).filter(
885
- (key) => isNaN(Number(key))
886
- );
887
- var LogSymbols = {
888
- [0 /* NONE */]: "\u26AB",
889
- [1 /* ERROR */]: "\u{1F534}",
890
- [2 /* WARN */]: "\u{1F7E1}",
891
- [3 /* INFO */]: "\u{1F535}",
892
- [4 /* DEBUG */]: "\u{1F7E3}"
893
- };
894
- var LogFunctions = {
895
- [0 /* NONE */]: console.log,
896
- [1 /* ERROR */]: console.error,
897
- [2 /* WARN */]: console.warn,
898
- [3 /* INFO */]: console.info,
899
- [4 /* DEBUG */]: console.debug
900
- };
901
- function getLevelByName(name) {
902
- const level = LogVerbosity[name];
903
- if (level === void 0) {
904
- return failure(
905
- `invalid log level name '${name}'; valid names are: ${LogLevelNames.join(", ")}`
906
- );
907
- }
908
- return success(level);
909
- }
910
- function getLevelName(level) {
911
- const name = LogVerbosity[level];
912
- if (name === void 0) {
913
- return failure(
914
- `invalid log level ${level}; valid levels are: ${LogLevels[0]}-${LogLevels[LogLevels.length - 1]}`
915
- );
916
- }
917
- return success(name);
918
- }
919
- var LOG_DEFAULT_ID = "default";
920
- var LOG_COLLECTION = /* @__PURE__ */ new Map();
921
- function getLogger(name = LOG_DEFAULT_ID) {
922
- let logger = LOG_COLLECTION.get(name);
923
- if (!logger) {
924
- logger = new Logger("WARN", name);
925
- }
926
- return logger;
927
- }
928
- function error(msg, ...args) {
929
- if (msg instanceof Function) {
930
- return getLogger(LOG_DEFAULT_ID).error(msg, ...args);
931
- }
932
- return getLogger(LOG_DEFAULT_ID).error(msg, ...args);
933
- }
934
- function warn(msg, ...args) {
935
- if (msg instanceof Function) {
936
- return getLogger(LOG_DEFAULT_ID).warn(msg, ...args);
937
- }
938
- return getLogger(LOG_DEFAULT_ID).warn(msg, ...args);
939
- }
940
- function info(msg, ...args) {
941
- if (msg instanceof Function) {
942
- return getLogger(LOG_DEFAULT_ID).info(msg, ...args);
943
- }
944
- return getLogger(LOG_DEFAULT_ID).info(msg, ...args);
945
- }
946
- function debug(msg, ...args) {
947
- if (msg instanceof Function) {
948
- return getLogger(LOG_DEFAULT_ID).debug(msg, ...args);
949
- }
950
- return getLogger(LOG_DEFAULT_ID).debug(msg, ...args);
951
- }
952
- var Logger = class {
953
- name;
954
- _Level;
955
- _Handlers;
956
- constructor(level, name, options) {
957
- this.name = name ?? LOG_DEFAULT_ID;
958
- if (isNumber(level)) {
959
- this._Level = unwrap(getLevelByName(unwrap(getLevelName(level))));
960
- } else {
961
- this._Level = unwrap(getLevelByName(level));
962
- }
963
- this._Handlers = options?.handlers || [new LogHandler(level)];
964
- LOG_COLLECTION.set(this.name, this);
965
- }
966
- get level() {
967
- return this._Level;
968
- }
969
- set level(value) {
970
- this.levelName = unwrap(getLevelName(value));
971
- }
972
- get levelName() {
973
- return unwrap(getLevelName(this._Level));
974
- }
975
- set levelName(value) {
976
- this._Level = unwrap(getLevelByName(value));
977
- this._Handlers.forEach((handler) => handler.level = this._Level);
978
- }
979
- get handlers() {
980
- return this._Handlers;
981
- }
982
- addHandler(handler) {
983
- this._Handlers.push(handler);
984
- }
985
- removeHandler(handler) {
986
- const index = this._Handlers.indexOf(handler);
987
- if (index !== -1) this._Handlers.splice(index, 1);
988
- }
989
- log(level, msg, ...args) {
990
- if (this.level < level) {
991
- return msg instanceof Function ? void 0 : msg;
992
- }
993
- let fnResult;
994
- let message;
995
- if (msg instanceof Function) {
996
- fnResult = msg();
997
- message = this.asString(fnResult);
998
- } else {
999
- message = this.asString(msg);
1000
- }
1001
- this._Handlers.forEach((handler) => {
1002
- handler.handle({
1003
- date: /* @__PURE__ */ new Date(),
1004
- level,
1005
- levelName: unwrap(getLevelName(level)),
1006
- logger: this.name,
1007
- message,
1008
- args
1009
- });
1010
- });
1011
- return msg instanceof Function ? fnResult : msg;
1012
- }
1013
- error(msg, ...args) {
1014
- return this.log(1 /* ERROR */, msg, ...args);
1015
- }
1016
- warn(msg, ...args) {
1017
- return this.log(2 /* WARN */, msg, ...args);
1018
- }
1019
- info(msg, ...args) {
1020
- return this.log(3 /* INFO */, msg, ...args);
1021
- }
1022
- debug(msg, ...args) {
1023
- return this.log(4 /* DEBUG */, msg, ...args);
1024
- }
1025
- asString(data, isProperty2 = false) {
1026
- if (typeof data === "string") {
1027
- if (isProperty2) return `"${data}"`;
1028
- return data;
1029
- } else if (data === null || typeof data === "number" || typeof data === "bigint" || typeof data === "boolean" || typeof data === "undefined" || typeof data === "symbol") {
1030
- return String(data);
1031
- } else if (data instanceof Error) {
1032
- return data.stack;
1033
- } else if (typeof data === "object") {
1034
- return `{${Object.entries(data).map(([k, v]) => `"${k}":${this.asString(v, true)}`).join(",")}}`;
1035
- }
1036
- return "undefined";
1037
- }
1038
- };
1039
- var DEFAULT_FORMATTER = ({ message }) => message;
1040
- var PRETTY_FORMATTER = (record2) => {
1041
- const date = `[${record2.date.toISOString()}]`;
1042
- const level = `[${record2.levelName}]`;
1043
- const logger = record2.logger !== LOG_DEFAULT_ID ? `[${record2.logger}] ` : "";
1044
- const symbol = LogSymbols[record2.level];
1045
- return `${date} ${symbol} ${level.padEnd(7, " ")} ${logger}${record2.message}`;
1046
- };
1047
- var LogHandler = class {
1048
- _Level;
1049
- _FormatterFn;
1050
- constructor(level, formatter = DEFAULT_FORMATTER) {
1051
- if (isNumber(level)) {
1052
- this._Level = unwrap(getLevelByName(unwrap(getLevelName(level))));
1053
- } else {
1054
- this._Level = unwrap(getLevelByName(level));
1055
- }
1056
- this._FormatterFn = formatter;
1057
- }
1058
- get level() {
1059
- return this._Level;
1060
- }
1061
- set level(value) {
1062
- this.levelName = unwrap(getLevelName(value));
1063
- }
1064
- get levelName() {
1065
- return unwrap(getLevelName(this._Level));
1066
- }
1067
- set levelName(value) {
1068
- this._Level = unwrap(getLevelByName(value));
1069
- }
1070
- handle(record2) {
1071
- if (this._Level < record2.level) return;
1072
- this.log(this._FormatterFn(record2), record2);
1073
- }
1074
- log(formattedString, record2) {
1075
- LogFunctions[record2.level](formattedString, ...record2.args);
1076
- }
1077
- };
1078
-
1079
- // src/plugin/api.ts
1080
- var MinDBFS = -758.596;
1081
- var Backend;
1082
- ((Backend2) => {
1083
- let Transport;
1084
- ((Transport2) => {
1085
- Transport2["H3"] = "h3";
1086
- Transport2["WebRTC"] = "webrtc";
1087
- })(Transport = Backend2.Transport || (Backend2.Transport = {}));
1088
- let PeerCipherStatus;
1089
- ((PeerCipherStatus2) => {
1090
- PeerCipherStatus2[PeerCipherStatus2["InvalidPassword"] = -1] = "InvalidPassword";
1091
- PeerCipherStatus2[PeerCipherStatus2["Unknown"] = 0] = "Unknown";
1092
- PeerCipherStatus2[PeerCipherStatus2["Unencrypted"] = 1] = "Unencrypted";
1093
- PeerCipherStatus2[PeerCipherStatus2["Encrypted"] = 2] = "Encrypted";
1094
- })(PeerCipherStatus = Backend2.PeerCipherStatus || (Backend2.PeerCipherStatus = {}));
1095
- })(Backend || (Backend = {}));
1096
- // Annotate the CommonJS export names for ESM import in node:
1097
- 0 && (module.exports = {
1098
- Backend,
1099
- ByteArraySchema,
1100
- ChannelSet,
1101
- ChannelSetSchema,
1102
- DEFAULT_FORMATTER,
1103
- JsonSchema,
1104
- LogFunctions,
1105
- LogHandler,
1106
- LogLevelNames,
1107
- LogLevels,
1108
- LogSymbols,
1109
- LogVerbosity,
1110
- Logger,
1111
- MainCommandsRpc,
1112
- MainNotificationSchema,
1113
- MainNotificationsRpc,
1114
- MediaAudioPropertiesSchema,
1115
- MediaIdSchema,
1116
- MediaPropertiesSchema,
1117
- MediaSchema,
1118
- MediaVideoPropertiesSchema,
1119
- MessagePackRpcSchema,
1120
- MessageReceivedSchema,
1121
- MinDBFS,
1122
- PRETTY_FORMATTER,
1123
- PeerIdSchema,
1124
- PeerPositionSchema,
1125
- PeerSchema,
1126
- PeerUpdateSchema,
1127
- RoomCommandsRpc,
1128
- RoomNotificationSchema,
1129
- RoomNotificationsRpc,
1130
- RoomV1,
1131
- RoomV2,
1132
- Selector,
1133
- Strand,
1134
- TokenAudienceSchema,
1135
- TokenClaimsSchema,
1136
- TokenSubjectSchema,
1137
- VideoCodec,
1138
- WebRtcUpdateSchema,
1139
- abortableSleep,
1140
- assert,
1141
- debug,
1142
- error,
1143
- extendUrl,
1144
- fail,
1145
- failure,
1146
- find,
1147
- fromBase64,
1148
- fromBase64Url,
1149
- fromBytes,
1150
- generateUUID,
1151
- getLevelByName,
1152
- getLevelName,
1153
- getLogger,
1154
- info,
1155
- isAudioCapable,
1156
- isBlinkBrowser,
1157
- isElectronBrowser,
1158
- isFailure,
1159
- isFirefoxBrowser,
1160
- isFunction,
1161
- isNull,
1162
- isNumber,
1163
- isObject,
1164
- isProperty,
1165
- isSafariBrowser,
1166
- isSharedArrayBufferCapable,
1167
- isString,
1168
- isSuccess,
1169
- isUndefined,
1170
- nextTick,
1171
- normalizeUrl,
1172
- oneOrMany,
1173
- sleep,
1174
- success,
1175
- toBytes,
1176
- toRaw,
1177
- unwrap,
1178
- unwrapOr,
1179
- validateUUID,
1180
- warn,
1181
- zod
1182
- });
1
+ var Se=Object.create;var N=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty;var we=(t,e)=>{for(var r in e)N(t,r,{get:e[r],enumerable:!0})},X=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let p of Le(e))!Pe.call(t,p)&&p!==r&&N(t,p,{get:()=>e[p],enumerable:!(s=ze(e,p))||s.enumerable});return t};var w=(t,e,r)=>(r=t!=null?Se(ke(t)):{},X(e||!t||!t.__esModule?N(r,"default",{value:t,enumerable:!0}):r,t)),Re=t=>X(N({},"__esModule",{value:!0}),t);var xt={};we(xt,{Backend:()=>me,ByteArraySchema:()=>g,ChannelSet:()=>B,ChannelSetSchema:()=>W,DEFAULT_FORMATTER:()=>le,JsonSchema:()=>A,LogFunctions:()=>ue,LogHandler:()=>q,LogLevelNames:()=>ce,LogLevels:()=>G,LogSymbols:()=>pe,LogVerbosity:()=>C,Logger:()=>$,MainCommandsRpc:()=>je,MainNotificationSchema:()=>Fe,MainNotificationsRpc:()=>Ne,MediaAudioPropertiesSchema:()=>re,MediaIdSchema:()=>T,MediaPropertiesSchema:()=>U,MediaSchema:()=>I,MediaVideoPropertiesSchema:()=>ne,MessagePackRpcSchema:()=>Ce,MessageReceivedSchema:()=>V,MinDBFS:()=>gr,PRETTY_FORMATTER:()=>yt,PeerIdSchema:()=>v,PeerPositionSchema:()=>M,PeerSchema:()=>O,PeerUpdateSchema:()=>E,RoomCommandsRpc:()=>Me,RoomNotificationSchema:()=>Ue,RoomNotificationsRpc:()=>Ie,RoomV1:()=>L,RoomV2:()=>ie,Selector:()=>Y,Strand:()=>Q,TokenAudienceSchema:()=>ee,TokenClaimsSchema:()=>Ae,TokenSubjectSchema:()=>te,VideoCodec:()=>K,WebRtcUpdateSchema:()=>_,abortableSleep:()=>Ye,assert:()=>F,debug:()=>gt,error:()=>lt,extendUrl:()=>et,fail:()=>Z,failure:()=>x,find:()=>Je,fromBase64:()=>Oe,fromBase64Url:()=>Ee,fromBytes:()=>Be,generateUUID:()=>rt,getLevelByName:()=>R,getLevelName:()=>P,getLogger:()=>k,info:()=>ft,isAudioCapable:()=>He,isBlinkBrowser:()=>se,isElectronBrowser:()=>$e,isFailure:()=>ut,isFirefoxBrowser:()=>qe,isFunction:()=>it,isNull:()=>at,isNumber:()=>H,isObject:()=>st,isProperty:()=>ot,isSafariBrowser:()=>We,isSharedArrayBufferCapable:()=>Ge,isString:()=>ct,isSuccess:()=>dt,isUndefined:()=>pt,nextTick:()=>Qe,normalizeUrl:()=>Xe,oneOrMany:()=>j,sleep:()=>Ke,success:()=>f,toBytes:()=>De,toRaw:()=>Ze,unwrap:()=>b,unwrapOr:()=>J,validateUUID:()=>nt,warn:()=>mt,zod:()=>bt});module.exports=Re(xt);var bt=w(require("zod"));var d=require("zod"),g=d.z.custom(t=>t instanceof Uint8Array),_e=d.z.union([d.z.string(),d.z.number(),d.z.boolean(),d.z.null()]),A=d.z.lazy(()=>d.z.union([_e,d.z.array(A),d.z.record(A)])),Ce=d.z.union([d.z.tuple([d.z.literal(0),d.z.number(),d.z.string(),d.z.unknown()]),d.z.tuple([d.z.literal(1),d.z.number(),d.z.nullable(d.z.string()),d.z.unknown()]),d.z.tuple([d.z.literal(2),d.z.string(),d.z.unknown()])]);var c=require("zod"),ee=c.z.enum(["sfu","gateway"]),te=c.z.enum(["connect","roomclose","roomupdate","roombanclient","roomsendmessage"]),Ae=c.z.object({uid:c.z.string(),cid:c.z.optional(c.z.string()),rid:j(c.z.string()).refine(t=>t.length>=1,{message:"missing rid"}),nsp:c.z.optional(c.z.string()),adr:c.z.optional(c.z.string()),aud:c.z.optional(j(ee)),sub:c.z.optional(j(te)),exp:c.z.optional(c.z.number()),nbf:c.z.optional(c.z.number()),ups:c.z.optional(c.z.string()),tgs:c.z.optional(j(c.z.string())),tsp:c.z.optional(c.z.number()),internal:c.z.optional(c.z.object({server:c.z.optional(c.z.string())}))});function j(t){return c.z.union([t.transform(e=>[e]),c.z.array(t)])}var n=w(require("zod"));var l=w(require("zod")),T=l.number(),re=l.object({kind:l.optional(l.literal("audio")),uid:l.optional(l.string()),customType:l.optional(l.string())}),ne=l.object({kind:l.optional(l.literal("video")),codec:l.optional(l.string()),uid:l.optional(l.string()),customType:l.optional(l.string())}),U=l.union([re,ne]),I=l.object({id:T,properties:U,paused:l.boolean()});var m=w(require("zod"));var v=m.number(),M=m.union([m.tuple([m.number(),m.number(),m.number()]),m.tuple([m.number(),m.number()])]),O=m.object({id:v,user_id:m.string(),user_data:g,medias:m.array(I)}),E=m.discriminatedUnion("kind",[m.object({kind:m.literal("UserDataChanged"),peer_id:v,user_data:g}),m.object({kind:m.literal("MediaStarted"),peer_id:v,media:I}),m.object({kind:m.literal("MediaStopped"),peer_id:v,media_id:T})]);var oe=w(require("zod")),B=class t{constructor(e=BigInt(0)){this.value=e}from(...e){let r=e.reduce((s,p)=>s|D(p),BigInt(0));return new t(r)}contains(e){return(this.value&D(e))!==BigInt(0)}insert(e){this.value|=D(e)}remove(e){this.value&=~D(e)}[Symbol.iterator](){let e=-1,r=new t(this.value);return{next(){for(;e<63;)if(e+=1,r.contains(e))return{value:e,done:!1};return{value:void 0,done:!0}}}}},W=oe.bigint().transform(t=>new B(t));function D(t){return BigInt(1)<<BigInt(t)}var L;(y=>(y.RoomIdSchema=n.string(),y.RoomSchema=n.object({id:y.RoomIdSchema,customer:n.string(),user_data:g,peers:n.array(O)}),y.RoomUpdateSchema=n.discriminatedUnion("kind",[n.object({kind:n.literal("Joined"),room:y.RoomSchema,media_ids:n.array(T),own_peer_id:v}),n.object({kind:n.literal("Left"),reason:n.enum(["RoomClosing","ServerClosing","PeerKicked"])}),n.object({kind:n.literal("UserDataChanged"),user_data:n.optional(g)}),n.object({kind:n.literal("PeerJoined"),peer:O}),n.object({kind:n.literal("PeerLeft"),peer_id:v})]),y.RoomUpdatesSchema=n.object({updates:n.array(y.RoomUpdateSchema)}),y.RoomStatusSchema=n.enum(["Joining","Joined","Closed"]),y.RoomStatusChangedSchema=n.object({status:y.RoomStatusSchema,message:n.optional(n.string())})))(L||={});var ie;(i=>(i.ParametersSchema=n.record(A),i.PeerProperties=n.object({user_data:g.optional(),tags:n.array(n.string()).optional(),audio_parameters:i.ParametersSchema.optional(),video_parameters:i.ParametersSchema.optional()}),i.PingSchema=n.object({Ping:n.object({id:n.number()})}),i.ChangeSelfSchema=n.object({ChangeSelf:i.PeerProperties.omit({tags:!0})}),i.SetAudioMaskSchema=n.object({SetAudioMask:n.object({peer_id:n.number(),mask:W})}),i.SendMessageSchema=n.object({SendMessage:n.object({peer_ids:n.number().array().default([]),message:g})}),i.CallSchema=i.PingSchema.or(i.ChangeSelfSchema).or(i.SetAudioMaskSchema).or(i.SendMessageSchema),i.PongSchema=n.object({Pong:n.object({id:n.number()})}),i.JoinedSchema=n.object({Joined:n.object({own_peer_id:n.number(),room_id:n.string(),customer:n.string()})}),i.LeftSchema=n.object({Left:n.object({reason:n.enum(["room_closing","server_closing","peer_kicked"])})}),i.PeerJoinedSchema=n.object({PeerJoined:i.PeerProperties.extend({peer_id:n.number(),user_id:n.string()})}),i.PeerLeftSchema=n.object({PeerLeft:n.object({peer_id:n.number()})}),i.PeerChangedSchema=n.object({PeerChanged:i.PeerProperties.extend({peer_id:n.number()})}),i.NewReconnectTokenSchema=n.object({NewReconnectToken:n.object({token:n.string()})}),i.MessageReceivedSchema=n.object({MessageReceived:n.object({sender_peer_id:n.number(),message:g})}),i.ErrorSchema=n.object({Error:n.object({message:g})}),i.EventSchema=i.PongSchema.or(i.JoinedSchema).or(i.LeftSchema).or(i.PeerJoinedSchema).or(i.PeerLeftSchema).or(i.PeerChangedSchema).or(i.NewReconnectTokenSchema).or(i.MessageReceivedSchema).or(i.ErrorSchema)))(ie||={});var ae=require("zod");var V=ae.z.object({sender_peer_id:v,message:g});var a=w(require("zod"));var _=a.discriminatedUnion("kind",[a.object({kind:a.literal("Sdp"),type:a.enum(["Answer","Offer"]),sdp:a.string(),media_map:a.array(a.tuple([T,a.string()]))}),a.object({kind:a.literal("Trickle"),candidate:a.string(),spd_mid:a.optional(a.string()),spd_mline_index:a.optional(a.number()),username_fragment:a.optional(a.union([a.string(),a.null()]))}),a.object({kind:a.literal("TrickleFinished")})]);var o=require("zod");var je={Hello:{request:o.z.object({stream:o.z.literal("main")}),response:o.z.null()},JoinRoom:{request:o.z.object({token:o.z.string(),room_id:L.RoomIdSchema,user_data:g,position:M}),response:o.z.object({peer_id:v,stream_id:o.z.optional(o.z.number()),token:o.z.optional(o.z.string())})},WebRtcUpdate:{request:_,response:o.z.null()},RequestReconnectToken:{request:o.z.object({peer_id:o.z.optional(v)}),response:o.z.string()},Ping:{request:o.z.object({}),response:o.z.null()}},Me={Hello:{request:o.z.object({stream:o.z.literal("room"),token:o.z.string(),room_id:o.z.string(),user_data:g,position:M}),response:o.z.null()},UpdatePeer:{request:o.z.object({user_data:g}),response:o.z.null()},StartMedia:{request:o.z.object({media_id:T,properties:U}),response:o.z.null()},StopMedia:{request:o.z.object({media_id:T}),response:o.z.null()},PauseMedia:{request:o.z.object({media_id:T}),response:o.z.null()},ResumeMedia:{request:o.z.object({media_id:T}),response:o.z.null()},SetPeerPosition:{request:o.z.object({position:M}),response:o.z.null()},SendMessage:{request:o.z.object({target_peer_ids:o.z.optional(o.z.array(v)),message:g}),response:o.z.null()}};var h=w(require("zod"));var Fe=h.object({name:h.literal("WebRtcUpdate"),properties:_}),Ne={WebRtcUpdate:_},Ue=h.union([h.object({name:h.literal("RoomStatusChanged"),properties:L.RoomStatusChangedSchema}),h.object({name:h.literal("RoomUpdated"),properties:L.RoomUpdatesSchema}),h.object({name:h.literal("PeerUpdated"),properties:E}),h.object({name:h.literal("MessageReceived"),properties:V})]),Ie={RoomStatusChanged:L.RoomStatusChangedSchema,RoomUpdated:L.RoomUpdatesSchema,PeerUpdated:E,MessageReceived:V};function F(t,e){t||Z(e)}function Z(t){throw new Error(t)}function f(t){return{type:"Success",value:t}}function x(t){return{type:"Failure",reason:t}}function b(t){return t.type==="Failure"&&Z(t.reason),t.value}function J(t,e){return t.type==="Success"?t.value:e}function Oe(t){try{let e=atob(t),r=Uint8Array.from(e,p=>p.codePointAt(0)),s=new TextDecoder("utf8");return f(s.decode(r))}catch(e){return x(String(e))}}function Ee(t){try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),r=Uint8Array.from(e,p=>p.codePointAt(0)),s=new TextDecoder("utf8");return f(s.decode(r))}catch(e){return x(String(e))}}function De(t){try{F(t!==void 0,"undefined cannot be converted to byte array"),F(t!==null,"null cannot be converted to byte array");let e=JSON.stringify(t),r=new TextEncoder;return f(r.encode(e))}catch(e){return x(String(e))}}function Be(t){try{F(t.length>0,"empty byte array cannot be converted to value");let e=new TextDecoder().decode(t),r=JSON.parse(e);return f(r)}catch(e){return x(String(e))}}var Ve=["VP8","VP9","AV1","H264"],K=class{constructor(e){this.codec=e}channels=0;clockRate=9e4;isValid(){return Ve.includes(this.codec)}isSupported(){if(typeof RTCRtpReceiver>"u"||typeof RTCRtpReceiver.getCapabilities>"u")return null;let e=J(this.getMimeType(),"").toLowerCase(),r=new Set(J(this.getSdpFmtpLine(),"").split(";").map(s=>s.trim().toLowerCase()));return RTCRtpReceiver.getCapabilities("video")?.codecs?.find(s=>{let p=s.mimeType.toLowerCase(),u=new Set((s.sdpFmtpLine??"").split(";").map(y=>y.trim().toLowerCase()));if(e!==p||r.size!==u.size)return!1;for(let y of r)if(!u.has(y))return!1;return!0})??null}getPayloadType(){switch(this.codec){case"VP8":return f(96);case"VP9":return f(98);case"AV1":return f(41);case"H264":return f(102);default:return x("invalid video codec")}}getMimeType(){switch(this.codec){case"VP8":return f("video/VP8");case"VP9":return f("video/VP9");case"AV1":return f("video/AV1");case"H264":return f("video/H264");default:return x("invalid video codec")}}getSdpFmtpLine(){switch(this.codec){case"VP8":return f("");case"VP9":return f("profile-id=2");case"AV1":return f("level-idx=5;profile=0;tier=0");case"H264":return f("level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f");default:return x("invalid video codec")}}};function Je(t,e){for(let r of t)if(e(r))return r}function He(){return typeof AudioContext<"u"&&typeof Worker<"u"}function Ge(){return typeof SharedArrayBuffer<"u"}function se(){return/(apple)?webkit\/537\.36/i.test(globalThis.navigator.userAgent)}function $e(){return/electron/i.test(globalThis.navigator.userAgent)}function qe(){return/firefox|iceweasel|fxios/i.test(globalThis.navigator.userAgent)}function We(){return se()?!1:/safari|applewebkit/i.test(globalThis.navigator.userAgent)}function Ze(t){return JSON.parse(JSON.stringify(t))}var Y=class t{constructor(e){this._Generators=e;this._Futures=e.map(t.addIndex)}_Futures;async next(){let[e,r]=await Promise.race(this._Futures);return this._Futures[r]=t.addIndex(this._Generators[r],r),e}static async addIndex(e,r){return[await e(),r]}};function Ke(t,e){return t<=0?Promise.resolve(e):new Promise(r=>setTimeout(()=>r(e),t))}function Ye(t,e){return e.aborted?Promise.resolve("aborted"):new Promise(r=>{let s=()=>r("aborted");e.addEventListener("abort",s,{once:!0}),setTimeout(()=>{e.removeEventListener("abort",s),r(void 0)},t)})}function Qe(){return new Promise(t=>setTimeout(t,0))}var Q=class{_Tasks=[];_Running=!1;_Values;constructor(...e){this._Values=e}enqueue(e){return new Promise((r,s)=>{let p=async()=>{try{let u=await e(...this._Values);r(u)}catch(u){s(u)}};this._Tasks.push(p),this._Running||this.execute()})}async execute(){for(this._Running=!0;;){let e=this._Tasks.shift();if(e===void 0)break;await e()}this._Running=!1}};function Xe(t){let e=t.trim();t.indexOf("://")===-1&&(e=`https://${e}`);try{return f(new URL(e))}catch(r){return x(String(r))}}function et(t,e){let r=t.pathname;r.endsWith("/")===!1&&(r+="/");try{return f(new URL(r+e,t))}catch(s){return x(String(s))}}var tt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function rt(){return crypto.randomUUID()}function nt(t){return tt.test(t)}function ot(t,e){return e in t}function it(t){return typeof t=="function"}function at(t){return typeof t=="object"&&t===null}function H(t){return typeof t=="number"}function st(t){return typeof t=="object"}function ct(t){return typeof t=="string"}function pt(t){return typeof t>"u"}function ut(t){return t.type==="Failure"}function dt(t){return t.type==="Success"}var C=(u=>(u[u.NONE=0]="NONE",u[u.ERROR=1]="ERROR",u[u.WARN=2]="WARN",u[u.INFO=3]="INFO",u[u.DEBUG=4]="DEBUG",u))(C||{}),G=Object.values(C).filter(t=>!isNaN(Number(t))),ce=Object.keys(C).filter(t=>isNaN(Number(t))),pe={0:"\u26AB",1:"\u{1F534}",2:"\u{1F7E1}",3:"\u{1F535}",4:"\u{1F7E3}"},ue={0:console.log,1:console.error,2:console.warn,3:console.info,4:console.debug};function R(t){let e=C[t];return e===void 0?x(`invalid log level name '${t}'; valid names are: ${ce.join(", ")}`):f(e)}function P(t){let e=C[t];return e===void 0?x(`invalid log level ${t}; valid levels are: ${G[0]}-${G[G.length-1]}`):f(e)}var S="default",de=new Map;function k(t=S){let e=de.get(t);return e||(e=new $("WARN",t)),e}function lt(t,...e){return t instanceof Function?k(S).error(t,...e):k(S).error(t,...e)}function mt(t,...e){return t instanceof Function?k(S).warn(t,...e):k(S).warn(t,...e)}function ft(t,...e){return t instanceof Function?k(S).info(t,...e):k(S).info(t,...e)}function gt(t,...e){return t instanceof Function?k(S).debug(t,...e):k(S).debug(t,...e)}var $=class{name;_Level;_Handlers;constructor(e,r,s){this.name=r??S,H(e)?this._Level=b(R(b(P(e)))):this._Level=b(R(e)),this._Handlers=s?.handlers||[new q(e)],de.set(this.name,this)}get level(){return this._Level}set level(e){this.levelName=b(P(e))}get levelName(){return b(P(this._Level))}set levelName(e){this._Level=b(R(e)),this._Handlers.forEach(r=>r.level=this._Level)}get handlers(){return this._Handlers}addHandler(e){this._Handlers.push(e)}removeHandler(e){let r=this._Handlers.indexOf(e);r!==-1&&this._Handlers.splice(r,1)}log(e,r,...s){if(this.level<e)return r instanceof Function?void 0:r;let p,u;return r instanceof Function?(p=r(),u=this.asString(p)):u=this.asString(r),this._Handlers.forEach(y=>{y.handle({date:new Date,level:e,levelName:b(P(e)),logger:this.name,message:u,args:s})}),r instanceof Function?p:r}error(e,...r){return this.log(1,e,...r)}warn(e,...r){return this.log(2,e,...r)}info(e,...r){return this.log(3,e,...r)}debug(e,...r){return this.log(4,e,...r)}asString(e,r=!1){return typeof e=="string"?r?`"${e}"`:e:e===null||typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"||typeof e>"u"||typeof e=="symbol"?String(e):e instanceof Error?e.stack:typeof e=="object"?`{${Object.entries(e).map(([s,p])=>`"${s}":${this.asString(p,!0)}`).join(",")}}`:"undefined"}},le=({message:t})=>t,yt=t=>{let e=`[${t.date.toISOString()}]`,r=`[${t.levelName}]`,s=t.logger!==S?`[${t.logger}] `:"",p=pe[t.level];return`${e} ${p} ${r.padEnd(7," ")} ${s}${t.message}`},q=class{_Level;_FormatterFn;constructor(e,r=le){H(e)?this._Level=b(R(b(P(e)))):this._Level=b(R(e)),this._FormatterFn=r}get level(){return this._Level}set level(e){this.levelName=b(P(e))}get levelName(){return b(P(this._Level))}set levelName(e){this._Level=b(R(e))}handle(e){this._Level<e.level||this.log(this._FormatterFn(e),e)}log(e,r){ue[r.level](e,...r.args)}};var gr=-758.596,me;(r=>{let t;(u=>(u.H3="h3",u.WebRTC="webrtc"))(t=r.Transport||={});let e;(z=>(z[z.InvalidPassword=-1]="InvalidPassword",z[z.Unknown=0]="Unknown",z[z.Unencrypted=1]="Unencrypted",z[z.Encrypted=2]="Encrypted"))(e=r.PeerCipherStatus||={})})(me||={});0&&(module.exports={Backend,ByteArraySchema,ChannelSet,ChannelSetSchema,DEFAULT_FORMATTER,JsonSchema,LogFunctions,LogHandler,LogLevelNames,LogLevels,LogSymbols,LogVerbosity,Logger,MainCommandsRpc,MainNotificationSchema,MainNotificationsRpc,MediaAudioPropertiesSchema,MediaIdSchema,MediaPropertiesSchema,MediaSchema,MediaVideoPropertiesSchema,MessagePackRpcSchema,MessageReceivedSchema,MinDBFS,PRETTY_FORMATTER,PeerIdSchema,PeerPositionSchema,PeerSchema,PeerUpdateSchema,RoomCommandsRpc,RoomNotificationSchema,RoomNotificationsRpc,RoomV1,RoomV2,Selector,Strand,TokenAudienceSchema,TokenClaimsSchema,TokenSubjectSchema,VideoCodec,WebRtcUpdateSchema,abortableSleep,assert,debug,error,extendUrl,fail,failure,find,fromBase64,fromBase64Url,fromBytes,generateUUID,getLevelByName,getLevelName,getLogger,info,isAudioCapable,isBlinkBrowser,isElectronBrowser,isFailure,isFirefoxBrowser,isFunction,isNull,isNumber,isObject,isProperty,isSafariBrowser,isSharedArrayBufferCapable,isString,isSuccess,isUndefined,nextTick,normalizeUrl,oneOrMany,sleep,success,toBytes,toRaw,unwrap,unwrapOr,validateUUID,warn,zod});