diff --git a/package.json b/package.json index b675bef87c..3a91edef48 100644 --- a/package.json +++ b/package.json @@ -135,6 +135,7 @@ "optionalDependencies": { "@node-rs/bcrypt": "1.1.0" }, + "types": "types/index.d.ts", "collective": { "type": "opencollective", "url": "https://opencollective.com/parse-server", diff --git a/types/README.md b/types/README.md new file mode 100644 index 0000000000..1bf2f5b2f6 --- /dev/null +++ b/types/README.md @@ -0,0 +1,3 @@ + +# Credits +These definitions were written by [ Ullisen Media Group](https://github.com/ullisenmedia), [David Poetzsch-Heffter](https://github.com/dpoetzsch), [Cedric Kemp](https://github.com/jaeggerr), [Flavio Negrão](https://github.com/flavionegrao), [Wes Grimes](https://github.com/wesleygrimes), [Otherwise SAS](https://github.com/owsas), [Andrew Goldis](https://github.com/agoldis), [Alexandre Hétu Rivard](https://github.com/AlexandreHetu), [Diamond Lewis](https://github.com/dplewis), [Jong Eun Lee](https://github.com/yomybaby), [Colin Ulin](https://github.com/pocketcolin), [Robert Helms](https://github.com/rdhelms), [Julien Quere](https://github.com/jlnquere), [Thibault MOCELLIN](https://github.com/tybi), [Raschid JF Rafaelly](https://github.com/RaschidJFR), [Jeff Gu Kang](https://github.com/jeffgukang), [Bui Tan Loc](https://github.com/buitanloc), [Linus Unnebäck](https://github.com/LinusU), [Jerome De Leon](https://github.com/JeromeDeLeon), [Kent Robin Haugen](https://github.com/kentrh), [Asen Lekov](https://github.com/L3K0V), and [Switt Kongdachalert](https://github.com/swittk). diff --git a/types/index.d.ts b/types/index.d.ts new file mode 100644 index 0000000000..1c6f7b3181 --- /dev/null +++ b/types/index.d.ts @@ -0,0 +1,1725 @@ +// Type definitions for parse 2.18 +// Project: https://parseplatform.org/ +// Definitions by: Ullisen Media Group +// David Poetzsch-Heffter +// Cedric Kemp +// Flavio Negrão +// Wes Grimes +// Otherwise SAS +// Andrew Goldis +// Alexandre Hétu Rivard +// Diamond Lewis +// Jong Eun Lee +// Colin Ulin +// Robert Helms +// Julien Quere +// Thibault MOCELLIN +// Raschid JF Rafaelly +// Jeff Gu Kang +// Bui Tan Loc +// Linus Unnebäck +// Jerome De Leon +// Kent Robin Haugen +// Asen Lekov +// Switt Kongdachalert +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Minimum TypeScript Version: 3.5 + +/// + +import { EventEmitter } from 'events'; + +declare 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, +} + +declare global { + namespace Parse { + let applicationId: string; + let javaScriptKey: string | undefined; + let liveQueryServerURL: string; + let masterKey: string | undefined; + let serverAuthToken: string | undefined; + let serverAuthType: string | undefined; + let serverURL: string; + let secret: string; + let idempotency: boolean; + let encryptedUser: boolean; + + interface BatchSizeOption { + batchSize?: number; + } + + interface CascadeSaveOption { + /** If `false`, nested objects will not be saved (default is `true`). */ + cascadeSave?: boolean; + } + + interface SuccessOption { + success?: Function; + } + + interface ErrorOption { + error?: Function; + } + + interface FullOptions { + success?: Function; + error?: Function; + useMasterKey?: boolean; + sessionToken?: string; + installationId?: string; + progress?: Function; + } + + interface RequestOptions { + useMasterKey?: boolean; + sessionToken?: string; + installationId?: string; + batchSize?: number; + include?: string | string[]; + progress?: Function; + } + + interface SuccessFailureOptions extends SuccessOption, ErrorOption {} + + interface SignUpOptions { + useMasterKey?: boolean; + installationId?: string; + } + + interface SessionTokenOption { + sessionToken?: string; + } + + interface WaitOption { + /** + * Set to true to wait for the server to confirm success + * before triggering an event. + */ + wait?: boolean; + } + + interface UseMasterKeyOption { + /** + * In Cloud Code and Node only, causes the Master Key to be used for this request. + */ + useMasterKey?: boolean; + } + + interface ScopeOptions extends SessionTokenOption, UseMasterKeyOption {} + + interface SilentOption { + /** + * Set to true to avoid firing the event. + */ + silent?: boolean; + } + + interface Pointer { + __type: string; + className: string; + objectId: string; + } + + interface AuthData { + [key: string]: any; + } + + /** + * Interface declaration for Authentication Providers + * https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html + */ + interface AuthProvider { + /** + * Called when _linkWith isn't passed authData. Handle your own authentication here. + */ + authenticate: () => void; + /** + * (Optional) Called when service is unlinked. Handle any cleanup here. + */ + deauthenticate?: () => void; + /** + * Unique identifier for this Auth Provider. + */ + getAuthType: () => string; + /** + * Called when auth data is syncronized. Can be used to determine if authData is still valid + */ + restoreAuthentication: () => boolean; + } + + interface BaseAttributes { + createdAt: Date; + objectId: string; + updatedAt: Date; + } + + interface CommonAttributes { + ACL: ACL; + } + + interface JSONBaseAttributes { + createdAt: string; + objectId: string; + updatedAt: string; + } + + /** + * Creates a new ACL. + * If no argument is given, the ACL has no permissions for anyone. + * If the argument is a Parse.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 Parse.Object#setACL + * + *

An ACL, or Access Control List can be added to any + * Parse.Object to restrict access to only a subset of users + * of your application.

+ */ + class ACL { + permissionsById: any; + + constructor(arg1?: any); + + setPublicReadAccess(allowed: boolean): void; + getPublicReadAccess(): boolean; + + setPublicWriteAccess(allowed: boolean): void; + getPublicWriteAccess(): boolean; + + setReadAccess(userId: User | string, allowed: boolean): void; + getReadAccess(userId: User | string): boolean; + + setWriteAccess(userId: User | string, allowed: boolean): void; + getWriteAccess(userId: User | string): boolean; + + setRoleReadAccess(role: Role | string, allowed: boolean): void; + getRoleReadAccess(role: Role | string): boolean; + + setRoleWriteAccess(role: Role | string, allowed: boolean): void; + getRoleWriteAccess(role: Role | string): boolean; + + toJSON(): any; + } + + /** + * A Parse.File is a local representation of a file that is saved to the Parse + * cloud. + * @param name 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 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 parseFile = new Parse.File(name, file);
+         *   parseFile.save().then(function() {
+         *     // The file has been saved to Parse.
+         *   }, function(error) {
+         *     // The file either could not be read, or could not be saved to Parse.
+         *   });
+         * }
+ * @param type Optional Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + */ + class File { + constructor( + name: string, + data: number[] | { base64: string } | { size: number; type: string } | { uri: string }, + type?: string, + ); + /** + * Return the data for the file, downloading it if not already present. + * Data is present if initialized with Byte Array, Base64 or Saved with Uri. + * Data is cleared if saved with File object selected with a file upload control + * + * @returns Promise that is resolved with base64 data + */ + getData(): Promise; + url(options?: { forceSecure?: boolean }): string; + metadata(): Record; + tags(): Record; + name(): string; + save(options?: FullOptions): Promise; + cancel(): void; + destroy(): Promise; + toJSON(): { __type: string; name: string; url: string }; + equals(other: File): boolean; + setMetadata(metadata: Record): void; + addMetadata(key: string, value: any): void; + setTags(tags: Record): void; + addTag(key: string, value: any): void; + readonly _url: string; + } + + /** + * 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)
+         *   
+ * + *

Represents a latitude / longitude point that may be associated + * with a key in a ParseObject 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 Parse.GeoPoint(30.0, -20.0);
+         *   var object = new Parse.Object("PlaceObject");
+         *   object.set("location", point);
+         *   object.save();

+ */ + class GeoPoint { + latitude: number; + longitude: number; + + constructor(latitude: number, longitude: number); + constructor(coords?: { latitude: number; longitude: number } | [number, number]); + + current(options?: SuccessFailureOptions): GeoPoint; + radiansTo(point: GeoPoint): number; + kilometersTo(point: GeoPoint): number; + milesTo(point: GeoPoint): number; + toJSON(): any; + } + + /** + * A class that is used to access all of the children of a many-to-many relationship. + * Each instance of Parse.Relation is associated with a particular parent object and key. + */ + class Relation { + parent: S; + key: string; + targetClassName: string; + + constructor(parent?: S, key?: string); + + // Adds a Parse.Object or an array of Parse.Objects to the relation. + add(object: T | T[]): void; + + // Returns a Parse.Query that is limited to objects in this relation. + query(): Query; + + // Removes a Parse.Object or an array of Parse.Objects from this relation. + remove(object: T | T[]): void; + + toJSON(): any; + } + + interface Attributes { + [key: string]: any; + } + + /** + * 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 Parse.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 Parse.Object("ClassName");
+         * 
+ * That is basically equivalent to:
+         *     var MyClass = Parse.Object.extend("ClassName");
+         *     var object = new MyClass();
+         * 

+ * + * @param attributes The initial set of data to store in the object. + * @param options The options for this object instance. + * @see Parse.Object.extend + * + * + * Creates a new model with defined attributes. + */ + interface Object { + id: string; + createdAt: Date; + updatedAt: Date; + attributes: T; + className: string; + + add( + attr: K, + item: T[K][number], + ): this | false; + addAll( + attr: K, + items: T[K], + ): this | false; + addAllUnique: this['addAll']; + addUnique: this['add']; + clear(options: any): any; + clone(): this; + destroy(options?: Object.DestroyOptions): Promise; + dirty(attr?: Extract): boolean; + dirtyKeys(): string[]; + equals(other: T): boolean; + escape(attr: Extract): string; + existed(): boolean; + exists(options?: RequestOptions): Promise; + fetch(options?: Object.FetchOptions): Promise; + fetchFromLocalDatastore(): Promise; + fetchWithInclude>( + keys: K | Array, + options?: RequestOptions, + ): Promise; + get>(attr: K): T[K]; + getACL(): ACL | undefined; + has(attr: Extract): boolean; + increment(attr: Extract, amount?: number): this | false; + decrement(attr: Extract, amount?: number): this | false; + initialize(): void; + isDataAvailable(): boolean; + isNew(): boolean; + isPinned(): Promise; + isValid(): boolean; + newInstance(): this; + op(attr: Extract): any; + pin(): Promise; + pinWithName(name: string): Promise; + relation = Extract>( + attr: T[K] extends Relation ? K : never, + ): Relation; + remove: this['add']; + removeAll: this['addAll']; + revert(...keys: Array>): void; + save>( + attrs?: + | (((x: T) => void) extends (x: Attributes) => void + ? Partial + : { + [key in K]: T[key]; + }) + | null, + options?: Object.SaveOptions, + ): Promise; + save>(key: K, value: T[K], options?: Object.SaveOptions): Promise; + set>( + attrs: ((x: T) => void) extends (x: Attributes) => void + ? Partial + : { + [key in K]: T[key]; + }, + options?: Object.SetOptions, + ): this | false; + set>(key: K, value: T[K], options?: Object.SetOptions): this | false; + setACL(acl: ACL, options?: SuccessFailureOptions): this | false; + toJSON(): Object.ToJSON & JSONBaseAttributes; + toPointer(): Pointer; + unPin(): Promise; + unPinWithName(name: string): Promise; + unset(attr: Extract, options?: any): this | false; + validate(attrs: Attributes, options?: SuccessFailureOptions): Error | false; + } + interface ObjectStatic { + createWithoutData(id: string): T; + destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; + extend(className: string | { className: string }, protoProps?: any, classProps?: any): any; + fetchAll(list: T[], options: Object.FetchAllOptions): Promise; + fetchAllIfNeeded(list: T[], options?: Object.FetchAllOptions): Promise; + fetchAllIfNeededWithInclude( + list: T[], + keys: keyof T['attributes'] | Array, + options?: RequestOptions, + ): Promise; + fetchAllWithInclude( + list: T[], + keys: keyof T['attributes'] | Array, + options?: RequestOptions, + ): Promise; + fromJSON(json: any, override?: boolean): T; + pinAll(objects: Object[]): Promise; + pinAllWithName(name: string, objects: Object[]): Promise; + registerSubclass(className: string, clazz: new (options?: any) => T): void; + saveAll(list: T, options?: Object.SaveAllOptions): Promise; + unPinAll(objects: Object[]): Promise; + unPinAllObjects(): Promise; + unPinAllObjectsWithName(name: string): Promise; + unPinAllWithName(name: string, objects: Object[]): Promise; + } + interface ObjectConstructor extends ObjectStatic { + new (className: string, attributes: T, options?: any): Object; + new (className?: string, attributes?: Attributes, options?: any): Object; + } + const Object: ObjectConstructor; + + namespace Object { + interface DestroyOptions extends SuccessFailureOptions, WaitOption, ScopeOptions {} + + interface DestroyAllOptions extends BatchSizeOption, ScopeOptions {} + + interface FetchAllOptions extends SuccessFailureOptions, ScopeOptions {} + + interface FetchOptions extends SuccessFailureOptions, ScopeOptions {} + + interface SaveOptions + extends CascadeSaveOption, + SuccessFailureOptions, + SilentOption, + ScopeOptions, + WaitOption {} + + interface SaveAllOptions extends BatchSizeOption, ScopeOptions {} + + interface SetOptions extends ErrorOption, SilentOption { + promise?: any; + } + + // From https://github.com/parse-community/Parse-SDK-JS/blob/master/src/encode.js + type Encode = T extends Object + ? ReturnType | Pointer + : T extends ACL | GeoPoint | Polygon | Relation | File + ? ReturnType + : T extends Date + ? { __type: 'Date'; iso: string } + : T extends RegExp + ? string + : T extends Array + ? Array> + : T extends object + ? ToJSON + : T; + + type ToJSON = { + [K in keyof T]: Encode; + }; + } + + class Polygon { + constructor(arg1: GeoPoint[] | number[][]); + containsPoint(point: GeoPoint): boolean; + equals(other: any): boolean; + toJSON(): any; + } + + /** + * Every Parse application installed on a device registered for + * push notifications has an associated Installation object. + */ + interface Installation extends Object { + badge: any; + channels: string[]; + timeZone: any; + deviceType: string; + pushType: string; + installationId: string; + deviceToken: string; + channelUris: string; + appName: string; + appVersion: string; + parseVersion: string; + appIdentifier: string; + } + interface InstallationConstructor extends ObjectStatic { + new (attributes: T): Installation; + new (): Installation; + } + const Installation: InstallationConstructor; + + /** + * Creates a new parse Parse.Query for the given Parse.Object subclass. + * @param objectClass - + * An instance of a subclass of Parse.Object, or a Parse className string. + * + *

Parse.Query defines a query that is used to fetch Parse.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 Parse.Query(MyClass);
+         * query.find({
+         *   success: function(results) {
+         *     // results is an array of Parse.Object.
+         *   },
+         *
+         *   error: function(error) {
+         *     // error is an instance of Parse.Error.
+         *   }
+         * });

+ * + *

A Parse.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 Parse.Query(MyClass);
+         * query.get(myId, {
+         *   success: function(object) {
+         *     // object is an instance of Parse.Object.
+         *   },
+         *
+         *   error: function(object, error) {
+         *     // error is an instance of Parse.Error.
+         *   }
+         * });

+ * + *

A Parse.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 Parse.Query(MyClass);
+         * query.count({
+         *   success: function(number) {
+         *     // There are number instances of MyClass.
+         *   },
+         *
+         *   error: function(error) {
+         *     // error is an instance of Parse.Error.
+         *   }
+         * });

+ */ + class Query { + objectClass: any; + className: string; + + constructor(objectClass: string | (new (...args: any[]) => T | Object)); + + static and(...args: Array>): Query; + static fromJSON(className: string | (new () => U), json: any): Query; + static nor(...args: Array>): Query; + static or(...var_args: Array>): Query; + + addAscending(key: K | K[]): this; + addDescending(key: K | K[]): this; + ascending(key: K | K[]): this; + aggregate(pipeline: Query.AggregationOptions | Query.AggregationOptions[]): Promise; + containedBy( + key: K, + values: Array, + ): this; + containedIn( + key: K, + values: Array, + ): this; + contains(key: K, substring: string): this; + containsAll(key: K, values: any[]): this; + containsAllStartingWith( + key: K, + values: any[], + ): this; + count(options?: Query.CountOptions): Promise; + descending(key: K | K[]): this; + doesNotExist(key: K): this; + doesNotMatchKeyInQuery< + U extends Object, + K extends keyof T['attributes'] | keyof BaseAttributes, + X extends Extract + >(key: K, queryKey: X, query: Query): this; + doesNotMatchQuery(key: K, query: Query): this; + distinct(key: K): Promise; + eachBatch(callback: (objs: T[]) => PromiseLike | void, options?: Query.BatchOptions): Promise; + each(callback: (obj: T) => PromiseLike | void, options?: Query.BatchOptions): Promise; + hint(value: string | object): this; + explain(explain: boolean): this; + map( + callback: (currentObject: T, index: number, query: Query) => PromiseLike | U, + options?: Query.BatchOptions, + ): Promise; + reduce( + callback: (accumulator: T, currentObject: T, index: number) => PromiseLike | T, + initialValue?: undefined, + options?: Query.BatchOptions, + ): Promise; + reduce( + callback: (accumulator: U, currentObject: T, index: number) => PromiseLike | U, + initialValue: U, + options?: Query.BatchOptions, + ): Promise; + filter( + callback: (currentObject: T, index: number, query: Query) => PromiseLike | boolean, + options?: Query.BatchOptions, + ): Promise; + endsWith(key: K, suffix: string): this; + equalTo( + key: K, + value: + | T['attributes'][K] + | (T['attributes'][K] extends Object + ? Pointer + : T['attributes'][K] extends Array + ? E + : never), + ): this; + exclude(...keys: K[]): this; + exists(key: K): this; + find(options?: Query.FindOptions): Promise; + findAll(options?: Query.BatchOptions): Promise; + first(options?: Query.FirstOptions): Promise; + fromNetwork(): this; + fromLocalDatastore(): this; + fromPin(): this; + fromPinWithName(name: string): this; + cancel(): this; + fullText( + key: K, + value: string, + options?: Query.FullTextOptions, + ): this; + get(objectId: string, options?: Query.GetOptions): Promise; + greaterThan( + key: K, + value: T['attributes'][K], + ): this; + greaterThanOrEqualTo( + key: K, + value: T['attributes'][K], + ): this; + include(...key: K[]): this; + include(key: K[]): this; + includeAll(): Query; + lessThan(key: K, value: T['attributes'][K]): this; + lessThanOrEqualTo( + key: K, + value: T['attributes'][K], + ): this; + limit(n: number): Query; + matches( + key: K, + regex: RegExp, + modifiers?: string, + ): this; + matchesKeyInQuery< + U extends Object, + K extends keyof T['attributes'], + X extends Extract + >(key: K, queryKey: X, query: Query): this; + matchesQuery(key: K, query: Query): this; + near(key: K, point: GeoPoint): this; + notContainedIn( + key: K, + values: Array, + ): this; + notEqualTo( + key: K, + value: + | T['attributes'][K] + | (T['attributes'][K] extends Object + ? Pointer + : T['attributes'][K] extends Array + ? E + : never), + ): this; + polygonContains(key: K, point: GeoPoint): this; + select(...keys: K[]): this; + select(keys: K[]): this; + skip(n: number): Query; + sortByTextScore(): this; + startsWith(key: K, prefix: string): this; + subscribe(): Promise; + toJSON(): any; + withJSON(json: any): this; + withCount(includeCount?: boolean): this; + withinGeoBox( + key: K, + southwest: GeoPoint, + northeast: GeoPoint, + ): this; + withinKilometers( + key: K, + point: GeoPoint, + maxDistance: number, + sorted?: boolean, + ): this; + withinMiles( + key: K, + point: GeoPoint, + maxDistance: number, + sorted?: boolean, + ): this; + withinPolygon(key: K, points: number[][]): this; + withinRadians( + key: K, + point: GeoPoint, + maxDistance: number, + ): this; + } + + namespace Query { + interface EachOptions extends SuccessFailureOptions, ScopeOptions {} + interface CountOptions extends SuccessFailureOptions, ScopeOptions {} + interface FindOptions extends SuccessFailureOptions, ScopeOptions {} + interface FirstOptions extends SuccessFailureOptions, ScopeOptions {} + interface GetOptions extends SuccessFailureOptions, ScopeOptions {} + + // According to http://docs.parseplatform.org/rest/guide/#aggregate-queries + interface AggregationOptions { + group?: { objectId?: string; [key: string]: any }; + match?: { [key: string]: any }; + project?: { [key: string]: any }; + limit?: number; + skip?: number; + // Sort documentation https://docs.mongodb.com/v3.2/reference/operator/aggregation/sort/#pipe._S_sort + sort?: { [key: string]: 1 | -1 }; + // Sample documentation: https://docs.mongodb.com/v3.2/reference/operator/aggregation/sample/ + sample?: { size: number }; + } + + // According to https://parseplatform.org/Parse-SDK-JS/api/2.1.0/Parse.Query.html#fullText + interface FullTextOptions { + language?: string; + caseSensitive?: boolean; + diacriticSensitive?: boolean; + } + + interface BatchOptions extends FullOptions { + batchSize?: number; + } + } + + /** + * Represents a LiveQuery Subscription. + * + * @see https://docs.parseplatform.org/js/guide/#live-queries + * @see NodeJS.EventEmitter + * + * Events list + * --- + * `open` - when you call `query.subscribe()`, we send a subscribe request to + * the LiveQuery server, when we get the confirmation from the LiveQuery server, + * this event will be emitted. When the client loses WebSocket connection to the + * LiveQuery server, we will try to auto reconnect the LiveQuery server. If we + * reconnect the LiveQuery server and successfully resubscribe the ParseQuery, + * you'll also get this event. + * + * ``` + * subscription.on('open', () => {}); + * ``` + * --- + * `create` - when a new ParseObject is created and it fulfills the ParseQuery you subscribe, + * you'll get this event. The object is the ParseObject which is created. + * + * ``` + * subscription.on('create', (object: Parse.Object) => {}); + * ``` + * --- + * `update` event - when an existing ParseObject which fulfills the ParseQuery you subscribe + * is updated (The ParseObject fulfills the ParseQuery before and after changes), + * you'll get this event. The object is the ParseObject which is updated. + * Its content is the latest value of the ParseObject. + * + * ``` + * subscription.on('update', (object: Parse.Object) => {}); + * ``` + * --- + * `enter` event - when an existing ParseObject's old value doesn't fulfill the ParseQuery + * but its new value fulfills the ParseQuery, you'll get this event. The object is the + * ParseObject which enters the ParseQuery. Its content is the latest value of the ParseObject. + * + * ``` + * subscription.on('enter', (object: Parse.Object) => {}); + * ``` + * --- + * `update` event - when an existing ParseObject's old value fulfills the ParseQuery but its new value + * doesn't fulfill the ParseQuery, you'll get this event. The object is the ParseObject + * which leaves the ParseQuery. Its content is the latest value of the ParseObject. + * + * ``` + * subscription.on('leave', (object: Parse.Object) => {}); + * ``` + * --- + * `delete` event - when an existing ParseObject which fulfills the ParseQuery is deleted, you'll + * get this event. The object is the ParseObject which is deleted. + * + * ``` + * subscription.on('delete', (object: Parse.Object) => {}); + * ``` + * --- + * `close` event - when the client loses the WebSocket connection to the LiveQuery + * server and we stop receiving events, you'll get this event. + * + * ``` + * subscription.on('close', () => {}); + * ``` + */ + class LiveQuerySubscription extends EventEmitter { + /** + * Creates an instance of LiveQuerySubscription. + * + * @param id + * @param query + * @param [sessionToken] + */ + constructor(id: string, query: string, sessionToken?: string); + + on( + event: 'open' | 'create' | 'update' | 'enter' | 'leave' | 'delete' | 'close', + listener: (object: Object) => void, + ): this; + + /** + * Closes the subscription. + * + */ + unsubscribe(): void; + } + + /** + * Represents a Role on the Parse 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.

+ * A Parse.Role is a local representation of a role persisted to the Parse + * cloud. + */ + interface Role extends Object { + getRoles(): Relation; + getUsers(): Relation; + getName(): string; + setName(name: string, options?: SuccessFailureOptions): any; + } + interface RoleConstructor extends ObjectStatic { + new (name: string, acl: ACL): Role>; + new (name: string, acl: ACL): Role; + } + const Role: RoleConstructor; + + class Config { + static get(options?: UseMasterKeyOption): Promise; + static current(): Config; + static save(attr: any, options?: { [attr: string]: boolean }): Promise; + + get(attr: string): any; + escape(attr: string): any; + } + + interface Session extends Object { + getSessionToken(): string; + isCurrentSessionRevocable(): boolean; + } + interface SessionConstructor extends ObjectStatic { + new (attributes: T): Session; + new (): Session; + + current(): Promise; + } + const Session: SessionConstructor; + + /** + * + *

A Parse.User object is a local representation of a user persisted to the + * Parse cloud. This class is a subclass of a Parse.Object, and retains the + * same functionality of a Parse.Object, but also extends it with various + * user specific methods, like authentication, signing up, and validation of + * uniqueness.

+ */ + interface User extends Object { + signUp(attrs?: any, options?: SignUpOptions): Promise; + logIn(options?: FullOptions): Promise; + authenticated(): boolean; + isCurrent(): boolean; + + getEmail(): string | undefined; + setEmail(email: string, options?: SuccessFailureOptions): boolean; + + getUsername(): string | undefined; + setUsername(username: string, options?: SuccessFailureOptions): boolean; + + setPassword(password: string, options?: SuccessFailureOptions): boolean; + getSessionToken(): string; + + linkWith: ( + provider: string | AuthProvider, + options: { authData?: AuthData }, + saveOpts?: FullOptions, + ) => Promise; + _isLinked: (provider: string | AuthProvider) => boolean; + _unlinkFrom: (provider: string | AuthProvider, options?: FullOptions) => Promise; + } + interface UserConstructor extends ObjectStatic { + new (attributes: T): User; + new (attributes?: Attributes): User; + + allowCustomUserClass(isAllowed: boolean): void; + become(sessionToken: string, options?: UseMasterKeyOption): Promise; + current(): T | undefined; + currentAsync(): Promise; + signUp(username: string, password: string, attrs: any, options?: SignUpOptions): Promise; + logIn(username: string, password: string, options?: FullOptions): Promise; + logOut(): Promise; + requestPasswordReset(email: string, options?: SuccessFailureOptions): Promise; + extend(protoProps?: any, classProps?: any): any; + hydrate(userJSON: any): Promise; + enableUnsafeCurrentUser(): void; + logInWith( + provider: string | AuthProvider, + options: { authData?: AuthData }, + saveOpts?: FullOptions, + ): Promise; + _registerAuthenticationProvider: (provider: AuthProvider) => void; + } + const User: UserConstructor; + + type LogLevels = 'error' | 'warn' | 'info' | 'debug' | 'verbose' |'silly'; + interface LoggerInterface { + + log(level : LogLevels, args : any) : void + + info(args : any): LoggerInterface + + error(args : any): LoggerInterface + + warn(args : any): LoggerInterface + + verbose(args : any): LoggerInterface + + debug(args : any): LoggerInterface + + silly(args : any): LoggerInterface + } + + + /** + * A Parse.Schema object is for handling schema data from Parse. + * All the schemas methods require MasterKey. + * + * @param className Parse Class string + * + * https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html + * + * ``` + * const schema = new Parse.Schema('MyClass'); + * schema.addString('field'); + * schema.addIndex('index_name', { field: 1 }); + * schema.save(); + * ``` + */ + class Schema { + constructor(className: string); + + /** + * Static method to get all schemas + * + * @return A promise that is resolved with the result when + * the query completes. + */ + static all(): Promise; + + addArray(key: Schema.AttrType, options?: Schema.FieldOptions): this; + addBoolean(key: Schema.AttrType, options?: Schema.FieldOptions): this; + addDate(key: Schema.AttrType, options?: Schema.FieldOptions): this; + addField(name: string, type?: T, options?: Schema.FieldOptions): this; + addFile(key: Schema.AttrType, options?: Schema.FieldOptions): this; + addGeoPoint(key: Schema.AttrType, options?: Schema.FieldOptions): this; + + /** + * Adding an Index to Create / Update a Schema + * @param name Name of the field that will be created on Parse + * @param index `{ 'field': value }` where `field` should exist in the schema before using addIndex. + * @return Returns the schema, so you can chain this call. + * @example + * ``` + * schema.addIndex('index_name', {'field': 1}); + * ``` + */ + addIndex(name: string, index: Schema.Index): this; + + addNumber(key: Schema.AttrType, options?: Schema.FieldOptions): this; + + addObject(key: Schema.AttrType, options?: Schema.FieldOptions): this; + + /** + * Adding Pointer Field + * @param name Name of the field that will be created on Parse + * @param targetClass Name of the target Pointer Class + * @return Returns the schema, so you can chain this call. + */ + addPointer( + key: Schema.AttrType, + targetClass: string, + options?: Schema.FieldOptions, + ): this; + + addPolygon(key: Schema.AttrType, options?: Schema.FieldOptions): this; + + /** + * Adding Relation Field + * @param name Name of the field that will be created on Parse + * @param targetClass Name of the target Pointer Class + * @return Returns the schema, so you can chain this call. + */ + addRelation( + key: Schema.AttrType, + targetClass: string, + options?: Schema.FieldOptions, + ): this; + + addString(key: Schema.AttrType, options?: Schema.FieldOptions): this; + + /** + * Removing a Schema from Parse Can only be used on Schema without objects + * @returns A promise that is resolved with the result when the query completes. + */ + // @TODO Fix Promise + delete(): Promise; + + /** + * Deleting a Field to Update on a Schema + * @param name Name of the field + * @return Returns the schema, so you can chain this call. + */ + deleteField(name: string): this; + + /** + * Deleting a Index Field to Update on a Schema + * @param name Name of the index field + * @return Returns the schema, so you can chain this call. + */ + deleteIndex(name: string): this; + + /** + * Get the Schema from Parse + */ + get(): Promise; + + /** + * Removes all objects from a Schema (class) in EXERCISE CAUTION, running this will delete all objects for this schema and cannot be reversed + */ + // TODO Fix Promise + purge(): Promise; + + /** + * Create a new Schema on Parse + */ + save(): Promise; + + /** + * Sets Class Level Permissions when creating / updating a Schema. + * EXERCISE CAUTION, running this may override CLP for this schema and cannot be reversed + */ + setCLP(clp: Schema.CLP): this; + + /** + * Update a Schema on Parse + */ + update(): Promise; + } + + namespace Schema { + type TYPE = + | 'String' + | 'Number' + | 'Boolean' + | 'Date' + | 'File' + | 'GeoPoint' + | 'Polygon' + | 'Array' + | 'Object' + | 'Pointer' + | 'Relation'; + type FieldType = + | string + | number + | boolean + | Date + | File + | GeoPoint + | Polygon + | any[] + | object + | Pointer + | Relation; + type AttrType = Extract< + { [K in keyof T['attributes']]: T['attributes'][K] extends V ? K : never }[keyof T['attributes']], + string + >; + + interface FieldOptions< + T extends + | string + | number + | boolean + | Date + | File + | GeoPoint + | Polygon + | any[] + | object + | Pointer + | Relation = any + > { + required?: boolean; + defaultValue?: T; + } + + interface Index { + [fieldName: string]: TYPE; + } + + /** + * The id of a `_User` object or a role name prefixed by `'role:'`. + * @example + * '*': false, // public + * requiresAuthentication: false, + * 'role:Admin': true, + * 'idOfASpecificUser': true + */ + interface CLPField { + '*'?: boolean; + requiresAuthentication?: boolean; + /** `role:Admin` */ + [userIdOrRoleName: string]: boolean | undefined; + } + + interface CLP { + find?: CLPField; + get?: CLPField; + count?: CLPField; + create?: CLPField; + update?: CLPField; + delete?: CLPField; + addField?: CLPField; + /** Array of fields that point to a `_User` object's ID or a `Role` object's name */ + readUserFields?: string[]; + /** Array of fields that point to a `_User` object's ID or a `Role` object's name */ + writeUserFields?: string[]; + } + } + + namespace Analytics { + function track(name: string, dimensions: any): Promise; + } + + /** + * Provides utility functions for working with Anonymously logged-in users. + */ + namespace AnonymousUtils { + function isLinked(user: User): boolean; + function link(user: User, options?: ScopeOptions): Promise; + function logIn(options?: ScopeOptions): Promise; + } + + /** + * Provides a set of utilities for using Parse with Facebook. + * Provides a set of utilities for using Parse with Facebook. + */ + namespace FacebookUtils { + function init(options?: any): void; + function isLinked(user: User): boolean; + function link(user: User, permissions: any, options?: SuccessFailureOptions): void; + function logIn(permissions: any, options?: FullOptions): void; + function unlink(user: User, options?: SuccessFailureOptions): void; + } + + /** + * Contains functions for calling and declaring + * cloud functions. + *

+ * Some functions are only available from Cloud Code. + *

+ */ + namespace Cloud { + interface CookieOptions { + domain?: string; + expires?: Date; + httpOnly?: boolean; + maxAge?: number; + path?: string; + secure?: boolean; + } + + interface HttpResponse { + buffer?: Buffer; + cookies?: any; + data?: any; + headers?: any; + status?: number; + text?: string; + } + + interface JobRequest { + params: T; + message: (response: any) => void; + log: LoggerInterface, + headers?: any; + ip: string; + jobName : string, + } + + interface Params { + [key: string]: any; + } + + interface FunctionRequest { + installationId?: string; + master?: boolean; + params: T; + user?: User; + } + + interface ValidatorField { + type?: any; + required?: boolean; + constant?: boolean; + default?: any; + options?: any[]|Function; + error?: String; + } + interface ValidatorFields { + [field: string]: ValidatorField; + } + interface Validator { + requireUser?: boolean; + requireMaster?: boolean; + validateMasterKey?: boolean; + skipWithMasterKey?: boolean; + requireAnyUserRoles?: String[]|Function; + requireAllUserRoles?: String[]|Function; + fields?: ValidatorFields|String[]; + requireUserKeys?: ValidatorFields|String[]; + } + + interface Cookie { + name?: string; + options?: CookieOptions; + value?: string; + } + + interface TriggerRequest { + installationId?: string; + master?: boolean; + user?: User; + ip: string; + headers: any; + triggerName: string; + log: any; + object: T; + original?: T; + } + + interface AfterSaveRequest extends TriggerRequest { + context: object; + } + interface AfterDeleteRequest extends TriggerRequest {} // tslint:disable-line no-empty-interface + interface BeforeDeleteRequest extends TriggerRequest {} // tslint:disable-line no-empty-interface + interface BeforeSaveRequest extends TriggerRequest { + context: object; + } + + interface FileTriggerRequest extends TriggerRequest { + file: File; + fileSize: number; + contentLength: number; + } + + // Read preference describes how MongoDB driver route read operations to the members of a replica set. + enum ReadPreferenceOption { + Primary = 'PRIMARY', + PrimaryPreferred = 'PRIMARY_PREFERRED', + Secondary = 'SECONDARY', + SecondaryPreferred = 'SECONDARY_PREFERRED', + Nearest = 'NEAREST', + } + + interface BeforeFindRequest extends TriggerRequest { + query: Query; + count: boolean; + isGet: boolean; + readPreference?: ReadPreferenceOption; + } + + interface AfterFindRequest extends TriggerRequest { + objects: T[]; + } + + function afterDelete( + arg1: { new (): T } | string, + func?: (request: AfterDeleteRequest) => Promise | void, + validator?: Validator|((request: FunctionRequest) => any), + ): void; + function afterSave( + arg1: { new (): T } | string, + func?: (request: AfterSaveRequest) => Promise | void, + validator?: Validator|((request: FunctionRequest) => any), + ): void; + function beforeDelete( + arg1: { new (): T } | string, + func?: (request: BeforeDeleteRequest) => Promise | void, + validator?: Validator|((request: FunctionRequest) => any), + ): void; + function beforeSave( + arg1: { new (): T } | string, + func?: (request: BeforeSaveRequest) => Promise | void, + validator?: Validator|((request: FunctionRequest) => any), + ): void; + function beforeFind( + arg1: { new (): T } | string, + func?: (request: BeforeFindRequest) => Promise> | Promise | Query | void, + validator?: Validator|((request: FunctionRequest) => any), + ): void; + function afterFind( + arg1: { new (): T } | string, + func?: (request: AfterFindRequest) => any, + validator?: Validator|((request: FunctionRequest) => any), + ): void; + + function beforeLogin(func?: (request: TriggerRequest) => PromiseLike | void): void; + function afterLogin(func?: (request: TriggerRequest) => PromiseLike | void, validator?: Validator|((request: FunctionRequest) => any)): void; + function afterLogout(func?: (request: TriggerRequest) => PromiseLike | void, validator?: Validator|((request: FunctionRequest) => any)): void; + + function beforeSaveFile(func?: (request: FileTriggerRequest) => PromiseLike | void, validator?: Validator|((request: FunctionRequest) => any)): void; + function afterSaveFile(func?: (request: FileTriggerRequest) => PromiseLike | void, validator?: Validator|((request: FunctionRequest) => any)): void; + function beforeDeleteFile(func?: (request: FileTriggerRequest) => PromiseLike | void, validator?: Validator|((request: FunctionRequest) => any)): void; + function afterDeleteFile(func?: (request: FileTriggerRequest) => PromiseLike | void, validator?: Validator|((request: FunctionRequest) => any)): void; + + function define(name: string, func: (request: FunctionRequest) => any, validator?: Validator|((request: FunctionRequest) => any)): void; + function define any>( + name: string, + func: (request: FunctionRequest<{}>) => Promise> | ReturnType, + validator?: Validator|((request: FunctionRequest) => any), + ): void; + function define[0]]: Parameters[0][P] }) => any>( + name: string, + func: (request: FunctionRequest[0]>) => Promise> | ReturnType, + validator?: Validator|((request: FunctionRequest) => any), + ): void; + /** + * Gets data for the current set of cloud jobs. + * @returns A promise that will be resolved with the result of the function. + */ + function getJobsData(): Promise; + /** + * Gets job status by Id + * @param jobStatusId The Id of Job Status. + * @returns Status of Job. + */ + function getJobStatus(jobStatusId: string): Promise; + function httpRequest(options: HTTPOptions): Promise; + function job(name: string, func?: (request: JobRequest) => Promise | void): HttpResponse; + function run(name: string, data?: Params, options?: RunOptions): Promise; + function run any>(name: string, data?: null, options?: RunOptions): Promise>; + function run[0]]: Parameters[0][P] }) => any>( + name: string, + data: Parameters[0], + options?: RunOptions, + ): Promise>; + /** + * Starts a given cloud job, which will process asynchronously. + * @param jobName The function name. + * @param data The parameters to send to the cloud function. + * @returns A promise that will be resolved with the jobStatusId of the job. + */ + function startJob(jobName: string, data: any): Promise; + function useMasterKey(): void; + + interface RunOptions extends SuccessFailureOptions, ScopeOptions {} + + /** + * To use this Cloud Module in Cloud Code, you must require 'buffer' in your JavaScript file. + * + * import Buffer = require("buffer").Buffer; + */ + let HTTPOptions: new () => HTTPOptions; + interface HTTPOptions { + /** + * The body of the request. + * If it is a JSON object, then the Content-Type set in the headers must be application/x-www-form-urlencoded or application/json. + * You can also set this to a Buffer object to send raw bytes. + * If you use a Buffer, you should also set the Content-Type header explicitly to describe what these bytes represent. + */ + body?: string | Buffer | object; + /** + * Defaults to 'false'. + */ + followRedirects?: boolean; + /** + * The headers for the request. + */ + headers?: { + [headerName: string]: string | number | boolean; + }; + /** + * The method of the request (i.e GET, POST, etc). + */ + method?: string; + /** + * The query portion of the url. + */ + params?: any; + /** + * The url to send the request to. + */ + url: string; + + success?: (response: any) => void; + error?: (response: any) => void; + } + } + + class Error { + static OTHER_CAUSE: ErrorCode.OTHER_CAUSE; + static INTERNAL_SERVER_ERROR: ErrorCode.INTERNAL_SERVER_ERROR; + static CONNECTION_FAILED: ErrorCode.CONNECTION_FAILED; + static OBJECT_NOT_FOUND: ErrorCode.OBJECT_NOT_FOUND; + static INVALID_QUERY: ErrorCode.INVALID_QUERY; + static INVALID_CLASS_NAME: ErrorCode.INVALID_CLASS_NAME; + static MISSING_OBJECT_ID: ErrorCode.MISSING_OBJECT_ID; + static INVALID_KEY_NAME: ErrorCode.INVALID_KEY_NAME; + static INVALID_POINTER: ErrorCode.INVALID_POINTER; + static INVALID_JSON: ErrorCode.INVALID_JSON; + static COMMAND_UNAVAILABLE: ErrorCode.COMMAND_UNAVAILABLE; + static NOT_INITIALIZED: ErrorCode.NOT_INITIALIZED; + static INCORRECT_TYPE: ErrorCode.INCORRECT_TYPE; + static INVALID_CHANNEL_NAME: ErrorCode.INVALID_CHANNEL_NAME; + static PUSH_MISCONFIGURED: ErrorCode.PUSH_MISCONFIGURED; + static OBJECT_TOO_LARGE: ErrorCode.OBJECT_TOO_LARGE; + static OPERATION_FORBIDDEN: ErrorCode.OPERATION_FORBIDDEN; + static CACHE_MISS: ErrorCode.CACHE_MISS; + static INVALID_NESTED_KEY: ErrorCode.INVALID_NESTED_KEY; + static INVALID_FILE_NAME: ErrorCode.INVALID_FILE_NAME; + static INVALID_ACL: ErrorCode.INVALID_ACL; + static TIMEOUT: ErrorCode.TIMEOUT; + static INVALID_EMAIL_ADDRESS: ErrorCode.INVALID_EMAIL_ADDRESS; + static MISSING_CONTENT_TYPE: ErrorCode.MISSING_CONTENT_TYPE; + static MISSING_CONTENT_LENGTH: ErrorCode.MISSING_CONTENT_LENGTH; + static INVALID_CONTENT_LENGTH: ErrorCode.INVALID_CONTENT_LENGTH; + static FILE_TOO_LARGE: ErrorCode.FILE_TOO_LARGE; + static FILE_SAVE_ERROR: ErrorCode.FILE_SAVE_ERROR; + static DUPLICATE_VALUE: ErrorCode.DUPLICATE_VALUE; + static INVALID_ROLE_NAME: ErrorCode.INVALID_ROLE_NAME; + static EXCEEDED_QUOTA: ErrorCode.EXCEEDED_QUOTA; + static SCRIPT_FAILED: ErrorCode.SCRIPT_FAILED; + static VALIDATION_ERROR: ErrorCode.VALIDATION_ERROR; + static INVALID_IMAGE_DATA: ErrorCode.INVALID_IMAGE_DATA; + static UNSAVED_FILE_ERROR: ErrorCode.UNSAVED_FILE_ERROR; + static INVALID_PUSH_TIME_ERROR: ErrorCode.INVALID_PUSH_TIME_ERROR; + static FILE_DELETE_ERROR: ErrorCode.FILE_DELETE_ERROR; + static REQUEST_LIMIT_EXCEEDED: ErrorCode.REQUEST_LIMIT_EXCEEDED; + static INVALID_EVENT_NAME: ErrorCode.INVALID_EVENT_NAME; + static USERNAME_MISSING: ErrorCode.USERNAME_MISSING; + static PASSWORD_MISSING: ErrorCode.PASSWORD_MISSING; + static USERNAME_TAKEN: ErrorCode.USERNAME_TAKEN; + static EMAIL_TAKEN: ErrorCode.EMAIL_TAKEN; + static EMAIL_MISSING: ErrorCode.EMAIL_MISSING; + static EMAIL_NOT_FOUND: ErrorCode.EMAIL_NOT_FOUND; + static SESSION_MISSING: ErrorCode.SESSION_MISSING; + static MUST_CREATE_USER_THROUGH_SIGNUP: ErrorCode.MUST_CREATE_USER_THROUGH_SIGNUP; + static ACCOUNT_ALREADY_LINKED: ErrorCode.ACCOUNT_ALREADY_LINKED; + static INVALID_SESSION_TOKEN: ErrorCode.INVALID_SESSION_TOKEN; + static LINKED_ID_MISSING: ErrorCode.LINKED_ID_MISSING; + static INVALID_LINKED_SESSION: ErrorCode.INVALID_LINKED_SESSION; + static UNSUPPORTED_SERVICE: ErrorCode.UNSUPPORTED_SERVICE; + static AGGREGATE_ERROR: ErrorCode.AGGREGATE_ERROR; + static FILE_READ_ERROR: ErrorCode.FILE_READ_ERROR; + static X_DOMAIN_REQUEST: ErrorCode.X_DOMAIN_REQUEST; + + code: ErrorCode; + message: string; + + constructor(code: ErrorCode, message: string); + } + + /** + * A Parse.Op is an atomic operation that can be applied to a field in a + * Parse.Object. For example, calling object.set("foo", "bar") + * is an example of a Parse.Op.Set. Calling object.unset("foo") + * is a Parse.Op.Unset. These operations are stored in a Parse.Object and + * sent to the server as part of object.save() operations. + * Instances of Parse.Op should be immutable. + * + * You should not create subclasses of Parse.Op or instantiate Parse.Op + * directly. + */ + namespace Op { + interface BaseOperation { + objects(): any[]; + } + + interface Add extends BaseOperation { + toJSON(): any; + } + + interface AddUnique extends BaseOperation { + toJSON(): any; + } + + interface Increment { + amount: number; + toJSON(): any; + } + + interface Relation { + added(): Object[]; + removed: Object[]; + toJSON(): any; + } + + interface Set { + value(): any; + toJSON(): any; + } + + interface Unset { + toJSON(): any; + } + } + + /** + * Contains functions to deal with Push in Parse + */ + namespace Push { + function send(data: PushData, options?: SendOptions): Promise; + + interface PushData { + channels?: string[]; + push_time?: Date; + expiration_time?: Date; + expiration_interval?: number; + where?: Query; + data?: any; + alert?: string; + badge?: string; + sound?: string; + title?: string; + notification?: any; + content_available?: any; + } + + interface SendOptions extends UseMasterKeyOption { + success?: () => void; + error?: (error: Error) => void; + } + } + + /** + * Call this method first to set up your authentication tokens for Parse. + * You can get your keys from the Data Browser on parse.com. + * @param applicationId Your Parse Application ID. + * @param javaScriptKey (optional) Your Parse JavaScript Key (Not needed for parse-server) + * @param masterKey (optional) Your Parse Master Key. (Node.js only!) + */ + function initialize(applicationId: string, javaScriptKey?: string, masterKey?: string): void; + + /** + * Use this to set custom headers + * The headers will be sent with every parse request + */ + namespace CoreManager { + function set(key: string, value: any): void; + function get(key: string): void; + } + + /** + * Additionally on React-Native / Expo environments, add AsyncStorage from 'react-native' package + * @param AsyncStorage AsyncStorage from 'react-native' package + */ + function setAsyncStorage(AsyncStorage: any): void; + + /** + * Gets all contents from Local Datastore. + */ + function dumpLocalDatastore(): Promise<{ [key: string]: any }>; + + /** + * Enable pinning in your application. + * This must be called before your application can use pinning. + */ + function enableLocalDatastore(): void; + + /** + * Flag that indicates whether Local Datastore is enabled. + */ + function isLocalDatastoreEnabled(): boolean; + + function setLocalDatastoreController(controller: any): void; + + /** + * Call this method to set your LocalDatastoreStorage engine + * If using React-Native use {@link Parse.setAsyncStorage Parse.setAsyncStorage()} + * @param controller a data storage. + */ + function setLocalDatastoreController(controller: any): void; + + /** + * Enable the current user encryption. + * This must be called before login any user. + */ + function enableEncryptedUser(): void; + + /** + * Flag that indicates whether Encrypted User is enabled. + */ + function isEncryptedUserEnabled(): boolean; + } +} + +export = Parse;