farvex 0.1.0 → 0.2.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.
@@ -1,6 +1,2902 @@
1
- // src/core/index.ts
2
- var corePlaceholder = "farvex/core";
1
+ import { io } from 'socket.io-client';
2
+ import { Room, RoomEvent, ConnectionState, Track, ConnectionQuality } from 'livekit-client';
3
3
 
4
- export { corePlaceholder };
4
+ // src/shared/types.ts
5
+ function nullify(value) {
6
+ if (value === void 0 || value === null) {
7
+ return null;
8
+ }
9
+ if (typeof value === "string" && value.length === 0) {
10
+ return null;
11
+ }
12
+ return value;
13
+ }
14
+
15
+ // src/shared/error.ts
16
+ function make(kind, retryable, code, title, overrides = {}) {
17
+ return {
18
+ kind,
19
+ code,
20
+ title,
21
+ retryable,
22
+ ...overrides
23
+ };
24
+ }
25
+ var callpadError = {
26
+ validation: (code, title, ov) => make("validation", false, code, title, ov),
27
+ unauth: (code, title, ov) => make("unauth", false, code, title, ov),
28
+ forbidden: (code, title, ov) => make("forbidden", false, code, title, ov),
29
+ notfound: (code, title, ov) => make("notfound", false, code, title, ov),
30
+ precondition: (code, title, ov) => make("precondition", false, code, title, ov),
31
+ conflict: (code, title, ov) => make("conflict", false, code, title, ov),
32
+ internal: (code, title, ov) => make("internal", true, code, title, ov),
33
+ unavailable: (code, title, ov) => make("unavailable", true, code, title, ov),
34
+ timeout: (code, title, ov) => make("timeout", true, code, title, ov),
35
+ network: (code, title, ov) => make("network", true, code, title, ov),
36
+ rateLimited: (code, title, ov) => make("rate_limited", true, code, title, ov),
37
+ mediaDevice: (code, title, ov) => make("media_device", false, code, title, ov),
38
+ mediaUnavailable: (code, title, ov) => make("media_unavailable", true, code, title, ov),
39
+ disposed: () => make("disposed", false, "callpad.disposed", "Client has been disposed"),
40
+ fromUnknown: (cause, context) => {
41
+ if (cause instanceof Error) {
42
+ return make(
43
+ "internal",
44
+ false,
45
+ "callpad.unknown",
46
+ context ?? "Unknown error",
47
+ {
48
+ detail: cause.message,
49
+ cause
50
+ }
51
+ );
52
+ }
53
+ return make(
54
+ "internal",
55
+ false,
56
+ "callpad.unknown",
57
+ context ?? "Unknown error",
58
+ {
59
+ detail: typeof cause === "string" ? cause : void 0
60
+ }
61
+ );
62
+ }
63
+ };
64
+
65
+ // src/shared/result.ts
66
+ function ok(value) {
67
+ return { ok: true, value };
68
+ }
69
+ function err(error) {
70
+ return { ok: false, error };
71
+ }
72
+ function isOk(r) {
73
+ return r.ok;
74
+ }
75
+ function isErr(r) {
76
+ return !r.ok;
77
+ }
78
+ function unwrap(r) {
79
+ if (r.ok) {
80
+ return r.value;
81
+ }
82
+ throw new Error(`unwrap on error: ${String(r.error)}`);
83
+ }
84
+
85
+ // src/core/logger.ts
86
+ var noopLogger = {
87
+ debug: () => void 0,
88
+ info: () => void 0,
89
+ warn: () => void 0,
90
+ error: () => void 0,
91
+ child: () => noopLogger
92
+ };
93
+
94
+ // src/api/generated/core/bodySerializer.ts
95
+ var jsonBodySerializer = {
96
+ bodySerializer: (body) => JSON.stringify(
97
+ body,
98
+ (key, value) => typeof value === "bigint" ? value.toString() : value
99
+ )
100
+ };
101
+
102
+ // src/api/generated/core/auth.ts
103
+ var getAuthToken = async (auth, callback) => {
104
+ const token = typeof callback === "function" ? await callback(auth) : callback;
105
+ if (!token) {
106
+ return;
107
+ }
108
+ if (auth.scheme === "bearer") {
109
+ return `Bearer ${token}`;
110
+ }
111
+ if (auth.scheme === "basic") {
112
+ return `Basic ${btoa(token)}`;
113
+ }
114
+ return token;
115
+ };
116
+
117
+ // src/api/generated/core/pathSerializer.ts
118
+ var separatorArrayExplode = (style) => {
119
+ switch (style) {
120
+ case "label":
121
+ return ".";
122
+ case "matrix":
123
+ return ";";
124
+ case "simple":
125
+ return ",";
126
+ default:
127
+ return "&";
128
+ }
129
+ };
130
+ var separatorArrayNoExplode = (style) => {
131
+ switch (style) {
132
+ case "form":
133
+ return ",";
134
+ case "pipeDelimited":
135
+ return "|";
136
+ case "spaceDelimited":
137
+ return "%20";
138
+ default:
139
+ return ",";
140
+ }
141
+ };
142
+ var separatorObjectExplode = (style) => {
143
+ switch (style) {
144
+ case "label":
145
+ return ".";
146
+ case "matrix":
147
+ return ";";
148
+ case "simple":
149
+ return ",";
150
+ default:
151
+ return "&";
152
+ }
153
+ };
154
+ var serializeArrayParam = ({
155
+ allowReserved,
156
+ explode,
157
+ name,
158
+ style,
159
+ value
160
+ }) => {
161
+ if (!explode) {
162
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
163
+ switch (style) {
164
+ case "label":
165
+ return `.${joinedValues2}`;
166
+ case "matrix":
167
+ return `;${name}=${joinedValues2}`;
168
+ case "simple":
169
+ return joinedValues2;
170
+ default:
171
+ return `${name}=${joinedValues2}`;
172
+ }
173
+ }
174
+ const separator = separatorArrayExplode(style);
175
+ const joinedValues = value.map((v) => {
176
+ if (style === "label" || style === "simple") {
177
+ return allowReserved ? v : encodeURIComponent(v);
178
+ }
179
+ return serializePrimitiveParam({
180
+ allowReserved,
181
+ name,
182
+ value: v
183
+ });
184
+ }).join(separator);
185
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
186
+ };
187
+ var serializePrimitiveParam = ({
188
+ allowReserved,
189
+ name,
190
+ value
191
+ }) => {
192
+ if (value === void 0 || value === null) {
193
+ return "";
194
+ }
195
+ if (typeof value === "object") {
196
+ throw new Error(
197
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
198
+ );
199
+ }
200
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
201
+ };
202
+ var serializeObjectParam = ({
203
+ allowReserved,
204
+ explode,
205
+ name,
206
+ style,
207
+ value,
208
+ valueOnly
209
+ }) => {
210
+ if (value instanceof Date) {
211
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
212
+ }
213
+ if (style !== "deepObject" && !explode) {
214
+ let values = [];
215
+ Object.entries(value).forEach(([key, v]) => {
216
+ values = [
217
+ ...values,
218
+ key,
219
+ allowReserved ? v : encodeURIComponent(v)
220
+ ];
221
+ });
222
+ const joinedValues2 = values.join(",");
223
+ switch (style) {
224
+ case "form":
225
+ return `${name}=${joinedValues2}`;
226
+ case "label":
227
+ return `.${joinedValues2}`;
228
+ case "matrix":
229
+ return `;${name}=${joinedValues2}`;
230
+ default:
231
+ return joinedValues2;
232
+ }
233
+ }
234
+ const separator = separatorObjectExplode(style);
235
+ const joinedValues = Object.entries(value).map(
236
+ ([key, v]) => serializePrimitiveParam({
237
+ allowReserved,
238
+ name: style === "deepObject" ? `${name}[${key}]` : key,
239
+ value: v
240
+ })
241
+ ).join(separator);
242
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
243
+ };
244
+
245
+ // src/api/generated/client/utils.ts
246
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
247
+ var defaultPathSerializer = ({ path, url: _url }) => {
248
+ let url = _url;
249
+ const matches = _url.match(PATH_PARAM_RE);
250
+ if (matches) {
251
+ for (const match of matches) {
252
+ let explode = false;
253
+ let name = match.substring(1, match.length - 1);
254
+ let style = "simple";
255
+ if (name.endsWith("*")) {
256
+ explode = true;
257
+ name = name.substring(0, name.length - 1);
258
+ }
259
+ if (name.startsWith(".")) {
260
+ name = name.substring(1);
261
+ style = "label";
262
+ } else if (name.startsWith(";")) {
263
+ name = name.substring(1);
264
+ style = "matrix";
265
+ }
266
+ const value = path[name];
267
+ if (value === void 0 || value === null) {
268
+ continue;
269
+ }
270
+ if (Array.isArray(value)) {
271
+ url = url.replace(
272
+ match,
273
+ serializeArrayParam({ explode, name, style, value })
274
+ );
275
+ continue;
276
+ }
277
+ if (typeof value === "object") {
278
+ url = url.replace(
279
+ match,
280
+ serializeObjectParam({
281
+ explode,
282
+ name,
283
+ style,
284
+ value,
285
+ valueOnly: true
286
+ })
287
+ );
288
+ continue;
289
+ }
290
+ if (style === "matrix") {
291
+ url = url.replace(
292
+ match,
293
+ `;${serializePrimitiveParam({
294
+ name,
295
+ value
296
+ })}`
297
+ );
298
+ continue;
299
+ }
300
+ const replaceValue = encodeURIComponent(
301
+ style === "label" ? `.${value}` : value
302
+ );
303
+ url = url.replace(match, replaceValue);
304
+ }
305
+ }
306
+ return url;
307
+ };
308
+ var createQuerySerializer = ({
309
+ allowReserved,
310
+ array,
311
+ object
312
+ } = {}) => {
313
+ const querySerializer = (queryParams) => {
314
+ const search = [];
315
+ if (queryParams && typeof queryParams === "object") {
316
+ for (const name in queryParams) {
317
+ const value = queryParams[name];
318
+ if (value === void 0 || value === null) {
319
+ continue;
320
+ }
321
+ if (Array.isArray(value)) {
322
+ const serializedArray = serializeArrayParam({
323
+ allowReserved,
324
+ explode: true,
325
+ name,
326
+ style: "form",
327
+ value,
328
+ ...array
329
+ });
330
+ if (serializedArray) search.push(serializedArray);
331
+ } else if (typeof value === "object") {
332
+ const serializedObject = serializeObjectParam({
333
+ allowReserved,
334
+ explode: true,
335
+ name,
336
+ style: "deepObject",
337
+ value,
338
+ ...object
339
+ });
340
+ if (serializedObject) search.push(serializedObject);
341
+ } else {
342
+ const serializedPrimitive = serializePrimitiveParam({
343
+ allowReserved,
344
+ name,
345
+ value
346
+ });
347
+ if (serializedPrimitive) search.push(serializedPrimitive);
348
+ }
349
+ }
350
+ }
351
+ return search.join("&");
352
+ };
353
+ return querySerializer;
354
+ };
355
+ var getParseAs = (contentType) => {
356
+ if (!contentType) {
357
+ return "stream";
358
+ }
359
+ const cleanContent = contentType.split(";")[0]?.trim();
360
+ if (!cleanContent) {
361
+ return;
362
+ }
363
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
364
+ return "json";
365
+ }
366
+ if (cleanContent === "multipart/form-data") {
367
+ return "formData";
368
+ }
369
+ if (["application/", "audio/", "image/", "video/"].some(
370
+ (type) => cleanContent.startsWith(type)
371
+ )) {
372
+ return "blob";
373
+ }
374
+ if (cleanContent.startsWith("text/")) {
375
+ return "text";
376
+ }
377
+ };
378
+ var setAuthParams = async ({
379
+ security,
380
+ ...options
381
+ }) => {
382
+ for (const auth of security) {
383
+ const token = await getAuthToken(auth, options.auth);
384
+ if (!token) {
385
+ continue;
386
+ }
387
+ const name = auth.name ?? "Authorization";
388
+ switch (auth.in) {
389
+ case "query":
390
+ if (!options.query) {
391
+ options.query = {};
392
+ }
393
+ options.query[name] = token;
394
+ break;
395
+ case "cookie":
396
+ options.headers.append("Cookie", `${name}=${token}`);
397
+ break;
398
+ case "header":
399
+ default:
400
+ options.headers.set(name, token);
401
+ break;
402
+ }
403
+ return;
404
+ }
405
+ };
406
+ var buildUrl = (options) => {
407
+ const url = getUrl({
408
+ baseUrl: options.baseUrl,
409
+ path: options.path,
410
+ query: options.query,
411
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
412
+ url: options.url
413
+ });
414
+ return url;
415
+ };
416
+ var getUrl = ({
417
+ baseUrl,
418
+ path,
419
+ query,
420
+ querySerializer,
421
+ url: _url
422
+ }) => {
423
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
424
+ let url = (baseUrl ?? "") + pathUrl;
425
+ if (path) {
426
+ url = defaultPathSerializer({ path, url });
427
+ }
428
+ let search = query ? querySerializer(query) : "";
429
+ if (search.startsWith("?")) {
430
+ search = search.substring(1);
431
+ }
432
+ if (search) {
433
+ url += `?${search}`;
434
+ }
435
+ return url;
436
+ };
437
+ var mergeConfigs = (a, b) => {
438
+ const config = { ...a, ...b };
439
+ if (config.baseUrl?.endsWith("/")) {
440
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
441
+ }
442
+ config.headers = mergeHeaders(a.headers, b.headers);
443
+ return config;
444
+ };
445
+ var mergeHeaders = (...headers) => {
446
+ const mergedHeaders = new Headers();
447
+ for (const header of headers) {
448
+ if (!header || typeof header !== "object") {
449
+ continue;
450
+ }
451
+ const iterator = header instanceof Headers ? header.entries() : Object.entries(header);
452
+ for (const [key, value] of iterator) {
453
+ if (value === null) {
454
+ mergedHeaders.delete(key);
455
+ } else if (Array.isArray(value)) {
456
+ for (const v of value) {
457
+ mergedHeaders.append(key, v);
458
+ }
459
+ } else if (value !== void 0) {
460
+ mergedHeaders.set(
461
+ key,
462
+ typeof value === "object" ? JSON.stringify(value) : value
463
+ );
464
+ }
465
+ }
466
+ }
467
+ return mergedHeaders;
468
+ };
469
+ var Interceptors = class {
470
+ _fns;
471
+ constructor() {
472
+ this._fns = [];
473
+ }
474
+ clear() {
475
+ this._fns = [];
476
+ }
477
+ getInterceptorIndex(id) {
478
+ if (typeof id === "number") {
479
+ return this._fns[id] ? id : -1;
480
+ } else {
481
+ return this._fns.indexOf(id);
482
+ }
483
+ }
484
+ exists(id) {
485
+ const index = this.getInterceptorIndex(id);
486
+ return !!this._fns[index];
487
+ }
488
+ eject(id) {
489
+ const index = this.getInterceptorIndex(id);
490
+ if (this._fns[index]) {
491
+ this._fns[index] = null;
492
+ }
493
+ }
494
+ update(id, fn) {
495
+ const index = this.getInterceptorIndex(id);
496
+ if (this._fns[index]) {
497
+ this._fns[index] = fn;
498
+ return id;
499
+ } else {
500
+ return false;
501
+ }
502
+ }
503
+ use(fn) {
504
+ this._fns = [...this._fns, fn];
505
+ return this._fns.length - 1;
506
+ }
507
+ };
508
+ var createInterceptors = () => ({
509
+ error: new Interceptors(),
510
+ request: new Interceptors(),
511
+ response: new Interceptors()
512
+ });
513
+ var defaultQuerySerializer = createQuerySerializer({
514
+ allowReserved: false,
515
+ array: {
516
+ explode: true,
517
+ style: "form"
518
+ },
519
+ object: {
520
+ explode: true,
521
+ style: "deepObject"
522
+ }
523
+ });
524
+ var defaultHeaders = {
525
+ "Content-Type": "application/json"
526
+ };
527
+ var createConfig = (override = {}) => ({
528
+ ...jsonBodySerializer,
529
+ headers: defaultHeaders,
530
+ parseAs: "auto",
531
+ querySerializer: defaultQuerySerializer,
532
+ ...override
533
+ });
534
+
535
+ // src/api/generated/client/client.ts
536
+ var createClient = (config = {}) => {
537
+ let _config = mergeConfigs(createConfig(), config);
538
+ const getConfig = () => ({ ..._config });
539
+ const setConfig = (config2) => {
540
+ _config = mergeConfigs(_config, config2);
541
+ return getConfig();
542
+ };
543
+ const interceptors = createInterceptors();
544
+ const request = async (options) => {
545
+ const opts = {
546
+ ..._config,
547
+ ...options,
548
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
549
+ headers: mergeHeaders(_config.headers, options.headers)
550
+ };
551
+ if (opts.security) {
552
+ await setAuthParams({
553
+ ...opts,
554
+ security: opts.security
555
+ });
556
+ }
557
+ if (opts.body && opts.bodySerializer) {
558
+ opts.body = opts.bodySerializer(opts.body);
559
+ }
560
+ if (opts.body === void 0 || opts.body === "") {
561
+ opts.headers.delete("Content-Type");
562
+ }
563
+ const url = buildUrl(opts);
564
+ const requestInit = {
565
+ redirect: "follow",
566
+ ...opts
567
+ };
568
+ let request2 = new Request(url, requestInit);
569
+ for (const fn of interceptors.request._fns) {
570
+ if (fn) {
571
+ request2 = await fn(request2, opts);
572
+ }
573
+ }
574
+ const _fetch = opts.fetch;
575
+ let response = await _fetch(request2);
576
+ for (const fn of interceptors.response._fns) {
577
+ if (fn) {
578
+ response = await fn(response, request2, opts);
579
+ }
580
+ }
581
+ const result = {
582
+ request: request2,
583
+ response
584
+ };
585
+ if (response.ok) {
586
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
587
+ return opts.responseStyle === "data" ? {} : {
588
+ data: {},
589
+ ...result
590
+ };
591
+ }
592
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
593
+ if (parseAs === "stream") {
594
+ return opts.responseStyle === "data" ? response.body : {
595
+ data: response.body,
596
+ ...result
597
+ };
598
+ }
599
+ let data = await response[parseAs]();
600
+ if (parseAs === "json") {
601
+ if (opts.responseValidator) {
602
+ await opts.responseValidator(data);
603
+ }
604
+ if (opts.responseTransformer) {
605
+ data = await opts.responseTransformer(data);
606
+ }
607
+ }
608
+ return opts.responseStyle === "data" ? data : {
609
+ data,
610
+ ...result
611
+ };
612
+ }
613
+ let error = await response.text();
614
+ try {
615
+ error = JSON.parse(error);
616
+ } catch {
617
+ }
618
+ let finalError = error;
619
+ for (const fn of interceptors.error._fns) {
620
+ if (fn) {
621
+ finalError = await fn(error, response, request2, opts);
622
+ }
623
+ }
624
+ finalError = finalError || {};
625
+ if (opts.throwOnError) {
626
+ throw finalError;
627
+ }
628
+ return opts.responseStyle === "data" ? void 0 : {
629
+ error: finalError,
630
+ ...result
631
+ };
632
+ };
633
+ return {
634
+ buildUrl,
635
+ connect: (options) => request({ ...options, method: "CONNECT" }),
636
+ delete: (options) => request({ ...options, method: "DELETE" }),
637
+ get: (options) => request({ ...options, method: "GET" }),
638
+ getConfig,
639
+ head: (options) => request({ ...options, method: "HEAD" }),
640
+ interceptors,
641
+ options: (options) => request({ ...options, method: "OPTIONS" }),
642
+ patch: (options) => request({ ...options, method: "PATCH" }),
643
+ post: (options) => request({ ...options, method: "POST" }),
644
+ put: (options) => request({ ...options, method: "PUT" }),
645
+ request,
646
+ setConfig,
647
+ trace: (options) => request({ ...options, method: "TRACE" })
648
+ };
649
+ };
650
+
651
+ // src/api/client-config.ts
652
+ var createClientConfig = (base) => ({
653
+ ...base,
654
+ throwOnError: false
655
+ });
656
+
657
+ // src/api/generated/client.gen.ts
658
+ var client = createClient(createClientConfig(createConfig({
659
+ baseUrl: "http://localhost:3002"
660
+ })));
661
+
662
+ // src/api/map-error.ts
663
+ function isBackendErrorBody(body) {
664
+ if (body === null || typeof body !== "object") {
665
+ return false;
666
+ }
667
+ const maybe = body;
668
+ if (maybe.error === null || typeof maybe.error !== "object") {
669
+ return false;
670
+ }
671
+ const e = maybe.error;
672
+ return typeof e.code === "string" && typeof e.title === "string" && typeof e.kind === "string";
673
+ }
674
+ var kindMap = {
675
+ validation: "validation",
676
+ unauth: "unauth",
677
+ forbidden: "forbidden",
678
+ notfound: "notfound",
679
+ precondition: "precondition",
680
+ conflict: "conflict",
681
+ internal: "internal",
682
+ unavailable: "unavailable",
683
+ timeout: "timeout"
684
+ };
685
+ function mapError(body, status) {
686
+ if (status === 0 || status === void 0 || status === null) {
687
+ return callpadError.network("callpad.network", "Network error", {
688
+ status: status ?? void 0
689
+ });
690
+ }
691
+ if (!isBackendErrorBody(body)) {
692
+ if (status === 401) {
693
+ return callpadError.unauth("callpad.unauth", "Unauthorized", { status });
694
+ }
695
+ if (status === 403) {
696
+ return callpadError.forbidden("callpad.forbidden", "Forbidden", {
697
+ status
698
+ });
699
+ }
700
+ if (status === 404) {
701
+ return callpadError.notfound("callpad.not_found", "Not found", {
702
+ status
703
+ });
704
+ }
705
+ if (status >= 500) {
706
+ return callpadError.internal(
707
+ "callpad.internal",
708
+ "Internal server error",
709
+ { status }
710
+ );
711
+ }
712
+ return callpadError.internal(
713
+ "callpad.unknown_response",
714
+ "Unexpected response shape",
715
+ {
716
+ status
717
+ }
718
+ );
719
+ }
720
+ const e = body.error;
721
+ const kind = kindMap[e.kind] ?? "internal";
722
+ return {
723
+ kind,
724
+ code: e.code,
725
+ title: e.title,
726
+ detail: e.detail,
727
+ retryable: e.retryable,
728
+ issues: e.issues,
729
+ status
730
+ };
731
+ }
732
+
733
+ // src/api/call.ts
734
+ async function apiCall(call) {
735
+ try {
736
+ const res = await call();
737
+ if (res.error !== void 0 || !res.response.ok) {
738
+ return err(
739
+ mapError(
740
+ res.error !== void 0 ? { error: res.error } : void 0,
741
+ res.response.status
742
+ )
743
+ );
744
+ }
745
+ if (res.data === void 0) {
746
+ return err(
747
+ callpadError.internal(
748
+ "callpad.empty_response",
749
+ "Expected response body, got empty"
750
+ )
751
+ );
752
+ }
753
+ return ok(res.data);
754
+ } catch (cause) {
755
+ return err(callpadError.fromUnknown(cause, "HTTP request failed"));
756
+ }
757
+ }
758
+
759
+ // src/api/generated/sdk.gen.ts
760
+ var getApiV1PulseGrants = (options) => {
761
+ return (options?.client ?? client).get({
762
+ security: [
763
+ {
764
+ scheme: "bearer",
765
+ type: "http"
766
+ }
767
+ ],
768
+ url: "/api/v1/pulse/grants",
769
+ ...options
770
+ });
771
+ };
772
+ var getApiV1VendorsBySlugPresence = (options) => {
773
+ return (options.client ?? client).get({
774
+ security: [
775
+ {
776
+ scheme: "bearer",
777
+ type: "http"
778
+ }
779
+ ],
780
+ url: "/api/v1/vendors/{slug}/presence",
781
+ ...options
782
+ });
783
+ };
784
+ var deleteApiV1VendorsBySlugPresenceStatus = (options) => {
785
+ return (options.client ?? client).delete({
786
+ security: [
787
+ {
788
+ scheme: "bearer",
789
+ type: "http"
790
+ }
791
+ ],
792
+ url: "/api/v1/vendors/{slug}/presence/status",
793
+ ...options
794
+ });
795
+ };
796
+ var putApiV1VendorsBySlugPresenceStatus = (options) => {
797
+ return (options.client ?? client).put({
798
+ security: [
799
+ {
800
+ scheme: "bearer",
801
+ type: "http"
802
+ }
803
+ ],
804
+ url: "/api/v1/vendors/{slug}/presence/status",
805
+ ...options,
806
+ headers: {
807
+ "Content-Type": "application/json",
808
+ ...options.headers
809
+ }
810
+ });
811
+ };
812
+ var getApiV1Sessions = (options) => {
813
+ return (options?.client ?? client).get({
814
+ security: [
815
+ {
816
+ scheme: "bearer",
817
+ type: "http"
818
+ }
819
+ ],
820
+ url: "/api/v1/sessions",
821
+ ...options
822
+ });
823
+ };
824
+ var postApiV1Sessions = (options) => {
825
+ return (options.client ?? client).post({
826
+ security: [
827
+ {
828
+ scheme: "bearer",
829
+ type: "http"
830
+ }
831
+ ],
832
+ url: "/api/v1/sessions",
833
+ ...options,
834
+ headers: {
835
+ "Content-Type": "application/json",
836
+ ...options.headers
837
+ }
838
+ });
839
+ };
840
+ var getApiV1SessionsInvites = (options) => {
841
+ return (options?.client ?? client).get({
842
+ security: [
843
+ {
844
+ scheme: "bearer",
845
+ type: "http"
846
+ }
847
+ ],
848
+ url: "/api/v1/sessions/invites",
849
+ ...options
850
+ });
851
+ };
852
+ var postApiV1SessionsBySessionIdInvitesByInviteIdAccept = (options) => {
853
+ return (options.client ?? client).post({
854
+ security: [
855
+ {
856
+ scheme: "bearer",
857
+ type: "http"
858
+ }
859
+ ],
860
+ url: "/api/v1/sessions/{sessionId}/invites/{inviteId}/accept",
861
+ ...options
862
+ });
863
+ };
864
+ var postApiV1SessionsBySessionIdInvitesByInviteIdReject = (options) => {
865
+ return (options.client ?? client).post({
866
+ security: [
867
+ {
868
+ scheme: "bearer",
869
+ type: "http"
870
+ }
871
+ ],
872
+ url: "/api/v1/sessions/{sessionId}/invites/{inviteId}/reject",
873
+ ...options
874
+ });
875
+ };
876
+ var getApiV1SessionsBySessionId = (options) => {
877
+ return (options.client ?? client).get({
878
+ security: [
879
+ {
880
+ scheme: "bearer",
881
+ type: "http"
882
+ }
883
+ ],
884
+ url: "/api/v1/sessions/{sessionId}",
885
+ ...options
886
+ });
887
+ };
888
+ var patchApiV1SessionsBySessionId = (options) => {
889
+ return (options.client ?? client).patch({
890
+ security: [
891
+ {
892
+ scheme: "bearer",
893
+ type: "http"
894
+ }
895
+ ],
896
+ url: "/api/v1/sessions/{sessionId}",
897
+ ...options,
898
+ headers: {
899
+ "Content-Type": "application/json",
900
+ ...options.headers
901
+ }
902
+ });
903
+ };
904
+ var postApiV1SessionsBySessionIdJoin = (options) => {
905
+ return (options.client ?? client).post({
906
+ security: [
907
+ {
908
+ scheme: "bearer",
909
+ type: "http"
910
+ }
911
+ ],
912
+ url: "/api/v1/sessions/{sessionId}/join",
913
+ ...options
914
+ });
915
+ };
916
+ var postApiV1SessionsBySessionIdCancel = (options) => {
917
+ return (options.client ?? client).post({
918
+ security: [
919
+ {
920
+ scheme: "bearer",
921
+ type: "http"
922
+ }
923
+ ],
924
+ url: "/api/v1/sessions/{sessionId}/cancel",
925
+ ...options
926
+ });
927
+ };
928
+ var postApiV1SessionsBySessionIdLeave = (options) => {
929
+ return (options.client ?? client).post({
930
+ security: [
931
+ {
932
+ scheme: "bearer",
933
+ type: "http"
934
+ }
935
+ ],
936
+ url: "/api/v1/sessions/{sessionId}/leave",
937
+ ...options
938
+ });
939
+ };
940
+ var postApiV1SessionsBySessionIdHold = (options) => {
941
+ return (options.client ?? client).post({
942
+ security: [
943
+ {
944
+ scheme: "bearer",
945
+ type: "http"
946
+ }
947
+ ],
948
+ url: "/api/v1/sessions/{sessionId}/hold",
949
+ ...options
950
+ });
951
+ };
952
+ var postApiV1SessionsBySessionIdUnhold = (options) => {
953
+ return (options.client ?? client).post({
954
+ security: [
955
+ {
956
+ scheme: "bearer",
957
+ type: "http"
958
+ }
959
+ ],
960
+ url: "/api/v1/sessions/{sessionId}/unhold",
961
+ ...options
962
+ });
963
+ };
964
+ var postApiV1SessionsBySessionIdEnd = (options) => {
965
+ return (options.client ?? client).post({
966
+ security: [
967
+ {
968
+ scheme: "bearer",
969
+ type: "http"
970
+ }
971
+ ],
972
+ url: "/api/v1/sessions/{sessionId}/end",
973
+ ...options
974
+ });
975
+ };
976
+ var postApiV1SessionsBySessionIdParticipants = (options) => {
977
+ return (options.client ?? client).post({
978
+ security: [
979
+ {
980
+ scheme: "bearer",
981
+ type: "http"
982
+ }
983
+ ],
984
+ url: "/api/v1/sessions/{sessionId}/participants",
985
+ ...options,
986
+ headers: {
987
+ "Content-Type": "application/json",
988
+ ...options.headers
989
+ }
990
+ });
991
+ };
992
+ var deleteApiV1SessionsBySessionIdParticipantsByParticipantId = (options) => {
993
+ return (options.client ?? client).delete({
994
+ security: [
995
+ {
996
+ scheme: "bearer",
997
+ type: "http"
998
+ }
999
+ ],
1000
+ url: "/api/v1/sessions/{sessionId}/participants/{participantId}",
1001
+ ...options
1002
+ });
1003
+ };
1004
+ var postApiV1SessionsBySessionIdRecordings = (options) => {
1005
+ return (options.client ?? client).post({
1006
+ security: [
1007
+ {
1008
+ scheme: "bearer",
1009
+ type: "http"
1010
+ }
1011
+ ],
1012
+ url: "/api/v1/sessions/{sessionId}/recordings",
1013
+ ...options
1014
+ });
1015
+ };
1016
+ var postApiV1SessionsBySessionIdRecordingsByRecordingIdStop = (options) => {
1017
+ return (options.client ?? client).post({
1018
+ security: [
1019
+ {
1020
+ scheme: "bearer",
1021
+ type: "http"
1022
+ }
1023
+ ],
1024
+ url: "/api/v1/sessions/{sessionId}/recordings/{recordingId}/stop",
1025
+ ...options
1026
+ });
1027
+ };
1028
+
1029
+ // src/api/retry.ts
1030
+ var RETRY_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
1031
+ var DEFAULT_MAX_ATTEMPTS = 3;
1032
+ var DEFAULT_INITIAL_DELAY_MS = 300;
1033
+ function sleep(ms) {
1034
+ return new Promise((resolve) => {
1035
+ setTimeout(resolve, ms);
1036
+ });
1037
+ }
1038
+ function nextDelay(attempt, initial) {
1039
+ return initial * 2 ** (attempt - 1);
1040
+ }
1041
+ function makeRetryingFetch(base, opts = {}) {
1042
+ const maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
1043
+ const initialDelay = opts.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
1044
+ return async (request) => {
1045
+ let attempt = 0;
1046
+ while (true) {
1047
+ attempt += 1;
1048
+ const res = await base(request.clone());
1049
+ if (!RETRY_STATUSES.has(res.status) || attempt >= maxAttempts) {
1050
+ return res;
1051
+ }
1052
+ await sleep(nextDelay(attempt, initialDelay));
1053
+ }
1054
+ };
1055
+ }
1056
+
1057
+ // src/core/dispatch.ts
1058
+ function dispatchFromView(view) {
1059
+ return {
1060
+ id: view.id,
1061
+ source: view.source,
1062
+ strategy: view.strategy,
1063
+ state: view.state,
1064
+ candidateParticipantIds: view.candidateParticipantIds,
1065
+ winnerParticipantId: nullify(view.winnerParticipantId),
1066
+ startedAt: view.startedAt,
1067
+ resolvedAt: nullify(view.resolvedAt),
1068
+ timeoutAt: nullify(view.timeoutAt)
1069
+ };
1070
+ }
1071
+
1072
+ // src/core/participant.ts
1073
+ var DEFAULT_MEDIA = {
1074
+ micPublished: false,
1075
+ micMuted: true,
1076
+ cameraPublished: false,
1077
+ cameraMuted: true,
1078
+ screenShareActive: false
1079
+ };
1080
+ function participantFromView(view, selfParticipantId, mediaLookup) {
1081
+ const media = mediaLookup.get(view.participantIdentity);
1082
+ return {
1083
+ id: view.id,
1084
+ ref: view.ref,
1085
+ info: view.info,
1086
+ role: view.role,
1087
+ capabilities: view.capabilities,
1088
+ transport: view.transport,
1089
+ state: view.state,
1090
+ participantIdentity: view.participantIdentity,
1091
+ participantSid: nullify(view.participantSid),
1092
+ invitedAt: view.invitedAt,
1093
+ acceptedAt: nullify(view.acceptedAt),
1094
+ joinedAt: nullify(view.joinedAt),
1095
+ endedAt: nullify(view.endedAt),
1096
+ leftReason: nullify(view.leftReason),
1097
+ failureReason: nullify(view.failureReason),
1098
+ isSelf: selfParticipantId !== null && view.id === selfParticipantId,
1099
+ isSpeaking: media?.isSpeaking ?? false,
1100
+ audioLevel: media?.audioLevel ?? 0,
1101
+ connectionQuality: media?.connectionQuality ?? "unknown",
1102
+ media: media ? {
1103
+ micPublished: media.micPublished,
1104
+ micMuted: media.micMuted,
1105
+ cameraPublished: media.cameraPublished,
1106
+ cameraMuted: media.cameraMuted,
1107
+ screenShareActive: media.screenShareActive
1108
+ } : DEFAULT_MEDIA
1109
+ };
1110
+ }
1111
+
1112
+ // src/core/recording.ts
1113
+ function recordingFromView(view) {
1114
+ return {
1115
+ id: view.id,
1116
+ target: view.target,
1117
+ policy: view.policy,
1118
+ state: view.state,
1119
+ livekitEgressId: nullify(view.livekitEgressId),
1120
+ requestedAt: view.requestedAt,
1121
+ startedAt: nullify(view.startedAt),
1122
+ stoppedAt: nullify(view.stoppedAt),
1123
+ failureReason: nullify(view.failureReason)
1124
+ };
1125
+ }
1126
+
1127
+ // src/core/state/event-bus.ts
1128
+ var EventBus = class {
1129
+ handlers = /* @__PURE__ */ new Map();
1130
+ on(type, handler) {
1131
+ let set = this.handlers.get(type);
1132
+ if (!set) {
1133
+ set = /* @__PURE__ */ new Set();
1134
+ this.handlers.set(type, set);
1135
+ }
1136
+ set.add(handler);
1137
+ return () => {
1138
+ set?.delete(handler);
1139
+ };
1140
+ }
1141
+ emit(type, payload) {
1142
+ const set = this.handlers.get(type);
1143
+ if (!set) {
1144
+ return;
1145
+ }
1146
+ for (const handler of set) {
1147
+ try {
1148
+ handler(payload);
1149
+ } catch {
1150
+ }
1151
+ }
1152
+ }
1153
+ clear() {
1154
+ this.handlers.clear();
1155
+ }
1156
+ hasHandlers(type) {
1157
+ const set = this.handlers.get(type);
1158
+ return set !== void 0 && set.size > 0;
1159
+ }
1160
+ };
1161
+
1162
+ // src/core/state/reconciler.ts
1163
+ function shouldApplyUpsert(prev, incoming) {
1164
+ if (prev === void 0) {
1165
+ return true;
1166
+ }
1167
+ return incoming.version > prev.version;
1168
+ }
1169
+
1170
+ // src/core/telephony-leg.ts
1171
+ function telephonyLegFromOperation(participant, op) {
1172
+ return {
1173
+ id: op.id,
1174
+ participantId: participant.id,
1175
+ participantIdentity: participant.participantIdentity,
1176
+ direction: op.direction,
1177
+ state: op.state,
1178
+ remotePhoneNumber: op.remotePhoneNumber,
1179
+ localPhoneNumber: nullify(op.localPhoneNumber),
1180
+ livekitSipCallId: nullify(op.provider.livekitSipCallId),
1181
+ providerSipCallId: nullify(op.provider.providerSipCallId),
1182
+ livekitSipTrunkId: nullify(op.provider.livekitSipTrunkId),
1183
+ vendorPhoneNumberId: nullify(op.provider.vendorPhoneNumberId),
1184
+ sipExtension: nullify(op.provider.sipExtension),
1185
+ createdAt: op.createdAt,
1186
+ ringingAt: nullify(op.ringingAt),
1187
+ activeAt: nullify(op.activeAt),
1188
+ endedAt: nullify(op.endedAt),
1189
+ failureReason: nullify(op.failureReason),
1190
+ sipStatusCode: nullify(op.sipStatusCode),
1191
+ providerError: nullify(op.providerError)
1192
+ };
1193
+ }
1194
+ function collectSipLegs(participants) {
1195
+ const legs = [];
1196
+ for (const participant of participants) {
1197
+ for (const op of participant.operations) {
1198
+ if (op.kind === "sip_leg") {
1199
+ legs.push(telephonyLegFromOperation(participant, op));
1200
+ }
1201
+ }
1202
+ }
1203
+ return legs;
1204
+ }
1205
+ var DEFAULT_ROTATE_LEAD_MS = 10 * 60 * 1e3;
1206
+ var FORWARDED_EVENTS = [
1207
+ "session.upsert",
1208
+ "session.remove",
1209
+ "session.invite.upsert",
1210
+ "session.invite.remove"
1211
+ ];
1212
+ var PulseTransport = class {
1213
+ socket = null;
1214
+ grant = null;
1215
+ rotateTimer = null;
1216
+ status = "idle";
1217
+ disposed = false;
1218
+ bus = new EventBus();
1219
+ rotateLeadMs;
1220
+ logger;
1221
+ grantFetcher;
1222
+ constructor(opts) {
1223
+ this.rotateLeadMs = opts.rotateLeadMs ?? DEFAULT_ROTATE_LEAD_MS;
1224
+ this.logger = opts.logger.child({ component: "pulse" });
1225
+ this.grantFetcher = opts.grantFetcher;
1226
+ }
1227
+ getStatus() {
1228
+ return this.status;
1229
+ }
1230
+ on(type, handler) {
1231
+ return this.bus.on(type, handler);
1232
+ }
1233
+ async connect() {
1234
+ if (this.disposed) {
1235
+ return err(callpadError.disposed());
1236
+ }
1237
+ if (this.status === "connected" || this.status === "connecting") {
1238
+ return ok(void 0);
1239
+ }
1240
+ this.setStatus("connecting");
1241
+ const grant = await this.grantFetcher();
1242
+ if (!grant.ok) {
1243
+ this.setStatus("disconnected");
1244
+ return err(grant.error);
1245
+ }
1246
+ this.grant = grant.value;
1247
+ try {
1248
+ await this.openSocket(grant.value);
1249
+ } catch (cause) {
1250
+ this.setStatus("disconnected");
1251
+ return err(
1252
+ callpadError.unavailable(
1253
+ "pulse.connect_failed",
1254
+ "Pulse connect failed",
1255
+ {
1256
+ cause: cause instanceof Error ? cause : void 0
1257
+ }
1258
+ )
1259
+ );
1260
+ }
1261
+ this.scheduleRotate(grant.value);
1262
+ return ok(void 0);
1263
+ }
1264
+ async disconnect() {
1265
+ this.clearRotate();
1266
+ this.closeSocket();
1267
+ this.setStatus("disconnected");
1268
+ }
1269
+ async dispose() {
1270
+ if (this.disposed) {
1271
+ return;
1272
+ }
1273
+ this.disposed = true;
1274
+ this.clearRotate();
1275
+ this.closeSocket();
1276
+ this.bus.clear();
1277
+ this.status = "disconnected";
1278
+ }
1279
+ setStatus(next) {
1280
+ if (next === this.status) {
1281
+ return;
1282
+ }
1283
+ const previous = this.status;
1284
+ this.status = next;
1285
+ this.bus.emit("status.changed", { status: next, previous });
1286
+ }
1287
+ openSocket(grant) {
1288
+ return new Promise((resolve, reject) => {
1289
+ const socket = io(grant.url, {
1290
+ path: grant.path,
1291
+ transports: ["websocket"],
1292
+ auth: { token: grant.token },
1293
+ reconnection: true,
1294
+ reconnectionAttempts: Infinity
1295
+ });
1296
+ socket.on("connect", () => {
1297
+ this.setStatus("connected");
1298
+ });
1299
+ socket.on("reconnect_attempt", () => {
1300
+ this.setStatus("recovering");
1301
+ });
1302
+ socket.on("disconnect", () => {
1303
+ if (!this.disposed) {
1304
+ this.setStatus("recovering");
1305
+ }
1306
+ });
1307
+ socket.on("connect_error", (cause) => {
1308
+ const error = callpadError.unavailable(
1309
+ "pulse.connect_error",
1310
+ "Pulse socket error",
1311
+ { cause: cause instanceof Error ? cause : void 0 }
1312
+ );
1313
+ this.bus.emit("error", { error });
1314
+ });
1315
+ for (const event of FORWARDED_EVENTS) {
1316
+ socket.on(event, (payload) => {
1317
+ this.bus.emit(event, payload);
1318
+ });
1319
+ }
1320
+ socket.once("connect", () => resolve());
1321
+ socket.once("connect_error", (cause) => {
1322
+ if (this.status !== "connected") {
1323
+ reject(cause);
1324
+ }
1325
+ });
1326
+ this.socket = socket;
1327
+ });
1328
+ }
1329
+ closeSocket() {
1330
+ if (!this.socket) {
1331
+ return;
1332
+ }
1333
+ this.socket.removeAllListeners();
1334
+ this.socket.disconnect();
1335
+ this.socket = null;
1336
+ }
1337
+ scheduleRotate(grant) {
1338
+ this.clearRotate();
1339
+ const expiresAt = Date.parse(grant.expiresAt);
1340
+ if (Number.isNaN(expiresAt)) {
1341
+ return;
1342
+ }
1343
+ const refreshAt = Math.max(0, expiresAt - Date.now() - this.rotateLeadMs);
1344
+ this.rotateTimer = setTimeout(() => {
1345
+ void this.rotateGrant();
1346
+ }, refreshAt);
1347
+ this.rotateTimer.unref?.();
1348
+ }
1349
+ scheduleRotateRetry() {
1350
+ this.clearRotate();
1351
+ this.rotateTimer = setTimeout(() => {
1352
+ void this.rotateGrant();
1353
+ }, this.rotateLeadMs);
1354
+ this.rotateTimer.unref?.();
1355
+ }
1356
+ clearRotate() {
1357
+ if (this.rotateTimer) {
1358
+ clearTimeout(this.rotateTimer);
1359
+ this.rotateTimer = null;
1360
+ }
1361
+ }
1362
+ async rotateGrant() {
1363
+ if (this.disposed) {
1364
+ return;
1365
+ }
1366
+ const grant = await this.grantFetcher();
1367
+ if (!grant.ok) {
1368
+ this.logger.warn(
1369
+ { code: grant.error.code },
1370
+ "pulse grant refresh failed"
1371
+ );
1372
+ this.scheduleRotateRetry();
1373
+ return;
1374
+ }
1375
+ this.grant = grant.value;
1376
+ this.closeSocket();
1377
+ try {
1378
+ await this.openSocket(grant.value);
1379
+ } catch (cause) {
1380
+ this.logger.warn(
1381
+ { err: cause instanceof Error ? cause : void 0 },
1382
+ "pulse reopen failed"
1383
+ );
1384
+ }
1385
+ this.scheduleRotate(grant.value);
1386
+ }
1387
+ };
1388
+ function qualityOf(q) {
1389
+ switch (q) {
1390
+ case ConnectionQuality.Excellent:
1391
+ return "excellent";
1392
+ case ConnectionQuality.Good:
1393
+ return "good";
1394
+ case ConnectionQuality.Poor:
1395
+ return "poor";
1396
+ case ConnectionQuality.Lost:
1397
+ return "lost";
1398
+ default:
1399
+ return "unknown";
1400
+ }
1401
+ }
1402
+ function snapshotOf(p) {
1403
+ const micPub = p.getTrackPublication(Track.Source.Microphone);
1404
+ const camPub = p.getTrackPublication(Track.Source.Camera);
1405
+ const screenPub = p.getTrackPublication(Track.Source.ScreenShare);
1406
+ return {
1407
+ identity: p.identity,
1408
+ isSpeaking: p.isSpeaking,
1409
+ audioLevel: p.audioLevel,
1410
+ micPublished: micPub !== void 0,
1411
+ micMuted: micPub?.isMuted ?? true,
1412
+ cameraPublished: camPub !== void 0,
1413
+ cameraMuted: camPub?.isMuted ?? true,
1414
+ screenShareActive: screenPub !== void 0 && !screenPub.isMuted,
1415
+ connectionQuality: qualityOf(p.connectionQuality)
1416
+ };
1417
+ }
1418
+ function snapshotEquals(a, b) {
1419
+ return a.isSpeaking === b.isSpeaking && a.audioLevel === b.audioLevel && a.micPublished === b.micPublished && a.micMuted === b.micMuted && a.cameraPublished === b.cameraPublished && a.cameraMuted === b.cameraMuted && a.screenShareActive === b.screenShareActive && a.connectionQuality === b.connectionQuality;
1420
+ }
1421
+ var MediaRoomAdapter = class {
1422
+ room;
1423
+ bus = new EventBus();
1424
+ logger;
1425
+ snapshots = /* @__PURE__ */ new Map();
1426
+ state = "unconnected";
1427
+ disposed = false;
1428
+ constructor(logger) {
1429
+ this.logger = logger.child({ component: "media" });
1430
+ this.room = new Room({
1431
+ adaptiveStream: true,
1432
+ dynacast: true,
1433
+ disconnectOnPageLeave: false,
1434
+ singlePeerConnection: false
1435
+ });
1436
+ this.wireRoomEvents();
1437
+ }
1438
+ getRoom() {
1439
+ return this.room;
1440
+ }
1441
+ getState() {
1442
+ return this.state;
1443
+ }
1444
+ getSnapshot(identity) {
1445
+ return this.snapshots.get(identity);
1446
+ }
1447
+ listSnapshots() {
1448
+ return this.snapshots;
1449
+ }
1450
+ on(type, handler) {
1451
+ return this.bus.on(type, handler);
1452
+ }
1453
+ async connect(opts) {
1454
+ if (this.disposed) {
1455
+ return err(callpadError.disposed());
1456
+ }
1457
+ this.setState("connecting");
1458
+ try {
1459
+ await this.room.connect(opts.url, opts.token);
1460
+ await this.room.localParticipant.setMicrophoneEnabled(true);
1461
+ if (opts.video === true) {
1462
+ await this.room.localParticipant.setCameraEnabled(true);
1463
+ }
1464
+ return ok(void 0);
1465
+ } catch (cause) {
1466
+ this.setState("disconnected");
1467
+ return err(
1468
+ callpadError.mediaUnavailable(
1469
+ "media.connect_failed",
1470
+ "Media connect failed",
1471
+ {
1472
+ cause: cause instanceof Error ? cause : void 0
1473
+ }
1474
+ )
1475
+ );
1476
+ }
1477
+ }
1478
+ async disconnect() {
1479
+ await this.room.disconnect(true);
1480
+ this.snapshots.clear();
1481
+ this.setState("disconnected");
1482
+ }
1483
+ async dispose() {
1484
+ if (this.disposed) {
1485
+ return;
1486
+ }
1487
+ this.disposed = true;
1488
+ await this.room.disconnect(true);
1489
+ this.bus.clear();
1490
+ this.snapshots.clear();
1491
+ this.state = "disconnected";
1492
+ }
1493
+ setState(next) {
1494
+ if (next === this.state) {
1495
+ return;
1496
+ }
1497
+ const previous = this.state;
1498
+ this.state = next;
1499
+ this.bus.emit("state.changed", { state: next, previous });
1500
+ }
1501
+ wireRoomEvents() {
1502
+ this.room.on(RoomEvent.ConnectionStateChanged, (state) => {
1503
+ switch (state) {
1504
+ case ConnectionState.Connected:
1505
+ this.setState("connected");
1506
+ break;
1507
+ case ConnectionState.Connecting:
1508
+ this.setState("connecting");
1509
+ break;
1510
+ case ConnectionState.Reconnecting:
1511
+ this.setState("reconnecting");
1512
+ break;
1513
+ case ConnectionState.Disconnected:
1514
+ this.setState("disconnected");
1515
+ break;
1516
+ }
1517
+ });
1518
+ const refresh = (p) => {
1519
+ const snapshot = snapshotOf(p);
1520
+ const previous = this.snapshots.get(p.identity);
1521
+ if (previous && snapshotEquals(previous, snapshot)) {
1522
+ return;
1523
+ }
1524
+ this.snapshots.set(p.identity, snapshot);
1525
+ this.bus.emit("participant.changed", { identity: p.identity, snapshot });
1526
+ };
1527
+ this.room.on(
1528
+ RoomEvent.ParticipantConnected,
1529
+ (p) => refresh(p)
1530
+ );
1531
+ this.room.on(RoomEvent.ParticipantDisconnected, (p) => {
1532
+ this.snapshots.delete(p.identity);
1533
+ this.bus.emit("participant.changed", {
1534
+ identity: p.identity,
1535
+ snapshot: {
1536
+ identity: p.identity,
1537
+ isSpeaking: false,
1538
+ audioLevel: 0,
1539
+ micPublished: false,
1540
+ micMuted: true,
1541
+ cameraPublished: false,
1542
+ cameraMuted: true,
1543
+ screenShareActive: false,
1544
+ connectionQuality: "lost"
1545
+ }
1546
+ });
1547
+ });
1548
+ this.room.on(RoomEvent.TrackSubscribed, (_track, _pub, p) => refresh(p));
1549
+ this.room.on(RoomEvent.TrackUnsubscribed, (_track, _pub, p) => refresh(p));
1550
+ this.room.on(RoomEvent.TrackMuted, (_pub, p) => refresh(p));
1551
+ this.room.on(RoomEvent.TrackUnmuted, (_pub, p) => refresh(p));
1552
+ this.room.on(
1553
+ RoomEvent.LocalTrackPublished,
1554
+ (_pub, p) => refresh(p)
1555
+ );
1556
+ this.room.on(
1557
+ RoomEvent.LocalTrackUnpublished,
1558
+ (_pub, p) => refresh(p)
1559
+ );
1560
+ this.room.on(
1561
+ RoomEvent.ConnectionQualityChanged,
1562
+ (_q, p) => refresh(p)
1563
+ );
1564
+ this.room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
1565
+ const identities = speakers.map((p) => p.identity);
1566
+ this.bus.emit("active_speakers.changed", { identities });
1567
+ });
1568
+ this.room.on(RoomEvent.MediaDevicesError, (cause) => {
1569
+ this.bus.emit("error", {
1570
+ error: callpadError.mediaDevice(
1571
+ "media.device_error",
1572
+ "Media device error",
1573
+ {
1574
+ cause: cause instanceof Error ? cause : void 0
1575
+ }
1576
+ )
1577
+ });
1578
+ this.logger.warn(
1579
+ { err: cause instanceof Error ? cause : void 0 },
1580
+ "media device error"
1581
+ );
1582
+ });
1583
+ }
1584
+ };
1585
+
1586
+ // src/core/session/session.ts
1587
+ var Session = class {
1588
+ view;
1589
+ vendor;
1590
+ logger;
1591
+ bus = new EventBus();
1592
+ media;
1593
+ commands;
1594
+ ctx;
1595
+ mediaStatus = "unconnected";
1596
+ selfParticipantId;
1597
+ disposed = false;
1598
+ cachedGrant = null;
1599
+ cachedParticipants = null;
1600
+ cachedTelephonyLegs = null;
1601
+ cachedRecordings = null;
1602
+ cachedDispatches = null;
1603
+ constructor(opts) {
1604
+ this.vendor = opts.vendor;
1605
+ this.logger = opts.logger.child({ session: opts.view.id });
1606
+ this.view = opts.view;
1607
+ this.selfParticipantId = opts.selfParticipantId;
1608
+ this.commands = opts.commands;
1609
+ this.media = new MediaRoomAdapter(this.logger);
1610
+ this.ctx = {
1611
+ session: this,
1612
+ media: this.media,
1613
+ applyView: (view) => this.applyView(view)
1614
+ };
1615
+ this.wireMedia();
1616
+ }
1617
+ get id() {
1618
+ return this.view.id;
1619
+ }
1620
+ get callId() {
1621
+ return this.view.callId;
1622
+ }
1623
+ get vendorId() {
1624
+ return this.view.vendorId;
1625
+ }
1626
+ get vendorSlug() {
1627
+ return this.vendor;
1628
+ }
1629
+ get mediaType() {
1630
+ return this.view.mediaType;
1631
+ }
1632
+ get state() {
1633
+ return this.view.state;
1634
+ }
1635
+ get version() {
1636
+ return this.view.version;
1637
+ }
1638
+ get route() {
1639
+ return this.view.route;
1640
+ }
1641
+ get viewSnapshot() {
1642
+ return this.view;
1643
+ }
1644
+ get mediaStatusSnapshot() {
1645
+ return this.mediaStatus;
1646
+ }
1647
+ get mediaRoom() {
1648
+ return this.media.getRoom();
1649
+ }
1650
+ get participants() {
1651
+ if (this.cachedParticipants === null) {
1652
+ const lookup = this.media.listSnapshots();
1653
+ this.cachedParticipants = this.view.participants.map(
1654
+ (p) => participantFromView(p, this.selfParticipantId, lookup)
1655
+ );
1656
+ }
1657
+ return this.cachedParticipants;
1658
+ }
1659
+ get telephonyLegs() {
1660
+ if (this.cachedTelephonyLegs === null) {
1661
+ this.cachedTelephonyLegs = collectSipLegs(this.view.participants);
1662
+ }
1663
+ return this.cachedTelephonyLegs;
1664
+ }
1665
+ get dispatches() {
1666
+ if (this.cachedDispatches === null) {
1667
+ this.cachedDispatches = this.view.dispatches.map(dispatchFromView);
1668
+ }
1669
+ return this.cachedDispatches;
1670
+ }
1671
+ get recordings() {
1672
+ if (this.cachedRecordings === null) {
1673
+ this.cachedRecordings = this.view.recordings.map(recordingFromView);
1674
+ }
1675
+ return this.cachedRecordings;
1676
+ }
1677
+ get activeRecording() {
1678
+ const active = this.view.recordings.find(
1679
+ (r) => r.state === "requested" || r.state === "active"
1680
+ );
1681
+ return active ? recordingFromView(active) : null;
1682
+ }
1683
+ get self() {
1684
+ if (this.selfParticipantId === null) {
1685
+ return null;
1686
+ }
1687
+ return this.participants.find((p) => p.id === this.selfParticipantId) ?? null;
1688
+ }
1689
+ capabilitiesOf(participantId) {
1690
+ const id = participantId ?? this.selfParticipantId;
1691
+ if (id === null || id === void 0) {
1692
+ return [];
1693
+ }
1694
+ const participant = this.view.participants.find((p) => p.id === id);
1695
+ return participant?.capabilities ?? [];
1696
+ }
1697
+ on(type, handler) {
1698
+ return this.bus.on(type, handler);
1699
+ }
1700
+ applyView(next) {
1701
+ const previous = this.view;
1702
+ if (!shouldApplyUpsert(previous, next)) {
1703
+ return;
1704
+ }
1705
+ this.view = next;
1706
+ this.invalidateCaches();
1707
+ this.bus.emit("view.changed", { view: next, previous });
1708
+ if (next.state !== previous.state) {
1709
+ this.bus.emit("state.changed", {
1710
+ state: next.state,
1711
+ previous: previous.state
1712
+ });
1713
+ }
1714
+ this.diffParticipants(previous, next);
1715
+ this.diffTelephonyLegs(previous, next);
1716
+ this.diffDispatches(previous, next);
1717
+ this.diffRecordings(previous, next);
1718
+ if (previous.state !== "on_hold" && next.state === "on_hold") {
1719
+ this.bus.emit("session.held", { heldAt: (/* @__PURE__ */ new Date()).toISOString() });
1720
+ }
1721
+ if (previous.state === "on_hold" && next.state !== "on_hold" && next.state !== "ended") {
1722
+ this.bus.emit("session.unheld", { unheldAt: (/* @__PURE__ */ new Date()).toISOString() });
1723
+ }
1724
+ if (previous.state !== "ended" && next.state === "ended") {
1725
+ this.bus.emit("session.ended", {
1726
+ reason: next.endReason ?? "completed",
1727
+ endedAt: next.endedAt ?? (/* @__PURE__ */ new Date()).toISOString()
1728
+ });
1729
+ }
1730
+ }
1731
+ async dispatch(name, ...rest) {
1732
+ if (this.disposed) {
1733
+ return err(callpadError.disposed());
1734
+ }
1735
+ const cmd = this.commands.get(name);
1736
+ if (!cmd) {
1737
+ return err(
1738
+ callpadError.notfound(
1739
+ "session.unknown_command",
1740
+ `Unknown session command: ${String(name)}`
1741
+ )
1742
+ );
1743
+ }
1744
+ return cmd.execute(this.ctx, rest[0]);
1745
+ }
1746
+ async join() {
1747
+ if (this.disposed) {
1748
+ return err(callpadError.disposed());
1749
+ }
1750
+ if (this.mediaStatus === "connected") {
1751
+ return ok(void 0);
1752
+ }
1753
+ if (this.isEnded()) {
1754
+ return ok(void 0);
1755
+ }
1756
+ const grant = await this.requestGrant();
1757
+ if (!grant.ok) {
1758
+ return grant;
1759
+ }
1760
+ return this.joinWithGrant(grant.value);
1761
+ }
1762
+ async joinWithGrant(grant) {
1763
+ if (this.disposed) {
1764
+ return err(callpadError.disposed());
1765
+ }
1766
+ if (this.mediaStatus === "connected") {
1767
+ return ok(void 0);
1768
+ }
1769
+ if (this.isEnded()) {
1770
+ return ok(void 0);
1771
+ }
1772
+ const previousSelfId = this.selfParticipantId;
1773
+ this.cachedGrant = grant;
1774
+ this.selfParticipantId = grant.participantId;
1775
+ this.cachedParticipants = null;
1776
+ const connected = await this.media.connect({
1777
+ url: grant.url,
1778
+ token: grant.token,
1779
+ video: this.view.mediaType === "video"
1780
+ });
1781
+ if (!connected.ok) {
1782
+ this.cachedGrant = null;
1783
+ this.selfParticipantId = previousSelfId;
1784
+ this.cachedParticipants = null;
1785
+ if (this.isEnded()) {
1786
+ return ok(void 0);
1787
+ }
1788
+ }
1789
+ return connected;
1790
+ }
1791
+ isEnded() {
1792
+ return this.view.state === "ended";
1793
+ }
1794
+ leave() {
1795
+ return this.dispatch("leave");
1796
+ }
1797
+ cancel() {
1798
+ return this.dispatch("cancel");
1799
+ }
1800
+ end() {
1801
+ return this.dispatch("end");
1802
+ }
1803
+ hold() {
1804
+ return this.dispatch("hold");
1805
+ }
1806
+ unhold() {
1807
+ return this.dispatch("unhold");
1808
+ }
1809
+ startRecording() {
1810
+ return this.dispatch("startRecording");
1811
+ }
1812
+ stopRecording(recordingId) {
1813
+ return this.dispatch("stopRecording", recordingId);
1814
+ }
1815
+ invite(target2) {
1816
+ return this.dispatch("invite", target2);
1817
+ }
1818
+ removeParticipant(participantId) {
1819
+ return this.dispatch("removeParticipant", participantId);
1820
+ }
1821
+ updateName(name) {
1822
+ return this.dispatch("updateName", name);
1823
+ }
1824
+ mediaGrant() {
1825
+ return this.cachedGrant;
1826
+ }
1827
+ async dispose() {
1828
+ if (this.disposed) {
1829
+ return;
1830
+ }
1831
+ this.disposed = true;
1832
+ await this.media.dispose();
1833
+ this.bus.clear();
1834
+ }
1835
+ async requestGrant() {
1836
+ return apiCall(
1837
+ () => postApiV1SessionsBySessionIdJoin({
1838
+ path: { sessionId: this.id },
1839
+ query: { vendor: this.vendor }
1840
+ })
1841
+ );
1842
+ }
1843
+ invalidateCaches() {
1844
+ this.cachedParticipants = null;
1845
+ this.cachedTelephonyLegs = null;
1846
+ this.cachedRecordings = null;
1847
+ this.cachedDispatches = null;
1848
+ }
1849
+ wireMedia() {
1850
+ this.media.on("state.changed", ({ state }) => {
1851
+ this.mediaStatus = state;
1852
+ this.bus.emit("media.status.changed", { status: state });
1853
+ });
1854
+ this.media.on("participant.changed", ({ identity }) => {
1855
+ this.cachedParticipants = null;
1856
+ const view = this.view.participants.find(
1857
+ (p2) => p2.participantIdentity === identity
1858
+ );
1859
+ if (!view) {
1860
+ return;
1861
+ }
1862
+ const p = participantFromView(
1863
+ view,
1864
+ this.selfParticipantId,
1865
+ this.media.listSnapshots()
1866
+ );
1867
+ this.bus.emit("participant.updated", { participant: p });
1868
+ });
1869
+ this.media.on("error", ({ error }) => {
1870
+ this.bus.emit("error", { error });
1871
+ });
1872
+ }
1873
+ diffParticipants(prev, next) {
1874
+ const byId = new Map(prev.participants.map((p) => [p.id, p]));
1875
+ const lookup = this.media.listSnapshots();
1876
+ const prevJoinedCount = prev.participants.filter(
1877
+ (p) => p.state === "joined"
1878
+ ).length;
1879
+ for (const current of next.participants) {
1880
+ const before = byId.get(current.id);
1881
+ const participant = participantFromView(
1882
+ current,
1883
+ this.selfParticipantId,
1884
+ lookup
1885
+ );
1886
+ if (!before) {
1887
+ this.bus.emit("participant.invited", { participant });
1888
+ continue;
1889
+ }
1890
+ if (before.state === current.state) {
1891
+ continue;
1892
+ }
1893
+ switch (current.state) {
1894
+ case "accepted":
1895
+ this.bus.emit("participant.accepted", { participant });
1896
+ break;
1897
+ case "joined": {
1898
+ const isFirstJoin = prevJoinedCount === 0;
1899
+ this.bus.emit("participant.joined", { participant, isFirstJoin });
1900
+ break;
1901
+ }
1902
+ case "left": {
1903
+ const reason = nullify(current.leftReason) ?? "left";
1904
+ this.bus.emit("participant.left", { participant, reason });
1905
+ break;
1906
+ }
1907
+ case "declined":
1908
+ this.bus.emit("participant.declined", { participant });
1909
+ break;
1910
+ case "withdrawn":
1911
+ this.bus.emit("participant.withdrawn", { participant });
1912
+ break;
1913
+ case "removed":
1914
+ this.bus.emit("participant.removed", { participant });
1915
+ break;
1916
+ case "failed": {
1917
+ const reason = nullify(current.failureReason) ?? "unknown";
1918
+ const failedSipLeg = current.operations.find(
1919
+ (op) => op.kind === "sip_leg" && op.state === "failed"
1920
+ );
1921
+ this.bus.emit("participant.failed", {
1922
+ participant,
1923
+ reason,
1924
+ legFailureReason: nullify(failedSipLeg?.failureReason ?? null),
1925
+ sipStatusCode: nullify(failedSipLeg?.sipStatusCode ?? null)
1926
+ });
1927
+ break;
1928
+ }
1929
+ default:
1930
+ this.bus.emit("participant.updated", { participant });
1931
+ }
1932
+ }
1933
+ }
1934
+ diffTelephonyLegs(prev, next) {
1935
+ const beforeState = /* @__PURE__ */ new Map();
1936
+ for (const p of prev.participants) {
1937
+ for (const op of p.operations) {
1938
+ if (op.kind === "sip_leg") {
1939
+ beforeState.set(op.id, op.state);
1940
+ }
1941
+ }
1942
+ }
1943
+ for (const participant of next.participants) {
1944
+ for (const op of participant.operations) {
1945
+ if (op.kind !== "sip_leg") {
1946
+ continue;
1947
+ }
1948
+ const beforeOp = beforeState.get(op.id);
1949
+ if (beforeOp === op.state) {
1950
+ continue;
1951
+ }
1952
+ this.bus.emit("telephony_leg.updated", {
1953
+ leg: telephonyLegFromOperation(participant, op)
1954
+ });
1955
+ }
1956
+ }
1957
+ }
1958
+ diffDispatches(prev, next) {
1959
+ const byId = new Map(prev.dispatches.map((d) => [d.id, d]));
1960
+ for (const current of next.dispatches) {
1961
+ const before = byId.get(current.id);
1962
+ const dispatch = dispatchFromView(current);
1963
+ if (!before) {
1964
+ if (current.state === "active") {
1965
+ this.bus.emit("dispatch.started", { dispatch });
1966
+ }
1967
+ continue;
1968
+ }
1969
+ if (before.state === current.state) {
1970
+ continue;
1971
+ }
1972
+ switch (current.state) {
1973
+ case "resolved":
1974
+ this.bus.emit("dispatch.resolved", { dispatch });
1975
+ break;
1976
+ case "cancelled":
1977
+ this.bus.emit("dispatch.cancelled", { dispatch });
1978
+ break;
1979
+ case "expired":
1980
+ this.bus.emit("dispatch.expired", { dispatch });
1981
+ break;
1982
+ }
1983
+ }
1984
+ }
1985
+ diffRecordings(prev, next) {
1986
+ const byId = new Map(prev.recordings.map((r) => [r.id, r]));
1987
+ for (const current of next.recordings) {
1988
+ const before = byId.get(current.id);
1989
+ const recording = recordingFromView(current);
1990
+ if (!before) {
1991
+ this.bus.emit("recording.requested", { recording });
1992
+ continue;
1993
+ }
1994
+ if (before.state === current.state) {
1995
+ continue;
1996
+ }
1997
+ if (current.state === "active") {
1998
+ this.bus.emit("recording.started", { recording });
1999
+ continue;
2000
+ }
2001
+ if (current.state === "stopped") {
2002
+ this.bus.emit("recording.stopped", { recording });
2003
+ continue;
2004
+ }
2005
+ if (current.state === "failed") {
2006
+ this.bus.emit("recording.failed", {
2007
+ recording,
2008
+ reason: nullify(current.failureReason)
2009
+ });
2010
+ }
2011
+ }
2012
+ }
2013
+ };
2014
+
2015
+ // src/core/session/commands.ts
2016
+ function target(ctx) {
2017
+ return {
2018
+ path: { sessionId: ctx.session.id },
2019
+ query: { vendor: ctx.session.vendorSlug }
2020
+ };
2021
+ }
2022
+ var holdCommand = {
2023
+ name: "hold",
2024
+ async execute(ctx) {
2025
+ const res = await apiCall(
2026
+ () => postApiV1SessionsBySessionIdHold(target(ctx))
2027
+ );
2028
+ if (!res.ok) {
2029
+ return res;
2030
+ }
2031
+ ctx.applyView(res.value);
2032
+ return ok(void 0);
2033
+ }
2034
+ };
2035
+ var unholdCommand = {
2036
+ name: "unhold",
2037
+ async execute(ctx) {
2038
+ const res = await apiCall(
2039
+ () => postApiV1SessionsBySessionIdUnhold(target(ctx))
2040
+ );
2041
+ if (!res.ok) {
2042
+ return res;
2043
+ }
2044
+ ctx.applyView(res.value);
2045
+ return ok(void 0);
2046
+ }
2047
+ };
2048
+ var cancelCommand = {
2049
+ name: "cancel",
2050
+ async execute(ctx) {
2051
+ const res = await apiCall(
2052
+ () => postApiV1SessionsBySessionIdCancel(target(ctx))
2053
+ );
2054
+ if (!res.ok) {
2055
+ return res;
2056
+ }
2057
+ ctx.applyView(res.value);
2058
+ return ok(void 0);
2059
+ }
2060
+ };
2061
+ var endCommand = {
2062
+ name: "end",
2063
+ async execute(ctx) {
2064
+ const res = await apiCall(
2065
+ () => postApiV1SessionsBySessionIdEnd(target(ctx))
2066
+ );
2067
+ if (!res.ok) {
2068
+ return res;
2069
+ }
2070
+ ctx.applyView(res.value);
2071
+ return ok(void 0);
2072
+ }
2073
+ };
2074
+ var leaveCommand = {
2075
+ name: "leave",
2076
+ async execute(ctx) {
2077
+ if (ctx.session.state === "ended") {
2078
+ await ctx.media.disconnect();
2079
+ return ok(void 0);
2080
+ }
2081
+ const res = await apiCall(
2082
+ () => postApiV1SessionsBySessionIdLeave(target(ctx))
2083
+ );
2084
+ await ctx.media.disconnect();
2085
+ if (!res.ok) {
2086
+ return res;
2087
+ }
2088
+ ctx.applyView(res.value);
2089
+ return ok(void 0);
2090
+ }
2091
+ };
2092
+ var inviteCommand = {
2093
+ name: "invite",
2094
+ async execute(ctx, invited) {
2095
+ const body = { target: invited };
2096
+ const res = await apiCall(
2097
+ () => postApiV1SessionsBySessionIdParticipants({
2098
+ ...target(ctx),
2099
+ body
2100
+ })
2101
+ );
2102
+ if (!res.ok) {
2103
+ return res;
2104
+ }
2105
+ ctx.applyView(res.value);
2106
+ return ok(void 0);
2107
+ }
2108
+ };
2109
+ var removeParticipantCommand = {
2110
+ name: "removeParticipant",
2111
+ async execute(ctx, participantId) {
2112
+ const res = await apiCall(
2113
+ () => deleteApiV1SessionsBySessionIdParticipantsByParticipantId({
2114
+ path: { sessionId: ctx.session.id, participantId },
2115
+ query: { vendor: ctx.session.vendorSlug }
2116
+ })
2117
+ );
2118
+ if (!res.ok) {
2119
+ return res;
2120
+ }
2121
+ ctx.applyView(res.value);
2122
+ return ok(void 0);
2123
+ }
2124
+ };
2125
+ var updateNameCommand = {
2126
+ name: "updateName",
2127
+ async execute(ctx, name) {
2128
+ const res = await apiCall(
2129
+ () => patchApiV1SessionsBySessionId({
2130
+ ...target(ctx),
2131
+ body: { name }
2132
+ })
2133
+ );
2134
+ if (!res.ok) {
2135
+ return res;
2136
+ }
2137
+ ctx.applyView(res.value);
2138
+ return ok(void 0);
2139
+ }
2140
+ };
2141
+ var startRecordingCommand = {
2142
+ name: "startRecording",
2143
+ async execute(ctx) {
2144
+ const res = await apiCall(
2145
+ () => postApiV1SessionsBySessionIdRecordings(target(ctx))
2146
+ );
2147
+ if (!res.ok) {
2148
+ return res;
2149
+ }
2150
+ return ok(void 0);
2151
+ }
2152
+ };
2153
+ var stopRecordingCommand = {
2154
+ name: "stopRecording",
2155
+ async execute(ctx, recordingId) {
2156
+ const res = await apiCall(
2157
+ () => postApiV1SessionsBySessionIdRecordingsByRecordingIdStop({
2158
+ path: { sessionId: ctx.session.id, recordingId },
2159
+ query: { vendor: ctx.session.vendorSlug }
2160
+ })
2161
+ );
2162
+ if (!res.ok) {
2163
+ return res;
2164
+ }
2165
+ return ok(void 0);
2166
+ }
2167
+ };
2168
+
2169
+ // src/core/managers/session-manager.ts
2170
+ var ACTIVE_STATES = /* @__PURE__ */ new Set(["ringing", "active", "on_hold"]);
2171
+ var SessionManager = class {
2172
+ sessions = /* @__PURE__ */ new Map();
2173
+ vendor;
2174
+ logger;
2175
+ pulse;
2176
+ commands;
2177
+ selfParticipantId;
2178
+ bus = new EventBus();
2179
+ unsubs = [];
2180
+ cachedList = null;
2181
+ disposed = false;
2182
+ constructor(opts) {
2183
+ this.vendor = opts.vendor;
2184
+ this.logger = opts.logger.child({ component: "session-manager" });
2185
+ this.pulse = opts.pulse;
2186
+ this.selfParticipantId = opts.selfParticipantId;
2187
+ this.commands = opts.commands;
2188
+ this.unsubs.push(
2189
+ this.pulse.on("session.upsert", (view) => this.onUpsert(view)),
2190
+ this.pulse.on(
2191
+ "session.remove",
2192
+ ({ sessionId, version }) => this.onRemove(sessionId, version)
2193
+ )
2194
+ );
2195
+ }
2196
+ list() {
2197
+ if (this.cachedList === null) {
2198
+ this.cachedList = Array.from(this.sessions.values());
2199
+ }
2200
+ return this.cachedList;
2201
+ }
2202
+ get(id) {
2203
+ return this.sessions.get(id) ?? null;
2204
+ }
2205
+ active() {
2206
+ for (const session of this.sessions.values()) {
2207
+ if (ACTIVE_STATES.has(session.state)) {
2208
+ return session;
2209
+ }
2210
+ }
2211
+ return null;
2212
+ }
2213
+ activeId() {
2214
+ return this.active()?.id ?? null;
2215
+ }
2216
+ on(type, handler) {
2217
+ return this.bus.on(type, handler);
2218
+ }
2219
+ async prime() {
2220
+ if (this.disposed) {
2221
+ return err(callpadError.disposed());
2222
+ }
2223
+ const res = await apiCall(
2224
+ () => getApiV1Sessions({ query: { vendor: this.vendor, limit: 50 } })
2225
+ );
2226
+ if (!res.ok) {
2227
+ return res;
2228
+ }
2229
+ for (const view of res.value.items) {
2230
+ this.onUpsert(view);
2231
+ }
2232
+ return ok(void 0);
2233
+ }
2234
+ async create(body) {
2235
+ if (this.disposed) {
2236
+ return err(callpadError.disposed());
2237
+ }
2238
+ const res = await apiCall(
2239
+ () => postApiV1Sessions({
2240
+ query: { vendor: this.vendor },
2241
+ body
2242
+ })
2243
+ );
2244
+ if (!res.ok) {
2245
+ return res;
2246
+ }
2247
+ const session = this.onUpsert(res.value);
2248
+ return ok(session);
2249
+ }
2250
+ async fetchById(id) {
2251
+ if (this.disposed) {
2252
+ return err(callpadError.disposed());
2253
+ }
2254
+ const res = await apiCall(
2255
+ () => getApiV1SessionsBySessionId({
2256
+ path: { sessionId: id },
2257
+ query: { vendor: this.vendor }
2258
+ })
2259
+ );
2260
+ if (!res.ok) {
2261
+ return res;
2262
+ }
2263
+ const session = this.onUpsert(res.value);
2264
+ return ok(session);
2265
+ }
2266
+ onAcceptedInvite(view) {
2267
+ return this.onUpsert(view);
2268
+ }
2269
+ onUpsert(view) {
2270
+ const existing = this.sessions.get(view.id);
2271
+ if (existing) {
2272
+ if (shouldApplyUpsert(existing, view)) {
2273
+ existing.applyView(view);
2274
+ }
2275
+ return existing;
2276
+ }
2277
+ const session = new Session({
2278
+ vendor: this.vendor,
2279
+ view,
2280
+ logger: this.logger,
2281
+ selfParticipantId: this.selfParticipantId,
2282
+ commands: this.commands
2283
+ });
2284
+ this.sessions.set(view.id, session);
2285
+ this.cachedList = null;
2286
+ this.bus.emit("session.added", { session });
2287
+ return session;
2288
+ }
2289
+ onRemove(sessionId, _version) {
2290
+ const session = this.sessions.get(sessionId);
2291
+ if (!session) {
2292
+ return;
2293
+ }
2294
+ this.sessions.delete(sessionId);
2295
+ this.cachedList = null;
2296
+ this.bus.emit("session.removed", { sessionId });
2297
+ void session.dispose();
2298
+ }
2299
+ async dispose() {
2300
+ if (this.disposed) {
2301
+ return;
2302
+ }
2303
+ this.disposed = true;
2304
+ for (const unsub of this.unsubs) {
2305
+ unsub();
2306
+ }
2307
+ await Promise.all(
2308
+ Array.from(this.sessions.values(), (session) => session.dispose())
2309
+ );
2310
+ this.sessions.clear();
2311
+ this.bus.clear();
2312
+ }
2313
+ };
2314
+
2315
+ // src/core/invite.ts
2316
+ var Invite = class {
2317
+ view;
2318
+ vendor;
2319
+ onAccept;
2320
+ disposed = false;
2321
+ constructor(view, vendor, onAccept) {
2322
+ this.view = view;
2323
+ this.vendor = vendor;
2324
+ this.onAccept = onAccept;
2325
+ }
2326
+ get id() {
2327
+ return this.view.id;
2328
+ }
2329
+ get sessionId() {
2330
+ return this.view.sessionId;
2331
+ }
2332
+ get callId() {
2333
+ return this.view.callId;
2334
+ }
2335
+ get state() {
2336
+ return this.view.state;
2337
+ }
2338
+ get createdAt() {
2339
+ return this.view.createdAt;
2340
+ }
2341
+ get expiresAt() {
2342
+ return nullify(this.view.expiresAt);
2343
+ }
2344
+ get completedAt() {
2345
+ return nullify(this.view.completedAt);
2346
+ }
2347
+ get dispatchId() {
2348
+ return nullify(this.view.dispatchId);
2349
+ }
2350
+ get recipient() {
2351
+ return this.view.recipient;
2352
+ }
2353
+ get participantId() {
2354
+ return this.view.participantId;
2355
+ }
2356
+ get inviterParticipantId() {
2357
+ return nullify(this.view.inviterParticipantId);
2358
+ }
2359
+ get session() {
2360
+ return this.view.session;
2361
+ }
2362
+ applyView(next) {
2363
+ this.view = next;
2364
+ }
2365
+ async accept() {
2366
+ if (this.disposed) {
2367
+ return err(callpadError.disposed());
2368
+ }
2369
+ const res = await apiCall(
2370
+ () => postApiV1SessionsBySessionIdInvitesByInviteIdAccept({
2371
+ path: { sessionId: this.sessionId, inviteId: this.id },
2372
+ query: { vendor: this.vendor }
2373
+ })
2374
+ );
2375
+ if (!res.ok) {
2376
+ return res;
2377
+ }
2378
+ return this.onAccept(res.value);
2379
+ }
2380
+ async reject() {
2381
+ if (this.disposed) {
2382
+ return err(callpadError.disposed());
2383
+ }
2384
+ const res = await apiCall(
2385
+ () => postApiV1SessionsBySessionIdInvitesByInviteIdReject({
2386
+ path: { sessionId: this.sessionId, inviteId: this.id },
2387
+ query: { vendor: this.vendor }
2388
+ })
2389
+ );
2390
+ if (!res.ok) {
2391
+ return res;
2392
+ }
2393
+ return ok(void 0);
2394
+ }
2395
+ dispose() {
2396
+ this.disposed = true;
2397
+ }
2398
+ };
2399
+
2400
+ // src/core/managers/invite-manager.ts
2401
+ var InviteManager = class {
2402
+ invites = /* @__PURE__ */ new Map();
2403
+ sessionIndex = /* @__PURE__ */ new Map();
2404
+ vendor;
2405
+ pulse;
2406
+ onAccept;
2407
+ bus = new EventBus();
2408
+ unsubs = [];
2409
+ cachedList = null;
2410
+ disposed = false;
2411
+ constructor(opts) {
2412
+ this.vendor = opts.vendor;
2413
+ this.pulse = opts.pulse;
2414
+ this.onAccept = opts.onAccept;
2415
+ this.unsubs.push(
2416
+ this.pulse.on("session.invite.upsert", (view) => this.onUpsert(view)),
2417
+ this.pulse.on(
2418
+ "session.invite.remove",
2419
+ ({ inviteId }) => this.onRemove(inviteId)
2420
+ ),
2421
+ this.pulse.on(
2422
+ "session.remove",
2423
+ ({ sessionId }) => this.dropBySession(sessionId)
2424
+ )
2425
+ );
2426
+ }
2427
+ list() {
2428
+ if (this.cachedList === null) {
2429
+ this.cachedList = Array.from(this.invites.values());
2430
+ }
2431
+ return this.cachedList;
2432
+ }
2433
+ get(id) {
2434
+ return this.invites.get(id) ?? null;
2435
+ }
2436
+ first() {
2437
+ const iterator = this.invites.values().next();
2438
+ return iterator.done ? null : iterator.value;
2439
+ }
2440
+ on(type, handler) {
2441
+ return this.bus.on(type, handler);
2442
+ }
2443
+ async prime() {
2444
+ if (this.disposed) {
2445
+ return err(callpadError.disposed());
2446
+ }
2447
+ const res = await apiCall(
2448
+ () => getApiV1SessionsInvites({ query: { vendor: this.vendor } })
2449
+ );
2450
+ if (!res.ok) {
2451
+ return res;
2452
+ }
2453
+ for (const view of res.value) {
2454
+ this.onUpsert(view);
2455
+ }
2456
+ return ok(void 0);
2457
+ }
2458
+ onUpsert(view) {
2459
+ if (view.state !== "pending") {
2460
+ this.onRemove(view.id);
2461
+ return;
2462
+ }
2463
+ const existing = this.invites.get(view.id);
2464
+ if (existing) {
2465
+ if (!shouldApplyUpsert(existing.session, view.session)) {
2466
+ return;
2467
+ }
2468
+ existing.applyView(view);
2469
+ this.bus.emit("invite.updated", { invite: existing });
2470
+ return;
2471
+ }
2472
+ const invite = new Invite(view, this.vendor, this.onAccept);
2473
+ this.invites.set(view.id, invite);
2474
+ this.trackSession(view.sessionId, view.id);
2475
+ this.cachedList = null;
2476
+ this.bus.emit("invite.added", { invite });
2477
+ }
2478
+ onRemove(inviteId) {
2479
+ const existing = this.invites.get(inviteId);
2480
+ if (!existing) {
2481
+ return;
2482
+ }
2483
+ this.invites.delete(inviteId);
2484
+ this.untrackSession(existing.sessionId, inviteId);
2485
+ this.cachedList = null;
2486
+ this.bus.emit("invite.removed", { inviteId });
2487
+ existing.dispose();
2488
+ }
2489
+ dropBySession(sessionId) {
2490
+ const ids = this.sessionIndex.get(sessionId);
2491
+ if (!ids) {
2492
+ return;
2493
+ }
2494
+ for (const inviteId of ids) {
2495
+ this.onRemove(inviteId);
2496
+ }
2497
+ }
2498
+ trackSession(sessionId, inviteId) {
2499
+ let set = this.sessionIndex.get(sessionId);
2500
+ if (!set) {
2501
+ set = /* @__PURE__ */ new Set();
2502
+ this.sessionIndex.set(sessionId, set);
2503
+ }
2504
+ set.add(inviteId);
2505
+ }
2506
+ untrackSession(sessionId, inviteId) {
2507
+ const set = this.sessionIndex.get(sessionId);
2508
+ if (!set) {
2509
+ return;
2510
+ }
2511
+ set.delete(inviteId);
2512
+ if (set.size === 0) {
2513
+ this.sessionIndex.delete(sessionId);
2514
+ }
2515
+ }
2516
+ async dispose() {
2517
+ if (this.disposed) {
2518
+ return;
2519
+ }
2520
+ this.disposed = true;
2521
+ for (const unsub of this.unsubs) {
2522
+ unsub();
2523
+ }
2524
+ for (const invite of this.invites.values()) {
2525
+ invite.dispose();
2526
+ }
2527
+ this.invites.clear();
2528
+ this.sessionIndex.clear();
2529
+ this.bus.clear();
2530
+ }
2531
+ };
2532
+
2533
+ // src/core/presence.ts
2534
+ function presenceFromItem(item) {
2535
+ return {
2536
+ id: item.id,
2537
+ availability: nullify(item.availability),
2538
+ connectivity: nullify(item.connectivity),
2539
+ lastSeenAt: nullify(item.lastSeenAt)
2540
+ };
2541
+ }
2542
+
2543
+ // src/core/managers/presence-manager.ts
2544
+ var PresenceManager = class {
2545
+ vendor;
2546
+ bus = new EventBus();
2547
+ disposed = false;
2548
+ constructor(opts) {
2549
+ this.vendor = opts.vendor;
2550
+ }
2551
+ on(type, handler) {
2552
+ return this.bus.on(type, handler);
2553
+ }
2554
+ async get(refs) {
2555
+ if (this.disposed) {
2556
+ return err(callpadError.disposed());
2557
+ }
2558
+ if (refs.length === 0) {
2559
+ return ok(/* @__PURE__ */ new Map());
2560
+ }
2561
+ const byKind = /* @__PURE__ */ new Map();
2562
+ for (const ref of refs) {
2563
+ const list = byKind.get(ref.kind) ?? [];
2564
+ list.push(ref.id);
2565
+ byKind.set(ref.kind, list);
2566
+ }
2567
+ const responses = await Promise.all(
2568
+ Array.from(byKind.entries()).map(
2569
+ ([kind, ids]) => apiCall(
2570
+ () => getApiV1VendorsBySlugPresence({
2571
+ path: { slug: this.vendor },
2572
+ query: { type: kind, ids: ids.join(",") }
2573
+ })
2574
+ )
2575
+ )
2576
+ );
2577
+ const result = /* @__PURE__ */ new Map();
2578
+ for (const res of responses) {
2579
+ if (!res.ok) {
2580
+ return res;
2581
+ }
2582
+ for (const item of res.value.items) {
2583
+ const snapshot = presenceFromItem(item);
2584
+ result.set(snapshot.id, snapshot);
2585
+ this.bus.emit("presence.updated", { snapshot });
2586
+ }
2587
+ }
2588
+ return ok(result);
2589
+ }
2590
+ async setMyStatus(mode, note) {
2591
+ if (this.disposed) {
2592
+ return err(callpadError.disposed());
2593
+ }
2594
+ const res = await apiCall(
2595
+ () => putApiV1VendorsBySlugPresenceStatus({
2596
+ path: { slug: this.vendor },
2597
+ body: { status: mode, note: note ?? void 0 }
2598
+ })
2599
+ );
2600
+ if (!res.ok) {
2601
+ return res;
2602
+ }
2603
+ return ok(void 0);
2604
+ }
2605
+ async clearMyStatus() {
2606
+ if (this.disposed) {
2607
+ return err(callpadError.disposed());
2608
+ }
2609
+ const res = await apiCall(
2610
+ () => deleteApiV1VendorsBySlugPresenceStatus({
2611
+ path: { slug: this.vendor }
2612
+ })
2613
+ );
2614
+ if (!res.ok) {
2615
+ return res;
2616
+ }
2617
+ return ok(void 0);
2618
+ }
2619
+ async dispose() {
2620
+ this.disposed = true;
2621
+ this.bus.clear();
2622
+ }
2623
+ };
2624
+
2625
+ // src/core/plugin.ts
2626
+ var PluginHost = class {
2627
+ handles = [];
2628
+ async register(plugin, ctx) {
2629
+ const handle = await plugin.install(ctx);
2630
+ this.handles.push(handle);
2631
+ }
2632
+ async disposeAll() {
2633
+ while (this.handles.length > 0) {
2634
+ const h = this.handles.pop();
2635
+ if (h) {
2636
+ try {
2637
+ await h.dispose();
2638
+ } catch {
2639
+ }
2640
+ }
2641
+ }
2642
+ }
2643
+ };
2644
+
2645
+ // src/core/client.ts
2646
+ var CallpadClient = class {
2647
+ config;
2648
+ logger;
2649
+ bus = new EventBus();
2650
+ pluginHost = new PluginHost();
2651
+ sessionCommands = /* @__PURE__ */ new Map();
2652
+ pulseTransport = null;
2653
+ sessions = null;
2654
+ invites = null;
2655
+ presence = null;
2656
+ responseInterceptorId = null;
2657
+ status = "idle";
2658
+ disposed = false;
2659
+ constructor(config) {
2660
+ this.config = config;
2661
+ this.logger = (config.logger ?? noopLogger).child({
2662
+ component: "callpad-client"
2663
+ });
2664
+ this.registerSessionCommand(holdCommand);
2665
+ this.registerSessionCommand(unholdCommand);
2666
+ this.registerSessionCommand(cancelCommand);
2667
+ this.registerSessionCommand(endCommand);
2668
+ this.registerSessionCommand(leaveCommand);
2669
+ this.registerSessionCommand(inviteCommand);
2670
+ this.registerSessionCommand(removeParticipantCommand);
2671
+ this.registerSessionCommand(updateNameCommand);
2672
+ this.registerSessionCommand(startRecordingCommand);
2673
+ this.registerSessionCommand(stopRecordingCommand);
2674
+ }
2675
+ registerSessionCommand(cmd) {
2676
+ this.sessionCommands.set(
2677
+ cmd.name,
2678
+ cmd
2679
+ );
2680
+ }
2681
+ getStatus() {
2682
+ return this.status;
2683
+ }
2684
+ getSessions() {
2685
+ if (!this.sessions) {
2686
+ throw new Error(
2687
+ "CallpadClient: sessions not initialized; call connect() first"
2688
+ );
2689
+ }
2690
+ return this.sessions;
2691
+ }
2692
+ getInvites() {
2693
+ if (!this.invites) {
2694
+ throw new Error(
2695
+ "CallpadClient: invites not initialized; call connect() first"
2696
+ );
2697
+ }
2698
+ return this.invites;
2699
+ }
2700
+ getPresence() {
2701
+ if (!this.presence) {
2702
+ throw new Error(
2703
+ "CallpadClient: presence not initialized; call connect() first"
2704
+ );
2705
+ }
2706
+ return this.presence;
2707
+ }
2708
+ on(type, handler) {
2709
+ return this.bus.on(type, handler);
2710
+ }
2711
+ async connect() {
2712
+ if (this.disposed) {
2713
+ return err(callpadError.disposed());
2714
+ }
2715
+ if (this.status === "ready" || this.status === "connecting") {
2716
+ return ok(void 0);
2717
+ }
2718
+ this.setStatus("connecting");
2719
+ this.configureApiClient();
2720
+ const pulse = new PulseTransport({
2721
+ grantFetcher: () => this.fetchPulseGrant(),
2722
+ logger: this.logger
2723
+ });
2724
+ this.pulseTransport = pulse;
2725
+ const sessions = new SessionManager({
2726
+ vendor: this.config.vendor,
2727
+ logger: this.logger,
2728
+ pulse,
2729
+ selfParticipantId: null,
2730
+ commands: this.sessionCommands
2731
+ });
2732
+ const invites = new InviteManager({
2733
+ vendor: this.config.vendor,
2734
+ pulse,
2735
+ onAccept: async ({ session: view, joinGrant }) => {
2736
+ const session = sessions.onAcceptedInvite(view);
2737
+ return session.joinWithGrant(joinGrant);
2738
+ }
2739
+ });
2740
+ const presence = new PresenceManager({
2741
+ vendor: this.config.vendor
2742
+ });
2743
+ sessions.on("session.added", ({ session }) => {
2744
+ this.bus.emit("session.added", { session });
2745
+ });
2746
+ sessions.on("session.removed", ({ sessionId }) => {
2747
+ this.bus.emit("session.removed", { sessionId });
2748
+ });
2749
+ invites.on("invite.added", ({ invite }) => {
2750
+ this.bus.emit("invite.added", { inviteId: invite.id });
2751
+ });
2752
+ invites.on("invite.removed", ({ inviteId }) => {
2753
+ this.bus.emit("invite.removed", { inviteId });
2754
+ });
2755
+ pulse.on("status.changed", ({ status }) => {
2756
+ if (status === "recovering") {
2757
+ this.setStatus("degraded");
2758
+ } else if (status === "connected") {
2759
+ this.setStatus("ready");
2760
+ } else if (status === "disconnected") {
2761
+ this.setStatus("offline");
2762
+ }
2763
+ });
2764
+ this.sessions = sessions;
2765
+ this.invites = invites;
2766
+ this.presence = presence;
2767
+ const [connectPulse, sessionsPrime, invitesPrime] = await Promise.all([
2768
+ pulse.connect(),
2769
+ sessions.prime(),
2770
+ invites.prime()
2771
+ ]);
2772
+ if (!connectPulse.ok) {
2773
+ this.setStatus("offline");
2774
+ this.bus.emit("error", { error: connectPulse.error });
2775
+ return connectPulse;
2776
+ }
2777
+ for (const r of [sessionsPrime, invitesPrime]) {
2778
+ if (!r.ok) {
2779
+ this.logger.warn({ code: r.error.code }, "prime failed");
2780
+ }
2781
+ }
2782
+ this.setStatus("ready");
2783
+ return ok(void 0);
2784
+ }
2785
+ async dispose() {
2786
+ if (this.disposed) {
2787
+ return;
2788
+ }
2789
+ this.disposed = true;
2790
+ if (this.responseInterceptorId !== null) {
2791
+ client.interceptors.response.eject(this.responseInterceptorId);
2792
+ this.responseInterceptorId = null;
2793
+ }
2794
+ await this.pluginHost.disposeAll();
2795
+ await this.sessions?.dispose();
2796
+ await this.invites?.dispose();
2797
+ await this.presence?.dispose();
2798
+ await this.pulseTransport?.dispose();
2799
+ this.bus.clear();
2800
+ this.setStatus("disposed");
2801
+ }
2802
+ async createSession(body) {
2803
+ const manager = this.sessions;
2804
+ if (!manager) {
2805
+ return err(
2806
+ callpadError.precondition(
2807
+ "callpad.not_connected",
2808
+ "Client not connected"
2809
+ )
2810
+ );
2811
+ }
2812
+ return manager.create(body);
2813
+ }
2814
+ async use(plugin) {
2815
+ const pulse = this.pulseTransport;
2816
+ const sessions = this.sessions;
2817
+ const invites = this.invites;
2818
+ const presence = this.presence;
2819
+ if (!pulse || !sessions || !invites || !presence) {
2820
+ return err(
2821
+ callpadError.precondition(
2822
+ "callpad.not_connected",
2823
+ "Plugins require connect() first"
2824
+ )
2825
+ );
2826
+ }
2827
+ const ctx = {
2828
+ logger: this.logger.child({ plugin: plugin.name }),
2829
+ pulse,
2830
+ sessions,
2831
+ invites,
2832
+ presence,
2833
+ registerSessionCommand: (cmd) => this.registerSessionCommand(cmd),
2834
+ onSessionCreated: (handler) => this.bus.on("session.added", ({ session }) => handler(session)),
2835
+ onSessionDisposed: (handler) => this.bus.on("session.removed", ({ sessionId }) => handler(sessionId))
2836
+ };
2837
+ try {
2838
+ await this.pluginHost.register(plugin, ctx);
2839
+ return ok(void 0);
2840
+ } catch (cause) {
2841
+ return err(
2842
+ callpadError.internal(
2843
+ "callpad.plugin_install_failed",
2844
+ `Plugin "${plugin.name}" failed to install`,
2845
+ { cause: cause instanceof Error ? cause : void 0 }
2846
+ )
2847
+ );
2848
+ }
2849
+ }
2850
+ configureApiClient() {
2851
+ const baseUrl = this.config.apiBaseUrl;
2852
+ const auth = this.config.auth.getAccessToken;
2853
+ const retryingFetch = makeRetryingFetch((request) => fetch(request), {
2854
+ maxAttempts: 3,
2855
+ initialDelayMs: 300
2856
+ });
2857
+ client.setConfig({
2858
+ baseUrl,
2859
+ auth: async () => auth(),
2860
+ fetch: retryingFetch
2861
+ });
2862
+ if (this.responseInterceptorId !== null) {
2863
+ client.interceptors.response.eject(this.responseInterceptorId);
2864
+ }
2865
+ let unauthorizedFired = false;
2866
+ this.responseInterceptorId = client.interceptors.response.use(
2867
+ (response) => {
2868
+ if (response.status === 401) {
2869
+ if (!unauthorizedFired) {
2870
+ unauthorizedFired = true;
2871
+ this.config.auth.onUnauthorized?.();
2872
+ }
2873
+ } else if (unauthorizedFired) {
2874
+ unauthorizedFired = false;
2875
+ }
2876
+ return response;
2877
+ }
2878
+ );
2879
+ }
2880
+ async fetchPulseGrant() {
2881
+ return apiCall(
2882
+ () => getApiV1PulseGrants({
2883
+ query: { vendor: this.config.vendor }
2884
+ })
2885
+ );
2886
+ }
2887
+ setStatus(next) {
2888
+ if (next === this.status) {
2889
+ return;
2890
+ }
2891
+ const previous = this.status;
2892
+ this.status = next;
2893
+ this.bus.emit("status.changed", { status: next, previous });
2894
+ }
2895
+ };
2896
+ function createCallpadClient(config) {
2897
+ return new CallpadClient(config);
2898
+ }
2899
+
2900
+ export { CallpadClient, Invite, InviteManager, PresenceManager, Session, SessionManager, callpadError, createCallpadClient, err, isErr, isOk, noopLogger, ok, unwrap };
5
2901
  //# sourceMappingURL=index.js.map
6
2902
  //# sourceMappingURL=index.js.map