@stream-io/video-client 1.16.7 → 1.17.1

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/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver).
4
4
 
5
+ ## [1.17.1](https://github.com/GetStream/stream-video-js/compare/@stream-io/video-client-1.17.0...@stream-io/video-client-1.17.1) (2025-02-19)
6
+
7
+
8
+ ### Bug Fixes
9
+
10
+ * do not reconnect when device is offline ([#1688](https://github.com/GetStream/stream-video-js/issues/1688)) ([c6b6f58](https://github.com/GetStream/stream-video-js/commit/c6b6f58310a3365eb6f40d76a15c26791f413241))
11
+
12
+ ## [1.17.0](https://github.com/GetStream/stream-video-js/compare/@stream-io/video-client-1.16.7...@stream-io/video-client-1.17.0) (2025-02-17)
13
+
14
+
15
+ ### Features
16
+
17
+ * support static token and token provider at the same time ([#1685](https://github.com/GetStream/stream-video-js/issues/1685)) ([4365a3d](https://github.com/GetStream/stream-video-js/commit/4365a3dd0a14c98041982bde8be21258b8cfd571))
18
+
5
19
  ## [1.16.7](https://github.com/GetStream/stream-video-js/compare/@stream-io/video-client-1.16.6...@stream-io/video-client-1.16.7) (2025-02-12)
6
20
 
7
21
 
@@ -4,7 +4,7 @@ import { ServiceType, stackIntercept, RpcError } from '@protobuf-ts/runtime-rpc'
4
4
  import axios from 'axios';
5
5
  export { AxiosError } from 'axios';
6
6
  import { TwirpFetchTransport, TwirpErrorCode } from '@protobuf-ts/twirp-transport';
7
- import { ReplaySubject, combineLatest, BehaviorSubject, map, shareReplay, distinctUntilChanged, takeWhile, distinctUntilKeyChanged, fromEventPattern, startWith, concatMap, from, fromEvent, debounceTime, merge, pairwise, of } from 'rxjs';
7
+ import { ReplaySubject, combineLatest, BehaviorSubject, map, shareReplay, distinctUntilChanged, takeWhile, distinctUntilKeyChanged, fromEventPattern, startWith, concatMap, merge, from, fromEvent, debounceTime, pairwise, of } from 'rxjs';
8
8
  import { parse } from 'sdp-transform';
9
9
  import { UAParser } from 'ua-parser-js';
10
10
 
@@ -3302,10 +3302,7 @@ function isFunction(value) {
3302
3302
  */
3303
3303
  const KnownCodes = {
3304
3304
  TOKEN_EXPIRED: 40,
3305
- WS_CLOSED_SUCCESS: 1000,
3306
- WS_CLOSED_ABRUPTLY: 1006,
3307
- WS_POLICY_VIOLATION: 1008,
3308
- };
3305
+ WS_CLOSED_SUCCESS: 1000};
3309
3306
  /**
3310
3307
  * retryInterval - A retry interval which increases acc to number of failures
3311
3308
  *
@@ -5286,6 +5283,8 @@ class BasePeerConnection {
5286
5283
  this.onIceConnectionStateChange = () => {
5287
5284
  const state = this.pc.iceConnectionState;
5288
5285
  this.logger('debug', `ICE connection state changed`, state);
5286
+ if (this.state.callingState === CallingState.OFFLINE)
5287
+ return;
5289
5288
  if (this.state.callingState === CallingState.RECONNECTING)
5290
5289
  return;
5291
5290
  // do nothing when ICE is restarting
@@ -7464,7 +7463,7 @@ const aggregate = (stats) => {
7464
7463
  return report;
7465
7464
  };
7466
7465
 
7467
- const version = "1.16.7";
7466
+ const version = "1.17.1";
7468
7467
  const [major, minor, patch] = version.split('.');
7469
7468
  let sdkInfo = {
7470
7469
  type: SdkType.PLAIN_JAVASCRIPT,
@@ -12581,9 +12580,6 @@ const decodeBase64 = (s) => {
12581
12580
  * Handles all the operations around user token.
12582
12581
  */
12583
12582
  class TokenManager {
12584
- /**
12585
- * Constructor
12586
- */
12587
12583
  constructor(secret) {
12588
12584
  /**
12589
12585
  * Set the static string token or token provider.
@@ -12594,8 +12590,9 @@ class TokenManager {
12594
12590
  * @param {boolean} isAnonymous - whether the user is anonymous or not.
12595
12591
  */
12596
12592
  this.setTokenOrProvider = async (tokenOrProvider, user, isAnonymous) => {
12597
- this.validateToken(tokenOrProvider, user, isAnonymous);
12598
12593
  this.user = user;
12594
+ this.isAnonymous = isAnonymous;
12595
+ this.validateToken(tokenOrProvider);
12599
12596
  if (isFunction(tokenOrProvider)) {
12600
12597
  this.tokenProvider = tokenOrProvider;
12601
12598
  this.type = 'provider';
@@ -12618,28 +12615,28 @@ class TokenManager {
12618
12615
  this.loadTokenPromise = null;
12619
12616
  };
12620
12617
  // Validates the user token.
12621
- this.validateToken = (tokenOrProvider, user, isAnonymous) => {
12618
+ this.validateToken = (tokenOrProvider) => {
12622
12619
  // allow empty token for anon user
12623
- if (user && isAnonymous && !tokenOrProvider)
12620
+ if (this.user && this.isAnonymous && !tokenOrProvider)
12624
12621
  return;
12625
12622
  // Don't allow empty token for non-server side client.
12626
12623
  if (!this.secret && !tokenOrProvider) {
12627
- throw new Error('UserWithId token can not be empty');
12624
+ throw new Error('User token can not be empty');
12628
12625
  }
12629
12626
  if (tokenOrProvider &&
12630
12627
  typeof tokenOrProvider !== 'string' &&
12631
12628
  !isFunction(tokenOrProvider)) {
12632
- throw new Error('user token should either be a string or a function');
12629
+ throw new Error('User token should either be a string or a function');
12633
12630
  }
12634
12631
  if (typeof tokenOrProvider === 'string') {
12635
12632
  // Allow empty token for anonymous users
12636
- if (isAnonymous && tokenOrProvider === '')
12633
+ if (this.isAnonymous && tokenOrProvider === '')
12637
12634
  return;
12638
12635
  const tokenUserId = getUserFromToken(tokenOrProvider);
12639
12636
  if (tokenOrProvider != null &&
12640
12637
  (tokenUserId == null ||
12641
12638
  tokenUserId === '' ||
12642
- (!isAnonymous && tokenUserId !== user.id))) {
12639
+ (!this.isAnonymous && tokenUserId !== this.user.id))) {
12643
12640
  throw new Error('userToken does not have a user_id or is not matching with user.id');
12644
12641
  }
12645
12642
  }
@@ -12656,7 +12653,9 @@ class TokenManager {
12656
12653
  }
12657
12654
  if (this.tokenProvider && typeof this.tokenProvider !== 'string') {
12658
12655
  try {
12659
- this.token = await this.tokenProvider();
12656
+ const token = await this.tokenProvider();
12657
+ this.validateToken(token);
12658
+ this.token = token;
12660
12659
  }
12661
12660
  catch (e) {
12662
12661
  return reject(new Error(`Call to tokenProvider failed with message: ${e}`));
@@ -13077,7 +13076,7 @@ class StreamClient {
13077
13076
  return await this.wsConnection.connect(this.defaultWSTimeout);
13078
13077
  };
13079
13078
  this.getUserAgent = () => {
13080
- const version = "1.16.7";
13079
+ const version = "1.17.1";
13081
13080
  return (this.userAgent ||
13082
13081
  `stream-video-javascript-client-${this.node ? 'node' : 'browser'}-${version}`);
13083
13082
  };
@@ -13194,14 +13193,68 @@ class StreamClient {
13194
13193
  }
13195
13194
  }
13196
13195
 
13196
+ /**
13197
+ * Utility function to get the instance key.
13198
+ */
13199
+ const getInstanceKey = (apiKey, user) => {
13200
+ return `${apiKey}/${user.id}`;
13201
+ };
13202
+ /**
13203
+ * Creates a coordinator client.
13204
+ */
13205
+ const createCoordinatorClient = (apiKey, options) => {
13206
+ const coordinatorLogger = getLogger(['coordinator']);
13207
+ const streamClient = new StreamClient(apiKey, {
13208
+ persistUserOnConnectionFailure: true,
13209
+ ...options,
13210
+ logger: coordinatorLogger,
13211
+ });
13212
+ const sdkInfo = getSdkInfo();
13213
+ if (sdkInfo) {
13214
+ const sdkName = SdkType[sdkInfo.type].toLowerCase();
13215
+ const sdkVersion = `${sdkInfo.major}.${sdkInfo.minor}.${sdkInfo.patch}`;
13216
+ const userAgent = streamClient.getUserAgent();
13217
+ streamClient.setUserAgent(`${userAgent}-video-${sdkName}-sdk-${sdkVersion}`);
13218
+ }
13219
+ return streamClient;
13220
+ };
13221
+ /**
13222
+ * Creates a token provider and allows integrators to provide
13223
+ * a static token and a token provider at the same time.
13224
+ *
13225
+ * When both of them are provided, this function will create an internal
13226
+ * token provider that will use the static token on the first invocation
13227
+ * and the token provider on the later invocations.
13228
+ */
13229
+ const createTokenOrProvider = (options) => {
13230
+ const { token, tokenProvider } = options;
13231
+ if (token && tokenProvider) {
13232
+ let initialTokenUsed = false;
13233
+ return async function wrappedTokenProvider() {
13234
+ if (!initialTokenUsed) {
13235
+ initialTokenUsed = true;
13236
+ return token;
13237
+ }
13238
+ return tokenProvider();
13239
+ };
13240
+ }
13241
+ return token || tokenProvider;
13242
+ };
13243
+
13197
13244
  /**
13198
13245
  * A `StreamVideoClient` instance lets you communicate with our API, and authenticate users.
13199
13246
  */
13200
13247
  class StreamVideoClient {
13201
13248
  constructor(apiKeyOrArgs, opts) {
13202
- this.logLevel = 'warn';
13203
13249
  this.eventHandlersToUnregister = [];
13204
13250
  this.connectionConcurrencyTag = Symbol('connectionConcurrencyTag');
13251
+ this.registerClientInstance = (apiKey, user) => {
13252
+ const instanceKey = getInstanceKey(apiKey, user);
13253
+ if (StreamVideoClient._instances.has(instanceKey)) {
13254
+ this.logger('warn', `A StreamVideoClient already exists for ${user.id}; Prefer using getOrCreateInstance method`);
13255
+ }
13256
+ StreamVideoClient._instances.set(instanceKey, this);
13257
+ };
13205
13258
  /**
13206
13259
  * Connects the given user to the client.
13207
13260
  * Only one user can connect at a time, if you want to change users, call `disconnectUser` before connecting a new user.
@@ -13215,37 +13268,30 @@ class StreamVideoClient {
13215
13268
  user.id = '!anon';
13216
13269
  return this.connectAnonymousUser(user, token);
13217
13270
  }
13218
- let connectUser = () => {
13219
- return this.streamClient.connectUser(user, token);
13220
- };
13221
- if (user.type === 'guest') {
13222
- connectUser = async () => {
13223
- return this.streamClient.connectGuestUser(user);
13224
- };
13225
- }
13271
+ const connectUser = user.type === 'guest'
13272
+ ? () => this.streamClient.connectGuestUser(user)
13273
+ : () => this.streamClient.connectUser(user, token);
13226
13274
  const connectUserResponse = await withoutConcurrency(this.connectionConcurrencyTag, () => connectUser());
13227
13275
  // connectUserResponse will be void if connectUser called twice for the same user
13228
13276
  if (connectUserResponse?.me) {
13229
13277
  this.writeableStateStore.setConnectedUser(connectUserResponse.me);
13230
13278
  }
13231
13279
  this.eventHandlersToUnregister.push(this.on('connection.changed', (event) => {
13232
- if (event.online) {
13233
- const callsToReWatch = this.writeableStateStore.calls
13234
- .filter((call) => call.watching)
13235
- .map((call) => call.cid);
13236
- this.logger('info', `Rewatching calls after connection changed ${callsToReWatch.join(', ')}`);
13237
- if (callsToReWatch.length > 0) {
13238
- this.queryCalls({
13239
- watch: true,
13240
- filter_conditions: {
13241
- cid: { $in: callsToReWatch },
13242
- },
13243
- sort: [{ field: 'cid', direction: 1 }],
13244
- }).catch((err) => {
13245
- this.logger('error', 'Failed to re-watch calls', err);
13246
- });
13247
- }
13248
- }
13280
+ if (!event.online)
13281
+ return;
13282
+ const callsToReWatch = this.writeableStateStore.calls
13283
+ .filter((call) => call.watching)
13284
+ .map((call) => call.cid);
13285
+ if (callsToReWatch.length <= 0)
13286
+ return;
13287
+ this.logger('info', `Rewatching calls ${callsToReWatch.join(', ')}`);
13288
+ this.queryCalls({
13289
+ watch: true,
13290
+ filter_conditions: { cid: { $in: callsToReWatch } },
13291
+ sort: [{ field: 'cid', direction: 1 }],
13292
+ }).catch((err) => {
13293
+ this.logger('error', 'Failed to re-watch calls', err);
13294
+ });
13249
13295
  }));
13250
13296
  this.eventHandlersToUnregister.push(this.on('call.created', (event) => {
13251
13297
  const { call, members } = event;
@@ -13301,15 +13347,12 @@ class StreamVideoClient {
13301
13347
  * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
13302
13348
  */
13303
13349
  this.disconnectUser = async (timeout) => {
13304
- if (!this.streamClient.user) {
13350
+ const { user, key } = this.streamClient;
13351
+ if (!user)
13305
13352
  return;
13306
- }
13307
- const userId = this.streamClient.user?.id;
13308
- const apiKey = this.streamClient.key;
13309
- const disconnectUser = () => this.streamClient.disconnectUser(timeout);
13310
- await withoutConcurrency(this.connectionConcurrencyTag, () => disconnectUser());
13311
- if (userId) {
13312
- StreamVideoClient._instanceMap.delete(apiKey + userId);
13353
+ await withoutConcurrency(this.connectionConcurrencyTag, () => this.streamClient.disconnectUser(timeout));
13354
+ if (user.id) {
13355
+ StreamVideoClient._instances.delete(getInstanceKey(key, user));
13313
13356
  }
13314
13357
  this.eventHandlersToUnregister.forEach((unregister) => unregister());
13315
13358
  this.eventHandlersToUnregister = [];
@@ -13490,92 +13533,46 @@ class StreamVideoClient {
13490
13533
  * @param tokenOrProvider a token or a function that returns a token.
13491
13534
  */
13492
13535
  this.connectAnonymousUser = async (user, tokenOrProvider) => {
13493
- const connectAnonymousUser = () => this.streamClient.connectAnonymousUser(user, tokenOrProvider);
13494
- return await withoutConcurrency(this.connectionConcurrencyTag, () => connectAnonymousUser());
13495
- };
13496
- let logger = logToConsole;
13497
- let logLevel = 'warn';
13498
- if (typeof apiKeyOrArgs === 'string') {
13499
- logLevel = opts?.logLevel || logLevel;
13500
- logger = opts?.logger || logger;
13501
- if (opts?.enableTimerWorker)
13502
- enableTimerWorker();
13503
- }
13504
- else {
13505
- logLevel = apiKeyOrArgs.options?.logLevel || logLevel;
13506
- logger = apiKeyOrArgs.options?.logger || logger;
13507
- if (apiKeyOrArgs.options?.enableTimerWorker)
13508
- enableTimerWorker();
13509
- }
13510
- setLogger(logger, logLevel);
13536
+ return withoutConcurrency(this.connectionConcurrencyTag, () => this.streamClient.connectAnonymousUser(user, tokenOrProvider));
13537
+ };
13538
+ const apiKey = typeof apiKeyOrArgs === 'string' ? apiKeyOrArgs : apiKeyOrArgs.apiKey;
13539
+ const clientOptions = typeof apiKeyOrArgs === 'string' ? opts : apiKeyOrArgs.options;
13540
+ if (clientOptions?.enableTimerWorker)
13541
+ enableTimerWorker();
13542
+ const rootLogger = clientOptions?.logger || logToConsole;
13543
+ setLogger(rootLogger, clientOptions?.logLevel || 'warn');
13511
13544
  this.logger = getLogger(['client']);
13512
- const coordinatorLogger = getLogger(['coordinator']);
13513
- if (typeof apiKeyOrArgs === 'string') {
13514
- this.streamClient = new StreamClient(apiKeyOrArgs, {
13515
- persistUserOnConnectionFailure: true,
13516
- ...opts,
13517
- logLevel,
13518
- logger: coordinatorLogger,
13519
- });
13520
- }
13521
- else {
13522
- this.streamClient = new StreamClient(apiKeyOrArgs.apiKey, {
13523
- persistUserOnConnectionFailure: true,
13524
- ...apiKeyOrArgs.options,
13525
- logLevel,
13526
- logger: coordinatorLogger,
13527
- });
13528
- const sdkInfo = getSdkInfo();
13529
- if (sdkInfo) {
13530
- const sdkName = SdkType[sdkInfo.type].toLowerCase();
13531
- const sdkVersion = `${sdkInfo.major}.${sdkInfo.minor}.${sdkInfo.patch}`;
13532
- const userAgent = this.streamClient.getUserAgent();
13533
- this.streamClient.setUserAgent(`${userAgent}-video-${sdkName}-sdk-${sdkVersion}`);
13534
- }
13535
- }
13545
+ this.streamClient = createCoordinatorClient(apiKey, clientOptions);
13536
13546
  this.writeableStateStore = new StreamVideoWriteableStateStore();
13537
13547
  this.readOnlyStateStore = new StreamVideoReadOnlyStateStore(this.writeableStateStore);
13538
- if (typeof apiKeyOrArgs !== 'string') {
13548
+ if (typeof apiKeyOrArgs !== 'string' && apiKeyOrArgs.user) {
13539
13549
  const user = apiKeyOrArgs.user;
13540
- const token = apiKeyOrArgs.token || apiKeyOrArgs.tokenProvider;
13541
- if (user) {
13542
- let id = user.id;
13543
- if (user.type === 'anonymous') {
13544
- id = '!anon';
13545
- }
13546
- if (id) {
13547
- if (StreamVideoClient._instanceMap.has(apiKeyOrArgs.apiKey + id)) {
13548
- this.logger('warn', `A StreamVideoClient already exists for ${user.type === 'anonymous' ? 'an anonymous user' : id}; Prefer using getOrCreateInstance method`);
13549
- }
13550
- user.id = id;
13551
- StreamVideoClient._instanceMap.set(apiKeyOrArgs.apiKey + id, this);
13552
- }
13553
- this.connectUser(user, token).catch((err) => {
13554
- this.logger('error', 'Failed to connect', err);
13555
- });
13556
- }
13550
+ if (user.type === 'anonymous')
13551
+ user.id = '!anon';
13552
+ if (user.id)
13553
+ this.registerClientInstance(apiKey, user);
13554
+ const tokenOrProvider = createTokenOrProvider(apiKeyOrArgs);
13555
+ this.connectUser(user, tokenOrProvider).catch((err) => {
13556
+ this.logger('error', 'Failed to connect', err);
13557
+ });
13557
13558
  }
13558
13559
  }
13560
+ /**
13561
+ * Gets or creates a StreamVideoClient instance based on the given options.
13562
+ */
13559
13563
  static getOrCreateInstance(args) {
13560
- const user = args.user;
13561
- if (!user.id) {
13562
- if (args.user.type === 'anonymous') {
13563
- user.id = '!anon';
13564
- }
13565
- else {
13566
- throw new Error('User ID is required for a non-anonymous user');
13567
- }
13568
- }
13569
- if (!args.token && !args.tokenProvider) {
13570
- if (args.user.type !== 'anonymous' && args.user.type !== 'guest') {
13571
- throw new Error('TokenProvider or token is required for a user that is not a guest or anonymous');
13572
- }
13564
+ const { apiKey, user, token, tokenProvider } = args;
13565
+ if (!user.id && user.type !== 'anonymous') {
13566
+ throw new Error('user.id is required for a non-anonymous user');
13573
13567
  }
13574
- let instance = StreamVideoClient._instanceMap.get(args.apiKey + user.id);
13575
- if (!instance) {
13576
- instance = new StreamVideoClient({ ...args, user });
13568
+ if (!token &&
13569
+ !tokenProvider &&
13570
+ user.type !== 'anonymous' &&
13571
+ user.type !== 'guest') {
13572
+ throw new Error('tokenProvider or token is required for a authenticated users');
13577
13573
  }
13578
- return instance;
13574
+ return (StreamVideoClient._instances.get(getInstanceKey(apiKey, user)) ||
13575
+ new StreamVideoClient(args));
13579
13576
  }
13580
13577
  /**
13581
13578
  * Return the reactive state store, use this if you want to be notified about changes to the client state
@@ -13584,7 +13581,7 @@ class StreamVideoClient {
13584
13581
  return this.readOnlyStateStore;
13585
13582
  }
13586
13583
  }
13587
- StreamVideoClient._instanceMap = new Map();
13584
+ StreamVideoClient._instances = new Map();
13588
13585
 
13589
13586
  export { AudioSettingsRequestDefaultDeviceEnum, AudioSettingsResponseDefaultDeviceEnum, browsers as Browsers, Call, CallState, CallType, CallTypes, CallingState, CameraManager, CameraManagerState, CreateDeviceRequestPushProviderEnum, DebounceType, DynascaleManager, ErrorFromResponse, FrameRecordingSettingsRequestModeEnum, FrameRecordingSettingsResponseModeEnum, InputMediaDeviceManager, InputMediaDeviceManagerState, LayoutSettingsRequestNameEnum, MicrophoneManager, MicrophoneManagerState, NoiseCancellationSettingsModeEnum, OwnCapability, RTMPBroadcastRequestQualityEnum, RTMPSettingsRequestQualityEnum, RecordSettingsRequestModeEnum, RecordSettingsRequestQualityEnum, rxUtils as RxUtils, ScreenShareManager, ScreenShareState, events as SfuEvents, models as SfuModels, SpeakerManager, SpeakerState, StreamSfuClient, StreamVideoClient, StreamVideoReadOnlyStateStore, StreamVideoWriteableStateStore, TranscriptionSettingsRequestClosedCaptionModeEnum, TranscriptionSettingsRequestLanguageEnum, TranscriptionSettingsRequestModeEnum, TranscriptionSettingsResponseClosedCaptionModeEnum, TranscriptionSettingsResponseLanguageEnum, TranscriptionSettingsResponseModeEnum, VideoSettingsRequestCameraFacingEnum, VideoSettingsResponseCameraFacingEnum, ViewportTracker, VisibilityState, checkIfAudioOutputChangeSupported, combineComparators, conditional, createSoundDetector, defaultSortPreset, descending, deviceIds$, disposeOfMediaStream, dominantSpeaker, getAudioBrowserPermission, getAudioDevices, getAudioOutputDevices, getAudioStream, getClientDetails, getDeviceInfo, getDeviceState, getLogLevel, getLogger, getOSInfo, getScreenShareStream, getSdkInfo, getVideoBrowserPermission, getVideoDevices, getVideoStream, getWebRTCInfo, hasAudio, hasScreenShare, hasScreenShareAudio, hasVideo, isPinned, livestreamOrAudioRoomSortPreset, logLevels, logToConsole, name, noopComparator, paginatedLayoutSortPreset, pinned, publishingAudio, publishingVideo, reactionType, role, screenSharing, setDeviceInfo, setLogLevel, setLogger, setOSInfo, setPowerState, setSdkInfo, setThermalState, setWebRTCInfo, speakerLayoutSortPreset, speaking };
13590
13587
  //# sourceMappingURL=index.browser.es.js.map