@d-id/client-sdk 2.0.2 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,482 @@
1
+ import { c as Ne, C as B, S as l, a as ze, b as Be, A as m, d as Je, l as pe, e as Qe, t as We, f as w, g as U, h as qe, i as He, j as P, n as Xe } from "./index-DROeMYRR.js";
2
+ function Ze() {
3
+ try {
4
+ return Intl.DateTimeFormat().resolvedOptions().timeZone ?? "";
5
+ } catch {
6
+ return "";
7
+ }
8
+ }
9
+ function Ge() {
10
+ if (typeof navigator > "u")
11
+ return "";
12
+ const p = navigator.userAgent ?? "", C = (navigator.platform ?? "").toLowerCase();
13
+ let u = "Unknown";
14
+ /android/i.test(p) ? u = "Android" : /iphone|ipad|ipod/i.test(p) ? u = "iOS" : C.includes("win") ? u = "Windows" : C.includes("mac") ? u = "Mac OS X" : C.includes("linux") && (u = "Linux");
15
+ const i = u === "Android" || u === "iOS" || /Mobi/i.test(p);
16
+ return `${u}, ${i ? "Mobile" : "Desktop"}`;
17
+ }
18
+ function Ye() {
19
+ const p = {}, C = Ze();
20
+ C && (p.timezone = C);
21
+ const u = Ge();
22
+ return u && (p.device = u), p;
23
+ }
24
+ function en(p, C, u, i) {
25
+ const M = Ne(p, `${C}/v2/agents/${u}`, i);
26
+ return {
27
+ async createStream(g) {
28
+ return M.post("/sessions", g);
29
+ }
30
+ };
31
+ }
32
+ const nn = {
33
+ [l.ChatAnswer]: B.Answer,
34
+ [l.ChatPartial]: B.Partial
35
+ }, fe = 2e4;
36
+ async function tn() {
37
+ try {
38
+ return await import("./livekit-client.esm-DypJ_fOm.js");
39
+ } catch {
40
+ throw new Error(
41
+ "LiveKit client is required for this streaming manager. Please install it using: npm install livekit-client"
42
+ );
43
+ }
44
+ }
45
+ const on = {
46
+ excellent: U.Strong,
47
+ good: U.Strong,
48
+ poor: U.Weak,
49
+ lost: U.Unknown,
50
+ unknown: U.Unknown
51
+ }, K = (p = "Stream Error") => new Qe(p);
52
+ function ge(p, C, u) {
53
+ var i, M;
54
+ throw C("Failed to connect to LiveKit room:", p), (i = u.onConnectionStateChange) == null || i.call(u, w.Fail, "internal:init-error"), (M = u.onError) == null || M.call(u, p, { sessionId: "" }), p;
55
+ }
56
+ async function an(p, C, u) {
57
+ var ce;
58
+ const i = ze(u.debug || !1, "LiveKitStreamingManager"), { Room: M, RoomEvent: g, ConnectionState: k, Track: Z } = await tn(), { callbacks: n, auth: he, baseURL: me, analytics: G } = u;
59
+ let a = null, A = !1;
60
+ const Y = Be.Fluent;
61
+ let R = null;
62
+ const L = { isPublishing: !1, publication: null }, J = { isPublishing: !1, publication: null };
63
+ let h = null, S = null, j = null, D = !1;
64
+ a = new M({
65
+ adaptiveStream: !1,
66
+ // Must be false to use mediaStreamTrack directly
67
+ dynacast: !0
68
+ });
69
+ let E = null, b = m.Idle, V = !0;
70
+ const O = /* @__PURE__ */ new Set();
71
+ let N = null;
72
+ const Ce = en(he, me || Je, p, n.onError);
73
+ let T, I, $, ee = !0;
74
+ try {
75
+ const e = await Ce.createStream({
76
+ transport: C.transport,
77
+ chat_persist: C.chat_persist ?? !0,
78
+ verbose: u.verbose ?? !1
79
+ }), { id: t, session_token: o, session_url: r, interrupt_enabled: s } = e;
80
+ (ce = n.onStreamCreated) == null || ce.call(n, { session_id: t, stream_id: t, agent_id: p }), T = t, I = o, $ = r, ee = s ?? !0, await a.prepareConnection($, I);
81
+ } catch (e) {
82
+ ge(e, i, n);
83
+ }
84
+ if (!$ || !I || !T)
85
+ return Promise.reject(new Error("Failed to initialize LiveKit stream"));
86
+ a.on(g.ConnectionStateChanged, ye).on(g.ConnectionQualityChanged, ve).on(g.ParticipantConnected, we).on(g.ParticipantDisconnected, Ae).on(g.TrackSubscribed, Pe).on(g.TrackUnsubscribed, Re).on(g.DataReceived, $e).on(g.MediaDevicesError, _e).on(g.TranscriptionReceived, Se).on(g.EncryptionError, Ke).on(g.TrackSubscriptionFailed, De);
87
+ function Se(e, t) {
88
+ t != null && t.isLocal && pe.update();
89
+ }
90
+ async function Te() {
91
+ const e = Ye();
92
+ if (!(!a || Object.keys(e).length === 0))
93
+ try {
94
+ await a.localParticipant.setAttributes(e);
95
+ } catch (t) {
96
+ i("Failed to set user context attributes", t);
97
+ }
98
+ }
99
+ try {
100
+ await a.connect($, I), i("LiveKit room joined successfully"), Te(), E = setTimeout(() => {
101
+ var t;
102
+ i(
103
+ `Track subscription timeout - no track subscribed within ${fe / 1e3} seconds after connect`
104
+ ), E = null;
105
+ const e = K("Track subscription timeout");
106
+ G.track("connectivity-error", {
107
+ error: We(e),
108
+ sessionId: T
109
+ }), (t = n.onError) == null || t.call(n, e, { sessionId: T }), X("internal:track-subscription-timeout");
110
+ }, fe);
111
+ } catch (e) {
112
+ ge(e, i, n);
113
+ }
114
+ G.enrich({
115
+ "stream-type": Y
116
+ });
117
+ function ye(e) {
118
+ var t, o, r, s;
119
+ switch (i("Connection state changed:", e), e) {
120
+ case k.Connecting:
121
+ i("CALLBACK: onConnectionStateChange(Connecting)"), (t = n.onConnectionStateChange) == null || t.call(n, w.Connecting, "livekit:connecting");
122
+ break;
123
+ case k.Connected:
124
+ i("LiveKit room connected successfully"), A = !0;
125
+ break;
126
+ case k.Disconnected:
127
+ i("LiveKit room disconnected"), A = !1, D = !1, L.publication = null, J.publication = null, (o = n.onConnectionStateChange) == null || o.call(n, w.Disconnected, "livekit:disconnected");
128
+ break;
129
+ case k.Reconnecting:
130
+ i("LiveKit room reconnecting..."), (r = n.onConnectionStateChange) == null || r.call(n, w.Connecting, "livekit:reconnecting");
131
+ break;
132
+ case k.SignalReconnecting:
133
+ i("LiveKit room signal reconnecting..."), (s = n.onConnectionStateChange) == null || s.call(n, w.Connecting, "livekit:signal-reconnecting");
134
+ break;
135
+ }
136
+ }
137
+ function ve(e, t) {
138
+ var o;
139
+ i("Connection quality:", e), t != null && t.isLocal && ((o = n.onConnectivityStateChange) == null || o.call(n, on[e]));
140
+ }
141
+ function we(e) {
142
+ i("Participant connected:", e.identity);
143
+ }
144
+ function Ae(e) {
145
+ i("Participant disconnected:", e.identity), X("livekit:participant-disconnected");
146
+ }
147
+ function Ee() {
148
+ var e;
149
+ j !== P.Start && (i("CALLBACK: onVideoStateChange(Start)"), j = P.Start, (e = n.onVideoStateChange) == null || e.call(n, P.Start));
150
+ }
151
+ function ne(e) {
152
+ var t;
153
+ j !== P.Stop && (i("CALLBACK: onVideoStateChange(Stop)"), j = P.Stop, (t = n.onVideoStateChange) == null || t.call(n, P.Stop, e));
154
+ }
155
+ function Pe(e, t, o) {
156
+ var s, d, f;
157
+ i(`Track subscribed: ${e.kind} from ${o.identity}`);
158
+ const r = e.mediaStreamTrack;
159
+ if (!r) {
160
+ i(`No mediaStreamTrack available for ${e.kind}`);
161
+ return;
162
+ }
163
+ R ? (R.addTrack(r), i(`Added ${e.kind} track to shared MediaStream`)) : (R = new MediaStream([r]), i(`Created shared MediaStream with ${e.kind} track`)), e.kind === "audio" && (S = He(
164
+ () => e.getRTCStatsReport(),
165
+ ({ sttLatency: c, serviceLatency: y }) => {
166
+ var se, de, ue;
167
+ const F = pe.get(!0);
168
+ let x = 0;
169
+ if (c) {
170
+ const le = ((de = (se = h == null ? void 0 : h.getReport()) == null ? void 0 : se.webRTCStats) == null ? void 0 : de.avgRtt) ?? 0;
171
+ x = le > 0 ? Math.round(le * 1e3) : 0;
172
+ }
173
+ const _ = F > 0 ? F + (c ?? 0) + x : void 0, v = _ !== void 0 && y !== void 0 ? _ - y : void 0;
174
+ (ue = n.onFirstAudioDetected) == null || ue.call(n, { latency: _, networkLatency: v });
175
+ }
176
+ )), e.kind === "video" && ((s = n.onStreamReady) == null || s.call(n), i("CALLBACK: onSrcObjectReady"), (d = n.onSrcObjectReady) == null || d.call(n, R), D || (D = !0, i("CALLBACK: onConnectionStateChange(Connected)"), (f = n.onConnectionStateChange) == null || f.call(n, w.Connected, "livekit:track-subscribed")), h = qe(
177
+ () => e.getRTCStatsReport(),
178
+ () => A,
179
+ Xe,
180
+ (c, y) => {
181
+ i(`Video state change: ${c}`), c === P.Start ? (E && (clearTimeout(E), E = null, i("Track subscription timeout cleared")), Ee()) : c === P.Stop && ne(y);
182
+ }
183
+ ), h.start());
184
+ }
185
+ function Re(e, t, o) {
186
+ i(`Track unsubscribed: ${e.kind} from ${o.identity}`), e.kind === "audio" && (S == null || S.destroy(), S = null), e.kind === "video" && (ne(h == null ? void 0 : h.getReport()), h == null || h.stop(), h = null);
187
+ }
188
+ function te(e, t) {
189
+ var r;
190
+ const o = nn[e];
191
+ o && ((r = n.onMessage) == null || r.call(n, o, { event: o, ...t }));
192
+ }
193
+ function Q(e, t) {
194
+ var o, r, s, d, f;
195
+ if (e === l.ToolCallStarted) {
196
+ const c = t;
197
+ V = c.interruptible !== !1, (o = n.onInterruptibleChange) == null || o.call(n, V), O.add(c.call_id), b = m.ToolActive, (r = n.onAgentActivityStateChange) == null || r.call(n, m.ToolActive), (s = n.onToolEvent) == null || s.call(n, l.ToolCallStarted, c);
198
+ return;
199
+ }
200
+ if (e === l.ToolCallDone) {
201
+ const c = t;
202
+ ie(c.call_id), (d = n.onToolEvent) == null || d.call(n, l.ToolCallDone, c);
203
+ return;
204
+ }
205
+ if (e === l.ToolCallError) {
206
+ const c = t;
207
+ ie(c.call_id), (f = n.onToolEvent) == null || f.call(n, l.ToolCallError, c);
208
+ }
209
+ }
210
+ function ie(e) {
211
+ O.delete(e);
212
+ }
213
+ function Le(e, t) {
214
+ var o, r, s, d, f;
215
+ if (V = ((o = t.metadata) == null ? void 0 : o.interruptible) !== !1, (r = n.onInterruptibleChange) == null || r.call(n, V), e === l.StreamVideoCreated) {
216
+ b = m.Talking, (s = n.onAgentActivityStateChange) == null || s.call(n, m.Talking), S == null || S.arm({
217
+ sttLatency: (d = t == null ? void 0 : t.stt) == null ? void 0 : d.latency,
218
+ serviceLatency: t == null ? void 0 : t.serviceLatency
219
+ });
220
+ return;
221
+ }
222
+ if (O.size > 0) {
223
+ b !== m.ToolActive && (b = m.ToolActive, (f = n.onAgentActivityStateChange) == null || f.call(n, m.ToolActive));
224
+ return;
225
+ }
226
+ }
227
+ function z(e, t) {
228
+ var d, f, c, y;
229
+ const o = ((f = (d = h == null ? void 0 : h.getReport()) == null ? void 0 : d.webRTCStats) == null ? void 0 : f.avgRtt) ?? 0, r = o > 0 ? Math.round(o / 2 * 1e3) : 0, s = { ...t, downstreamNetworkLatency: r };
230
+ u.debug && ((c = t == null ? void 0 : t.metadata) != null && c.sentiment) && (s.sentiment = {
231
+ id: t.metadata.sentiment.id,
232
+ name: t.metadata.sentiment.sentiment
233
+ }), (y = n.onMessage) == null || y.call(n, e, s), Le(e, t);
234
+ }
235
+ function be(e, t) {
236
+ var o;
237
+ (o = n.onMessage) == null || o.call(n, B.Transcribe, { event: B.Transcribe, ...t }), queueMicrotask(() => {
238
+ var r;
239
+ (r = n.onAgentActivityStateChange) == null || r.call(n, m.Loading);
240
+ });
241
+ }
242
+ function Me(e, t) {
243
+ var o;
244
+ N = (t == null ? void 0 : t.turn_id) ?? null, b = m.Loading, (o = n.onAgentActivityStateChange) == null || o.call(n, m.Loading);
245
+ }
246
+ function ke(e, t) {
247
+ var r;
248
+ const o = (t == null ? void 0 : t.turn_id) ?? null;
249
+ N !== null && o !== null && o < N || (b = m.Idle, (r = n.onAgentActivityStateChange) == null || r.call(n, m.Idle));
250
+ }
251
+ const Ie = {
252
+ [l.ChatAnswer]: te,
253
+ [l.ChatPartial]: te,
254
+ [l.ToolCallStarted]: Q,
255
+ [l.ToolCallDone]: Q,
256
+ [l.ToolCallError]: Q,
257
+ [l.StreamVideoCreated]: z,
258
+ [l.StreamVideoDone]: z,
259
+ [l.StreamVideoError]: z,
260
+ [l.StreamVideoRejected]: z,
261
+ [l.ChatAudioTranscribed]: be,
262
+ [l.TurnStarted]: Me,
263
+ [l.TurnEnded]: ke
264
+ };
265
+ function $e(e, t, o, r) {
266
+ const s = new TextDecoder().decode(e);
267
+ try {
268
+ const d = JSON.parse(s), f = r || d.subject;
269
+ if (i("Data received:", { subject: f, data: d }), !f) return;
270
+ const c = Ie[f];
271
+ c == null || c(f, d);
272
+ } catch (d) {
273
+ i("Failed to parse data channel message:", d);
274
+ }
275
+ }
276
+ function _e(e) {
277
+ var t;
278
+ i("Media devices error:", e), (t = n.onError) == null || t.call(n, K(), { sessionId: T });
279
+ }
280
+ function Ke(e) {
281
+ var t;
282
+ i("Encryption error:", e), (t = n.onError) == null || t.call(n, K(), { sessionId: T });
283
+ }
284
+ function De(e, t, o) {
285
+ i("Track subscription failed:", { trackSid: e, participant: t, reason: o });
286
+ }
287
+ function Ve(e, t, o) {
288
+ for (const [r, s] of o)
289
+ if (s.source === t && s.track) {
290
+ const d = s.track.mediaStreamTrack;
291
+ if (d === e || (d == null ? void 0 : d.id) === e.id)
292
+ return s;
293
+ }
294
+ return null;
295
+ }
296
+ async function oe(e, t, o, r, s, d) {
297
+ var F, x, _;
298
+ if (!A || !a)
299
+ throw i(`Room is not connected, cannot publish ${r} stream`), new Error("Room is not connected");
300
+ if (e.isPublishing) {
301
+ i(`${r} publish already in progress, skipping`);
302
+ return;
303
+ }
304
+ const f = o(t);
305
+ if (f.length === 0)
306
+ throw new Error(`No ${r} track found in the provided MediaStream`);
307
+ const c = f[0], y = Ve(c, r, s());
308
+ if (y) {
309
+ i(`${r} track is already published, skipping`, {
310
+ trackId: c.id,
311
+ publishedTrackId: (x = (F = y.track) == null ? void 0 : F.mediaStreamTrack) == null ? void 0 : x.id
312
+ }), e.publication = y;
313
+ return;
314
+ }
315
+ if ((_ = e.publication) != null && _.track) {
316
+ const v = e.publication.track.mediaStreamTrack;
317
+ v !== c && (v == null ? void 0 : v.id) !== c.id && (i(`Unpublishing existing ${r} track before publishing new one`), await d());
318
+ }
319
+ i(`Publishing ${r} track from provided MediaStream`, { trackId: c.id }), e.isPublishing = !0;
320
+ try {
321
+ e.publication = await a.localParticipant.publishTrack(c, { source: r }), i(`${r} track published successfully`, { trackSid: e.publication.trackSid });
322
+ } catch (v) {
323
+ throw i(`Failed to publish ${r} track:`, v), v;
324
+ } finally {
325
+ e.isPublishing = !1;
326
+ }
327
+ }
328
+ async function re(e, t) {
329
+ if (!(!e.publication || !e.publication.track))
330
+ try {
331
+ a && (await a.localParticipant.unpublishTrack(e.publication.track, !1), i(`${t} track unpublished`));
332
+ } catch (o) {
333
+ i(`Error unpublishing ${t} track:`, o);
334
+ } finally {
335
+ e.publication = null;
336
+ }
337
+ }
338
+ async function Fe(e) {
339
+ return oe(
340
+ L,
341
+ e,
342
+ (t) => t.getAudioTracks(),
343
+ Z.Source.Microphone,
344
+ () => a.localParticipant.audioTrackPublications,
345
+ W
346
+ );
347
+ }
348
+ async function W() {
349
+ return re(L, "Microphone");
350
+ }
351
+ async function xe(e) {
352
+ if (!A || !a)
353
+ throw i("Cannot replace microphone track: room is not connected"), new Error("Room is not connected");
354
+ if (e.kind !== "audio")
355
+ throw i("Cannot replace microphone track: not an audio track", { kind: e.kind }), new Error("Microphone track must be an audio track");
356
+ if (L.isPublishing)
357
+ throw i("Cannot replace microphone track: publish in progress"), new Error("Microphone publish in progress");
358
+ const t = L.publication;
359
+ if (!t || !t.track)
360
+ throw i("Cannot replace microphone track: no publication to replace"), new Error("No microphone publication to replace");
361
+ try {
362
+ L.isPublishing = !0, await t.track.replaceTrack(e), i("Microphone track replaced", { trackId: e.id, trackSid: t.trackSid });
363
+ } finally {
364
+ L.isPublishing = !1;
365
+ }
366
+ }
367
+ async function Ue(e) {
368
+ return oe(
369
+ J,
370
+ e,
371
+ (t) => t.getVideoTracks(),
372
+ Z.Source.Camera,
373
+ () => a.localParticipant.videoTrackPublications,
374
+ q
375
+ );
376
+ }
377
+ async function q() {
378
+ return re(J, "Camera");
379
+ }
380
+ function je() {
381
+ R && (R.getTracks().forEach((e) => e.stop()), R = null);
382
+ }
383
+ async function H(e, t) {
384
+ var o, r;
385
+ if (!A || !a) {
386
+ i("Room is not connected for sending messages"), (o = n.onError) == null || o.call(n, K(), {
387
+ sessionId: T
388
+ });
389
+ return;
390
+ }
391
+ try {
392
+ await a.localParticipant.sendText(e, { topic: t }), i("Message sent successfully:", e);
393
+ } catch (s) {
394
+ i("Failed to send message:", s), (r = n.onError) == null || r.call(n, K(), { sessionId: T });
395
+ }
396
+ }
397
+ async function ae(e) {
398
+ var t;
399
+ try {
400
+ const r = JSON.parse(e).topic;
401
+ return H("", r);
402
+ } catch (o) {
403
+ i("Failed to send data channel message:", o), (t = n.onError) == null || t.call(n, K(), { sessionId: T });
404
+ }
405
+ }
406
+ function Oe(e) {
407
+ return H(
408
+ e,
409
+ "lk.chat"
410
+ /* Chat */
411
+ );
412
+ }
413
+ async function X(e) {
414
+ var t, o;
415
+ E && (clearTimeout(E), E = null), S == null || S.destroy(), S = null, a && ((t = n.onConnectionStateChange) == null || t.call(n, w.Disconnecting, e), await Promise.all([W(), q()]), await a.disconnect()), je(), A = !1, D = !1, O.clear(), N = null, (o = n.onAgentActivityStateChange) == null || o.call(n, m.Idle), b = m.Idle;
416
+ }
417
+ return {
418
+ speak(e) {
419
+ const t = typeof e == "string" ? e : JSON.stringify(e);
420
+ return H(
421
+ t,
422
+ "did.speak"
423
+ /* Speak */
424
+ );
425
+ },
426
+ disconnect: () => X("user:disconnect"),
427
+ async reconnect() {
428
+ var e, t;
429
+ if ((a == null ? void 0 : a.state) === k.Connected) {
430
+ i("Room is already connected");
431
+ return;
432
+ }
433
+ if (!a || !$ || !I)
434
+ throw i("Cannot reconnect: missing room, URL or token"), new Error("Cannot reconnect: session not available");
435
+ i("Reconnecting to LiveKit room, state:", a.state), D = !1, (e = n.onConnectionStateChange) == null || e.call(n, w.Connecting, "user:reconnect");
436
+ try {
437
+ if (await a.connect($, I), i("Room reconnected"), A = !0, a.remoteParticipants.size === 0) {
438
+ if (i("Waiting for agent to join..."), !await new Promise((r) => {
439
+ const s = setTimeout(() => {
440
+ a == null || a.off(g.ParticipantConnected, d), r(!1);
441
+ }, 5e3), d = () => {
442
+ clearTimeout(s), a == null || a.off(g.ParticipantConnected, d), r(!0);
443
+ };
444
+ a == null || a.on(g.ParticipantConnected, d);
445
+ }))
446
+ throw i("Agent did not join within timeout"), await a.disconnect(), new Error("Agent did not rejoin the room");
447
+ i("Agent joined, reconnection successful");
448
+ }
449
+ } catch (o) {
450
+ throw i("Failed to reconnect:", o), (t = n.onConnectionStateChange) == null || t.call(n, w.Fail, "user:reconnect-failed"), o;
451
+ }
452
+ },
453
+ sendDataChannelMessage: ae,
454
+ sendTextMessage: Oe,
455
+ publishMicrophoneStream: Fe,
456
+ unpublishMicrophoneStream: W,
457
+ replaceMicrophoneTrack: xe,
458
+ publishCameraStream: Ue,
459
+ unpublishCameraStream: q,
460
+ interrupt(e) {
461
+ e !== "text" && ae(JSON.stringify({
462
+ topic: "did.interrupt"
463
+ /* Interrupt */
464
+ }));
465
+ },
466
+ registerRpcMethod(e, t) {
467
+ a == null || a.registerRpcMethod(e, t);
468
+ },
469
+ unregisterRpcMethod(e) {
470
+ a == null || a.unregisterRpcMethod(e);
471
+ },
472
+ sessionId: T,
473
+ streamId: T,
474
+ streamType: Y,
475
+ interruptAvailable: ee,
476
+ isInterruptible: V
477
+ };
478
+ }
479
+ export {
480
+ an as createLiveKitStreamingManager,
481
+ ge as handleInitError
482
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@d-id/client-sdk",
3
3
  "private": false,
4
- "version": "2.0.2",
4
+ "version": "2.0.3",
5
5
  "type": "module",
6
6
  "description": "d-id client sdk",
7
7
  "repository": {