@cuekit-ai/react 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5363,7 +5363,7 @@ function supportsAV1() {
5363
5363
  if (!("getCapabilities" in RTCRtpSender)) {
5364
5364
  return false;
5365
5365
  }
5366
- if (isSafari()) {
5366
+ if (isSafari() || isFireFox()) {
5367
5367
  return false;
5368
5368
  }
5369
5369
  const capabilities = RTCRtpSender.getCapabilities("video");
@@ -5460,9 +5460,9 @@ function isE2EESimulcastSupported() {
5460
5460
  if (browser) {
5461
5461
  if (browser.name !== "Safari" && browser.os !== "iOS") {
5462
5462
  return true;
5463
- } else if (browser.os === "iOS" && browser.osVersion && compareVersions(supportedSafariVersion, browser.osVersion) >= 0) {
5463
+ } else if (browser.os === "iOS" && browser.osVersion && compareVersions(browser.osVersion, supportedSafariVersion) >= 0) {
5464
5464
  return true;
5465
- } else if (browser.name === "Safari" && compareVersions(supportedSafariVersion, browser.version) >= 0) {
5465
+ } else if (browser.name === "Safari" && compareVersions(browser.version, supportedSafariVersion) >= 0) {
5466
5466
  return true;
5467
5467
  } else {
5468
5468
  return false;
@@ -5641,13 +5641,13 @@ function unwrapConstraint(constraint) {
5641
5641
  if (Array.isArray(constraint)) {
5642
5642
  return constraint[0];
5643
5643
  }
5644
- if (constraint.exact) {
5644
+ if (constraint.exact !== void 0) {
5645
5645
  if (Array.isArray(constraint.exact)) {
5646
5646
  return constraint.exact[0];
5647
5647
  }
5648
5648
  return constraint.exact;
5649
5649
  }
5650
- if (constraint.ideal) {
5650
+ if (constraint.ideal !== void 0) {
5651
5651
  if (Array.isArray(constraint.ideal)) {
5652
5652
  return constraint.ideal[0];
5653
5653
  }
@@ -5870,7 +5870,7 @@ function constraintsForOptions(options) {
5870
5870
  function detectSilence(track_1) {
5871
5871
  return __awaiter(this, arguments, void 0, function(track) {
5872
5872
  let timeOffset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 200;
5873
- return function* () {
5873
+ return (function* () {
5874
5874
  const ctx = getNewAudioContext();
5875
5875
  if (ctx) {
5876
5876
  const analyser = ctx.createAnalyser();
@@ -5886,7 +5886,7 @@ function detectSilence(track_1) {
5886
5886
  return !someNoise;
5887
5887
  }
5888
5888
  return false;
5889
- }();
5889
+ })();
5890
5890
  });
5891
5891
  }
5892
5892
  function getNewAudioContext() {
@@ -7610,7 +7610,7 @@ function isIPPrivate(address) {
7610
7610
  }
7611
7611
  return false;
7612
7612
  }
7613
- var e, h, o, _, FLOAT32_MAX, FLOAT32_MIN, UINT32_MAX, INT32_MAX, INT32_MIN, enumTypeSymbol, Message, TWO_PWR_32_DBL, decimalFrom1e7WithLeadingZeros, protoInt64, ScalarType, LongType, WireType, BinaryWriter, BinaryReader, encTable, decTable, protoBase64, jsonReadDefaults, jsonWriteDefaults, tokenNull, tokenIgnoredUnknownEnum, unknownFieldsSymbol, readDefaults, writeDefaults, InternalFieldList, fieldJsonName, reservedObjectProperties, reservedMessageProperties, fallback, safeMessageProperty, safeObjectProperty, InternalOneofInfo, proto3, Timestamp, MetricsBatch, TimeSeriesMetric, MetricSample, EventMetric, BackupCodecPolicy$1, TrackType, TrackSource, VideoQuality$1, ConnectionQuality$1, ClientConfigSetting, DisconnectReason, ReconnectReason, SubscriptionError, AudioTrackFeature, Room$1, Codec, ParticipantPermission, ParticipantInfo, ParticipantInfo_State, ParticipantInfo_Kind, ParticipantInfo_KindDetail, Encryption_Type, SimulcastCodecInfo, TrackInfo, VideoLayer, DataPacket, DataPacket_Kind, ActiveSpeakerUpdate, SpeakerInfo, UserPacket, SipDTMF, Transcription, TranscriptionSegment, ChatMessage, RpcRequest, RpcAck, RpcResponse, RpcError$1, ParticipantTracks, ServerInfo, ServerInfo_Edition, ClientInfo, ClientInfo_SDK, ClientConfiguration, VideoConfiguration, DisabledCodecs, TimedVersion, DataStream_OperationType, DataStream_TextHeader, DataStream_ByteHeader, DataStream_Header, DataStream_Chunk, DataStream_Trailer, SignalTarget, StreamState, CandidateProtocol, SignalRequest, SignalResponse, SimulcastCodec, AddTrackRequest, TrickleRequest, MuteTrackRequest, JoinResponse, ReconnectResponse, TrackPublishedResponse, TrackUnpublishedResponse, SessionDescription, ParticipantUpdate, UpdateSubscription, UpdateTrackSettings, UpdateLocalAudioTrack, UpdateLocalVideoTrack, LeaveRequest, LeaveRequest_Action, UpdateVideoLayers, UpdateParticipantMetadata, ICEServer, SpeakersChanged, RoomUpdate, ConnectionQualityInfo, ConnectionQualityUpdate, StreamStateInfo, StreamStateUpdate, SubscribedQuality, SubscribedCodec, SubscribedQualityUpdate, TrackPermission, SubscriptionPermission, SubscriptionPermissionUpdate, RoomMovedResponse, SyncState, DataChannelReceiveState, DataChannelInfo, SimulateScenario, Ping, Pong, RegionSettings, RegionInfo, SubscriptionResponse, RequestResponse, RequestResponse_Reason, TrackSubscribed, loglevel$1, loglevel, hasRequiredLoglevel, loglevelExports, LogLevel, LoggerNames, livekitLogger, livekitLoggers, workerLogger, maxRetryDelay, DEFAULT_RETRY_DELAYS_IN_MS, DefaultReconnectPolicy, events, hasRequiredEvents, eventsExports, logDisabled_, deprecationWarnings_, logging, chromeShim, firefoxShim, safariShim, sdp$1, hasRequiredSdp, sdpExports, SDPUtils, sdp, commonShim, DECRYPTION_FAILURE_TOLERANCE, E2EE_FLAG, SALT, KEY_PROVIDER_DEFAULTS, KeyProviderEvent, KeyHandlerEvent, EncryptionEvent, CryptorEvent, BaseKeyProvider, LivekitError, ConnectionErrorReason, ConnectionError, DeviceUnsupportedError, TrackInvalidError, UnsupportedServer, UnexpectedConnectionState, NegotiationError, PublishTrackError, SignalRequestError, MediaDeviceFailure, CryptorErrorReason, RoomEvent, ParticipantEvent, EngineEvent, TrackEvent, commonVersionIdentifier, browserDetails, browsersList, version$1, version, protocolVersion, CriticalTimers, BACKGROUND_REACTION_DELAY, recycledElements, VideoQuality, Track, VideoPreset, backupCodecs, videoCodecs, BackupCodecPolicy, AudioPresets, VideoPresets, VideoPresets43, ScreenSharePresets, separator, ddExtensionURI, resizeObserver, getResizeObserver, intersectionObserver, getIntersectionObserver, emptyAudioStreamTrack, Future, E2EEManager, defaultId, DeviceManager, QueueTaskStatus, AsyncQueue, passThroughQueueSignals, SignalConnectionState, SignalClient, DataPacketBuffer, TTLMap, lib, parser, grammar, hasRequiredGrammar, hasRequiredParser, writer, hasRequiredWriter, hasRequiredLib, libExports, startBitrateForSVC, debounceInterval, PCEvents, PCTransport, defaultVideoCodec, publishDefaults, audioDefaults, videoDefaults, roomOptionDefaults, roomConnectOptionDefaults, PCTransportState, PCTransportManager, RpcError, MAX_PAYLOAD_BYTES, monitorFrequency, isMediaRecorderAvailable, FallbackRecorder, RecorderBase, LocalTrackRecorder, DEFAULT_DIMENSIONS_TIMEOUT, PRE_CONNECT_BUFFER_TIMEOUT, LocalTrack, LocalAudioTrack, presets169, presets43, presetsScreenShare, defaultSimulcastPresets169, defaultSimulcastPresets43, computeDefaultScreenShareSimulcastPresets, videoRids, ScalabilityMode, refreshSubscribedCodecAfterNewCodec, LocalVideoTrack, lossyDataChannel, reliableDataChannel, minReconnectWait, leaveReconnect, reliabeReceiveStateTTL, PCState, RTCEngine, SignalReconnectError, RegionUrlProvider, BaseStreamReader, ByteStreamReader, TextStreamReader, BaseStreamWriter, TextStreamWriter, ByteStreamWriter, RemoteTrack, RemoteAudioTrack, REACTION_DELAY, RemoteVideoTrack, HTMLElementInfo, TrackPublication, LocalTrackPublication, ConnectionQuality, Participant, STREAM_CHUNK_SIZE, LocalParticipant, RemoteTrackPublication, RemoteParticipant, ConnectionState, connectionReconcileFrequency, Room, CheckStatus, Checker, CloudRegionCheck, TEST_DURATION, ConnectionProtocolCheck, PublishAudioCheck, PublishVideoCheck, ReconnectCheck, TURNCheck, WebRTCCheck, WebSocketCheck, ConnectionCheck;
7613
+ var e, h, o, _, FLOAT32_MAX, FLOAT32_MIN, UINT32_MAX, INT32_MAX, INT32_MIN, enumTypeSymbol, Message, TWO_PWR_32_DBL, decimalFrom1e7WithLeadingZeros, protoInt64, ScalarType, LongType, WireType, BinaryWriter, BinaryReader, encTable, decTable, protoBase64, jsonReadDefaults, jsonWriteDefaults, tokenNull, tokenIgnoredUnknownEnum, unknownFieldsSymbol, readDefaults, writeDefaults, InternalFieldList, fieldJsonName, reservedObjectProperties, reservedMessageProperties, fallback, safeMessageProperty, safeObjectProperty, InternalOneofInfo, proto3, Timestamp, MetricsBatch, TimeSeriesMetric, MetricSample, EventMetric, BackupCodecPolicy$1, TrackType, TrackSource, VideoQuality$1, ConnectionQuality$1, ClientConfigSetting, DisconnectReason, ReconnectReason, SubscriptionError, AudioTrackFeature, Room$1, Codec, ParticipantPermission, ParticipantInfo, ParticipantInfo_State, ParticipantInfo_Kind, ParticipantInfo_KindDetail, Encryption_Type, SimulcastCodecInfo, TrackInfo, VideoLayer, DataPacket, DataPacket_Kind, ActiveSpeakerUpdate, SpeakerInfo, UserPacket, SipDTMF, Transcription, TranscriptionSegment, ChatMessage, RpcRequest, RpcAck, RpcResponse, RpcError$1, ParticipantTracks, ServerInfo, ServerInfo_Edition, ClientInfo, ClientInfo_SDK, ClientConfiguration, VideoConfiguration, DisabledCodecs, TimedVersion, DataStream_OperationType, DataStream_TextHeader, DataStream_ByteHeader, DataStream_Header, DataStream_Chunk, DataStream_Trailer, SignalTarget, StreamState, CandidateProtocol, SignalRequest, SignalResponse, SimulcastCodec, AddTrackRequest, TrickleRequest, MuteTrackRequest, JoinResponse, ReconnectResponse, TrackPublishedResponse, TrackUnpublishedResponse, SessionDescription, ParticipantUpdate, UpdateSubscription, UpdateTrackSettings, UpdateLocalAudioTrack, UpdateLocalVideoTrack, LeaveRequest, LeaveRequest_Action, UpdateVideoLayers, UpdateParticipantMetadata, ICEServer, SpeakersChanged, RoomUpdate, ConnectionQualityInfo, ConnectionQualityUpdate, StreamStateInfo, StreamStateUpdate, SubscribedQuality, SubscribedCodec, SubscribedQualityUpdate, TrackPermission, SubscriptionPermission, SubscriptionPermissionUpdate, RoomMovedResponse, SyncState, DataChannelReceiveState, DataChannelInfo, SimulateScenario, Ping, Pong, RegionSettings, RegionInfo, SubscriptionResponse, RequestResponse, RequestResponse_Reason, TrackSubscribed, loglevel$1, loglevel, hasRequiredLoglevel, loglevelExports, LogLevel, LoggerNames, livekitLogger, livekitLoggers, workerLogger, maxRetryDelay, DEFAULT_RETRY_DELAYS_IN_MS, DefaultReconnectPolicy, events, hasRequiredEvents, eventsExports, logDisabled_, deprecationWarnings_, logging, chromeShim, firefoxShim, safariShim, sdp$1, hasRequiredSdp, sdpExports, SDPUtils, sdp, commonShim, DECRYPTION_FAILURE_TOLERANCE, E2EE_FLAG, SALT, KEY_PROVIDER_DEFAULTS, KeyProviderEvent, KeyHandlerEvent, EncryptionEvent, CryptorEvent, BaseKeyProvider, LivekitError, ConnectionErrorReason, ConnectionError, DeviceUnsupportedError, TrackInvalidError, UnsupportedServer, UnexpectedConnectionState, NegotiationError, PublishTrackError, SignalRequestError, DataStreamErrorReason, DataStreamError, MediaDeviceFailure, CryptorErrorReason, RoomEvent, ParticipantEvent, EngineEvent, TrackEvent, commonVersionIdentifier, browserDetails, browsersList, version$1, version, protocolVersion, CriticalTimers, BACKGROUND_REACTION_DELAY, recycledElements, VideoQuality, Track, VideoPreset, backupCodecs, videoCodecs, BackupCodecPolicy, AudioPresets, VideoPresets, VideoPresets43, ScreenSharePresets, separator, ddExtensionURI, resizeObserver, getResizeObserver, intersectionObserver, getIntersectionObserver, emptyAudioStreamTrack, Future, E2EEManager, defaultId, DeviceManager, QueueTaskStatus, AsyncQueue, passThroughQueueSignals, SignalConnectionState, SignalClient, DataPacketBuffer, TTLMap, lib, parser, grammar, hasRequiredGrammar, hasRequiredParser, writer, hasRequiredWriter, hasRequiredLib, libExports, startBitrateForSVC, debounceInterval, PCEvents, PCTransport, defaultVideoCodec, publishDefaults, audioDefaults, videoDefaults, roomOptionDefaults, roomConnectOptionDefaults, PCTransportState, PCTransportManager, RpcError, MAX_PAYLOAD_BYTES, monitorFrequency, isMediaRecorderAvailable, FallbackRecorder, RecorderBase, LocalTrackRecorder, DEFAULT_DIMENSIONS_TIMEOUT, PRE_CONNECT_BUFFER_TIMEOUT, LocalTrack, LocalAudioTrack, presets169, presets43, presetsScreenShare, defaultSimulcastPresets169, defaultSimulcastPresets43, computeDefaultScreenShareSimulcastPresets, videoRids, ScalabilityMode, refreshSubscribedCodecAfterNewCodec, LocalVideoTrack, lossyDataChannel, reliableDataChannel, minReconnectWait, leaveReconnect, reliabeReceiveStateTTL, PCState, RTCEngine, SignalReconnectError, RegionUrlProvider, BaseStreamReader, ByteStreamReader, TextStreamReader, IncomingDataStreamManager, BaseStreamWriter, TextStreamWriter, ByteStreamWriter, STREAM_CHUNK_SIZE, OutgoingDataStreamManager, RemoteTrack, RemoteAudioTrack, REACTION_DELAY, RemoteVideoTrack, HTMLElementInfo, TrackPublication, LocalTrackPublication, ConnectionQuality, Participant, LocalParticipant, RemoteTrackPublication, RemoteParticipant, ConnectionState, connectionReconcileFrequency, Room, CheckStatus, Checker, CloudRegionCheck, TEST_DURATION, ConnectionProtocolCheck, PublishAudioCheck, PublishVideoCheck, ReconnectCheck, TURNCheck, WebRTCCheck, WebSocketCheck, ConnectionCheck;
7614
7614
  var init_livekit_client_esm = __esm({
7615
7615
  "node_modules/livekit-client/dist/livekit-client.esm.mjs"() {
7616
7616
  "use strict";
@@ -11486,6 +11486,22 @@ var init_livekit_client_esm = __esm({
11486
11486
  this.reasonName = typeof reason === "string" ? reason : RequestResponse_Reason[reason];
11487
11487
  }
11488
11488
  };
11489
+ (function(DataStreamErrorReason2) {
11490
+ DataStreamErrorReason2[DataStreamErrorReason2["AlreadyOpened"] = 0] = "AlreadyOpened";
11491
+ DataStreamErrorReason2[DataStreamErrorReason2["AbnormalEnd"] = 1] = "AbnormalEnd";
11492
+ DataStreamErrorReason2[DataStreamErrorReason2["DecodeFailed"] = 2] = "DecodeFailed";
11493
+ DataStreamErrorReason2[DataStreamErrorReason2["LengthExceeded"] = 3] = "LengthExceeded";
11494
+ DataStreamErrorReason2[DataStreamErrorReason2["Incomplete"] = 4] = "Incomplete";
11495
+ DataStreamErrorReason2[DataStreamErrorReason2["HandlerAlreadyRegistered"] = 7] = "HandlerAlreadyRegistered";
11496
+ })(DataStreamErrorReason || (DataStreamErrorReason = {}));
11497
+ DataStreamError = class extends LivekitError {
11498
+ constructor(message, reason) {
11499
+ super(16, message);
11500
+ this.name = "DataStreamError";
11501
+ this.reason = reason;
11502
+ this.reasonName = DataStreamErrorReason[reason];
11503
+ }
11504
+ };
11489
11505
  (function(MediaDeviceFailure2) {
11490
11506
  MediaDeviceFailure2["PermissionDenied"] = "PermissionDenied";
11491
11507
  MediaDeviceFailure2["NotFound"] = "NotFound";
@@ -11697,7 +11713,7 @@ var init_livekit_client_esm = __esm({
11697
11713
  }
11698
11714
  }
11699
11715
  ];
11700
- version$1 = "2.15.4";
11716
+ version$1 = "2.15.6";
11701
11717
  version = version$1;
11702
11718
  protocolVersion = 16;
11703
11719
  CriticalTimers = class {
@@ -11723,13 +11739,24 @@ var init_livekit_client_esm = __esm({
11723
11739
  VideoQuality2[VideoQuality2["HIGH"] = 2] = "HIGH";
11724
11740
  })(VideoQuality || (VideoQuality = {}));
11725
11741
  Track = class _Track extends eventsExports.EventEmitter {
11742
+ /**
11743
+ * indicates current state of stream, it'll indicate `paused` if the track
11744
+ * has been paused by congestion controller
11745
+ */
11746
+ get streamState() {
11747
+ return this._streamState;
11748
+ }
11749
+ /** @internal */
11750
+ setStreamState(value) {
11751
+ this._streamState = value;
11752
+ }
11726
11753
  constructor(mediaTrack, kind) {
11727
11754
  let loggerOptions = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
11728
11755
  var _a;
11729
11756
  super();
11730
11757
  this.attachedElements = [];
11731
11758
  this.isMuted = false;
11732
- this.streamState = _Track.StreamState.Active;
11759
+ this._streamState = _Track.StreamState.Active;
11733
11760
  this.isInBackground = false;
11734
11761
  this._currentBitrate = 0;
11735
11762
  this.log = livekitLogger;
@@ -12262,6 +12289,20 @@ var init_livekit_client_esm = __esm({
12262
12289
  room2.localParticipant.on(ParticipantEvent.LocalSenderCreated, (sender, track) => __awaiter(this, void 0, void 0, function* () {
12263
12290
  this.setupE2EESender(track, sender);
12264
12291
  }));
12292
+ room2.localParticipant.on(ParticipantEvent.LocalTrackPublished, (publication) => {
12293
+ if (!isVideoTrack(publication.track) || !isSafariBased()) {
12294
+ return;
12295
+ }
12296
+ const msg = {
12297
+ kind: "updateCodec",
12298
+ data: {
12299
+ trackId: publication.track.mediaStreamID,
12300
+ codec: mimeTypeToVideoCodecString(publication.trackInfo.codecs[0].mimeType),
12301
+ participantIdentity: this.room.localParticipant.identity
12302
+ }
12303
+ };
12304
+ this.worker.postMessage(msg);
12305
+ });
12265
12306
  keyProvider.on(KeyProviderEvent.SetKey, (keyInfo) => this.postKey(keyInfo)).on(KeyProviderEvent.RatchetRequest, (participantId, keyIndex) => this.postRatchetRequest(participantId, keyIndex));
12266
12307
  }
12267
12308
  postRatchetRequest(participantIdentity, keyIndex) {
@@ -12472,7 +12513,7 @@ var init_livekit_client_esm = __esm({
12472
12513
  return __awaiter(this, arguments, void 0, function(kind) {
12473
12514
  var _this = this;
12474
12515
  let requestPermissions = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
12475
- return function* () {
12516
+ return (function* () {
12476
12517
  var _a;
12477
12518
  if (((_a = _DeviceManager.userMediaPromiseMap) === null || _a === void 0 ? void 0 : _a.size) > 0) {
12478
12519
  livekitLogger.debug("awaiting getUserMedia promise");
@@ -12515,7 +12556,7 @@ var init_livekit_client_esm = __esm({
12515
12556
  devices = devices.filter((device) => device.kind === kind);
12516
12557
  }
12517
12558
  return devices;
12518
- }();
12559
+ })();
12519
12560
  });
12520
12561
  }
12521
12562
  normalizeDeviceId(kind, deviceId, groupId) {
@@ -12796,7 +12837,7 @@ var init_livekit_client_esm = __esm({
12796
12837
  return __awaiter(this, arguments, void 0, function() {
12797
12838
  var _this = this;
12798
12839
  let updateState = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
12799
- return function* () {
12840
+ return (function* () {
12800
12841
  const unlock = yield _this.closingLock.lock();
12801
12842
  try {
12802
12843
  _this.clearPingInterval();
@@ -12828,7 +12869,7 @@ var init_livekit_client_esm = __esm({
12828
12869
  }
12829
12870
  unlock();
12830
12871
  }
12831
- }();
12872
+ })();
12832
12873
  });
12833
12874
  }
12834
12875
  // initial offer after joining
@@ -12882,7 +12923,7 @@ var init_livekit_client_esm = __esm({
12882
12923
  return __awaiter(this, arguments, void 0, function(metadata, name2) {
12883
12924
  var _this2 = this;
12884
12925
  let attributes = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
12885
- return function* () {
12926
+ return (function* () {
12886
12927
  const requestId = _this2.getNextRequestId();
12887
12928
  yield _this2.sendRequest({
12888
12929
  case: "updateMetadata",
@@ -12894,7 +12935,7 @@ var init_livekit_client_esm = __esm({
12894
12935
  })
12895
12936
  });
12896
12937
  return requestId;
12897
- }();
12938
+ })();
12898
12939
  });
12899
12940
  }
12900
12941
  sendUpdateTrackSettings(settings) {
@@ -12974,7 +13015,7 @@ var init_livekit_client_esm = __esm({
12974
13015
  return __awaiter(this, arguments, void 0, function(message) {
12975
13016
  var _this3 = this;
12976
13017
  let fromQueue = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
12977
- return function* () {
13018
+ return (function* () {
12978
13019
  const canQueue = !fromQueue && !canPassThroughQueue(message);
12979
13020
  if (canQueue && _this3.state === SignalConnectionState.RECONNECTING) {
12980
13021
  _this3.queuedRequests.push(() => __awaiter(_this3, void 0, void 0, function* () {
@@ -13010,7 +13051,7 @@ var init_livekit_client_esm = __esm({
13010
13051
  error: e3
13011
13052
  }));
13012
13053
  }
13013
- }();
13054
+ })();
13014
13055
  });
13015
13056
  }
13016
13057
  handleSignalResponse(res) {
@@ -14076,7 +14117,7 @@ var init_livekit_client_esm = __esm({
14076
14117
  return __awaiter(this, arguments, void 0, function(pcTransport, abortController) {
14077
14118
  var _this = this;
14078
14119
  let timeout = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : this.peerConnectionTimeout;
14079
- return function* () {
14120
+ return (function* () {
14080
14121
  const connectionState = pcTransport.getConnectionState();
14081
14122
  if (connectionState === "connected") {
14082
14123
  return;
@@ -14106,7 +14147,7 @@ var init_livekit_client_esm = __esm({
14106
14147
  abortController === null || abortController === void 0 ? void 0 : abortController.signal.removeEventListener("abort", abortHandler);
14107
14148
  resolve();
14108
14149
  }));
14109
- }();
14150
+ })();
14110
14151
  });
14111
14152
  }
14112
14153
  };
@@ -14287,9 +14328,14 @@ var init_livekit_client_esm = __esm({
14287
14328
  this.providedByUser = userProvidedTrack;
14288
14329
  this.muteLock = new _();
14289
14330
  this.pauseUpstreamLock = new _();
14290
- this.processorLock = new _();
14291
- this.restartLock = new _();
14292
- this.setMediaStreamTrack(mediaTrack, true);
14331
+ this.trackChangeLock = new _();
14332
+ this.trackChangeLock.lock().then((unlock) => __awaiter(this, void 0, void 0, function* () {
14333
+ try {
14334
+ yield this.setMediaStreamTrack(mediaTrack, true);
14335
+ } finally {
14336
+ unlock();
14337
+ }
14338
+ }));
14293
14339
  this._constraints = mediaTrack.getConstraints();
14294
14340
  if (constraints) {
14295
14341
  this._constraints = constraints;
@@ -14358,25 +14404,20 @@ var init_livekit_client_esm = __esm({
14358
14404
  }
14359
14405
  let processedTrack;
14360
14406
  if (this.processor && newTrack) {
14361
- const unlock = yield this.processorLock.lock();
14362
- try {
14363
- this.log.debug("restarting processor", this.logContext);
14364
- if (this.kind === "unknown") {
14365
- throw TypeError("cannot set processor on track of unknown kind");
14366
- }
14367
- if (this.processorElement) {
14368
- attachToElement(newTrack, this.processorElement);
14369
- this.processorElement.muted = true;
14370
- }
14371
- yield this.processor.restart({
14372
- track: newTrack,
14373
- kind: this.kind,
14374
- element: this.processorElement
14375
- });
14376
- processedTrack = this.processor.processedTrack;
14377
- } finally {
14378
- unlock();
14407
+ this.log.debug("restarting processor", this.logContext);
14408
+ if (this.kind === "unknown") {
14409
+ throw TypeError("cannot set processor on track of unknown kind");
14379
14410
  }
14411
+ if (this.processorElement) {
14412
+ attachToElement(newTrack, this.processorElement);
14413
+ this.processorElement.muted = true;
14414
+ }
14415
+ yield this.processor.restart({
14416
+ track: newTrack,
14417
+ kind: this.kind,
14418
+ element: this.processorElement
14419
+ });
14420
+ processedTrack = this.processor.processedTrack;
14380
14421
  }
14381
14422
  if (this.sender && ((_a = this.sender.transport) === null || _a === void 0 ? void 0 : _a.state) !== "closed") {
14382
14423
  yield this.sender.replaceTrack(processedTrack !== null && processedTrack !== void 0 ? processedTrack : newTrack);
@@ -14398,7 +14439,7 @@ var init_livekit_client_esm = __esm({
14398
14439
  return __awaiter(this, arguments, void 0, function() {
14399
14440
  var _this = this;
14400
14441
  let timeout = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : DEFAULT_DIMENSIONS_TIMEOUT;
14401
- return function* () {
14442
+ return (function* () {
14402
14443
  var _a;
14403
14444
  if (_this.kind === Track.Kind.Audio) {
14404
14445
  throw new Error("cannot get dimensions for audio tracks");
@@ -14415,7 +14456,7 @@ var init_livekit_client_esm = __esm({
14415
14456
  yield sleep(50);
14416
14457
  }
14417
14458
  throw new TrackInvalidError("unable to get track dimensions after timeout");
14418
- }();
14459
+ })();
14419
14460
  });
14420
14461
  }
14421
14462
  setDeviceId(deviceId) {
@@ -14438,7 +14479,7 @@ var init_livekit_client_esm = __esm({
14438
14479
  return __awaiter(this, arguments, void 0, function() {
14439
14480
  var _this2 = this;
14440
14481
  let normalize3 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
14441
- return function* () {
14482
+ return (function* () {
14442
14483
  if (_this2.source === Track.Source.ScreenShare) {
14443
14484
  return;
14444
14485
  }
@@ -14448,7 +14489,7 @@ var init_livekit_client_esm = __esm({
14448
14489
  } = _this2._mediaStreamTrack.getSettings();
14449
14490
  const kind = _this2.kind === Track.Kind.Audio ? "audioinput" : "videoinput";
14450
14491
  return normalize3 ? DeviceManager.getInstance().normalizeDeviceId(kind, deviceId, groupId) : deviceId;
14451
- }();
14492
+ })();
14452
14493
  });
14453
14494
  }
14454
14495
  mute() {
@@ -14465,30 +14506,35 @@ var init_livekit_client_esm = __esm({
14465
14506
  }
14466
14507
  replaceTrack(track, userProvidedOrOptions) {
14467
14508
  return __awaiter(this, void 0, void 0, function* () {
14468
- if (!this.sender) {
14469
- throw new TrackInvalidError("unable to replace an unpublished track");
14470
- }
14471
- let userProvidedTrack;
14472
- let stopProcessor;
14473
- if (typeof userProvidedOrOptions === "boolean") {
14474
- userProvidedTrack = userProvidedOrOptions;
14475
- } else if (userProvidedOrOptions !== void 0) {
14476
- userProvidedTrack = userProvidedOrOptions.userProvidedTrack;
14477
- stopProcessor = userProvidedOrOptions.stopProcessor;
14478
- }
14479
- this.providedByUser = userProvidedTrack !== null && userProvidedTrack !== void 0 ? userProvidedTrack : true;
14480
- this.log.debug("replace MediaStreamTrack", this.logContext);
14481
- yield this.setMediaStreamTrack(track);
14482
- if (stopProcessor && this.processor) {
14483
- yield this.stopProcessor();
14509
+ const unlock = yield this.trackChangeLock.lock();
14510
+ try {
14511
+ if (!this.sender) {
14512
+ throw new TrackInvalidError("unable to replace an unpublished track");
14513
+ }
14514
+ let userProvidedTrack;
14515
+ let stopProcessor;
14516
+ if (typeof userProvidedOrOptions === "boolean") {
14517
+ userProvidedTrack = userProvidedOrOptions;
14518
+ } else if (userProvidedOrOptions !== void 0) {
14519
+ userProvidedTrack = userProvidedOrOptions.userProvidedTrack;
14520
+ stopProcessor = userProvidedOrOptions.stopProcessor;
14521
+ }
14522
+ this.providedByUser = userProvidedTrack !== null && userProvidedTrack !== void 0 ? userProvidedTrack : true;
14523
+ this.log.debug("replace MediaStreamTrack", this.logContext);
14524
+ yield this.setMediaStreamTrack(track);
14525
+ if (stopProcessor && this.processor) {
14526
+ yield this.internalStopProcessor();
14527
+ }
14528
+ return this;
14529
+ } finally {
14530
+ unlock();
14484
14531
  }
14485
- return this;
14486
14532
  });
14487
14533
  }
14488
14534
  restart(constraints) {
14489
14535
  return __awaiter(this, void 0, void 0, function* () {
14490
14536
  this.manuallyStopped = false;
14491
- const unlock = yield this.restartLock.lock();
14537
+ const unlock = yield this.trackChangeLock.lock();
14492
14538
  try {
14493
14539
  if (!constraints) {
14494
14540
  constraints = this._constraints;
@@ -14510,9 +14556,9 @@ var init_livekit_client_esm = __esm({
14510
14556
  facingMode
14511
14557
  } : true;
14512
14558
  } else {
14513
- streamConstraints.audio = deviceId ? {
14559
+ streamConstraints.audio = deviceId ? Object.assign({
14514
14560
  deviceId
14515
- } : true;
14561
+ }, otherConstraints) : true;
14516
14562
  }
14517
14563
  this.attachedElements.forEach((el) => {
14518
14564
  detachTrack(this.mediaStreamTrack, el);
@@ -14521,7 +14567,9 @@ var init_livekit_client_esm = __esm({
14521
14567
  this._mediaStreamTrack.stop();
14522
14568
  const mediaStream = yield navigator.mediaDevices.getUserMedia(streamConstraints);
14523
14569
  const newTrack = mediaStream.getTracks()[0];
14524
- yield newTrack.applyConstraints(otherConstraints);
14570
+ if (this.kind === Track.Kind.Video) {
14571
+ yield newTrack.applyConstraints(otherConstraints);
14572
+ }
14525
14573
  newTrack.addEventListener("ended", this.handleEnded);
14526
14574
  this.log.debug("re-acquired MediaStreamTrack", this.logContext);
14527
14575
  yield this.setMediaStreamTrack(newTrack);
@@ -14660,9 +14708,9 @@ var init_livekit_client_esm = __esm({
14660
14708
  return __awaiter(this, arguments, void 0, function(processor) {
14661
14709
  var _this3 = this;
14662
14710
  let showProcessedStreamLocally = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
14663
- return function* () {
14711
+ return (function* () {
14664
14712
  var _a;
14665
- const unlock = yield _this3.processorLock.lock();
14713
+ const unlock = yield _this3.trackChangeLock.lock();
14666
14714
  try {
14667
14715
  _this3.log.debug("setting up processor", _this3.logContext);
14668
14716
  const processorElement = document.createElement(_this3.kind);
@@ -14675,7 +14723,7 @@ var init_livekit_client_esm = __esm({
14675
14723
  yield processor.init(processorOptions);
14676
14724
  _this3.log.debug("processor initialized", _this3.logContext);
14677
14725
  if (_this3.processor) {
14678
- yield _this3.stopProcessor();
14726
+ yield _this3.internalStopProcessor();
14679
14727
  }
14680
14728
  if (_this3.kind === "unknown") {
14681
14729
  throw TypeError("cannot set processor on track of unknown kind");
@@ -14715,7 +14763,7 @@ var init_livekit_client_esm = __esm({
14715
14763
  } finally {
14716
14764
  unlock();
14717
14765
  }
14718
- }();
14766
+ })();
14719
14767
  });
14720
14768
  }
14721
14769
  getProcessor() {
@@ -14732,21 +14780,40 @@ var init_livekit_client_esm = __esm({
14732
14780
  return __awaiter(this, arguments, void 0, function() {
14733
14781
  var _this4 = this;
14734
14782
  let keepElement = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
14735
- return function* () {
14783
+ return (function* () {
14784
+ const unlock = yield _this4.trackChangeLock.lock();
14785
+ try {
14786
+ yield _this4.internalStopProcessor(keepElement);
14787
+ } finally {
14788
+ unlock();
14789
+ }
14790
+ })();
14791
+ });
14792
+ }
14793
+ /**
14794
+ * @internal
14795
+ * This method assumes the caller has acquired a trackChangeLock already.
14796
+ * The public facing method for stopping the processor is `stopProcessor` and it wraps this method in the trackChangeLock.
14797
+ */
14798
+ internalStopProcessor() {
14799
+ return __awaiter(this, arguments, void 0, function() {
14800
+ var _this5 = this;
14801
+ let keepElement = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
14802
+ return (function* () {
14736
14803
  var _a, _b;
14737
- if (!_this4.processor) return;
14738
- _this4.log.debug("stopping processor", _this4.logContext);
14739
- (_a = _this4.processor.processedTrack) === null || _a === void 0 ? void 0 : _a.stop();
14740
- yield _this4.processor.destroy();
14741
- _this4.processor = void 0;
14804
+ if (!_this5.processor) return;
14805
+ _this5.log.debug("stopping processor", _this5.logContext);
14806
+ (_a = _this5.processor.processedTrack) === null || _a === void 0 ? void 0 : _a.stop();
14807
+ yield _this5.processor.destroy();
14808
+ _this5.processor = void 0;
14742
14809
  if (!keepElement) {
14743
- (_b = _this4.processorElement) === null || _b === void 0 ? void 0 : _b.remove();
14744
- _this4.processorElement = void 0;
14810
+ (_b = _this5.processorElement) === null || _b === void 0 ? void 0 : _b.remove();
14811
+ _this5.processorElement = void 0;
14745
14812
  }
14746
- yield _this4._mediaStreamTrack.applyConstraints(_this4._constraints);
14747
- yield _this4.setMediaStreamTrack(_this4._mediaStreamTrack, true);
14748
- _this4.emit(TrackEvent.TrackProcessorUpdate);
14749
- }();
14813
+ yield _this5._mediaStreamTrack.applyConstraints(_this5._constraints);
14814
+ yield _this5.setMediaStreamTrack(_this5._mediaStreamTrack, true);
14815
+ _this5.emit(TrackEvent.TrackProcessorUpdate);
14816
+ })();
14750
14817
  });
14751
14818
  }
14752
14819
  /** @internal */
@@ -14934,13 +15001,13 @@ var init_livekit_client_esm = __esm({
14934
15001
  setProcessor(processor) {
14935
15002
  return __awaiter(this, void 0, void 0, function* () {
14936
15003
  var _a;
14937
- const unlock = yield this.processorLock.lock();
15004
+ const unlock = yield this.trackChangeLock.lock();
14938
15005
  try {
14939
15006
  if (!isReactNative() && !this.audioContext) {
14940
15007
  throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");
14941
15008
  }
14942
15009
  if (this.processor) {
14943
- yield this.stopProcessor();
15010
+ yield this.internalStopProcessor();
14944
15011
  }
14945
15012
  const processorOptions = {
14946
15013
  kind: this.kind,
@@ -15355,7 +15422,7 @@ var init_livekit_client_esm = __esm({
15355
15422
  return __awaiter(this, arguments, void 0, function(processor) {
15356
15423
  var _this = this;
15357
15424
  let showProcessedStreamLocally = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
15358
- return function* () {
15425
+ return (function* () {
15359
15426
  var _a, e_4, _b, _c;
15360
15427
  var _d, _e;
15361
15428
  yield _super.setProcessor.call(_this, processor, showProcessedStreamLocally);
@@ -15379,7 +15446,7 @@ var init_livekit_client_esm = __esm({
15379
15446
  }
15380
15447
  }
15381
15448
  }
15382
- }();
15449
+ })();
15383
15450
  });
15384
15451
  }
15385
15452
  setDegradationPreference(preference) {
@@ -15603,7 +15670,7 @@ var init_livekit_client_esm = __esm({
15603
15670
  let {
15604
15671
  channel
15605
15672
  } = _ref;
15606
- return function* () {
15673
+ return (function* () {
15607
15674
  if (!channel) {
15608
15675
  return;
15609
15676
  }
@@ -15616,7 +15683,7 @@ var init_livekit_client_esm = __esm({
15616
15683
  }
15617
15684
  _this.log.debug("on data channel ".concat(channel.id, ", ").concat(channel.label), _this.logContext);
15618
15685
  channel.onmessage = _this.handleDataMessage;
15619
- }();
15686
+ })();
15620
15687
  });
15621
15688
  this.handleDataMessage = (message) => __awaiter(this, void 0, void 0, function* () {
15622
15689
  var _a2, _b;
@@ -16499,7 +16566,7 @@ var init_livekit_client_esm = __esm({
16499
16566
  return __awaiter(this, arguments, void 0, function(kind) {
16500
16567
  var _this2 = this;
16501
16568
  let subscriber = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this.subscriberPrimary;
16502
- return function* () {
16569
+ return (function* () {
16503
16570
  var _a;
16504
16571
  if (!_this2.pcManager) {
16505
16572
  throw new UnexpectedConnectionState("PC manager is closed");
@@ -16532,7 +16599,7 @@ var init_livekit_client_esm = __esm({
16532
16599
  yield sleep(50);
16533
16600
  }
16534
16601
  throw new ConnectionError("could not establish ".concat(transportName, " connection, state: ").concat(transport.getICEConnectionState()), ConnectionErrorReason.InternalError);
16535
- }();
16602
+ })();
16536
16603
  });
16537
16604
  }
16538
16605
  ensurePublisherConnected(kind) {
@@ -16775,30 +16842,72 @@ var init_livekit_client_esm = __esm({
16775
16842
  get info() {
16776
16843
  return this._info;
16777
16844
  }
16778
- constructor(info, stream, totalByteSize) {
16845
+ /** @internal */
16846
+ validateBytesReceived() {
16847
+ let doneReceiving = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
16848
+ if (typeof this.totalByteSize !== "number" || this.totalByteSize === 0) {
16849
+ return;
16850
+ }
16851
+ if (doneReceiving && this.bytesReceived < this.totalByteSize) {
16852
+ throw new DataStreamError("Not enough chunk(s) received - expected ".concat(this.totalByteSize, " bytes of data total, only received ").concat(this.bytesReceived, " bytes"), DataStreamErrorReason.Incomplete);
16853
+ } else if (this.bytesReceived > this.totalByteSize) {
16854
+ throw new DataStreamError("Extra chunk(s) received - expected ".concat(this.totalByteSize, " bytes of data total, received ").concat(this.bytesReceived, " bytes"), DataStreamErrorReason.LengthExceeded);
16855
+ }
16856
+ }
16857
+ constructor(info, stream, totalByteSize, outOfBandFailureRejectingFuture) {
16779
16858
  this.reader = stream;
16780
16859
  this.totalByteSize = totalByteSize;
16781
16860
  this._info = info;
16782
16861
  this.bytesReceived = 0;
16862
+ this.outOfBandFailureRejectingFuture = outOfBandFailureRejectingFuture;
16783
16863
  }
16784
16864
  };
16785
16865
  ByteStreamReader = class extends BaseStreamReader {
16786
16866
  handleChunkReceived(chunk) {
16787
16867
  var _a;
16788
16868
  this.bytesReceived += chunk.content.byteLength;
16869
+ this.validateBytesReceived();
16789
16870
  const currentProgress = this.totalByteSize ? this.bytesReceived / this.totalByteSize : void 0;
16790
16871
  (_a = this.onProgress) === null || _a === void 0 ? void 0 : _a.call(this, currentProgress);
16791
16872
  }
16792
16873
  [Symbol.asyncIterator]() {
16793
16874
  const reader = this.reader.getReader();
16875
+ let rejectingSignalFuture = new Future();
16876
+ let activeSignal = null;
16877
+ let onAbort = null;
16878
+ if (this.signal) {
16879
+ const signal = this.signal;
16880
+ onAbort = () => {
16881
+ var _a;
16882
+ (_a = rejectingSignalFuture.reject) === null || _a === void 0 ? void 0 : _a.call(rejectingSignalFuture, signal.reason);
16883
+ };
16884
+ signal.addEventListener("abort", onAbort);
16885
+ activeSignal = signal;
16886
+ }
16887
+ const cleanup = () => {
16888
+ reader.releaseLock();
16889
+ if (activeSignal && onAbort) {
16890
+ activeSignal.removeEventListener("abort", onAbort);
16891
+ }
16892
+ this.signal = void 0;
16893
+ };
16794
16894
  return {
16795
16895
  next: () => __awaiter(this, void 0, void 0, function* () {
16896
+ var _a, _b;
16796
16897
  try {
16797
16898
  const {
16798
16899
  done,
16799
16900
  value
16800
- } = yield reader.read();
16901
+ } = yield Promise.race([
16902
+ reader.read(),
16903
+ // Rejects if this.signal is aborted
16904
+ rejectingSignalFuture.promise,
16905
+ // Rejects if something external says it should, like a participant disconnecting, etc
16906
+ (_b = (_a = this.outOfBandFailureRejectingFuture) === null || _a === void 0 ? void 0 : _a.promise) !== null && _b !== void 0 ? _b : new Promise(() => {
16907
+ })
16908
+ ]);
16801
16909
  if (done) {
16910
+ this.validateBytesReceived(true);
16802
16911
  return {
16803
16912
  done: true,
16804
16913
  value: void 0
@@ -16810,16 +16919,16 @@ var init_livekit_client_esm = __esm({
16810
16919
  value: value.content
16811
16920
  };
16812
16921
  }
16813
- } catch (error) {
16814
- return {
16815
- done: true,
16816
- value: void 0
16817
- };
16922
+ } catch (err) {
16923
+ cleanup();
16924
+ throw err;
16818
16925
  }
16819
16926
  }),
16927
+ // note: `return` runs only for premature exits, see:
16928
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#errors_during_iteration
16820
16929
  return() {
16821
16930
  return __awaiter(this, void 0, void 0, function* () {
16822
- reader.releaseLock();
16931
+ cleanup();
16823
16932
  return {
16824
16933
  done: true,
16825
16934
  value: void 0
@@ -16828,29 +16937,45 @@ var init_livekit_client_esm = __esm({
16828
16937
  }
16829
16938
  };
16830
16939
  }
16940
+ /**
16941
+ * Injects an AbortSignal, which if aborted, will terminate the currently active
16942
+ * stream iteration operation.
16943
+ *
16944
+ * Note that when using AbortSignal.timeout(...), the timeout applies across
16945
+ * the whole iteration operation, not just one individual chunk read.
16946
+ */
16947
+ withAbortSignal(signal) {
16948
+ this.signal = signal;
16949
+ return this;
16950
+ }
16831
16951
  readAll() {
16832
- return __awaiter(this, void 0, void 0, function* () {
16833
- var _a, e_1, _b, _c;
16834
- let chunks = /* @__PURE__ */ new Set();
16835
- try {
16836
- for (var _d = true, _e = __asyncValues(this), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
16837
- _c = _f.value;
16838
- _d = false;
16839
- const chunk = _c;
16840
- chunks.add(chunk);
16841
- }
16842
- } catch (e_1_1) {
16843
- e_1 = {
16844
- error: e_1_1
16845
- };
16846
- } finally {
16952
+ return __awaiter(this, arguments, void 0, function() {
16953
+ var _this = this;
16954
+ let opts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
16955
+ return (function* () {
16956
+ var _a, e_1, _b, _c;
16957
+ let chunks = /* @__PURE__ */ new Set();
16958
+ const iterator = opts.signal ? _this.withAbortSignal(opts.signal) : _this;
16847
16959
  try {
16848
- if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
16960
+ for (var _d = true, iterator_1 = __asyncValues(iterator), iterator_1_1; iterator_1_1 = yield iterator_1.next(), _a = iterator_1_1.done, !_a; _d = true) {
16961
+ _c = iterator_1_1.value;
16962
+ _d = false;
16963
+ const chunk = _c;
16964
+ chunks.add(chunk);
16965
+ }
16966
+ } catch (e_1_1) {
16967
+ e_1 = {
16968
+ error: e_1_1
16969
+ };
16849
16970
  } finally {
16850
- if (e_1) throw e_1.error;
16971
+ try {
16972
+ if (!_d && !_a && (_b = iterator_1.return)) yield _b.call(iterator_1);
16973
+ } finally {
16974
+ if (e_1) throw e_1.error;
16975
+ }
16851
16976
  }
16852
- }
16853
- return Array.from(chunks);
16977
+ return Array.from(chunks);
16978
+ })();
16854
16979
  });
16855
16980
  }
16856
16981
  };
@@ -16859,8 +16984,8 @@ var init_livekit_client_esm = __esm({
16859
16984
  * A TextStreamReader instance can be used as an AsyncIterator that returns the entire string
16860
16985
  * that has been received up to the current point in time.
16861
16986
  */
16862
- constructor(info, stream, totalChunkCount) {
16863
- super(info, stream, totalChunkCount);
16987
+ constructor(info, stream, totalChunkCount, outOfBandFailureRejectingFuture) {
16988
+ super(info, stream, totalChunkCount, outOfBandFailureRejectingFuture);
16864
16989
  this.receivedChunks = /* @__PURE__ */ new Map();
16865
16990
  }
16866
16991
  handleChunkReceived(chunk) {
@@ -16872,6 +16997,7 @@ var init_livekit_client_esm = __esm({
16872
16997
  }
16873
16998
  this.receivedChunks.set(index2, chunk);
16874
16999
  this.bytesReceived += chunk.content.byteLength;
17000
+ this.validateBytesReceived();
16875
17001
  const currentProgress = this.totalByteSize ? this.bytesReceived / this.totalByteSize : void 0;
16876
17002
  (_a = this.onProgress) === null || _a === void 0 ? void 0 : _a.call(this, currentProgress);
16877
17003
  }
@@ -16882,36 +17008,72 @@ var init_livekit_client_esm = __esm({
16882
17008
  */
16883
17009
  [Symbol.asyncIterator]() {
16884
17010
  const reader = this.reader.getReader();
16885
- const decoder = new TextDecoder();
17011
+ const decoder = new TextDecoder("utf-8", {
17012
+ fatal: true
17013
+ });
17014
+ let rejectingSignalFuture = new Future();
17015
+ let activeSignal = null;
17016
+ let onAbort = null;
17017
+ if (this.signal) {
17018
+ const signal = this.signal;
17019
+ onAbort = () => {
17020
+ var _a;
17021
+ (_a = rejectingSignalFuture.reject) === null || _a === void 0 ? void 0 : _a.call(rejectingSignalFuture, signal.reason);
17022
+ };
17023
+ signal.addEventListener("abort", onAbort);
17024
+ activeSignal = signal;
17025
+ }
17026
+ const cleanup = () => {
17027
+ reader.releaseLock();
17028
+ if (activeSignal && onAbort) {
17029
+ activeSignal.removeEventListener("abort", onAbort);
17030
+ }
17031
+ this.signal = void 0;
17032
+ };
16886
17033
  return {
16887
17034
  next: () => __awaiter(this, void 0, void 0, function* () {
17035
+ var _a, _b;
16888
17036
  try {
16889
17037
  const {
16890
17038
  done,
16891
17039
  value
16892
- } = yield reader.read();
17040
+ } = yield Promise.race([
17041
+ reader.read(),
17042
+ // Rejects if this.signal is aborted
17043
+ rejectingSignalFuture.promise,
17044
+ // Rejects if something external says it should, like a participant disconnecting, etc
17045
+ (_b = (_a = this.outOfBandFailureRejectingFuture) === null || _a === void 0 ? void 0 : _a.promise) !== null && _b !== void 0 ? _b : new Promise(() => {
17046
+ })
17047
+ ]);
16893
17048
  if (done) {
17049
+ this.validateBytesReceived(true);
16894
17050
  return {
16895
17051
  done: true,
16896
17052
  value: void 0
16897
17053
  };
16898
17054
  } else {
16899
17055
  this.handleChunkReceived(value);
17056
+ let decodedResult;
17057
+ try {
17058
+ decodedResult = decoder.decode(value.content);
17059
+ } catch (err) {
17060
+ throw new DataStreamError("Cannot decode datastream chunk ".concat(value.chunkIndex, " as text: ").concat(err), DataStreamErrorReason.DecodeFailed);
17061
+ }
16900
17062
  return {
16901
17063
  done: false,
16902
- value: decoder.decode(value.content)
17064
+ value: decodedResult
16903
17065
  };
16904
17066
  }
16905
- } catch (error) {
16906
- return {
16907
- done: true,
16908
- value: void 0
16909
- };
17067
+ } catch (err) {
17068
+ cleanup();
17069
+ throw err;
16910
17070
  }
16911
17071
  }),
17072
+ // note: `return` runs only for premature exits, see:
17073
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#errors_during_iteration
16912
17074
  return() {
16913
17075
  return __awaiter(this, void 0, void 0, function* () {
16914
- reader.releaseLock();
17076
+ cleanup();
16915
17077
  return {
16916
17078
  done: true,
16917
17079
  value: void 0
@@ -16920,31 +17082,215 @@ var init_livekit_client_esm = __esm({
16920
17082
  }
16921
17083
  };
16922
17084
  }
17085
+ /**
17086
+ * Injects an AbortSignal, which if aborted, will terminate the currently active
17087
+ * stream iteration operation.
17088
+ *
17089
+ * Note that when using AbortSignal.timeout(...), the timeout applies across
17090
+ * the whole iteration operation, not just one individual chunk read.
17091
+ */
17092
+ withAbortSignal(signal) {
17093
+ this.signal = signal;
17094
+ return this;
17095
+ }
16923
17096
  readAll() {
17097
+ return __awaiter(this, arguments, void 0, function() {
17098
+ var _this2 = this;
17099
+ let opts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
17100
+ return (function* () {
17101
+ var _a, e_2, _b, _c;
17102
+ let finalString = "";
17103
+ const iterator = opts.signal ? _this2.withAbortSignal(opts.signal) : _this2;
17104
+ try {
17105
+ for (var _d = true, iterator_2 = __asyncValues(iterator), iterator_2_1; iterator_2_1 = yield iterator_2.next(), _a = iterator_2_1.done, !_a; _d = true) {
17106
+ _c = iterator_2_1.value;
17107
+ _d = false;
17108
+ const chunk = _c;
17109
+ finalString += chunk;
17110
+ }
17111
+ } catch (e_2_1) {
17112
+ e_2 = {
17113
+ error: e_2_1
17114
+ };
17115
+ } finally {
17116
+ try {
17117
+ if (!_d && !_a && (_b = iterator_2.return)) yield _b.call(iterator_2);
17118
+ } finally {
17119
+ if (e_2) throw e_2.error;
17120
+ }
17121
+ }
17122
+ return finalString;
17123
+ })();
17124
+ });
17125
+ }
17126
+ };
17127
+ IncomingDataStreamManager = class {
17128
+ constructor() {
17129
+ this.log = livekitLogger;
17130
+ this.byteStreamControllers = /* @__PURE__ */ new Map();
17131
+ this.textStreamControllers = /* @__PURE__ */ new Map();
17132
+ this.byteStreamHandlers = /* @__PURE__ */ new Map();
17133
+ this.textStreamHandlers = /* @__PURE__ */ new Map();
17134
+ }
17135
+ registerTextStreamHandler(topic, callback) {
17136
+ if (this.textStreamHandlers.has(topic)) {
17137
+ throw new DataStreamError('A text stream handler for topic "'.concat(topic, '" has already been set.'), DataStreamErrorReason.HandlerAlreadyRegistered);
17138
+ }
17139
+ this.textStreamHandlers.set(topic, callback);
17140
+ }
17141
+ unregisterTextStreamHandler(topic) {
17142
+ this.textStreamHandlers.delete(topic);
17143
+ }
17144
+ registerByteStreamHandler(topic, callback) {
17145
+ if (this.byteStreamHandlers.has(topic)) {
17146
+ throw new DataStreamError('A byte stream handler for topic "'.concat(topic, '" has already been set.'), DataStreamErrorReason.HandlerAlreadyRegistered);
17147
+ }
17148
+ this.byteStreamHandlers.set(topic, callback);
17149
+ }
17150
+ unregisterByteStreamHandler(topic) {
17151
+ this.byteStreamHandlers.delete(topic);
17152
+ }
17153
+ clearHandlersAndControllers() {
17154
+ this.byteStreamControllers.clear();
17155
+ this.textStreamControllers.clear();
17156
+ this.byteStreamHandlers.clear();
17157
+ this.textStreamHandlers.clear();
17158
+ }
17159
+ validateParticipantHasNoActiveDataStreams(participantIdentity) {
17160
+ var _a, _b, _c, _d;
17161
+ const textStreamsBeingSentByDisconnectingParticipant = Array.from(this.textStreamControllers.entries()).filter((entry) => entry[1].sendingParticipantIdentity === participantIdentity);
17162
+ const byteStreamsBeingSentByDisconnectingParticipant = Array.from(this.byteStreamControllers.entries()).filter((entry) => entry[1].sendingParticipantIdentity === participantIdentity);
17163
+ if (textStreamsBeingSentByDisconnectingParticipant.length > 0 || byteStreamsBeingSentByDisconnectingParticipant.length > 0) {
17164
+ const abnormalEndError = new DataStreamError("Participant ".concat(participantIdentity, " unexpectedly disconnected in the middle of sending data"), DataStreamErrorReason.AbnormalEnd);
17165
+ for (const [id, controller] of byteStreamsBeingSentByDisconnectingParticipant) {
17166
+ (_b = (_a = controller.outOfBandFailureRejectingFuture).reject) === null || _b === void 0 ? void 0 : _b.call(_a, abnormalEndError);
17167
+ this.byteStreamControllers.delete(id);
17168
+ }
17169
+ for (const [id, controller] of textStreamsBeingSentByDisconnectingParticipant) {
17170
+ (_d = (_c = controller.outOfBandFailureRejectingFuture).reject) === null || _d === void 0 ? void 0 : _d.call(_c, abnormalEndError);
17171
+ this.textStreamControllers.delete(id);
17172
+ }
17173
+ }
17174
+ }
17175
+ handleDataStreamPacket(packet) {
16924
17176
  return __awaiter(this, void 0, void 0, function* () {
16925
- var _a, e_2, _b, _c;
16926
- let finalString = "";
16927
- try {
16928
- for (var _d = true, _e = __asyncValues(this), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
16929
- _c = _f.value;
16930
- _d = false;
16931
- const chunk = _c;
16932
- finalString += chunk;
17177
+ switch (packet.value.case) {
17178
+ case "streamHeader":
17179
+ return this.handleStreamHeader(packet.value.value, packet.participantIdentity);
17180
+ case "streamChunk":
17181
+ return this.handleStreamChunk(packet.value.value);
17182
+ case "streamTrailer":
17183
+ return this.handleStreamTrailer(packet.value.value);
17184
+ default:
17185
+ throw new Error('DataPacket of value "'.concat(packet.value.case, '" is not data stream related!'));
17186
+ }
17187
+ });
17188
+ }
17189
+ handleStreamHeader(streamHeader, participantIdentity) {
17190
+ return __awaiter(this, void 0, void 0, function* () {
17191
+ var _a;
17192
+ if (streamHeader.contentHeader.case === "byteHeader") {
17193
+ const streamHandlerCallback = this.byteStreamHandlers.get(streamHeader.topic);
17194
+ if (!streamHandlerCallback) {
17195
+ this.log.debug("ignoring incoming byte stream due to no handler for topic", streamHeader.topic);
17196
+ return;
16933
17197
  }
16934
- } catch (e_2_1) {
16935
- e_2 = {
16936
- error: e_2_1
17198
+ let streamController;
17199
+ const outOfBandFailureRejectingFuture = new Future();
17200
+ const info = {
17201
+ id: streamHeader.streamId,
17202
+ name: (_a = streamHeader.contentHeader.value.name) !== null && _a !== void 0 ? _a : "unknown",
17203
+ mimeType: streamHeader.mimeType,
17204
+ size: streamHeader.totalLength ? Number(streamHeader.totalLength) : void 0,
17205
+ topic: streamHeader.topic,
17206
+ timestamp: bigIntToNumber(streamHeader.timestamp),
17207
+ attributes: streamHeader.attributes
16937
17208
  };
16938
- } finally {
16939
- try {
16940
- if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
16941
- } finally {
16942
- if (e_2) throw e_2.error;
17209
+ const stream = new ReadableStream({
17210
+ start: (controller) => {
17211
+ streamController = controller;
17212
+ if (this.textStreamControllers.has(streamHeader.streamId)) {
17213
+ throw new DataStreamError("A data stream read is already in progress for a stream with id ".concat(streamHeader.streamId, "."), DataStreamErrorReason.AlreadyOpened);
17214
+ }
17215
+ this.byteStreamControllers.set(streamHeader.streamId, {
17216
+ info,
17217
+ controller: streamController,
17218
+ startTime: Date.now(),
17219
+ sendingParticipantIdentity: participantIdentity,
17220
+ outOfBandFailureRejectingFuture
17221
+ });
17222
+ }
17223
+ });
17224
+ streamHandlerCallback(new ByteStreamReader(info, stream, bigIntToNumber(streamHeader.totalLength), outOfBandFailureRejectingFuture), {
17225
+ identity: participantIdentity
17226
+ });
17227
+ } else if (streamHeader.contentHeader.case === "textHeader") {
17228
+ const streamHandlerCallback = this.textStreamHandlers.get(streamHeader.topic);
17229
+ if (!streamHandlerCallback) {
17230
+ this.log.debug("ignoring incoming text stream due to no handler for topic", streamHeader.topic);
17231
+ return;
16943
17232
  }
17233
+ let streamController;
17234
+ const outOfBandFailureRejectingFuture = new Future();
17235
+ const info = {
17236
+ id: streamHeader.streamId,
17237
+ mimeType: streamHeader.mimeType,
17238
+ size: streamHeader.totalLength ? Number(streamHeader.totalLength) : void 0,
17239
+ topic: streamHeader.topic,
17240
+ timestamp: Number(streamHeader.timestamp),
17241
+ attributes: streamHeader.attributes
17242
+ };
17243
+ const stream = new ReadableStream({
17244
+ start: (controller) => {
17245
+ streamController = controller;
17246
+ if (this.textStreamControllers.has(streamHeader.streamId)) {
17247
+ throw new DataStreamError("A data stream read is already in progress for a stream with id ".concat(streamHeader.streamId, "."), DataStreamErrorReason.AlreadyOpened);
17248
+ }
17249
+ this.textStreamControllers.set(streamHeader.streamId, {
17250
+ info,
17251
+ controller: streamController,
17252
+ startTime: Date.now(),
17253
+ sendingParticipantIdentity: participantIdentity,
17254
+ outOfBandFailureRejectingFuture
17255
+ });
17256
+ }
17257
+ });
17258
+ streamHandlerCallback(new TextStreamReader(info, stream, bigIntToNumber(streamHeader.totalLength), outOfBandFailureRejectingFuture), {
17259
+ identity: participantIdentity
17260
+ });
16944
17261
  }
16945
- return finalString;
16946
17262
  });
16947
17263
  }
17264
+ handleStreamChunk(chunk) {
17265
+ const fileBuffer = this.byteStreamControllers.get(chunk.streamId);
17266
+ if (fileBuffer) {
17267
+ if (chunk.content.length > 0) {
17268
+ fileBuffer.controller.enqueue(chunk);
17269
+ }
17270
+ }
17271
+ const textBuffer = this.textStreamControllers.get(chunk.streamId);
17272
+ if (textBuffer) {
17273
+ if (chunk.content.length > 0) {
17274
+ textBuffer.controller.enqueue(chunk);
17275
+ }
17276
+ }
17277
+ }
17278
+ handleStreamTrailer(trailer) {
17279
+ const textBuffer = this.textStreamControllers.get(trailer.streamId);
17280
+ if (textBuffer) {
17281
+ textBuffer.info.attributes = Object.assign(Object.assign({}, textBuffer.info.attributes), trailer.attributes);
17282
+ textBuffer.controller.close();
17283
+ this.textStreamControllers.delete(trailer.streamId);
17284
+ }
17285
+ const fileBuffer = this.byteStreamControllers.get(trailer.streamId);
17286
+ if (fileBuffer) {
17287
+ {
17288
+ fileBuffer.info.attributes = Object.assign(Object.assign({}, fileBuffer.info.attributes), trailer.attributes);
17289
+ fileBuffer.controller.close();
17290
+ this.byteStreamControllers.delete(trailer.streamId);
17291
+ }
17292
+ }
17293
+ }
16948
17294
  };
16949
17295
  BaseStreamWriter = class {
16950
17296
  constructor(writableStream, info, onClose) {
@@ -16969,6 +17315,277 @@ var init_livekit_client_esm = __esm({
16969
17315
  };
16970
17316
  ByteStreamWriter = class extends BaseStreamWriter {
16971
17317
  };
17318
+ STREAM_CHUNK_SIZE = 15e3;
17319
+ OutgoingDataStreamManager = class {
17320
+ constructor(engine, log2) {
17321
+ this.engine = engine;
17322
+ this.log = log2;
17323
+ }
17324
+ setupEngine(engine) {
17325
+ this.engine = engine;
17326
+ }
17327
+ /** {@inheritDoc LocalParticipant.sendText} */
17328
+ sendText(text7, options) {
17329
+ return __awaiter(this, void 0, void 0, function* () {
17330
+ var _a;
17331
+ const streamId = crypto.randomUUID();
17332
+ const textInBytes = new TextEncoder().encode(text7);
17333
+ const totalTextLength = textInBytes.byteLength;
17334
+ const fileIds = (_a = options === null || options === void 0 ? void 0 : options.attachments) === null || _a === void 0 ? void 0 : _a.map(() => crypto.randomUUID());
17335
+ const progresses = new Array(fileIds ? fileIds.length + 1 : 1).fill(0);
17336
+ const handleProgress = (progress, idx) => {
17337
+ var _a2;
17338
+ progresses[idx] = progress;
17339
+ const totalProgress = progresses.reduce((acc, val) => acc + val, 0);
17340
+ (_a2 = options === null || options === void 0 ? void 0 : options.onProgress) === null || _a2 === void 0 ? void 0 : _a2.call(options, totalProgress);
17341
+ };
17342
+ const writer2 = yield this.streamText({
17343
+ streamId,
17344
+ totalSize: totalTextLength,
17345
+ destinationIdentities: options === null || options === void 0 ? void 0 : options.destinationIdentities,
17346
+ topic: options === null || options === void 0 ? void 0 : options.topic,
17347
+ attachedStreamIds: fileIds,
17348
+ attributes: options === null || options === void 0 ? void 0 : options.attributes
17349
+ });
17350
+ yield writer2.write(text7);
17351
+ handleProgress(1, 0);
17352
+ yield writer2.close();
17353
+ if ((options === null || options === void 0 ? void 0 : options.attachments) && fileIds) {
17354
+ yield Promise.all(options.attachments.map((file, idx) => __awaiter(this, void 0, void 0, function* () {
17355
+ return this._sendFile(fileIds[idx], file, {
17356
+ topic: options.topic,
17357
+ mimeType: file.type,
17358
+ onProgress: (progress) => {
17359
+ handleProgress(progress, idx + 1);
17360
+ }
17361
+ });
17362
+ })));
17363
+ }
17364
+ return writer2.info;
17365
+ });
17366
+ }
17367
+ /**
17368
+ * @internal
17369
+ * @experimental CAUTION, might get removed in a minor release
17370
+ */
17371
+ streamText(options) {
17372
+ return __awaiter(this, void 0, void 0, function* () {
17373
+ var _a, _b;
17374
+ const streamId = (_a = options === null || options === void 0 ? void 0 : options.streamId) !== null && _a !== void 0 ? _a : crypto.randomUUID();
17375
+ const info = {
17376
+ id: streamId,
17377
+ mimeType: "text/plain",
17378
+ timestamp: Date.now(),
17379
+ topic: (_b = options === null || options === void 0 ? void 0 : options.topic) !== null && _b !== void 0 ? _b : "",
17380
+ size: options === null || options === void 0 ? void 0 : options.totalSize,
17381
+ attributes: options === null || options === void 0 ? void 0 : options.attributes
17382
+ };
17383
+ const header = new DataStream_Header({
17384
+ streamId,
17385
+ mimeType: info.mimeType,
17386
+ topic: info.topic,
17387
+ timestamp: numberToBigInt(info.timestamp),
17388
+ totalLength: numberToBigInt(options === null || options === void 0 ? void 0 : options.totalSize),
17389
+ attributes: info.attributes,
17390
+ contentHeader: {
17391
+ case: "textHeader",
17392
+ value: new DataStream_TextHeader({
17393
+ version: options === null || options === void 0 ? void 0 : options.version,
17394
+ attachedStreamIds: options === null || options === void 0 ? void 0 : options.attachedStreamIds,
17395
+ replyToStreamId: options === null || options === void 0 ? void 0 : options.replyToStreamId,
17396
+ operationType: (options === null || options === void 0 ? void 0 : options.type) === "update" ? DataStream_OperationType.UPDATE : DataStream_OperationType.CREATE
17397
+ })
17398
+ }
17399
+ });
17400
+ const destinationIdentities = options === null || options === void 0 ? void 0 : options.destinationIdentities;
17401
+ const packet = new DataPacket({
17402
+ destinationIdentities,
17403
+ value: {
17404
+ case: "streamHeader",
17405
+ value: header
17406
+ }
17407
+ });
17408
+ yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
17409
+ let chunkId = 0;
17410
+ const engine = this.engine;
17411
+ const writableStream = new WritableStream({
17412
+ // Implement the sink
17413
+ write(text7) {
17414
+ return __awaiter(this, void 0, void 0, function* () {
17415
+ for (const textByteChunk of splitUtf8(text7, STREAM_CHUNK_SIZE)) {
17416
+ yield engine.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);
17417
+ const chunk = new DataStream_Chunk({
17418
+ content: textByteChunk,
17419
+ streamId,
17420
+ chunkIndex: numberToBigInt(chunkId)
17421
+ });
17422
+ const chunkPacket = new DataPacket({
17423
+ destinationIdentities,
17424
+ value: {
17425
+ case: "streamChunk",
17426
+ value: chunk
17427
+ }
17428
+ });
17429
+ yield engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
17430
+ chunkId += 1;
17431
+ }
17432
+ });
17433
+ },
17434
+ close() {
17435
+ return __awaiter(this, void 0, void 0, function* () {
17436
+ const trailer = new DataStream_Trailer({
17437
+ streamId
17438
+ });
17439
+ const trailerPacket = new DataPacket({
17440
+ destinationIdentities,
17441
+ value: {
17442
+ case: "streamTrailer",
17443
+ value: trailer
17444
+ }
17445
+ });
17446
+ yield engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
17447
+ });
17448
+ },
17449
+ abort(err) {
17450
+ console.log("Sink error:", err);
17451
+ }
17452
+ });
17453
+ let onEngineClose = () => __awaiter(this, void 0, void 0, function* () {
17454
+ yield writer2.close();
17455
+ });
17456
+ engine.once(EngineEvent.Closing, onEngineClose);
17457
+ const writer2 = new TextStreamWriter(writableStream, info, () => this.engine.off(EngineEvent.Closing, onEngineClose));
17458
+ return writer2;
17459
+ });
17460
+ }
17461
+ sendFile(file, options) {
17462
+ return __awaiter(this, void 0, void 0, function* () {
17463
+ const streamId = crypto.randomUUID();
17464
+ yield this._sendFile(streamId, file, options);
17465
+ return {
17466
+ id: streamId
17467
+ };
17468
+ });
17469
+ }
17470
+ _sendFile(streamId, file, options) {
17471
+ return __awaiter(this, void 0, void 0, function* () {
17472
+ var _a;
17473
+ const writer2 = yield this.streamBytes({
17474
+ streamId,
17475
+ totalSize: file.size,
17476
+ name: file.name,
17477
+ mimeType: (_a = options === null || options === void 0 ? void 0 : options.mimeType) !== null && _a !== void 0 ? _a : file.type,
17478
+ topic: options === null || options === void 0 ? void 0 : options.topic,
17479
+ destinationIdentities: options === null || options === void 0 ? void 0 : options.destinationIdentities
17480
+ });
17481
+ const reader = file.stream().getReader();
17482
+ while (true) {
17483
+ const {
17484
+ done,
17485
+ value
17486
+ } = yield reader.read();
17487
+ if (done) {
17488
+ break;
17489
+ }
17490
+ yield writer2.write(value);
17491
+ }
17492
+ yield writer2.close();
17493
+ return writer2.info;
17494
+ });
17495
+ }
17496
+ streamBytes(options) {
17497
+ return __awaiter(this, void 0, void 0, function* () {
17498
+ var _a, _b, _c, _d, _e;
17499
+ const streamId = (_a = options === null || options === void 0 ? void 0 : options.streamId) !== null && _a !== void 0 ? _a : crypto.randomUUID();
17500
+ const destinationIdentities = options === null || options === void 0 ? void 0 : options.destinationIdentities;
17501
+ const info = {
17502
+ id: streamId,
17503
+ mimeType: (_b = options === null || options === void 0 ? void 0 : options.mimeType) !== null && _b !== void 0 ? _b : "application/octet-stream",
17504
+ topic: (_c = options === null || options === void 0 ? void 0 : options.topic) !== null && _c !== void 0 ? _c : "",
17505
+ timestamp: Date.now(),
17506
+ attributes: options === null || options === void 0 ? void 0 : options.attributes,
17507
+ size: options === null || options === void 0 ? void 0 : options.totalSize,
17508
+ name: (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : "unknown"
17509
+ };
17510
+ const header = new DataStream_Header({
17511
+ totalLength: numberToBigInt((_e = info.size) !== null && _e !== void 0 ? _e : 0),
17512
+ mimeType: info.mimeType,
17513
+ streamId,
17514
+ topic: info.topic,
17515
+ timestamp: numberToBigInt(Date.now()),
17516
+ attributes: info.attributes,
17517
+ contentHeader: {
17518
+ case: "byteHeader",
17519
+ value: new DataStream_ByteHeader({
17520
+ name: info.name
17521
+ })
17522
+ }
17523
+ });
17524
+ const packet = new DataPacket({
17525
+ destinationIdentities,
17526
+ value: {
17527
+ case: "streamHeader",
17528
+ value: header
17529
+ }
17530
+ });
17531
+ yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
17532
+ let chunkId = 0;
17533
+ const writeMutex = new _();
17534
+ const engine = this.engine;
17535
+ const logLocal = this.log;
17536
+ const writableStream = new WritableStream({
17537
+ write(chunk) {
17538
+ return __awaiter(this, void 0, void 0, function* () {
17539
+ const unlock = yield writeMutex.lock();
17540
+ let byteOffset = 0;
17541
+ try {
17542
+ while (byteOffset < chunk.byteLength) {
17543
+ const subChunk = chunk.slice(byteOffset, byteOffset + STREAM_CHUNK_SIZE);
17544
+ yield engine.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);
17545
+ const chunkPacket = new DataPacket({
17546
+ destinationIdentities,
17547
+ value: {
17548
+ case: "streamChunk",
17549
+ value: new DataStream_Chunk({
17550
+ content: subChunk,
17551
+ streamId,
17552
+ chunkIndex: numberToBigInt(chunkId)
17553
+ })
17554
+ }
17555
+ });
17556
+ yield engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
17557
+ chunkId += 1;
17558
+ byteOffset += subChunk.byteLength;
17559
+ }
17560
+ } finally {
17561
+ unlock();
17562
+ }
17563
+ });
17564
+ },
17565
+ close() {
17566
+ return __awaiter(this, void 0, void 0, function* () {
17567
+ const trailer = new DataStream_Trailer({
17568
+ streamId
17569
+ });
17570
+ const trailerPacket = new DataPacket({
17571
+ destinationIdentities,
17572
+ value: {
17573
+ case: "streamTrailer",
17574
+ value: trailer
17575
+ }
17576
+ });
17577
+ yield engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
17578
+ });
17579
+ },
17580
+ abort(err) {
17581
+ logLocal.error("Sink error:", err);
17582
+ }
17583
+ });
17584
+ const byteWriter = new ByteStreamWriter(writableStream, info);
17585
+ return byteWriter;
17586
+ });
17587
+ }
17588
+ };
16972
17589
  RemoteTrack = class extends Track {
16973
17590
  constructor(mediaTrack, sid, kind, receiver, loggerOptions) {
16974
17591
  super(mediaTrack, kind, loggerOptions);
@@ -17304,6 +17921,13 @@ var init_livekit_client_esm = __esm({
17304
17921
  get isAdaptiveStream() {
17305
17922
  return this.adaptiveStreamSettings !== void 0;
17306
17923
  }
17924
+ setStreamState(value) {
17925
+ super.setStreamState(value);
17926
+ console.log("setStreamState", value);
17927
+ if (value === Track.StreamState.Active) {
17928
+ this.updateVisibility();
17929
+ }
17930
+ }
17307
17931
  /**
17308
17932
  * Note: When using adaptiveStream, you need to use remoteVideoTrack.attach() to add the track to a HTMLVideoElement, otherwise your video tracks might never start
17309
17933
  */
@@ -17447,13 +18071,13 @@ var init_livekit_client_esm = __esm({
17447
18071
  this.updateVisibility();
17448
18072
  });
17449
18073
  }
17450
- updateVisibility() {
18074
+ updateVisibility(forceEmit) {
17451
18075
  var _a, _b;
17452
18076
  const lastVisibilityChange = this.elementInfos.reduce((prev, info) => Math.max(prev, info.visibilityChangedAt || 0), 0);
17453
18077
  const backgroundPause = ((_b = (_a = this.adaptiveStreamSettings) === null || _a === void 0 ? void 0 : _a.pauseVideoInBackground) !== null && _b !== void 0 ? _b : true) ? this.isInBackground : false;
17454
18078
  const isPiPMode = this.elementInfos.some((info) => info.pictureInPicture);
17455
18079
  const isVisible = this.elementInfos.some((info) => info.visible) && !backgroundPause || isPiPMode;
17456
- if (this.lastVisible === isVisible) {
18080
+ if (this.lastVisible === isVisible && !forceEmit) {
17457
18081
  return;
17458
18082
  }
17459
18083
  if (!isVisible && Date.now() - lastVisibilityChange < REACTION_DELAY) {
@@ -18021,10 +18645,9 @@ var init_livekit_client_esm = __esm({
18021
18645
  }
18022
18646
  }
18023
18647
  };
18024
- STREAM_CHUNK_SIZE = 15e3;
18025
18648
  LocalParticipant = class extends Participant {
18026
18649
  /** @internal */
18027
- constructor(sid, identity, engine, options, roomRpcHandlers) {
18650
+ constructor(sid, identity, engine, options, roomRpcHandlers, roomOutgoingDataStreamManager) {
18028
18651
  super(sid, identity, void 0, void 0, void 0, {
18029
18652
  loggerName: options.loggerName,
18030
18653
  loggerContextCb: () => this.engine.logContext
@@ -18250,6 +18873,7 @@ var init_livekit_client_esm = __esm({
18250
18873
  this.activeDeviceMap = /* @__PURE__ */ new Map([["audioinput", "default"], ["videoinput", "default"], ["audiooutput", "default"]]);
18251
18874
  this.pendingSignalRequests = /* @__PURE__ */ new Map();
18252
18875
  this.rpcHandlers = roomRpcHandlers;
18876
+ this.roomOutgoingDataStreamManager = roomOutgoingDataStreamManager;
18253
18877
  }
18254
18878
  get lastCameraError() {
18255
18879
  return this.cameraError;
@@ -18341,7 +18965,7 @@ var init_livekit_client_esm = __esm({
18341
18965
  name: name2,
18342
18966
  attributes
18343
18967
  } = _ref;
18344
- return function* () {
18968
+ return (function* () {
18345
18969
  return new Promise((resolve, reject) => __awaiter(_this, void 0, void 0, function* () {
18346
18970
  var _a2, _b;
18347
18971
  try {
@@ -18376,7 +19000,7 @@ var init_livekit_client_esm = __esm({
18376
19000
  if (e3 instanceof Error) reject(e3);
18377
19001
  }
18378
19002
  }));
18379
- }();
19003
+ })();
18380
19004
  });
18381
19005
  }
18382
19006
  /**
@@ -18645,7 +19269,7 @@ var init_livekit_client_esm = __esm({
18645
19269
  return __awaiter(this, arguments, void 0, function(track, options) {
18646
19270
  var _this2 = this;
18647
19271
  let isRepublish = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
18648
- return function* () {
19272
+ return (function* () {
18649
19273
  var _a, _b, _c, _d;
18650
19274
  if (isLocalAudioTrack(track)) {
18651
19275
  track.setAudioContext(_this2.audioContext);
@@ -18770,7 +19394,7 @@ var init_livekit_client_esm = __esm({
18770
19394
  } finally {
18771
19395
  _this2.pendingPublishPromises.delete(track);
18772
19396
  }
18773
- }();
19397
+ })();
18774
19398
  });
18775
19399
  }
18776
19400
  waitUntilEngineConnected() {
@@ -19252,7 +19876,7 @@ var init_livekit_client_esm = __esm({
19252
19876
  return __awaiter(this, arguments, void 0, function(options) {
19253
19877
  var _this3 = this;
19254
19878
  let restartTracks = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
19255
- return function* () {
19879
+ return (function* () {
19256
19880
  if (_this3.republishPromise) {
19257
19881
  yield _this3.republishPromise;
19258
19882
  }
@@ -19286,7 +19910,7 @@ var init_livekit_client_esm = __esm({
19286
19910
  }
19287
19911
  }));
19288
19912
  yield _this3.republishPromise;
19289
- }();
19913
+ })();
19290
19914
  });
19291
19915
  }
19292
19916
  /**
@@ -19300,7 +19924,7 @@ var init_livekit_client_esm = __esm({
19300
19924
  return __awaiter(this, arguments, void 0, function(data) {
19301
19925
  var _this4 = this;
19302
19926
  let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
19303
- return function* () {
19927
+ return (function* () {
19304
19928
  const kind = options.reliable ? DataPacket_Kind.RELIABLE : DataPacket_Kind.LOSSY;
19305
19929
  const destinationIdentities = options.destinationIdentities;
19306
19930
  const topic = options.topic;
@@ -19317,7 +19941,7 @@ var init_livekit_client_esm = __esm({
19317
19941
  }
19318
19942
  });
19319
19943
  yield _this4.engine.sendDataPacket(packet, kind);
19320
- }();
19944
+ })();
19321
19945
  });
19322
19946
  }
19323
19947
  /**
@@ -19341,6 +19965,7 @@ var init_livekit_client_esm = __esm({
19341
19965
  yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
19342
19966
  });
19343
19967
  }
19968
+ /** @deprecated Consider migrating to {@link sendText} */
19344
19969
  sendChatMessage(text7, options) {
19345
19970
  return __awaiter(this, void 0, void 0, function* () {
19346
19971
  const msg = {
@@ -19362,6 +19987,7 @@ var init_livekit_client_esm = __esm({
19362
19987
  return msg;
19363
19988
  });
19364
19989
  }
19990
+ /** @deprecated Consider migrating to {@link sendText} */
19365
19991
  editChatMessage(editText, originalMessage) {
19366
19992
  return __awaiter(this, void 0, void 0, function* () {
19367
19993
  const msg = Object.assign(Object.assign({}, originalMessage), {
@@ -19382,264 +20008,51 @@ var init_livekit_client_esm = __esm({
19382
20008
  return msg;
19383
20009
  });
19384
20010
  }
20011
+ /**
20012
+ * Sends the given string to participants in the room via the data channel.
20013
+ * For longer messages, consider using {@link streamText} instead.
20014
+ *
20015
+ * @param text The text payload
20016
+ * @param options.topic Topic identifier used to route the stream to appropriate handlers.
20017
+ */
19385
20018
  sendText(text7, options) {
19386
20019
  return __awaiter(this, void 0, void 0, function* () {
19387
- var _a;
19388
- const streamId = crypto.randomUUID();
19389
- const textInBytes = new TextEncoder().encode(text7);
19390
- const totalTextLength = textInBytes.byteLength;
19391
- const fileIds = (_a = options === null || options === void 0 ? void 0 : options.attachments) === null || _a === void 0 ? void 0 : _a.map(() => crypto.randomUUID());
19392
- const progresses = new Array(fileIds ? fileIds.length + 1 : 1).fill(0);
19393
- const handleProgress = (progress, idx) => {
19394
- var _a2;
19395
- progresses[idx] = progress;
19396
- const totalProgress = progresses.reduce((acc, val) => acc + val, 0);
19397
- (_a2 = options === null || options === void 0 ? void 0 : options.onProgress) === null || _a2 === void 0 ? void 0 : _a2.call(options, totalProgress);
19398
- };
19399
- const writer2 = yield this.streamText({
19400
- streamId,
19401
- totalSize: totalTextLength,
19402
- destinationIdentities: options === null || options === void 0 ? void 0 : options.destinationIdentities,
19403
- topic: options === null || options === void 0 ? void 0 : options.topic,
19404
- attachedStreamIds: fileIds,
19405
- attributes: options === null || options === void 0 ? void 0 : options.attributes
19406
- });
19407
- yield writer2.write(text7);
19408
- handleProgress(1, 0);
19409
- yield writer2.close();
19410
- if ((options === null || options === void 0 ? void 0 : options.attachments) && fileIds) {
19411
- yield Promise.all(options.attachments.map((file, idx) => __awaiter(this, void 0, void 0, function* () {
19412
- return this._sendFile(fileIds[idx], file, {
19413
- topic: options.topic,
19414
- mimeType: file.type,
19415
- onProgress: (progress) => {
19416
- handleProgress(progress, idx + 1);
19417
- }
19418
- });
19419
- })));
19420
- }
19421
- return writer2.info;
20020
+ return this.roomOutgoingDataStreamManager.sendText(text7, options);
19422
20021
  });
19423
20022
  }
19424
20023
  /**
20024
+ * Creates a new TextStreamWriter which can be used to stream text incrementally
20025
+ * to participants in the room via the data channel.
20026
+ *
20027
+ * @param options.topic Topic identifier used to route the stream to appropriate handlers.
20028
+ *
19425
20029
  * @internal
19426
20030
  * @experimental CAUTION, might get removed in a minor release
19427
20031
  */
19428
20032
  streamText(options) {
19429
20033
  return __awaiter(this, void 0, void 0, function* () {
19430
- var _a, _b;
19431
- const streamId = (_a = options === null || options === void 0 ? void 0 : options.streamId) !== null && _a !== void 0 ? _a : crypto.randomUUID();
19432
- const info = {
19433
- id: streamId,
19434
- mimeType: "text/plain",
19435
- timestamp: Date.now(),
19436
- topic: (_b = options === null || options === void 0 ? void 0 : options.topic) !== null && _b !== void 0 ? _b : "",
19437
- size: options === null || options === void 0 ? void 0 : options.totalSize,
19438
- attributes: options === null || options === void 0 ? void 0 : options.attributes
19439
- };
19440
- const header = new DataStream_Header({
19441
- streamId,
19442
- mimeType: info.mimeType,
19443
- topic: info.topic,
19444
- timestamp: numberToBigInt(info.timestamp),
19445
- totalLength: numberToBigInt(options === null || options === void 0 ? void 0 : options.totalSize),
19446
- attributes: info.attributes,
19447
- contentHeader: {
19448
- case: "textHeader",
19449
- value: new DataStream_TextHeader({
19450
- version: options === null || options === void 0 ? void 0 : options.version,
19451
- attachedStreamIds: options === null || options === void 0 ? void 0 : options.attachedStreamIds,
19452
- replyToStreamId: options === null || options === void 0 ? void 0 : options.replyToStreamId,
19453
- operationType: (options === null || options === void 0 ? void 0 : options.type) === "update" ? DataStream_OperationType.UPDATE : DataStream_OperationType.CREATE
19454
- })
19455
- }
19456
- });
19457
- const destinationIdentities = options === null || options === void 0 ? void 0 : options.destinationIdentities;
19458
- const packet = new DataPacket({
19459
- destinationIdentities,
19460
- value: {
19461
- case: "streamHeader",
19462
- value: header
19463
- }
19464
- });
19465
- yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
19466
- let chunkId = 0;
19467
- const localP = this;
19468
- const writableStream = new WritableStream({
19469
- // Implement the sink
19470
- write(text7) {
19471
- return __awaiter(this, void 0, void 0, function* () {
19472
- for (const textByteChunk of splitUtf8(text7, STREAM_CHUNK_SIZE)) {
19473
- yield localP.engine.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);
19474
- const chunk = new DataStream_Chunk({
19475
- content: textByteChunk,
19476
- streamId,
19477
- chunkIndex: numberToBigInt(chunkId)
19478
- });
19479
- const chunkPacket = new DataPacket({
19480
- destinationIdentities,
19481
- value: {
19482
- case: "streamChunk",
19483
- value: chunk
19484
- }
19485
- });
19486
- yield localP.engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
19487
- chunkId += 1;
19488
- }
19489
- });
19490
- },
19491
- close() {
19492
- return __awaiter(this, void 0, void 0, function* () {
19493
- const trailer = new DataStream_Trailer({
19494
- streamId
19495
- });
19496
- const trailerPacket = new DataPacket({
19497
- destinationIdentities,
19498
- value: {
19499
- case: "streamTrailer",
19500
- value: trailer
19501
- }
19502
- });
19503
- yield localP.engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
19504
- });
19505
- },
19506
- abort(err) {
19507
- console.log("Sink error:", err);
19508
- }
19509
- });
19510
- let onEngineClose = () => __awaiter(this, void 0, void 0, function* () {
19511
- yield writer2.close();
19512
- });
19513
- localP.engine.once(EngineEvent.Closing, onEngineClose);
19514
- const writer2 = new TextStreamWriter(writableStream, info, () => this.engine.off(EngineEvent.Closing, onEngineClose));
19515
- return writer2;
20034
+ return this.roomOutgoingDataStreamManager.streamText(options);
19516
20035
  });
19517
20036
  }
20037
+ /** Send a File to all participants in the room via the data channel.
20038
+ * @param file The File object payload
20039
+ * @param options.topic Topic identifier used to route the stream to appropriate handlers.
20040
+ * @param options.onProgress A callback function used to monitor the upload progress percentage.
20041
+ */
19518
20042
  sendFile(file, options) {
19519
20043
  return __awaiter(this, void 0, void 0, function* () {
19520
- const streamId = crypto.randomUUID();
19521
- yield this._sendFile(streamId, file, options);
19522
- return {
19523
- id: streamId
19524
- };
19525
- });
19526
- }
19527
- _sendFile(streamId, file, options) {
19528
- return __awaiter(this, void 0, void 0, function* () {
19529
- var _a;
19530
- const writer2 = yield this.streamBytes({
19531
- streamId,
19532
- totalSize: file.size,
19533
- name: file.name,
19534
- mimeType: (_a = options === null || options === void 0 ? void 0 : options.mimeType) !== null && _a !== void 0 ? _a : file.type,
19535
- topic: options === null || options === void 0 ? void 0 : options.topic,
19536
- destinationIdentities: options === null || options === void 0 ? void 0 : options.destinationIdentities
19537
- });
19538
- const reader = file.stream().getReader();
19539
- while (true) {
19540
- const {
19541
- done,
19542
- value
19543
- } = yield reader.read();
19544
- if (done) {
19545
- break;
19546
- }
19547
- yield writer2.write(value);
19548
- }
19549
- yield writer2.close();
19550
- return writer2.info;
20044
+ return this.roomOutgoingDataStreamManager.sendFile(file, options);
19551
20045
  });
19552
20046
  }
20047
+ /**
20048
+ * Stream bytes incrementally to participants in the room via the data channel.
20049
+ * For sending files, consider using {@link sendFile} instead.
20050
+ *
20051
+ * @param options.topic Topic identifier used to route the stream to appropriate handlers.
20052
+ */
19553
20053
  streamBytes(options) {
19554
20054
  return __awaiter(this, void 0, void 0, function* () {
19555
- var _a, _b, _c, _d, _e;
19556
- const streamId = (_a = options === null || options === void 0 ? void 0 : options.streamId) !== null && _a !== void 0 ? _a : crypto.randomUUID();
19557
- const destinationIdentities = options === null || options === void 0 ? void 0 : options.destinationIdentities;
19558
- const info = {
19559
- id: streamId,
19560
- mimeType: (_b = options === null || options === void 0 ? void 0 : options.mimeType) !== null && _b !== void 0 ? _b : "application/octet-stream",
19561
- topic: (_c = options === null || options === void 0 ? void 0 : options.topic) !== null && _c !== void 0 ? _c : "",
19562
- timestamp: Date.now(),
19563
- attributes: options === null || options === void 0 ? void 0 : options.attributes,
19564
- size: options === null || options === void 0 ? void 0 : options.totalSize,
19565
- name: (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : "unknown"
19566
- };
19567
- const header = new DataStream_Header({
19568
- totalLength: numberToBigInt((_e = info.size) !== null && _e !== void 0 ? _e : 0),
19569
- mimeType: info.mimeType,
19570
- streamId,
19571
- topic: info.topic,
19572
- timestamp: numberToBigInt(Date.now()),
19573
- attributes: info.attributes,
19574
- contentHeader: {
19575
- case: "byteHeader",
19576
- value: new DataStream_ByteHeader({
19577
- name: info.name
19578
- })
19579
- }
19580
- });
19581
- const packet = new DataPacket({
19582
- destinationIdentities,
19583
- value: {
19584
- case: "streamHeader",
19585
- value: header
19586
- }
19587
- });
19588
- yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
19589
- let chunkId = 0;
19590
- const writeMutex = new _();
19591
- const engine = this.engine;
19592
- const log2 = this.log;
19593
- const writableStream = new WritableStream({
19594
- write(chunk) {
19595
- return __awaiter(this, void 0, void 0, function* () {
19596
- const unlock = yield writeMutex.lock();
19597
- let byteOffset = 0;
19598
- try {
19599
- while (byteOffset < chunk.byteLength) {
19600
- const subChunk = chunk.slice(byteOffset, byteOffset + STREAM_CHUNK_SIZE);
19601
- yield engine.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);
19602
- const chunkPacket = new DataPacket({
19603
- destinationIdentities,
19604
- value: {
19605
- case: "streamChunk",
19606
- value: new DataStream_Chunk({
19607
- content: subChunk,
19608
- streamId,
19609
- chunkIndex: numberToBigInt(chunkId)
19610
- })
19611
- }
19612
- });
19613
- yield engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
19614
- chunkId += 1;
19615
- byteOffset += subChunk.byteLength;
19616
- }
19617
- } finally {
19618
- unlock();
19619
- }
19620
- });
19621
- },
19622
- close() {
19623
- return __awaiter(this, void 0, void 0, function* () {
19624
- const trailer = new DataStream_Trailer({
19625
- streamId
19626
- });
19627
- const trailerPacket = new DataPacket({
19628
- destinationIdentities,
19629
- value: {
19630
- case: "streamTrailer",
19631
- value: trailer
19632
- }
19633
- });
19634
- yield engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
19635
- });
19636
- },
19637
- abort(err) {
19638
- log2.error("Sink error:", err);
19639
- }
19640
- });
19641
- const byteWriter = new ByteStreamWriter(writableStream, info);
19642
- return byteWriter;
20055
+ return this.roomOutgoingDataStreamManager.streamBytes(options);
19643
20056
  });
19644
20057
  }
19645
20058
  /**
@@ -19657,7 +20070,7 @@ var init_livekit_client_esm = __esm({
19657
20070
  payload,
19658
20071
  responseTimeout = 1e4
19659
20072
  } = _ref3;
19660
- return function* () {
20073
+ return (function* () {
19661
20074
  const maxRoundTripLatency = 2e3;
19662
20075
  return new Promise((resolve, reject) => __awaiter(_this5, void 0, void 0, function* () {
19663
20076
  var _a2, _b, _c, _d;
@@ -19704,7 +20117,7 @@ var init_livekit_client_esm = __esm({
19704
20117
  participantIdentity: destinationIdentity
19705
20118
  });
19706
20119
  }));
19707
- }();
20120
+ })();
19708
20121
  });
19709
20122
  }
19710
20123
  /**
@@ -20396,12 +20809,12 @@ var init_livekit_client_esm = __esm({
20396
20809
  return super.emit(event, ...args);
20397
20810
  }
20398
20811
  };
20399
- (function(ConnectionState2) {
20400
- ConnectionState2["Disconnected"] = "disconnected";
20401
- ConnectionState2["Connecting"] = "connecting";
20402
- ConnectionState2["Connected"] = "connected";
20403
- ConnectionState2["Reconnecting"] = "reconnecting";
20404
- ConnectionState2["SignalReconnecting"] = "signalReconnecting";
20812
+ (function(ConnectionState3) {
20813
+ ConnectionState3["Disconnected"] = "disconnected";
20814
+ ConnectionState3["Connecting"] = "connecting";
20815
+ ConnectionState3["Connected"] = "connected";
20816
+ ConnectionState3["Reconnecting"] = "reconnecting";
20817
+ ConnectionState3["SignalReconnecting"] = "signalReconnecting";
20405
20818
  })(ConnectionState || (ConnectionState = {}));
20406
20819
  connectionReconcileFrequency = 4 * 1e3;
20407
20820
  Room = class _Room extends eventsExports.EventEmitter {
@@ -20422,10 +20835,6 @@ var init_livekit_client_esm = __esm({
20422
20835
  this.log = livekitLogger;
20423
20836
  this.bufferedEvents = [];
20424
20837
  this.isResuming = false;
20425
- this.byteStreamControllers = /* @__PURE__ */ new Map();
20426
- this.textStreamControllers = /* @__PURE__ */ new Map();
20427
- this.byteStreamHandlers = /* @__PURE__ */ new Map();
20428
- this.textStreamHandlers = /* @__PURE__ */ new Map();
20429
20838
  this.rpcHandlers = /* @__PURE__ */ new Map();
20430
20839
  this.connect = (url, token2, opts) => __awaiter(this, void 0, void 0, function* () {
20431
20840
  var _a2;
@@ -20640,7 +21049,7 @@ var init_livekit_client_esm = __esm({
20640
21049
  return __awaiter(_this, [...args_1], void 0, function() {
20641
21050
  var _this2 = this;
20642
21051
  let stopTracks = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
20643
- return function* () {
21052
+ return (function* () {
20644
21053
  var _a2, _b2, _c2, _d;
20645
21054
  const unlock = yield _this2.disconnectLock.lock();
20646
21055
  try {
@@ -20666,7 +21075,7 @@ var init_livekit_client_esm = __esm({
20666
21075
  } finally {
20667
21076
  unlock();
20668
21077
  }
20669
- }();
21078
+ })();
20670
21079
  });
20671
21080
  };
20672
21081
  this.onPageLeave = () => __awaiter(this, void 0, void 0, function* () {
@@ -20874,8 +21283,8 @@ var init_livekit_client_esm = __esm({
20874
21283
  return;
20875
21284
  }
20876
21285
  const newStreamState = Track.streamStateFromProto(streamState.state);
21286
+ pub.track.setStreamState(newStreamState);
20877
21287
  if (newStreamState !== pub.track.streamState) {
20878
- pub.track.streamState = newStreamState;
20879
21288
  participant.emit(ParticipantEvent.TrackStreamStateChanged, pub, pub.track.streamState);
20880
21289
  this.emitWhenConnected(RoomEvent.TrackStreamStateChanged, pub, pub.track.streamState, participant);
20881
21290
  }
@@ -20915,12 +21324,8 @@ var init_livekit_client_esm = __esm({
20915
21324
  this.handleChatMessage(participant, packet.value.value);
20916
21325
  } else if (packet.value.case === "metrics") {
20917
21326
  this.handleMetrics(packet.value.value, participant);
20918
- } else if (packet.value.case === "streamHeader") {
20919
- this.handleStreamHeader(packet.value.value, packet.participantIdentity);
20920
- } else if (packet.value.case === "streamChunk") {
20921
- this.handleStreamChunk(packet.value.value);
20922
- } else if (packet.value.case === "streamTrailer") {
20923
- this.handleStreamTrailer(packet.value.value);
21327
+ } else if (packet.value.case === "streamHeader" || packet.value.case === "streamChunk" || packet.value.case === "streamTrailer") {
21328
+ this.handleDataStream(packet);
20924
21329
  } else if (packet.value.case === "rpcRequest") {
20925
21330
  const rpc = packet.value.value;
20926
21331
  this.handleIncomingRpcRequest(packet.participantIdentity, rpc.id, rpc.method, rpc.payload, rpc.responseTimeoutMs, rpc.version);
@@ -20934,7 +21339,6 @@ var init_livekit_client_esm = __esm({
20934
21339
  this.emit(RoomEvent.SipDTMFReceived, dtmf, participant);
20935
21340
  participant === null || participant === void 0 ? void 0 : participant.emit(ParticipantEvent.SipDTMFReceived, dtmf);
20936
21341
  };
20937
- this.bufferedSegments = /* @__PURE__ */ new Map();
20938
21342
  this.handleTranscription = (_remoteParticipant, transcription) => {
20939
21343
  const participant = transcription.transcribedParticipantIdentity === this.localParticipant.identity ? this.localParticipant : this.getParticipantByIdentity(transcription.transcribedParticipantIdentity);
20940
21344
  const publication = participant === null || participant === void 0 ? void 0 : participant.trackPublications.get(transcription.trackId);
@@ -20950,6 +21354,10 @@ var init_livekit_client_esm = __esm({
20950
21354
  this.handleMetrics = (metrics, participant) => {
20951
21355
  this.emit(RoomEvent.MetricsReceived, metrics, participant);
20952
21356
  };
21357
+ this.handleDataStream = (packet) => {
21358
+ this.incomingDataStreamManager.handleDataStreamPacket(packet);
21359
+ };
21360
+ this.bufferedSegments = /* @__PURE__ */ new Map();
20953
21361
  this.handleAudioPlaybackStarted = () => {
20954
21362
  if (this.canPlaybackAudio) {
20955
21363
  return;
@@ -21083,8 +21491,10 @@ var init_livekit_client_esm = __esm({
21083
21491
  this.options.videoCaptureDefaults = Object.assign(Object.assign({}, videoDefaults), options === null || options === void 0 ? void 0 : options.videoCaptureDefaults);
21084
21492
  this.options.publishDefaults = Object.assign(Object.assign({}, publishDefaults), options === null || options === void 0 ? void 0 : options.publishDefaults);
21085
21493
  this.maybeCreateEngine();
21494
+ this.incomingDataStreamManager = new IncomingDataStreamManager();
21495
+ this.outgoingDataStreamManager = new OutgoingDataStreamManager(this.engine, this.log);
21086
21496
  this.disconnectLock = new _();
21087
- this.localParticipant = new LocalParticipant("", "", this.engine, this.options, this.rpcHandlers);
21497
+ this.localParticipant = new LocalParticipant("", "", this.engine, this.options, this.rpcHandlers, this.outgoingDataStreamManager);
21088
21498
  if (this.options.videoCaptureDefaults.deviceId) {
21089
21499
  this.localParticipant.activeDeviceMap.set("videoinput", unwrapConstraint(this.options.videoCaptureDefaults.deviceId));
21090
21500
  }
@@ -21110,22 +21520,16 @@ var init_livekit_client_esm = __esm({
21110
21520
  }
21111
21521
  }
21112
21522
  registerTextStreamHandler(topic, callback) {
21113
- if (this.textStreamHandlers.has(topic)) {
21114
- throw new TypeError('A text stream handler for topic "'.concat(topic, '" has already been set.'));
21115
- }
21116
- this.textStreamHandlers.set(topic, callback);
21523
+ return this.incomingDataStreamManager.registerTextStreamHandler(topic, callback);
21117
21524
  }
21118
21525
  unregisterTextStreamHandler(topic) {
21119
- this.textStreamHandlers.delete(topic);
21526
+ return this.incomingDataStreamManager.unregisterTextStreamHandler(topic);
21120
21527
  }
21121
21528
  registerByteStreamHandler(topic, callback) {
21122
- if (this.byteStreamHandlers.has(topic)) {
21123
- throw new TypeError('A byte stream handler for topic "'.concat(topic, '" has already been set.'));
21124
- }
21125
- this.byteStreamHandlers.set(topic, callback);
21529
+ return this.incomingDataStreamManager.registerByteStreamHandler(topic, callback);
21126
21530
  }
21127
21531
  unregisterByteStreamHandler(topic) {
21128
- this.byteStreamHandlers.delete(topic);
21532
+ return this.incomingDataStreamManager.unregisterByteStreamHandler(topic);
21129
21533
  }
21130
21534
  /**
21131
21535
  * Establishes the participant as a receiver for calls of the specified RPC method.
@@ -21167,44 +21571,6 @@ var init_livekit_client_esm = __esm({
21167
21571
  unregisterRpcMethod(method) {
21168
21572
  this.rpcHandlers.delete(method);
21169
21573
  }
21170
- handleIncomingRpcRequest(callerIdentity, requestId, method, payload, responseTimeout, version2) {
21171
- return __awaiter(this, void 0, void 0, function* () {
21172
- yield this.engine.publishRpcAck(callerIdentity, requestId);
21173
- if (version2 !== 1) {
21174
- yield this.engine.publishRpcResponse(callerIdentity, requestId, null, RpcError.builtIn("UNSUPPORTED_VERSION"));
21175
- return;
21176
- }
21177
- const handler = this.rpcHandlers.get(method);
21178
- if (!handler) {
21179
- yield this.engine.publishRpcResponse(callerIdentity, requestId, null, RpcError.builtIn("UNSUPPORTED_METHOD"));
21180
- return;
21181
- }
21182
- let responseError = null;
21183
- let responsePayload = null;
21184
- try {
21185
- const response = yield handler({
21186
- requestId,
21187
- callerIdentity,
21188
- payload,
21189
- responseTimeout
21190
- });
21191
- if (byteLength(response) > MAX_PAYLOAD_BYTES) {
21192
- responseError = RpcError.builtIn("RESPONSE_PAYLOAD_TOO_LARGE");
21193
- console.warn("RPC Response payload too large for ".concat(method));
21194
- } else {
21195
- responsePayload = response;
21196
- }
21197
- } catch (error) {
21198
- if (error instanceof RpcError) {
21199
- responseError = error;
21200
- } else {
21201
- console.warn("Uncaught error returned by RPC handler for ".concat(method, ". Returning APPLICATION_ERROR instead."), error);
21202
- responseError = RpcError.builtIn("APPLICATION_ERROR");
21203
- }
21204
- }
21205
- yield this.engine.publishRpcResponse(callerIdentity, requestId, responsePayload, responseError);
21206
- });
21207
- }
21208
21574
  /**
21209
21575
  * @experimental
21210
21576
  */
@@ -21369,6 +21735,9 @@ var init_livekit_client_esm = __esm({
21369
21735
  if (this.e2eeManager) {
21370
21736
  this.e2eeManager.setupEngine(this.engine);
21371
21737
  }
21738
+ if (this.outgoingDataStreamManager) {
21739
+ this.outgoingDataStreamManager.setupEngine(this.engine);
21740
+ }
21372
21741
  }
21373
21742
  /**
21374
21743
  * getLocalDevices abstracts navigator.mediaDevices.enumerateDevices.
@@ -21579,7 +21948,7 @@ var init_livekit_client_esm = __esm({
21579
21948
  return __awaiter(this, arguments, void 0, function(kind, deviceId) {
21580
21949
  var _this3 = this;
21581
21950
  let exact = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
21582
- return function* () {
21951
+ return (function* () {
21583
21952
  var _a, _b, _c, _d, _e, _f;
21584
21953
  var _g;
21585
21954
  let success = true;
@@ -21653,7 +22022,7 @@ var init_livekit_client_esm = __esm({
21653
22022
  _this3.emit(RoomEvent.ActiveDeviceChanged, kind, deviceId);
21654
22023
  }
21655
22024
  return success;
21656
- }();
22025
+ })();
21657
22026
  });
21658
22027
  }
21659
22028
  setupLocalParticipantEvents() {
@@ -21715,7 +22084,10 @@ var init_livekit_client_esm = __esm({
21715
22084
  adaptiveStreamSettings = {};
21716
22085
  }
21717
22086
  }
21718
- participant.addSubscribedMediaTrack(mediaTrack, trackId, stream, receiver, adaptiveStreamSettings);
22087
+ const publication = participant.addSubscribedMediaTrack(mediaTrack, trackId, stream, receiver, adaptiveStreamSettings);
22088
+ if ((publication === null || publication === void 0 ? void 0 : publication.isEncrypted) && !this.e2eeManager) {
22089
+ this.emit(RoomEvent.EncryptionError, new Error("Encrypted ".concat(publication.source, " track received from participant ").concat(participant.sid, ", but room does not have encryption enabled!")));
22090
+ }
21719
22091
  }
21720
22092
  handleDisconnect() {
21721
22093
  let shouldStopTracks = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
@@ -21725,6 +22097,7 @@ var init_livekit_client_esm = __esm({
21725
22097
  this.isResuming = false;
21726
22098
  this.bufferedEvents = [];
21727
22099
  this.transcriptionReceivedTimes.clear();
22100
+ this.incomingDataStreamManager.clearHandlersAndControllers();
21728
22101
  if (this.state === ConnectionState.Disconnected) {
21729
22102
  return;
21730
22103
  }
@@ -21775,6 +22148,7 @@ var init_livekit_client_esm = __esm({
21775
22148
  if (!participant) {
21776
22149
  return;
21777
22150
  }
22151
+ this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(identity);
21778
22152
  participant.trackPublications.forEach((publication) => {
21779
22153
  participant.unpublishTrack(publication.trackSid, true);
21780
22154
  });
@@ -21782,99 +22156,44 @@ var init_livekit_client_esm = __esm({
21782
22156
  participant.setDisconnected();
21783
22157
  (_a = this.localParticipant) === null || _a === void 0 ? void 0 : _a.handleParticipantDisconnected(participant.identity);
21784
22158
  }
21785
- handleStreamHeader(streamHeader, participantIdentity) {
22159
+ handleIncomingRpcRequest(callerIdentity, requestId, method, payload, responseTimeout, version2) {
21786
22160
  return __awaiter(this, void 0, void 0, function* () {
21787
- var _a;
21788
- if (streamHeader.contentHeader.case === "byteHeader") {
21789
- const streamHandlerCallback = this.byteStreamHandlers.get(streamHeader.topic);
21790
- if (!streamHandlerCallback) {
21791
- this.log.debug("ignoring incoming byte stream due to no handler for topic", streamHeader.topic);
21792
- return;
21793
- }
21794
- let streamController;
21795
- const info = {
21796
- id: streamHeader.streamId,
21797
- name: (_a = streamHeader.contentHeader.value.name) !== null && _a !== void 0 ? _a : "unknown",
21798
- mimeType: streamHeader.mimeType,
21799
- size: streamHeader.totalLength ? Number(streamHeader.totalLength) : void 0,
21800
- topic: streamHeader.topic,
21801
- timestamp: bigIntToNumber(streamHeader.timestamp),
21802
- attributes: streamHeader.attributes
21803
- };
21804
- const stream = new ReadableStream({
21805
- start: (controller) => {
21806
- streamController = controller;
21807
- this.byteStreamControllers.set(streamHeader.streamId, {
21808
- info,
21809
- controller: streamController,
21810
- startTime: Date.now()
21811
- });
21812
- }
21813
- });
21814
- streamHandlerCallback(new ByteStreamReader(info, stream, bigIntToNumber(streamHeader.totalLength)), {
21815
- identity: participantIdentity
22161
+ yield this.engine.publishRpcAck(callerIdentity, requestId);
22162
+ if (version2 !== 1) {
22163
+ yield this.engine.publishRpcResponse(callerIdentity, requestId, null, RpcError.builtIn("UNSUPPORTED_VERSION"));
22164
+ return;
22165
+ }
22166
+ const handler = this.rpcHandlers.get(method);
22167
+ if (!handler) {
22168
+ yield this.engine.publishRpcResponse(callerIdentity, requestId, null, RpcError.builtIn("UNSUPPORTED_METHOD"));
22169
+ return;
22170
+ }
22171
+ let responseError = null;
22172
+ let responsePayload = null;
22173
+ try {
22174
+ const response = yield handler({
22175
+ requestId,
22176
+ callerIdentity,
22177
+ payload,
22178
+ responseTimeout
21816
22179
  });
21817
- } else if (streamHeader.contentHeader.case === "textHeader") {
21818
- const streamHandlerCallback = this.textStreamHandlers.get(streamHeader.topic);
21819
- if (!streamHandlerCallback) {
21820
- this.log.debug("ignoring incoming text stream due to no handler for topic", streamHeader.topic);
21821
- return;
22180
+ if (byteLength(response) > MAX_PAYLOAD_BYTES) {
22181
+ responseError = RpcError.builtIn("RESPONSE_PAYLOAD_TOO_LARGE");
22182
+ console.warn("RPC Response payload too large for ".concat(method));
22183
+ } else {
22184
+ responsePayload = response;
22185
+ }
22186
+ } catch (error) {
22187
+ if (error instanceof RpcError) {
22188
+ responseError = error;
22189
+ } else {
22190
+ console.warn("Uncaught error returned by RPC handler for ".concat(method, ". Returning APPLICATION_ERROR instead."), error);
22191
+ responseError = RpcError.builtIn("APPLICATION_ERROR");
21822
22192
  }
21823
- let streamController;
21824
- const info = {
21825
- id: streamHeader.streamId,
21826
- mimeType: streamHeader.mimeType,
21827
- size: streamHeader.totalLength ? Number(streamHeader.totalLength) : void 0,
21828
- topic: streamHeader.topic,
21829
- timestamp: Number(streamHeader.timestamp),
21830
- attributes: streamHeader.attributes
21831
- };
21832
- const stream = new ReadableStream({
21833
- start: (controller) => {
21834
- streamController = controller;
21835
- this.textStreamControllers.set(streamHeader.streamId, {
21836
- info,
21837
- controller: streamController,
21838
- startTime: Date.now()
21839
- });
21840
- }
21841
- });
21842
- streamHandlerCallback(new TextStreamReader(info, stream, bigIntToNumber(streamHeader.totalLength)), {
21843
- identity: participantIdentity
21844
- });
21845
22193
  }
22194
+ yield this.engine.publishRpcResponse(callerIdentity, requestId, responsePayload, responseError);
21846
22195
  });
21847
22196
  }
21848
- handleStreamChunk(chunk) {
21849
- const fileBuffer = this.byteStreamControllers.get(chunk.streamId);
21850
- if (fileBuffer) {
21851
- if (chunk.content.length > 0) {
21852
- fileBuffer.controller.enqueue(chunk);
21853
- }
21854
- }
21855
- const textBuffer = this.textStreamControllers.get(chunk.streamId);
21856
- if (textBuffer) {
21857
- if (chunk.content.length > 0) {
21858
- textBuffer.controller.enqueue(chunk);
21859
- }
21860
- }
21861
- }
21862
- handleStreamTrailer(trailer) {
21863
- const textBuffer = this.textStreamControllers.get(trailer.streamId);
21864
- if (textBuffer) {
21865
- textBuffer.info.attributes = Object.assign(Object.assign({}, textBuffer.info.attributes), trailer.attributes);
21866
- textBuffer.controller.close();
21867
- this.textStreamControllers.delete(trailer.streamId);
21868
- }
21869
- const fileBuffer = this.byteStreamControllers.get(trailer.streamId);
21870
- if (fileBuffer) {
21871
- {
21872
- fileBuffer.info.attributes = Object.assign(Object.assign({}, fileBuffer.info.attributes), trailer.attributes);
21873
- fileBuffer.controller.close();
21874
- this.byteStreamControllers.delete(trailer.streamId);
21875
- }
21876
- }
21877
- }
21878
22197
  /**
21879
22198
  * attempt to select the default devices if the previously selected devices are no longer available after a device change event
21880
22199
  */
@@ -23916,7 +24235,7 @@ var require_core = __commonJS({
23916
24235
  root4.CryptoJS = factory();
23917
24236
  }
23918
24237
  })(exports, function() {
23919
- var CryptoJS = CryptoJS || function(Math2, undefined2) {
24238
+ var CryptoJS = CryptoJS || (function(Math2, undefined2) {
23920
24239
  var crypto2;
23921
24240
  if (typeof window !== "undefined" && window.crypto) {
23922
24241
  crypto2 = window.crypto;
@@ -23956,7 +24275,7 @@ var require_core = __commonJS({
23956
24275
  }
23957
24276
  throw new Error("Native crypto module could not be used to get secure random number.");
23958
24277
  };
23959
- var create2 = Object.create || /* @__PURE__ */ function() {
24278
+ var create2 = Object.create || /* @__PURE__ */ (function() {
23960
24279
  function F2() {
23961
24280
  }
23962
24281
  return function(obj) {
@@ -23966,10 +24285,10 @@ var require_core = __commonJS({
23966
24285
  F2.prototype = null;
23967
24286
  return subtype;
23968
24287
  };
23969
- }();
24288
+ })();
23970
24289
  var C = {};
23971
24290
  var C_lib = C.lib = {};
23972
- var Base = C_lib.Base = /* @__PURE__ */ function() {
24291
+ var Base = C_lib.Base = /* @__PURE__ */ (function() {
23973
24292
  return {
23974
24293
  /**
23975
24294
  * Creates a new object that inherits from this object.
@@ -24068,7 +24387,7 @@ var require_core = __commonJS({
24068
24387
  return this.init.prototype.extend(this);
24069
24388
  }
24070
24389
  };
24071
- }();
24390
+ })();
24072
24391
  var WordArray = C_lib.WordArray = Base.extend({
24073
24392
  /**
24074
24393
  * Initializes a newly created word array.
@@ -24506,7 +24825,7 @@ var require_core = __commonJS({
24506
24825
  });
24507
24826
  var C_algo = C.algo = {};
24508
24827
  return C;
24509
- }(Math);
24828
+ })(Math);
24510
24829
  return CryptoJS;
24511
24830
  });
24512
24831
  }
@@ -24938,6 +25257,7 @@ var import_react15 = __toESM(require("react"));
24938
25257
 
24939
25258
  // src/hooks/use-cuekit.ts
24940
25259
  var import_react3 = require("react");
25260
+ init_livekit_client_esm();
24941
25261
 
24942
25262
  // src/hooks/use-webrtc.ts
24943
25263
  var import_react2 = require("react");
@@ -25078,6 +25398,7 @@ var useCuekit = (options) => {
25078
25398
  }, []);
25079
25399
  const [micState, setMicState] = (0, import_react3.useState)("idle");
25080
25400
  const [status, setStatus] = (0, import_react3.useState)("");
25401
+ const [muteState, setMuteState] = (0, import_react3.useState)({ isMuted: false, canMute: false });
25081
25402
  const handleNavigationCommand = (event) => {
25082
25403
  console.log(`\u2B07\uFE0F Received event from backend: ${event.type}`, event);
25083
25404
  switch (event.type) {
@@ -25142,6 +25463,22 @@ var useCuekit = (options) => {
25142
25463
  }
25143
25464
  break;
25144
25465
  }
25466
+ case "chat": {
25467
+ const chatData = event.data;
25468
+ console.log("\u{1F4AC} Chat message received:", chatData);
25469
+ if (chatData.message && chatData.sender === "ai") {
25470
+ const newMessage = {
25471
+ id: `ai-${Date.now()}`,
25472
+ role: "ai",
25473
+ text: chatData.message,
25474
+ isFinal: true,
25475
+ timestamp: new Date(chatData.timestamp || Date.now()).toISOString()
25476
+ };
25477
+ setMessages((prev) => [...prev, newMessage]);
25478
+ setMicState("listening");
25479
+ }
25480
+ break;
25481
+ }
25145
25482
  case "request_runtime_data": {
25146
25483
  console.log("\u{1F9E0} Requesting runtime data");
25147
25484
  sendRuntimeData();
@@ -25174,17 +25511,21 @@ var useCuekit = (options) => {
25174
25511
  switch (state) {
25175
25512
  case "connecting":
25176
25513
  setStatus("Connecting...");
25514
+ setMuteState((prev) => ({ ...prev, canMute: false }));
25177
25515
  break;
25178
25516
  case "connected":
25179
25517
  setStatus("");
25180
25518
  setMicState("listening");
25519
+ setMuteState((prev) => ({ ...prev, canMute: true }));
25181
25520
  break;
25182
25521
  case "disconnected":
25183
25522
  setStatus("Disconnected");
25184
25523
  setMicState("idle");
25524
+ setMuteState({ isMuted: false, canMute: false });
25185
25525
  break;
25186
25526
  case "reconnecting":
25187
25527
  setStatus("Reconnecting...");
25528
+ setMuteState((prev) => ({ ...prev, canMute: false }));
25188
25529
  break;
25189
25530
  default:
25190
25531
  break;
@@ -25206,7 +25547,88 @@ var useCuekit = (options) => {
25206
25547
  await webrtc.disconnect();
25207
25548
  clearMessages();
25208
25549
  setMicState("idle");
25550
+ setMuteState({ isMuted: false, canMute: false });
25209
25551
  }, [webrtc, clearMessages]);
25552
+ const toggleMute = (0, import_react3.useCallback)(async () => {
25553
+ if (!webrtc.isConnected) return;
25554
+ try {
25555
+ const room2 = webrtc.room;
25556
+ if (!room2) return;
25557
+ const localParticipant = room2.localParticipant;
25558
+ const audioTrack = localParticipant.getTrackPublication(Track.Source.Microphone)?.track;
25559
+ if (audioTrack) {
25560
+ if (muteState.isMuted) {
25561
+ await audioTrack.unmute();
25562
+ setMuteState((prev) => ({ ...prev, isMuted: false }));
25563
+ } else {
25564
+ await audioTrack.mute();
25565
+ setMuteState((prev) => ({ ...prev, isMuted: true }));
25566
+ }
25567
+ }
25568
+ } catch (error) {
25569
+ console.error("Failed to toggle mute:", error);
25570
+ }
25571
+ }, [webrtc, muteState.isMuted]);
25572
+ const setMute = (0, import_react3.useCallback)(
25573
+ async (muted) => {
25574
+ if (!webrtc.isConnected) return;
25575
+ try {
25576
+ const room2 = webrtc.room;
25577
+ if (!room2) return;
25578
+ const localParticipant = room2.localParticipant;
25579
+ const audioTrack = localParticipant.getTrackPublication(Track.Source.Microphone)?.track;
25580
+ if (audioTrack) {
25581
+ if (muted && !muteState.isMuted) {
25582
+ await audioTrack.mute();
25583
+ setMuteState((prev) => ({ ...prev, isMuted: true }));
25584
+ } else if (!muted && muteState.isMuted) {
25585
+ await audioTrack.unmute();
25586
+ setMuteState((prev) => ({ ...prev, isMuted: false }));
25587
+ }
25588
+ }
25589
+ } catch (error) {
25590
+ console.error("Failed to set mute:", error);
25591
+ }
25592
+ },
25593
+ [webrtc, muteState.isMuted]
25594
+ );
25595
+ const sendChatMessage = (0, import_react3.useCallback)(
25596
+ async (message) => {
25597
+ if (!webrtc.isConnected) {
25598
+ console.warn("Cannot send chat message: not connected to LiveKit");
25599
+ return;
25600
+ }
25601
+ try {
25602
+ const room2 = webrtc.room;
25603
+ if (!room2) return;
25604
+ const payload = {
25605
+ type: "chat",
25606
+ message,
25607
+ timestamp: Date.now(),
25608
+ sender: "user"
25609
+ };
25610
+ console.log("\u{1F4E4} Sending chat message via LiveKit:", payload);
25611
+ const encoder = new TextEncoder();
25612
+ const encodedData = encoder.encode(JSON.stringify(payload));
25613
+ await room2.localParticipant.publishData(encodedData, {
25614
+ reliable: true
25615
+ });
25616
+ const newMessage = {
25617
+ id: `user-${Date.now()}`,
25618
+ role: "user",
25619
+ text: message,
25620
+ isFinal: true,
25621
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
25622
+ };
25623
+ setMessages((prev) => [...prev, newMessage]);
25624
+ setMicState("thinking");
25625
+ } catch (error) {
25626
+ console.error("Failed to send chat message:", error);
25627
+ throw error;
25628
+ }
25629
+ },
25630
+ [webrtc]
25631
+ );
25210
25632
  return {
25211
25633
  ...webrtc,
25212
25634
  messages,
@@ -25215,12 +25637,16 @@ var useCuekit = (options) => {
25215
25637
  status,
25216
25638
  setStatus,
25217
25639
  connect,
25218
- disconnect
25640
+ disconnect,
25641
+ muteState,
25642
+ toggleMute,
25643
+ setMute,
25644
+ sendChatMessage
25219
25645
  };
25220
25646
  };
25221
25647
 
25222
25648
  // src/components/chat-popup.tsx
25223
- var import_react9 = __toESM(require("react"));
25649
+ var import_react11 = __toESM(require("react"));
25224
25650
 
25225
25651
  // node_modules/devlop/lib/default.js
25226
25652
  function ok() {
@@ -32817,7 +33243,7 @@ var convert = (
32817
33243
  * @param {Test} [test]
32818
33244
  * @returns {Check}
32819
33245
  */
32820
- function(test) {
33246
+ (function(test) {
32821
33247
  if (test === null || test === void 0) {
32822
33248
  return ok2;
32823
33249
  }
@@ -32831,7 +33257,7 @@ var convert = (
32831
33257
  return typeFactory(test);
32832
33258
  }
32833
33259
  throw new Error("Expected function, string, or object as test");
32834
- }
33260
+ })
32835
33261
  );
32836
33262
  function anyFactory(tests) {
32837
33263
  const checks2 = [];
@@ -34011,7 +34437,7 @@ var CallableInstance = (
34011
34437
  * @param {string | symbol} property
34012
34438
  * @returns {(...parameters: Array<unknown>) => unknown}
34013
34439
  */
34014
- function(property) {
34440
+ (function(property) {
34015
34441
  const self2 = this;
34016
34442
  const constr = self2.constructor;
34017
34443
  const proto = (
@@ -34026,7 +34452,7 @@ var CallableInstance = (
34026
34452
  };
34027
34453
  Object.setPrototypeOf(apply, proto);
34028
34454
  return apply;
34029
- }
34455
+ })
34030
34456
  );
34031
34457
 
34032
34458
  // node_modules/unified/lib/index.js
@@ -37964,6 +38390,59 @@ var PhoneOffIcon = ({ width = 24, height = 24, className, ...props }) => {
37964
38390
  };
37965
38391
  var phone_off_default = PhoneOffIcon;
37966
38392
 
38393
+ // src/components/svgs/mic-off.tsx
38394
+ var import_react9 = __toESM(require("react"));
38395
+ var MicOffIcon = ({ style, className }) => {
38396
+ return /* @__PURE__ */ import_react9.default.createElement(
38397
+ "svg",
38398
+ {
38399
+ xmlns: "http://www.w3.org/2000/svg",
38400
+ width: "24",
38401
+ height: "24",
38402
+ viewBox: "0 0 24 24",
38403
+ fill: "none",
38404
+ stroke: "currentColor",
38405
+ strokeWidth: "2",
38406
+ strokeLinecap: "round",
38407
+ strokeLinejoin: "round",
38408
+ className: `lucide lucide-mic-off-icon lucide-mic-off ${className || ""}`,
38409
+ style
38410
+ },
38411
+ /* @__PURE__ */ import_react9.default.createElement("path", { d: "M12 19v3" }),
38412
+ /* @__PURE__ */ import_react9.default.createElement("path", { d: "M15 9.34V5a3 3 0 0 0-5.68-1.33" }),
38413
+ /* @__PURE__ */ import_react9.default.createElement("path", { d: "M16.95 16.95A7 7 0 0 1 5 12v-2" }),
38414
+ /* @__PURE__ */ import_react9.default.createElement("path", { d: "M18.89 13.23A7 7 0 0 0 19 12v-2" }),
38415
+ /* @__PURE__ */ import_react9.default.createElement("path", { d: "m2 2 20 20" }),
38416
+ /* @__PURE__ */ import_react9.default.createElement("path", { d: "M9 9v3a3 3 0 0 0 5.12 2.12" })
38417
+ );
38418
+ };
38419
+ var mic_off_default = MicOffIcon;
38420
+
38421
+ // src/components/svgs/mic.tsx
38422
+ var import_react10 = __toESM(require("react"));
38423
+ var MicIcon = ({ width = 24, height = 24, className, ...props }) => {
38424
+ return /* @__PURE__ */ import_react10.default.createElement(
38425
+ "svg",
38426
+ {
38427
+ xmlns: "http://www.w3.org/2000/svg",
38428
+ width,
38429
+ height,
38430
+ viewBox: "0 0 24 24",
38431
+ fill: "none",
38432
+ stroke: "currentColor",
38433
+ strokeWidth: "2",
38434
+ strokeLinecap: "round",
38435
+ strokeLinejoin: "round",
38436
+ className,
38437
+ ...props
38438
+ },
38439
+ /* @__PURE__ */ import_react10.default.createElement("path", { d: "M12 19v3" }),
38440
+ /* @__PURE__ */ import_react10.default.createElement("path", { d: "M19 10v2a7 7 0 0 1-14 0v-2" }),
38441
+ /* @__PURE__ */ import_react10.default.createElement("rect", { x: "9", y: "2", width: "6", height: "13", rx: "3" })
38442
+ );
38443
+ };
38444
+ var mic_default = MicIcon;
38445
+
37967
38446
  // src/components/chat-popup.tsx
37968
38447
  var ChatPopup = ({
37969
38448
  isOpen,
@@ -37980,15 +38459,17 @@ var ChatPopup = ({
37980
38459
  currentTheme = "dark",
37981
38460
  onThemeToggle,
37982
38461
  status,
37983
- anchor
38462
+ anchor,
38463
+ muteState,
38464
+ onToggleMute
37984
38465
  }) => {
37985
- const [inputText, setInputText] = (0, import_react9.useState)("");
37986
- const [isSending, setIsSending] = (0, import_react9.useState)(false);
37987
- const messagesEndRef = (0, import_react9.useRef)(null);
38466
+ const [inputText, setInputText] = (0, import_react11.useState)("");
38467
+ const [isSending, setIsSending] = (0, import_react11.useState)(false);
38468
+ const messagesEndRef = (0, import_react11.useRef)(null);
37988
38469
  const scrollToBottom = () => {
37989
38470
  messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
37990
38471
  };
37991
- (0, import_react9.useEffect)(() => {
38472
+ (0, import_react11.useEffect)(() => {
37992
38473
  console.log("\u{1F4EC} ChatPopup received messages:", JSON.stringify(messages, null, 2));
37993
38474
  scrollToBottom();
37994
38475
  }, [messages]);
@@ -38050,7 +38531,7 @@ var ChatPopup = ({
38050
38531
  }
38051
38532
  };
38052
38533
  const positionStyle = getPositionStyle();
38053
- return /* @__PURE__ */ import_react9.default.createElement(
38534
+ return /* @__PURE__ */ import_react11.default.createElement(
38054
38535
  "div",
38055
38536
  {
38056
38537
  "data-cuekit-ignore": true,
@@ -38073,7 +38554,7 @@ var ChatPopup = ({
38073
38554
  ...positionStyle
38074
38555
  }
38075
38556
  },
38076
- /* @__PURE__ */ import_react9.default.createElement(
38557
+ /* @__PURE__ */ import_react11.default.createElement(
38077
38558
  "div",
38078
38559
  {
38079
38560
  style: {
@@ -38084,14 +38565,14 @@ var ChatPopup = ({
38084
38565
  justifyContent: "space-between"
38085
38566
  }
38086
38567
  },
38087
- /* @__PURE__ */ import_react9.default.createElement("div", { style: { display: "flex", alignItems: "center", gap: 0 } }, /* @__PURE__ */ import_react9.default.createElement(
38568
+ /* @__PURE__ */ import_react11.default.createElement("div", { style: { display: "flex", alignItems: "center", gap: 0 } }, /* @__PURE__ */ import_react11.default.createElement(
38088
38569
  "img",
38089
38570
  {
38090
38571
  src: "https://dashboard.cuekit.ai/_next/image?url=%2Fimages%2Fcuekit-logo-2.png&w=256&q=100",
38091
38572
  alt: "Cuekit AI",
38092
38573
  style: { width: 58, objectFit: "cover" }
38093
38574
  }
38094
- ), /* @__PURE__ */ import_react9.default.createElement(
38575
+ ), /* @__PURE__ */ import_react11.default.createElement(
38095
38576
  "div",
38096
38577
  {
38097
38578
  style: {
@@ -38102,7 +38583,7 @@ var ChatPopup = ({
38102
38583
  justifyContent: "center"
38103
38584
  }
38104
38585
  },
38105
- /* @__PURE__ */ import_react9.default.createElement(
38586
+ /* @__PURE__ */ import_react11.default.createElement(
38106
38587
  "span",
38107
38588
  {
38108
38589
  style: {
@@ -38117,9 +38598,9 @@ var ChatPopup = ({
38117
38598
  WebkitTextFillColor: "transparent"
38118
38599
  }
38119
38600
  },
38120
- "Cuekit.ai"
38601
+ "ansyr.ai"
38121
38602
  ),
38122
- /* @__PURE__ */ import_react9.default.createElement("div", { style: { display: "flex", flexDirection: "column", alignItems: "center", gap: 4 } }, /* @__PURE__ */ import_react9.default.createElement(
38603
+ /* @__PURE__ */ import_react11.default.createElement("div", { style: { display: "flex", flexDirection: "column", alignItems: "center", gap: 4 } }, /* @__PURE__ */ import_react11.default.createElement(
38123
38604
  "div",
38124
38605
  {
38125
38606
  style: {
@@ -38135,7 +38616,7 @@ var ChatPopup = ({
38135
38616
  fontWeight: "500"
38136
38617
  }
38137
38618
  },
38138
- /* @__PURE__ */ import_react9.default.createElement(
38619
+ /* @__PURE__ */ import_react11.default.createElement(
38139
38620
  "span",
38140
38621
  {
38141
38622
  style: {
@@ -38146,8 +38627,8 @@ var ChatPopup = ({
38146
38627
  )
38147
38628
  ))
38148
38629
  )),
38149
- /* @__PURE__ */ import_react9.default.createElement("div", { style: { minWidth: 100, textAlign: "center" } }),
38150
- /* @__PURE__ */ import_react9.default.createElement(
38630
+ /* @__PURE__ */ import_react11.default.createElement("div", { style: { minWidth: 100, textAlign: "center" } }),
38631
+ /* @__PURE__ */ import_react11.default.createElement(
38151
38632
  "div",
38152
38633
  {
38153
38634
  style: {
@@ -38159,7 +38640,7 @@ var ChatPopup = ({
38159
38640
  top: 16
38160
38641
  }
38161
38642
  },
38162
- onThemeToggle && /* @__PURE__ */ import_react9.default.createElement(
38643
+ onThemeToggle && /* @__PURE__ */ import_react11.default.createElement(
38163
38644
  "button",
38164
38645
  {
38165
38646
  onClick: () => {
@@ -38189,7 +38670,7 @@ var ChatPopup = ({
38189
38670
  "aria-label": "Toggle theme",
38190
38671
  title: `Switch to ${currentTheme === "dark" ? "light" : "dark"} mode`
38191
38672
  },
38192
- currentTheme === "dark" ? /* @__PURE__ */ import_react9.default.createElement(
38673
+ currentTheme === "dark" ? /* @__PURE__ */ import_react11.default.createElement(
38193
38674
  sun_default,
38194
38675
  {
38195
38676
  style: {
@@ -38199,7 +38680,7 @@ var ChatPopup = ({
38199
38680
  animation: "themeToggleEnter 0.3s ease-in-out"
38200
38681
  }
38201
38682
  }
38202
- ) : /* @__PURE__ */ import_react9.default.createElement(
38683
+ ) : /* @__PURE__ */ import_react11.default.createElement(
38203
38684
  moon_default,
38204
38685
  {
38205
38686
  style: {
@@ -38211,7 +38692,7 @@ var ChatPopup = ({
38211
38692
  }
38212
38693
  )
38213
38694
  ),
38214
- /* @__PURE__ */ import_react9.default.createElement(
38695
+ /* @__PURE__ */ import_react11.default.createElement(
38215
38696
  "button",
38216
38697
  {
38217
38698
  onClick: onMinimize,
@@ -38238,11 +38719,11 @@ var ChatPopup = ({
38238
38719
  "aria-label": "Minimize",
38239
38720
  title: "Minimize chat"
38240
38721
  },
38241
- /* @__PURE__ */ import_react9.default.createElement(close_default, { style: { width: 16, height: 16, color: "hsl(var(--voice-text-muted))" } })
38722
+ /* @__PURE__ */ import_react11.default.createElement(close_default, { style: { width: 16, height: 16, color: "hsl(var(--voice-text-muted))" } })
38242
38723
  )
38243
38724
  )
38244
38725
  ),
38245
- /* @__PURE__ */ import_react9.default.createElement(
38726
+ /* @__PURE__ */ import_react11.default.createElement(
38246
38727
  "div",
38247
38728
  {
38248
38729
  style: {
@@ -38255,7 +38736,7 @@ var ChatPopup = ({
38255
38736
  color: "hsl(var(--voice-text))"
38256
38737
  }
38257
38738
  },
38258
- messages.length === 0 ? /* @__PURE__ */ import_react9.default.createElement(
38739
+ messages.length === 0 ? /* @__PURE__ */ import_react11.default.createElement(
38259
38740
  "div",
38260
38741
  {
38261
38742
  style: {
@@ -38265,7 +38746,7 @@ var ChatPopup = ({
38265
38746
  }
38266
38747
  },
38267
38748
  "Start a conversation with CueKit AI"
38268
- ) : messages.map((message, index2) => /* @__PURE__ */ import_react9.default.createElement(
38749
+ ) : messages.map((message, index2) => /* @__PURE__ */ import_react11.default.createElement(
38269
38750
  "div",
38270
38751
  {
38271
38752
  key: index2,
@@ -38279,7 +38760,7 @@ var ChatPopup = ({
38279
38760
  justifyContent: message.sender === "user" ? "flex-end" : "flex-start"
38280
38761
  }
38281
38762
  },
38282
- message.sender === "assistant" && /* @__PURE__ */ import_react9.default.createElement(
38763
+ message.sender === "assistant" && /* @__PURE__ */ import_react11.default.createElement(
38283
38764
  "div",
38284
38765
  {
38285
38766
  style: {
@@ -38294,7 +38775,7 @@ var ChatPopup = ({
38294
38775
  overflow: "hidden"
38295
38776
  }
38296
38777
  },
38297
- /* @__PURE__ */ import_react9.default.createElement(
38778
+ /* @__PURE__ */ import_react11.default.createElement(
38298
38779
  "img",
38299
38780
  {
38300
38781
  src: "https://dashboard.cuekit.ai/_next/image?url=%2Fimages%2Fcuekit-logo-2.png&w=256&q=100",
@@ -38308,7 +38789,7 @@ var ChatPopup = ({
38308
38789
  }
38309
38790
  )
38310
38791
  ),
38311
- /* @__PURE__ */ import_react9.default.createElement(
38792
+ /* @__PURE__ */ import_react11.default.createElement(
38312
38793
  "div",
38313
38794
  {
38314
38795
  style: {
@@ -38319,7 +38800,7 @@ var ChatPopup = ({
38319
38800
  flex: 1
38320
38801
  }
38321
38802
  },
38322
- /* @__PURE__ */ import_react9.default.createElement(
38803
+ /* @__PURE__ */ import_react11.default.createElement(
38323
38804
  "div",
38324
38805
  {
38325
38806
  style: {
@@ -38337,12 +38818,12 @@ var ChatPopup = ({
38337
38818
  marginLeft: message.sender === "user" ? "auto" : 0
38338
38819
  }
38339
38820
  },
38340
- /* @__PURE__ */ import_react9.default.createElement("div", null, /* @__PURE__ */ import_react9.default.createElement(
38821
+ /* @__PURE__ */ import_react11.default.createElement("div", null, /* @__PURE__ */ import_react11.default.createElement(
38341
38822
  Markdown,
38342
38823
  {
38343
38824
  remarkPlugins: [remarkGfm],
38344
38825
  components: {
38345
- p: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38826
+ p: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38346
38827
  "p",
38347
38828
  {
38348
38829
  style: {
@@ -38353,7 +38834,7 @@ var ChatPopup = ({
38353
38834
  },
38354
38835
  children
38355
38836
  ),
38356
- h1: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38837
+ h1: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38357
38838
  "h1",
38358
38839
  {
38359
38840
  style: {
@@ -38365,7 +38846,7 @@ var ChatPopup = ({
38365
38846
  },
38366
38847
  children
38367
38848
  ),
38368
- h2: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38849
+ h2: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38369
38850
  "h2",
38370
38851
  {
38371
38852
  style: {
@@ -38377,7 +38858,7 @@ var ChatPopup = ({
38377
38858
  },
38378
38859
  children
38379
38860
  ),
38380
- h3: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38861
+ h3: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38381
38862
  "h3",
38382
38863
  {
38383
38864
  style: {
@@ -38389,7 +38870,7 @@ var ChatPopup = ({
38389
38870
  },
38390
38871
  children
38391
38872
  ),
38392
- ul: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38873
+ ul: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38393
38874
  "ul",
38394
38875
  {
38395
38876
  style: {
@@ -38401,7 +38882,7 @@ var ChatPopup = ({
38401
38882
  },
38402
38883
  children
38403
38884
  ),
38404
- ol: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38885
+ ol: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38405
38886
  "ol",
38406
38887
  {
38407
38888
  style: {
@@ -38413,7 +38894,7 @@ var ChatPopup = ({
38413
38894
  },
38414
38895
  children
38415
38896
  ),
38416
- li: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38897
+ li: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38417
38898
  "li",
38418
38899
  {
38419
38900
  style: {
@@ -38424,7 +38905,7 @@ var ChatPopup = ({
38424
38905
  },
38425
38906
  children
38426
38907
  ),
38427
- strong: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38908
+ strong: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38428
38909
  "strong",
38429
38910
  {
38430
38911
  style: {
@@ -38435,7 +38916,7 @@ var ChatPopup = ({
38435
38916
  },
38436
38917
  children
38437
38918
  ),
38438
- em: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38919
+ em: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38439
38920
  "em",
38440
38921
  {
38441
38922
  style: {
@@ -38446,7 +38927,7 @@ var ChatPopup = ({
38446
38927
  },
38447
38928
  children
38448
38929
  ),
38449
- code: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38930
+ code: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38450
38931
  "code",
38451
38932
  {
38452
38933
  style: {
@@ -38459,7 +38940,7 @@ var ChatPopup = ({
38459
38940
  },
38460
38941
  children
38461
38942
  ),
38462
- pre: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38943
+ pre: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38463
38944
  "pre",
38464
38945
  {
38465
38946
  style: {
@@ -38474,7 +38955,7 @@ var ChatPopup = ({
38474
38955
  },
38475
38956
  children
38476
38957
  ),
38477
- blockquote: ({ children }) => /* @__PURE__ */ import_react9.default.createElement(
38958
+ blockquote: ({ children }) => /* @__PURE__ */ import_react11.default.createElement(
38478
38959
  "blockquote",
38479
38960
  {
38480
38961
  style: {
@@ -38493,7 +38974,7 @@ var ChatPopup = ({
38493
38974
  message.text
38494
38975
  ))
38495
38976
  ),
38496
- message.sender === "user" && /* @__PURE__ */ import_react9.default.createElement(
38977
+ message.sender === "user" && /* @__PURE__ */ import_react11.default.createElement(
38497
38978
  "div",
38498
38979
  {
38499
38980
  style: {
@@ -38514,9 +38995,9 @@ var ChatPopup = ({
38514
38995
  )
38515
38996
  )
38516
38997
  )),
38517
- /* @__PURE__ */ import_react9.default.createElement("div", { ref: messagesEndRef })
38998
+ /* @__PURE__ */ import_react11.default.createElement("div", { ref: messagesEndRef })
38518
38999
  ),
38519
- /* @__PURE__ */ import_react9.default.createElement(
39000
+ /* @__PURE__ */ import_react11.default.createElement(
38520
39001
  "div",
38521
39002
  {
38522
39003
  style: {
@@ -38525,7 +39006,7 @@ var ChatPopup = ({
38525
39006
  background: "hsl(var(--voice-bg))"
38526
39007
  }
38527
39008
  },
38528
- /* @__PURE__ */ import_react9.default.createElement(
39009
+ /* @__PURE__ */ import_react11.default.createElement(
38529
39010
  "form",
38530
39011
  {
38531
39012
  onSubmit: (e3) => {
@@ -38534,7 +39015,7 @@ var ChatPopup = ({
38534
39015
  },
38535
39016
  style: { display: "flex", alignItems: "center", gap: 8, margin: 0 }
38536
39017
  },
38537
- /* @__PURE__ */ import_react9.default.createElement(
39018
+ /* @__PURE__ */ import_react11.default.createElement(
38538
39019
  "input",
38539
39020
  {
38540
39021
  type: "text",
@@ -38561,7 +39042,47 @@ var ChatPopup = ({
38561
39042
  }
38562
39043
  }
38563
39044
  ),
38564
- isConnected2 && onEndCall && /* @__PURE__ */ import_react9.default.createElement(
39045
+ muteState?.canMute && onToggleMute && /* @__PURE__ */ import_react11.default.createElement(
39046
+ "button",
39047
+ {
39048
+ onClick: onToggleMute,
39049
+ style: {
39050
+ padding: "10px 12px",
39051
+ borderRadius: 8,
39052
+ border: "1px solid hsl(var(--voice-accent))",
39053
+ background: "hsl(var(--voice-accent))",
39054
+ fontSize: 12,
39055
+ fontWeight: 700,
39056
+ display: "flex",
39057
+ alignItems: "center",
39058
+ justifyContent: "center",
39059
+ cursor: "pointer",
39060
+ transition: "all 0.3s ease"
39061
+ },
39062
+ "aria-label": muteState.isMuted ? "Unmute microphone" : "Mute microphone",
39063
+ title: muteState.isMuted ? "Unmute microphone" : "Mute microphone"
39064
+ },
39065
+ muteState.isMuted ? /* @__PURE__ */ import_react11.default.createElement(
39066
+ mic_default,
39067
+ {
39068
+ style: {
39069
+ width: 16,
39070
+ height: 16,
39071
+ color: "hsl(var(--voice-user-text))"
39072
+ }
39073
+ }
39074
+ ) : /* @__PURE__ */ import_react11.default.createElement(
39075
+ mic_off_default,
39076
+ {
39077
+ style: {
39078
+ width: 16,
39079
+ height: 16,
39080
+ color: "hsl(var(--voice-user-text))"
39081
+ }
39082
+ }
39083
+ )
39084
+ ),
39085
+ isConnected2 && onEndCall && /* @__PURE__ */ import_react11.default.createElement(
38565
39086
  "button",
38566
39087
  {
38567
39088
  type: "submit",
@@ -38580,7 +39101,7 @@ var ChatPopup = ({
38580
39101
  cursor: "pointer"
38581
39102
  }
38582
39103
  },
38583
- /* @__PURE__ */ import_react9.default.createElement(phone_off_default, { style: { width: 16, height: 16 } })
39104
+ /* @__PURE__ */ import_react11.default.createElement(phone_off_default, { style: { width: 16, height: 16 } })
38584
39105
  )
38585
39106
  )
38586
39107
  )
@@ -38588,7 +39109,7 @@ var ChatPopup = ({
38588
39109
  };
38589
39110
 
38590
39111
  // src/components/border-glow.tsx
38591
- var import_react10 = __toESM(require("react"));
39112
+ var import_react12 = __toESM(require("react"));
38592
39113
  var BorderGlow = ({ isActive }) => {
38593
39114
  if (!isActive) return null;
38594
39115
  const styles = {
@@ -38715,7 +39236,7 @@ var BorderGlow = ({ isActive }) => {
38715
39236
  opacity: 0.6
38716
39237
  }
38717
39238
  };
38718
- return /* @__PURE__ */ import_react10.default.createElement(import_react10.default.Fragment, null, /* @__PURE__ */ import_react10.default.createElement("style", null, `
39239
+ return /* @__PURE__ */ import_react12.default.createElement(import_react12.default.Fragment, null, /* @__PURE__ */ import_react12.default.createElement("style", null, `
38719
39240
  @keyframes borderPulse {
38720
39241
  0%, 100% {
38721
39242
  opacity: 1;
@@ -38724,12 +39245,12 @@ var BorderGlow = ({ isActive }) => {
38724
39245
  opacity: 0.5;
38725
39246
  }
38726
39247
  }
38727
- `), /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.container }, /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.rightBorder1 }), /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.rightBorder2 }), /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.rightBorder3 }), /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.leftBorder1 }), /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.leftBorder2 }), /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.leftBorder3 }), /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.cornerTopLeft }), /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.cornerTopRight }), /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.cornerBottomRight }), /* @__PURE__ */ import_react10.default.createElement("div", { style: styles.cornerBottomLeft })));
39248
+ `), /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.container }, /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.rightBorder1 }), /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.rightBorder2 }), /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.rightBorder3 }), /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.leftBorder1 }), /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.leftBorder2 }), /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.leftBorder3 }), /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.cornerTopLeft }), /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.cornerTopRight }), /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.cornerBottomRight }), /* @__PURE__ */ import_react12.default.createElement("div", { style: styles.cornerBottomLeft })));
38728
39249
  };
38729
39250
  var border_glow_default = BorderGlow;
38730
39251
 
38731
39252
  // src/components/voice-intensity-visualizer.tsx
38732
- var import_react12 = __toESM(require("react"));
39253
+ var import_react14 = __toESM(require("react"));
38733
39254
 
38734
39255
  // node_modules/@livekit/components-react/dist/hooks-C2Bp5v2q.mjs
38735
39256
  var r2 = __toESM(require("react"), 1);
@@ -38745,7 +39266,7 @@ var Me = { exports: {} };
38745
39266
  var Or = Me.exports;
38746
39267
  var kt;
38747
39268
  function kr() {
38748
- return kt || (kt = 1, function(e3) {
39269
+ return kt || (kt = 1, (function(e3) {
38749
39270
  (function(t, n) {
38750
39271
  e3.exports ? e3.exports = n() : t.log = n();
38751
39272
  })(Or, function() {
@@ -38889,7 +39410,7 @@ function kr() {
38889
39410
  return o2;
38890
39411
  }, s.default = s, s;
38891
39412
  });
38892
- }(Me)), Me.exports;
39413
+ })(Me)), Me.exports;
38893
39414
  }
38894
39415
  var _r = kr();
38895
39416
  var Lr = /* @__PURE__ */ Ar(_r);
@@ -39112,7 +39633,7 @@ function Ue(e3, t) {
39112
39633
  0 <= n && e3.splice(n, 1);
39113
39634
  }
39114
39635
  }
39115
- var Oe = function() {
39636
+ var Oe = (function() {
39116
39637
  function e3(t) {
39117
39638
  this.initialTeardown = t, this.closed = false, this._parentage = null, this._finalizers = null;
39118
39639
  }
@@ -39196,11 +39717,11 @@ var Oe = function() {
39196
39717
  }, e3.prototype.remove = function(t) {
39197
39718
  var n = this._finalizers;
39198
39719
  n && Ue(n, t), t instanceof e3 && t._removeParent(this);
39199
- }, e3.EMPTY = function() {
39720
+ }, e3.EMPTY = (function() {
39200
39721
  var t = new e3();
39201
39722
  return t.closed = true, t;
39202
- }(), e3;
39203
- }();
39723
+ })(), e3;
39724
+ })();
39204
39725
  var an = Oe.EMPTY;
39205
39726
  function cn(e3) {
39206
39727
  return e3 instanceof Oe || e3 && "closed" in e3 && P(e3.remove) && P(e3.add) && P(e3.unsubscribe);
@@ -39232,7 +39753,7 @@ function je() {
39232
39753
  function Re(e3) {
39233
39754
  e3();
39234
39755
  }
39235
- var gt = function(e3) {
39756
+ var gt = (function(e3) {
39236
39757
  te(t, e3);
39237
39758
  function t(n) {
39238
39759
  var r3 = e3.call(this) || this;
@@ -39263,8 +39784,8 @@ var gt = function(e3) {
39263
39784
  this.unsubscribe();
39264
39785
  }
39265
39786
  }, t;
39266
- }(Oe);
39267
- var Nr = function() {
39787
+ })(Oe);
39788
+ var Nr = (function() {
39268
39789
  function e3(t) {
39269
39790
  this.partialObserver = t;
39270
39791
  }
@@ -39295,8 +39816,8 @@ var Nr = function() {
39295
39816
  Le(n);
39296
39817
  }
39297
39818
  }, e3;
39298
- }();
39299
- var Ce = function(e3) {
39819
+ })();
39820
+ var Ce = (function(e3) {
39300
39821
  te(t, e3);
39301
39822
  function t(n, r3, i2) {
39302
39823
  var o2 = e3.call(this) || this, s;
@@ -39307,7 +39828,7 @@ var Ce = function(e3) {
39307
39828
  } : s = n, o2.destination = new Nr(s), o2;
39308
39829
  }
39309
39830
  return t;
39310
- }(gt);
39831
+ })(gt);
39311
39832
  function Le(e3) {
39312
39833
  un(e3);
39313
39834
  }
@@ -39320,9 +39841,9 @@ var Ur = {
39320
39841
  error: Fr,
39321
39842
  complete: je
39322
39843
  };
39323
- var bt = function() {
39844
+ var bt = (function() {
39324
39845
  return typeof Symbol == "function" && Symbol.observable || "@@observable";
39325
- }();
39846
+ })();
39326
39847
  function Ge(e3) {
39327
39848
  return e3;
39328
39849
  }
@@ -39333,7 +39854,7 @@ function jr(e3) {
39333
39854
  }, n);
39334
39855
  };
39335
39856
  }
39336
- var k = function() {
39857
+ var k = (function() {
39337
39858
  function e3(t) {
39338
39859
  t && (this._subscribe = t);
39339
39860
  }
@@ -39392,7 +39913,7 @@ var k = function() {
39392
39913
  }, e3.create = function(t) {
39393
39914
  return new e3(t);
39394
39915
  }, e3;
39395
- }();
39916
+ })();
39396
39917
  function Lt(e3) {
39397
39918
  var t;
39398
39919
  return (t = e3 ?? Dr.Promise) !== null && t !== void 0 ? t : Promise;
@@ -39422,7 +39943,7 @@ function j(e3) {
39422
39943
  function F(e3, t, n, r3, i2) {
39423
39944
  return new Hr(e3, t, n, r3, i2);
39424
39945
  }
39425
- var Hr = function(e3) {
39946
+ var Hr = (function(e3) {
39426
39947
  te(t, e3);
39427
39948
  function t(n, r3, i2, o2, s, a) {
39428
39949
  var c = e3.call(this, n) || this;
@@ -39457,13 +39978,13 @@ var Hr = function(e3) {
39457
39978
  e3.prototype.unsubscribe.call(this), !r3 && ((n = this.onFinalize) === null || n === void 0 || n.call(this));
39458
39979
  }
39459
39980
  }, t;
39460
- }(gt);
39981
+ })(gt);
39461
39982
  var zr = mt(function(e3) {
39462
39983
  return function() {
39463
39984
  e3(this), this.name = "ObjectUnsubscribedError", this.message = "object unsubscribed";
39464
39985
  };
39465
39986
  });
39466
- var ee = function(e3) {
39987
+ var ee = (function(e3) {
39467
39988
  te(t, e3);
39468
39989
  function t() {
39469
39990
  var n = e3.call(this) || this;
@@ -39542,8 +40063,8 @@ var ee = function(e3) {
39542
40063
  }, t.create = function(n, r3) {
39543
40064
  return new It(n, r3);
39544
40065
  }, t;
39545
- }(k);
39546
- var It = function(e3) {
40066
+ })(k);
40067
+ var It = (function(e3) {
39547
40068
  te(t, e3);
39548
40069
  function t(n, r3) {
39549
40070
  var i2 = e3.call(this) || this;
@@ -39562,8 +40083,8 @@ var It = function(e3) {
39562
40083
  var r3, i2;
39563
40084
  return (i2 = (r3 = this.source) === null || r3 === void 0 ? void 0 : r3.subscribe(n)) !== null && i2 !== void 0 ? i2 : an;
39564
40085
  }, t;
39565
- }(ee);
39566
- var ln = function(e3) {
40086
+ })(ee);
40087
+ var ln = (function(e3) {
39567
40088
  te(t, e3);
39568
40089
  function t(n) {
39569
40090
  var r3 = e3.call(this) || this;
@@ -39586,13 +40107,13 @@ var ln = function(e3) {
39586
40107
  }, t.prototype.next = function(n) {
39587
40108
  e3.prototype.next.call(this, this._value = n);
39588
40109
  }, t;
39589
- }(ee);
40110
+ })(ee);
39590
40111
  var Yr = {
39591
40112
  now: function() {
39592
40113
  return Date.now();
39593
40114
  }
39594
40115
  };
39595
- var qr = function(e3) {
40116
+ var qr = (function(e3) {
39596
40117
  te(t, e3);
39597
40118
  function t(n, r3) {
39598
40119
  return e3.call(this) || this;
@@ -39600,7 +40121,7 @@ var qr = function(e3) {
39600
40121
  return t.prototype.schedule = function(n, r3) {
39601
40122
  return this;
39602
40123
  }, t;
39603
- }(Oe);
40124
+ })(Oe);
39604
40125
  var Mt = {
39605
40126
  setInterval: function(e3, t) {
39606
40127
  for (var n = [], r3 = 2; r3 < arguments.length; r3++)
@@ -39612,7 +40133,7 @@ var Mt = {
39612
40133
  },
39613
40134
  delegate: void 0
39614
40135
  };
39615
- var Kr = function(e3) {
40136
+ var Kr = (function(e3) {
39616
40137
  te(t, e3);
39617
40138
  function t(n, r3) {
39618
40139
  var i2 = e3.call(this, n, r3) || this;
@@ -39654,16 +40175,16 @@ var Kr = function(e3) {
39654
40175
  this.work = this.state = this.scheduler = null, this.pending = false, Ue(o2, this), r3 != null && (this.id = this.recycleAsyncId(i2, r3, null)), this.delay = null, e3.prototype.unsubscribe.call(this);
39655
40176
  }
39656
40177
  }, t;
39657
- }(qr);
39658
- var Rt = function() {
40178
+ })(qr);
40179
+ var Rt = (function() {
39659
40180
  function e3(t, n) {
39660
40181
  n === void 0 && (n = e3.now), this.schedulerActionCtor = t, this.now = n;
39661
40182
  }
39662
40183
  return e3.prototype.schedule = function(t, n, r3) {
39663
40184
  return n === void 0 && (n = 0), new this.schedulerActionCtor(this, t).schedule(r3, n);
39664
40185
  }, e3.now = Yr.now, e3;
39665
- }();
39666
- var Gr = function(e3) {
40186
+ })();
40187
+ var Gr = (function(e3) {
39667
40188
  te(t, e3);
39668
40189
  function t(n, r3) {
39669
40190
  r3 === void 0 && (r3 = Rt.now);
@@ -39688,7 +40209,7 @@ var Gr = function(e3) {
39688
40209
  throw i2;
39689
40210
  }
39690
40211
  }, t;
39691
- }(Rt);
40212
+ })(Rt);
39692
40213
  var Qr = new Gr(Kr);
39693
40214
  function Jr(e3) {
39694
40215
  return e3 && P(e3.schedule);
@@ -40375,7 +40896,7 @@ function Yt(e3, t = {}) {
40375
40896
 
40376
40897
  // node_modules/@livekit/components-react/dist/components-Bz2b1Fa9.mjs
40377
40898
  var e2 = __toESM(require("react"), 1);
40378
- var import_react11 = require("react");
40899
+ var import_react13 = require("react");
40379
40900
  init_livekit_client_esm();
40380
40901
  var Y;
40381
40902
  var ue;
@@ -40470,8 +40991,8 @@ var Dt = (t) => {
40470
40991
  };
40471
40992
  var fe2 = (t) => [[Math.floor(t / 2)], [-1]];
40472
40993
  var Ut2 = (t, n, a) => {
40473
- const [r3, c] = (0, import_react11.useState)(0), [s, o2] = (0, import_react11.useState)([[]]);
40474
- (0, import_react11.useEffect)(() => {
40994
+ const [r3, c] = (0, import_react13.useState)(0), [s, o2] = (0, import_react13.useState)([[]]);
40995
+ (0, import_react13.useEffect)(() => {
40475
40996
  if (t === "thinking")
40476
40997
  o2(fe2(n));
40477
40998
  else if (t === "connecting" || t === "initializing") {
@@ -40480,8 +41001,8 @@ var Ut2 = (t, n, a) => {
40480
41001
  } else o2(t === "listening" ? fe2(n) : t === void 0 || t === "speaking" ? [new Array(n).fill(0).map((i2, u) => u)] : [[]]);
40481
41002
  c(0);
40482
41003
  }, [t, n]);
40483
- const l = (0, import_react11.useRef)(null);
40484
- return (0, import_react11.useEffect)(() => {
41004
+ const l = (0, import_react13.useRef)(null);
41005
+ return (0, import_react13.useEffect)(() => {
40485
41006
  let i2 = performance.now();
40486
41007
  const u = (d) => {
40487
41008
  d - i2 >= a && (c((f) => f + 1), i2 = d), l.current = requestAnimationFrame(u);
@@ -40551,8 +41072,8 @@ var Xt = /* @__PURE__ */ e2.forwardRef(
40551
41072
  init_livekit_client_esm();
40552
41073
  init_webrtc_service();
40553
41074
  var VoiceIntensityWithRoom = (props) => {
40554
- const [room2, setRoom] = (0, import_react12.useState)(null);
40555
- (0, import_react12.useEffect)(() => {
41075
+ const [room2, setRoom] = (0, import_react14.useState)(null);
41076
+ (0, import_react14.useEffect)(() => {
40556
41077
  if (props.isActive) {
40557
41078
  const currentRoom = getRoom();
40558
41079
  if (currentRoom) {
@@ -40565,7 +41086,7 @@ var VoiceIntensityWithRoom = (props) => {
40565
41086
  if (!room2) {
40566
41087
  return null;
40567
41088
  }
40568
- return /* @__PURE__ */ import_react12.default.createElement(Wn.Provider, { value: room2 }, /* @__PURE__ */ import_react12.default.createElement(VoiceIntensityBars, { ...props }));
41089
+ return /* @__PURE__ */ import_react14.default.createElement(Wn.Provider, { value: room2 }, /* @__PURE__ */ import_react14.default.createElement(VoiceIntensityBars, { ...props }));
40569
41090
  };
40570
41091
  var VoiceIntensityBars = ({
40571
41092
  isActive,
@@ -40608,7 +41129,7 @@ var VoiceIntensityBars = ({
40608
41129
  if (!trackRef) {
40609
41130
  return null;
40610
41131
  }
40611
- return /* @__PURE__ */ import_react12.default.createElement(
41132
+ return /* @__PURE__ */ import_react14.default.createElement(
40612
41133
  "div",
40613
41134
  {
40614
41135
  className: `voice-intensity-visualizer ${className}`,
@@ -40625,7 +41146,7 @@ var VoiceIntensityBars = ({
40625
41146
  pointerEvents: "none"
40626
41147
  }
40627
41148
  },
40628
- /* @__PURE__ */ import_react12.default.createElement(
41149
+ /* @__PURE__ */ import_react14.default.createElement(
40629
41150
  Xt,
40630
41151
  {
40631
41152
  barCount,
@@ -40639,7 +41160,7 @@ var VoiceIntensityBars = ({
40639
41160
  gap: "0.25rem"
40640
41161
  }
40641
41162
  },
40642
- /* @__PURE__ */ import_react12.default.createElement("span", { className: "cuekit-voice-intensity-bar" })
41163
+ /* @__PURE__ */ import_react14.default.createElement("span", { className: "cuekit-voice-intensity-bar" })
40643
41164
  )
40644
41165
  );
40645
41166
  };
@@ -40647,56 +41168,6 @@ var VoiceIntensityVisualizer = VoiceIntensityWithRoom;
40647
41168
 
40648
41169
  // src/components/mic-button.tsx
40649
41170
  init_webrtc_service();
40650
-
40651
- // src/components/svgs/mic.tsx
40652
- var import_react13 = __toESM(require("react"));
40653
- var MicIcon = ({ width = 24, height = 24, className, ...props }) => {
40654
- return /* @__PURE__ */ import_react13.default.createElement(
40655
- "svg",
40656
- {
40657
- xmlns: "http://www.w3.org/2000/svg",
40658
- width,
40659
- height,
40660
- viewBox: "0 0 24 24",
40661
- fill: "none",
40662
- stroke: "currentColor",
40663
- strokeWidth: "2",
40664
- strokeLinecap: "round",
40665
- strokeLinejoin: "round",
40666
- className,
40667
- ...props
40668
- },
40669
- /* @__PURE__ */ import_react13.default.createElement("path", { d: "M12 19v3" }),
40670
- /* @__PURE__ */ import_react13.default.createElement("path", { d: "M19 10v2a7 7 0 0 1-14 0v-2" }),
40671
- /* @__PURE__ */ import_react13.default.createElement("rect", { x: "9", y: "2", width: "6", height: "13", rx: "3" })
40672
- );
40673
- };
40674
- var mic_default = MicIcon;
40675
-
40676
- // src/components/svgs/loader.tsx
40677
- var import_react14 = __toESM(require("react"));
40678
- var LoaderIcon = ({ width = 24, height = 24, className, ...props }) => {
40679
- return /* @__PURE__ */ import_react14.default.createElement(
40680
- "svg",
40681
- {
40682
- xmlns: "http://www.w3.org/2000/svg",
40683
- width: "24",
40684
- height: "24",
40685
- viewBox: "0 0 24 24",
40686
- fill: "none",
40687
- stroke: "currentColor",
40688
- strokeWidth: "2",
40689
- strokeLinecap: "round",
40690
- strokeLinejoin: "round",
40691
- className,
40692
- ...props
40693
- },
40694
- /* @__PURE__ */ import_react14.default.createElement("path", { d: "M21 12a9 9 0 1 1-6.219-8.56" })
40695
- );
40696
- };
40697
- var loader_default = LoaderIcon;
40698
-
40699
- // src/components/mic-button.tsx
40700
41171
  var chatState = {
40701
41172
  isOpen: false,
40702
41173
  isMinimized: false
@@ -40746,12 +41217,16 @@ var MicButton = ({
40746
41217
  connect: voiceConnect,
40747
41218
  disconnect: voiceDisconnect,
40748
41219
  sendUserCommand: sendUserCommand2,
41220
+ sendChatMessage,
40749
41221
  messages: messageManagerMessages,
40750
41222
  micState,
40751
41223
  setMicState,
40752
41224
  status,
40753
41225
  setStatus,
40754
- participants
41226
+ participants,
41227
+ muteState,
41228
+ toggleMute,
41229
+ setMute
40755
41230
  } = useCuekit({
40756
41231
  // Don't override navigation command - let the provider handle it
40757
41232
  onConnectionStateChange: (state) => {
@@ -40898,7 +41373,9 @@ var MicButton = ({
40898
41373
  apiKey,
40899
41374
  appId,
40900
41375
  openChat,
40901
- showBorderGlow
41376
+ showBorderGlow,
41377
+ sendChatMessage,
41378
+ isChatOpen
40902
41379
  ]);
40903
41380
  const handleSendText = async (textToSend) => {
40904
41381
  setMicState("thinking");
@@ -40908,13 +41385,14 @@ var MicButton = ({
40908
41385
  }
40909
41386
  if (isConnected2) {
40910
41387
  try {
40911
- await sendUserCommand2(textToSend);
41388
+ await sendChatMessage(textToSend);
40912
41389
  setMicState("replying");
40913
41390
  setTimeout(() => {
40914
41391
  setMicState("listening");
40915
41392
  if (showBorderGlow) setShowBodyGlow(true);
40916
41393
  }, 1e3);
40917
41394
  } catch (error) {
41395
+ console.error("Failed to send chat message:", error);
40918
41396
  } finally {
40919
41397
  setMicState("listening");
40920
41398
  if (showBorderGlow) setShowBodyGlow(true);
@@ -40941,8 +41419,11 @@ var MicButton = ({
40941
41419
  filter: "drop-shadow(0 10px 8px rgba(0, 0, 0, 0.04)) drop-shadow(0 4px 3px rgba(0, 0, 0, 0.1))",
40942
41420
  ...imageStyle
40943
41421
  };
40944
- const animatedImageStyle = micState === "thinking" ? { ...baseImageStyle, animation: "spin 1s linear infinite" } : micState === "replying" ? { ...baseImageStyle, animation: "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite" } : baseImageStyle;
40945
- return /* @__PURE__ */ import_react15.default.createElement("img", { src: imageSource, alt: "Voice Assistant", style: animatedImageStyle });
41422
+ if (micState === "idle") {
41423
+ return /* @__PURE__ */ import_react15.default.createElement("img", { src: imageSource, alt: "Voice Assistant", style: baseImageStyle });
41424
+ } else {
41425
+ return /* @__PURE__ */ import_react15.default.createElement(VoiceIntensityWrapper, { active: true, buttonSize });
41426
+ }
40946
41427
  }
40947
41428
  const iconStyle = {
40948
41429
  width: `100%`,
@@ -40950,15 +41431,10 @@ var MicButton = ({
40950
41431
  color: "white",
40951
41432
  filter: "drop-shadow(0 10px 8px rgba(0, 0, 0, 0.04)) drop-shadow(0 4px 3px rgba(0, 0, 0, 0.1))"
40952
41433
  };
40953
- switch (micState) {
40954
- case "thinking":
40955
- return /* @__PURE__ */ import_react15.default.createElement(loader_default, { style: { ...iconStyle, animation: "spin 1s linear infinite" } });
40956
- case "replying":
40957
- return /* @__PURE__ */ import_react15.default.createElement(VoiceIntensityWrapper, { active: true, buttonSize });
40958
- case "listening":
40959
- return /* @__PURE__ */ import_react15.default.createElement(VoiceIntensityWrapper, { active: true, buttonSize });
40960
- default:
40961
- return /* @__PURE__ */ import_react15.default.createElement(mic_default, { style: iconStyle });
41434
+ if (micState === "idle") {
41435
+ return /* @__PURE__ */ import_react15.default.createElement(mic_default, { style: iconStyle });
41436
+ } else {
41437
+ return /* @__PURE__ */ import_react15.default.createElement(VoiceIntensityWrapper, { active: true, buttonSize });
40962
41438
  }
40963
41439
  };
40964
41440
  const getPositionStyle = () => {
@@ -41026,7 +41502,6 @@ var MicButton = ({
41026
41502
  case "thinking":
41027
41503
  baseStyle.transform = "scale(1.05)";
41028
41504
  baseStyle.boxShadow = "0 20px 25px -5px rgba(196, 132, 252, 0.4)";
41029
- baseStyle.animation = "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite";
41030
41505
  break;
41031
41506
  case "replying":
41032
41507
  baseStyle.transform = "scale(1.05)";
@@ -41103,7 +41578,9 @@ var MicButton = ({
41103
41578
  currentTheme,
41104
41579
  onThemeToggle: setCurrentTheme,
41105
41580
  status: getUserFriendlyStatus(micState, isConnected2 ?? false),
41106
- anchor: { position: screenPosition, bottom: bottomSpace, size: buttonSize }
41581
+ anchor: { position: screenPosition, bottom: bottomSpace, size: buttonSize },
41582
+ muteState,
41583
+ onToggleMute: toggleMute
41107
41584
  }
41108
41585
  ), isChatOpen && isChatMinimized && /* @__PURE__ */ import_react15.default.createElement(
41109
41586
  "button",