export as namespace AV;
interface IteratorResult {
done: boolean;
value: T;
}
interface AsyncIterator {
next(): Promise>;
}
declare class EventEmitter {
on(evt: string, listener: Function): EventEmitter;
once(evt: string, listener: Function): EventEmitter;
off(evt: string, listener: Function): EventEmitter;
emit(evt: string, ...args: any[]): Boolean;
}
export var applicationId: string;
export var applicationKey: string;
export var masterKey: string;
interface FetchOptions {
keys?: string | string[];
include?: string | string[];
includeACL?: boolean;
}
export interface AuthOptions {
/**
* In Cloud Code and Node only, causes the Master Key to be used for this request.
*/
useMasterKey?: boolean;
sessionToken?: string;
user?: User;
}
interface SMSAuthOptions extends AuthOptions {
validateToken?: string;
}
interface CaptchaOptions {
size?: number;
width?: number;
height?: number;
ttl?: number;
}
interface FileSaveOptions extends AuthOptions {
onprogress?: (
event: {
loaded: number;
total: number;
percent: number;
}
) => void;
}
export interface WaitOption {
/**
* Set to true to wait for the server to confirm success
* before triggering an event.
*/
wait?: boolean;
}
export interface SilentOption {
/**
* Set to true to avoid firing the event.
*/
silent?: boolean;
}
export interface IBaseObject {
toJSON(): any;
}
export class BaseObject implements IBaseObject {
toJSON(): any;
}
/**
* Creates a new ACL.
* If no argument is given, the ACL has no permissions for anyone.
* If the argument is a AV.User, the ACL will have read and write
* permission for only that user.
* If the argument is any other JSON object, that object will be interpretted
* as a serialized ACL created with toJSON().
* @see AV.Object#setACL
* @class
*
* An ACL, or Access Control List can be added to any
* AV.Object
to restrict access to only a subset of users
* of your application.
*/
export class ACL extends BaseObject {
constructor(arg1?: any);
setPublicReadAccess(allowed: boolean): void;
getPublicReadAccess(): boolean;
setPublicWriteAccess(allowed: boolean): void;
getPublicWriteAccess(): boolean;
setReadAccess(userId: User, allowed: boolean): void;
getReadAccess(userId: User): boolean;
setReadAccess(userId: string, allowed: boolean): void;
getReadAccess(userId: string): boolean;
setRoleReadAccess(role: Role, allowed: boolean): void;
setRoleReadAccess(role: string, allowed: boolean): void;
getRoleReadAccess(role: Role): boolean;
getRoleReadAccess(role: string): boolean;
setRoleWriteAccess(role: Role, allowed: boolean): void;
setRoleWriteAccess(role: string, allowed: boolean): void;
getRoleWriteAccess(role: Role): boolean;
getRoleWriteAccess(role: string): boolean;
setWriteAccess(userId: User, allowed: boolean): void;
setWriteAccess(userId: string, allowed: boolean): void;
getWriteAccess(userId: User): boolean;
getWriteAccess(userId: string): boolean;
}
/**
* A AV.File is a local representation of a file that is saved to the AV
* cloud.
* @class
* @param name {String} The file's name. This will be prefixed by a unique
* value once the file has finished saving. The file name must begin with
* an alphanumeric character, and consist of alphanumeric characters,
* periods, spaces, underscores, or dashes.
* @param data {Array} The data for the file, as either:
* 1. an Array of byte value Numbers, or
* 2. an Object like { base64: "..." } with a base64-encoded String.
* 3. a File object selected with a file upload control. (3) only works
* in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
* For example:
* var fileUploadControl = $("#profilePhotoFileUpload")[0];
* if (fileUploadControl.files.length > 0) {
* var file = fileUploadControl.files[0];
* var name = "photo.jpg";
* var AVFile = new AV.File(name, file);
* AVFile.save().then(function() {
* // The file has been saved to AV.
* }, function(error) {
* // The file either could not be read, or could not be saved to AV.
* });
* }
* @param type {String} Optional Content-Type header to use for the file. If
* this is omitted, the content type will be inferred from the name's
* extension.
*/
export class File extends BaseObject {
constructor(name: string, data: any, type?: string);
static withURL(name: string, url: string): File;
static createWithoutData(objectId: string): File;
destroy(): Promise;
fetch(fetchOptions?: FetchOptions, options?: AuthOptions): Promise;
metaData(): any;
metaData(metaKey: string): any;
metaData(metaKey: string, metaValue: any): any;
name(): string;
ownerId(): string;
url(): string;
save(options?: FileSaveOptions): Promise;
setACL(acl?: ACL): any;
setUploadHeader(key: string, value: string): File;
size(): any;
thumbnailURL(width: number, height: number): string;
toFullJSON(): any;
}
/**
* Creates a new GeoPoint with any of the following forms:
*
* new GeoPoint(otherGeoPoint)
* new GeoPoint(30, 30)
* new GeoPoint([30, 30])
* new GeoPoint({latitude: 30, longitude: 30})
* new GeoPoint() // defaults to (0, 0)
*
* @class
*
* Represents a latitude / longitude point that may be associated
* with a key in a AVObject or used as a reference point for geo queries.
* This allows proximity-based queries on the key.
*
* Only one key in a class may contain a GeoPoint.
*
* Example:
* var point = new AV.GeoPoint(30.0, -20.0);
* var object = new AV.Object("PlaceObject");
* object.set("location", point);
* object.save();
*/
export class GeoPoint extends BaseObject {
latitude: number;
longitude: number;
constructor(arg1?: any, arg2?: any);
static current(options?: AuthOptions): Promise;
radiansTo(point: GeoPoint): number;
kilometersTo(point: GeoPoint): number;
milesTo(point: GeoPoint): number;
}
/**
* A class that is used to access all of the children of a many-to-many relationship.
* Each instance of AV.Relation is associated with a particular parent object and key.
*/
export class Relation extends BaseObject {
parent: Object;
key: string;
targetClassName: string;
constructor(parent?: Object, key?: string);
static reverseQuery(
parentClass: string,
relationKey: string,
child: Object
): Query;
//Adds a AV.Object or an array of AV.Objects to the relation.
add(object: Object): void;
// Returns a AV.Query that is limited to objects in this relation.
query(): Query;
// Removes a AV.Object or an array of AV.Objects from this relation.
remove(object: Object): void;
}
/**
* Creates a new model with defined attributes. A client id (cid) is
* automatically generated and assigned for you.
*
* You won't normally call this method directly. It is recommended that
* you use a subclass of AV.Object
instead, created by calling
* extend
.
*
* However, if you don't want to use a subclass, or aren't sure which
* subclass is appropriate, you can use this form:
* var object = new AV.Object("ClassName");
*
* That is basically equivalent to:
* var MyClass = AV.Object.extend("ClassName");
* var object = new MyClass();
*
*
* @param {Object} attributes The initial set of data to store in the object.
* @param {Object} options A set of Backbone-like options for creating the
* object. The only option currently supported is "collection".
* @see AV.Object.extend
*
* @class
*
* The fundamental unit of AV data, which implements the Backbone Model
* interface.
*/
export class Object extends BaseObject {
id: any;
createdAt: any;
updatedAt: any;
attributes: any;
changed: boolean;
className: string;
query: Query;
constructor(className?: string, options?: any);
constructor(attributes?: string[], options?: any);
static createWithoutData(className: string, objectId: string): Object;
static extend(className: string, protoProps?: any, classProps?: any): any;
static fetchAll(list: Object[], options?: AuthOptions): Promise;
static destroyAll(
list: Object[],
options?: Object.DestroyAllOptions
): Promise;
static saveAll(
list: Object[],
options?: Object.SaveAllOptions
): Promise;
static register(klass: Function, name?: string): void;
initialize(): void;
add(attributeName: string, item: any): this;
addUnique(attributeName: string, item: any): any;
bitAnd(attributeName: string, item: number): this;
bitOr(attributeName: string, item: number): this;
bitXor(attributeName: string, item: number): this;
change(options: any): Object;
changedAttributes(diff: any): boolean;
clear(options: any): any;
clone(): Object;
destroy(options?: Object.DestroyOptions): Promise;
dirty(attr: String): boolean;
escape(attr: string): string;
fetch(fetchOptions?: FetchOptions, options?: AuthOptions): Promise;
fetchWhenSave(enable: boolean): void;
get(attr: string): any;
getACL(): ACL;
has(attr: string): boolean;
hasChanged(attr: string): boolean;
increment(attr: string, amount?: number): this;
isValid(): boolean;
op(attr: string): any;
previous(attr: string): any;
previousAttributes(): any;
relation(attr: string): Relation;
remove(attr: string, item: any): this;
save(attrs?: object | null, options?: Object.SaveOptions): Promise;
save(key: string, value: any, options?: Object.SaveOptions): Promise;
set(key: string, value: any, options?: Object.SetOptions): this;
setACL(acl: ACL, options?: Object.SetOptions): this;
unset(attr: string, options?: Object.SetOptions): this;
validate(attrs: any): any;
toFullJSON(): any;
}
export namespace Object {
interface DestroyOptions extends AuthOptions, WaitOption {}
interface DestroyAllOptions extends AuthOptions {}
interface SaveOptions extends AuthOptions, SilentOption, WaitOption {
fetchWhenSave?: boolean;
where?: Query;
}
interface SaveAllOptions extends AuthOptions {}
interface SetOptions extends SilentOption {}
}
/**
* Every AV application installed on a device registered for
* push notifications has an associated Installation object.
*/
export class Installation extends Object {
badge: any;
channels: string[];
timeZone: any;
deviceType: string;
pushType: string;
installationId: string;
deviceToken: string;
channelUris: string;
appName: string;
appVersion: string;
AVVersion: string;
appIdentifier: string;
}
/**
* @class
*
* AV.Events is a fork of Backbone's Events module, provided for your
* convenience.
*
* A module that can be mixed in to any object in order to provide
* it with custom events. You may bind callback functions to an event
* with `on`, or remove these functions with `off`.
* Triggering an event fires all callbacks in the order that `on` was
* called.
*
*
* var object = {};
* _.extend(object, AV.Events);
* object.on('expand', function(){ alert('expanded'); });
* object.trigger('expand');
*
* For more information, see the
* Backbone
* documentation .
*/
export class Events {
static off(events: string[], callback?: Function, context?: any): Events;
static on(events: string[], callback?: Function, context?: any): Events;
static trigger(events: string[]): Events;
static bind(): Events;
static unbind(): Events;
on(eventName: string, callback?: Function, context?: any): Events;
off(eventName?: string, callback?: Function, context?: any): Events;
trigger(eventName: string, ...args: any[]): Events;
bind(eventName: string, callback: Function, context?: any): Events;
unbind(eventName?: string, callback?: Function, context?: any): Events;
}
declare class BaseQuery extends BaseObject {
className: string;
constructor(objectClass: string);
constructor(objectClass: Object);
addAscending(key: string): this;
addAscending(key: string[]): this;
addDescending(key: string): this;
addDescending(key: string[]): this;
ascending(key: string): this;
ascending(key: string[]): this;
include(...keys: string[]): this;
include(keys: string[]): this;
limit(n: number): this;
skip(n: number): this;
find(options?: AuthOptions): Promise;
}
/**
* Creates a new AV AV.Query for the given AV.Object subclass.
* @param objectClass -
* An instance of a subclass of AV.Object, or a AV className string.
* @class
*
* AV.Query defines a query that is used to fetch AV.Objects. The
* most common use case is finding all objects that match a query through the
* find
method. For example, this sample code fetches all objects
* of class MyClass
. It calls a different function depending on
* whether the fetch succeeded or not.
*
*
* var query = new AV.Query(MyClass);
* query.find({
* success: function(results) {
* // results is an array of AV.Object.
* },
*
* error: function(error) {
* // error is an instance of AV.Error.
* }
* });
*
* A AV.Query can also be used to retrieve a single object whose id is
* known, through the get method. For example, this sample code fetches an
* object of class MyClass
and id myId
. It calls a
* different function depending on whether the fetch succeeded or not.
*
*
* var query = new AV.Query(MyClass);
* query.get(myId, {
* success: function(object) {
* // object is an instance of AV.Object.
* },
*
* error: function(object, error) {
* // error is an instance of AV.Error.
* }
* });
*
* A AV.Query can also be used to count the number of objects that match
* the query without retrieving all of those objects. For example, this
* sample code counts the number of objects of the class MyClass
*
* var query = new AV.Query(MyClass);
* query.count({
* success: function(number) {
* // There are number instances of MyClass.
* },
*
* error: function(error) {
* // error is an instance of AV.Error.
* }
* });
*/
export class Query extends BaseQuery {
static or(...querys: Query[]): Query;
static and(...querys: Query[]): Query;
static doCloudQuery(
cql: string,
pvalues?: any,
options?: AuthOptions
): Promise;
containedIn(key: string, values: any[]): Query;
contains(key: string, substring: string): Query;
containsAll(key: string, values: any[]): Query;
count(options?: AuthOptions): Promise;
descending(key: string): Query;
descending(key: string[]): Query;
doesNotExist(key: string): Query;
doesNotMatchKeyInQuery(key: string, queryKey: string, query: Query): Query;
doesNotMatchQuery(key: string, query: Query): Query;
each(callback: Function, options?: AuthOptions): Promise;
endsWith(key: string, suffix: string): Query;
equalTo(key: string, value: any): Query;
exists(key: string): Query;
first(options?: AuthOptions): Promise;
get(objectId: string, options?: AuthOptions): Promise;
greaterThan(key: string, value: any): Query;
greaterThanOrEqualTo(key: string, value: any): Query;
includeACL(value?: boolean): Query;
lessThan(key: string, value: any): Query;
lessThanOrEqualTo(key: string, value: any): Query;
matches(key: string, regex: RegExp, modifiers?: any): Query;
matchesKeyInQuery(key: string, queryKey: string, query: Query): Query;
matchesQuery(key: string, query: Query): Query;
near(key: string, point: GeoPoint): Query;
notContainedIn(key: string, values: any[]): Query;
notEqualTo(key: string, value: any): Query;
select(...keys: string[]): Query;
select(keys: string[]): Query;
startsWith(key: string, prefix: string): Query;
withinGeoBox(key: string, southwest: GeoPoint, northeast: GeoPoint): Query;
withinKilometers(key: string, point: GeoPoint, maxDistance: number): Query;
withinMiles(key: string, point: GeoPoint, maxDistance: number): Query;
withinRadians(key: string, point: GeoPoint, maxDistance: number): Query;
scan(
options?: { orderedBy?: string; batchSize?: number },
authOptions?: AuthOptions
): AsyncIterator;
subscribe(options?: { subscriptionId?: string }): Promise;
}
declare class LiveQuery extends EventEmitter {
unsubscribe(): Promise;
}
declare class FriendShipQuery extends Query {}
export class SearchQuery extends BaseQuery {
sid(sid: string): this;
queryString(q: string): this;
highlights(highlights: string[]): this;
highlights(highlight: string): this;
sortBy(builder: SearchSortBuilder): this;
hits(): number;
hasMore(): boolean;
reset(): void;
}
export class SearchSortBuilder {
constructor();
ascending(key: string, mode?: string, missingKeyBehaviour?: string): this;
descending(key: string, mode?: string, missingKeyBehaviour?: string): this;
whereNear(
key: string,
point?: GeoPoint,
options?: { order?: string; mode?: string; unit?: string }
): this;
build(): string;
}
/**
* Represents a Role on the AV server. Roles represent groupings of
* Users for the purposes of granting permissions (e.g. specifying an ACL
* for an Object). Roles are specified by their sets of child users and
* child roles, all of which are granted any permissions that the parent
* role has.
*
* Roles must have a name (which cannot be changed after creation of the
* role), and must specify an ACL.
* @class
* A AV.Role is a local representation of a role persisted to the AV
* cloud.
*/
export class Role extends Object {
constructor(name: string, acl: ACL);
getRoles(): Relation;
getUsers(): Relation;
getName(): string;
setName(name: string): Role;
}
interface OAuthLoginOptions {
failOnNotExist?: boolean;
}
interface UnionOptions {
unionIdPlatform?: string;
asMainAccount?: boolean;
}
interface UnionLoginOptions extends OAuthLoginOptions, UnionOptions {}
/**
* @class
*
* A AV.User object is a local representation of a user persisted to the
* AV cloud. This class is a subclass of a AV.Object, and retains the
* same functionality of a AV.Object, but also extends it with various
* user specific methods, like authentication, signing up, and validation of
* uniqueness.
*/
export class User extends Object {
static current(): User;
static currentAsync(): Promise;
static signUp(
username: string,
password: string,
attrs?: any,
options?: AuthOptions
): Promise;
static logIn(username: string, password: string): Promise;
static logOut(): Promise;
static become(sessionToken: string): Promise;
static loginWithWeapp(options?: OAuthLoginOptions): Promise;
static logInWithMobilePhone(
mobilePhone: string,
password: string
): Promise;
static logInWithMobilePhoneSmsCode(
mobilePhone: string,
smsCode: string
): Promise;
static loginWithAuthData(
authData: Object,
platform: string,
options?: OAuthLoginOptions
): Promise;
static signUpOrlogInWithAuthData(
authData: Object,
platform: string,
options?: OAuthLoginOptions
): Promise;
static loginWithAuthDataAndUnionId(
authData: Object,
platform: string,
unionId: string,
unionLoginOptions?: UnionLoginOptions
): Promise;
static signUpOrlogInWithAuthDataAndUnionId(
authData: Object,
platform: string,
unionId: string,
unionLoginOptions?: UnionLoginOptions
): Promise;
static signUpOrlogInWithMobilePhone(
mobilePhoneNumber: string,
smsCode: string,
attributes?: any,
options?: AuthOptions
): Promise;
static requestEmailVerify(
email: string,
options?: AuthOptions
): Promise;
static requestLoginSmsCode(
mobilePhoneNumber: string,
options?: SMSAuthOptions
): Promise;
static requestMobilePhoneVerify(
mobilePhoneNumber: string,
options?: SMSAuthOptions
): Promise;
static requestPasswordReset(
email: string,
options?: AuthOptions
): Promise;
static requestPasswordResetBySmsCode(
mobilePhoneNumber: string,
options?: SMSAuthOptions
): Promise;
static resetPasswordBySmsCode(
code: string,
password: string,
options?: AuthOptions
): Promise;
static verifyMobilePhone(code: string, options?: AuthOptions): Promise;
static followerQuery(userObjectId: string): FriendShipQuery;
static followeeQuery(userObjectId: string): FriendShipQuery;
loginWithWeapp(options?: OAuthLoginOptions): Promise;
loginWithAuthData(
authData: Object,
platform: string,
options?: OAuthLoginOptions
): Promise;
loginWithAuthDataAndUnionId(
authData: Object,
platform: string,
unionId: string,
unionLoginOptions?: UnionLoginOptions
): Promise;
signUp(attrs?: any, options?: AuthOptions): Promise;
logIn(): Promise;
linkWithWeapp(): Promise;
isAuthenticated(): Promise;
isCurrent(): boolean;
associateWithAuthData(authData: Object, platform: string): Promise;
associateWithAuthDataAndUnionId(
authData: Object,
platform: string,
unionId: string,
unionLoginOptions?: UnionOptions
): Promise;
dissociateAuthData(platform: string): Promise;
getEmail(): string;
setEmail(email: string): boolean;
setMobilePhoneNumber(mobilePhoneNumber: string): boolean;
getMobilePhoneNumber(): string;
getUsername(): string;
setUsername(username: string): boolean;
setPassword(password: string): boolean;
getSessionToken(): string;
refreshSessionToken(options?: AuthOptions): Promise;
getRoles(options?: AuthOptions): Promise;
follow(user: User | string, authOptions?: AuthOptions): Promise;
follow(
options: { user: User | string; attributes?: Object },
authOptions?: AuthOptions
): Promise;
unfollow(user: User | string, authOptions?: AuthOptions): Promise;
unfollow(
options: { user: User | string },
authOptions?: AuthOptions
): Promise;
followerQuery(): FriendShipQuery;
followeeQuery(): FriendShipQuery;
}
export class Captcha {
url: string;
captchaToken: string;
validateToken: string;
static request(
options?: CaptchaOptions,
authOptions?: AuthOptions
): Promise;
refresh(): Promise;
verify(code: string): Promise;
bind(
elements?: {
textInput?: string | HTMLInputElement;
image?: string | HTMLImageElement;
verifyButton?: string | HTMLElement;
},
callbacks?: {
success?: (validateToken: string) => any;
error?: (error: Error) => any;
}
): void;
unbind(): void;
}
/**
* @class AV.Conversation
* An AV.Conversation is a local representation of a LeanCloud realtime's
* conversation. This class is a subclass of AV.Object, and retains the
* same functionality of an AV.Object, but also extends it with various
* conversation specific methods, like get members, creators of this conversation.
*
*
* @param {String} name The name of the Role to create.
* @param {Boolean} [options.isSystem] Set this conversation as system conversation.
* @param {Boolean} [options.isTransient] Set this conversation as transient conversation.
*/
export class Conversation extends Object {
constructor(
name: string,
options?: { isSytem?: boolean; isTransient?: boolean }
);
getCreator(): string;
getLastMessageAt(): Date;
getMembers(): string[];
addMember(member: string): Conversation;
getMutedMembers(): string[];
getName(): string;
isTransient(): boolean;
isSystem(): boolean;
send(
fromClient: string,
message: string | object,
options?: { transient?: boolean; pushData?: object; toClients?: string[] },
authOptions?: AuthOptions
): Promise;
broadcast(
fromClient: string,
message: string | object,
options?: { pushData?: object; validTill?: number | Date },
authOptions?: AuthOptions
): Promise;
}
declare class Statistic {
name: string;
value: number;
version?: number;
}
declare interface Ranking {
value: number;
user: AV.User;
rank: number;
includedStatistics?: Statistic[];
}
export class Leaderboard {
statisticName: string;
order?: LeaderboardOrder;
updateStrategy?: LeaderboardUpdateStrategy;
versionChangeInterval?: LeaderboardVersionChangeInterval;
version?: number;
nextResetAt?: Date;
createdAt?: Date;
static createWithoutData(statisticName: string): Leaderboard;
static createLeaderboard(
options: {
statisticName: string;
order: LeaderboardOrder;
versionChangeInterval?: LeaderboardVersionChangeInterval;
updateStrategy?: LeaderboardUpdateStrategy;
},
authOptions?: AuthOptions
): Promise;
static getLeaderboard(
statisticName: string,
authOptions?: AuthOptions
): Promise;
static getStatistics(
user: User,
options?: { statisticNames?: string[] }
): Promise;
static updateStatistics(
user: User,
statistics: { [name: string]: number },
authOptions?: AuthOptions
): Promise;
fetch(authOptions?: AuthOptions): Promise;
getResults(
options?: {
skip?: number;
limit?: number;
selectUserKeys?: string | string[];
includeStatistics?: string | string[];
},
authOptions?: AuthOptions
): Promise;
getResultsAroundUser(
options?: {
limit?: number;
selectUserKeys?: string | string[];
includeStatistics?: string | string[];
},
authOptions?: AuthOptions
): Promise;
updateVersionChangeInterval(
versionChangeInterval: LeaderboardVersionChangeInterval,
authOptions?: AuthOptions
): Promise;
updateUpdateStrategy(
updateStrategy: LeaderboardUpdateStrategy,
authOptions?: AuthOptions
): Promise;
reset(authOptions?: AuthOptions): Promise;
destroy(authOptions?: AuthOptions): Promise;
}
export enum LeaderboardOrder {
ASCENDING,
DESCENDING,
}
export enum LeaderboardUpdateStrategy {
BETTER,
LAST,
}
export enum LeaderboardVersionChangeInterval {
NEVER,
HOUR,
DAY,
WEEK,
MONTH,
}
export class Error {
code: ErrorCode;
message: string;
constructor(code: ErrorCode, message: string);
}
export enum ErrorCode {
OTHER_CAUSE = -1,
INTERNAL_SERVER_ERROR = 1,
CONNECTION_FAILED = 100,
OBJECT_NOT_FOUND = 101,
INVALID_QUERY = 102,
INVALID_CLASS_NAME = 103,
MISSING_OBJECT_ID = 104,
INVALID_KEY_NAME = 105,
INVALID_POINTER = 106,
INVALID_JSON = 107,
COMMAND_UNAVAILABLE = 108,
NOT_INITIALIZED = 109,
INCORRECT_TYPE = 111,
INVALID_CHANNEL_NAME = 112,
PUSH_MISCONFIGURED = 115,
OBJECT_TOO_LARGE = 116,
OPERATION_FORBIDDEN = 119,
CACHE_MISS = 120,
INVALID_NESTED_KEY = 121,
INVALID_FILE_NAME = 122,
INVALID_ACL = 123,
TIMEOUT = 124,
INVALID_EMAIL_ADDRESS = 125,
MISSING_CONTENT_TYPE = 126,
MISSING_CONTENT_LENGTH = 127,
INVALID_CONTENT_LENGTH = 128,
FILE_TOO_LARGE = 129,
FILE_SAVE_ERROR = 130,
DUPLICATE_VALUE = 137,
INVALID_ROLE_NAME = 139,
EXCEEDED_QUOTA = 140,
SCRIPT_FAILED = 141,
VALIDATION_ERROR = 142,
INVALID_IMAGE_DATA = 150,
UNSAVED_FILE_ERROR = 151,
INVALID_PUSH_TIME_ERROR = 152,
FILE_DELETE_ERROR = 153,
REQUEST_LIMIT_EXCEEDED = 155,
INVALID_EVENT_NAME = 160,
USERNAME_MISSING = 200,
PASSWORD_MISSING = 201,
USERNAME_TAKEN = 202,
EMAIL_TAKEN = 203,
EMAIL_MISSING = 204,
EMAIL_NOT_FOUND = 205,
SESSION_MISSING = 206,
MUST_CREATE_USER_THROUGH_SIGNUP = 207,
ACCOUNT_ALREADY_LINKED = 208,
INVALID_SESSION_TOKEN = 209,
LINKED_ID_MISSING = 250,
INVALID_LINKED_SESSION = 251,
UNSUPPORTED_SERVICE = 252,
AGGREGATE_ERROR = 600,
FILE_READ_ERROR = 601,
X_DOMAIN_REQUEST = 602,
}
/**
* @class
* A AV.Op is an atomic operation that can be applied to a field in a
* AV.Object. For example, calling object.set("foo", "bar")
* is an example of a AV.Op.Set. Calling object.unset("foo")
* is a AV.Op.Unset. These operations are stored in a AV.Object and
* sent to the server as part of object.save()
operations.
* Instances of AV.Op should be immutable.
*
* You should not create subclasses of AV.Op or instantiate AV.Op
* directly.
*/
export namespace Op {
interface BaseOperation extends IBaseObject {
objects(): any[];
}
interface Add extends BaseOperation {}
interface AddUnique extends BaseOperation {}
interface Increment extends IBaseObject {
amount: number;
}
interface Relation extends IBaseObject {
added(): Object[];
removed: Object[];
}
interface Set extends IBaseObject {
value(): any;
}
interface Unset extends IBaseObject {}
}
/**
* Contains functions to deal with Push in AV
* @name AV.Push
* @namespace
*/
export namespace Push {
function send(data: PushData, options?: AuthOptions): Promise;
interface PushData {
channels?: string[];
push_time?: Date;
expiration_time?: Date;
expiration_interval?: number;
where?: Query;
cql?: string;
data?: any;
alert?: string;
badge?: string;
sound?: string;
title?: string;
}
}
export namespace Cloud {
function run(name: string, data?: any, options?: AuthOptions): Promise;
function requestSmsCode(
data:
| string
| { mobilePhoneNumber: string; template?: string; sign?: string },
options?: SMSAuthOptions
): Promise;
function verifySmsCode(code: string, phone: string): Promise;
function requestCaptcha(
options?: CaptchaOptions,
authOptions?: AuthOptions
): Promise;
function verifyCaptcha(code: string, captchaToken: string): Promise;
}
interface ServerURLs {
api?: string;
engine?: string;
stats?: string;
push?: string;
}
export function init(options: {
appId: string;
appKey: string;
masterKey?: string;
region?: string;
production?: boolean;
serverURLs?: string | ServerURLs;
disableCurrentUser?: boolean;
}): void;
export function setServerURLs(urls: string | ServerURLs): void;
export function setProduction(production: boolean): void;
export function setRequestTimeout(ms: number): void;
export function parseJSON(json: any): Object | File | any;
export function request(options: {
method: string;
path: string;
query?: object;
data?: object;
authOptions?: AuthOptions;
service?: string;
version?: string;
}): Promise;
interface AVUser {
getSessionToken(): string;
}
interface SignatureResult {
signature: string;
timestamp: number;
nonce: string;
}
type SignatureFactoryResult = Promise | SignatureResult;
export class Realtime extends EventEmitter {
constructor(options: {
appId: string;
appKey: string;
region?: string;
pushOfflineMessages?: boolean;
noBinary?: boolean;
ssl?: boolean;
server?: string | { RTMRouter: string; api: string };
RTMServers?: string | string[];
plugins?: Array;
});
createIMClient(
client: string | AVUser,
options?: {
signatureFactory?: (clientId: string) => SignatureFactoryResult;
conversationSignatureFactory?: (
clientId: string,
conversationId: string,
targetIds: string[],
action: string
) => SignatureFactoryResult;
blacklistSignatureFactory?: (
clientId: string,
conversationId: string,
targetIds: string[],
action: string
) => SignatureFactoryResult;
tag?: string;
isReconnect?: boolean;
},
tag?: string
): Promise;
static defineConversationProperty(prop: string, descriptor?: Object);
register(messageClass: AVMessage[]);
retry();
}
class IMClient extends EventEmitter {
id: string;
close(): Promise;
createConversation(options: {
members?: string[];
name?: string;
transient?: boolean;
unique?: boolean;
[key: string]: any;
}): Promise;
createChatRoom(options: {
name?: string;
[key: string]: any;
}): Promise;
createTemporaryConversation(options: {
members?: string[];
ttl?: number;
}): Promise;
getConversation(id: string, noCache?: boolean): Promise;
getQuery(): ConversationQuery;
getServiceConversationQuery(): ConversationQuery;
getChatRoomQuery(): ConversationQuery;
markAllAsRead(
conversations: ConversationBase[]
): Promise>;
ping(clientIds: string[]): Promise>;
parseMessage(json: Object): Promise;
parseConversation(json: Object): Promise;
}
class ConversationQuery {
addAscending(key: string): this;
addDescending(key: string): this;
ascending(key: string): this;
compact(enabled?: boolean): this;
containedIn(key: string, values: any): this;
contains(key: string, subString: string): this;
containsAll(key: string, values: any): this;
containsMembers(peerIds: string[]): this;
descending(key: string): this;
doesNotExist(key: string): this;
endsWith(key: string, suffix: string): this;
equalTo(key: string, value: any): this;
exists(key: string): this;
find(): Promise;
greaterThan(key: string, value: any): this;
greaterThanOrEqualTo(key: string, value: any): this;
lessThan(key: string, value: any): this;
lessThanOrEqualTo(key: string, value: any): this;
limit(limit: number): this;
matches(key: string, regex: string): this;
notContainsIn(key: string, values: any): this;
notEqualTo(key: string, value: any): this;
sizeEqualTo(key: string, length: number): this;
skip(skip: number): this;
startsWith(key: string, prefix: string): this;
withLastMessagesRefreshed(enabled?: boolean): this;
withMembers(peerIds: string[], includeSelf: boolean): this;
}
/**
* 对话
*/
class ConversationBase extends EventEmitter {
id: string;
lastMessage?: Message;
lastMessageAt?: Date;
lastDeliveredAt?: Date;
lastReadAt?: Date;
unreadMessagesCount: Number;
members: string[];
readonly unreadMessagesMentioned: Boolean;
[key: string]: any;
// constructor();
createMessagesIterator(option: {
limit?: number;
beforeTime?: Date;
beforeMessageId?: string;
});
read(): Promise;
fetchReceiptTimestamps(): Promise;
queryMessages(options: {
beforeTime?: Date;
beforeMessageId?: string;
afterTime?: Date;
afterMessageId?: string;
limit?: number;
type: number;
}): Promise>;
queryMessages(options: {
startTime?: Date;
startMessageId?: string;
startClosed?: boolean;
endTime?: Date;
endMessageId?: string;
endClosed?: boolean;
limit?: number;
type: number;
direction?: MessageQueryDirection;
}): Promise>;
send(
message: T,
options?: {
pushData?: Object;
priority?: MessagePriority;
receipt?: boolean;
transient?: boolean;
will?: boolean;
}
): Promise;
update(message: MessagePointer, newMessage: T): Promise;
recall(message: MessagePointer): Promise;
count(): Promise;
toJSON(): Object;
toFullJSON(): Object;
}
interface OperationFailureError extends Error {
clientIds: string[];
code?: number;
detail?: string;
}
interface PartiallySuccess {
successfulClientIds: string[];
failures: OperationFailureError[];
}
interface PagedQueryParams {
limit?: number;
next?: string;
}
interface PagedResults {
results: T[];
next: string;
}
class PresistentConversation extends ConversationBase {
name: string;
creator: string;
createdAt: Date;
updatedAt: Date;
muted: boolean;
mutedMembers?: string[];
system: boolean;
transient: boolean;
get(key: string): any;
set(key: string, value: any): this;
save(): Promise;
fetch(): Promise;
mute(): Promise;
unmute(): Promise;
add(members: string[]): Promise;
join(): Promise;
quit(): Promise;
remove(clientIds: string[]): Promise;
muteMembers(clientIds: string[]): Promise;
unmuteMembers(clientIds: string[]): Promise;
queryMutedMembers(options?: PagedQueryParams): Promise>;
blockMembers(clientIds: string[]): Promise;
unblockMembers(clientIds: string[]): Promise;
queryBlockedMembers(
options?: PagedQueryParams
): Promise>;
getAllMemberInfo(): Promise;
getMemberInfo(memberId: string): Promise;
updateMemberRole(
memberId: string,
role: ConversationMemberRole
): Promise;
}
export class Conversation extends PresistentConversation {}
export class ChatRoom extends PresistentConversation {}
export class ServiceConversation extends PresistentConversation {
subscribe(): Promise;
unsubscribe(): Promise;
}
export class TemporaryConversation extends ConversationBase {
expiredAt: Date;
expired: Boolean;
}
export enum ConversationMemberRole {
MANAGER,
MEMBER,
}
class ConversationMemberInfo {
readonly conversationId: string;
readonly memberId: string;
readonly role: ConversationMemberRole;
readonly isOwner: boolean;
toJSON(): Object;
}
type MessagePointer = Message | { id: string; timestamp: Date | number };
type Payload = Object | String | ArrayBuffer;
export interface AVMessage {
getPayload(): Payload;
}
export class Message implements AVMessage {
constructor(content: any);
cid: string;
deliveredAt?: Date;
updatedAt: Date;
from: string;
id: string;
status: MessageStatus;
timestamp: Date;
readonly mentioned: Boolean;
mentionList: string[];
mentionedAll: Boolean;
static parse(json: Object, message: Message): Message;
static validate(): boolean;
getPayload(): Payload;
toJSON(): Object;
toFullJSON(): Object;
setMentionList(mentionList: string[]): this;
getMentionList(): string[];
mentionAll(): this;
}
// 二进制消息
export class BinaryMessage extends Message {
constructor(buffer: ArrayBuffer);
buffer: ArrayBuffer;
}
// 富媒体消息
export class TypedMessage extends Message {
static TYPE: number;
attributes: Object;
text: string;
readonly summary: string;
type: number;
getAttributes(): Object;
getText(): string;
setAttributes(attributes: Object): this;
}
// 内置文本消息类
export class TextMessage extends TypedMessage {
constructor(text?: string);
}
export class RecalledMessage extends TypedMessage {}
class EventEmitter {
on(evt: string, listener: Function): this;
once(evt: string, listener: Function): this;
off(evt: string, listener: Function): this;
emit(evt: string, ...args: any[]): boolean;
}
interface Middleware {
(target: T): T;
}
interface Decorator {
(target: T): void;
}
export interface Plugin {
name?: string;
beforeMessageParse?: Middleware;
afterMessageParse?: Middleware;
beforeMessageDispatch?: (message: AVMessage) => boolean;
messageClasses?: AVMessage[];
onConversationCreate?: Decorator;
onIMClientCreate?: Decorator;
onRealtimeCreate?: Decorator;
}
export enum MessagePriority {
LOW,
NORMAL,
HIGH,
}
export enum MessageStatus {
NONE,
SENDING,
SENT,
DELIVERED,
FAILED,
}
export enum MessageQueryDirection {
NEW_TO_OLD,
OLD_TO_NEW,
}
export enum ErrorCode {
CLOSE_NORMAL,
CLOSE_ABNORMAL,
APP_NOT_AVAILABLE,
SIGNATURE_FAILED,
INVALID_LOGIN,
SESSION_REQUIRED,
READ_TIMEOUT,
LOGIN_TIMEOUT,
FRAME_TOO_LONG,
INVALID_ORIGIN,
SESSION_CONFLICT,
SESSION_TOKEN_EXPIRED,
APP_QUOTA_EXCEEDED,
MESSAGE_SENT_QUOTA_EXCEEDED,
INTERNAL_ERROR,
CONVERSATION_API_FAILED,
CONVERSATION_SIGNATURE_FAILED,
CONVERSATION_NOT_FOUND,
CONVERSATION_FULL,
CONVERSATION_REJECTED_BY_APP,
CONVERSATION_UPDATE_FAILED,
CONVERSATION_READ_ONLY,
CONVERSATION_NOT_ALLOWED,
CONVERSATION_UPDATE_REJECTED,
CONVERSATION_QUERY_FAILED,
CONVERSATION_LOG_FAILED,
CONVERSATION_LOG_REJECTED,
SYSTEM_CONVERSATION_REQUIRED,
NORMAL_CONVERSATION_REQUIRED,
CONVERSATION_BLACKLISTED,
TRANSIENT_CONVERSATION_REQUIRED,
CONVERSATION_MEMBERSHIP_REQUIRED,
CONVERSATION_API_QUOTA_EXCEEDED,
TEMPORARY_CONVERSATION_EXPIRED,
INVALID_MESSAGING_TARGET,
MESSAGE_REJECTED_BY_APP,
MESSAGE_OWNERSHIP_REQUIRED,
MESSAGE_NOT_FOUND,
MESSAGE_UPDATE_REJECTED_BY_APP,
MESSAGE_EDIT_DISABLED,
MESSAGE_RECALL_DISABLED,
}
export enum Event {
DISCONNECT,
RECONNECT,
RETRY,
SCHEDULE,
OFFLINE,
ONLINE,
RECONNECT_ERROR,
INVITED,
KICKED,
MEMBERS_JOINED,
MEMBERS_LEFT,
MEMBER_INFO_UPDATED,
BLOCKED,
UNBLOCKED,
MEMBERS_BLOCKED,
MEMBERS_UNBLOCKED,
MUTED,
UNMUTED,
MEMBERS_MUTED,
MEMBERS_UNMUTED,
MESSAGE,
UNREAD_MESSAGES_COUNT_UPDATE,
CLOSE,
CONFLICT,
UNHANDLED_MESSAGE,
CONVERSATION_INFO_UPDATED,
LAST_DELIVERED_AT_UPDATE,
LAST_READ_AT_UPDATE,
MESSAGE_RECALL,
MESSAGE_UPDATE,
INFO_UPDATED,
}
export function messageType(type: number): Function;
export function messageField(fields: string[]): Function;
export as namespace AV;