@stream-io/video-client 0.0.1-alpha.7

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.
Files changed (157) hide show
  1. package/LICENSE +219 -0
  2. package/README.md +14 -0
  3. package/dist/index.d.ts +23 -0
  4. package/dist/index.js +14663 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/src/Batcher.d.ts +12 -0
  7. package/dist/src/CallDropScheduler.d.ts +44 -0
  8. package/dist/src/StreamSfuClient.d.ts +25 -0
  9. package/dist/src/StreamVideoClient.d.ts +145 -0
  10. package/dist/src/__tests__/StreamVideoClient.test.d.ts +1 -0
  11. package/dist/src/config/defaultConfigs.d.ts +2 -0
  12. package/dist/src/config/types.d.ts +29 -0
  13. package/dist/src/coordinator/StreamCoordinatorClient.d.ts +19 -0
  14. package/dist/src/coordinator/connection/base64.d.ts +2 -0
  15. package/dist/src/coordinator/connection/client.d.ts +174 -0
  16. package/dist/src/coordinator/connection/connection.d.ts +139 -0
  17. package/dist/src/coordinator/connection/connection_fallback.d.ts +38 -0
  18. package/dist/src/coordinator/connection/errors.d.ts +16 -0
  19. package/dist/src/coordinator/connection/events.d.ts +7 -0
  20. package/dist/src/coordinator/connection/insights.d.ts +58 -0
  21. package/dist/src/coordinator/connection/signing.d.ts +30 -0
  22. package/dist/src/coordinator/connection/token_manager.d.ts +39 -0
  23. package/dist/src/coordinator/connection/types.d.ts +96 -0
  24. package/dist/src/coordinator/connection/utils.d.ts +25 -0
  25. package/dist/src/devices.d.ts +79 -0
  26. package/dist/src/events/call.d.ts +26 -0
  27. package/dist/src/events/internal.d.ts +8 -0
  28. package/dist/src/events/participant.d.ts +21 -0
  29. package/dist/src/events/speaker.d.ts +10 -0
  30. package/dist/src/gen/coordinator/index.d.ts +1664 -0
  31. package/dist/src/gen/google/protobuf/descriptor.d.ts +1650 -0
  32. package/dist/src/gen/google/protobuf/duration.d.ts +113 -0
  33. package/dist/src/gen/google/protobuf/struct.d.ts +184 -0
  34. package/dist/src/gen/google/protobuf/timestamp.d.ts +158 -0
  35. package/dist/src/gen/video/coordinator/broadcast_v1/broadcast.d.ts +66 -0
  36. package/dist/src/gen/video/coordinator/call_v1/call.d.ts +254 -0
  37. package/dist/src/gen/video/coordinator/client_v1_rpc/client_rpc.client.d.ts +351 -0
  38. package/dist/src/gen/video/coordinator/client_v1_rpc/client_rpc.d.ts +1488 -0
  39. package/dist/src/gen/video/coordinator/client_v1_rpc/envelopes.d.ts +143 -0
  40. package/dist/src/gen/video/coordinator/client_v1_rpc/websocket.d.ts +292 -0
  41. package/dist/src/gen/video/coordinator/edge_v1/edge.d.ts +183 -0
  42. package/dist/src/gen/video/coordinator/event_v1/event.d.ts +411 -0
  43. package/dist/src/gen/video/coordinator/geofence_v1/geofence.d.ts +63 -0
  44. package/dist/src/gen/video/coordinator/member_v1/member.d.ts +59 -0
  45. package/dist/src/gen/video/coordinator/participant_v1/participant.d.ts +103 -0
  46. package/dist/src/gen/video/coordinator/push_v1/push.d.ts +240 -0
  47. package/dist/src/gen/video/coordinator/stat_v1/stat.d.ts +308 -0
  48. package/dist/src/gen/video/coordinator/user_v1/user.d.ts +112 -0
  49. package/dist/src/gen/video/coordinator/utils_v1/utils.d.ts +47 -0
  50. package/dist/src/gen/video/sfu/event/events.d.ts +736 -0
  51. package/dist/src/gen/video/sfu/models/models.d.ts +460 -0
  52. package/dist/src/gen/video/sfu/signal_rpc/signal.client.d.ts +89 -0
  53. package/dist/src/gen/video/sfu/signal_rpc/signal.d.ts +320 -0
  54. package/dist/src/helpers/browsers.d.ts +8 -0
  55. package/dist/src/helpers/sound-detector.d.ts +34 -0
  56. package/dist/src/rpc/createClient.d.ts +10 -0
  57. package/dist/src/rpc/index.d.ts +2 -0
  58. package/dist/src/rpc/latency.d.ts +9 -0
  59. package/dist/src/rtc/Call.d.ts +180 -0
  60. package/dist/src/rtc/CallMetadata.d.ts +9 -0
  61. package/dist/src/rtc/Dispatcher.d.ts +9 -0
  62. package/dist/src/rtc/IceTrickleBuffer.d.ts +11 -0
  63. package/dist/src/rtc/callEventHandlers.d.ts +5 -0
  64. package/dist/src/rtc/codecs.d.ts +2 -0
  65. package/dist/src/rtc/helpers/iceCandidate.d.ts +2 -0
  66. package/dist/src/rtc/helpers/tracks.d.ts +3 -0
  67. package/dist/src/rtc/publisher.d.ts +53 -0
  68. package/dist/src/rtc/signal.d.ts +5 -0
  69. package/dist/src/rtc/subscriber.d.ts +7 -0
  70. package/dist/src/rtc/types.d.ts +84 -0
  71. package/dist/src/rtc/videoLayers.d.ts +17 -0
  72. package/dist/src/stats/coordinator-stats-reporter.d.ts +10 -0
  73. package/dist/src/stats/state-store-stats-reporter.d.ts +57 -0
  74. package/dist/src/stats/types.d.ts +42 -0
  75. package/dist/src/store/index.d.ts +2 -0
  76. package/dist/src/store/rxUtils.d.ts +18 -0
  77. package/dist/src/store/stateStore.d.ts +182 -0
  78. package/generate-openapi.sh +32 -0
  79. package/index.ts +30 -0
  80. package/openapitools.json +7 -0
  81. package/package.json +54 -0
  82. package/rollup.config.mjs +48 -0
  83. package/src/Batcher.ts +43 -0
  84. package/src/CallDropScheduler.ts +192 -0
  85. package/src/StreamSfuClient.ts +185 -0
  86. package/src/StreamVideoClient.ts +487 -0
  87. package/src/__tests__/StreamVideoClient.test.ts +83 -0
  88. package/src/config/defaultConfigs.ts +15 -0
  89. package/src/config/types.ts +30 -0
  90. package/src/coordinator/StreamCoordinatorClient.ts +111 -0
  91. package/src/coordinator/connection/base64.ts +80 -0
  92. package/src/coordinator/connection/client.ts +815 -0
  93. package/src/coordinator/connection/connection.ts +750 -0
  94. package/src/coordinator/connection/connection_fallback.ts +239 -0
  95. package/src/coordinator/connection/errors.ts +70 -0
  96. package/src/coordinator/connection/events.ts +10 -0
  97. package/src/coordinator/connection/insights.ts +88 -0
  98. package/src/coordinator/connection/signing.ts +104 -0
  99. package/src/coordinator/connection/token_manager.ts +160 -0
  100. package/src/coordinator/connection/types.ts +120 -0
  101. package/src/coordinator/connection/utils.ts +148 -0
  102. package/src/devices.ts +266 -0
  103. package/src/events/call.ts +166 -0
  104. package/src/events/internal.ts +47 -0
  105. package/src/events/participant.ts +97 -0
  106. package/src/events/speaker.ts +62 -0
  107. package/src/gen/coordinator/index.ts +1653 -0
  108. package/src/gen/google/protobuf/descriptor.ts +3466 -0
  109. package/src/gen/google/protobuf/duration.ts +232 -0
  110. package/src/gen/google/protobuf/struct.ts +481 -0
  111. package/src/gen/google/protobuf/timestamp.ts +291 -0
  112. package/src/gen/video/coordinator/broadcast_v1/broadcast.ts +154 -0
  113. package/src/gen/video/coordinator/call_v1/call.ts +651 -0
  114. package/src/gen/video/coordinator/client_v1_rpc/client_rpc.client.ts +463 -0
  115. package/src/gen/video/coordinator/client_v1_rpc/client_rpc.ts +3819 -0
  116. package/src/gen/video/coordinator/client_v1_rpc/envelopes.ts +424 -0
  117. package/src/gen/video/coordinator/client_v1_rpc/websocket.ts +719 -0
  118. package/src/gen/video/coordinator/edge_v1/edge.ts +532 -0
  119. package/src/gen/video/coordinator/event_v1/event.ts +1171 -0
  120. package/src/gen/video/coordinator/geofence_v1/geofence.ts +128 -0
  121. package/src/gen/video/coordinator/member_v1/member.ts +138 -0
  122. package/src/gen/video/coordinator/participant_v1/participant.ts +261 -0
  123. package/src/gen/video/coordinator/push_v1/push.ts +651 -0
  124. package/src/gen/video/coordinator/stat_v1/stat.ts +656 -0
  125. package/src/gen/video/coordinator/user_v1/user.ts +277 -0
  126. package/src/gen/video/coordinator/utils_v1/utils.ts +98 -0
  127. package/src/gen/video/sfu/event/events.ts +1962 -0
  128. package/src/gen/video/sfu/models/models.ts +1062 -0
  129. package/src/gen/video/sfu/signal_rpc/signal.client.ts +108 -0
  130. package/src/gen/video/sfu/signal_rpc/signal.ts +906 -0
  131. package/src/helpers/browsers.ts +13 -0
  132. package/src/helpers/sound-detector.ts +85 -0
  133. package/src/rpc/createClient.ts +50 -0
  134. package/src/rpc/index.ts +2 -0
  135. package/src/rpc/latency.ts +43 -0
  136. package/src/rtc/Call.ts +585 -0
  137. package/src/rtc/CallMetadata.ts +24 -0
  138. package/src/rtc/Dispatcher.ts +46 -0
  139. package/src/rtc/IceTrickleBuffer.ts +21 -0
  140. package/src/rtc/callEventHandlers.ts +37 -0
  141. package/src/rtc/codecs.ts +61 -0
  142. package/src/rtc/helpers/iceCandidate.ts +16 -0
  143. package/src/rtc/helpers/tracks.ts +18 -0
  144. package/src/rtc/publisher.ts +305 -0
  145. package/src/rtc/signal.ts +34 -0
  146. package/src/rtc/subscriber.ts +85 -0
  147. package/src/rtc/types.ts +105 -0
  148. package/src/rtc/videoLayers.ts +103 -0
  149. package/src/stats/coordinator-stats-reporter.ts +167 -0
  150. package/src/stats/state-store-stats-reporter.ts +364 -0
  151. package/src/stats/types.ts +46 -0
  152. package/src/store/index.ts +2 -0
  153. package/src/store/rxUtils.ts +42 -0
  154. package/src/store/stateStore.ts +341 -0
  155. package/tsconfig.json +25 -0
  156. package/typedoc.json +11 -0
  157. package/vite.config.ts +11 -0
