farvex 0.2.0 → 1.0.0

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