stream-chat
Version:
JS SDK for the Stream Chat API
1,055 lines • 87.5 kB
TypeScript
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import type WebSocket from 'isomorphic-ws';
import { Channel } from './channel';
import { ClientState } from './client_state';
import { StableWSConnection } from './connection';
import { TokenManager } from './token_manager';
import { WSConnectionFallback } from './connection_fallback';
import { Campaign } from './campaign';
import { Segment } from './segment';
import type { ActiveLiveLocationsAPIResponse, APIErrorResponse, APIResponse, AppSettings, AppSettingsAPIResponse, BannedUsersFilters, BannedUsersPaginationOptions, BannedUsersResponse, BannedUsersSort, BanUserOptions, BaseDeviceFields, BlockList, BlockListResponse, BlockUserAPIResponse, CampaignData, CampaignFilters, CampaignQueryOptions, CampaignResponse, CampaignSort, CastVoteAPIResponse, ChannelAPIResponse, ChannelData, ChannelFilters, ChannelMute, ChannelOptions, ChannelResponse, ChannelSort, ChannelStateOptions, CheckPushResponse, CheckSNSResponse, CheckSQSResponse, Configs, ConnectAPIResponse, CreateChannelOptions, CreateChannelResponse, CreateCommandOptions, CreateCommandResponse, CreateImportOptions, CreateImportResponse, CreateImportURLResponse, CreatePollAPIResponse, CreatePollData, CreatePollOptionAPIResponse, CreateReminderOptions, CustomPermissionOptions, DeactivateUsersOptions, DeleteCommandResponse, DeleteMessageOptions, DeleteUserOptions, Device, DeviceIdentifier, DraftFilters, DraftSort, EndpointName, Event, EventAPIResponse, EventHandler, ExportChannelOptions, ExportChannelRequest, ExportChannelResponse, ExportChannelStatusResponse, ExportUsersRequest, ExportUsersResponse, FlagMessageResponse, FlagReportsFilters, FlagReportsPaginationOptions, FlagReportsResponse, FlagsFilters, FlagsPaginationOptions, FlagsResponse, FlagUserResponse, GetBlockedUsersAPIResponse, GetCampaignOptions, GetChannelTypeResponse, GetCommandResponse, GetHookEventsResponse, GetImportResponse, GetMessageOptions, GetPollAPIResponse, GetRateLimitsResponse, GetThreadAPIResponse, GetThreadOptions, GetUnreadCountAPIResponse, GetUnreadCountBatchAPIResponse, ListChannelResponse, ListCommandsResponse, ListImportsPaginationOptions, ListImportsResponse, LocalMessage, Logger, MarkChannelsReadOptions, MarkDeliveredOptions, MessageFilters, MessageFlagsFilters, MessageFlagsPaginationOptions, MessageFlagsResponse, MessageResponse, Mute, MuteUserOptions, MuteUserResponse, OGAttachment, OwnUserResponse, Pager, PartialMessageUpdate, PartialPollUpdate, PartialThreadUpdate, PartialUserUpdate, PermissionAPIResponse, PermissionsAPIResponse, PollAnswersAPIResponse, PollData, PollOptionData, PollSort, PollVote, PollVoteData, PollVotesAPIResponse, Product, PushPreference, PushProvider, PushProviderConfig, PushProviderID, PushProviderListResponse, PushProviderUpsertResponse, QueryDraftsResponse, QueryMessageHistoryFilters, QueryMessageHistoryOptions, QueryMessageHistoryResponse, QueryMessageHistorySort, QueryPollsFilters, QueryPollsOptions, QueryPollsResponse, QueryReactionsAPIResponse, QueryReactionsOptions, QueryRemindersOptions, QueryRemindersResponse, QuerySegmentsOptions, QuerySegmentTargetsFilter, QueryThreadsOptions, QueryVotesFilters, QueryVotesOptions, ReactionFilters, ReactionResponse, ReactionSort, ReactivateUserOptions, ReactivateUsersOptions, ReminderAPIResponse, ReviewFlagReportOptions, ReviewFlagReportResponse, SdkIdentifier, SearchAPIResponse, SearchOptions, SegmentData, SegmentResponse, SegmentTargetsResponse, SegmentType, SendFileAPIResponse, SharedLocationResponse, SortParam, StreamChatOptions, SyncOptions, SyncResponse, TaskResponse, TaskStatus, TestPushDataInput, TestSNSDataInput, TestSQSDataInput, TokenOrProvider, TranslateResponse, UnBanUserOptions, UpdateChannelTypeRequest, UpdateChannelTypeResponse, UpdateCommandOptions, UpdateCommandResponse, UpdateLocationPayload, UpdateMessageAPIResponse, UpdateMessageOptions, UpdatePollAPIResponse, UpdateReminderOptions, UpdateSegmentData, UpdateUsersAPIResponse, UpsertPushPreferencesResponse, UserCustomEvent, UserFilters, UserOptions, UserResponse, UserSort, VoteSort } from './types';
import { ErrorFromResponse } from './types';
import { InsightMetrics } from './insights';
import { Thread } from './thread';
import { Moderation } from './moderation';
import { ThreadManager } from './thread_manager';
import { PollManager } from './poll_manager';
import type { ChannelManagerEventHandlerOverrides, ChannelManagerOptions, QueryChannelsRequestType } from './channel_manager';
import { ChannelManager } from './channel_manager';
import { MessageDeliveryReporter } from './messageDelivery';
import { NotificationManager } from './notifications';
import { ReminderManager } from './reminders';
import { StateStore } from './store';
import type { MessageComposer } from './messageComposer';
import type { AbstractOfflineDB } from './offline-support';
type MessageComposerTearDownFunction = () => void;
type MessageComposerSetupFunction = ({ composer, }: {
composer: MessageComposer;
}) => void | MessageComposerTearDownFunction;
export type MessageComposerSetupState = {
/**
* Each `MessageComposer` runs this function each time its signature changes or
* whenever you run `MessageComposer.registerSubscriptions`. Function returned
* from `applyModifications` will be used as a cleanup function - it will be stored
* and ran before new modification is applied. Cleaning up only the
* modified parts is the general way to go but if your setup gets a bit
* complicated, feel free to restore the whole composer with `MessageComposer.restore`.
*/
setupFunction: MessageComposerSetupFunction | null;
};
export declare class StreamChat {
private static _instance?;
messageDeliveryReporter: MessageDeliveryReporter;
_user?: OwnUserResponse | UserResponse;
appSettingsPromise?: Promise<AppSettingsAPIResponse>;
activeChannels: {
[key: string]: Channel;
};
threads: ThreadManager;
polls: PollManager;
offlineDb?: AbstractOfflineDB;
notifications: NotificationManager;
reminders: ReminderManager;
anonymous: boolean;
persistUserOnConnectionFailure?: boolean;
axiosInstance: AxiosInstance;
baseURL?: string;
browser: boolean;
cleaningIntervalRef?: NodeJS.Timeout;
clientID?: string;
configs: Configs;
key: string;
listeners: Record<string, Array<(event: Event) => void>>;
logger: Logger;
/**
* When network is recovered, we re-query the active channels on client. But in single query, you can recover
* only 30 channels. So its not guaranteed that all the channels in activeChannels object have updated state.
* Thus in UI sdks, state recovery is managed by components themselves, they don't rely on js client for this.
*
* `recoverStateOnReconnect` parameter can be used in such cases, to disable state recovery within js client.
* When false, user/consumer of this client will need to make sure all the channels present on UI by
* manually calling queryChannels endpoint.
*/
recoverStateOnReconnect?: boolean;
moderation: Moderation;
mutedChannels: ChannelMute[];
mutedUsers: Mute[];
node: boolean;
options: StreamChatOptions;
secret?: string;
setUserPromise: ConnectAPIResponse | null;
state: ClientState;
tokenManager: TokenManager;
user?: OwnUserResponse | UserResponse;
userAgent?: string;
userID?: string;
wsBaseURL?: string;
wsConnection: StableWSConnection | null;
wsFallback?: WSConnectionFallback;
wsPromise: ConnectAPIResponse | null;
consecutiveFailures: number;
insightMetrics: InsightMetrics;
defaultWSTimeoutWithFallback: number;
defaultWSTimeout: number;
sdkIdentifier?: SdkIdentifier;
deviceIdentifier?: DeviceIdentifier;
private nextRequestAbortController;
/**
* @private
*/
_messageComposerSetupState: StateStore<MessageComposerSetupState>;
/**
* Initialize a client
*
* **Only use constructor for advanced usages. It is strongly advised to use `StreamChat.getInstance()` instead of `new StreamChat()` to reduce integration issues due to multiple WebSocket connections**
* @param {string} key - the api key
* @param {string} [secret] - the api secret
* @param {StreamChatOptions} [options] - additional options, here you can pass custom options to axios instance
* @param {boolean} [options.browser] - enforce the client to be in browser mode
* @param {boolean} [options.warmUp] - default to false, if true, client will open a connection as soon as possible to speed up following requests
* @param {Logger} [options.Logger] - custom logger
* @param {number} [options.timeout] - default to 3000
* @param {httpsAgent} [options.httpsAgent] - custom httpsAgent, in node it's default to https.agent()
* @example <caption>initialize the client in user mode</caption>
* new StreamChat('api_key')
* @example <caption>initialize the client in user mode with options</caption>
* new StreamChat('api_key', { warmUp:true, timeout:5000 })
* @example <caption>secret is optional and only used in server side mode</caption>
* new StreamChat('api_key', "secret", { httpsAgent: customAgent })
*/
constructor(key: string, options?: StreamChatOptions);
constructor(key: string, secret?: string, options?: StreamChatOptions);
/**
* Get a client instance
*
* This function always returns the same Client instance to avoid issues raised by multiple Client and WS connections
*
* **After the first call, the client configuration will not change if the key or options parameters change**
*
* @param {string} key - the api key
* @param {string} [secret] - the api secret
* @param {StreamChatOptions} [options] - additional options, here you can pass custom options to axios instance
* @param {boolean} [options.browser] - enforce the client to be in browser mode
* @param {boolean} [options.warmUp] - default to false, if true, client will open a connection as soon as possible to speed up following requests
* @param {Logger} [options.Logger] - custom logger
* @param {number} [options.timeout] - default to 3000
* @param {httpsAgent} [options.httpsAgent] - custom httpsAgent, in node it's default to https.agent()
* @example <caption>initialize the client in user mode</caption>
* StreamChat.getInstance('api_key')
* @example <caption>initialize the client in user mode with options</caption>
* StreamChat.getInstance('api_key', { timeout:5000 })
* @example <caption>secret is optional and only used in server side mode</caption>
* StreamChat.getInstance('api_key', "secret", { httpsAgent: customAgent })
*/
static getInstance(key: string, options?: StreamChatOptions): StreamChat;
static getInstance(key: string, secret?: string, options?: StreamChatOptions): StreamChat;
setOfflineDBApi(offlineDBInstance: AbstractOfflineDB): void;
devToken(userID: string): string;
getAuthType(): "anonymous" | "jwt";
setBaseURL(baseURL: string): void;
_getConnectionID: () => string | undefined;
_hasConnectionID: () => boolean;
setMessageComposerSetupFunction: (setupFunction: MessageComposerSetupState["setupFunction"]) => void;
/**
* connectUser - Set the current user and open a WebSocket connection
*
* @param {OwnUserResponse | UserResponse} user Data about this user. IE {name: "john"}
* @param {TokenOrProvider} userTokenOrProvider Token or provider
*
* @return {ConnectAPIResponse} Returns a promise that resolves when the connection is setup
*/
connectUser: (user: OwnUserResponse | UserResponse, userTokenOrProvider: TokenOrProvider) => Promise<void | import("./types").ConnectionOpen>;
/**
* @deprecated Please use connectUser() function instead. Its naming is more consistent with its functionality.
*
* setUser - Set the current user and open a WebSocket connection
*
* @param {OwnUserResponse | UserResponse} user Data about this user. IE {name: "john"}
* @param {TokenOrProvider} userTokenOrProvider Token or provider
*
* @return {ConnectAPIResponse} Returns a promise that resolves when the connection is setup
*/
setUser: (user: OwnUserResponse | UserResponse, userTokenOrProvider: TokenOrProvider) => Promise<void | import("./types").ConnectionOpen>;
_setToken: (user: UserResponse, userTokenOrProvider: TokenOrProvider) => Promise<void>;
_setUser(user: OwnUserResponse | UserResponse): void;
/**
* Disconnects the websocket connection, without removing the user set on client.
* client.closeConnection will not trigger default auto-retry mechanism for reconnection. You need
* to call client.openConnection to reconnect to websocket.
*
* This is mainly useful on mobile side. You can only receive push notifications
* if you don't have active websocket connection.
* So when your app goes to background, you can call `client.closeConnection`.
* And when app comes back to foreground, call `client.openConnection`.
*
* @param timeout Max number of ms, to wait for close event of websocket, before forcefully assuming succesful disconnection.
* https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
*/
closeConnection: (timeout?: number) => Promise<void>;
/**
* Creates an instance of ChannelManager.
*
* @internal
*
* @param eventHandlerOverrides - the overrides for event handlers to be used
* @param options - the options used for the channel manager
*/
createChannelManager: ({ eventHandlerOverrides, options, queryChannelsOverride, }: {
eventHandlerOverrides?: ChannelManagerEventHandlerOverrides;
options?: ChannelManagerOptions;
queryChannelsOverride?: QueryChannelsRequestType;
}) => ChannelManager;
/**
* Creates a new WebSocket connection with the current user. Returns empty promise, if there is an active connection
*/
openConnection: () => ConnectAPIResponse | undefined;
/**
* @deprecated Please use client.openConnction instead.
* @private
*
* Creates a new websocket connection with current user.
*/
_setupConnection: () => ConnectAPIResponse | undefined;
/**
* updateAppSettings - updates application settings
*
* @param {AppSettings} options App settings.
* IE: {
'apn_config': {
'auth_type': 'token',
'auth_key": fs.readFileSync(
'./apn-push-auth-key.p8',
'utf-8',
),
'key_id': 'keyid',
'team_id': 'teamid',
'notification_template": 'notification handlebars template',
'bundle_id': 'com.apple.your.app',
'development': true
},
'firebase_config': {
'server_key': 'server key from fcm',
'notification_template': 'notification handlebars template',
'data_template': 'data handlebars template',
'apn_template': 'apn notification handlebars template under v2'
},
'webhook_url': 'https://acme.com/my/awesome/webhook/',
'event_hooks': [
{
'hook_type': 'webhook',
'enabled': true,
'event_types': ['message.new'],
'webhook_url': 'https://acme.com/my/awesome/webhook/'
},
{
'hook_type': 'sqs',
'enabled': true,
'event_types': ['message.new'],
'sqs_url': 'https://sqs.us-east-1.amazonaws.com/1234567890/my-queue',
'sqs_auth_type': 'key',
'sqs_key': 'my-access-key',
'sqs_secret': 'my-secret-key'
}
]
}
*/
updateAppSettings(options: AppSettings): Promise<APIResponse>;
_normalizeDate: (before: Date | string | null) => string | null;
/**
* Revokes all tokens on application level issued before given time
*/
revokeTokens(before: Date | string | null): Promise<APIResponse>;
/**
* Revokes token for a user issued before given time
*/
revokeUserToken(userID: string, before?: Date | string | null): Promise<UpdateUsersAPIResponse>;
/**
* Revokes tokens for a list of users issued before given time
*/
revokeUsersToken(userIDs: string[], before?: Date | string | null): Promise<UpdateUsersAPIResponse>;
/**
* getAppSettings - retrieves application settings
*/
getAppSettings(): Promise<AppSettingsAPIResponse>;
/**
* testPushSettings - Tests the push settings for a user with a random chat message and the configured push templates
*
* @param {string} userID User ID. If user has no devices, it will error
* @param {TestPushDataInput} [data] Overrides for push templates/message used
* IE: {
messageID: 'id-of-message', // will error if message does not exist
apnTemplate: '{}', // if app doesn't have apn configured it will error
firebaseTemplate: '{}', // if app doesn't have firebase configured it will error
firebaseDataTemplate: '{}', // if app doesn't have firebase configured it will error
skipDevices: true, // skip config/device checks and sending to real devices
pushProviderName: 'staging' // one of your configured push providers
pushProviderType: 'apn' // one of supported provider types
}
*/
testPushSettings(userID: string, data?: TestPushDataInput): Promise<CheckPushResponse>;
/**
* testSQSSettings - Tests that the given or configured SQS configuration is valid
*
* @param {TestSQSDataInput} [data] Overrides SQS settings for testing if needed
* IE: {
sqs_key: 'auth_key',
sqs_secret: 'auth_secret',
sqs_url: 'url_to_queue',
}
*/
testSQSSettings(data?: TestSQSDataInput): Promise<CheckSQSResponse>;
/**
* testSNSSettings - Tests that the given or configured SNS configuration is valid
*
* @param {TestSNSDataInput} [data] Overrides SNS settings for testing if needed
* IE: {
sns_key: 'auth_key',
sns_secret: 'auth_secret',
sns_topic_arn: 'topic_to_publish_to',
}
*/
testSNSSettings(data?: TestSNSDataInput): Promise<CheckSNSResponse>;
/**
* Disconnects the websocket and removes the user from client.
*
* @param timeout Max number of ms, to wait for close event of websocket, before forcefully assuming successful disconnection.
* https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
*/
disconnectUser: (timeout?: number) => Promise<void>;
/**
*
* @deprecated Please use client.disconnectUser instead.
*
* Disconnects the websocket and removes the user from client.
*/
disconnect: (timeout?: number) => Promise<void>;
/**
* connectAnonymousUser - Set an anonymous user and open a WebSocket connection
*/
connectAnonymousUser: () => ConnectAPIResponse | undefined;
/**
* @deprecated Please use connectAnonymousUser. Its naming is more consistent with its functionality.
*/
setAnonymousUser: () => ConnectAPIResponse | undefined;
/**
* setGuestUser - Setup a temporary guest user
*
* @param {UserResponse} user Data about this user. IE {name: "john"}
*
* @return {ConnectAPIResponse} Returns a promise that resolves when the connection is setup
*/
setGuestUser(user: UserResponse): Promise<void | import("./types").ConnectionOpen>;
/**
* createToken - Creates a token to authenticate this user. This function is used server side.
* The resulting token should be passed to the client side when the users registers or logs in.
*
* @param {string} userID The User ID
* @param {number} [exp] The expiration time for the token expressed in the number of seconds since the epoch
*
* @return {string} Returns a token
*/
createToken(userID: string, exp?: number, iat?: number): string;
/**
* on - Listen to events on all channels and users your watching
*
* client.on('message.new', event => {console.log("my new message", event, channel.state.messages)})
* or
* client.on(event => {console.log(event.type)})
*
* @param {EventHandler | string} callbackOrString The event type to listen for (optional)
* @param {EventHandler} [callbackOrNothing] The callback to call
*
* @return {{ unsubscribe: () => void }} Description
*/
on(callback: EventHandler): {
unsubscribe: () => void;
};
on(eventType: string, callback: EventHandler): {
unsubscribe: () => void;
};
/**
* off - Remove the event handler
*
*/
off(callback: EventHandler): void;
off(eventType: string, callback: EventHandler): void;
_logApiRequest(type: string, url: string, data: unknown, config: AxiosRequestConfig & {
config?: AxiosRequestConfig & {
maxBodyLength?: number;
};
}): void;
_logApiResponse<T>(type: string, url: string, response: AxiosResponse<T>): void;
_logApiError(type: string, url: string, error: unknown): void;
doAxiosRequest: <T>(type: string, url: string, data?: unknown, options?: AxiosRequestConfig & {
config?: AxiosRequestConfig & {
maxBodyLength?: number;
};
}) => Promise<T>;
get<T>(url: string, params?: AxiosRequestConfig['params']): Promise<T>;
put<T>(url: string, data?: unknown): Promise<T>;
post<T>(url: string, data?: unknown): Promise<T>;
patch<T>(url: string, data?: unknown): Promise<T>;
delete<T>(url: string, params?: AxiosRequestConfig['params']): Promise<T>;
sendFile(url: string, uri: string | NodeJS.ReadableStream | Buffer | File, name?: string, contentType?: string, user?: UserResponse): Promise<SendFileAPIResponse>;
errorFromResponse(response: AxiosResponse<APIErrorResponse>): ErrorFromResponse<APIErrorResponse>;
handleResponse<T>(response: AxiosResponse<T>): T;
dispatchEvent: (event: Event) => void;
handleEvent: (messageEvent: WebSocket.MessageEvent) => void;
/**
* Updates the members, watchers and read references of the currently active channels that contain this user
*
* @param {UserResponse} user
*/
_updateMemberWatcherReferences: (user: UserResponse) => void;
/**
* @deprecated Please _updateMemberWatcherReferences instead.
* @private
*/
_updateUserReferences: (user: UserResponse) => void;
/**
* @private
*
* Updates the messages from the currently active channels that contain this user,
* with updated user object.
*
* @param {UserResponse} user
*/
_updateUserMessageReferences: (user: UserResponse) => void;
/**
* @private
*
* Deletes the messages from the currently active channels that contain this user
*
* If hardDelete is true, all the content of message will be stripped down.
* Otherwise, only 'message.type' will be set as 'deleted'.
*
* @param {UserResponse} user
* @param {boolean} hardDelete
*/
_deleteUserMessageReference: (user: UserResponse, hardDelete?: boolean, deletedAt?: LocalMessage["deleted_at"]) => void;
/**
* @private
*
* Handle following user related events:
* - user.presence.changed
* - user.updated
* - user.deleted
*
* @param {Event} event
*/
_handleUserEvent: (event: Event) => void;
_handleClientEvent(event: Event): (() => void)[];
_muteStatus(cid: string): {
muted: boolean;
createdAt: Date;
expiresAt: Date | null;
} | {
muted: boolean;
createdAt: null;
expiresAt: null;
};
_callClientListeners: (event: Event) => void;
recoverState: () => Promise<void>;
/**
* @private
*/
connect(): Promise<void | import("./types").ConnectionOpen>;
/**
* Check the connectivity with server for warmup purpose.
*
* @private
*/
_sayHi(): void;
/**
* queryUsers - Query users and watch user presence
*
* @param {UserFilters} filterConditions MongoDB style filter conditions
* @param {UserSort} sort Sort options, for instance [{last_active: -1}].
* When using multiple fields, make sure you use array of objects to guarantee field order, for instance [{last_active: -1}, {created_at: 1}]
* @param {UserOptions} options Option object, {presence: true}
*
* @return {Promise<{ users: Array<UserResponse> }>} User Query Response
*/
queryUsers(filterConditions: UserFilters, sort?: UserSort, options?: UserOptions): Promise<APIResponse & {
users: Array<UserResponse>;
}>;
/**
* queryBannedUsers - Query user bans
*
* @param {BannedUsersFilters} filterConditions MongoDB style filter conditions
* @param {BannedUsersSort} sort Sort options [{created_at: 1}].
* @param {BannedUsersPaginationOptions} options Option object, {limit: 10, offset:0, exclude_expired_bans: true}
*
* @return {Promise<BannedUsersResponse>} Ban Query Response
*/
queryBannedUsers(filterConditions?: BannedUsersFilters, sort?: BannedUsersSort, options?: BannedUsersPaginationOptions): Promise<BannedUsersResponse>;
/**
* queryMessageFlags - Query message flags
*
* @param {MessageFlagsFilters} filterConditions MongoDB style filter conditions
* @param {MessageFlagsPaginationOptions} options Option object, {limit: 10, offset:0}
*
* @return {Promise<MessageFlagsResponse>} Message Flags Response
*/
queryMessageFlags(filterConditions?: MessageFlagsFilters, options?: MessageFlagsPaginationOptions): Promise<MessageFlagsResponse>;
/**
* queryChannelsRequest - Queries channels and returns the raw response
*
* @param {ChannelFilters} filterConditions object MongoDB style filters
* @param {ChannelSort} [sort] Sort options, for instance {created_at: -1}.
* When using multiple fields, make sure you use array of objects to guarantee field order, for instance [{last_updated: -1}, {created_at: 1}]
* @param {ChannelOptions} [options] Options object
*
* @return {Promise<Array<ChannelAPIResponse>>} search channels response
*/
queryChannelsRequest(filterConditions: ChannelFilters, sort?: ChannelSort, options?: ChannelOptions): Promise<Omit<ChannelAPIResponse, keyof APIResponse>[]>;
/**
* queryChannels - Query channels
*
* @param {ChannelFilters} filterConditions object MongoDB style filters
* @param {ChannelSort} [sort] Sort options, for instance {created_at: -1}.
* When using multiple fields, make sure you use array of objects to guarantee field order, for instance [{last_updated: -1}, {created_at: 1}]
* @param {ChannelOptions} [options] Options object
* @param {ChannelStateOptions} [stateOptions] State options object. These options will only be used for state management and won't be sent in the request.
* - stateOptions.skipInitialization - Skips the initialization of the state for the channels matching the ids in the list.
* - stateOptions.skipHydration - Skips returning the channels as instances of the Channel class and rather returns the raw query response.
*
* @return {Promise<Array<Channel>>} search channels response
*/
queryChannels(filterConditions: ChannelFilters, sort?: ChannelSort, options?: ChannelOptions, stateOptions?: ChannelStateOptions): Promise<Channel[]>;
/**
* queryReactions - Query reactions
*
* @param {ReactionFilters} filter object MongoDB style filters
* @param {ReactionSort} [sort] Sort options, for instance {created_at: -1}.
* @param {QueryReactionsOptions} [options] Pagination object
*
* @return {Promise<{ QueryReactionsAPIResponse } search channels response
*/
queryReactions(messageID: string, filter: ReactionFilters, sort?: ReactionSort, options?: QueryReactionsOptions): Promise<QueryReactionsAPIResponse>;
hydrateActiveChannels(channelsFromApi?: ChannelAPIResponse[], stateOptions?: ChannelStateOptions, queryChannelsOptions?: ChannelOptions): Channel[];
/**
* search - Query messages
*
* @param {ChannelFilters} filterConditions MongoDB style filter conditions
* @param {MessageFilters | string} query search query or object MongoDB style filters
* @param {SearchOptions} [options] Option object, {user_id: 'tommaso'}
*
* @return {Promise<SearchAPIResponse>} search messages response
*/
search(filterConditions: ChannelFilters, query: string | MessageFilters, options?: SearchOptions): Promise<SearchAPIResponse>;
/**
* setLocalDevice - Set the device info for the current client(device) that will be sent via WS connection automatically
*
* @param {BaseDeviceFields} device the device object
* @param {string} device.id device id
* @param {string} device.push_provider the push provider
*
*/
setLocalDevice(device: BaseDeviceFields): void;
/**
* addDevice - Adds a push device for a user.
*
* @param {string} id the device id
* @param {PushProvider} push_provider the push provider
* @param {string} [userID] the user id (defaults to current user)
* @param {string} [push_provider_name] user provided push provider name for multi bundle support
*
*/
addDevice(id: string, push_provider: PushProvider, userID?: string, push_provider_name?: string): Promise<APIResponse>;
/**
* getDevices - Returns the devices associated with a current user
*
* @param {string} [userID] User ID. Only works on serverside
*
* @return {Device[]} Array of devices
*/
getDevices(userID?: string): Promise<APIResponse & {
devices?: Device[];
}>;
/**
* getUnreadCount - Returns unread counts for a single user
*
* @param {string} [userID] User ID.
*
* @return {<GetUnreadCountAPIResponse>}
*/
getUnreadCount(userID?: string): Promise<GetUnreadCountAPIResponse>;
/**
* getUnreadCountBatch - Returns unread counts for multiple users at once. Only works server side.
*
* @param {string[]} [userIDs] List of user IDs to fetch unread counts for.
*
* @return {<GetUnreadCountBatchAPIResponse>}
*/
getUnreadCountBatch(userIDs: string[]): Promise<GetUnreadCountBatchAPIResponse>;
/**
* setPushPreferences - Applies the list of push preferences.
*
* @param {PushPreference[]} A list of push preferences.
*
* @return {<UpsertPushPreferencesResponse>}
*/
setPushPreferences(preferences: PushPreference[]): Promise<UpsertPushPreferencesResponse>;
/**
* removeDevice - Removes the device with the given id. Clientside users can only delete their own devices
*
* @param {string} id The device id
* @param {string} [userID] The user id. Only specify this for serverside requests
*
*/
removeDevice(id: string, userID?: string): Promise<APIResponse>;
/**
* getRateLimits - Returns the rate limits quota and usage for the current app, possibly filter for a specific platform and/or endpoints.
* Only available server-side.
*
* @param {object} [params] The params for the call. If none of the params are set, all limits for all platforms are returned.
* @returns {Promise<GetRateLimitsResponse>}
*/
getRateLimits(params?: {
android?: boolean;
endpoints?: EndpointName[];
ios?: boolean;
serverSide?: boolean;
web?: boolean;
}): Promise<GetRateLimitsResponse>;
/**
* getHookEvents - Get available events for hooks (webhook, SQS, and SNS)
*
* @param {Product[]} [products] Optional array of products to filter events by (e.g., [Product.Chat, Product.Video])
* @returns {Promise<GetHookEventsResponse>} Response containing available hook events
*/
getHookEvents(products?: Product[]): Promise<GetHookEventsResponse>;
_addChannelConfig({ cid, config }: ChannelResponse): void;
/**
* channel - Returns a new channel with the given type, id and custom data
*
* If you want to create a unique conversation between 2 or more users; you can leave out the ID parameter and provide the list of members.
* Make sure to await channel.create() or channel.watch() before accessing channel functions:
* ie. channel = client.channel("messaging", {members: ["tommaso", "thierry"]})
* await channel.create() to assign an ID to channel
*
* @param {string} channelType The channel type
* @param {string | ChannelData | null} [channelIDOrCustom] The channel ID, you can leave this out if you want to create a conversation channel
* @param {object} [custom] Custom data to attach to the channel
*
* @return {channel} The channel object, initialize it using channel.watch()
*/
channel(channelType: string, channelID?: string | null, custom?: ChannelData): Channel;
channel(channelType: string, custom?: ChannelData): Channel;
/**
* It's a helper method for `client.channel()` method, used to create unique conversation or
* channel based on member list instead of id.
*
* If the channel already exists in `activeChannels` list, then we simply return it, since that
* means the same channel was already requested or created.
*
* Otherwise we create a new instance of Channel class and return it.
*
* @private
*
* @param {string} channelType The channel type
* @param {object} [custom] Custom data to attach to the channel
*
* @return {channel} The channel object, initialize it using channel.watch()
*/
getChannelByMembers: (channelType: string, custom: ChannelData) => Channel;
/**
* Its a helper method for `client.channel()` method, used to channel given the id of channel.
*
* If the channel already exists in `activeChannels` list, then we simply return it, since that
* means the same channel was already requested or created.
*
* Otherwise we create a new instance of Channel class and return it.
*
* @private
*
* @param {string} channelType The channel type
* @param {string} [channelID] The channel ID
* @param {object} [custom] Custom data to attach to the channel
*
* @return {channel} The channel object, initialize it using channel.watch()
*/
getChannelById: (channelType: string, channelID: string, custom: ChannelData) => Channel;
/**
* partialUpdateUser - Update the given user object
*
* @param {PartialUserUpdate} partialUserObject which should contain id and any of "set" or "unset" params;
* example: {id: "user1", set:{field: value}, unset:["field2"]}
*
* @return {Promise<{ users: { [key: string]: UserResponse } }>} list of updated users
*/
partialUpdateUser(partialUserObject: PartialUserUpdate): Promise<UpdateUsersAPIResponse>;
/**
* upsertUsers - Batch upsert the list of users
*
* @param {UserResponse[]} users list of users
*
* @return {Promise<{ users: { [key: string]: UserResponse } }>}
*/
upsertUsers(users: UserResponse[]): Promise<UpdateUsersAPIResponse>;
/**
* @deprecated Please use upsertUsers() function instead.
*
* updateUsers - Batch update the list of users
*
* @param {UserResponse[]} users list of users
* @return {Promise<{ users: { [key: string]: UserResponse } }>}
*/
updateUsers: (users: UserResponse[]) => Promise<UpdateUsersAPIResponse>;
/**
* upsertUser - Update or Create the given user object
*
* @param {UserResponse} userObject user object, the only required field is the user id. IE {id: "myuser"} is valid
*
* @return {Promise<{ users: { [key: string]: UserResponse } }>}
*/
upsertUser(userObject: UserResponse): Promise<UpdateUsersAPIResponse>;
/**
* @deprecated Please use upsertUser() function instead.
*
* updateUser - Update or Create the given user object
*
* @param {UserResponse} userObject user object, the only required field is the user id. IE {id: "myuser"} is valid
* @return {Promise<{ users: { [key: string]: UserResponse } }>}
*/
updateUser: (userObject: UserResponse) => Promise<UpdateUsersAPIResponse>;
/**
* partialUpdateUsers - Batch partial update of users
*
* @param {PartialUserUpdate[]} users list of partial update requests
*
* @return {Promise<{ users: { [key: string]: UserResponse } }>}
*/
partialUpdateUsers(users: PartialUserUpdate[]): Promise<UpdateUsersAPIResponse>;
deleteUser(userID: string, params?: {
delete_conversation_channels?: boolean;
hard_delete?: boolean;
mark_messages_deleted?: boolean;
}): Promise<APIResponse & {
user: UserResponse;
} & {
task_id?: string;
}>;
/**
* restoreUsers - Restore soft deleted users
*
* @param {string[]} user_ids which users to restore
*
* @return {APIResponse} An API response
*/
restoreUsers(user_ids: string[]): Promise<APIResponse>;
/**
* reactivateUser - Reactivate one user
*
* @param {string} userID which user to reactivate
* @param {ReactivateUserOptions} [options]
*
* @return {UserResponse} Reactivated user
*/
reactivateUser(userID: string, options?: ReactivateUserOptions): Promise<APIResponse & {
user: UserResponse;
}>;
/**
* reactivateUsers - Reactivate many users asynchronously
*
* @param {string[]} user_ids which users to reactivate
* @param {ReactivateUsersOptions} [options]
*
* @return {TaskResponse} A task ID
*/
reactivateUsers(user_ids: string[], options?: ReactivateUsersOptions): Promise<APIResponse & TaskResponse>;
/**
* deactivateUser - Deactivate one user
*
* @param {string} userID which user to deactivate
* @param {DeactivateUsersOptions} [options]
*
* @return {UserResponse} Deactivated user
*/
deactivateUser(userID: string, options?: DeactivateUsersOptions): Promise<APIResponse & {
user: UserResponse;
}>;
/**
* deactivateUsers - Deactivate many users asynchronously
*
* @param {string[]} user_ids which users to deactivate
* @param {DeactivateUsersOptions} [options]
*
* @return {TaskResponse} A task ID
*/
deactivateUsers(user_ids: string[], options?: DeactivateUsersOptions): Promise<APIResponse & TaskResponse>;
exportUser(userID: string, options?: Record<string, string>): Promise<APIResponse & {
messages: MessageResponse[];
reactions: ReactionResponse[];
user: UserResponse;
}>;
/** banUser - bans a user from all channels
*
* @param {string} targetUserID
* @param {BanUserOptions} [options]
* @returns {Promise<APIResponse>}
*/
banUser(targetUserID: string, options?: BanUserOptions): Promise<APIResponse>;
/** unbanUser - revoke global ban for a user
*
* @param {string} targetUserID
* @param {UnBanUserOptions} [options]
* @returns {Promise<APIResponse>}
*/
unbanUser(targetUserID: string, options?: UnBanUserOptions): Promise<APIResponse>;
/** shadowBan - shadow bans a user from all channels
*
* @param {string} targetUserID
* @param {BanUserOptions} [options]
* @returns {Promise<APIResponse>}
*/
shadowBan(targetUserID: string, options?: BanUserOptions): Promise<APIResponse>;
/** removeShadowBan - revoke global shadow ban for a user
*
* @param {string} targetUserID
* @param {UnBanUserOptions} [options]
* @returns {Promise<APIResponse>}
*/
removeShadowBan(targetUserID: string, options?: UnBanUserOptions): Promise<APIResponse>;
blockUser(blockedUserID: string, user_id?: string): Promise<BlockUserAPIResponse>;
getBlockedUsers(user_id?: string): Promise<GetBlockedUsersAPIResponse>;
unBlockUser(blockedUserID: string, userID?: string): Promise<APIResponse>;
/** getSharedLocations
*
* @returns {Promise<ActiveLiveLocationsAPIResponse>} The server response
*
*/
getSharedLocations(): Promise<ActiveLiveLocationsAPIResponse>;
/** muteUser - mutes a user
*
* @param {string} targetID
* @param {string} [userID] Only used with serverside auth
* @param {MuteUserOptions} [options]
* @returns {Promise<MuteUserResponse>}
*/
muteUser(targetID: string, userID?: string, options?: MuteUserOptions): Promise<MuteUserResponse>;
/** unmuteUser - unmutes a user
*
* @param {string} targetID
* @param {string} [currentUserID] Only used with serverside auth
* @returns {Promise<APIResponse>}
*/
unmuteUser(targetID: string, currentUserID?: string): Promise<APIResponse>;
/** userMuteStatus - check if a user is muted or not, can be used after connectUser() is called
*
* @param {string} targetID
* @returns {boolean}
*/
userMuteStatus(targetID: string): boolean;
/**
* flagMessage - flag a message
* @param {string} targetMessageID
* @param {string} [options.user_id] currentUserID, only used with serverside auth
* @returns {Promise<APIResponse>}
*/
flagMessage(targetMessageID: string, options?: {
reason?: string;
user_id?: string;
}): Promise<FlagMessageResponse>;
/**
* flagUser - flag a user
* @param {string} targetID
* @param {string} [options.user_id] currentUserID, only used with serverside auth
* @returns {Promise<APIResponse>}
*/
flagUser(targetID: string, options?: {
reason?: string;
user_id?: string;
}): Promise<FlagUserResponse>;
/**
* unflagMessage - unflag a message
* @param {string} targetMessageID
* @param {string} [options.user_id] currentUserID, only used with serverside auth
* @returns {Promise<APIResponse>}
*/
unflagMessage(targetMessageID: string, options?: {
user_id?: string;
}): Promise<FlagMessageResponse>;
/**
* unflagUser - unflag a user
* @param {string} targetID
* @param {string} [options.user_id] currentUserID, only used with serverside auth
* @returns {Promise<APIResponse>}
*/
unflagUser(targetID: string, options?: {
user_id?: string;
}): Promise<FlagUserResponse>;
/**
* _queryFlags - Query flags.
*
* Note: Do not use this.
* It is present for internal usage only.
* This function can, and will, break and/or be removed at any point in time.
*
* @private
* @param {FlagsFilters} filterConditions MongoDB style filter conditions
* @param {FlagsPaginationOptions} options Option object, {limit: 10, offset:0}
*
* @return {Promise<FlagsResponse>} Flags Response
*/
_queryFlags(filterConditions?: FlagsFilters, options?: FlagsPaginationOptions): Promise<FlagsResponse>;
/**
* _queryFlagReports - Query flag reports.
*
* Note: Do not use this.
* It is present for internal usage only.
* This function can, and will, break and/or be removed at any point in time.
*
* @private
* @param {FlagReportsFilters} filterConditions MongoDB style filter conditions
* @param {FlagReportsPaginationOptions} options Option object, {limit: 10, offset:0}
*
* @return {Promise<FlagReportsResponse>} Flag Reports Response
*/
_queryFlagReports(filterConditions?: FlagReportsFilters, options?: FlagReportsPaginationOptions): Promise<FlagReportsResponse>;
/**
* _reviewFlagReport - review flag report
*
* Note: Do not use this.
* It is present for internal usage only.
* This function can, and will, break and/or be removed at any point in time.
*
* @private
* @param {string} [id] flag report to review
* @param {string} [reviewResult] flag report review result
* @param {string} [options.user_id] currentUserID, only used with serverside auth
* @param {string} [options.review_details] custom information about review result
* @returns {Promise<ReviewFlagReportResponse>>}
*/
_reviewFlagReport(id: string, reviewResult: string, options?: ReviewFlagReportOptions): Promise<ReviewFlagReportResponse>;
/**
* unblockMessage - unblocks message blocked by automod
*
*
* @param {string} targetMessageID
* @param {string} [options.user_id] currentUserID, only used with serverside auth
* @returns {Promise<APIResponse>}
*/
unblockMessage(targetMessageID: string, options?: {
user_id?: string;
}): Promise<APIResponse>;
_unblockMessage: (targetMessageID: string, options?: {
user_id?: string;
}) => Promise<APIResponse>;
/**
* @deprecated use markChannelsRead instead
*
* markAllRead - marks all channels for this user as read
* @param {MarkAllReadOptions} [data]
*
* @return {Promise<APIResponse>}
*/
markAllRead: (data?: MarkChannelsReadOptions) => Promise<void>;
/**
* markChannelsRead - marks channels read -
* it accepts a map of cid:messageid pairs, if messageid is empty, the whole channel will be marked as read
*
* @param {MarkChannelsReadOptions } [data]
*
* @return {Promise<APIResponse>}
*/
markChannelsRead(data?: MarkChannelsReadOptions): Promise<void>;
createCommand(data: CreateCommandOptions): Promise<CreateCommandResponse>;
getCommand(name: string): Promise<GetCommandResponse>;
updateCommand(name: string, data: UpdateCommandOptions): Promise<UpdateCommandResponse>;
deleteCommand(name: string): Promise<DeleteCommandResponse>;
listCommands(): Promise<ListCommandsResponse>;
createChannelType(data: CreateChannelOptions): Promise<CreateChannelResponse>;
getChannelType(channelType: string): Promise<GetChannelTypeResponse>;
updateChannelType(channelType: string, data: UpdateChannelTypeRequest): Promise<UpdateChannelTypeResponse>;
deleteChannelType(channelType: string): Promise<APIResponse>;
listChannelTypes(): Promise<ListChannelResponse>;
/**
* translateMessage - adds the translation to the message
*
* @param {string} messageId
* @param {string} language
*
* @return {MessageResponse} Response that includes the message
*/
translateMessage(messageId: string, language: string): Promise<APIResponse & import("./custom_types").CustomMessageData & {
id: string;
attachments?: import("./types").Attachment[];
html?: string;
mml?: string;
parent_id?: string;
pin_expires?: string | null;
pinned?: boolean;
pinned_at?: string | null;
poll_id?: string;
quoted_message_id?: string;
restricted_visibility?: string[];
show_in_channel?: boolean;
silent?: boolean;
text?: string;
type?: import("./types").MessageLabel;
user?: UserResponse | null;
user_id?: string;
} & {
type: import("./types").MessageLabel;
args?: string;
before_message_send_failed?: boolean;
channel?: ChannelResponse;
cid?: string;
command?: string;
command_info?: {
name?: string;
};
created_at?: string;
deleted_at?: string;
deleted_reply_count?: number;
i18n?: import("./types").RequireAtLeastOne<Record<`${import("./types").TranslationLanguages}_text`, string>> & {
language: import("./types").TranslationLanguages;
};
latest_reactions?: ReactionResponse[];
member?: import("./types").ChannelMemberResponse;
mentioned_users?: UserResponse[];
message_text_updated_at?: string;
moderation?: import("./types").ModerationResponse;
moderation_details?: import("./types").ModerationDetailsResponse;
own_reactions?: ReactionResponse[] | null;
pin_expires?: string | null;
pinned_at?: string | null;
pinned_by?: UserResponse | null;
poll?: import("./types").PollResponse;
reaction_counts?: {
[key: string]: number;
} | null;
reaction_groups?: {
[key: string]: import("./types").ReactionGroupResponse;
} | null;
reaction_scores?: {
[key: string]: number;
} | null;
reminder?: import("./types").ReminderResponseBase;
reply_count?: number;
shadowed?: boolean;
shared_location?: SharedLocationResponse;
status?: string;
thread_participants?: UserResponse[];
updated_at?: string;
deleted_for_me?: boolean;
} & {
quoted_message?: import("./types").MessageResponseBase;
}>;
/**
* translate - translates the given text to provided language
*
* @param {string} text
* @param {string} destination_language
* @param {string} source_language
*
* @return {TranslateResponse} Response that includes the message
*/
translate(text: string, destination_language: string, source_language: string): Promise<APIResponse & TranslateResponse>;
/**
* _normalizeExpiration - transforms expiration value into ISO string
* @param {undefined|null|number|string|Date} timeoutOrExpirationDate expiration date or timeout. Use number type to set timeout in seconds, string or Date to set exact expiration date
*/
_normalizeExpiration(timeoutOrExpirationDate?: null | number | string | Date): string