@@ -0,0 +1,12 @@
1
+ export declare class Batcher<BatchItemType> {
2
+ private readonly timeoutInterval;
3
+ private readonly requestFunction;
4
+ private batch;
5
+ private timeoutId;
6
+ constructor(timeoutInterval: number, requestFunction: (data: Array<BatchItemType>) => void);
7
+ private scheduleTimeout;
8
+ private clearTimeout;
9
+ clearBatch: () => void;
10
+ addToBatch: (item: BatchItemType) => void;
11
+ removeFromBatch: (item: BatchItemType) => void;
12
+ }
@@ -0,0 +1,44 @@
1
+ import { StreamVideoWriteableStateStore } from './store';
2
+ import { CallConfig } from './config/types';
3
+ type CallCID = string;
4
+ type DropFunction = (callCid: CallCID) => Promise<void>;
5
+ export declare class CallDropScheduler {
6
+ private store;
7
+ private callConfig;
8
+ private reject;
9
+ private cancel;
10
+ private autoCallDropSchedule;
11
+ private storeSubscriptions;
12
+ private pairwisePendingCalls$;
13
+ private pairwiseIncomingCalls$;
14
+ private pairwiseOutgoingCalls$;
15
+ constructor(store: StreamVideoWriteableStateStore, callConfig: CallConfig, reject: DropFunction, cancel: DropFunction);
16
+ private static getLatestCall;
17
+ private startAutoRejectWhenInCall;
18
+ private scheduleRejectAfterTimeout;
19
+ private scheduleCancelAfterTimeout;
20
+ private startCancellingDrops;
21
+ /**
22
+ * Schedules automatic call cancellation.
23
+ * The cancellation is intended for the scenarios, when the call has been rejected
24
+ * or not accepted by all the call members.
25
+ * @param {string} callCid
26
+ */
27
+ private scheduleCancel;
28
+ /**
29
+ * Schedules automatic call rejection.
30
+ * @param {string} callCid
31
+ */
32
+ private scheduleReject;
33
+ /**
34
+ * Cancels the automatic call drop (rejection of an incoming call / cancellation of an outgoing call).
35
+ * Indented for the scenario, when:
36
+ * - an incoming call has been cancelled
37
+ * - an outgoing call has been accepted by at least one member
38
+ * - an outgoing call has been rejected / left by all the members resp. participants
39
+ * - a call has been cancelled / rejected / accepted manually before the cancellation timeout expires.
40
+ */
41
+ private cancelDrop;
42
+ cleanUp: () => void;
43
+ }
44
+ export {};
@@ -0,0 +1,25 @@
1
+ import { JoinRequest, SfuRequest } from './gen/video/sfu/event/events';
2
+ import { Dispatcher } from './rtc/Dispatcher';
3
+ import { IceTrickleBuffer } from './rtc/IceTrickleBuffer';
4
+ import { SendAnswerRequest, SetPublisherRequest, TrackSubscriptionDetails, UpdateMuteStatesRequest } from './gen/video/sfu/signal_rpc/signal';
5
+ import { ICETrickle, TrackType } from './gen/video/sfu/models/models';
6
+ export declare class StreamSfuClient {
7
+ readonly dispatcher: Dispatcher;
8
+ readonly iceTrickleBuffer: IceTrickleBuffer;
9
+ readonly sessionId: string;
10
+ private readonly rpc;
11
+ private readonly token;
12
+ signalReady: Promise<WebSocket>;
13
+ private keepAliveInterval?;
14
+ constructor(url: string, token: string);
15
+ close: () => void;
16
+ updateSubscriptions: (subscriptions: TrackSubscriptionDetails[]) => Promise<import("@protobuf-ts/runtime-rpc").FinishedUnaryCall<import("./gen/video/sfu/signal_rpc/signal").UpdateSubscriptionsRequest, import("./gen/video/sfu/signal_rpc/signal").UpdateSubscriptionsResponse>>;
17
+ setPublisher: (data: Omit<SetPublisherRequest, 'sessionId'>) => Promise<import("@protobuf-ts/runtime-rpc").FinishedUnaryCall<SetPublisherRequest, import("./gen/video/sfu/signal_rpc/signal").SetPublisherResponse>>;
18
+ sendAnswer: (data: Omit<SendAnswerRequest, 'sessionId'>) => Promise<import("@protobuf-ts/runtime-rpc").FinishedUnaryCall<SendAnswerRequest, import("./gen/video/sfu/signal_rpc/signal").SendAnswerResponse>>;
19
+ iceTrickle: (data: Omit<ICETrickle, 'sessionId'>) => Promise<import("@protobuf-ts/runtime-rpc").FinishedUnaryCall<ICETrickle, import("./gen/video/sfu/signal_rpc/signal").ICETrickleResponse>>;
20
+ updateMuteState: (trackType: TrackType, muted: boolean) => Promise<import("@protobuf-ts/runtime-rpc").FinishedUnaryCall<UpdateMuteStatesRequest, import("./gen/video/sfu/signal_rpc/signal").UpdateMuteStatesResponse>>;
21
+ updateMuteStates: (data: Omit<UpdateMuteStatesRequest, 'sessionId'>) => Promise<import("@protobuf-ts/runtime-rpc").FinishedUnaryCall<UpdateMuteStatesRequest, import("./gen/video/sfu/signal_rpc/signal").UpdateMuteStatesResponse>>;
22
+ join: (data: Omit<JoinRequest, 'sessionId' | 'token'>) => Promise<void>;
23
+ send: (message: SfuRequest) => Promise<void>;
24
+ keepAlive(): Promise<void>;
25
+ }
@@ -0,0 +1,145 @@
1
+ import { StreamVideoReadOnlyStateStore } from './store';
2
+ import type { GetOrCreateCallRequest } from './gen/coordinator';
3
+ import { Call } from './rtc/Call';
4
+ import { Batcher } from './Batcher';
5
+ import { CallConfig } from './config/types';
6
+ import { EventHandler, StreamClientOptions, TokenOrProvider, User } from './coordinator/connection/types';
7
+ /**
8
+ * A `StreamVideoClient` instance lets you communicate with our API, and authenticate users.
9
+ */
10
+ export declare class StreamVideoClient {
11
+ /**
12
+ * Configuration parameters for controlling call behavior.
13
+ */
14
+ callConfig: CallConfig;
15
+ /**
16
+ * A reactive store that exposes all the state variables in a reactive manner - you can subscribe to changes of the different state variables. Our library is built in a way that all state changes are exposed in this store, so all UI changes in your application should be handled by subscribing to these variables.
17
+ * @angular If you're using our Angular SDK, you shouldn't be interacting with the state store directly, instead, you should be using the [`StreamVideoService`](./StreamVideoService.md).
18
+ */
19
+ readonly readOnlyStateStore: StreamVideoReadOnlyStateStore;
20
+ private readonly writeableStateStore;
21
+ private callDropScheduler;
22
+ private coordinatorClient;
23
+ /**
24
+ * @internal
25
+ */
26
+ readonly userBatcher: Batcher<string>;
27
+ /**
28
+ * You should create only one instance of `StreamVideoClient`.
29
+ * @angular If you're using our Angular SDK, you shouldn't be calling the `constructor` directly, instead you should be using [`StreamVideoService`](./StreamVideoService.md/#init).
30
+ * @param apiKey your Stream API key
31
+ * @param opts the options for the client.
32
+ * @param {CallConfig} [callConfig=CALL_CONFIG.meeting] custom call configuration
33
+ */
34
+ constructor(apiKey: string, opts?: StreamClientOptions, callConfig?: CallConfig);
35
+ /**
36
+ * Connects the given user to the client.
37
+ * Only one user can connect at a time, if you want to change users, call `disconnectUser` before connecting a new user.
38
+ * If the connection is successful, the connected user [state variable](#readonlystatestore) will be updated accordingly.
39
+ *
40
+ * @param user the user to connect.
41
+ * @param tokenOrProvider a token or a function that returns a token.
42
+ */
43
+ connectUser: (user: User, tokenOrProvider: TokenOrProvider) => Promise<void>;
44
+ /**
45
+ * Disconnects the currently connected user from the client.
46
+ *
47
+ * If the connection is successfully disconnected, the connected user [state variable](#readonlystatestore) will be updated accordingly
48
+ */
49
+ disconnectUser: () => Promise<void>;
50
+ /**
51
+ * You can subscribe to WebSocket events provided by the API.
52
+ * To remove a subscription, call the `off` method or, execute the returned unsubscribe function.
53
+ * Please note that subscribing to WebSocket events is an advanced use-case, for most use-cases it should be enough to watch for changes in the reactive [state store](#readonlystatestore).
54
+ *
55
+ * @param eventName the event name.
56
+ * @param callback the callback which will be called when the event is emitted.
57
+ * @returns an unsubscribe function.
58
+ */
59
+ on: (eventName: string, callback: EventHandler) => () => void;
60
+ /**
61
+ * Remove subscription for WebSocket events that were created by the `on` method.
62
+ *
63
+ * @param event the event name.
64
+ * @param callback the callback which was passed to the `on` method.
65
+ */
66
+ off: (event: string, callback: EventHandler) => void;
67
+ /**
68
+ * Allows you to create new calls with the given parameters.
69
+ * If a call with the same combination of type and id already exists, it will be returned.
70
+ *
71
+ * Causes the CallCreated event to be emitted to all the call members in case this call didnot exist before.
72
+ *
73
+ * @param id the id of the call.
74
+ * @param type the type of the call.
75
+ * @param data the data for the call.
76
+ * @returns A call metadata with information about the call.
77
+ */
78
+ getOrCreateCall: (id: string, type: string, data?: GetOrCreateCallRequest) => Promise<import("./gen/coordinator").GetOrCreateCallResponse | undefined>;
79
+ /**
80
+ * Signals other users that I have accepted the incoming call.
81
+ * Causes the `CallAccepted` event to be emitted to all the call members.
82
+ * @param callCid config ID of the rejected call
83
+ * @returns
84
+ */
85
+ acceptCall: (callCid: string) => Promise<Call | undefined>;
86
+ /**
87
+ * Signals other users that I have rejected the incoming call.
88
+ * Causes the `CallRejected` event to be emitted to all the call members.
89
+ * @param callCid config ID of the rejected call
90
+ * @returns
91
+ */
92
+ rejectCall: (callCid: string) => Promise<void>;
93
+ /**
94
+ * Signals other users that I have cancelled my call to them before they accepted it.
95
+ * Causes the CallCancelled event to be emitted to all the call members.
96
+ *
97
+ * Cancelling a call is only possible before the local participant joined the call.
98
+ * @param callCid config ID of the cancelled call
99
+ * @returns
100
+ */
101
+ cancelCall: (callCid: string) => Promise<void>;
102
+ /**
103
+ * Allows you to create a new call with the given parameters and joins the call immediately.
104
+ * If a call with the same combination of `type` and `id` already exists, it will join the existing call.
105
+ *
106
+ * @param id the id of the call.
107
+ * @param type the type of the call.
108
+ * @param data the data for the call.
109
+ * @returns A [`Call`](./Call.md) instance that can be used to interact with the call.
110
+ */
111
+ joinCall: (id: string, type: string, data?: GetOrCreateCallRequest) => Promise<Call | undefined>;
112
+ /**
113
+ * Starts recording for the call described by the given `callId` and `callType`.
114
+ * @param callId can be extracted from a [`Call` instance](./Call.md/#data)
115
+ * @param callType can be extracted from a [`Call` instance](./Call.md/#data)
116
+ */
117
+ startRecording: (callId: string, callType: string) => Promise<void>;
118
+ /**
119
+ * Stops recording for the call described by the given `callId` and `callType`.
120
+ * @param callId can be extracted from a [`Call` instance](./Call.md/#data)
121
+ * @param callType can be extracted from a [`Call` instance](./Call.md/#data)
122
+ */
123
+ stopRecording: (callId: string, callType: string) => Promise<void>;
124
+ /**
125
+ * Reports call WebRTC metrics to coordinator API
126
+ * @param stats
127
+ * @returns
128
+ */
129
+ private reportCallStats;
130
+ private getCallEdgeServer;
131
+ private toRtcConfiguration;
132
+ /**
133
+ * Reports call events (for example local participant muted themselves) to the coordinator API
134
+ * @param statEvent
135
+ * @returns
136
+ */
137
+ private reportCallStatEvent;
138
+ /**
139
+ * Sets the `participant.isPinned` value.
140
+ * @param sessionId the session id of the participant
141
+ * @param isPinned the value to set the participant.isPinned
142
+ * @returns
143
+ */
144
+ setParticipantIsPinned: (sessionId: string, isPinned: boolean) => void;
145
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import { CallConfig, CallType } from './types';
2
+ export declare const CALL_CONFIG: Record<CallType, CallConfig>;
@@ -0,0 +1,29 @@
1
+ export type CallType = 'ring' | 'meeting';
2
+ export type CallConfig = {
3
+ /**
4
+ * Optional parameter to define after how many milliseconds without receiving CallAccepted event should the outgoing call be cancelled.
5
+ * If not defined, the call will not be cancelled automatically by the client and the user is expected to cancel or leave the call manually.
6
+ * Note: Is relevant to outgoing calls only.
7
+ */
8
+ autoCancelTimeoutInMs?: number;
9
+ /**
10
+ * Optional parameter to define after how many milliseconds an incoming ring call should be automatically rejected.
11
+ * If not defined, the call will not be rejected automatically by the client and the user is expected to reject the call manually.
12
+ * Note: Is relevant to incoming calls only.
13
+ */
14
+ autoRejectTimeoutInMs?: number;
15
+ /**
16
+ * Optional parameter enabling automatic rejections of incoming calls while participating at an active call.
17
+ */
18
+ autoRejectWhenInCall?: boolean;
19
+ /**
20
+ * Flag signals to SDK components not to wait until CallAccepted event is received,
21
+ * but join the call immediately upon emitting a new PendingCall by the stateStore.
22
+ * Note: Is relevant to outgoing calls only. Once the caller joins an outgoing call it's not possible to cancel that call.
23
+ */
24
+ joinCallInstantly?: boolean;
25
+ /**
26
+ * Flag signals, whether sounds should be played upon initiation of a new call.
27
+ */
28
+ playSounds?: boolean;
29
+ };
@@ -0,0 +1,19 @@
1
+ import { EventHandler, StreamClientOptions, TokenOrProvider, UR, User } from './connection/types';
2
+ import { GetCallEdgeServerRequest, GetCallEdgeServerResponse, GetOrCreateCallRequest, GetOrCreateCallResponse, JoinCallResponse, SendEventRequest } from '../gen/coordinator';
3
+ export declare class StreamCoordinatorClient {
4
+ private client;
5
+ constructor(apiKey: string, options?: StreamClientOptions);
6
+ on: (callbackOrEventName: EventHandler | string, callbackOrNothing?: EventHandler) => () => void;
7
+ off: (callbackOrEventName: EventHandler | string, callbackOrNothing?: EventHandler) => void;
8
+ connectUser: (user: User, token: TokenOrProvider) => Promise<void | import("./connection/types").ConnectionOpen>;
9
+ disconnectUser: (timeout?: number) => Promise<void>;
10
+ getOrCreateCall: (id: string, type: string, data?: GetOrCreateCallRequest) => Promise<GetOrCreateCallResponse>;
11
+ joinCall: (id: string, type: string, data?: GetOrCreateCallRequest) => Promise<JoinCallResponse>;
12
+ getCallEdgeServer: (id: string, type: string, data: GetCallEdgeServerRequest) => Promise<GetCallEdgeServerResponse>;
13
+ queryUsers: () => Promise<void>;
14
+ sendEvent: (id: string, type: string, data: SendEventRequest) => Promise<unknown>;
15
+ startRecording: (id: string, type: string) => Promise<void>;
16
+ stopRecording: (id: string, type: string) => Promise<void>;
17
+ reportCallStats: (id: string, type: string, data: UR) => Promise<void>;
18
+ reportCallStatEvent: (id: string, type: string, data: UR) => Promise<void>;
19
+ }
@@ -0,0 +1,2 @@
1
+ export declare const encodeBase64: (data: string) => string;
2
+ export declare const decodeBase64: (s: string) => string;
@@ -0,0 +1,174 @@
1
+ /// <reference types="node" />
2
+ import { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
3
+ import WebSocket from 'isomorphic-ws';
4
+ import { StableWSConnection } from './connection';
5
+ import { TokenManager } from './token_manager';
6
+ import { WSConnectionFallback } from './connection_fallback';
7
+ import { APIErrorResponse, ConnectAPIResponse, ErrorFromResponse, Event, EventHandler, Logger, OwnUserResponse, StreamClientOptions, TokenOrProvider, UserResponse } from './types';
8
+ import { InsightMetrics } from './insights';
9
+ export declare class StreamClient {
10
+ _user?: OwnUserResponse | UserResponse;
11
+ anonymous: boolean;
12
+ persistUserOnConnectionFailure?: boolean;
13
+ axiosInstance: AxiosInstance;
14
+ baseURL?: string;
15
+ browser: boolean;
16
+ cleaningIntervalRef?: NodeJS.Timeout;
17
+ clientID?: string;
18
+ key: string;
19
+ listeners: Record<string, Array<(event: Event) => void>>;
20
+ logger: Logger;
21
+ node: boolean;
22
+ options: StreamClientOptions;
23
+ secret?: string;
24
+ setUserPromise: ConnectAPIResponse | null;
25
+ tokenManager: TokenManager;
26
+ user?: OwnUserResponse | UserResponse;
27
+ userAgent?: string;
28
+ userID?: string;
29
+ wsBaseURL?: string;
30
+ wsConnection: StableWSConnection | null;
31
+ wsFallback?: WSConnectionFallback;
32
+ wsPromise: ConnectAPIResponse | null;
33
+ consecutiveFailures: number;
34
+ insightMetrics: InsightMetrics;
35
+ defaultWSTimeoutWithFallback: number;
36
+ defaultWSTimeout: number;
37
+ private nextRequestAbortController;
38
+ /**
39
+ * Initialize a client.
40
+ *
41
+ * @param {string} key - the api key
42
+ * @param {string} [secret] - the api secret
43
+ * @param {StreamClientOptions} [options] - additional options, here you can pass custom options to axios instance
44
+ * @param {boolean} [options.browser] - enforce the client to be in browser mode
45
+ * @param {boolean} [options.warmUp] - default to false, if true, client will open a connection as soon as possible to speed up following requests
46
+ * @param {Logger} [options.Logger] - custom logger
47
+ * @param {number} [options.timeout] - default to 3000
48
+ * @param {httpsAgent} [options.httpsAgent] - custom httpsAgent, in node it's default to https.agent()
49
+ * @example <caption>initialize the client in user mode</caption>
50
+ * new StreamChat('api_key')
51
+ * @example <caption>initialize the client in user mode with options</caption>
52
+ * new StreamChat('api_key', { warmUp:true, timeout:5000 })
53
+ * @example <caption>secret is optional and only used in server side mode</caption>
54
+ * new StreamChat('api_key', "secret", { httpsAgent: customAgent })
55
+ */
56
+ constructor(key: string, options?: StreamClientOptions);
57
+ constructor(key: string, secret?: string, options?: StreamClientOptions);
58
+ devToken(userID: string): string;
59
+ getAuthType(): "anonymous" | "jwt";
60
+ setBaseURL(baseURL: string): void;
61
+ _getConnectionID: () => string | undefined;
62
+ _hasConnectionID: () => boolean;
63
+ /**
64
+ * connectUser - Set the current user and open a WebSocket connection
65
+ *
66
+ * @param {OwnUserResponse | UserResponse} user Data about this user. IE {name: "john"}
67
+ * @param {TokenOrProvider} userTokenOrProvider Token or provider
68
+ *
69
+ * @return {ConnectAPIResponse} Returns a promise that resolves when the connection is setup
70
+ */
71
+ connectUser: (user: OwnUserResponse | UserResponse, userTokenOrProvider: TokenOrProvider) => Promise<void | import("./types").ConnectionOpen>;
72
+ _setToken: (user: UserResponse, userTokenOrProvider: TokenOrProvider) => Promise<void>;
73
+ _setUser(user: OwnUserResponse | UserResponse): void;
74
+ /**
75
+ * Disconnects the websocket connection, without removing the user set on client.
76
+ * client.closeConnection will not trigger default auto-retry mechanism for reconnection. You need
77
+ * to call client.openConnection to reconnect to websocket.
78
+ *
79
+ * This is mainly useful on mobile side. You can only receive push notifications
80
+ * if you don't have active websocket connection.
81
+ * So when your app goes to background, you can call `client.closeConnection`.
82
+ * And when app comes back to foreground, call `client.openConnection`.
83
+ *
84
+ * @param timeout Max number of ms, to wait for close event of websocket, before forcefully assuming succesful disconnection.
85
+ * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
86
+ */
87
+ closeConnection: (timeout?: number) => Promise<void>;
88
+ /**
89
+ * Creates a new WebSocket connection with the current user. Returns empty promise, if there is an active connection
90
+ */
91
+ openConnection: () => Promise<void | import("./types").ConnectionOpen>;
92
+ _normalizeDate: (before: Date | string | null) => string | null;
93
+ /**
94
+ * Disconnects the websocket and removes the user from client.
95
+ *
96
+ * @param timeout Max number of ms, to wait for close event of websocket, before forcefully assuming successful disconnection.
97
+ * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
98
+ */
99
+ disconnectUser: (timeout?: number) => Promise<void>;
100
+ /**
101
+ * connectAnonymousUser - Set an anonymous user and open a WebSocket connection
102
+ */
103
+ connectAnonymousUser: () => Promise<void | import("./types").ConnectionOpen>;
104
+ /**
105
+ * on - Listen to events on all channels and users your watching
106
+ *
107
+ * client.on('message.new', event => {console.log("my new message", event, channel.state.messages)})
108
+ * or
109
+ * client.on(event => {console.log(event.type)})
110
+ *
111
+ * @param {EventHandler | string} callbackOrEventName The event type to listen for (optional)
112
+ * @param {EventHandler} [callbackOrNothing] The callback to call
113
+ *
114
+ * @return {Function} Returns a function which, when called, unsubscribes the event handler.
115
+ */
116
+ on(callbackOrEventName: EventHandler | string, callbackOrNothing?: EventHandler): () => void;
117
+ /**
118
+ * off - Remove the event handler
119
+ *
120
+ */
121
+ off(callbackOrEventName: EventHandler | string, callbackOrNothing?: EventHandler): void;
122
+ _logApiRequest(type: string, url: string, data: unknown, config: AxiosRequestConfig & {
123
+ config?: AxiosRequestConfig & {
124
+ maxBodyLength?: number;
125
+ };
126
+ }): void;
127
+ _logApiResponse<T>(type: string, url: string, response: AxiosResponse<T>): void;
128
+ _logApiError(type: string, url: string, error: unknown): void;
129
+ doAxiosRequest: <T>(type: string, url: string, data?: unknown, options?: AxiosRequestConfig & {
130
+ config?: AxiosRequestConfig & {
131
+ maxBodyLength?: number;
132
+ };
133
+ }) => Promise<T>;
134
+ get<T>(url: string, params?: AxiosRequestConfig['params']): Promise<T>;
135
+ put<T>(url: string, data?: unknown): Promise<T>;
136
+ post<T>(url: string, data?: unknown): Promise<T>;
137
+ patch<T>(url: string, data?: unknown): Promise<T>;
138
+ delete<T>(url: string, params?: AxiosRequestConfig['params']): Promise<T>;
139
+ errorFromResponse(response: AxiosResponse<APIErrorResponse>): ErrorFromResponse<APIErrorResponse>;
140
+ handleResponse<T>(response: AxiosResponse<T>): T;
141
+ dispatchEvent: (event: Event) => void;
142
+ handleEvent: (messageEvent: WebSocket.MessageEvent) => void;
143
+ _callClientListeners: (event: Event) => void;
144
+ /**
145
+ * @private
146
+ */
147
+ connect(): Promise<void | import("./types").ConnectionOpen>;
148
+ /**
149
+ * Check the connectivity with server for warmup purpose.
150
+ *
151
+ * @private
152
+ */
153
+ _sayHi(): void;
154
+ getUserAgent(): string;
155
+ setUserAgent(userAgent: string): void;
156
+ /**
157
+ * _isUsingServerAuth - Returns true if we're using server side auth
158
+ */
159
+ _isUsingServerAuth: () => boolean;
160
+ _enrichAxiosOptions(options?: AxiosRequestConfig & {
161
+ config?: AxiosRequestConfig;
162
+ }): AxiosRequestConfig;
163
+ _getToken(): string | null | undefined;
164
+ /**
165
+ * encode ws url payload
166
+ * @private
167
+ * @returns json string
168
+ */
169
+ _buildWSPayload: (client_request_id?: string) => string;
170
+ /**
171
+ * creates an abort controller that will be used by the next HTTP Request.
172
+ */
173
+ createAbortControllerForNextRequest(): AbortController;
174
+ }
@@ -0,0 +1,139 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="ws" />
3
+ import WebSocket from 'isomorphic-ws';
4
+ import { StreamClient } from './client';
5
+ import type { ConnectAPIResponse, ConnectionOpen, LogLevel, UR } from './types';
6
+ /**
7
+ * StableWSConnection - A WS connection that reconnects upon failure.
8
+ * - the browser will sometimes report that you're online or offline
9
+ * - the WS connection can break and fail (there is a 30s health check)
10
+ * - sometimes your WS connection will seem to work while the user is in fact offline
11
+ * - to speed up online/offline detection you can use the window.addEventListener('offline');
12
+ *
13
+ * There are 4 ways in which a connection can become unhealthy:
14
+ * - websocket.onerror is called
15
+ * - websocket.onclose is called
16
+ * - the health check fails and no event is received for ~40 seconds
17
+ * - the browser indicates the connection is now offline
18
+ *
19
+ * There are 2 assumptions we make about the server:
20
+ * - state can be recovered by querying the channel again
21
+ * - if the servers fails to publish a message to the client, the WS connection is destroyed
22
+ */
23
+ export declare class StableWSConnection {
24
+ connectionID?: string;
25
+ connectionOpen?: ConnectAPIResponse;
26
+ consecutiveFailures: number;
27
+ pingInterval: number;
28
+ healthCheckTimeoutRef?: NodeJS.Timeout;
29
+ isConnecting: boolean;
30
+ isDisconnected: boolean;
31
+ isHealthy: boolean;
32
+ isResolved?: boolean;
33
+ lastEvent: Date | null;
34
+ connectionCheckTimeout: number;
35
+ connectionCheckTimeoutRef?: NodeJS.Timeout;
36
+ rejectPromise?: (reason?: Error & {
37
+ code?: string | number;
38
+ isWSFailure?: boolean;
39
+ StatusCode?: string | number;
40
+ }) => void;
41
+ requestID: string | undefined;
42
+ resolvePromise?: (value: ConnectionOpen) => void;
43
+ totalFailures: number;
44
+ ws?: WebSocket;
45
+ wsID: number;
46
+ token: string;
47
+ client: StreamClient;
48
+ constructor(client: StreamClient);
49
+ _log(msg: string, extra?: UR, level?: LogLevel): void;
50
+ setClient: (client: StreamClient) => void;
51
+ /**
52
+ * connect - Connect to the WS URL
53
+ * the default 15s timeout allows between 2~3 tries
54
+ * @return {ConnectAPIResponse<ChannelType, CommandType, UserType>} Promise that completes once the first health check message is received
55
+ */
56
+ connect(timeout?: number): Promise<void | ConnectionOpen>;
57
+ /**
58
+ * _waitForHealthy polls the promise connection to see if its resolved until it times out
59
+ * the default 15s timeout allows between 2~3 tries
60
+ * @param timeout duration(ms)
61
+ */
62
+ _waitForHealthy(timeout?: number): Promise<void | ConnectionOpen>;
63
+ /**
64
+ * Builds and returns the url for websocket.
65
+ * @private
66
+ * @returns url string
67
+ */
68
+ _buildUrl: () => string;
69
+ /**
70
+ * disconnect - Disconnect the connection and doesn't recover...
71
+ *
72
+ */
73
+ disconnect(timeout?: number): Promise<void>;
74
+ /**
75
+ * _connect - Connect to the WS endpoint
76
+ *
77
+ * @return {ConnectAPIResponse<ChannelType, CommandType, UserType>} Promise that completes once the first health check message is received
78
+ */
79
+ _connect(): Promise<ConnectionOpen | undefined>;
80
+ /**
81
+ * _reconnect - Retry the connection to WS endpoint
82
+ *
83
+ * @param {{ interval?: number; refreshToken?: boolean }} options Following options are available
84
+ *
85
+ * - `interval` {int} number of ms that function should wait before reconnecting
86
+ * - `refreshToken` {boolean} reload/refresh user token be refreshed before attempting reconnection.
87
+ */
88
+ _reconnect(options?: {
89
+ interval?: number;
90
+ refreshToken?: boolean;
91
+ }): Promise<void>;
92
+ /**
93
+ * onlineStatusChanged - this function is called when the browser connects or disconnects from the internet.
94
+ *
95
+ * @param {Event} event Event with type online or offline
96
+ *
97
+ */
98
+ onlineStatusChanged: (event: Event) => void;
99
+ onopen: (wsID: number) => void;
100
+ onmessage: (wsID: number, event: WebSocket.MessageEvent) => void;
101
+ onclose: (wsID: number, event: WebSocket.CloseEvent) => void;
102
+ onerror: (wsID: number, event: WebSocket.ErrorEvent) => void;
103
+ /**
104
+ * _setHealth - Sets the connection to healthy or unhealthy.
105
+ * Broadcasts an event in case the connection status changed.
106
+ *
107
+ * @param {boolean} healthy boolean indicating if the connection is healthy or not
108
+ *
109
+ */
110
+ _setHealth: (healthy: boolean) => void;
111
+ /**
112
+ * _errorFromWSEvent - Creates an error object for the WS event
113
+ *
114
+ */
115
+ _errorFromWSEvent: (event: WebSocket.CloseEvent | WebSocket.Data | WebSocket.ErrorEvent, isWSFailure?: boolean) => Error & {
116
+ code?: string | number | undefined;
117
+ isWSFailure?: boolean | undefined;
118
+ StatusCode?: string | number | undefined;
119
+ };
120
+ /**
121
+ * _destroyCurrentWSConnection - Removes the current WS connection
122
+ *
123
+ */
124
+ _destroyCurrentWSConnection(): void;
125
+ /**
126
+ * _setupPromise - sets up the this.connectOpen promise
127
+ */
128
+ _setupConnectionPromise: () => void;
129
+ /**
130
+ * Schedules a next health check ping for websocket.
131
+ */
132
+ scheduleNextPing: () => void;
133
+ /**
134
+ * scheduleConnectionCheck - schedules a check for time difference between last received event and now.
135
+ * If the difference is more than 35 seconds, it means our health check logic has failed and websocket needs
136
+ * to be reconnected.
137
+ */
138
+ scheduleConnectionCheck: () => void;
139
+ }
@@ -0,0 +1,38 @@
1
+ import { AxiosRequestConfig, CancelTokenSource } from 'axios';
2
+ import { StreamClient } from './client';
3
+ import { ConnectionOpen, UR, LogLevel } from './types';
4
+ export declare enum ConnectionState {
5
+ Closed = "CLOSED",
6
+ Connected = "CONNECTED",
7
+ Connecting = "CONNECTING",
8
+ Disconnected = "DISCONNECTED",
9
+ Init = "INIT"
10
+ }
11
+ export declare class WSConnectionFallback {
12
+ client: StreamClient;
13
+ state: ConnectionState;
14
+ consecutiveFailures: number;
15
+ connectionID?: string;
16
+ cancelToken?: CancelTokenSource;
17
+ constructor(client: StreamClient);
18
+ _log(msg: string, extra?: UR, level?: LogLevel): void;
19
+ _setState(state: ConnectionState): void;
20
+ /** @private */
21
+ _onlineStatusChanged: (event: {
22
+ type: string;
23
+ }) => void;
24
+ /** @private */
25
+ _req: <T = UR>(params: UR, config: AxiosRequestConfig, retry: boolean) => Promise<T>;
26
+ /** @private */
27
+ _poll: () => Promise<void>;
28
+ /**
29
+ * connect try to open a longpoll request
30
+ * @param reconnect should be false for first call and true for subsequent calls to keep the connection alive and call recoverState
31
+ */
32
+ connect: (reconnect?: boolean) => Promise<ConnectionOpen | undefined>;
33
+ /**
34
+ * isHealthy checks if there is a connectionID and connection is in Connected state
35
+ */
36
+ isHealthy: () => boolean;
37
+ disconnect: (timeout?: number) => Promise<void>;
38
+ }
@@ -0,0 +1,16 @@
1
+ import { AxiosResponse } from 'axios';
2
+ import { APIErrorResponse } from './types';
3
+ export declare const APIErrorCodes: Record<string, {
4
+ name: string;
5
+ retryable: boolean;
6
+ }>;
7
+ type APIError = Error & {
8
+ code: number;
9
+ isWSFailure?: boolean;
10
+ };
11
+ export declare function isAPIError(error: Error): error is APIError;
12
+ export declare function isErrorRetryable(error: APIError): boolean;
13
+ export declare function isConnectionIDError(error: APIError): boolean;
14
+ export declare function isWSFailure(err: APIError): boolean;
15
+ export declare function isErrorResponse(res: AxiosResponse<unknown>): res is AxiosResponse<APIErrorResponse>;
16
+ export {};