@d-id/client-sdk 1.1.14-staging.55 → 1.1.14-staging.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index-BHt2AhLb.js → index-DrArdZby.js} +78 -74
- package/dist/index.js +1 -1
- package/dist/index.umd.cjs +1 -1
- package/dist/{livekit-manager-DZ_BAT5P.js → livekit-manager-D5VqT5zj.js} +6 -6
- package/dist/src/types/stream/stream.d.ts +6 -0
- package/dist/src/types/stream/streams-v2.d.ts +1 -1
- package/package.json +1 -1
|
@@ -35,8 +35,8 @@ class Se extends te {
|
|
|
35
35
|
super({ kind: "WSError", description: t });
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
-
var Ie = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(Ie || {}), Ee = /* @__PURE__ */ ((e) => (e.TRIAL = "deid-trial", e.PRO = "deid-pro", e.ENTERPRISE = "deid-enterprise", e.LITE = "deid-lite", e.ADVANCED = "deid-advanced", e.BUILD = "deid-api-build", e.LAUNCH = "deid-api-launch", e.SCALE = "deid-api-scale", e))(Ee || {}), Me = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(Me || {}), _e = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(_e || {}), E = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e.Off = "Off", e))(E || {}), q = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(q || {}), Te = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(Te || {}),
|
|
39
|
-
const
|
|
38
|
+
var Ie = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(Ie || {}), Ee = /* @__PURE__ */ ((e) => (e.TRIAL = "deid-trial", e.PRO = "deid-pro", e.ENTERPRISE = "deid-enterprise", e.LITE = "deid-lite", e.ADVANCED = "deid-advanced", e.BUILD = "deid-api-build", e.LAUNCH = "deid-api-launch", e.SCALE = "deid-api-scale", e))(Ee || {}), Me = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(Me || {}), _e = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(_e || {}), E = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e.Off = "Off", e))(E || {}), q = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(q || {}), Te = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(Te || {}), Ae = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(Ae || {}), je = /* @__PURE__ */ ((e) => (e.Pdf = "pdf", e.Text = "text", e.Html = "html", e.Word = "word", e.Json = "json", e.Markdown = "markdown", e.Csv = "csv", e.Excel = "excel", e.Powerpoint = "powerpoint", e.Archive = "archive", e.Image = "image", e.Audio = "audio", e.Video = "video", e))(je || {}), de = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e.Expressive = "expressive", e))(de || {});
|
|
39
|
+
const At = (e) => {
|
|
40
40
|
switch (e) {
|
|
41
41
|
case "clip":
|
|
42
42
|
return "clip";
|
|
@@ -46,7 +46,7 @@ const jt = (e) => {
|
|
|
46
46
|
throw new Error(`Unknown video type: ${e}`);
|
|
47
47
|
}
|
|
48
48
|
};
|
|
49
|
-
var w = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(w || {}), G = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(G || {}), O = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Talking = "TALKING", e))(O || {}),
|
|
49
|
+
var w = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(w || {}), G = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(G || {}), O = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Talking = "TALKING", e))(O || {}), b = /* @__PURE__ */ ((e) => (e.ChatAnswer = "chat/answer", e.ChatPartial = "chat/partial", e.StreamDone = "stream/done", e.StreamStarted = "stream/started", e.StreamFailed = "stream/error", e.StreamReady = "stream/ready", e.StreamCreated = "stream/created", e.StreamInterrupt = "stream/interrupt", e.StreamVideoCreated = "stream-video/started", e.StreamVideoDone = "stream-video/done", e.StreamVideoError = "stream-video/error", e.StreamVideoRejected = "stream-video/rejected", e))(b || {}), R = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnected = "disconnected", e))(R || {}), J = /* @__PURE__ */ ((e) => (e.Legacy = "legacy", e.Fluent = "fluent", e))(J || {}), Pe = /* @__PURE__ */ ((e) => (e.Livekit = "livekit", e))(Pe || {}), be = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(be || {}), Le = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(Le || {});
|
|
50
50
|
const Be = 45 * 1e3, $e = "X-Playground-Chat", ee = "https://api.d-id.com", xe = "wss://notifications.d-id.com", ze = "79f81a83a67430be2bc0fd61042b8faa", le = (e) => new Promise((t) => setTimeout(t, e)), V = (e = 16) => {
|
|
51
51
|
const t = new Uint8Array(e);
|
|
52
52
|
return window.crypto.getRandomValues(t), Array.from(t, (n) => n.toString(16).padStart(2, "0")).join("").slice(0, 13);
|
|
@@ -181,7 +181,7 @@ function he(e, t = ee, n) {
|
|
|
181
181
|
};
|
|
182
182
|
}
|
|
183
183
|
const we = (e) => e.type === "clip" && e.presenter_id.startsWith("v2_") ? "clip_v2" : e.type;
|
|
184
|
-
function
|
|
184
|
+
function Ue(e) {
|
|
185
185
|
var i, o, c, a;
|
|
186
186
|
const t = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", n = () => {
|
|
187
187
|
const s = navigator.platform;
|
|
@@ -199,7 +199,7 @@ function Ke(e) {
|
|
|
199
199
|
}
|
|
200
200
|
};
|
|
201
201
|
}
|
|
202
|
-
function
|
|
202
|
+
function Ke(e) {
|
|
203
203
|
var n, r, i, o, c, a;
|
|
204
204
|
const t = (n = e.llm) == null ? void 0 : n.prompt_customization;
|
|
205
205
|
return {
|
|
@@ -347,7 +347,7 @@ function Ye(e, t, n) {
|
|
|
347
347
|
}
|
|
348
348
|
async function Qe(e, t) {
|
|
349
349
|
const n = {
|
|
350
|
-
type:
|
|
350
|
+
type: b.StreamInterrupt,
|
|
351
351
|
videoId: t,
|
|
352
352
|
timestamp: Date.now()
|
|
353
353
|
};
|
|
@@ -426,12 +426,12 @@ function nt(e, t, n, r, i) {
|
|
|
426
426
|
mode: t.chatMode
|
|
427
427
|
});
|
|
428
428
|
else {
|
|
429
|
-
const l =
|
|
429
|
+
const l = b, y = [l.StreamVideoDone, l.StreamVideoError, l.StreamVideoRejected], M = [l.StreamFailed, l.StreamVideoError, l.StreamVideoRejected], A = qe(a, r, { mode: t.chatMode });
|
|
430
430
|
if (c = c, c === l.StreamVideoCreated)
|
|
431
|
-
e.linkTrack("agent-video",
|
|
431
|
+
e.linkTrack("agent-video", A, l.StreamVideoCreated, ["start"]);
|
|
432
432
|
else if (y.includes(c)) {
|
|
433
|
-
const
|
|
434
|
-
M.includes(c) ? e.track("agent-video", { ...
|
|
433
|
+
const P = c.split("/")[1];
|
|
434
|
+
M.includes(c) ? e.track("agent-video", { ...A, event: P }) : e.linkTrack("agent-video", { ...A, event: P }, c, ["done"]);
|
|
435
435
|
}
|
|
436
436
|
M.includes(c) && ((d = (s = n.callbacks).onError) == null || d.call(s, new Error(`Stream failed with event ${c}`), { data: a })), a.event === l.StreamDone && i();
|
|
437
437
|
}
|
|
@@ -611,15 +611,15 @@ function mt() {
|
|
|
611
611
|
};
|
|
612
612
|
}
|
|
613
613
|
function gt(e, t, n, r, i, o = !1) {
|
|
614
|
-
let c = [], a, s = 0, d = !1, l = G.Unknown, y = G.Unknown, M = 0,
|
|
615
|
-
const
|
|
614
|
+
let c = [], a, s = 0, d = !1, l = G.Unknown, y = G.Unknown, M = 0, A = 0;
|
|
615
|
+
const P = mt();
|
|
616
616
|
return setInterval(async () => {
|
|
617
|
-
const z = await e.getStats(), { isReceiving:
|
|
618
|
-
if (
|
|
619
|
-
s = 0, M = C -
|
|
617
|
+
const z = await e.getStats(), { isReceiving: U, avgJitterDelayInInterval: W, freezeCount: C } = P(z), K = ct(z);
|
|
618
|
+
if (U)
|
|
619
|
+
s = 0, M = C - A, y = W < ut ? G.Strong : W > ft && M > 1 ? G.Weak : l, y !== l && (i == null || i(y), l = y, A += M, M = 0), d || (r == null || r(w.Start), a = c[c.length - 1], c = [], d = !0), c.push(K);
|
|
620
620
|
else if (d && (s++, s >= lt)) {
|
|
621
621
|
const u = dt(c, ie, a);
|
|
622
|
-
r == null || r(w.Stop, u), t() || n(),
|
|
622
|
+
r == null || r(w.Stop, u), t() || n(), A = C, d = !1;
|
|
623
623
|
}
|
|
624
624
|
}, ie);
|
|
625
625
|
}
|
|
@@ -690,20 +690,20 @@ async function vt(e, t, { debug: n = !1, callbacks: r, auth: i, baseURL: o = ee,
|
|
|
690
690
|
var Y;
|
|
691
691
|
const a = it(n, "WebRTCStreamingManager"), s = wt(a);
|
|
692
692
|
let d = !1, l = !1, y = w.Stop, M = w.Stop;
|
|
693
|
-
const { startConnection:
|
|
693
|
+
const { startConnection: A, sendStreamRequest: P, close: z, createStream: U, addIceCandidate: W } = at(
|
|
694
694
|
i,
|
|
695
695
|
o,
|
|
696
696
|
e,
|
|
697
697
|
r.onError
|
|
698
698
|
), {
|
|
699
699
|
id: C,
|
|
700
|
-
offer:
|
|
700
|
+
offer: K,
|
|
701
701
|
ice_servers: u,
|
|
702
702
|
session_id: h,
|
|
703
703
|
fluent: p,
|
|
704
704
|
interrupt_enabled: _,
|
|
705
705
|
triggers_enabled: v
|
|
706
|
-
} = await
|
|
706
|
+
} = await U(t);
|
|
707
707
|
(Y = r.onStreamCreated) == null || Y.call(r, { stream_id: C, session_id: h, agent_id: e });
|
|
708
708
|
const f = new ht({ iceServers: u }), S = f.createDataChannel("JanusDataChannel");
|
|
709
709
|
if (!h)
|
|
@@ -746,8 +746,8 @@ async function vt(e, t, { debug: n = !1, callbacks: r, auth: i, baseURL: o = ee,
|
|
|
746
746
|
},
|
|
747
747
|
h
|
|
748
748
|
) : W(C, { candidate: null }, h);
|
|
749
|
-
} catch (
|
|
750
|
-
(g = r.onError) == null || g.call(r,
|
|
749
|
+
} catch (j) {
|
|
750
|
+
(g = r.onError) == null || g.call(r, j, { streamId: C });
|
|
751
751
|
}
|
|
752
752
|
}, S.onopen = () => {
|
|
753
753
|
l = !0, (!L || d) && I();
|
|
@@ -757,11 +757,11 @@ async function vt(e, t, { debug: n = !1, callbacks: r, auth: i, baseURL: o = ee,
|
|
|
757
757
|
(g = r.onVideoIdChange) == null || g.call(r, m);
|
|
758
758
|
};
|
|
759
759
|
function B(m, g) {
|
|
760
|
-
if (m ===
|
|
761
|
-
const
|
|
762
|
-
x(
|
|
760
|
+
if (m === b.StreamStarted && typeof g == "object" && "metadata" in g) {
|
|
761
|
+
const j = g.metadata;
|
|
762
|
+
x(j.videoId);
|
|
763
763
|
}
|
|
764
|
-
m ===
|
|
764
|
+
m === b.StreamDone && x(null), y = m === b.StreamStarted ? w.Start : w.Stop, ce({
|
|
765
765
|
statsSignal: T === J.Legacy ? M : void 0,
|
|
766
766
|
dataChannelSignal: y,
|
|
767
767
|
onVideoStateChange: r.onVideoStateChange,
|
|
@@ -770,18 +770,18 @@ async function vt(e, t, { debug: n = !1, callbacks: r, auth: i, baseURL: o = ee,
|
|
|
770
770
|
});
|
|
771
771
|
}
|
|
772
772
|
function F(m, g) {
|
|
773
|
-
const
|
|
774
|
-
|
|
773
|
+
const j = typeof g == "string" ? g : g == null ? void 0 : g.metadata;
|
|
774
|
+
j && c.enrich({ streamMetadata: j }), c.track("agent-chat", { event: "ready" });
|
|
775
775
|
}
|
|
776
776
|
const N = {
|
|
777
|
-
[
|
|
778
|
-
[
|
|
779
|
-
[
|
|
777
|
+
[b.StreamStarted]: B,
|
|
778
|
+
[b.StreamDone]: B,
|
|
779
|
+
[b.StreamReady]: F
|
|
780
780
|
};
|
|
781
781
|
S.onmessage = (m) => {
|
|
782
782
|
var Q;
|
|
783
|
-
const { subject: g, data:
|
|
784
|
-
(Q = N[g]) == null || Q.call(N, g,
|
|
783
|
+
const { subject: g, data: j } = s(m.data);
|
|
784
|
+
(Q = N[g]) == null || Q.call(N, g, j);
|
|
785
785
|
}, f.oniceconnectionstatechange = () => {
|
|
786
786
|
var g;
|
|
787
787
|
a("peerConnection.oniceconnectionstatechange => " + f.iceConnectionState);
|
|
@@ -790,15 +790,15 @@ async function vt(e, t, { debug: n = !1, callbacks: r, auth: i, baseURL: o = ee,
|
|
|
790
790
|
}, f.ontrack = (m) => {
|
|
791
791
|
var g;
|
|
792
792
|
a("peerConnection.ontrack", m), (g = r.onSrcObjectReady) == null || g.call(r, m.streams[0]);
|
|
793
|
-
}, await f.setRemoteDescription(
|
|
793
|
+
}, await f.setRemoteDescription(K), a("set remote description OK");
|
|
794
794
|
const X = await f.createAnswer();
|
|
795
|
-
return a("create answer OK"), await f.setLocalDescription(X), a("set local description OK"), await
|
|
795
|
+
return a("create answer OK"), await f.setLocalDescription(X), a("set local description OK"), await A(C, X, h), a("start connection OK"), {
|
|
796
796
|
/**
|
|
797
797
|
* Method to send request to server to get clip or talk depend on you payload
|
|
798
798
|
* @param payload
|
|
799
799
|
*/
|
|
800
800
|
speak(m) {
|
|
801
|
-
return
|
|
801
|
+
return P(C, h, m);
|
|
802
802
|
},
|
|
803
803
|
/**
|
|
804
804
|
* Method to close RTC connection
|
|
@@ -815,10 +815,10 @@ async function vt(e, t, { debug: n = !1, callbacks: r, auth: i, baseURL: o = ee,
|
|
|
815
815
|
f.close(), f.oniceconnectionstatechange = null, f.onnegotiationneeded = null, f.onicecandidate = null, f.ontrack = null;
|
|
816
816
|
}
|
|
817
817
|
try {
|
|
818
|
-
g === R.Connected && await z(C, h).catch((
|
|
818
|
+
g === R.Connected && await z(C, h).catch((j) => {
|
|
819
819
|
});
|
|
820
|
-
} catch (
|
|
821
|
-
a("Error on close stream connection",
|
|
820
|
+
} catch (j) {
|
|
821
|
+
a("Error on close stream connection", j);
|
|
822
822
|
}
|
|
823
823
|
(m = r.onAgentActivityStateChange) == null || m.call(r, O.Idle), clearInterval(k);
|
|
824
824
|
}
|
|
@@ -827,7 +827,7 @@ async function vt(e, t, { debug: n = !1, callbacks: r, auth: i, baseURL: o = ee,
|
|
|
827
827
|
* Method to send data channel messages to the server
|
|
828
828
|
*/
|
|
829
829
|
sendDataChannelMessage(m) {
|
|
830
|
-
var g,
|
|
830
|
+
var g, j;
|
|
831
831
|
if (!d || S.readyState !== "open") {
|
|
832
832
|
a("Data channel is not ready for sending messages"), (g = r.onError) == null || g.call(r, new Error("Data channel is not ready for sending messages"), {
|
|
833
833
|
streamId: C
|
|
@@ -837,7 +837,7 @@ async function vt(e, t, { debug: n = !1, callbacks: r, auth: i, baseURL: o = ee,
|
|
|
837
837
|
try {
|
|
838
838
|
S.send(m);
|
|
839
839
|
} catch (Q) {
|
|
840
|
-
a("Error sending data channel message", Q), (
|
|
840
|
+
a("Error sending data channel message", Q), (j = r.onError) == null || j.call(r, Q, { streamId: C });
|
|
841
841
|
}
|
|
842
842
|
},
|
|
843
843
|
/**
|
|
@@ -857,20 +857,24 @@ const kt = (e) => e.presenter.type === de.Expressive;
|
|
|
857
857
|
async function Dt(e, t, n) {
|
|
858
858
|
const r = e.id;
|
|
859
859
|
if (kt(e)) {
|
|
860
|
-
const { createLiveKitStreamingManager: i } = await import("./livekit-manager-
|
|
860
|
+
const { createLiveKitStreamingManager: i } = await import("./livekit-manager-D5VqT5zj.js");
|
|
861
861
|
return i(r, t, n);
|
|
862
862
|
} else
|
|
863
863
|
return vt(r, t, n);
|
|
864
864
|
}
|
|
865
865
|
function Ct(e) {
|
|
866
|
-
|
|
867
|
-
|
|
866
|
+
var i, o, c;
|
|
867
|
+
const { streamOptions: t } = e ?? {}, n = e != null && e.distinctId || ((i = e == null ? void 0 : e.mixpanelAdditionalProperties) == null ? void 0 : i.plan) !== void 0 ? {
|
|
868
|
+
...e != null && e.distinctId ? { distinct_id: e.distinctId } : {},
|
|
869
|
+
...((o = e == null ? void 0 : e.mixpanelAdditionalProperties) == null ? void 0 : o.plan) !== void 0 ? { plan: (c = e.mixpanelAdditionalProperties) == null ? void 0 : c.plan } : {}
|
|
870
|
+
} : void 0;
|
|
871
|
+
return { ...{
|
|
868
872
|
output_resolution: t == null ? void 0 : t.outputResolution,
|
|
869
873
|
session_timeout: t == null ? void 0 : t.sessionTimeout,
|
|
870
874
|
stream_warmup: t == null ? void 0 : t.streamWarmup,
|
|
871
875
|
compatibility_mode: t == null ? void 0 : t.compatibilityMode,
|
|
872
876
|
fluent: t == null ? void 0 : t.fluent
|
|
873
|
-
};
|
|
877
|
+
}, ...n && { end_user_data: n } };
|
|
874
878
|
}
|
|
875
879
|
function Rt(e, t, n, r, i) {
|
|
876
880
|
i === J.Fluent ? St(e, t, n, r, i) : Et(e, t, n, r, i);
|
|
@@ -889,7 +893,7 @@ function It(e, t, n, r) {
|
|
|
889
893
|
"agent-video",
|
|
890
894
|
{ event: "start", latency: $.get(!0), "stream-type": r },
|
|
891
895
|
"start",
|
|
892
|
-
[
|
|
896
|
+
[b.StreamVideoCreated]
|
|
893
897
|
) : e === w.Stop && n.linkTrack(
|
|
894
898
|
"agent-video",
|
|
895
899
|
{
|
|
@@ -899,7 +903,7 @@ function It(e, t, n, r) {
|
|
|
899
903
|
"stream-type": r
|
|
900
904
|
},
|
|
901
905
|
"done",
|
|
902
|
-
[
|
|
906
|
+
[b.StreamVideoDone]
|
|
903
907
|
));
|
|
904
908
|
}
|
|
905
909
|
function Et(e, t, n, r, i) {
|
|
@@ -907,7 +911,7 @@ function Et(e, t, n, r, i) {
|
|
|
907
911
|
"agent-video",
|
|
908
912
|
{ event: "start", latency: $.get(!0), "stream-type": i },
|
|
909
913
|
"start",
|
|
910
|
-
[
|
|
914
|
+
[b.StreamVideoCreated]
|
|
911
915
|
) : e === w.Stop && r.linkTrack(
|
|
912
916
|
"agent-video",
|
|
913
917
|
{
|
|
@@ -918,7 +922,7 @@ function Et(e, t, n, r, i) {
|
|
|
918
922
|
...n
|
|
919
923
|
},
|
|
920
924
|
"done",
|
|
921
|
-
[
|
|
925
|
+
[b.StreamVideoDone]
|
|
922
926
|
));
|
|
923
927
|
}
|
|
924
928
|
function Mt(e, t, n) {
|
|
@@ -961,12 +965,12 @@ function Mt(e, t, n) {
|
|
|
961
965
|
});
|
|
962
966
|
}
|
|
963
967
|
async function _t(e, t, n, r, i) {
|
|
964
|
-
var y, M,
|
|
968
|
+
var y, M, A, P;
|
|
965
969
|
const o = ve(e, n, r, t.mode, t.persistentChat, i), c = Mt(e, t, r), [a, s] = await Promise.all([o, c]), { chat: d, chatMode: l } = a;
|
|
966
|
-
return l && l !== t.mode && (t.mode = l, (M = (y = t.callbacks).onModeChange) == null || M.call(y, l), l !== E.Functional) ? ((
|
|
970
|
+
return l && l !== t.mode && (t.mode = l, (M = (y = t.callbacks).onModeChange) == null || M.call(y, l), l !== E.Functional) ? ((P = (A = t.callbacks).onError) == null || P.call(A, new Re(l)), s == null || s.disconnect(), { chat: d }) : { chat: d, streamingManager: s };
|
|
967
971
|
}
|
|
968
|
-
async function
|
|
969
|
-
var W, C,
|
|
972
|
+
async function jt(e, t) {
|
|
973
|
+
var W, C, K;
|
|
970
974
|
let n = !0, r = null;
|
|
971
975
|
const i = t.mixpanelKey || ze, o = t.wsURL || xe, c = t.baseURL || ee, a = {
|
|
972
976
|
messages: [],
|
|
@@ -980,7 +984,7 @@ async function At(e, t) {
|
|
|
980
984
|
});
|
|
981
985
|
s.track("agent-sdk", { event: "init" });
|
|
982
986
|
const d = he(t.auth, c, t.callbacks.onError), l = await d.getById(e);
|
|
983
|
-
s.enrich(
|
|
987
|
+
s.enrich(Ke(l));
|
|
984
988
|
const { onMessage: y, clearQueue: M } = nt(
|
|
985
989
|
s,
|
|
986
990
|
a,
|
|
@@ -992,17 +996,17 @@ async function At(e, t) {
|
|
|
992
996
|
}
|
|
993
997
|
);
|
|
994
998
|
a.messages = Xe(t.initialMessages), (C = (W = t.callbacks).onNewMessage) == null || C.call(W, [...a.messages], "answer");
|
|
995
|
-
const
|
|
999
|
+
const A = (u) => {
|
|
996
1000
|
r = u;
|
|
997
1001
|
};
|
|
998
|
-
s.track("agent-sdk", { event: "loaded", ...
|
|
999
|
-
async function
|
|
1002
|
+
s.track("agent-sdk", { event: "loaded", ...Ue(l) });
|
|
1003
|
+
async function P(u) {
|
|
1000
1004
|
var S, T, L, D, I, k, x;
|
|
1001
1005
|
(T = (S = t.callbacks).onConnectionStateChange) == null || T.call(S, R.Connecting), $.reset(), u && !n && (delete a.chat, (D = (L = t.callbacks).onNewMessage) == null || D.call(L, [...a.messages], "answer"));
|
|
1002
1006
|
const h = t.mode === E.DirectPlayback ? Promise.resolve(void 0) : et(t.auth, o, { onMessage: y, onError: t.callbacks.onError }), p = ne(
|
|
1003
1007
|
() => _t(
|
|
1004
1008
|
l,
|
|
1005
|
-
{ ...t, callbacks: { ...t.callbacks, onVideoIdChange:
|
|
1009
|
+
{ ...t, callbacks: { ...t.callbacks, onVideoIdChange: A } },
|
|
1006
1010
|
d,
|
|
1007
1011
|
s,
|
|
1008
1012
|
a.chat
|
|
@@ -1017,19 +1021,19 @@ async function At(e, t) {
|
|
|
1017
1021
|
}
|
|
1018
1022
|
).catch((B) => {
|
|
1019
1023
|
var F, N;
|
|
1020
|
-
throw
|
|
1024
|
+
throw U(E.Maintenance), (N = (F = t.callbacks).onConnectionStateChange) == null || N.call(F, R.Fail), B;
|
|
1021
1025
|
}), [_, { streamingManager: v, chat: f }] = await Promise.all([h, p]);
|
|
1022
1026
|
f && f.id !== ((I = a.chat) == null ? void 0 : I.id) && ((x = (k = t.callbacks).onNewChat) == null || x.call(k, f.id)), a.streamingManager = v, a.socketManager = _, a.chat = f, n = !1, s.enrich({
|
|
1023
1027
|
chatId: f == null ? void 0 : f.id,
|
|
1024
1028
|
streamId: v == null ? void 0 : v.streamId,
|
|
1025
1029
|
mode: a.chatMode
|
|
1026
|
-
}),
|
|
1030
|
+
}), U((f == null ? void 0 : f.chat_mode) ?? t.mode ?? E.Functional);
|
|
1027
1031
|
}
|
|
1028
1032
|
async function z() {
|
|
1029
1033
|
var u, h, p, _;
|
|
1030
1034
|
(u = a.socketManager) == null || u.disconnect(), await ((h = a.streamingManager) == null ? void 0 : h.disconnect()), delete a.streamingManager, delete a.socketManager, (_ = (p = t.callbacks).onConnectionStateChange) == null || _.call(p, R.Disconnected);
|
|
1031
1035
|
}
|
|
1032
|
-
async function
|
|
1036
|
+
async function U(u) {
|
|
1033
1037
|
var h, p;
|
|
1034
1038
|
u !== a.chatMode && (s.track("agent-mode-change", { mode: u }), a.chatMode = u, a.chatMode !== E.Functional && await z(), (p = (h = t.callbacks).onModeChange) == null || p.call(h, u));
|
|
1035
1039
|
}
|
|
@@ -1047,18 +1051,18 @@ async function At(e, t) {
|
|
|
1047
1051
|
var u;
|
|
1048
1052
|
return ((u = a.streamingManager) == null ? void 0 : u.triggersAvailable) ?? !1;
|
|
1049
1053
|
},
|
|
1050
|
-
starterMessages: ((
|
|
1054
|
+
starterMessages: ((K = l.knowledge) == null ? void 0 : K.starter_message) || [],
|
|
1051
1055
|
getSTTToken: () => d.getSTTToken(l.id),
|
|
1052
|
-
changeMode:
|
|
1056
|
+
changeMode: U,
|
|
1053
1057
|
enrichAnalytics: s.enrich,
|
|
1054
1058
|
async connect() {
|
|
1055
|
-
await
|
|
1059
|
+
await P(!0), s.track("agent-chat", {
|
|
1056
1060
|
event: "connect",
|
|
1057
1061
|
mode: a.chatMode
|
|
1058
1062
|
});
|
|
1059
1063
|
},
|
|
1060
1064
|
async reconnect() {
|
|
1061
|
-
await z(), await
|
|
1065
|
+
await z(), await P(!1), s.track("agent-chat", {
|
|
1062
1066
|
event: "reconnect",
|
|
1063
1067
|
mode: a.chatMode
|
|
1064
1068
|
});
|
|
@@ -1127,7 +1131,7 @@ async function At(e, t) {
|
|
|
1127
1131
|
return !((N = k == null ? void 0 : k.message) == null ? void 0 : N.includes("Stream Error")) && !x ? ((Y = (X = t.callbacks).onError) == null || Y.call(X, k), !1) : !0;
|
|
1128
1132
|
},
|
|
1129
1133
|
onRetry: async () => {
|
|
1130
|
-
await z(), await
|
|
1134
|
+
await z(), await P(!1);
|
|
1131
1135
|
}
|
|
1132
1136
|
}
|
|
1133
1137
|
);
|
|
@@ -1247,19 +1251,19 @@ async function At(e, t) {
|
|
|
1247
1251
|
}
|
|
1248
1252
|
};
|
|
1249
1253
|
}
|
|
1250
|
-
function
|
|
1254
|
+
function Pt(e, t, n) {
|
|
1251
1255
|
const { getById: r } = he(t, n || ee);
|
|
1252
1256
|
return r(e);
|
|
1253
1257
|
}
|
|
1254
1258
|
export {
|
|
1255
1259
|
O as A,
|
|
1256
1260
|
R as C,
|
|
1257
|
-
|
|
1258
|
-
|
|
1261
|
+
je as D,
|
|
1262
|
+
Ae as K,
|
|
1259
1263
|
Ee as P,
|
|
1260
1264
|
_e as R,
|
|
1261
1265
|
J as S,
|
|
1262
|
-
|
|
1266
|
+
Pe as T,
|
|
1263
1267
|
Ie as U,
|
|
1264
1268
|
H as V,
|
|
1265
1269
|
Se as W,
|
|
@@ -1267,18 +1271,18 @@ export {
|
|
|
1267
1271
|
G as b,
|
|
1268
1272
|
ge as c,
|
|
1269
1273
|
w as d,
|
|
1270
|
-
|
|
1274
|
+
b as e,
|
|
1271
1275
|
ee as f,
|
|
1272
1276
|
Ce as g,
|
|
1273
1277
|
Re as h,
|
|
1274
|
-
|
|
1275
|
-
|
|
1278
|
+
jt as i,
|
|
1279
|
+
Pt as j,
|
|
1276
1280
|
Me as k,
|
|
1277
1281
|
E as l,
|
|
1278
1282
|
q as m,
|
|
1279
1283
|
Te as n,
|
|
1280
1284
|
de as o,
|
|
1281
|
-
|
|
1282
|
-
|
|
1285
|
+
At as p,
|
|
1286
|
+
be as q,
|
|
1283
1287
|
Le as r
|
|
1284
1288
|
};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as t, k as s, g as r, l as o, h as n, m as i, C as d, b as g, D as S, K as p, P as c, q as C, R as m, e as y, S as A, d as T, n as l, T as h, U as P, V, o as u, r as v, W as D, i as E, j as M, p as b } from "./index-
|
|
1
|
+
import { A as t, k as s, g as r, l as o, h as n, m as i, C as d, b as g, D as S, K as p, P as c, q as C, R as m, e as y, S as A, d as T, n as l, T as h, U as P, V, o as u, r as v, W as D, i as E, j as M, p as b } from "./index-DrArdZby.js";
|
|
2
2
|
export {
|
|
3
3
|
t as AgentActivityState,
|
|
4
4
|
s as AgentStatus,
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(q,ue){typeof exports=="object"&&typeof module<"u"?ue(exports):typeof define=="function"&&define.amd?define(["exports"],ue):(q=typeof globalThis<"u"?globalThis:q||self,ue(q.index={}))})(this,function(q){"use strict";var zh=Object.defineProperty;var Wh=(q,ue,ft)=>ue in q?zh(q,ue,{enumerable:!0,configurable:!0,writable:!0,value:ft}):q[ue]=ft;var ln=(q,ue,ft)=>Wh(q,typeof ue!="symbol"?ue+"":ue,ft);class ue extends Error{constructor({kind:t,description:i,error:r}){super(JSON.stringify({kind:t,description:i}));ln(this,"kind");ln(this,"description");ln(this,"error");this.kind=t,this.description=i,this.error=r}}class ft extends ue{constructor(e,t){super({kind:"ChatCreationFailed",description:`Failed to create ${t?"persistent":""} chat, mode: ${e}`})}}class pr extends ue{constructor(e){super({kind:"ChatModeDowngraded",description:`Chat mode downgraded to ${e}`})}}class mt extends ue{constructor(t,i){super({kind:"ValidationError",description:t});ln(this,"key");this.key=i}}class gr extends ue{constructor(e){super({kind:"WSError",description:e})}}var vr=(n=>(n.TRIAL="trial",n.BASIC="basic",n.ENTERPRISE="enterprise",n.LITE="lite",n.ADVANCED="advanced",n))(vr||{}),yr=(n=>(n.TRIAL="deid-trial",n.PRO="deid-pro",n.ENTERPRISE="deid-enterprise",n.LITE="deid-lite",n.ADVANCED="deid-advanced",n.BUILD="deid-api-build",n.LAUNCH="deid-api-launch",n.SCALE="deid-api-scale",n))(yr||{}),br=(n=>(n.Created="created",n.Started="started",n.Done="done",n.Error="error",n.Rejected="rejected",n.Ready="ready",n))(br||{}),kr=(n=>(n.Unrated="Unrated",n.Positive="Positive",n.Negative="Negative",n))(kr||{}),le=(n=>(n.Functional="Functional",n.TextOnly="TextOnly",n.Maintenance="Maintenance",n.Playground="Playground",n.DirectPlayback="DirectPlayback",n.Off="Off",n))(le||{}),pt=(n=>(n.Embed="embed",n.Query="query",n.Partial="partial",n.Answer="answer",n.Complete="done",n))(pt||{}),Tr=(n=>(n.KnowledgeProcessing="knowledge/processing",n.KnowledgeIndexing="knowledge/indexing",n.KnowledgeFailed="knowledge/error",n.KnowledgeDone="knowledge/done",n))(Tr||{}),Sr=(n=>(n.Knowledge="knowledge",n.Document="document",n.Record="record",n))(Sr||{}),Cr=(n=>(n.Pdf="pdf",n.Text="text",n.Html="html",n.Word="word",n.Json="json",n.Markdown="markdown",n.Csv="csv",n.Excel="excel",n.Powerpoint="powerpoint",n.Archive="archive",n.Image="image",n.Audio="audio",n.Video="video",n))(Cr||{}),zn=(n=>(n.Clip="clip",n.Talk="talk",n.Expressive="expressive",n))(zn||{});const Qo=n=>{switch(n){case"clip":return"clip";case"talk":return"talk";default:throw new Error(`Unknown video type: ${n}`)}};var H=(n=>(n.Start="START",n.Stop="STOP",n))(H||{}),gt=(n=>(n.Strong="STRONG",n.Weak="WEAK",n.Unknown="UNKNOWN",n))(gt||{}),je=(n=>(n.Idle="IDLE",n.Talking="TALKING",n))(je||{}),he=(n=>(n.ChatAnswer="chat/answer",n.ChatPartial="chat/partial",n.StreamDone="stream/done",n.StreamStarted="stream/started",n.StreamFailed="stream/error",n.StreamReady="stream/ready",n.StreamCreated="stream/created",n.StreamInterrupt="stream/interrupt",n.StreamVideoCreated="stream-video/started",n.StreamVideoDone="stream-video/done",n.StreamVideoError="stream-video/error",n.StreamVideoRejected="stream-video/rejected",n))(he||{}),Y=(n=>(n.New="new",n.Fail="fail",n.Connected="connected",n.Connecting="connecting",n.Closed="closed",n.Completed="completed",n.Disconnected="disconnected",n))(Y||{}),Oe=(n=>(n.Legacy="legacy",n.Fluent="fluent",n))(Oe||{}),Wn=(n=>(n.Livekit="livekit",n))(Wn||{}),Er=(n=>(n.Amazon="amazon",n.Microsoft="microsoft",n.Afflorithmics="afflorithmics",n.Elevenlabs="elevenlabs",n))(Er||{}),Pr=(n=>(n.Public="public",n.Premium="premium",n.Private="private",n))(Pr||{});const Yo=45*1e3,Xo="X-Playground-Chat",wt="https://api.d-id.com",Zo="wss://notifications.d-id.com",ec="79f81a83a67430be2bc0fd61042b8faa",wr=n=>new Promise(e=>setTimeout(e,n)),Rt=(n=16)=>{const e=new Uint8Array(n);return window.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("").slice(0,13)},tc=n=>[le.TextOnly,le.Playground,le.Maintenance].includes(n),Rr=n=>n&&[le.DirectPlayback,le.Off].includes(n);function nc(n,e){let t;return{promise:new Promise((r,s)=>{t=setTimeout(()=>s(new Error(e)),n)}),clear:()=>clearTimeout(t)}}async function Gn(n,e){const t={limit:(e==null?void 0:e.limit)??3,delayMs:(e==null?void 0:e.delayMs)??0,timeout:(e==null?void 0:e.timeout)??3e4,timeoutErrorMessage:(e==null?void 0:e.timeoutErrorMessage)||"Timeout error",shouldRetryFn:(e==null?void 0:e.shouldRetryFn)??(()=>!0),onRetry:(e==null?void 0:e.onRetry)??(()=>{})};let i;for(let r=1;r<=t.limit;r++)try{if(!t.timeout)return await n();const{promise:s,clear:a}=nc(t.timeout,t.timeoutErrorMessage),o=n().finally(a);return await Promise.race([o,s])}catch(s){if(i=s,!t.shouldRetryFn(s)||r>=t.limit)throw s;await wr(t.delayMs),t.onRetry(s)}throw i}function _r(){let n=window.localStorage.getItem("did_external_key_id");if(!n){let e=Rt();window.localStorage.setItem("did_external_key_id",e),n=e}return n}let ic=Rt();function Ir(n){if(n.type==="bearer")return`Bearer ${n.token}`;if(n.type==="basic")return`Basic ${btoa(`${n.username}:${n.password}`)}`;if(n.type==="key")return`Client-Key ${n.clientKey}.${_r()}_${ic}`;throw new Error(`Unknown auth type: ${n}`)}const rc=n=>Gn(n,{limit:3,delayMs:1e3,timeout:0,shouldRetryFn:e=>e.status===429});function Hn(n,e=wt,t){const i=async(r,s)=>{const{skipErrorHandler:a,...o}=s||{},c=await rc(()=>fetch(e+(r!=null&&r.startsWith("/")?r:`/${r}`),{...o,headers:{...o.headers,Authorization:Ir(n),"Content-Type":"application/json"}}));if(!c.ok){let d=await c.text().catch(()=>`Failed to fetch with status ${c.status}`);const l=new Error(d);throw t&&!a&&t(l,{url:r,options:o,headers:c.headers}),l}return c.json()};return{get(r,s){return i(r,{...s,method:"GET"})},post(r,s,a){return i(r,{...a,body:JSON.stringify(s),method:"POST"})},delete(r,s,a){return i(r,{...a,body:JSON.stringify(s),method:"DELETE"})},patch(r,s,a){return i(r,{...a,body:JSON.stringify(s),method:"PATCH"})}}}function Dr(n,e=wt,t){const i=Hn(n,`${e}/agents`,t);return{create(r,s){return i.post("/",r,s)},getAgents(r,s){return i.get(`/${r?`?tag=${r}`:""}`,s).then(a=>a??[])},getById(r,s){return i.get(`/${r}`,s)},delete(r,s){return i.delete(`/${r}`,void 0,s)},update(r,s,a){return i.patch(`/${r}`,s,a)},newChat(r,s,a){return i.post(`/${r}/chat`,s,a)},chat(r,s,a,o){return i.post(`/${r}/chat/${s}`,a,o)},createRating(r,s,a,o){return i.post(`/${r}/chat/${s}/ratings`,a,o)},updateRating(r,s,a,o,c){return i.patch(`/${r}/chat/${s}/ratings/${a}`,o,c)},deleteRating(r,s,a,o){return i.delete(`/${r}/chat/${s}/ratings/${a}`,o)},getSTTToken(r,s){return i.get(`/${r}/stt-token`,s)}}}const Or=n=>n.type==="clip"&&n.presenter_id.startsWith("v2_")?"clip_v2":n.type;function sc(n){var r,s,a,o;const e=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop",t=()=>{const c=navigator.platform;return c.toLowerCase().includes("win")?"Windows":c.toLowerCase().includes("mac")?"Mac OS X":c.toLowerCase().includes("linux")?"Linux":"Unknown"},i=n.presenter;return{$os:`${t()}`,isMobile:`${e()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:Or(i),agentVoice:{voiceId:(s=(r=n.presenter)==null?void 0:r.voice)==null?void 0:s.voice_id,provider:(o=(a=n.presenter)==null?void 0:a.voice)==null?void 0:o.type}}}function ac(n){var t,i,r,s,a,o;const e=(t=n.llm)==null?void 0:t.prompt_customization;return{agentType:Or(n.presenter),owner_id:n.owner_id??"",promptVersion:(i=n.llm)==null?void 0:i.prompt_version,behavior:{role:e==null?void 0:e.role,personality:e==null?void 0:e.personality,instructions:(r=n.llm)==null?void 0:r.instructions},temperature:(s=n.llm)==null?void 0:s.temperature,knowledgeSource:e==null?void 0:e.knowledge_source,starterQuestionsCount:(o=(a=n.knowledge)==null?void 0:a.starter_message)==null?void 0:o.length,topicsToAvoid:e==null?void 0:e.topics_to_avoid,maxResponseLength:e==null?void 0:e.max_response_length,agentId:n.id,access:n.access,name:n.preview_name,...n.access==="public"?{from:"agent-template"}:{}}}const oc=n=>n.reduce((e,t)=>e+t,0),Mr=n=>oc(n)/n.length;function cc(n,e,t){var c,d,l;const{event:i,...r}=n,{template:s}=(e==null?void 0:e.llm)||{},{language:a}=((c=e==null?void 0:e.presenter)==null?void 0:c.voice)||{};return{...r,llm:{...r.llm,template:s},script:{...r.script,provider:{...(d=r==null?void 0:r.script)==null?void 0:d.provider,language:a}},stitch:(e==null?void 0:e.presenter.type)==="talk"?(l=e==null?void 0:e.presenter)==null?void 0:l.stitch:void 0,...t}}let Jn={};const dc="https://api-js.mixpanel.com/track/?verbose=1&ip=1";function lc(n){const e=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk";return{token:n.token||"testKey",distinct_id:n.distinctId||_r(),agentId:n.agentId,additionalProperties:{id:n.distinctId,...n.mixpanelAdditionalProperties||{}},isEnabled:n.isEnabled??!0,getRandom:Rt,enrich(t){this.additionalProperties={...this.additionalProperties,...t}},async track(t,i){if(!this.isEnabled)return Promise.resolve();const{audioPath:r,...s}=i||{},a={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify([{event:t,properties:{...this.additionalProperties,...s,agentId:this.agentId,source:e,token:this.token,time:Date.now(),$insert_id:this.getRandom(),origin:window.location.href,"Screen Height":window.screen.height||window.innerWidth,"Screen Width":window.screen.width||window.innerHeight,"User Agent":navigator.userAgent}}])})};try{return await fetch(dc,a).then(o=>o.json())}catch(o){return console.error(o)}},linkTrack(t,i,r,s){Jn[t]||(Jn[t]={events:{},resolvedDependencies:[]}),s.includes(r)||s.push(r);const a=Jn[t];if(a.events[r]={props:i},a.resolvedDependencies.push(r),s.every(c=>a.resolvedDependencies.includes(c))){const c=s.reduce((d,l)=>a.events[l]?{...d,...a.events[l].props}:d,{});this.track(t,c),a.resolvedDependencies=a.resolvedDependencies.filter(d=>!s.includes(d)),s.forEach(d=>{delete a.events[d]})}}}}function Ar(){let n=0;return{reset:()=>n=0,update:()=>n=Date.now(),get:(e=!1)=>e?Date.now()-n:n}}const Me=Ar(),$n=Ar();function xr(n){return n===le.Playground?{headers:{[Xo]:"true"}}:{}}async function Lr(n,e,t,i,r=!1,s){try{return!s&&!Rr(i)&&(s=await e.newChat(n.id,{persist:r},xr(i)),t.track("agent-chat",{event:"created",chatId:s.id,mode:i})),{chat:s,chatMode:(s==null?void 0:s.chat_mode)??i}}catch(a){try{const o=JSON.parse(a.message);if((o==null?void 0:o.kind)==="InsufficientCreditsError")throw new Error("InsufficientCreditsError")}catch(o){console.error("Error parsing the error message:",o)}throw new Error("Cannot create new chat")}}function uc(n){return n&&n.length>0?n:[]}function hc(n,e,t){if(!n)throw new Error("Please connect to the agent first");if(!n.interruptAvailable)throw new Error("Interrupt is not enabled for this stream");if(e!==Oe.Fluent)throw new Error("Interrupt only available for Fluent streams");if(!t)throw new Error("No active video to interrupt")}async function fc(n,e){const t={type:he.StreamInterrupt,videoId:e,timestamp:Date.now()};n.sendDataChannelMessage(JSON.stringify(t))}function mc(n){return new Promise((e,t)=>{const{callbacks:i,host:r,auth:s}=n,{onMessage:a=null,onOpen:o=null,onClose:c=null,onError:d=null}=i||{},l=new WebSocket(`${r}?authorization=${Ir(s)}`);l.onmessage=a,l.onclose=c,l.onerror=u=>{console.error(u),d==null||d("Websocket failed to connect",u),t(u)},l.onopen=u=>{o==null||o(u),e(l)}})}async function pc(n){const{retries:e=1}=n;let t=null;for(let i=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;i++)try{t=await mc(n)}catch(r){if(i===e)throw r;await wr(i*500)}return t}async function gc(n,e,t){const i=t!=null&&t.onMessage?[t.onMessage]:[],r=await pc({auth:n,host:e,callbacks:{onError:s=>{var a;return(a=t.onError)==null?void 0:a.call(t,new gr(s))},onMessage(s){const a=JSON.parse(s.data);i.forEach(o=>o(a.event,a))}}});return{socket:r,disconnect:()=>r.close(),subscribeToEvents:s=>i.push(s)}}function vc(n){if(n.answer!==void 0)return n.answer;let e=0,t="";for(;e in n;)t+=n[e++];return t}function yc(n,e,t,i,r){const s=i.messages[i.messages.length-1];if(!(n===pt.Partial||n===pt.Answer)||(s==null?void 0:s.role)!=="assistant")return;const{content:a,sequence:o}=e;n===pt.Partial?t[o]=a:t.answer=a;const c=vc(t);(s.content!==c||n===pt.Answer)&&(s.content=c,r==null||r([...i.messages],n))}function bc(n,e,t,i,r){let s={};return{clearQueue:()=>s={},onMessage:(a,o)=>{var c,d;if("content"in o)yc(a,o,s,e,t.callbacks.onNewMessage),a===pt.Answer&&n.track("agent-message-received",{messages:e.messages.length,mode:e.chatMode});else{const l=he,u=[l.StreamVideoDone,l.StreamVideoError,l.StreamVideoRejected],h=[l.StreamFailed,l.StreamVideoError,l.StreamVideoRejected],m=cc(o,i,{mode:e.chatMode});if(a=a,a===l.StreamVideoCreated)n.linkTrack("agent-video",m,l.StreamVideoCreated,["start"]);else if(u.includes(a)){const y=a.split("/")[1];h.includes(a)?n.track("agent-video",{...m,event:y}):n.linkTrack("agent-video",{...m,event:y},a,["done"])}h.includes(a)&&((d=(c=t.callbacks).onError)==null||d.call(c,new Error(`Stream failed with event ${a}`),{data:o})),o.event===l.StreamDone&&r()}}}}function kc(n,e,t,i){const r=Hn(n,`${e}/agents/${t}`,i);return{createStream(s){return r.post("/streams",s)},startConnection(s,a,o){return r.post(`/streams/${s}/sdp`,{session_id:o,answer:a})},addIceCandidate(s,a,o){return r.post(`/streams/${s}/ice`,{session_id:o,...a})},sendStreamRequest(s,a,o){return r.post(`/streams/${s}`,{session_id:a,...o})},close(s,a){return r.delete(`/streams/${s}`,{session_id:a})}}}const Nr=(n,e)=>(t,i)=>n&&console.log(`[${e}] ${t}`,i??"");function Tc(n,e,t){const i=(e.timestamp-n.timestamp)/1e3;return{duration:i,bytesReceived:e.bytesReceived-n.bytesReceived,bitrate:Math.round((e.bytesReceived-n.bytesReceived)*8/i),packetsReceived:e.packetsReceived-n.packetsReceived,packetsLost:e.packetsLost-n.packetsLost,framesDropped:e.framesDropped-n.framesDropped,framesDecoded:e.framesDecoded-n.framesDecoded,jitter:e.jitter,avgJitterDelayInInterval:(e.jitterBufferDelay-n.jitterBufferDelay)/(e.jitterBufferEmittedCount-n.jitterBufferEmittedCount),jitterBufferEmittedCount:e.jitterBufferEmittedCount-n.jitterBufferEmittedCount,jitterBufferDelay:(e.jitterBufferDelay-n.jitterBufferDelay)/i,framesPerSecond:e.framesPerSecond,freezeCount:e.freezeCount-n.freezeCount,freezeDuration:e.freezeDuration-n.freezeDuration,lowFpsCount:t}}function Sc(n){return n.filter(e=>e.freezeCount>0||e.framesPerSecond<21||e.framesDropped>0||e.packetsLost>0).map(e=>{const{timestamp:t,...i}=e,r=[];return e.freezeCount>0&&r.push("freeze"),e.framesPerSecond<21&&r.push("low fps"),e.framesDropped>0&&r.push("frames dropped"),e.packetsLost>0&&r.push("packet loss"),{...i,causes:r}})}function Cc(n){let e="",t=0;for(const i of n.values())if(i&&i.type==="codec"&&i.mimeType.startsWith("video")&&(e=i.mimeType.split("/")[1]),i&&i.type==="candidate-pair"&&(t=i.currentRoundTripTime),i&&i.type==="inbound-rtp"&&i.kind==="video")return{codec:e,rtt:t,timestamp:i.timestamp,bytesReceived:i.bytesReceived,packetsReceived:i.packetsReceived,packetsLost:i.packetsLost,framesDropped:i.framesDropped,framesDecoded:i.framesDecoded,jitter:i.jitter,jitterBufferDelay:i.jitterBufferDelay,jitterBufferEmittedCount:i.jitterBufferEmittedCount,avgJitterDelayInInterval:i.jitterBufferDelay/i.jitterBufferEmittedCount,frameWidth:i.frameWidth,frameHeight:i.frameHeight,framesPerSecond:i.framesPerSecond,freezeCount:i.freezeCount,freezeDuration:i.totalFreezesDuration};return{}}function Ec(n,e,t){const i=n.map((c,d)=>d===0?t?{timestamp:c.timestamp,duration:0,rtt:c.rtt,bytesReceived:c.bytesReceived-t.bytesReceived,bitrate:(c.bytesReceived-t.bytesReceived)*8/(e/1e3),packetsReceived:c.packetsReceived-t.packetsReceived,packetsLost:c.packetsLost-t.packetsLost,framesDropped:c.framesDropped-t.framesDropped,framesDecoded:c.framesDecoded-t.framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay-t.jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount-t.jitterBufferEmittedCount,avgJitterDelayInInterval:(c.jitterBufferDelay-t.jitterBufferDelay)/(c.jitterBufferEmittedCount-t.jitterBufferEmittedCount),framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount-t.freezeCount,freezeDuration:c.freezeDuration-t.freezeDuration}:{timestamp:c.timestamp,rtt:c.rtt,duration:0,bytesReceived:c.bytesReceived,bitrate:c.bytesReceived*8/(e/1e3),packetsReceived:c.packetsReceived,packetsLost:c.packetsLost,framesDropped:c.framesDropped,framesDecoded:c.framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount,avgJitterDelayInInterval:c.jitterBufferDelay/c.jitterBufferEmittedCount,framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount,freezeDuration:c.freezeDuration}:{timestamp:c.timestamp,duration:e*d/1e3,rtt:c.rtt,bytesReceived:c.bytesReceived-n[d-1].bytesReceived,bitrate:(c.bytesReceived-n[d-1].bytesReceived)*8/(e/1e3),packetsReceived:c.packetsReceived-n[d-1].packetsReceived,packetsLost:c.packetsLost-n[d-1].packetsLost,framesDropped:c.framesDropped-n[d-1].framesDropped,framesDecoded:c.framesDecoded-n[d-1].framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay-n[d-1].jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount,avgJitterDelayInInterval:(c.jitterBufferDelay-n[d-1].jitterBufferDelay)/(c.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount),framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount-n[d-1].freezeCount,freezeDuration:c.freezeDuration-n[d-1].freezeDuration}),r=Sc(i),s=r.reduce((c,d)=>c+(d.causes.includes("low fps")?1:0),0),a=i.filter(c=>!!c.avgJitterDelayInInterval).map(c=>c.avgJitterDelayInInterval),o=i.filter(c=>!!c.rtt).map(c=>c.rtt);return{webRTCStats:{anomalies:r,minRtt:Math.min(...o),avgRtt:Mr(o),maxRtt:Math.max(...o),aggregateReport:Tc(n[0],n[n.length-1],s),minJitterDelayInInterval:Math.min(...a),maxJitterDelayInInterval:Math.max(...a),avgJitterDelayInInterval:Mr(a)},codec:n[0].codec,resolution:`${n[0].frameWidth}x${n[0].frameHeight}`}}const Qn=100,Pc=Math.max(Math.ceil(400/Qn),1),wc=.25,Rc=.28;function _c(){let n=0,e,t,i=0;return r=>{for(const s of r.values())if(s&&s.type==="inbound-rtp"&&s.kind==="video"){const a=s.jitterBufferDelay,o=s.jitterBufferEmittedCount;if(t&&o>t){const l=a-e,u=o-t;i=l/u}e=a,t=o;const c=s.framesDecoded,d=c-n>0;return n=c,{isReceiving:d,avgJitterDelayInInterval:i,freezeCount:s.freezeCount}}return{isReceiving:!1,avgJitterDelayInInterval:i}}}function Ic(n,e,t,i,r,s=!1){let a=[],o,c=0,d=!1,l=gt.Unknown,u=gt.Unknown,h=0,m=0;const y=_c();return setInterval(async()=>{const g=await n.getStats(),{isReceiving:P,avgJitterDelayInInterval:S,freezeCount:w}=y(g),D=Cc(g);if(P)c=0,h=w-m,u=S<wc?gt.Strong:S>Rc&&h>1?gt.Weak:l,u!==l&&(r==null||r(u),l=u,m+=h,h=0),d||(i==null||i(H.Start),o=a[a.length-1],a=[],d=!0),a.push(D);else if(d&&(c++,c>=Pc)){const p=Ec(a,Qn,o);i==null||i(H.Stop,p),e()||t(),m=w,d=!1}},Qn)}const Dc=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function Ur(n){switch(n){case"connected":return Y.Connected;case"checking":return Y.Connecting;case"failed":return Y.Fail;case"new":return Y.New;case"closed":return Y.Closed;case"disconnected":return Y.Disconnected;case"completed":return Y.Completed;default:return Y.New}}const Oc=n=>e=>{const[t,i=""]=e.split(/:(.+)/);try{const r=JSON.parse(i);return n("parsed data channel message",{subject:t,data:r}),{subject:t,data:r}}catch(r){return n("Failed to parse data channel message, returning data as string",{subject:t,rawData:i,error:r}),{subject:t,data:i}}};function Mc({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:i}){n===H.Start&&e===H.Start?t==null||t(H.Start):n===H.Stop&&e===H.Stop&&(t==null||t(H.Stop,i))}function Ac({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:r}){n===H.Start?t==null||t(H.Start):n===H.Stop&&(t==null||t(H.Stop,r)),e===H.Start?i==null||i(je.Talking):e===H.Stop&&(i==null||i(je.Idle))}function Fr({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,streamType:r,report:s}){r===Oe.Legacy?Mc({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:s}):r===Oe.Fluent&&Ac({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:s})}async function xc(n,e,{debug:t=!1,callbacks:i,auth:r,baseURL:s=wt,analytics:a}){var st;const o=Nr(t,"WebRTCStreamingManager"),c=Oc(o);let d=!1,l=!1,u=H.Stop,h=H.Stop;const{startConnection:m,sendStreamRequest:y,close:g,createStream:P,addIceCandidate:S}=kc(r,s,n,i.onError),{id:w,offer:D,ice_servers:p,session_id:v,fluent:T,interrupt_enabled:x,triggers_enabled:L}=await P(e);(st=i.onStreamCreated)==null||st.call(i,{stream_id:w,session_id:v,agent_id:n});const k=new Dc({iceServers:p}),I=k.createDataChannel("JanusDataChannel");if(!v)throw new Error("Could not create session_id");const O=T?Oe.Fluent:Oe.Legacy;a.enrich({"stream-type":O});const N=e.stream_warmup&&!T,U=()=>d,G=()=>{var j;d=!0,l&&((j=i.onConnectionStateChange)==null||j.call(i,Y.Connected))},Q=Ic(k,U,G,(j,B)=>Fr({statsSignal:h=j,dataChannelSignal:O===Oe.Legacy?u:void 0,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,report:B,streamType:O}),j=>{var B;return(B=i.onConnectivityStateChange)==null?void 0:B.call(i,j)},N);k.onicecandidate=j=>{var B;o("peerConnection.onicecandidate",j);try{j.candidate&&j.candidate.sdpMid&&j.candidate.sdpMLineIndex!==null?S(w,{candidate:j.candidate.candidate,sdpMid:j.candidate.sdpMid,sdpMLineIndex:j.candidate.sdpMLineIndex},v):S(w,{candidate:null},v)}catch(me){(B=i.onError)==null||B.call(i,me,{streamId:w})}},I.onopen=()=>{l=!0,(!N||d)&&G()};const fe=j=>{var B;(B=i.onVideoIdChange)==null||B.call(i,j)};function re(j,B){if(j===he.StreamStarted&&typeof B=="object"&&"metadata"in B){const me=B.metadata;fe(me.videoId)}j===he.StreamDone&&fe(null),u=j===he.StreamStarted?H.Start:H.Stop,Fr({statsSignal:O===Oe.Legacy?h:void 0,dataChannelSignal:u,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,streamType:O})}function Ce(j,B){const me=typeof B=="string"?B:B==null?void 0:B.metadata;me&&a.enrich({streamMetadata:me}),a.track("agent-chat",{event:"ready"})}const Ee={[he.StreamStarted]:re,[he.StreamDone]:re,[he.StreamReady]:Ce};I.onmessage=j=>{var ht;const{subject:B,data:me}=c(j.data);(ht=Ee[B])==null||ht.call(Ee,B,me)},k.oniceconnectionstatechange=()=>{var B;o("peerConnection.oniceconnectionstatechange => "+k.iceConnectionState);const j=Ur(k.iceConnectionState);j!==Y.Connected&&((B=i.onConnectionStateChange)==null||B.call(i,j))},k.ontrack=j=>{var B;o("peerConnection.ontrack",j),(B=i.onSrcObjectReady)==null||B.call(i,j.streams[0])},await k.setRemoteDescription(D),o("set remote description OK");const rt=await k.createAnswer();return o("create answer OK"),await k.setLocalDescription(rt),o("set local description OK"),await m(w,rt,v),o("start connection OK"),{speak(j){return y(w,v,j)},async disconnect(){var j;if(w){const B=Ur(k.iceConnectionState);if(k){if(B===Y.New){clearInterval(Q);return}k.close(),k.oniceconnectionstatechange=null,k.onnegotiationneeded=null,k.onicecandidate=null,k.ontrack=null}try{B===Y.Connected&&await g(w,v).catch(me=>{})}catch(me){o("Error on close stream connection",me)}(j=i.onAgentActivityStateChange)==null||j.call(i,je.Idle),clearInterval(Q)}},sendDataChannelMessage(j){var B,me;if(!d||I.readyState!=="open"){o("Data channel is not ready for sending messages"),(B=i.onError)==null||B.call(i,new Error("Data channel is not ready for sending messages"),{streamId:w});return}try{I.send(j)}catch(ht){o("Error sending data channel message",ht),(me=i.onError)==null||me.call(i,ht,{streamId:w})}},sessionId:v,streamId:w,streamType:O,interruptAvailable:x??!1,triggersAvailable:L??!1}}const Lc=n=>n.presenter.type===zn.Expressive;async function Nc(n,e,t){const i=n.id;if(Lc(n)){const{createLiveKitStreamingManager:r}=await Promise.resolve().then(()=>$c);return r(i,e,t)}else return xc(i,e,t)}function Uc(n){const{streamOptions:e}=n??{};return{output_resolution:e==null?void 0:e.outputResolution,session_timeout:e==null?void 0:e.sessionTimeout,stream_warmup:e==null?void 0:e.streamWarmup,compatibility_mode:e==null?void 0:e.compatibilityMode,fluent:e==null?void 0:e.fluent}}function Fc(n,e,t,i,r){r===Oe.Fluent?jc(n,e,t,i,r):Vc(n,e,t,i,r)}function jc(n,e,t,i,r){n===H.Start?i.track("stream-session",{event:"start","stream-type":r}):n===H.Stop&&i.track("stream-session",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t})}function Bc(n,e,t,i){Me.get()<=0||(n===H.Start?t.linkTrack("agent-video",{event:"start",latency:Me.get(!0),"stream-type":i},"start",[he.StreamVideoCreated]):n===H.Stop&&t.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":i},"done",[he.StreamVideoDone]))}function Vc(n,e,t,i,r){Me.get()<=0||(n===H.Start?i.linkTrack("agent-video",{event:"start",latency:Me.get(!0),"stream-type":r},"start",[he.StreamVideoCreated]):n===H.Stop&&i.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t},"done",[he.StreamVideoDone]))}function qc(n,e,t){return Me.reset(),new Promise(async(i,r)=>{try{let s;s=await Nc(n,Uc(e),{...e,analytics:t,callbacks:{...e.callbacks,onConnectionStateChange:a=>{var o,c;(c=(o=e.callbacks).onConnectionStateChange)==null||c.call(o,a),a===Y.Connected&&i(s)},onVideoStateChange:(a,o)=>{var c,d;(d=(c=e.callbacks).onVideoStateChange)==null||d.call(c,a),Fc(a,n,o,t,s.streamType)},onAgentActivityStateChange:a=>{var o,c;(c=(o=e.callbacks).onAgentActivityStateChange)==null||c.call(o,a),a===je.Talking?$n.update():$n.reset(),Bc(a===je.Talking?H.Start:H.Stop,n,t,s.streamType)}}})}catch(s){r(s)}})}async function Kc(n,e,t,i,r){var u,h,m,y;const s=Lr(n,t,i,e.mode,e.persistentChat,r),a=qc(n,e,i),[o,c]=await Promise.all([s,a]),{chat:d,chatMode:l}=o;return l&&l!==e.mode&&(e.mode=l,(h=(u=e.callbacks).onModeChange)==null||h.call(u,l),l!==le.Functional)?((y=(m=e.callbacks).onError)==null||y.call(m,new pr(l)),c==null||c.disconnect(),{chat:d}):{chat:d,streamingManager:c}}async function zc(n,e){var S,w,D;let t=!0,i=null;const r=e.mixpanelKey||ec,s=e.wsURL||Zo,a=e.baseURL||wt,o={messages:[],chatMode:e.mode||le.Functional},c=lc({token:r,agentId:n,isEnabled:e.enableAnalitics,distinctId:e.distinctId,mixpanelAdditionalProperties:e.mixpanelAdditionalProperties});c.track("agent-sdk",{event:"init"});const d=Dr(e.auth,a,e.callbacks.onError),l=await d.getById(n);c.enrich(ac(l));const{onMessage:u,clearQueue:h}=bc(c,o,e,l,()=>{var p;return(p=o.socketManager)==null?void 0:p.disconnect()});o.messages=uc(e.initialMessages),(w=(S=e.callbacks).onNewMessage)==null||w.call(S,[...o.messages],"answer");const m=p=>{i=p};c.track("agent-sdk",{event:"loaded",...sc(l)});async function y(p){var I,O,N,U,G,Q,fe;(O=(I=e.callbacks).onConnectionStateChange)==null||O.call(I,Y.Connecting),Me.reset(),p&&!t&&(delete o.chat,(U=(N=e.callbacks).onNewMessage)==null||U.call(N,[...o.messages],"answer"));const v=e.mode===le.DirectPlayback?Promise.resolve(void 0):gc(e.auth,s,{onMessage:u,onError:e.callbacks.onError}),T=Gn(()=>Kc(l,{...e,callbacks:{...e.callbacks,onVideoIdChange:m}},d,c,o.chat),{limit:3,timeout:Yo,timeoutErrorMessage:"Timeout initializing the stream",shouldRetryFn:re=>(re==null?void 0:re.message)!=="Could not connect"&&re.status!==429,delayMs:1e3}).catch(re=>{var Ce,Ee;throw P(le.Maintenance),(Ee=(Ce=e.callbacks).onConnectionStateChange)==null||Ee.call(Ce,Y.Fail),re}),[x,{streamingManager:L,chat:k}]=await Promise.all([v,T]);k&&k.id!==((G=o.chat)==null?void 0:G.id)&&((fe=(Q=e.callbacks).onNewChat)==null||fe.call(Q,k.id)),o.streamingManager=L,o.socketManager=x,o.chat=k,t=!1,c.enrich({chatId:k==null?void 0:k.id,streamId:L==null?void 0:L.streamId,mode:o.chatMode}),P((k==null?void 0:k.chat_mode)??e.mode??le.Functional)}async function g(){var p,v,T,x;(p=o.socketManager)==null||p.disconnect(),await((v=o.streamingManager)==null?void 0:v.disconnect()),delete o.streamingManager,delete o.socketManager,(x=(T=e.callbacks).onConnectionStateChange)==null||x.call(T,Y.Disconnected)}async function P(p){var v,T;p!==o.chatMode&&(c.track("agent-mode-change",{mode:p}),o.chatMode=p,o.chatMode!==le.Functional&&await g(),(T=(v=e.callbacks).onModeChange)==null||T.call(v,p))}return{agent:l,getStreamType:()=>{var p;return(p=o.streamingManager)==null?void 0:p.streamType},getIsInterruptAvailable:()=>{var p;return((p=o.streamingManager)==null?void 0:p.interruptAvailable)??!1},getIsTriggersAvailable:()=>{var p;return((p=o.streamingManager)==null?void 0:p.triggersAvailable)??!1},starterMessages:((D=l.knowledge)==null?void 0:D.starter_message)||[],getSTTToken:()=>d.getSTTToken(l.id),changeMode:P,enrichAnalytics:c.enrich,async connect(){await y(!0),c.track("agent-chat",{event:"connect",mode:o.chatMode})},async reconnect(){await g(),await y(!1),c.track("agent-chat",{event:"reconnect",mode:o.chatMode})},async disconnect(){await g(),c.track("agent-chat",{event:"disconnect",mode:o.chatMode})},async chat(p){var L,k,I,O,N;const v=()=>{if(Rr(e.mode))throw new mt(`${e.mode} is enabled, chat is disabled`);if(p.length>=800)throw new mt("Message cannot be more than 800 characters");if(p.length===0)throw new mt("Message cannot be empty");if(o.chatMode===le.Maintenance)throw new mt("Chat is in maintenance mode");if(![le.TextOnly,le.Playground].includes(o.chatMode)){if(!o.streamingManager)throw new mt("Streaming manager is not initialized");if(!o.chat)throw new mt("Chat is not initialized")}},T=async()=>{var U,G;if(!o.chat){const Q=await Lr(l,d,c,o.chatMode,e.persistentChat);if(!Q.chat)throw new ft(o.chatMode,!!e.persistentChat);o.chat=Q.chat,(G=(U=e.callbacks).onNewChat)==null||G.call(U,o.chat.id)}return o.chat.id},x=async(U,G)=>Gn(()=>{var Q,fe;return d.chat(l.id,G,{chatMode:o.chatMode,streamId:(Q=o.streamingManager)==null?void 0:Q.streamId,sessionId:(fe=o.streamingManager)==null?void 0:fe.sessionId,messages:U.map(({matches:re,...Ce})=>Ce)},{...xr(o.chatMode),skipErrorHandler:!0})},{limit:2,shouldRetryFn:Q=>{var Ce,Ee,rt,st;const fe=(Ce=Q==null?void 0:Q.message)==null?void 0:Ce.includes("missing or invalid session_id");return!((Ee=Q==null?void 0:Q.message)==null?void 0:Ee.includes("Stream Error"))&&!fe?((st=(rt=e.callbacks).onError)==null||st.call(rt,Q),!1):!0},onRetry:async()=>{await g(),await y(!1)}});try{h(),v(),o.messages.push({id:Rt(),role:"user",content:p,created_at:new Date(Me.update()).toISOString()}),(k=(L=e.callbacks).onNewMessage)==null||k.call(L,[...o.messages],"user");const U=await T(),G=await x([...o.messages],U);return o.messages.push({id:Rt(),role:"assistant",content:G.result||"",created_at:new Date().toISOString(),context:G.context,matches:G.matches}),c.track("agent-message-send",{event:"success",messages:o.messages.length+1}),G.result&&((O=(I=e.callbacks).onNewMessage)==null||O.call(I,[...o.messages],"answer"),c.track("agent-message-received",{latency:Me.get(!0),messages:o.messages.length})),G}catch(U){throw((N=o.messages[o.messages.length-1])==null?void 0:N.role)==="assistant"&&o.messages.pop(),c.track("agent-message-send",{event:"error",messages:o.messages.length}),U}},rate(p,v,T){var k,I,O,N;const x=o.messages.find(U=>U.id===p);if(o.chat){if(!x)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const L=((k=x.matches)==null?void 0:k.map(U=>[U.document_id,U.id]))??[];return c.track("agent-rate",{event:T?"update":"create",thumb:v===1?"up":"down",knowledge_id:((I=l.knowledge)==null?void 0:I.id)??"",matches:L,score:v}),T?d.updateRating(l.id,o.chat.id,T,{knowledge_id:((O=l.knowledge)==null?void 0:O.id)??"",message_id:p,matches:L,score:v}):d.createRating(l.id,o.chat.id,{knowledge_id:((N=l.knowledge)==null?void 0:N.id)??"",message_id:p,matches:L,score:v})},deleteRate(p){if(!o.chat)throw new Error("Chat is not initialized");return c.track("agent-rate-delete",{type:"text"}),d.deleteRating(l.id,o.chat.id,p)},async speak(p){var L,k,I;function v(){if(typeof p=="string"){if(!l.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:l.presenter.voice,input:p,ssml:!1}}if(p.type==="text"&&!p.provider){if(!l.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:l.presenter.voice,input:p.input,ssml:p.ssml}}return p}const T=v();if(c.track("agent-speak",T),Me.update(),o.messages&&T.type==="text"&&(o.messages.push({id:Rt(),role:"assistant",content:T.input,created_at:new Date(Me.get(!0)).toISOString()}),(k=(L=e.callbacks).onNewMessage)==null||k.call(L,[...o.messages],"answer")),tc(o.chatMode))return{duration:0,video_id:"",status:"success"};if(!o.streamingManager)throw new Error("Please connect to the agent first");return o.streamingManager.speak({script:T,metadata:{chat_id:(I=o.chat)==null?void 0:I.id,agent_id:l.id}})},async interrupt({type:p}){var T,x,L;hc(o.streamingManager,(T=o.streamingManager)==null?void 0:T.streamType,i);const v=o.messages[o.messages.length-1];c.track("agent-video-interrupt",{type:p||"click",video_duration_to_interrupt:$n.get(!0),message_duration_to_interrupt:Me.get(!0)}),v.interrupted=!0,(L=(x=e.callbacks).onNewMessage)==null||L.call(x,[...o.messages],"answer"),fc(o.streamingManager,i)}}}function Wc(n,e,t){const{getById:i}=Dr(e,t||wt);return i(n)}function Gc(n,e,t,i){const r=Hn(n,`${e}/v2/agents/${t}`,i);return{async createStream(s){return r.post("/streams",s)}}}async function Hc(){try{return await Promise.resolve().then(()=>Kh)}catch{throw new Error("LiveKit client is required for this streaming manager. Please install it using: npm install livekit-client")}}async function Jc(n,e,t){var T,x,L;const i=Nr(t.debug||!1,"LiveKitStreamingManager"),{Room:r,RoomEvent:s,ConnectionState:a,RemoteParticipant:o,RemoteTrack:c}=await Hc(),{callbacks:d,auth:l,baseURL:u,analytics:h}=t;let m=null,y=!1,g=null,P=null;const S=Oe.Fluent;m=new r({adaptiveStream:!0,dynacast:!0}),m.on(s.ConnectionStateChanged,k=>{var I,O,N,U,G;switch(i("Connection state changed:",k),k){case a.Connecting:(I=d.onConnectionStateChange)==null||I.call(d,Y.Connecting);break;case a.Connected:i("LiveKit room connected successfully"),y=!0,(O=d.onConnectionStateChange)==null||O.call(d,Y.Connected);break;case a.Disconnected:i("LiveKit room disconnected"),y=!1,(N=d.onConnectionStateChange)==null||N.call(d,Y.Disconnected);break;case a.Reconnecting:i("LiveKit room reconnecting..."),(U=d.onConnectionStateChange)==null||U.call(d,Y.Connecting);break;case a.SignalReconnecting:i("LiveKit room signal reconnecting..."),(G=d.onConnectionStateChange)==null||G.call(d,Y.Connecting);break}}),m.on(s.ConnectionQualityChanged,(k,I)=>{var O;I!=null&&I.isLocal&&k==="poor"&&(i("Connection quality is poor"),(O=d.onConnectivityStateChange)==null||O.call(d,gt.Weak))}),m.on(s.ParticipantConnected,k=>{i("Participant connected:",k.identity)}),m.on(s.TrackSubscribed,(k,I,O)=>{var N,U;i(`Track subscribed: ${k.kind} from ${O.identity}`),P?P.addTrack(k.mediaStreamTrack):P=new MediaStream([k.mediaStreamTrack]),(N=d.onSrcObjectReady)==null||N.call(d,P),k.kind==="video"&&((U=d.onVideoStateChange)==null||U.call(d,H.Start))}),m.on(s.TrackUnsubscribed,(k,I,O)=>{var N;i(`Track unsubscribed: ${k.kind} from ${O.identity}`),k.kind==="video"&&((N=d.onVideoStateChange)==null||N.call(d,H.Stop))}),m.on(s.DataReceived,(k,I)=>{var N,U,G,Q,fe;const O=new TextDecoder().decode(k);i("Data received:",O);try{const re=JSON.parse(O);re.subject===he.StreamStarted&&((N=re.metadata)!=null&&N.videoId)?(g=re.metadata.videoId,(U=d.onVideoIdChange)==null||U.call(d,g),(G=d.onAgentActivityStateChange)==null||G.call(d,je.Talking)):re.subject===he.StreamDone&&(g=null,(Q=d.onVideoIdChange)==null||Q.call(d,g),(fe=d.onAgentActivityStateChange)==null||fe.call(d,je.Idle))}catch(re){i("Failed to parse data channel message:",re)}}),(T=d.onConnectionStateChange)==null||T.call(d,Y.New);const w=Gc(l,u||wt,n,d.onError);let D,p;try{const k=await w.createStream({transport:Wn.Livekit}),{agent_id:I,session_id:O,session_token:N,session_url:U}=k;D=I,p=O,await m.connect(U,N),i("LiveKit room joined successfully")}catch(k){throw i("Failed to connect to LiveKit room:",k),(x=d.onConnectionStateChange)==null||x.call(d,Y.Fail),(L=d.onError)==null||L.call(d,k,{streamId:""}),k}h.enrich({"stream-type":S});async function v(k){var I,O;if(!y||!m){i("Room is not connected for sending messages"),(I=d.onError)==null||I.call(d,new Error("Room is not connected for sending messages"),{streamId:D});return}try{await m.localParticipant.publishData(new TextEncoder().encode(k),{reliable:!0})}catch(N){i("Error sending data channel message",N),(O=d.onError)==null||O.call(d,N,{streamId:D})}}return{speak(k){const I=JSON.stringify({type:"speak",payload:k});return v(I)},async disconnect(){var k,I;m&&(await m.disconnect(),m=null),P&&(P.getTracks().forEach(O=>O.stop()),P=null),y=!1,(k=d.onConnectionStateChange)==null||k.call(d,Y.Completed),(I=d.onAgentActivityStateChange)==null||I.call(d,je.Idle)},sendDataChannelMessage:v,sessionId:p,streamId:D,streamType:S,interruptAvailable:!0,triggersAvailable:!1}}const $c=Object.freeze(Object.defineProperty({__proto__:null,createLiveKitStreamingManager:Jc},Symbol.toStringTag,{value:"Module"}));function Qc(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var Yc=Object.defineProperty,Xc=(n,e,t)=>e in n?Yc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,jr=(n,e,t)=>Xc(n,typeof e!="symbol"?e+"":e,t);class pe{constructor(){jr(this,"_locking"),jr(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function te(n,e){if(!n)throw new Error(e)}const Zc=34028234663852886e22,ed=-34028234663852886e22,td=4294967295,nd=2147483647,id=-2147483648;function un(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>nd||n<id)throw new Error("invalid int 32: "+n)}function Yn(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>td||n<0)throw new Error("invalid uint 32: "+n)}function Br(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>Zc||n<ed))throw new Error("invalid float 32: "+n)}const Vr=Symbol("@bufbuild/protobuf/enum-type");function rd(n){const e=n[Vr];return te(e,"missing enum type on enum object"),e}function qr(n,e,t,i){n[Vr]=Kr(e,t.map(r=>({no:r.no,name:r.name,localName:n[r.no]})))}function Kr(n,e,t){const i=Object.create(null),r=Object.create(null),s=[];for(const a of e){const o=zr(a);s.push(o),i[a.name]=o,r[a.no]=o}return{typeName:n,values:s,findName(a){return i[a]},findNumber(a){return r[a]}}}function sd(n,e,t){const i={};for(const r of e){const s=zr(r);i[s.localName]=s.no,i[s.no]=s.localName}return qr(i,n,e),i}function zr(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class Xn{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(t);return r.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function ad(n,e,t,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),a={[s]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[s];return Object.setPrototypeOf(a.prototype,new Xn),Object.assign(a,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return n.util.equals(a,o,c)}}),a}function od(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,!(r&128))return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,!(t&128))return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,!(r&128))return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Zn(n,e,t){for(let s=0;s<28;s=s+7){const a=n>>>s,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const i=n>>>28&15|(e&7)<<4,r=!!(e>>3);if(t.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const a=e>>>s,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const hn=4294967296;function Wr(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,r=0;function s(a,o){const c=Number(n.slice(a,o));r*=t,i=i*t+c,i>=hn&&(r=r+(i/hn|0),i=i%hn)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Hr(i,r):ei(i,r)}function cd(n,e){let t=ei(n,e);const i=t.hi&2147483648;i&&(t=Hr(t.lo,t.hi));const r=Gr(t.lo,t.hi);return i?"-"+r:r}function Gr(n,e){if({lo:n,hi:e}=dd(n,e),e<=2097151)return String(hn*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,r=e>>16&65535;let s=t+i*6777216+r*6710656,a=i+r*8147497,o=r*2;const c=1e7;return s>=c&&(a+=Math.floor(s/c),s%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+Jr(a)+Jr(s)}function dd(n,e){return{lo:n>>>0,hi:e>>>0}}function ei(n,e){return{lo:n|0,hi:e|0}}function Hr(n,e){return e=~e,n?n=~n+1:e+=1,ei(n,e)}const Jr=n=>{const e=String(n);return"0000000".slice(e.length)+e};function $r(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function ld(){let n=this.buf[this.pos++],e=n&127;if(!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,!(n&128))return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;n&128&&t<10;t++)n=this.buf[this.pos++];if(n&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function ud(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>s||d<r)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>o||d<a)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=r=>te(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>te(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),Wr(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),Wr(r)},dec(r,s){return cd(r,s)},uDec(r,s){return Gr(r,s)}}}const Z=ud();var E;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(E||(E={}));var at;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(at||(at={}));function ot(n,e,t){if(e===t)return!0;if(n==E.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==t}return!1}function _t(n,e){switch(n){case E.BOOL:return!1;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==0?Z.zero:"0";case E.DOUBLE:case E.FLOAT:return 0;case E.BYTES:return new Uint8Array(0);case E.STRING:return"";default:return 0}}function Qr(n,e){switch(n){case E.BOOL:return e===!1;case E.STRING:return e==="";case E.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var ie;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ie||(ie={}));class hd{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Yn(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return un(e),$r(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Br(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Yn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){un(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return un(e),e=(e<<1^e>>31)>>>0,$r(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=Z.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=Z.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=Z.enc(e);return Zn(t.lo,t.hi,this.buf),this}sint64(e){let t=Z.enc(e),i=t.hi>>31,r=t.lo<<1^i,s=(t.hi<<1|t.lo>>>31)^i;return Zn(r,s,this.buf),this}uint64(e){let t=Z.uEnc(e);return Zn(t.lo,t.hi,this.buf),this}}class fd{constructor(e,t){this.varint64=od,this.uint32=ld,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ie.Varint:for(;this.buf[this.pos++]&128;);break;case ie.Bit64:this.pos+=4;case ie.Bit32:this.pos+=4;break;case ie.LengthDelimited:let r=this.uint32();this.pos+=r;break;case ie.StartGroup:for(;;){const[s,a]=this.tag();if(a===ie.EndGroup){if(t!==void 0&&s!==t)throw new Error("invalid end group tag");break}this.skip(a,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return Z.dec(...this.varint64())}uint64(){return Z.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,Z.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Z.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Z.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function md(n,e,t,i){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=n.util.newFieldList([s]).list()[0]}return r},runtime:n}}function Yr(n){const e=n.field.localName,t=Object.create(null);return t[e]=pd(n),[t,()=>t[e]]}function pd(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return _t(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function gd(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Je="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),fn=[];for(let n=0;n<Je.length;n++)fn[Je[n].charCodeAt(0)]=n;fn[45]=Je.indexOf("+"),fn[95]=Je.indexOf("/");const Xr={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,r=0,s,a=0;for(let o=0;o<n.length;o++){if(s=fn[n.charCodeAt(o)],s===void 0)switch(n[o]){case"=":r=0;case`
|
|
1
|
+
(function(q,ue){typeof exports=="object"&&typeof module<"u"?ue(exports):typeof define=="function"&&define.amd?define(["exports"],ue):(q=typeof globalThis<"u"?globalThis:q||self,ue(q.index={}))})(this,function(q){"use strict";var zh=Object.defineProperty;var Wh=(q,ue,ft)=>ue in q?zh(q,ue,{enumerable:!0,configurable:!0,writable:!0,value:ft}):q[ue]=ft;var ln=(q,ue,ft)=>Wh(q,typeof ue!="symbol"?ue+"":ue,ft);class ue extends Error{constructor({kind:t,description:i,error:r}){super(JSON.stringify({kind:t,description:i}));ln(this,"kind");ln(this,"description");ln(this,"error");this.kind=t,this.description=i,this.error=r}}class ft extends ue{constructor(e,t){super({kind:"ChatCreationFailed",description:`Failed to create ${t?"persistent":""} chat, mode: ${e}`})}}class pr extends ue{constructor(e){super({kind:"ChatModeDowngraded",description:`Chat mode downgraded to ${e}`})}}class mt extends ue{constructor(t,i){super({kind:"ValidationError",description:t});ln(this,"key");this.key=i}}class gr extends ue{constructor(e){super({kind:"WSError",description:e})}}var vr=(n=>(n.TRIAL="trial",n.BASIC="basic",n.ENTERPRISE="enterprise",n.LITE="lite",n.ADVANCED="advanced",n))(vr||{}),yr=(n=>(n.TRIAL="deid-trial",n.PRO="deid-pro",n.ENTERPRISE="deid-enterprise",n.LITE="deid-lite",n.ADVANCED="deid-advanced",n.BUILD="deid-api-build",n.LAUNCH="deid-api-launch",n.SCALE="deid-api-scale",n))(yr||{}),br=(n=>(n.Created="created",n.Started="started",n.Done="done",n.Error="error",n.Rejected="rejected",n.Ready="ready",n))(br||{}),kr=(n=>(n.Unrated="Unrated",n.Positive="Positive",n.Negative="Negative",n))(kr||{}),le=(n=>(n.Functional="Functional",n.TextOnly="TextOnly",n.Maintenance="Maintenance",n.Playground="Playground",n.DirectPlayback="DirectPlayback",n.Off="Off",n))(le||{}),pt=(n=>(n.Embed="embed",n.Query="query",n.Partial="partial",n.Answer="answer",n.Complete="done",n))(pt||{}),Tr=(n=>(n.KnowledgeProcessing="knowledge/processing",n.KnowledgeIndexing="knowledge/indexing",n.KnowledgeFailed="knowledge/error",n.KnowledgeDone="knowledge/done",n))(Tr||{}),Sr=(n=>(n.Knowledge="knowledge",n.Document="document",n.Record="record",n))(Sr||{}),Cr=(n=>(n.Pdf="pdf",n.Text="text",n.Html="html",n.Word="word",n.Json="json",n.Markdown="markdown",n.Csv="csv",n.Excel="excel",n.Powerpoint="powerpoint",n.Archive="archive",n.Image="image",n.Audio="audio",n.Video="video",n))(Cr||{}),zn=(n=>(n.Clip="clip",n.Talk="talk",n.Expressive="expressive",n))(zn||{});const Qo=n=>{switch(n){case"clip":return"clip";case"talk":return"talk";default:throw new Error(`Unknown video type: ${n}`)}};var H=(n=>(n.Start="START",n.Stop="STOP",n))(H||{}),gt=(n=>(n.Strong="STRONG",n.Weak="WEAK",n.Unknown="UNKNOWN",n))(gt||{}),je=(n=>(n.Idle="IDLE",n.Talking="TALKING",n))(je||{}),he=(n=>(n.ChatAnswer="chat/answer",n.ChatPartial="chat/partial",n.StreamDone="stream/done",n.StreamStarted="stream/started",n.StreamFailed="stream/error",n.StreamReady="stream/ready",n.StreamCreated="stream/created",n.StreamInterrupt="stream/interrupt",n.StreamVideoCreated="stream-video/started",n.StreamVideoDone="stream-video/done",n.StreamVideoError="stream-video/error",n.StreamVideoRejected="stream-video/rejected",n))(he||{}),Y=(n=>(n.New="new",n.Fail="fail",n.Connected="connected",n.Connecting="connecting",n.Closed="closed",n.Completed="completed",n.Disconnected="disconnected",n))(Y||{}),Oe=(n=>(n.Legacy="legacy",n.Fluent="fluent",n))(Oe||{}),Wn=(n=>(n.Livekit="livekit",n))(Wn||{}),Er=(n=>(n.Amazon="amazon",n.Microsoft="microsoft",n.Afflorithmics="afflorithmics",n.Elevenlabs="elevenlabs",n))(Er||{}),Pr=(n=>(n.Public="public",n.Premium="premium",n.Private="private",n))(Pr||{});const Yo=45*1e3,Xo="X-Playground-Chat",wt="https://api.d-id.com",Zo="wss://notifications.d-id.com",ec="79f81a83a67430be2bc0fd61042b8faa",wr=n=>new Promise(e=>setTimeout(e,n)),Rt=(n=16)=>{const e=new Uint8Array(n);return window.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("").slice(0,13)},tc=n=>[le.TextOnly,le.Playground,le.Maintenance].includes(n),Rr=n=>n&&[le.DirectPlayback,le.Off].includes(n);function nc(n,e){let t;return{promise:new Promise((r,s)=>{t=setTimeout(()=>s(new Error(e)),n)}),clear:()=>clearTimeout(t)}}async function Gn(n,e){const t={limit:(e==null?void 0:e.limit)??3,delayMs:(e==null?void 0:e.delayMs)??0,timeout:(e==null?void 0:e.timeout)??3e4,timeoutErrorMessage:(e==null?void 0:e.timeoutErrorMessage)||"Timeout error",shouldRetryFn:(e==null?void 0:e.shouldRetryFn)??(()=>!0),onRetry:(e==null?void 0:e.onRetry)??(()=>{})};let i;for(let r=1;r<=t.limit;r++)try{if(!t.timeout)return await n();const{promise:s,clear:a}=nc(t.timeout,t.timeoutErrorMessage),o=n().finally(a);return await Promise.race([o,s])}catch(s){if(i=s,!t.shouldRetryFn(s)||r>=t.limit)throw s;await wr(t.delayMs),t.onRetry(s)}throw i}function _r(){let n=window.localStorage.getItem("did_external_key_id");if(!n){let e=Rt();window.localStorage.setItem("did_external_key_id",e),n=e}return n}let ic=Rt();function Ir(n){if(n.type==="bearer")return`Bearer ${n.token}`;if(n.type==="basic")return`Basic ${btoa(`${n.username}:${n.password}`)}`;if(n.type==="key")return`Client-Key ${n.clientKey}.${_r()}_${ic}`;throw new Error(`Unknown auth type: ${n}`)}const rc=n=>Gn(n,{limit:3,delayMs:1e3,timeout:0,shouldRetryFn:e=>e.status===429});function Hn(n,e=wt,t){const i=async(r,s)=>{const{skipErrorHandler:a,...o}=s||{},c=await rc(()=>fetch(e+(r!=null&&r.startsWith("/")?r:`/${r}`),{...o,headers:{...o.headers,Authorization:Ir(n),"Content-Type":"application/json"}}));if(!c.ok){let d=await c.text().catch(()=>`Failed to fetch with status ${c.status}`);const l=new Error(d);throw t&&!a&&t(l,{url:r,options:o,headers:c.headers}),l}return c.json()};return{get(r,s){return i(r,{...s,method:"GET"})},post(r,s,a){return i(r,{...a,body:JSON.stringify(s),method:"POST"})},delete(r,s,a){return i(r,{...a,body:JSON.stringify(s),method:"DELETE"})},patch(r,s,a){return i(r,{...a,body:JSON.stringify(s),method:"PATCH"})}}}function Dr(n,e=wt,t){const i=Hn(n,`${e}/agents`,t);return{create(r,s){return i.post("/",r,s)},getAgents(r,s){return i.get(`/${r?`?tag=${r}`:""}`,s).then(a=>a??[])},getById(r,s){return i.get(`/${r}`,s)},delete(r,s){return i.delete(`/${r}`,void 0,s)},update(r,s,a){return i.patch(`/${r}`,s,a)},newChat(r,s,a){return i.post(`/${r}/chat`,s,a)},chat(r,s,a,o){return i.post(`/${r}/chat/${s}`,a,o)},createRating(r,s,a,o){return i.post(`/${r}/chat/${s}/ratings`,a,o)},updateRating(r,s,a,o,c){return i.patch(`/${r}/chat/${s}/ratings/${a}`,o,c)},deleteRating(r,s,a,o){return i.delete(`/${r}/chat/${s}/ratings/${a}`,o)},getSTTToken(r,s){return i.get(`/${r}/stt-token`,s)}}}const Or=n=>n.type==="clip"&&n.presenter_id.startsWith("v2_")?"clip_v2":n.type;function sc(n){var r,s,a,o;const e=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop",t=()=>{const c=navigator.platform;return c.toLowerCase().includes("win")?"Windows":c.toLowerCase().includes("mac")?"Mac OS X":c.toLowerCase().includes("linux")?"Linux":"Unknown"},i=n.presenter;return{$os:`${t()}`,isMobile:`${e()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:Or(i),agentVoice:{voiceId:(s=(r=n.presenter)==null?void 0:r.voice)==null?void 0:s.voice_id,provider:(o=(a=n.presenter)==null?void 0:a.voice)==null?void 0:o.type}}}function ac(n){var t,i,r,s,a,o;const e=(t=n.llm)==null?void 0:t.prompt_customization;return{agentType:Or(n.presenter),owner_id:n.owner_id??"",promptVersion:(i=n.llm)==null?void 0:i.prompt_version,behavior:{role:e==null?void 0:e.role,personality:e==null?void 0:e.personality,instructions:(r=n.llm)==null?void 0:r.instructions},temperature:(s=n.llm)==null?void 0:s.temperature,knowledgeSource:e==null?void 0:e.knowledge_source,starterQuestionsCount:(o=(a=n.knowledge)==null?void 0:a.starter_message)==null?void 0:o.length,topicsToAvoid:e==null?void 0:e.topics_to_avoid,maxResponseLength:e==null?void 0:e.max_response_length,agentId:n.id,access:n.access,name:n.preview_name,...n.access==="public"?{from:"agent-template"}:{}}}const oc=n=>n.reduce((e,t)=>e+t,0),Mr=n=>oc(n)/n.length;function cc(n,e,t){var c,d,l;const{event:i,...r}=n,{template:s}=(e==null?void 0:e.llm)||{},{language:a}=((c=e==null?void 0:e.presenter)==null?void 0:c.voice)||{};return{...r,llm:{...r.llm,template:s},script:{...r.script,provider:{...(d=r==null?void 0:r.script)==null?void 0:d.provider,language:a}},stitch:(e==null?void 0:e.presenter.type)==="talk"?(l=e==null?void 0:e.presenter)==null?void 0:l.stitch:void 0,...t}}let Jn={};const dc="https://api-js.mixpanel.com/track/?verbose=1&ip=1";function lc(n){const e=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk";return{token:n.token||"testKey",distinct_id:n.distinctId||_r(),agentId:n.agentId,additionalProperties:{id:n.distinctId,...n.mixpanelAdditionalProperties||{}},isEnabled:n.isEnabled??!0,getRandom:Rt,enrich(t){this.additionalProperties={...this.additionalProperties,...t}},async track(t,i){if(!this.isEnabled)return Promise.resolve();const{audioPath:r,...s}=i||{},a={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify([{event:t,properties:{...this.additionalProperties,...s,agentId:this.agentId,source:e,token:this.token,time:Date.now(),$insert_id:this.getRandom(),origin:window.location.href,"Screen Height":window.screen.height||window.innerWidth,"Screen Width":window.screen.width||window.innerHeight,"User Agent":navigator.userAgent}}])})};try{return await fetch(dc,a).then(o=>o.json())}catch(o){return console.error(o)}},linkTrack(t,i,r,s){Jn[t]||(Jn[t]={events:{},resolvedDependencies:[]}),s.includes(r)||s.push(r);const a=Jn[t];if(a.events[r]={props:i},a.resolvedDependencies.push(r),s.every(c=>a.resolvedDependencies.includes(c))){const c=s.reduce((d,l)=>a.events[l]?{...d,...a.events[l].props}:d,{});this.track(t,c),a.resolvedDependencies=a.resolvedDependencies.filter(d=>!s.includes(d)),s.forEach(d=>{delete a.events[d]})}}}}function Ar(){let n=0;return{reset:()=>n=0,update:()=>n=Date.now(),get:(e=!1)=>e?Date.now()-n:n}}const Me=Ar(),$n=Ar();function xr(n){return n===le.Playground?{headers:{[Xo]:"true"}}:{}}async function Lr(n,e,t,i,r=!1,s){try{return!s&&!Rr(i)&&(s=await e.newChat(n.id,{persist:r},xr(i)),t.track("agent-chat",{event:"created",chatId:s.id,mode:i})),{chat:s,chatMode:(s==null?void 0:s.chat_mode)??i}}catch(a){try{const o=JSON.parse(a.message);if((o==null?void 0:o.kind)==="InsufficientCreditsError")throw new Error("InsufficientCreditsError")}catch(o){console.error("Error parsing the error message:",o)}throw new Error("Cannot create new chat")}}function uc(n){return n&&n.length>0?n:[]}function hc(n,e,t){if(!n)throw new Error("Please connect to the agent first");if(!n.interruptAvailable)throw new Error("Interrupt is not enabled for this stream");if(e!==Oe.Fluent)throw new Error("Interrupt only available for Fluent streams");if(!t)throw new Error("No active video to interrupt")}async function fc(n,e){const t={type:he.StreamInterrupt,videoId:e,timestamp:Date.now()};n.sendDataChannelMessage(JSON.stringify(t))}function mc(n){return new Promise((e,t)=>{const{callbacks:i,host:r,auth:s}=n,{onMessage:a=null,onOpen:o=null,onClose:c=null,onError:d=null}=i||{},l=new WebSocket(`${r}?authorization=${Ir(s)}`);l.onmessage=a,l.onclose=c,l.onerror=u=>{console.error(u),d==null||d("Websocket failed to connect",u),t(u)},l.onopen=u=>{o==null||o(u),e(l)}})}async function pc(n){const{retries:e=1}=n;let t=null;for(let i=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;i++)try{t=await mc(n)}catch(r){if(i===e)throw r;await wr(i*500)}return t}async function gc(n,e,t){const i=t!=null&&t.onMessage?[t.onMessage]:[],r=await pc({auth:n,host:e,callbacks:{onError:s=>{var a;return(a=t.onError)==null?void 0:a.call(t,new gr(s))},onMessage(s){const a=JSON.parse(s.data);i.forEach(o=>o(a.event,a))}}});return{socket:r,disconnect:()=>r.close(),subscribeToEvents:s=>i.push(s)}}function vc(n){if(n.answer!==void 0)return n.answer;let e=0,t="";for(;e in n;)t+=n[e++];return t}function yc(n,e,t,i,r){const s=i.messages[i.messages.length-1];if(!(n===pt.Partial||n===pt.Answer)||(s==null?void 0:s.role)!=="assistant")return;const{content:a,sequence:o}=e;n===pt.Partial?t[o]=a:t.answer=a;const c=vc(t);(s.content!==c||n===pt.Answer)&&(s.content=c,r==null||r([...i.messages],n))}function bc(n,e,t,i,r){let s={};return{clearQueue:()=>s={},onMessage:(a,o)=>{var c,d;if("content"in o)yc(a,o,s,e,t.callbacks.onNewMessage),a===pt.Answer&&n.track("agent-message-received",{messages:e.messages.length,mode:e.chatMode});else{const l=he,u=[l.StreamVideoDone,l.StreamVideoError,l.StreamVideoRejected],h=[l.StreamFailed,l.StreamVideoError,l.StreamVideoRejected],m=cc(o,i,{mode:e.chatMode});if(a=a,a===l.StreamVideoCreated)n.linkTrack("agent-video",m,l.StreamVideoCreated,["start"]);else if(u.includes(a)){const y=a.split("/")[1];h.includes(a)?n.track("agent-video",{...m,event:y}):n.linkTrack("agent-video",{...m,event:y},a,["done"])}h.includes(a)&&((d=(c=t.callbacks).onError)==null||d.call(c,new Error(`Stream failed with event ${a}`),{data:o})),o.event===l.StreamDone&&r()}}}}function kc(n,e,t,i){const r=Hn(n,`${e}/agents/${t}`,i);return{createStream(s){return r.post("/streams",s)},startConnection(s,a,o){return r.post(`/streams/${s}/sdp`,{session_id:o,answer:a})},addIceCandidate(s,a,o){return r.post(`/streams/${s}/ice`,{session_id:o,...a})},sendStreamRequest(s,a,o){return r.post(`/streams/${s}`,{session_id:a,...o})},close(s,a){return r.delete(`/streams/${s}`,{session_id:a})}}}const Nr=(n,e)=>(t,i)=>n&&console.log(`[${e}] ${t}`,i??"");function Tc(n,e,t){const i=(e.timestamp-n.timestamp)/1e3;return{duration:i,bytesReceived:e.bytesReceived-n.bytesReceived,bitrate:Math.round((e.bytesReceived-n.bytesReceived)*8/i),packetsReceived:e.packetsReceived-n.packetsReceived,packetsLost:e.packetsLost-n.packetsLost,framesDropped:e.framesDropped-n.framesDropped,framesDecoded:e.framesDecoded-n.framesDecoded,jitter:e.jitter,avgJitterDelayInInterval:(e.jitterBufferDelay-n.jitterBufferDelay)/(e.jitterBufferEmittedCount-n.jitterBufferEmittedCount),jitterBufferEmittedCount:e.jitterBufferEmittedCount-n.jitterBufferEmittedCount,jitterBufferDelay:(e.jitterBufferDelay-n.jitterBufferDelay)/i,framesPerSecond:e.framesPerSecond,freezeCount:e.freezeCount-n.freezeCount,freezeDuration:e.freezeDuration-n.freezeDuration,lowFpsCount:t}}function Sc(n){return n.filter(e=>e.freezeCount>0||e.framesPerSecond<21||e.framesDropped>0||e.packetsLost>0).map(e=>{const{timestamp:t,...i}=e,r=[];return e.freezeCount>0&&r.push("freeze"),e.framesPerSecond<21&&r.push("low fps"),e.framesDropped>0&&r.push("frames dropped"),e.packetsLost>0&&r.push("packet loss"),{...i,causes:r}})}function Cc(n){let e="",t=0;for(const i of n.values())if(i&&i.type==="codec"&&i.mimeType.startsWith("video")&&(e=i.mimeType.split("/")[1]),i&&i.type==="candidate-pair"&&(t=i.currentRoundTripTime),i&&i.type==="inbound-rtp"&&i.kind==="video")return{codec:e,rtt:t,timestamp:i.timestamp,bytesReceived:i.bytesReceived,packetsReceived:i.packetsReceived,packetsLost:i.packetsLost,framesDropped:i.framesDropped,framesDecoded:i.framesDecoded,jitter:i.jitter,jitterBufferDelay:i.jitterBufferDelay,jitterBufferEmittedCount:i.jitterBufferEmittedCount,avgJitterDelayInInterval:i.jitterBufferDelay/i.jitterBufferEmittedCount,frameWidth:i.frameWidth,frameHeight:i.frameHeight,framesPerSecond:i.framesPerSecond,freezeCount:i.freezeCount,freezeDuration:i.totalFreezesDuration};return{}}function Ec(n,e,t){const i=n.map((c,d)=>d===0?t?{timestamp:c.timestamp,duration:0,rtt:c.rtt,bytesReceived:c.bytesReceived-t.bytesReceived,bitrate:(c.bytesReceived-t.bytesReceived)*8/(e/1e3),packetsReceived:c.packetsReceived-t.packetsReceived,packetsLost:c.packetsLost-t.packetsLost,framesDropped:c.framesDropped-t.framesDropped,framesDecoded:c.framesDecoded-t.framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay-t.jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount-t.jitterBufferEmittedCount,avgJitterDelayInInterval:(c.jitterBufferDelay-t.jitterBufferDelay)/(c.jitterBufferEmittedCount-t.jitterBufferEmittedCount),framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount-t.freezeCount,freezeDuration:c.freezeDuration-t.freezeDuration}:{timestamp:c.timestamp,rtt:c.rtt,duration:0,bytesReceived:c.bytesReceived,bitrate:c.bytesReceived*8/(e/1e3),packetsReceived:c.packetsReceived,packetsLost:c.packetsLost,framesDropped:c.framesDropped,framesDecoded:c.framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount,avgJitterDelayInInterval:c.jitterBufferDelay/c.jitterBufferEmittedCount,framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount,freezeDuration:c.freezeDuration}:{timestamp:c.timestamp,duration:e*d/1e3,rtt:c.rtt,bytesReceived:c.bytesReceived-n[d-1].bytesReceived,bitrate:(c.bytesReceived-n[d-1].bytesReceived)*8/(e/1e3),packetsReceived:c.packetsReceived-n[d-1].packetsReceived,packetsLost:c.packetsLost-n[d-1].packetsLost,framesDropped:c.framesDropped-n[d-1].framesDropped,framesDecoded:c.framesDecoded-n[d-1].framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay-n[d-1].jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount,avgJitterDelayInInterval:(c.jitterBufferDelay-n[d-1].jitterBufferDelay)/(c.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount),framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount-n[d-1].freezeCount,freezeDuration:c.freezeDuration-n[d-1].freezeDuration}),r=Sc(i),s=r.reduce((c,d)=>c+(d.causes.includes("low fps")?1:0),0),a=i.filter(c=>!!c.avgJitterDelayInInterval).map(c=>c.avgJitterDelayInInterval),o=i.filter(c=>!!c.rtt).map(c=>c.rtt);return{webRTCStats:{anomalies:r,minRtt:Math.min(...o),avgRtt:Mr(o),maxRtt:Math.max(...o),aggregateReport:Tc(n[0],n[n.length-1],s),minJitterDelayInInterval:Math.min(...a),maxJitterDelayInInterval:Math.max(...a),avgJitterDelayInInterval:Mr(a)},codec:n[0].codec,resolution:`${n[0].frameWidth}x${n[0].frameHeight}`}}const Qn=100,Pc=Math.max(Math.ceil(400/Qn),1),wc=.25,Rc=.28;function _c(){let n=0,e,t,i=0;return r=>{for(const s of r.values())if(s&&s.type==="inbound-rtp"&&s.kind==="video"){const a=s.jitterBufferDelay,o=s.jitterBufferEmittedCount;if(t&&o>t){const l=a-e,u=o-t;i=l/u}e=a,t=o;const c=s.framesDecoded,d=c-n>0;return n=c,{isReceiving:d,avgJitterDelayInInterval:i,freezeCount:s.freezeCount}}return{isReceiving:!1,avgJitterDelayInInterval:i}}}function Ic(n,e,t,i,r,s=!1){let a=[],o,c=0,d=!1,l=gt.Unknown,u=gt.Unknown,h=0,m=0;const y=_c();return setInterval(async()=>{const g=await n.getStats(),{isReceiving:P,avgJitterDelayInInterval:S,freezeCount:w}=y(g),D=Cc(g);if(P)c=0,h=w-m,u=S<wc?gt.Strong:S>Rc&&h>1?gt.Weak:l,u!==l&&(r==null||r(u),l=u,m+=h,h=0),d||(i==null||i(H.Start),o=a[a.length-1],a=[],d=!0),a.push(D);else if(d&&(c++,c>=Pc)){const p=Ec(a,Qn,o);i==null||i(H.Stop,p),e()||t(),m=w,d=!1}},Qn)}const Dc=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function Ur(n){switch(n){case"connected":return Y.Connected;case"checking":return Y.Connecting;case"failed":return Y.Fail;case"new":return Y.New;case"closed":return Y.Closed;case"disconnected":return Y.Disconnected;case"completed":return Y.Completed;default:return Y.New}}const Oc=n=>e=>{const[t,i=""]=e.split(/:(.+)/);try{const r=JSON.parse(i);return n("parsed data channel message",{subject:t,data:r}),{subject:t,data:r}}catch(r){return n("Failed to parse data channel message, returning data as string",{subject:t,rawData:i,error:r}),{subject:t,data:i}}};function Mc({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:i}){n===H.Start&&e===H.Start?t==null||t(H.Start):n===H.Stop&&e===H.Stop&&(t==null||t(H.Stop,i))}function Ac({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:r}){n===H.Start?t==null||t(H.Start):n===H.Stop&&(t==null||t(H.Stop,r)),e===H.Start?i==null||i(je.Talking):e===H.Stop&&(i==null||i(je.Idle))}function Fr({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,streamType:r,report:s}){r===Oe.Legacy?Mc({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:s}):r===Oe.Fluent&&Ac({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:s})}async function xc(n,e,{debug:t=!1,callbacks:i,auth:r,baseURL:s=wt,analytics:a}){var st;const o=Nr(t,"WebRTCStreamingManager"),c=Oc(o);let d=!1,l=!1,u=H.Stop,h=H.Stop;const{startConnection:m,sendStreamRequest:y,close:g,createStream:P,addIceCandidate:S}=kc(r,s,n,i.onError),{id:w,offer:D,ice_servers:p,session_id:v,fluent:T,interrupt_enabled:x,triggers_enabled:L}=await P(e);(st=i.onStreamCreated)==null||st.call(i,{stream_id:w,session_id:v,agent_id:n});const k=new Dc({iceServers:p}),I=k.createDataChannel("JanusDataChannel");if(!v)throw new Error("Could not create session_id");const O=T?Oe.Fluent:Oe.Legacy;a.enrich({"stream-type":O});const N=e.stream_warmup&&!T,U=()=>d,G=()=>{var j;d=!0,l&&((j=i.onConnectionStateChange)==null||j.call(i,Y.Connected))},Q=Ic(k,U,G,(j,B)=>Fr({statsSignal:h=j,dataChannelSignal:O===Oe.Legacy?u:void 0,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,report:B,streamType:O}),j=>{var B;return(B=i.onConnectivityStateChange)==null?void 0:B.call(i,j)},N);k.onicecandidate=j=>{var B;o("peerConnection.onicecandidate",j);try{j.candidate&&j.candidate.sdpMid&&j.candidate.sdpMLineIndex!==null?S(w,{candidate:j.candidate.candidate,sdpMid:j.candidate.sdpMid,sdpMLineIndex:j.candidate.sdpMLineIndex},v):S(w,{candidate:null},v)}catch(me){(B=i.onError)==null||B.call(i,me,{streamId:w})}},I.onopen=()=>{l=!0,(!N||d)&&G()};const fe=j=>{var B;(B=i.onVideoIdChange)==null||B.call(i,j)};function re(j,B){if(j===he.StreamStarted&&typeof B=="object"&&"metadata"in B){const me=B.metadata;fe(me.videoId)}j===he.StreamDone&&fe(null),u=j===he.StreamStarted?H.Start:H.Stop,Fr({statsSignal:O===Oe.Legacy?h:void 0,dataChannelSignal:u,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,streamType:O})}function Ce(j,B){const me=typeof B=="string"?B:B==null?void 0:B.metadata;me&&a.enrich({streamMetadata:me}),a.track("agent-chat",{event:"ready"})}const Ee={[he.StreamStarted]:re,[he.StreamDone]:re,[he.StreamReady]:Ce};I.onmessage=j=>{var ht;const{subject:B,data:me}=c(j.data);(ht=Ee[B])==null||ht.call(Ee,B,me)},k.oniceconnectionstatechange=()=>{var B;o("peerConnection.oniceconnectionstatechange => "+k.iceConnectionState);const j=Ur(k.iceConnectionState);j!==Y.Connected&&((B=i.onConnectionStateChange)==null||B.call(i,j))},k.ontrack=j=>{var B;o("peerConnection.ontrack",j),(B=i.onSrcObjectReady)==null||B.call(i,j.streams[0])},await k.setRemoteDescription(D),o("set remote description OK");const rt=await k.createAnswer();return o("create answer OK"),await k.setLocalDescription(rt),o("set local description OK"),await m(w,rt,v),o("start connection OK"),{speak(j){return y(w,v,j)},async disconnect(){var j;if(w){const B=Ur(k.iceConnectionState);if(k){if(B===Y.New){clearInterval(Q);return}k.close(),k.oniceconnectionstatechange=null,k.onnegotiationneeded=null,k.onicecandidate=null,k.ontrack=null}try{B===Y.Connected&&await g(w,v).catch(me=>{})}catch(me){o("Error on close stream connection",me)}(j=i.onAgentActivityStateChange)==null||j.call(i,je.Idle),clearInterval(Q)}},sendDataChannelMessage(j){var B,me;if(!d||I.readyState!=="open"){o("Data channel is not ready for sending messages"),(B=i.onError)==null||B.call(i,new Error("Data channel is not ready for sending messages"),{streamId:w});return}try{I.send(j)}catch(ht){o("Error sending data channel message",ht),(me=i.onError)==null||me.call(i,ht,{streamId:w})}},sessionId:v,streamId:w,streamType:O,interruptAvailable:x??!1,triggersAvailable:L??!1}}const Lc=n=>n.presenter.type===zn.Expressive;async function Nc(n,e,t){const i=n.id;if(Lc(n)){const{createLiveKitStreamingManager:r}=await Promise.resolve().then(()=>$c);return r(i,e,t)}else return xc(i,e,t)}function Uc(n){var r,s,a;const{streamOptions:e}=n??{},t=n!=null&&n.distinctId||((r=n==null?void 0:n.mixpanelAdditionalProperties)==null?void 0:r.plan)!==void 0?{...n!=null&&n.distinctId?{distinct_id:n.distinctId}:{},...((s=n==null?void 0:n.mixpanelAdditionalProperties)==null?void 0:s.plan)!==void 0?{plan:(a=n.mixpanelAdditionalProperties)==null?void 0:a.plan}:{}}:void 0;return{...{output_resolution:e==null?void 0:e.outputResolution,session_timeout:e==null?void 0:e.sessionTimeout,stream_warmup:e==null?void 0:e.streamWarmup,compatibility_mode:e==null?void 0:e.compatibilityMode,fluent:e==null?void 0:e.fluent},...t&&{end_user_data:t}}}function Fc(n,e,t,i,r){r===Oe.Fluent?jc(n,e,t,i,r):Vc(n,e,t,i,r)}function jc(n,e,t,i,r){n===H.Start?i.track("stream-session",{event:"start","stream-type":r}):n===H.Stop&&i.track("stream-session",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t})}function Bc(n,e,t,i){Me.get()<=0||(n===H.Start?t.linkTrack("agent-video",{event:"start",latency:Me.get(!0),"stream-type":i},"start",[he.StreamVideoCreated]):n===H.Stop&&t.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":i},"done",[he.StreamVideoDone]))}function Vc(n,e,t,i,r){Me.get()<=0||(n===H.Start?i.linkTrack("agent-video",{event:"start",latency:Me.get(!0),"stream-type":r},"start",[he.StreamVideoCreated]):n===H.Stop&&i.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t},"done",[he.StreamVideoDone]))}function qc(n,e,t){return Me.reset(),new Promise(async(i,r)=>{try{let s;s=await Nc(n,Uc(e),{...e,analytics:t,callbacks:{...e.callbacks,onConnectionStateChange:a=>{var o,c;(c=(o=e.callbacks).onConnectionStateChange)==null||c.call(o,a),a===Y.Connected&&i(s)},onVideoStateChange:(a,o)=>{var c,d;(d=(c=e.callbacks).onVideoStateChange)==null||d.call(c,a),Fc(a,n,o,t,s.streamType)},onAgentActivityStateChange:a=>{var o,c;(c=(o=e.callbacks).onAgentActivityStateChange)==null||c.call(o,a),a===je.Talking?$n.update():$n.reset(),Bc(a===je.Talking?H.Start:H.Stop,n,t,s.streamType)}}})}catch(s){r(s)}})}async function Kc(n,e,t,i,r){var u,h,m,y;const s=Lr(n,t,i,e.mode,e.persistentChat,r),a=qc(n,e,i),[o,c]=await Promise.all([s,a]),{chat:d,chatMode:l}=o;return l&&l!==e.mode&&(e.mode=l,(h=(u=e.callbacks).onModeChange)==null||h.call(u,l),l!==le.Functional)?((y=(m=e.callbacks).onError)==null||y.call(m,new pr(l)),c==null||c.disconnect(),{chat:d}):{chat:d,streamingManager:c}}async function zc(n,e){var S,w,D;let t=!0,i=null;const r=e.mixpanelKey||ec,s=e.wsURL||Zo,a=e.baseURL||wt,o={messages:[],chatMode:e.mode||le.Functional},c=lc({token:r,agentId:n,isEnabled:e.enableAnalitics,distinctId:e.distinctId,mixpanelAdditionalProperties:e.mixpanelAdditionalProperties});c.track("agent-sdk",{event:"init"});const d=Dr(e.auth,a,e.callbacks.onError),l=await d.getById(n);c.enrich(ac(l));const{onMessage:u,clearQueue:h}=bc(c,o,e,l,()=>{var p;return(p=o.socketManager)==null?void 0:p.disconnect()});o.messages=uc(e.initialMessages),(w=(S=e.callbacks).onNewMessage)==null||w.call(S,[...o.messages],"answer");const m=p=>{i=p};c.track("agent-sdk",{event:"loaded",...sc(l)});async function y(p){var I,O,N,U,G,Q,fe;(O=(I=e.callbacks).onConnectionStateChange)==null||O.call(I,Y.Connecting),Me.reset(),p&&!t&&(delete o.chat,(U=(N=e.callbacks).onNewMessage)==null||U.call(N,[...o.messages],"answer"));const v=e.mode===le.DirectPlayback?Promise.resolve(void 0):gc(e.auth,s,{onMessage:u,onError:e.callbacks.onError}),T=Gn(()=>Kc(l,{...e,callbacks:{...e.callbacks,onVideoIdChange:m}},d,c,o.chat),{limit:3,timeout:Yo,timeoutErrorMessage:"Timeout initializing the stream",shouldRetryFn:re=>(re==null?void 0:re.message)!=="Could not connect"&&re.status!==429,delayMs:1e3}).catch(re=>{var Ce,Ee;throw P(le.Maintenance),(Ee=(Ce=e.callbacks).onConnectionStateChange)==null||Ee.call(Ce,Y.Fail),re}),[x,{streamingManager:L,chat:k}]=await Promise.all([v,T]);k&&k.id!==((G=o.chat)==null?void 0:G.id)&&((fe=(Q=e.callbacks).onNewChat)==null||fe.call(Q,k.id)),o.streamingManager=L,o.socketManager=x,o.chat=k,t=!1,c.enrich({chatId:k==null?void 0:k.id,streamId:L==null?void 0:L.streamId,mode:o.chatMode}),P((k==null?void 0:k.chat_mode)??e.mode??le.Functional)}async function g(){var p,v,T,x;(p=o.socketManager)==null||p.disconnect(),await((v=o.streamingManager)==null?void 0:v.disconnect()),delete o.streamingManager,delete o.socketManager,(x=(T=e.callbacks).onConnectionStateChange)==null||x.call(T,Y.Disconnected)}async function P(p){var v,T;p!==o.chatMode&&(c.track("agent-mode-change",{mode:p}),o.chatMode=p,o.chatMode!==le.Functional&&await g(),(T=(v=e.callbacks).onModeChange)==null||T.call(v,p))}return{agent:l,getStreamType:()=>{var p;return(p=o.streamingManager)==null?void 0:p.streamType},getIsInterruptAvailable:()=>{var p;return((p=o.streamingManager)==null?void 0:p.interruptAvailable)??!1},getIsTriggersAvailable:()=>{var p;return((p=o.streamingManager)==null?void 0:p.triggersAvailable)??!1},starterMessages:((D=l.knowledge)==null?void 0:D.starter_message)||[],getSTTToken:()=>d.getSTTToken(l.id),changeMode:P,enrichAnalytics:c.enrich,async connect(){await y(!0),c.track("agent-chat",{event:"connect",mode:o.chatMode})},async reconnect(){await g(),await y(!1),c.track("agent-chat",{event:"reconnect",mode:o.chatMode})},async disconnect(){await g(),c.track("agent-chat",{event:"disconnect",mode:o.chatMode})},async chat(p){var L,k,I,O,N;const v=()=>{if(Rr(e.mode))throw new mt(`${e.mode} is enabled, chat is disabled`);if(p.length>=800)throw new mt("Message cannot be more than 800 characters");if(p.length===0)throw new mt("Message cannot be empty");if(o.chatMode===le.Maintenance)throw new mt("Chat is in maintenance mode");if(![le.TextOnly,le.Playground].includes(o.chatMode)){if(!o.streamingManager)throw new mt("Streaming manager is not initialized");if(!o.chat)throw new mt("Chat is not initialized")}},T=async()=>{var U,G;if(!o.chat){const Q=await Lr(l,d,c,o.chatMode,e.persistentChat);if(!Q.chat)throw new ft(o.chatMode,!!e.persistentChat);o.chat=Q.chat,(G=(U=e.callbacks).onNewChat)==null||G.call(U,o.chat.id)}return o.chat.id},x=async(U,G)=>Gn(()=>{var Q,fe;return d.chat(l.id,G,{chatMode:o.chatMode,streamId:(Q=o.streamingManager)==null?void 0:Q.streamId,sessionId:(fe=o.streamingManager)==null?void 0:fe.sessionId,messages:U.map(({matches:re,...Ce})=>Ce)},{...xr(o.chatMode),skipErrorHandler:!0})},{limit:2,shouldRetryFn:Q=>{var Ce,Ee,rt,st;const fe=(Ce=Q==null?void 0:Q.message)==null?void 0:Ce.includes("missing or invalid session_id");return!((Ee=Q==null?void 0:Q.message)==null?void 0:Ee.includes("Stream Error"))&&!fe?((st=(rt=e.callbacks).onError)==null||st.call(rt,Q),!1):!0},onRetry:async()=>{await g(),await y(!1)}});try{h(),v(),o.messages.push({id:Rt(),role:"user",content:p,created_at:new Date(Me.update()).toISOString()}),(k=(L=e.callbacks).onNewMessage)==null||k.call(L,[...o.messages],"user");const U=await T(),G=await x([...o.messages],U);return o.messages.push({id:Rt(),role:"assistant",content:G.result||"",created_at:new Date().toISOString(),context:G.context,matches:G.matches}),c.track("agent-message-send",{event:"success",messages:o.messages.length+1}),G.result&&((O=(I=e.callbacks).onNewMessage)==null||O.call(I,[...o.messages],"answer"),c.track("agent-message-received",{latency:Me.get(!0),messages:o.messages.length})),G}catch(U){throw((N=o.messages[o.messages.length-1])==null?void 0:N.role)==="assistant"&&o.messages.pop(),c.track("agent-message-send",{event:"error",messages:o.messages.length}),U}},rate(p,v,T){var k,I,O,N;const x=o.messages.find(U=>U.id===p);if(o.chat){if(!x)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const L=((k=x.matches)==null?void 0:k.map(U=>[U.document_id,U.id]))??[];return c.track("agent-rate",{event:T?"update":"create",thumb:v===1?"up":"down",knowledge_id:((I=l.knowledge)==null?void 0:I.id)??"",matches:L,score:v}),T?d.updateRating(l.id,o.chat.id,T,{knowledge_id:((O=l.knowledge)==null?void 0:O.id)??"",message_id:p,matches:L,score:v}):d.createRating(l.id,o.chat.id,{knowledge_id:((N=l.knowledge)==null?void 0:N.id)??"",message_id:p,matches:L,score:v})},deleteRate(p){if(!o.chat)throw new Error("Chat is not initialized");return c.track("agent-rate-delete",{type:"text"}),d.deleteRating(l.id,o.chat.id,p)},async speak(p){var L,k,I;function v(){if(typeof p=="string"){if(!l.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:l.presenter.voice,input:p,ssml:!1}}if(p.type==="text"&&!p.provider){if(!l.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:l.presenter.voice,input:p.input,ssml:p.ssml}}return p}const T=v();if(c.track("agent-speak",T),Me.update(),o.messages&&T.type==="text"&&(o.messages.push({id:Rt(),role:"assistant",content:T.input,created_at:new Date(Me.get(!0)).toISOString()}),(k=(L=e.callbacks).onNewMessage)==null||k.call(L,[...o.messages],"answer")),tc(o.chatMode))return{duration:0,video_id:"",status:"success"};if(!o.streamingManager)throw new Error("Please connect to the agent first");return o.streamingManager.speak({script:T,metadata:{chat_id:(I=o.chat)==null?void 0:I.id,agent_id:l.id}})},async interrupt({type:p}){var T,x,L;hc(o.streamingManager,(T=o.streamingManager)==null?void 0:T.streamType,i);const v=o.messages[o.messages.length-1];c.track("agent-video-interrupt",{type:p||"click",video_duration_to_interrupt:$n.get(!0),message_duration_to_interrupt:Me.get(!0)}),v.interrupted=!0,(L=(x=e.callbacks).onNewMessage)==null||L.call(x,[...o.messages],"answer"),fc(o.streamingManager,i)}}}function Wc(n,e,t){const{getById:i}=Dr(e,t||wt);return i(n)}function Gc(n,e,t,i){const r=Hn(n,`${e}/v2/agents/${t}`,i);return{async createStream(s){return r.post("/streams",s)}}}async function Hc(){try{return await Promise.resolve().then(()=>Kh)}catch{throw new Error("LiveKit client is required for this streaming manager. Please install it using: npm install livekit-client")}}async function Jc(n,e,t){var T,x,L;const i=Nr(t.debug||!1,"LiveKitStreamingManager"),{Room:r,RoomEvent:s,ConnectionState:a,RemoteParticipant:o,RemoteTrack:c}=await Hc(),{callbacks:d,auth:l,baseURL:u,analytics:h}=t;let m=null,y=!1,g=null,P=null;const S=Oe.Fluent;m=new r({adaptiveStream:!0,dynacast:!0}),m.on(s.ConnectionStateChanged,k=>{var I,O,N,U,G;switch(i("Connection state changed:",k),k){case a.Connecting:(I=d.onConnectionStateChange)==null||I.call(d,Y.Connecting);break;case a.Connected:i("LiveKit room connected successfully"),y=!0,(O=d.onConnectionStateChange)==null||O.call(d,Y.Connected);break;case a.Disconnected:i("LiveKit room disconnected"),y=!1,(N=d.onConnectionStateChange)==null||N.call(d,Y.Disconnected);break;case a.Reconnecting:i("LiveKit room reconnecting..."),(U=d.onConnectionStateChange)==null||U.call(d,Y.Connecting);break;case a.SignalReconnecting:i("LiveKit room signal reconnecting..."),(G=d.onConnectionStateChange)==null||G.call(d,Y.Connecting);break}}),m.on(s.ConnectionQualityChanged,(k,I)=>{var O;I!=null&&I.isLocal&&k==="poor"&&(i("Connection quality is poor"),(O=d.onConnectivityStateChange)==null||O.call(d,gt.Weak))}),m.on(s.ParticipantConnected,k=>{i("Participant connected:",k.identity)}),m.on(s.TrackSubscribed,(k,I,O)=>{var N,U;i(`Track subscribed: ${k.kind} from ${O.identity}`),P?P.addTrack(k.mediaStreamTrack):P=new MediaStream([k.mediaStreamTrack]),(N=d.onSrcObjectReady)==null||N.call(d,P),k.kind==="video"&&((U=d.onVideoStateChange)==null||U.call(d,H.Start))}),m.on(s.TrackUnsubscribed,(k,I,O)=>{var N;i(`Track unsubscribed: ${k.kind} from ${O.identity}`),k.kind==="video"&&((N=d.onVideoStateChange)==null||N.call(d,H.Stop))}),m.on(s.DataReceived,(k,I)=>{var N,U,G,Q,fe;const O=new TextDecoder().decode(k);i("Data received:",O);try{const re=JSON.parse(O);re.subject===he.StreamStarted&&((N=re.metadata)!=null&&N.videoId)?(g=re.metadata.videoId,(U=d.onVideoIdChange)==null||U.call(d,g),(G=d.onAgentActivityStateChange)==null||G.call(d,je.Talking)):re.subject===he.StreamDone&&(g=null,(Q=d.onVideoIdChange)==null||Q.call(d,g),(fe=d.onAgentActivityStateChange)==null||fe.call(d,je.Idle))}catch(re){i("Failed to parse data channel message:",re)}}),(T=d.onConnectionStateChange)==null||T.call(d,Y.New);const w=Gc(l,u||wt,n,d.onError);let D,p;try{const k=await w.createStream({transport_provider:Wn.Livekit}),{agent_id:I,session_id:O,session_token:N,session_url:U}=k;D=I,p=O,await m.connect(U,N),i("LiveKit room joined successfully")}catch(k){throw i("Failed to connect to LiveKit room:",k),(x=d.onConnectionStateChange)==null||x.call(d,Y.Fail),(L=d.onError)==null||L.call(d,k,{streamId:""}),k}h.enrich({"stream-type":S});async function v(k){var I,O;if(!y||!m){i("Room is not connected for sending messages"),(I=d.onError)==null||I.call(d,new Error("Room is not connected for sending messages"),{streamId:D});return}try{await m.localParticipant.publishData(new TextEncoder().encode(k),{reliable:!0})}catch(N){i("Error sending data channel message",N),(O=d.onError)==null||O.call(d,N,{streamId:D})}}return{speak(k){const I=JSON.stringify({type:"speak",payload:k});return v(I)},async disconnect(){var k,I;m&&(await m.disconnect(),m=null),P&&(P.getTracks().forEach(O=>O.stop()),P=null),y=!1,(k=d.onConnectionStateChange)==null||k.call(d,Y.Completed),(I=d.onAgentActivityStateChange)==null||I.call(d,je.Idle)},sendDataChannelMessage:v,sessionId:p,streamId:D,streamType:S,interruptAvailable:!0,triggersAvailable:!1}}const $c=Object.freeze(Object.defineProperty({__proto__:null,createLiveKitStreamingManager:Jc},Symbol.toStringTag,{value:"Module"}));function Qc(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var Yc=Object.defineProperty,Xc=(n,e,t)=>e in n?Yc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,jr=(n,e,t)=>Xc(n,typeof e!="symbol"?e+"":e,t);class pe{constructor(){jr(this,"_locking"),jr(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function te(n,e){if(!n)throw new Error(e)}const Zc=34028234663852886e22,ed=-34028234663852886e22,td=4294967295,nd=2147483647,id=-2147483648;function un(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>nd||n<id)throw new Error("invalid int 32: "+n)}function Yn(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>td||n<0)throw new Error("invalid uint 32: "+n)}function Br(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>Zc||n<ed))throw new Error("invalid float 32: "+n)}const Vr=Symbol("@bufbuild/protobuf/enum-type");function rd(n){const e=n[Vr];return te(e,"missing enum type on enum object"),e}function qr(n,e,t,i){n[Vr]=Kr(e,t.map(r=>({no:r.no,name:r.name,localName:n[r.no]})))}function Kr(n,e,t){const i=Object.create(null),r=Object.create(null),s=[];for(const a of e){const o=zr(a);s.push(o),i[a.name]=o,r[a.no]=o}return{typeName:n,values:s,findName(a){return i[a]},findNumber(a){return r[a]}}}function sd(n,e,t){const i={};for(const r of e){const s=zr(r);i[s.localName]=s.no,i[s.no]=s.localName}return qr(i,n,e),i}function zr(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class Xn{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(t);return r.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function ad(n,e,t,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),a={[s]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[s];return Object.setPrototypeOf(a.prototype,new Xn),Object.assign(a,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return n.util.equals(a,o,c)}}),a}function od(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,!(r&128))return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,!(t&128))return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,!(r&128))return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Zn(n,e,t){for(let s=0;s<28;s=s+7){const a=n>>>s,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const i=n>>>28&15|(e&7)<<4,r=!!(e>>3);if(t.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const a=e>>>s,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const hn=4294967296;function Wr(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,r=0;function s(a,o){const c=Number(n.slice(a,o));r*=t,i=i*t+c,i>=hn&&(r=r+(i/hn|0),i=i%hn)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Hr(i,r):ei(i,r)}function cd(n,e){let t=ei(n,e);const i=t.hi&2147483648;i&&(t=Hr(t.lo,t.hi));const r=Gr(t.lo,t.hi);return i?"-"+r:r}function Gr(n,e){if({lo:n,hi:e}=dd(n,e),e<=2097151)return String(hn*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,r=e>>16&65535;let s=t+i*6777216+r*6710656,a=i+r*8147497,o=r*2;const c=1e7;return s>=c&&(a+=Math.floor(s/c),s%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+Jr(a)+Jr(s)}function dd(n,e){return{lo:n>>>0,hi:e>>>0}}function ei(n,e){return{lo:n|0,hi:e|0}}function Hr(n,e){return e=~e,n?n=~n+1:e+=1,ei(n,e)}const Jr=n=>{const e=String(n);return"0000000".slice(e.length)+e};function $r(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function ld(){let n=this.buf[this.pos++],e=n&127;if(!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,!(n&128))return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;n&128&&t<10;t++)n=this.buf[this.pos++];if(n&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function ud(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>s||d<r)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>o||d<a)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=r=>te(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>te(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),Wr(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),Wr(r)},dec(r,s){return cd(r,s)},uDec(r,s){return Gr(r,s)}}}const Z=ud();var E;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(E||(E={}));var at;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(at||(at={}));function ot(n,e,t){if(e===t)return!0;if(n==E.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==t}return!1}function _t(n,e){switch(n){case E.BOOL:return!1;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==0?Z.zero:"0";case E.DOUBLE:case E.FLOAT:return 0;case E.BYTES:return new Uint8Array(0);case E.STRING:return"";default:return 0}}function Qr(n,e){switch(n){case E.BOOL:return e===!1;case E.STRING:return e==="";case E.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var ie;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ie||(ie={}));class hd{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Yn(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return un(e),$r(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Br(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Yn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){un(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return un(e),e=(e<<1^e>>31)>>>0,$r(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=Z.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=Z.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=Z.enc(e);return Zn(t.lo,t.hi,this.buf),this}sint64(e){let t=Z.enc(e),i=t.hi>>31,r=t.lo<<1^i,s=(t.hi<<1|t.lo>>>31)^i;return Zn(r,s,this.buf),this}uint64(e){let t=Z.uEnc(e);return Zn(t.lo,t.hi,this.buf),this}}class fd{constructor(e,t){this.varint64=od,this.uint32=ld,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ie.Varint:for(;this.buf[this.pos++]&128;);break;case ie.Bit64:this.pos+=4;case ie.Bit32:this.pos+=4;break;case ie.LengthDelimited:let r=this.uint32();this.pos+=r;break;case ie.StartGroup:for(;;){const[s,a]=this.tag();if(a===ie.EndGroup){if(t!==void 0&&s!==t)throw new Error("invalid end group tag");break}this.skip(a,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return Z.dec(...this.varint64())}uint64(){return Z.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,Z.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Z.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Z.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function md(n,e,t,i){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=n.util.newFieldList([s]).list()[0]}return r},runtime:n}}function Yr(n){const e=n.field.localName,t=Object.create(null);return t[e]=pd(n),[t,()=>t[e]]}function pd(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return _t(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function gd(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Je="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),fn=[];for(let n=0;n<Je.length;n++)fn[Je[n].charCodeAt(0)]=n;fn[45]=Je.indexOf("+"),fn[95]=Je.indexOf("/");const Xr={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,r=0,s,a=0;for(let o=0;o<n.length;o++){if(s=fn[n.charCodeAt(o)],s===void 0)switch(n[o]){case"=":r=0;case`
|
|
2
2
|
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:a=s,r=1;break;case 1:t[i++]=a<<2|(s&48)>>4,a=s,r=2;break;case 2:t[i++]=(a&15)<<4|(s&60)>>2,a=s,r=3;break;case 3:t[i++]=(a&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,r=0;for(let s=0;s<n.length;s++)switch(i=n[s],t){case 0:e+=Je[i>>2],r=(i&3)<<4,t=1;break;case 1:e+=Je[r|i>>4],r=(i&15)<<2,t=2;break;case 2:e+=Je[r|i>>6],e+=Je[i&63],t=0;break}return t&&(e+=Je[r],e+="=",t==1&&(e+="=")),e}};function vd(n,e,t){es(e,n);const i=e.runtime.bin.makeReadOptions(t),r=gd(n.getType().runtime.bin.listUnknownFields(n),e.field),[s,a]=Yr(e);for(const o of r)e.runtime.bin.readField(s,i.readerFactory(o.data),e.field,o.wireType,i);return a()}function yd(n,e,t,i){es(e,n);const r=e.runtime.bin.makeReadOptions(i),s=e.runtime.bin.makeWriteOptions(i);if(Zr(n,e)){const d=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of d)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const a=s.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,s);const c=r.readerFactory(a.finish());for(;c.pos<c.len;){const[d,l]=c.tag(),u=c.skip(l,d);n.getType().runtime.bin.onUnknownField(n,d,l,u)}}function Zr(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function es(n,e){te(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function ts(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!Qr(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function ns(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?_t(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function $e(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(Xn.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function is(n,e){return $e(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}E.DOUBLE,E.FLOAT,E.INT64,E.UINT64,E.INT32,E.UINT32,E.BOOL,E.STRING,E.BYTES;const rs={ignoreUnknownFields:!1},ss={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function bd(n){return n?Object.assign(Object.assign({},rs),n):rs}function kd(n){return n?Object.assign(Object.assign({},ss),n):ss}const mn=Symbol(),pn=Symbol();function Td(){return{makeReadOptions:bd,makeWriteOptions:kd,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(Be(e)));i=i??new n;const r=new Map,s=t.typeRegistry;for(const[a,o]of Object.entries(e)){const c=n.fields.findJsonName(a);if(c){if(c.oneof){if(o===null&&c.kind=="scalar")continue;const d=r.get(c.oneof);if(d!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(d,'", "').concat(a,'"'));r.set(c.oneof,a)}as(i,o,c,t,n)}else{let d=!1;if(s!=null&&s.findExtension&&a.startsWith("[")&&a.endsWith("]")){const l=s.findExtension(a.substring(1,a.length-1));if(l&&l.extendee.typeName==n.typeName){d=!0;const[u,h]=Yr(l);as(u,o,l.field,t,l),yd(i,l,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let r;try{for(r of t.fields.byNumber()){if(!ts(r,n)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!Cd(r))continue}const a=r.oneof?n[r.oneof.localName].value:n[r.localName],o=os(r,a,e);o!==void 0&&(i[e.useProtoFieldName?r.name:r.jsonName]=o)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(n)){const o=s.findExtensionFor(t.typeName,a.no);if(o&&Zr(n,o)){const c=vd(n,o,e),d=os(o.field,c,e);d!==void 0&&(i[o.field.jsonName]=d)}}}catch(s){const a=r?"cannot encode field ".concat(t.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=s instanceof Error?s.message:String(s);throw new Error(a+(o.length>0?": ".concat(o):""))}return i},readScalar(n,e,t){return Kt(n,e,t??at.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||Qr(n,e)))return gn(n,e)},debug:Be}}function Be(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function as(n,e,t,i,r){let s=t.localName;if(t.repeated){if(te(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Be(e)));const a=n[s];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Be(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,i));break;case"enum":const c=ti(t.T,o,i.ignoreUnknownFields,!0);c!==pn&&a.push(c);break;case"scalar":try{a.push(Kt(t.T,o,t.L,!0))}catch(d){let l="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Be(o));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Be(e)));const a=n[s];for(const[o,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: map value null"));let d;try{d=Sd(t.K,o)}catch(l){let u="cannot decode map key for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Be(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(t.V.kind){case"message":a[d]=t.V.T.fromJson(c,i);break;case"enum":const l=ti(t.V.T,c,i.ignoreUnknownFields,!0);l!==pn&&(a[d]=l);break;case"scalar":try{a[d]=Kt(t.V.T,c,at.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Be(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:s},s="value"),t.kind){case"message":const a=t.T;if(e===null&&a.typeName!="google.protobuf.Value")return;let o=n[s];$e(o)?o.fromJson(e,i):(n[s]=o=a.fromJson(e,i),a.fieldWrapper&&!t.oneof&&(n[s]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=ti(t.T,e,i.ignoreUnknownFields,!1);switch(c){case mn:ns(t,n);break;case pn:break;default:n[s]=c;break}break;case"scalar":try{const d=Kt(t.T,e,t.L,!1);switch(d){case mn:ns(t,n);break;default:n[s]=d;break}}catch(d){let l="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Be(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function Sd(n,e){if(n===E.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Kt(n,e,at.BIGINT,!0).toString()}function Kt(n,e,t,i){if(e===null)return i?_t(n,t):mn;switch(n){case E.DOUBLE:case E.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return n==E.FLOAT&&Br(r),r;case E.INT32:case E.FIXED32:case E.SFIXED32:case E.SINT32:case E.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return n==E.UINT32||n==E.FIXED32?Yn(s):un(s),s;case E.INT64:case E.SFIXED64:case E.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=Z.parse(e);return t?a.toString():a;case E.FIXED64:case E.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=Z.uParse(e);return t?o.toString():o;case E.BOOL:if(typeof e!="boolean")break;return e;case E.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case E.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Xr.dec(e)}throw new Error}function ti(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:mn;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=n.findName(e);if(r!==void 0)return r.no;if(t)return pn;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(Be(e)))}function Cd(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function os(n,e,t){if(n.kind=="map"){te(typeof e=="object"&&e!=null);const i={},r=Object.entries(e);switch(n.V.kind){case"scalar":for(const[a,o]of r)i[a.toString()]=gn(n.V.T,o);break;case"message":for(const[a,o]of r)i[a.toString()]=o.toJson(t);break;case"enum":const s=n.V.T;for(const[a,o]of r)i[a.toString()]=ni(s,o,t.enumAsInteger);break}return t.emitDefaultValues||r.length>0?i:void 0}if(n.repeated){te(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let r=0;r<e.length;r++)i.push(gn(n.T,e[r]));break;case"enum":for(let r=0;r<e.length;r++)i.push(ni(n.T,e[r],t.enumAsInteger));break;case"message":for(let r=0;r<e.length;r++)i.push(e[r].toJson(t));break}return t.emitDefaultValues||i.length>0?i:void 0}switch(n.kind){case"scalar":return gn(n.T,e);case"enum":return ni(n.T,e,t.enumAsInteger);case"message":return is(n.T,e).toJson(t)}}function ni(n,e,t){var i;if(te(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const r=n.findNumber(e);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:e}function gn(n,e){switch(n){case E.INT32:case E.SFIXED32:case E.SINT32:case E.FIXED32:case E.UINT32:return te(typeof e=="number"),e;case E.FLOAT:case E.DOUBLE:return te(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case E.STRING:return te(typeof e=="string"),e;case E.BOOL:return te(typeof e=="boolean"),e;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return te(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case E.BYTES:return te(e instanceof Uint8Array),Xr.enc(e)}}const It=Symbol("@bufbuild/protobuf/unknown-fields"),cs={readUnknownFields:!0,readerFactory:n=>new fd(n)},ds={writeUnknownFields:!0,writerFactory:()=>new hd};function Ed(n){return n?Object.assign(Object.assign({},cs),n):cs}function Pd(n){return n?Object.assign(Object.assign({},ds),n):ds}function wd(){return{makeReadOptions:Ed,makeWriteOptions:Pd,listUnknownFields(n){var e;return(e=n[It])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[It]},writeUnknownFields(n,e){const i=n[It];if(i)for(const r of i)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(n,e,t,i){const r=n;Array.isArray(r[It])||(r[It]=[]),r[It].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,r){const s=n.getType(),a=r?e.len:e.pos+t;let o,c;for(;e.pos<a&&([o,c]=e.tag(),!(r===!0&&c==ie.EndGroup));){const d=s.fields.find(o);if(!d){const l=e.skip(c,o);i.readUnknownFields&&this.onUnknownField(n,o,c,l);continue}ls(n,e,d,c,i)}if(r&&(c!=ie.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:ls,writeMessage(n,e,t){const i=n.getType();for(const r of i.fields.byNumber()){if(!ts(r,n)){if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?n[r.oneof.localName].value:n[r.localName];us(r,s,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&us(n,e,t,i)}}}function ls(n,e,t,i,r){let{repeated:s,localName:a}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=a&&delete n.value,n.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?E.INT32:t.T;let c=yn;if(t.kind=="scalar"&&t.L>0&&(c=_d),s){let h=n[a];if(i==ie.LengthDelimited&&o!=E.STRING&&o!=E.BYTES){let y=e.uint32()+e.pos;for(;e.pos<y;)h.push(c(e,o))}else h.push(c(e,o))}else n[a]=c(e,o);break;case"message":const d=t.T;s?n[a].push(vn(e,new d,r,t)):$e(n[a])?vn(e,n[a],r,t):(n[a]=vn(e,new d,r,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[a]=d.fieldWrapper.unwrapField(n[a])));break;case"map":let[l,u]=Rd(t,e,r);n[a][l]=u;break}}function vn(n,e,t,i){const r=e.getType().runtime.bin,s=i==null?void 0:i.delimited;return r.readMessage(e,n,s?i.no:n.uint32(),t,s),e}function Rd(n,e,t){const i=e.uint32(),r=e.pos+i;let s,a;for(;e.pos<r;){const[o]=e.tag();switch(o){case 1:s=yn(e,n.K);break;case 2:switch(n.V.kind){case"scalar":a=yn(e,n.V.T);break;case"enum":a=e.int32();break;case"message":a=vn(e,new n.V.T,t,void 0);break}break}}if(s===void 0&&(s=_t(n.K,at.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),a===void 0)switch(n.V.kind){case"scalar":a=_t(n.V.T,at.BIGINT);break;case"enum":a=n.V.T.values[0].no;break;case"message":a=new n.V.T;break}return[s,a]}function _d(n,e){const t=yn(n,e);return typeof t=="bigint"?t.toString():t}function yn(n,e){switch(e){case E.STRING:return n.string();case E.BOOL:return n.bool();case E.DOUBLE:return n.double();case E.FLOAT:return n.float();case E.INT32:return n.int32();case E.INT64:return n.int64();case E.UINT64:return n.uint64();case E.FIXED64:return n.fixed64();case E.BYTES:return n.bytes();case E.FIXED32:return n.fixed32();case E.SFIXED32:return n.sfixed32();case E.SFIXED64:return n.sfixed64();case E.SINT64:return n.sint64();case E.UINT32:return n.uint32();case E.SINT32:return n.sint32()}}function us(n,e,t,i){te(e!==void 0);const r=n.repeated;switch(n.kind){case"scalar":case"enum":let s=n.kind=="enum"?E.INT32:n.T;if(r)if(te(Array.isArray(e)),n.packed)Dd(t,s,n.no,e);else for(const a of e)zt(t,s,n.no,a);else zt(t,s,n.no,e);break;case"message":if(r){te(Array.isArray(e));for(const a of e)hs(t,i,n,a)}else hs(t,i,n,e);break;case"map":te(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))Id(t,i,n,a,o);break}}function Id(n,e,t,i,r){n.tag(t.no,ie.LengthDelimited),n.fork();let s=i;switch(t.K){case E.INT32:case E.FIXED32:case E.UINT32:case E.SFIXED32:case E.SINT32:s=Number.parseInt(i);break;case E.BOOL:te(i=="true"||i=="false"),s=i=="true";break}switch(zt(n,t.K,1,s),t.V.kind){case"scalar":zt(n,t.V.T,2,r);break;case"enum":zt(n,E.INT32,2,r);break;case"message":te(r!==void 0),n.tag(2,ie.LengthDelimited).bytes(r.toBinary(e));break}n.join()}function hs(n,e,t,i){const r=is(t.T,i);t.delimited?n.tag(t.no,ie.StartGroup).raw(r.toBinary(e)).tag(t.no,ie.EndGroup):n.tag(t.no,ie.LengthDelimited).bytes(r.toBinary(e))}function zt(n,e,t,i){te(i!==void 0);let[r,s]=fs(e);n.tag(t,r)[s](i)}function Dd(n,e,t,i){if(!i.length)return;n.tag(t,ie.LengthDelimited).fork();let[,r]=fs(e);for(let s=0;s<i.length;s++)n[r](i[s]);n.join()}function fs(n){let e=ie.Varint;switch(n){case E.BYTES:case E.STRING:e=ie.LengthDelimited;break;case E.DOUBLE:case E.FIXED64:case E.SFIXED64:e=ie.Bit64;break;case E.FIXED32:case E.SFIXED32:case E.FLOAT:e=ie.Bit32;break}const t=E[n].toLowerCase();return[e,t]}function Od(){return{setEnumType:qr,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const i of t.fields.byMember()){const r=i.localName,s=e,a=n;if(a[r]!=null)switch(i.kind){case"oneof":const o=a[r].case;if(o===void 0)continue;const c=i.findField(o);let d=a[r].value;c&&c.kind=="message"&&!$e(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===E.BYTES&&(d=Wt(d)),s[r]={case:o,value:d};break;case"scalar":case"enum":let l=a[r];i.T===E.BYTES&&(l=i.repeated?l.map(Wt):Wt(l)),s[r]=l;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===E.BYTES)for(const[m,y]of Object.entries(a[r]))s[r][m]=Wt(y);else Object.assign(s[r],a[r]);break;case"message":const h=i.V.T;for(const m of Object.keys(a[r])){let y=a[r][m];h.fieldWrapper||(y=new h(y)),s[r][m]=y}break}break;case"message":const u=i.T;if(i.repeated)s[r]=a[r].map(h=>$e(h,u)?h:new u(h));else{const h=a[r];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?s[r]=Wt(h):s[r]=h:s[r]=$e(h,u)?h:new u(h)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const r=e[i.localName],s=t[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((a,o)=>i.T.equals(a,s[o]));case"scalar":return r.every((a,o)=>ot(i.T,a,s[o]));case"enum":return r.every((a,o)=>ot(E.INT32,a,s[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let a=r,o=s;return i.T.fieldWrapper&&(a!==void 0&&!$e(a)&&(a=i.T.fieldWrapper.wrapField(a)),o!==void 0&&!$e(o)&&(o=i.T.fieldWrapper.wrapField(o))),i.T.equals(a,o);case"enum":return ot(E.INT32,r,s);case"scalar":return ot(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const c=i.findField(r.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(r.value,s.value);case"enum":return ot(E.INT32,r.value,s.value);case"scalar":return ot(c.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const d=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const l=i.V.T;return d.every(h=>l.equals(r[h],s[h]));case"enum":return d.every(h=>ot(E.INT32,r[h],s[h]));case"scalar":const u=i.V.T;return d.every(h=>ot(u,r[h],s[h]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const r of e.fields.byMember()){const s=n[r.localName];let a;if(r.repeated)a=s.map(bn);else if(r.kind=="map"){a=i[r.localName];for(const[o,c]of Object.entries(s))a[o]=bn(c)}else r.kind=="oneof"?a=r.findField(s.case)?{case:s.case,value:bn(s.value)}:{case:void 0}:a=bn(s);i[r.localName]=a}for(const r of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return t}}}function bn(n){if(n===void 0)return n;if($e(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function Wt(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function Md(n,e,t){return{syntax:n,json:Td(),bin:wd(),util:Object.assign(Object.assign({},Od()),{newFieldList:e,initFields:t}),makeMessageType(i,r,s){return ad(this,i,r,s)},makeEnum:sd,makeEnumType:Kr,getEnumType:rd,makeExtension(i,r,s){return md(this,i,r,s)}}}class Ad{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function ms(n,e){const t=ps(n);return e?t:jd(Fd(t))}function xd(n){return ms(n,!1)}const Ld=ps;function ps(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let r=n.charAt(i);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),t.push(r);break}}return t.join("")}const Nd=new Set(["constructor","toString","toJSON","valueOf"]),Ud=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),gs=n=>"".concat(n,"$"),Fd=n=>Ud.has(n)?gs(n):n,jd=n=>Nd.has(n)?gs(n):n;class Bd{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=xd(e)}addField(e){te(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function Vd(n,e){var t,i,r,s,a,o;const c=[];let d;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=ms(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Ld(l.name),u.repeated=(i=l.repeated)!==null&&i!==void 0?i:!1,l.kind=="scalar"&&(u.L=(r=l.L)!==null&&r!==void 0?r:at.BIGINT),u.delimited=(s=l.delimited)!==null&&s!==void 0?s:!1,u.req=(a=l.req)!==null&&a!==void 0?a:!1,u.opt=(o=l.opt)!==null&&o!==void 0?o:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=E.BYTES&&l.T!=E.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new Bd(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const b=Md("proto3",n=>new Ad(n,e=>Vd(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=_t(e.T,e.L);break}}});class ge extends Xn{constructor(e){super(),this.seconds=Z.zero,this.nanos=0,b.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(b.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=Z.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return ge.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ge({seconds:Z.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new ge().fromBinary(e,t)}static fromJson(e,t){return new ge().fromJson(e,t)}static fromJsonString(e,t){return new ge().fromJsonString(e,t)}static equals(e,t){return b.util.equals(ge,e,t)}}ge.runtime=b,ge.typeName="google.protobuf.Timestamp",ge.fields=b.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const qd=b.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ge},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Kd,repeated:!0},{no:5,name:"events",kind:"message",T:Wd,repeated:!0}]),Kd=b.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:zd,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),zd=b.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ge},{no:3,name:"value",kind:"scalar",T:2}]),Wd=b.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:ge},{no:7,name:"normalized_end_timestamp",kind:"message",T:ge,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),vs=b.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Pe=b.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),se=b.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),ii=b.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Gt=b.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ht=b.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),we=b.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),Dt=b.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),ys=b.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),oe=b.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),kn=b.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Tn,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:Ms}]),Tn=b.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Gd=b.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:b.getEnumType(se),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),vt=b.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:b.getEnumType(Ot)},{no:4,name:"tracks",kind:"message",T:At,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:Gd},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:b.getEnumType(Mt)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:b.getEnumType(we)},{no:18,name:"kind_details",kind:"enum",T:b.getEnumType(Hd),repeated:!0}]),Ot=b.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Mt=b.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Hd=b.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Se=b.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Jd=b.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:yt,repeated:!0}]),At=b.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:b.getEnumType(Pe)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:b.getEnumType(se)},{no:10,name:"layers",kind:"message",T:yt,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Jd,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:b.getEnumType(Se)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Ms},{no:19,name:"audio_features",kind:"enum",T:b.getEnumType(oe),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(vs)}]),yt=b.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(ii)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),ve=b.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:b.getEnumType(F)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:ks,oneof:"value"},{no:3,name:"speaker",kind:"message",T:$d,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Ts,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Qd,oneof:"value"},{no:8,name:"metrics",kind:"message",T:qd,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:ri,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Ss,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Cs,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Es,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:ai,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:oi,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:ci,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),F=b.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),$d=b.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:bs,repeated:!0}]),bs=b.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),ks=b.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),Ts=b.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Qd=b.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Yd,repeated:!0}]),Yd=b.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),ri=b.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),Ss=b.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),Cs=b.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Es=b.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Ps,oneof:"value"}]),Ps=b.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),ws=b.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Rs=b.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:b.getEnumType(_s)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),_s=b.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Xd=b.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:b.getEnumType(Is)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),Is=b.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),Ds=b.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Os},{no:2,name:"screen",kind:"message",T:Os},{no:3,name:"resume_connection",kind:"enum",T:b.getEnumType(Ht)},{no:4,name:"disabled_codecs",kind:"message",T:Zd},{no:5,name:"force_relay",kind:"enum",T:b.getEnumType(Ht)}]),Os=b.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:b.getEnumType(Ht)}]),Zd=b.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Tn,repeated:!0},{no:2,name:"publish",kind:"message",T:Tn,repeated:!0}]),Ms=b.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),si=b.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),As=b.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:b.getEnumType(si)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),xs=b.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),ai=b.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:b.getEnumType(Se)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:As,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:xs,oneof:"content_header"}],{localName:"DataStream_Header"}),oi=b.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),ci=b.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),Ae=b.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),di=b.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),el=b.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),tl=b.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:bt,oneof:"message"},{no:2,name:"answer",kind:"message",T:bt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:hi,oneof:"message"},{no:4,name:"add_track",kind:"message",T:ui,oneof:"message"},{no:5,name:"mute",kind:"message",T:fi,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Sn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Ns,oneof:"message"},{no:8,name:"leave",kind:"message",T:Cn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Fs,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:qs,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ks,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ve,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:js,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Gs,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Us,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:al,oneof:"message"}]),Ls=b.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:nl,oneof:"message"},{no:2,name:"answer",kind:"message",T:bt,oneof:"message"},{no:3,name:"offer",kind:"message",T:bt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:hi,oneof:"message"},{no:5,name:"update",kind:"message",T:sl,oneof:"message"},{no:6,name:"track_published",kind:"message",T:mi,oneof:"message"},{no:8,name:"leave",kind:"message",T:Cn,oneof:"message"},{no:9,name:"mute",kind:"message",T:fi,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ol,oneof:"message"},{no:11,name:"room_update",kind:"message",T:cl,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:ll,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:hl,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:ml,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:pl,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:rl,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:il,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:vl,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:kl,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Tl,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Sl,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:gl,oneof:"message"}]),li=b.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),ui=b.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:b.getEnumType(Pe)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:b.getEnumType(se)},{no:9,name:"layers",kind:"message",T:yt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:li,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:b.getEnumType(Se)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(vs)},{no:17,name:"audio_features",kind:"enum",T:b.getEnumType(oe),repeated:!0}]),hi=b.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:b.getEnumType(Ae)},{no:3,name:"final",kind:"scalar",T:8}]),fi=b.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),nl=b.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:kn},{no:2,name:"participant",kind:"message",T:vt},{no:3,name:"other_participants",kind:"message",T:vt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Bs,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:Ds},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Rs},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Tn,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),il=b.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Bs,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Ds},{no:3,name:"server_info",kind:"message",T:Rs},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),mi=b.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:At}]),rl=b.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),bt=b.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}]),sl=b.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:vt,repeated:!0}]),Sn=b.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:ws,repeated:!0}]),Ns=b.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:b.getEnumType(ii)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),Us=b.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:b.getEnumType(oe),repeated:!0}]),al=b.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),Cn=b.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:b.getEnumType(we)},{no:3,name:"action",kind:"enum",T:b.getEnumType(xt)},{no:4,name:"regions",kind:"message",T:yl}]),xt=b.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Fs=b.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:yt,repeated:!0}]),js=b.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),Bs=b.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),ol=b.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:bs,repeated:!0}]),cl=b.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:kn}]),dl=b.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:b.getEnumType(Gt)},{no:3,name:"score",kind:"scalar",T:2}]),ll=b.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:dl,repeated:!0}]),ul=b.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:b.getEnumType(di)}]),hl=b.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:ul,repeated:!0}]),pi=b.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(ii)},{no:2,name:"enabled",kind:"scalar",T:8}]),fl=b.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:pi,repeated:!0}]),ml=b.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:pi,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:fl,repeated:!0}]),Vs=b.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),qs=b.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Vs,repeated:!0}]),pl=b.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),gl=b.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:kn},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:vt},{no:4,name:"other_participants",kind:"message",T:vt,repeated:!0}]),Ks=b.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:bt},{no:2,name:"subscription",kind:"message",T:Sn},{no:3,name:"publish_tracks",kind:"message",T:mi,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ws,repeated:!0},{no:5,name:"offer",kind:"message",T:bt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:zs,repeated:!0}]),zs=b.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Ws=b.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:b.getEnumType(Ae)}]),Ve=b.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:b.getEnumType(el),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),Gs=b.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),vl=b.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),yl=b.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:bl,repeated:!0}]),bl=b.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),kl=b.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:b.getEnumType(ys)}]),Tl=b.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:b.getEnumType(gi)},{no:3,name:"message",kind:"scalar",T:9}]),gi=b.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Sl=b.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function Cl(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var En={exports:{}},El=En.exports,Hs;function Pl(){return Hs||(Hs=1,function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(El,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},a=null;function o(g,P){var S=g[P];if(typeof S.bind=="function")return S.bind(g);try{return Function.prototype.bind.call(S,g)}catch{return function(){return Function.prototype.apply.apply(S,[g,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&i?c:console[g]!==void 0?o(console,g):console.log!==void 0?o(console,"log"):e}function l(){for(var g=this.getLevel(),P=0;P<r.length;P++){var S=r[P];this[S]=P<g?e:this.methodFactory(S,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function u(g){return function(){typeof console!==t&&(l.call(this),this[g].apply(this,arguments))}}function h(g,P,S){return d(g)||u.apply(this,arguments)}function m(g,P){var S=this,w,D,p,v="loglevel";typeof g=="string"?v+=":"+g:typeof g=="symbol"&&(v=void 0);function T(O){var N=(r[O]||"silent").toUpperCase();if(!(typeof window===t||!v)){try{window.localStorage[v]=N;return}catch{}try{window.document.cookie=encodeURIComponent(v)+"="+N+";"}catch{}}}function x(){var O;if(!(typeof window===t||!v)){try{O=window.localStorage[v]}catch{}if(typeof O===t)try{var N=window.document.cookie,U=encodeURIComponent(v),G=N.indexOf(U+"=");G!==-1&&(O=/^([^;]+)/.exec(N.slice(G+U.length+1))[1])}catch{}return S.levels[O]===void 0&&(O=void 0),O}}function L(){if(!(typeof window===t||!v)){try{window.localStorage.removeItem(v)}catch{}try{window.document.cookie=encodeURIComponent(v)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function k(O){var N=O;if(typeof N=="string"&&S.levels[N.toUpperCase()]!==void 0&&(N=S.levels[N.toUpperCase()]),typeof N=="number"&&N>=0&&N<=S.levels.SILENT)return N;throw new TypeError("log.setLevel() called with invalid level: "+O)}S.name=g,S.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},S.methodFactory=P||h,S.getLevel=function(){return p??D??w},S.setLevel=function(O,N){return p=k(O),N!==!1&&T(p),l.call(S)},S.setDefaultLevel=function(O){D=k(O),x()||S.setLevel(O,!1)},S.resetLevel=function(){p=null,L(),l.call(S)},S.enableAll=function(O){S.setLevel(S.levels.TRACE,O)},S.disableAll=function(O){S.setLevel(S.levels.SILENT,O)},S.rebuild=function(){if(a!==S&&(w=k(a.getLevel())),l.call(S),a===S)for(var O in s)s[O].rebuild()},w=k(a?a.getLevel():"WARN");var I=x();I!=null&&(p=k(I)),l.call(S)}a=new m,a.getLogger=function(P){if(typeof P!="symbol"&&typeof P!="string"||P==="")throw new TypeError("You must supply a name when creating a logger.");var S=s[P];return S||(S=s[P]=new m(P,a.methodFactory)),S};var y=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=y),a},a.getLoggers=function(){return s},a.default=a,a})}(En)),En.exports}var Jt=Pl(),Lt;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(Lt||(Lt={}));var Re;(function(n){n.Default="livekit",n.Room="livekit-room",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee"})(Re||(Re={}));let V=Jt.getLogger("livekit");const Js=Object.values(Re).map(n=>Jt.getLogger(n));V.setDefaultLevel(Lt.info);function qe(n){const e=Jt.getLogger(n);return e.setDefaultLevel(V.getLevel()),e}function wl(n,e){if(e)Jt.getLogger(e).setLevel(n);else for(const t of Js)t.setLevel(n)}function Rl(n,e){(e?[e]:Js).forEach(i=>{const r=i.methodFactory;i.methodFactory=(s,a,o)=>{const c=r(s,a,o),d=Lt[s],l=d>=a&&d<Lt.silent;return(u,h)=>{h?c(u,h):c(u),l&&n(d,u,h)}},i.setLevel(i.getLevel())})}const _l=Jt.getLogger("lk-e2ee"),$t=7e3,Il=[0,300,2*2*300,3*3*300,4*4*300,$t,$t,$t,$t,$t];class $s{constructor(e){this._retryDelays=e!==void 0?[...e]:Il}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function Dl(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(n);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(n,i[r])&&(t[i[r]]=n[i[r]]);return t}function f(n,e,t,i){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(l){try{d(i.next(l))}catch(u){a(u)}}function c(l){try{d(i.throw(l))}catch(u){a(u)}}function d(l){l.done?s(l.value):r(l.value).then(o,c)}d((i=i.apply(n,e||[])).next())})}function Qs(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Qe(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof Qs=="function"?Qs(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(a){return new Promise(function(o,c){a=n[s](a),r(o,c,a.done,a.value)})}}function r(s,a,o,c){Promise.resolve(c).then(function(d){s({value:d,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;var Pn={exports:{}},Ys;function Ol(){if(Ys)return Pn.exports;Ys=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(v,T,x){return Function.prototype.apply.call(v,T,x)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(v){return Object.getOwnPropertyNames(v).concat(Object.getOwnPropertySymbols(v))}:t=function(v){return Object.getOwnPropertyNames(v)};function i(p){console&&console.warn&&console.warn(p)}var r=Number.isNaN||function(v){return v!==v};function s(){s.init.call(this)}Pn.exports=s,Pn.exports.once=S,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(p){if(typeof p!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof p)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(p){if(typeof p!="number"||p<0||r(p))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+p+".");a=p}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(v){if(typeof v!="number"||v<0||r(v))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+v+".");return this._maxListeners=v,this};function c(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(v){for(var T=[],x=1;x<arguments.length;x++)T.push(arguments[x]);var L=v==="error",k=this._events;if(k!==void 0)L=L&&k.error===void 0;else if(!L)return!1;if(L){var I;if(T.length>0&&(I=T[0]),I instanceof Error)throw I;var O=new Error("Unhandled error."+(I?" ("+I.message+")":""));throw O.context=I,O}var N=k[v];if(N===void 0)return!1;if(typeof N=="function")e(N,this,T);else for(var U=N.length,G=y(N,U),x=0;x<U;++x)e(G[x],this,T);return!0};function d(p,v,T,x){var L,k,I;if(o(T),k=p._events,k===void 0?(k=p._events=Object.create(null),p._eventsCount=0):(k.newListener!==void 0&&(p.emit("newListener",v,T.listener?T.listener:T),k=p._events),I=k[v]),I===void 0)I=k[v]=T,++p._eventsCount;else if(typeof I=="function"?I=k[v]=x?[T,I]:[I,T]:x?I.unshift(T):I.push(T),L=c(p),L>0&&I.length>L&&!I.warned){I.warned=!0;var O=new Error("Possible EventEmitter memory leak detected. "+I.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");O.name="MaxListenersExceededWarning",O.emitter=p,O.type=v,O.count=I.length,i(O)}return p}s.prototype.addListener=function(v,T){return d(this,v,T,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(v,T){return d(this,v,T,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(p,v,T){var x={fired:!1,wrapFn:void 0,target:p,type:v,listener:T},L=l.bind(x);return L.listener=T,x.wrapFn=L,L}s.prototype.once=function(v,T){return o(T),this.on(v,u(this,v,T)),this},s.prototype.prependOnceListener=function(v,T){return o(T),this.prependListener(v,u(this,v,T)),this},s.prototype.removeListener=function(v,T){var x,L,k,I,O;if(o(T),L=this._events,L===void 0)return this;if(x=L[v],x===void 0)return this;if(x===T||x.listener===T)--this._eventsCount===0?this._events=Object.create(null):(delete L[v],L.removeListener&&this.emit("removeListener",v,x.listener||T));else if(typeof x!="function"){for(k=-1,I=x.length-1;I>=0;I--)if(x[I]===T||x[I].listener===T){O=x[I].listener,k=I;break}if(k<0)return this;k===0?x.shift():g(x,k),x.length===1&&(L[v]=x[0]),L.removeListener!==void 0&&this.emit("removeListener",v,O||T)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(v){var T,x,L;if(x=this._events,x===void 0)return this;if(x.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):x[v]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete x[v]),this;if(arguments.length===0){var k=Object.keys(x),I;for(L=0;L<k.length;++L)I=k[L],I!=="removeListener"&&this.removeAllListeners(I);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(T=x[v],typeof T=="function")this.removeListener(v,T);else if(T!==void 0)for(L=T.length-1;L>=0;L--)this.removeListener(v,T[L]);return this};function h(p,v,T){var x=p._events;if(x===void 0)return[];var L=x[v];return L===void 0?[]:typeof L=="function"?T?[L.listener||L]:[L]:T?P(L):y(L,L.length)}s.prototype.listeners=function(v){return h(this,v,!0)},s.prototype.rawListeners=function(v){return h(this,v,!1)},s.listenerCount=function(p,v){return typeof p.listenerCount=="function"?p.listenerCount(v):m.call(p,v)},s.prototype.listenerCount=m;function m(p){var v=this._events;if(v!==void 0){var T=v[p];if(typeof T=="function")return 1;if(T!==void 0)return T.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function y(p,v){for(var T=new Array(v),x=0;x<v;++x)T[x]=p[x];return T}function g(p,v){for(;v+1<p.length;v++)p[v]=p[v+1];p.pop()}function P(p){for(var v=new Array(p.length),T=0;T<v.length;++T)v[T]=p[T].listener||p[T];return v}function S(p,v){return new Promise(function(T,x){function L(I){p.removeListener(v,k),x(I)}function k(){typeof p.removeListener=="function"&&p.removeListener("error",L),T([].slice.call(arguments))}D(p,v,k,{once:!0}),v!=="error"&&w(p,L,{once:!0})})}function w(p,v,T){typeof p.on=="function"&&D(p,"error",v,T)}function D(p,v,T,x){if(typeof p.on=="function")x.once?p.once(v,T):p.on(v,T);else if(typeof p.addEventListener=="function")p.addEventListener(v,function L(k){x.once&&p.removeEventListener(v,L),T(k)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof p)}return Pn.exports}var Ke=Ol();let Xs=!0,Zs=!0;function Qt(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function kt(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return r.apply(this,arguments);const c=d=>{const l=t(d);l&&(o.handleEvent?o.handleEvent(l):o(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),r.apply(this,[a,c])};const s=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(o))return s.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[a,c])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function Ml(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Xs=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function Al(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Zs=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function ea(){if(typeof window=="object"){if(Xs)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function vi(n,e){Zs&&console.warn(n+" is deprecated, please use "+e+" instead.")}function xl(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(r=>r.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Qt(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Qt(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Qt(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=Qt(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function ta(n){return Object.prototype.toString.call(n)==="[object Object]"}function na(n){return ta(n)?Object.keys(n).reduce(function(e,t){const i=ta(n[t]),r=i?na(n[t]):n[t],s=i&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):n}function yi(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?yi(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(r=>{yi(n,n.get(r),t)})}))}function ia(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return n.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{n.forEach(o=>{o.type===i&&o.trackId===a.id&&yi(n,o,r)})}),r}const ra=ea;function sa(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof o[d]=="object"?o[d]:{ideal:o[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,m){return h?h+m.charAt(0).toUpperCase()+m.slice(1):m==="deviceId"?"sourceId":m};if(l.ideal!==void 0){c.optional=c.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",d)]=l.ideal,c.optional.push(h),h={},h[u("max",d)]=l.ideal,c.optional.push(h)):(h[u("",d)]=l.ideal,c.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",d)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,d)]=l[h])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},r=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const l=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete o.video.facingMode;let u;if(d.exact==="environment"||d.ideal==="environment"?u=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(y=>y.kind==="videoinput");let m=h.find(y=>u.some(g=>y.label.toLowerCase().includes(g)));return!m&&h.length&&u.includes("back")&&(m=h[h.length-1]),m&&(o.video.deviceId=d.exact?{exact:m.deviceId}:{ideal:m.deviceId}),o.video=i(o.video),ra("chrome: "+JSON.stringify(o)),c(o)})}o.video=i(o.video)}return ra("chrome: "+JSON.stringify(o)),c(o)},s=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,d){r(o,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(s(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return r(c,d=>o(d).then(l=>{if(d.audio&&!l.getAudioTracks().length||d.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(s(l))))}}}function aa(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function oa(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",r=>{let s;n.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===r.track.id):s={track:r.track};const a=new Event("track");a.track=r.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(r=>{let s;n.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===r.id):s={track:r};const a=new Event("track");a.track=r,a.receiver=s,a.transceiver={receiver:s},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else kt(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function ca(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,c){let d=r.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function da(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=t.apply(this,[]);return s.forEach(a=>a._pc=this),s});const i=n.RTCPeerConnection.prototype.addTrack;i&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>ia(a,s.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const r=t.apply(this,[]);return r.forEach(s=>s._pc=this),r}),kt(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>ia(s,r.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const i=arguments[0];let r,s,a;return this.getSenders().forEach(o=>{o.track===i&&(r?a=!0:r=o)}),this.getReceivers().forEach(o=>(o.track===i&&(s?a=!0:s=o),o.track===i)),a||r&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function la(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),r.apply(this,arguments)}}function ua(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return la(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(m=>m.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}i.apply(this,[l])};const r=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(g=>g===l))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(g=>g.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const y=this._streams[u.id];if(y)y.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new n.MediaStream([l]);this._streams[u.id]=g,this._reverseStreams[g.id]=u,this.addStream(g)}return this.getSenders().find(g=>g.track===l)};function s(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const m=d._reverseStreams[h],y=d._streams[m.id];u=u.replace(new RegExp(y.id,"g"),m.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const m=d._reverseStreams[h],y=d._streams[m.id];u=u.replace(new RegExp(m.id,"g"),y.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(d){const l=n.RTCPeerConnection.prototype[d],u={[d](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[y=>{const g=s(this,y);h[0].apply(null,[g])},y=>{h[1]&&h[1].apply(null,y)},arguments[2]]):l.apply(this,arguments).then(y=>s(this,y))}};n.RTCPeerConnection.prototype[d]=u[d]});const o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:s(this,d)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(m=>{this._streams[m].getTracks().find(g=>l.track===g)&&(h=this._streams[m])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function bi(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=r[t]})}function ha(n,e){kt(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var fa=Object.freeze({__proto__:null,fixNegotiationNeeded:ha,shimAddTrackRemoveTrack:ua,shimAddTrackRemoveTrackWithNative:la,shimGetSendersWithDtmf:ca,shimGetUserMedia:sa,shimMediaStream:aa,shimOnTrack:oa,shimPeerConnection:bi,shimSenderReceiverGetStats:da});function ma(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(r,s,a){vi("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const r=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a.audio,"autoGainControl","mozAutoGainControl"),r(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return r(o,"mozAutoGainControl","autoGainControl"),r(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o,"autoGainControl","mozAutoGainControl"),r(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Ll(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function pa(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ki(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=n.RTCPeerConnection.prototype[r],a={[r](){return arguments[0]=new(r==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};n.RTCPeerConnection.prototype[r]=a[r]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[s,a,o]=arguments;return i.apply(this,[s||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((l,u)=>{c.set(u,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(a,o)}}function ga(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=t.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function va(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i}),kt(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ya(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){vi("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function ba(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function ka(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(r){const{sender:a}=s,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function Ta(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function Sa(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Ca(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var Ea=Object.freeze({__proto__:null,shimAddTransceiver:ka,shimCreateAnswer:Ca,shimCreateOffer:Sa,shimGetDisplayMedia:Ll,shimGetParameters:Ta,shimGetUserMedia:ma,shimOnTrack:pa,shimPeerConnection:ki,shimRTCDataChannel:ba,shimReceiverGetStats:va,shimRemoveStream:ya,shimSenderGetStats:ga});function Pa(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>e.call(this,r,i)),i.getVideoTracks().forEach(r=>e.call(this,r,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),a=1;a<r;a++)s[a-1]=arguments[a];return s&&s.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const r=t.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function wa(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function Ra(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h},e.createAnswer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h};let o=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(c,d,l){const u=a.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=o}function _a(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>i(Ia(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,r,s){e.mediaDevices.getUserMedia(i).then(r,s)}).bind(e))}function Ia(n){return n&&n.video!==void 0?Object.assign({},n,{video:na(n.video)}):n}function Da(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const s=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(vi("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(i.iceServers[a])}i.iceServers=s}return new e(i,r)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Oa(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ma(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Aa(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var xa=Object.freeze({__proto__:null,shimAudioContext:Aa,shimCallbacksAPI:Ra,shimConstraints:Ia,shimCreateOfferLegacy:Ma,shimGetUserMedia:_a,shimLocalStreamsAPI:Pa,shimRTCIceServerUrls:Da,shimRemoteStreamsAPI:wa,shimTrackEventTransceiver:Oa}),Ti={exports:{}},La;function Nl(){return La||(La=1,function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
|
|
3
3
|
`).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
|
|
4
4
|
m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as x, a as N, S as O, C as g, b as U, d as P, e as V, A as w, f as q, T as J } from "./index-
|
|
1
|
+
import { c as x, a as N, S as O, C as g, b as U, d as P, e as V, A as w, f as q, T as J } from "./index-DrArdZby.js";
|
|
2
2
|
function Q(u, T, h, i) {
|
|
3
3
|
const p = x(u, `${T}/v2/agents/${h}`, i);
|
|
4
4
|
return {
|
|
@@ -24,7 +24,7 @@ async function H(u, T, h) {
|
|
|
24
24
|
ConnectionState: C,
|
|
25
25
|
RemoteParticipant: z,
|
|
26
26
|
RemoteTrack: B
|
|
27
|
-
} = await W(), { callbacks: e, auth:
|
|
27
|
+
} = await W(), { callbacks: e, auth: _, baseURL: j, analytics: F } = h;
|
|
28
28
|
let a = null, v = !1, y = null, c = null;
|
|
29
29
|
const L = O.Fluent;
|
|
30
30
|
a = new p({
|
|
@@ -71,17 +71,17 @@ async function H(u, T, h) {
|
|
|
71
71
|
i("Failed to parse data channel message:", m);
|
|
72
72
|
}
|
|
73
73
|
}), (E = e.onConnectionStateChange) == null || E.call(e, g.New);
|
|
74
|
-
const
|
|
74
|
+
const M = Q(_, j || q, u, e.onError);
|
|
75
75
|
let f, A;
|
|
76
76
|
try {
|
|
77
|
-
const n = await
|
|
78
|
-
|
|
77
|
+
const n = await M.createStream({
|
|
78
|
+
transport_provider: J.Livekit
|
|
79
79
|
}), { agent_id: t, session_id: o, session_token: r, session_url: s } = n;
|
|
80
80
|
f = t, A = o, await a.connect(s, r), i("LiveKit room joined successfully");
|
|
81
81
|
} catch (n) {
|
|
82
82
|
throw i("Failed to connect to LiveKit room:", n), (K = e.onConnectionStateChange) == null || K.call(e, g.Fail), (I = e.onError) == null || I.call(e, n, { streamId: "" }), n;
|
|
83
83
|
}
|
|
84
|
-
|
|
84
|
+
F.enrich({
|
|
85
85
|
"stream-type": L
|
|
86
86
|
});
|
|
87
87
|
async function R(n) {
|
|
@@ -61,11 +61,17 @@ export interface ManagerCallbacks {
|
|
|
61
61
|
}) => void;
|
|
62
62
|
}
|
|
63
63
|
export type ManagerCallbackKeys = keyof ManagerCallbacks;
|
|
64
|
+
export interface StreamEndUserData {
|
|
65
|
+
distinct_id?: string;
|
|
66
|
+
plan?: string;
|
|
67
|
+
}
|
|
64
68
|
export interface TalkStreamOptions extends CreateTalkStreamRequest {
|
|
65
69
|
fluent?: boolean;
|
|
70
|
+
end_user_data?: StreamEndUserData;
|
|
66
71
|
}
|
|
67
72
|
export interface ClipStreamOptions extends CreateClipStreamRequest {
|
|
68
73
|
fluent?: boolean;
|
|
74
|
+
end_user_data?: StreamEndUserData;
|
|
69
75
|
}
|
|
70
76
|
export type CreateStreamOptions = TalkStreamOptions | ClipStreamOptions;
|
|
71
77
|
export type PayloadType<T> = T extends TalkStreamOptions ? SendTalkStreamPayload : T extends ClipStreamOptions ? SendClipStreamPayload : never;
|