farvex 0.1.0 → 0.2.0

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