diff --git a/src/CoreManager.ts b/src/CoreManager.ts index dff47e32a..f13e76694 100644 --- a/src/CoreManager.ts +++ b/src/CoreManager.ts @@ -51,7 +51,7 @@ type ObjectController = { forceFetch: boolean, options: RequestOptions ) => Promise | ParseObject | undefined>, - save: (object: ParseObject | Array | null, options: RequestOptions) => Promise | ParseFile>, + save: (object: ParseObject | Array | null, options: RequestOptions) => Promise | ParseFile | undefined>, destroy: (object: ParseObject | Array, options: RequestOptions) => Promise>, }; type ObjectStateController = { diff --git a/src/ObjectStateMutations.js b/src/ObjectStateMutations.ts similarity index 98% rename from src/ObjectStateMutations.js rename to src/ObjectStateMutations.ts index 6fc32e911..2a11cd856 100644 --- a/src/ObjectStateMutations.js +++ b/src/ObjectStateMutations.ts @@ -1,15 +1,11 @@ -/** - * @flow - */ - import encode from './encode'; import CoreManager from './CoreManager'; import ParseFile from './ParseFile'; import ParseRelation from './ParseRelation'; import TaskQueue from './TaskQueue'; import { RelationOp } from './ParseOp'; - import type { Op } from './ParseOp'; +import type ParseObject from './ParseObject'; export type AttributeMap = { [attr: string]: any }; export type OpsMap = { [attr: string]: Op }; @@ -43,7 +39,7 @@ export function setServerData(serverData: AttributeMap, attributes: AttributeMap } } -export function setPendingOp(pendingOps: Array, attr: string, op: ?Op) { +export function setPendingOp(pendingOps: Array, attr: string, op?: Op) { const last = pendingOps.length - 1; if (op) { pendingOps[last][attr] = op; @@ -84,7 +80,7 @@ export function estimateAttribute( pendingOps: Array, object: ParseObject, attr: string -): mixed { +): any { let value = serverData[attr]; for (let i = 0; i < pendingOps.length; i++) { if (pendingOps[i][attr]) { diff --git a/src/Parse.ts b/src/Parse.ts index b271b013e..345efdcc9 100644 --- a/src/Parse.ts +++ b/src/Parse.ts @@ -43,8 +43,7 @@ import WebSocketController from './WebSocketController'; * @global * @class * @hideconstructor -*/ - + */ interface ParseType { ACL: typeof ACL, Parse?: ParseType, diff --git a/src/ParseFile.js b/src/ParseFile.ts similarity index 92% rename from src/ParseFile.js rename to src/ParseFile.ts index 491487ca7..8d8ae79b7 100644 --- a/src/ParseFile.js +++ b/src/ParseFile.ts @@ -1,11 +1,7 @@ -/** - * @flow - */ /* global XMLHttpRequest, Blob */ import CoreManager from './CoreManager'; import type { FullOptions } from './RESTController'; - -const ParseError = require('./ParseError').default; +import ParseError from './ParseError'; let XHR = null; if (typeof XMLHttpRequest !== 'undefined') { @@ -66,13 +62,13 @@ function b64Digit(number: number): string { */ class ParseFile { _name: string; - _url: ?string; + _url?: string; _source: FileSource; - _previousSave: ?Promise; - _data: ?string; - _requestTask: ?any; - _metadata: ?Object; - _tags: ?Object; + _previousSave?: Promise; + _data?: string; + _requestTask?: any; + _metadata?: Object; + _tags?: Object; /** * @param name {String} The file's name. This will be prefixed by a unique @@ -125,17 +121,17 @@ class ParseFile { file: data, type: specifiedType, }; - } else if (data && typeof data.uri === 'string' && data.uri !== undefined) { + } else if (data && typeof (data as Uri).uri === 'string' && (data as Uri).uri !== undefined) { this._source = { format: 'uri', - uri: data.uri, + uri: (data as Uri).uri, type: specifiedType, }; - } else if (data && typeof data.base64 === 'string') { - const base64 = data.base64.split(',').slice(-1)[0]; + } else if (data && typeof (data as Base64).base64 === 'string') { + const base64 = (data as Base64).base64.split(',').slice(-1)[0]; const dataType = specifiedType || - data.base64.split(';').slice(0, 1)[0].split(':').slice(1, 2)[0] || + (data as Base64).base64.split(';').slice(0, 1)[0].split(':').slice(1, 2)[0] || 'text/plain'; this._data = base64; this._source = { @@ -156,7 +152,7 @@ class ParseFile { * * @returns {Promise} Promise that is resolve with base64 data */ - async getData(): Promise { + async getData(): Promise { if (this._data) { return this._data; } @@ -190,7 +186,7 @@ class ParseFile { * @param {object} options An object to specify url options * @returns {string | undefined} */ - url(options?: { forceSecure?: boolean }): ?string { + url(options?: { forceSecure?: boolean }): string | undefined { options = options || {}; if (!this._url) { return; @@ -207,7 +203,7 @@ class ParseFile { * * @returns {object} */ - metadata(): Object { + metadata() { return this._metadata; } @@ -216,7 +212,7 @@ class ParseFile { * * @returns {object} */ - tags(): Object { + tags() { return this._tags; } @@ -243,7 +239,7 @@ class ParseFile { * * @returns {Promise | undefined} Promise that is resolved when the save finishes. */ - save(options?: FullOptions): ?Promise { + save(options?: FileSaveOptions): Promise | undefined { options = options || {}; options.requestTask = task => (this._requestTask = task); options.metadata = this._metadata; @@ -267,7 +263,7 @@ class ParseFile { return {}; } const newSource = { - format: 'base64', + format: 'base64' as const, base64: result.base64, type: result.contentType, }; @@ -275,7 +271,7 @@ class ParseFile { this._requestTask = null; return controller.saveBase64(this._name, newSource, options); }) - .then(res => { + .then((res: { name?: string, url?: string }) => { this._name = res.name; this._url = res.url; this._requestTask = null; @@ -317,7 +313,7 @@ class ParseFile { *
    * @returns {Promise} Promise that is resolved when the delete finishes.
    */
-  destroy(options?: FullOptions = {}) {
+  destroy(options: FullOptions = {}) {
     if (!this._name) {
       throw new ParseError(ParseError.FILE_DELETE_UNNAMED_ERROR, 'Cannot delete an unnamed file.');
     }
@@ -333,7 +329,7 @@ class ParseFile {
     });
   }
 
-  toJSON(): { name: ?string, url: ?string } {
+  toJSON(): { __type: 'File', name?: string, url?: string } {
     return {
       __type: 'File',
       name: this._name,
@@ -341,7 +337,7 @@ class ParseFile {
     };
   }
 
-  equals(other: mixed): boolean {
+  equals(other: any): boolean {
     if (this === other) {
       return true;
     }
@@ -413,7 +409,7 @@ class ParseFile {
     return file;
   }
 
-  static encodeBase64(bytes: Array): string {
+  static encodeBase64(bytes: Array | Uint8Array): string {
     const chunks = [];
     chunks.length = Math.ceil(bytes.length / 3);
     for (let i = 0; i < chunks.length; i++) {
@@ -441,10 +437,10 @@ const DefaultController = {
     if (source.format !== 'file') {
       throw new Error('saveFile can only be used with File-type sources.');
     }
-    const base64Data = await new Promise((res, rej) => {
+    const base64Data = await new Promise((res, rej) => {
       // eslint-disable-next-line no-undef
       const reader = new FileReader();
-      reader.onload = () => res(reader.result);
+      reader.onload = () => res(reader.result as string);
       reader.onerror = error => rej(error);
       reader.readAsDataURL(source.file);
     });
@@ -455,9 +451,9 @@ const DefaultController = {
     // use the entire string instead
     const data = second ? second : first;
     const newSource = {
-      format: 'base64',
+      format: 'base64' as const,
       base64: data,
-      type: source.type || (source.file ? source.file.type : null),
+      type: source.type || (source.file ? source.file.type : undefined),
     };
     return await DefaultController.saveBase64(name, newSource, options);
   },
@@ -510,7 +506,7 @@ const DefaultController = {
     }
   },
 
-  downloadAjax: function (uri, options) {
+  downloadAjax: function (uri: string, options: any) {
     return new Promise((resolve, reject) => {
       const xhr = new XHR();
       xhr.open('GET', uri, true);
diff --git a/src/ParseGeoPoint.ts b/src/ParseGeoPoint.ts
index b821dc838..62b3c525e 100644
--- a/src/ParseGeoPoint.ts
+++ b/src/ParseGeoPoint.ts
@@ -180,9 +180,15 @@ class ParseGeoPoint {
    * Creates a GeoPoint with the user's current location, if available.
    *
    * @param {object} options The options.
-   * @param {boolean} [options.enableHighAccuracy=false] A boolean value that indicates the application would like to receive the best possible results. If true and if the device is able to provide a more accurate position, it will do so. Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example). On the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power. Default: false.
-   * @param {number} [options.timeout=Infinity] A positive long value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position. The default value is Infinity, meaning that getCurrentPosition() won't return until the position is available.
-   * @param {number} [options.maximumAge=0] A positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device must return a cached position regardless of its age. Default: 0.
+   * @param {boolean} [options.enableHighAccuracy=false] A boolean value that indicates the application would like to receive the best possible results.
+   *  If true and if the device is able to provide a more accurate position, it will do so.
+   *  Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example).
+   *  On the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power. Default: false.
+   * @param {number} [options.timeout=Infinity] A positive long value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position.
+   *  The default value is Infinity, meaning that getCurrentPosition() won't return until the position is available.
+   * @param {number} [options.maximumAge=0] A positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return.
+   *  If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position.
+   *  If set to Infinity the device must return a cached position regardless of its age. Default: 0.
    * @static
    * @returns {Promise} User's current location
    */
diff --git a/src/ParseHooks.js b/src/ParseHooks.ts
similarity index 80%
rename from src/ParseHooks.js
rename to src/ParseHooks.ts
index 43375ba7a..313d089c2 100644
--- a/src/ParseHooks.js
+++ b/src/ParseHooks.ts
@@ -13,52 +13,52 @@ export function getTriggers() {
   return CoreManager.getHooksController().get('triggers');
 }
 
-export function getFunction(name) {
+export function getFunction(name: string) {
   return CoreManager.getHooksController().get('functions', name);
 }
 
-export function getTrigger(className, triggerName) {
+export function getTrigger(className: string, triggerName: string) {
   return CoreManager.getHooksController().get('triggers', className, triggerName);
 }
 
-export function createFunction(functionName, url) {
+export function createFunction(functionName: string, url: string) {
   return create({ functionName: functionName, url: url });
 }
 
-export function createTrigger(className, triggerName, url) {
+export function createTrigger(className: string, triggerName: string, url: string) {
   return create({ className: className, triggerName: triggerName, url: url });
 }
 
-export function create(hook) {
+export function create(hook: HookDeclaration) {
   return CoreManager.getHooksController().create(hook);
 }
 
-export function updateFunction(functionName, url) {
+export function updateFunction(functionName: string, url: string) {
   return update({ functionName: functionName, url: url });
 }
 
-export function updateTrigger(className, triggerName, url) {
+export function updateTrigger(className: string, triggerName: string, url: string) {
   return update({ className: className, triggerName: triggerName, url: url });
 }
 
-export function update(hook) {
+export function update(hook: HookDeclaration) {
   return CoreManager.getHooksController().update(hook);
 }
 
-export function removeFunction(functionName) {
+export function removeFunction(functionName: string) {
   return remove({ functionName: functionName });
 }
 
-export function removeTrigger(className, triggerName) {
+export function removeTrigger(className: string, triggerName: string) {
   return remove({ className: className, triggerName: triggerName });
 }
 
-export function remove(hook) {
+export function remove(hook: HookDeleteArg) {
   return CoreManager.getHooksController().remove(hook);
 }
 
 const DefaultController = {
-  get(type, functionName, triggerName) {
+  get(type: string, functionName?: string, triggerName?: string) {
     let url = '/hooks/' + type;
     if (functionName) {
       url += '/' + functionName;
@@ -111,7 +111,7 @@ const DefaultController = {
     return this.sendRequest('PUT', url, hook);
   },
 
-  sendRequest(method, url, body) {
+  sendRequest(method: string, url: string, body?: any) {
     return CoreManager.getRESTController()
       .request(method, url, body, { useMasterKey: true })
       .then(res => {
diff --git a/src/ParseObject.ts b/src/ParseObject.ts
index f00be9eef..0c3c9f4cd 100644
--- a/src/ParseObject.ts
+++ b/src/ParseObject.ts
@@ -1343,7 +1343,7 @@ class ParseObject {
     const unsaved = options.cascadeSave !== false ? unsavedChildren(this) : null;
     return controller.save(unsaved, saveOptions).then(() => {
       return controller.save(this, saveOptions);
-    });
+    }) as Promise as Promise;
   }
 
   /**
@@ -2210,11 +2210,11 @@ const DefaultController = {
       if (target.length < 1) {
         return Promise.resolve([]);
       }
-      const objs = [];
-      const ids = [];
-      let className = null;
-      const results = [];
-      let error = null;
+      const objs: ParseObject[] = [];
+      const ids: string[] = [];
+      let className: string | null = null;
+      const results: ParseObject[] = [];
+      let error: ParseError | null = null;
       target.forEach(el => {
         if (error) {
           return;
@@ -2232,7 +2232,7 @@ const DefaultController = {
           error = new ParseError(ParseError.MISSING_OBJECT_ID, 'All objects must have an ID');
         }
         if (forceFetch || !el.isDataAvailable()) {
-          ids.push(el.id);
+          ids.push(el.id!);
           objs.push(el);
         }
         results.push(el);
@@ -2385,7 +2385,7 @@ const DefaultController = {
     return Promise.resolve(target);
   },
 
-  save(target: ParseObject | null | Array, options: RequestOptions): Promise | ParseFile> {
+  save(target: ParseObject | null | Array, options: RequestOptions): Promise | ParseFile | undefined> {
     const batchSize =
       options && options.batchSize ? options.batchSize : CoreManager.get('REQUEST_BATCH_SIZE');
     const localDatastore = CoreManager.getLocalDatastore();
@@ -2404,13 +2404,14 @@ const DefaultController = {
 
       let unsaved = target.concat();
       for (let i = 0; i < target.length; i++) {
-        if (target[i] instanceof ParseObject) {
-          unsaved = unsaved.concat(unsavedChildren(target[i], true));
+        const target_i = target[i];
+        if (target_i instanceof ParseObject) {
+          unsaved = unsaved.concat(unsavedChildren(target_i, true));
         }
       }
       unsaved = unique(unsaved);
 
-      const filesSaved: Array = [];
+      const filesSaved: Array | undefined> = [];
       let pending: Array = [];
       unsaved.forEach(el => {
         if (el instanceof ParseFile) {
@@ -2558,7 +2559,7 @@ const DefaultController = {
         }
       );
     }
-    return Promise.resolve();
+    return Promise.resolve(undefined);
   },
 };
 
diff --git a/src/ParseQuery.js b/src/ParseQuery.ts
similarity index 94%
rename from src/ParseQuery.js
rename to src/ParseQuery.ts
index 2a26122a7..47a548624 100644
--- a/src/ParseQuery.js
+++ b/src/ParseQuery.ts
@@ -1,7 +1,3 @@
-/*
- * @flow
- */
-
 import CoreManager from './CoreManager';
 import encode from './encode';
 import { continueWhile } from './promiseUtils';
@@ -14,10 +10,29 @@ import { DEFAULT_PIN } from './LocalDatastoreUtils';
 import type LiveQuerySubscription from './LiveQuerySubscription';
 import type { RequestOptions, FullOptions } from './RESTController';
 
-type BatchOptions = FullOptions & { batchSize?: number };
+type BatchOptions = FullOptions & {
+  batchSize?: number
+  useMasterKey?: boolean,
+  sessionToken?: string,
+  context?: { [key: string]: any },
+  json?: boolean
+};
 
 export type WhereClause = {
-  [attr: string]: mixed,
+  [attr: string]: any,
+};
+
+type QueryOptions = {
+  useMasterKey?: boolean,
+  sessionToken?: string,
+  context?: { [key: string]: any },
+  json?: boolean,
+};
+
+type FullTextQueryOptions = {
+  language?: string,
+  caseSensitive?: boolean,
+  diacriticSensitive?: boolean,
 };
 
 export type QueryJSON = {
@@ -31,7 +46,7 @@ export type QueryJSON = {
   order?: string,
   className?: string,
   count?: number,
-  hint?: mixed,
+  hint?: any,
   explain?: boolean,
   readPreference?: string,
   includeReadPreference?: string,
@@ -60,8 +75,8 @@ function quote(s: string): string {
  * @private
  * @returns {string}
  */
-function _getClassNameFromQueries(queries: Array): ?string {
-  let className = null;
+function _getClassNameFromQueries(queries: Array): string | null {
+  let className: string | null = null;
   queries.forEach(q => {
     if (!className) {
       className = q.className;
@@ -234,13 +249,13 @@ class ParseQuery {
   _skip: number;
   _count: boolean;
   _order: Array;
-  _readPreference: string;
-  _includeReadPreference: string;
-  _subqueryReadPreference: string;
+  _readPreference: string | null;
+  _includeReadPreference: string | null;
+  _subqueryReadPreference: string | null;
   _queriesLocalDatastore: boolean;
   _localDatastorePinName: any;
-  _extraOptions: { [key: string]: mixed };
-  _hint: mixed;
+  _extraOptions: { [key: string]: any };
+  _hint: any;
   _explain: boolean;
   _xhrRequest: any;
   _comment: string;
@@ -258,10 +273,11 @@ class ParseQuery {
     } else if (objectClass instanceof ParseObject) {
       this.className = objectClass.className;
     } else if (typeof objectClass === 'function') {
-      if (typeof objectClass.className === 'string') {
-        this.className = objectClass.className;
+      const objClass = objectClass as any;
+      if (typeof objClass.className === 'string') {
+        this.className = objClass.className;
       } else {
-        const obj = new objectClass();
+        const obj = new objClass();
         this.className = obj.className;
       }
     } else {
@@ -341,7 +357,7 @@ class ParseQuery {
    * @param value
    * @returns {Parse.Query}
    */
-  _addCondition(key: string, condition: string, value: mixed): ParseQuery {
+  _addCondition(key: string, condition: string, value: any): ParseQuery {
     if (!this._where[key] || typeof this._where[key] === 'string') {
       this._where[key] = {};
     }
@@ -359,7 +375,7 @@ class ParseQuery {
     return '^' + quote(string);
   }
 
-  async _handleOfflineQuery(params: any) {
+  async _handleOfflineQuery(params: QueryJSON) {
     OfflineQuery.validateQuery(this);
     const localDatastore = CoreManager.getLocalDatastore();
     const objects = await localDatastore._serializeObjectsFromPinName(this._localDatastorePinName);
@@ -620,10 +636,10 @@ class ParseQuery {
    * @returns {Promise} A promise that is resolved with the result when
    * the query completes.
    */
-  get(objectId: string, options?: FullOptions): Promise {
+  get(objectId: string, options?: QueryOptions): Promise {
     this.equalTo('objectId', objectId);
 
-    const firstOptions = {};
+    const firstOptions: QueryOptions = {};
     if (options && options.hasOwnProperty('useMasterKey')) {
       firstOptions.useMasterKey = options.useMasterKey;
     }
@@ -662,10 +678,10 @@ class ParseQuery {
    * @returns {Promise} A promise that is resolved with the results when
    * the query completes.
    */
-  find(options?: FullOptions): Promise> {
+  find(options?: QueryOptions): Promise> {
     options = options || {};
 
-    const findOptions = {};
+    const findOptions: QueryOptions = {};
     if (options.hasOwnProperty('useMasterKey')) {
       findOptions.useMasterKey = options.useMasterKey;
     }
@@ -689,7 +705,7 @@ class ParseQuery {
       if (this._explain) {
         return response.results;
       }
-      const results = response.results.map(data => {
+      const results = response.results?.map(data => {
         // In cases of relations, the server may send back a className
         // on the top level of the payload
         const override = response.className || this.className;
@@ -713,7 +729,7 @@ class ParseQuery {
       const count = response.count;
 
       if (typeof count === 'number') {
-        return { results, count };
+        return { results, count } as any;
       } else {
         return results;
       }
@@ -755,10 +771,10 @@ class ParseQuery {
    * @returns {Promise} A promise that is resolved with the count when
    * the query completes.
    */
-  count(options?: FullOptions): Promise {
+  count(options?: { useMasterKey?: boolean, sessionToken?: string }): Promise {
     options = options || {};
 
-    const findOptions = {};
+    const findOptions: { useMasterKey?: boolean, sessionToken?: string } = {};
     if (options.hasOwnProperty('useMasterKey')) {
       findOptions.useMasterKey = options.useMasterKey;
     }
@@ -789,11 +805,10 @@ class ParseQuery {
    * 
    * @returns {Promise} A promise that is resolved with the query completes.
    */
-  distinct(key: string, options?: FullOptions): Promise> {
+  distinct(key: string, options?: { sessionToken?: string }): Promise> {
     options = options || {};
 
-    const distinctOptions = {};
-    distinctOptions.useMasterKey = true;
+    const distinctOptions: { sessionToken?: string, useMasterKey: boolean } = { useMasterKey: true};
 
     if (options.hasOwnProperty('sessionToken')) {
       distinctOptions.sessionToken = options.sessionToken;
@@ -807,7 +822,7 @@ class ParseQuery {
       hint: this._hint,
     };
     return controller.aggregate(this.className, params, distinctOptions).then(results => {
-      return results.results;
+      return results.results!;
     });
   }
 
@@ -821,10 +836,9 @@ class ParseQuery {
    * 
    * @returns {Promise} A promise that is resolved with the query completes.
    */
-  aggregate(pipeline: mixed, options?: FullOptions): Promise> {
+  aggregate(pipeline: any, options?: { sessionToken?: string }): Promise> {
     options = options || {};
-    const aggregateOptions = {};
-    aggregateOptions.useMasterKey = true;
+    const aggregateOptions: { sessionToken?: string, useMasterKey: boolean } = { useMasterKey: true };
 
     if (options.hasOwnProperty('sessionToken')) {
       aggregateOptions.sessionToken = options.sessionToken;
@@ -851,7 +865,7 @@ class ParseQuery {
       readPreference: this._readPreference,
     };
     return controller.aggregate(this.className, params, aggregateOptions).then(results => {
-      return results.results;
+      return results.results!;
     });
   }
 
@@ -871,10 +885,8 @@ class ParseQuery {
    * @returns {Promise} A promise that is resolved with the object when
    * the query completes.
    */
-  first(options?: FullOptions): Promise {
-    options = options || {};
-
-    const findOptions = {};
+  first(options: QueryOptions = {}): Promise {
+    const findOptions: QueryOptions = {};
     if (options.hasOwnProperty('useMasterKey')) {
       findOptions.useMasterKey = options.useMasterKey;
     }
@@ -903,7 +915,7 @@ class ParseQuery {
     }
 
     return controller.find(this.className, params, findOptions).then(response => {
-      const objects = response.results;
+      const objects = response.results!;
       if (!objects[0]) {
         return undefined;
       }
@@ -947,7 +959,7 @@ class ParseQuery {
    *     iteration has completed.
    */
   eachBatch(
-    callback: (objs: Array) => Promise<*>,
+    callback: (objs: Array) => void,
     options?: BatchOptions
   ): Promise {
     options = options || {};
@@ -985,7 +997,7 @@ class ParseQuery {
 
     query.ascending('objectId');
 
-    const findOptions = {};
+    const findOptions: BatchOptions = {};
     if (options.hasOwnProperty('useMasterKey')) {
       findOptions.useMasterKey = options.useMasterKey;
     }
@@ -1000,7 +1012,7 @@ class ParseQuery {
     }
 
     let finished = false;
-    let previousResults = [];
+    let previousResults: ParseObject[] = [];
     return continueWhile(
       () => {
         return !finished;
@@ -1061,7 +1073,7 @@ class ParseQuery {
    * @param {(string|object)} value String or Object of index that should be used when executing query
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  hint(value: mixed): ParseQuery {
+  hint(value: any): ParseQuery {
     if (typeof value === 'undefined') {
       delete this._hint;
     }
@@ -1109,7 +1121,7 @@ class ParseQuery {
     callback: (currentObject: ParseObject, index: number, query: ParseQuery) => any,
     options?: BatchOptions
   ): Promise> {
-    const array = [];
+    const array: ParseObject[] = [];
     let index = 0;
     await this.each(object => {
       return Promise.resolve(callback(object, index, this)).then(result => {
@@ -1197,7 +1209,7 @@ class ParseQuery {
     callback: (currentObject: ParseObject, index: number, query: ParseQuery) => boolean,
     options?: BatchOptions
   ): Promise> {
-    const array = [];
+    const array: ParseObject[] = [];
     let index = 0;
     await this.each(object => {
       return Promise.resolve(callback(object, index, this)).then(flag => {
@@ -1220,16 +1232,16 @@ class ParseQuery {
    * @param value The value that the Parse.Object must contain.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  equalTo(key: string | { [key: string]: any }, value: ?mixed): ParseQuery {
+  equalTo(key: string | { [key: string]: any }, value?: any): ParseQuery {
     if (key && typeof key === 'object') {
       Object.entries(key).forEach(([k, val]) => this.equalTo(k, val));
       return this;
     }
     if (typeof value === 'undefined') {
-      return this.doesNotExist(key);
+      return this.doesNotExist(key as string);
     }
 
-    this._where[key] = encode(value, false, true);
+    this._where[key as string] = encode(value, false, true);
     return this;
   }
 
@@ -1241,12 +1253,12 @@ class ParseQuery {
    * @param value The value that must not be equalled.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  notEqualTo(key: string | { [key: string]: any }, value: ?mixed): ParseQuery {
+  notEqualTo(key: string | { [key: string]: any }, value?: any): ParseQuery {
     if (key && typeof key === 'object') {
       Object.entries(key).forEach(([k, val]) => this.notEqualTo(k, val));
       return this;
     }
-    return this._addCondition(key, '$ne', value);
+    return this._addCondition(key as string, '$ne', value);
   }
 
   /**
@@ -1257,7 +1269,7 @@ class ParseQuery {
    * @param value The value that provides an upper bound.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  lessThan(key: string, value: mixed): ParseQuery {
+  lessThan(key: string, value: any): ParseQuery {
     return this._addCondition(key, '$lt', value);
   }
 
@@ -1269,7 +1281,7 @@ class ParseQuery {
    * @param value The value that provides an lower bound.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  greaterThan(key: string, value: mixed): ParseQuery {
+  greaterThan(key: string, value: any): ParseQuery {
     return this._addCondition(key, '$gt', value);
   }
 
@@ -1281,7 +1293,7 @@ class ParseQuery {
    * @param value The value that provides an upper bound.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  lessThanOrEqualTo(key: string, value: mixed): ParseQuery {
+  lessThanOrEqualTo(key: string, value: any): ParseQuery {
     return this._addCondition(key, '$lte', value);
   }
 
@@ -1293,7 +1305,7 @@ class ParseQuery {
    * @param {*} value The value that provides an lower bound.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  greaterThanOrEqualTo(key: string, value: mixed): ParseQuery {
+  greaterThanOrEqualTo(key: string, value: any): ParseQuery {
     return this._addCondition(key, '$gte', value);
   }
 
@@ -1305,7 +1317,7 @@ class ParseQuery {
    * @param {Array<*>} value The values that will match.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  containedIn(key: string, value: Array): ParseQuery {
+  containedIn(key: string, value: Array): ParseQuery {
     return this._addCondition(key, '$in', value);
   }
 
@@ -1317,7 +1329,7 @@ class ParseQuery {
    * @param {Array<*>} value The values that will not match.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  notContainedIn(key: string, value: Array): ParseQuery {
+  notContainedIn(key: string, value: Array): ParseQuery {
     return this._addCondition(key, '$nin', value);
   }
 
@@ -1329,7 +1341,7 @@ class ParseQuery {
    * @param {Array} values The values that will match.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  containedBy(key: string, values: Array): ParseQuery {
+  containedBy(key: string, values: Array): ParseQuery {
     return this._addCondition(key, '$containedBy', values);
   }
 
@@ -1341,7 +1353,7 @@ class ParseQuery {
    * @param {Array} values The values that will match.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  containsAll(key: string, values: Array): ParseQuery {
+  containsAll(key: string, values: Array): ParseQuery {
     return this._addCondition(key, '$all', values);
   }
 
@@ -1392,20 +1404,22 @@ class ParseQuery {
    * This may be slow for large datasets.
    *
    * @param {string} key The key that the string to match is stored in.
-   * @param {RegExp} regex The regular expression pattern to match.
+   * @param {RegExp | string} regex The regular expression pattern to match.
    * @param {string} modifiers The regular expression mode.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  matches(key: string, regex: RegExp, modifiers: string): ParseQuery {
+  matches(key: string, regex: RegExp | string, modifiers: string): ParseQuery {
     this._addCondition(key, '$regex', regex);
     if (!modifiers) {
       modifiers = '';
     }
-    if (regex.ignoreCase) {
-      modifiers += 'i';
-    }
-    if (regex.multiline) {
-      modifiers += 'm';
+    if (typeof regex !== 'string') {
+      if (regex.ignoreCase) {
+        modifiers += 'i';
+      }
+      if (regex.multiline) {
+        modifiers += 'm';
+      }
     }
     if (modifiers.length) {
       this._addCondition(key, '$options', modifiers);
@@ -1527,7 +1541,7 @@ class ParseQuery {
    * @param {boolean} options.diacriticSensitive A boolean flag to enable or disable diacritic sensitive search.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  fullText(key: string, value: string, options: ?Object): ParseQuery {
+  fullText(key: string, value: string, options: FullTextQueryOptions = {}): ParseQuery {
     options = options || {};
 
     if (!key) {
@@ -1540,7 +1554,7 @@ class ParseQuery {
       throw new Error('The value being searched for must be a string.');
     }
 
-    const fullOptions = {};
+    const fullOptions: { $term?: string, $language?: string, $caseSensitive?: boolean, $diacriticSensitive?: boolean } = {};
     fullOptions.$term = value;
 
     for (const option in options) {
@@ -1972,8 +1986,8 @@ class ParseQuery {
     subqueryReadPreference?: string
   ): ParseQuery {
     this._readPreference = readPreference;
-    this._includeReadPreference = includeReadPreference;
-    this._subqueryReadPreference = subqueryReadPreference;
+    this._includeReadPreference = includeReadPreference || null;
+    this._subqueryReadPreference = subqueryReadPreference || null;
     return this;
   }
 
@@ -1987,13 +2001,13 @@ class ParseQuery {
   async subscribe(sessionToken?: string): Promise {
     const currentUser = await CoreManager.getUserController().currentUserAsync();
     if (!sessionToken) {
-      sessionToken = currentUser ? currentUser.getSessionToken() : undefined;
+      sessionToken = currentUser ? currentUser.getSessionToken() || undefined : undefined;
     }
     const liveQueryClient = await CoreManager.getLiveQueryController().getDefaultLiveQueryClient();
     if (liveQueryClient.shouldOpen()) {
       liveQueryClient.open();
     }
-    const subscription = liveQueryClient.subscribe(this, sessionToken);
+    const subscription = liveQueryClient.subscribe(this, sessionToken!);
     return subscription.subscribePromise.then(() => {
       return subscription;
     });
@@ -2013,7 +2027,7 @@ class ParseQuery {
    */
   static or(...queries: Array): ParseQuery {
     const className = _getClassNameFromQueries(queries);
-    const query = new ParseQuery(className);
+    const query = new ParseQuery(className!);
     query._orQuery(queries);
     return query;
   }
@@ -2032,7 +2046,7 @@ class ParseQuery {
    */
   static and(...queries: Array): ParseQuery {
     const className = _getClassNameFromQueries(queries);
-    const query = new ParseQuery(className);
+    const query = new ParseQuery(className!);
     query._andQuery(queries);
     return query;
   }
@@ -2051,7 +2065,7 @@ class ParseQuery {
    */
   static nor(...queries: Array): ParseQuery {
     const className = _getClassNameFromQueries(queries);
-    const query = new ParseQuery(className);
+    const query = new ParseQuery(className!);
     query._norQuery(queries);
     return query;
   }
@@ -2091,7 +2105,7 @@ class ParseQuery {
    * @param {string} name The name of query source.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
    */
-  fromPinWithName(name?: string): ParseQuery {
+  fromPinWithName(name?: string | null): ParseQuery {
     const localDatastore = CoreManager.getLocalDatastore();
     if (localDatastore.checkIfEnabled()) {
       this._queriesLocalDatastore = true;
@@ -2113,7 +2127,8 @@ class ParseQuery {
       this._xhrRequest.onchange = () => {};
       return this;
     }
-    return (this._xhrRequest.onchange = () => this.cancel());
+    this._xhrRequest.onchange = () => this.cancel();
+    return this;
   }
 
   _setRequestTask(options) {
@@ -2125,7 +2140,7 @@ class ParseQuery {
 
   /**
    * Sets a comment to the query so that the query
-   *can be identified when using a the profiler for MongoDB.
+   * can be identified when using a the profiler for MongoDB.
    *
    * @param {string} value a comment can make your profile data easier to interpret and trace.
    * @returns {Parse.Query} Returns the query, so you can chain this call.
@@ -2144,12 +2159,12 @@ class ParseQuery {
 }
 
 const DefaultController = {
-  find(className: string, params: QueryJSON, options: RequestOptions): Promise> {
+  find(className: string, params: QueryJSON, options: RequestOptions): Promise<{ results: Array }> {
     const RESTController = CoreManager.getRESTController();
     return RESTController.request('GET', 'classes/' + className, params, options);
   },
 
-  aggregate(className: string, params: any, options: RequestOptions): Promise> {
+  aggregate(className: string, params: any, options: RequestOptions): Promise<{ results: Array }> {
     const RESTController = CoreManager.getRESTController();
 
     return RESTController.request('GET', 'aggregate/' + className, params, options);
diff --git a/src/ParseRole.js b/src/ParseRole.ts
similarity index 94%
rename from src/ParseRole.js
rename to src/ParseRole.ts
index 546a28577..67e5a5b31 100644
--- a/src/ParseRole.js
+++ b/src/ParseRole.ts
@@ -1,7 +1,3 @@
-/**
- * @flow
- */
-
 import CoreManager from './CoreManager';
 import ParseACL from './ParseACL';
 import ParseError from './ParseError';
@@ -43,7 +39,7 @@ class ParseRole extends ParseObject {
    *
    * @returns {string} the name of the role.
    */
-  getName(): ?string {
+  getName(): string | null {
     const name = this.get('name');
     if (name == null || typeof name === 'string') {
       return name;
@@ -68,7 +64,7 @@ class ParseRole extends ParseObject {
    *     callbacks.
    * @returns {(ParseObject|boolean)} true if the set succeeded.
    */
-  setName(name: string, options?: mixed): ParseObject | boolean {
+  setName(name: string, options?: any): ParseObject | boolean {
     this._validateName(name);
     return this.set('name', name, options);
   }
@@ -115,8 +111,8 @@ class ParseRole extends ParseObject {
     }
   }
 
-  validate(attrs: AttributeMap, options?: mixed): ParseError | boolean {
-    const isInvalid = super.validate(attrs, options);
+  validate(attrs: AttributeMap, options?: any): ParseError | boolean {
+    const isInvalid = (super.validate as typeof this['validate'])(attrs, options);
     if (isInvalid) {
       return isInvalid;
     }
diff --git a/src/ParseUser.js b/src/ParseUser.ts
similarity index 95%
rename from src/ParseUser.js
rename to src/ParseUser.ts
index 328512452..48a0c2a66 100644
--- a/src/ParseUser.js
+++ b/src/ParseUser.ts
@@ -1,25 +1,28 @@
-/**
- * @flow
- */
-
 import CoreManager from './CoreManager';
 import isRevocableSession from './isRevocableSession';
 import ParseError from './ParseError';
 import ParseObject from './ParseObject';
-import ParseSession from './ParseSession';
 import Storage from './Storage';
 
 import type { AttributeMap } from './ObjectStateMutations';
 import type { RequestOptions, FullOptions } from './RESTController';
 
-export type AuthData = ?{ [key: string]: mixed };
-
+export type AuthData = { [key: string]: any };
+export type AuthProviderType = {
+  authenticate?(options: {
+    error?: (provider: AuthProviderType, error: string | any) => void,
+    success?: (provider: AuthProviderType, result: AuthData) => void,
+  }): void,
+  restoreAuthentication(authData: any): boolean;
+  getAuthType(): string;
+  deauthenticate?(): void;
+};
 const CURRENT_USER_KEY = 'currentUser';
 let canUseCurrentUser = !CoreManager.get('IS_NODE');
 let currentUserCacheMatchesDisk = false;
-let currentUserCache = null;
+let currentUserCache: ParseUser | null = null;
 
-const authProviders = {};
+const authProviders: { [key: string]: AuthProviderType } = {};
 
 /**
  * 

A Parse.User object is a local representation of a user persisted to the @@ -35,7 +38,7 @@ class ParseUser extends ParseObject { /** * @param {object} attributes The initial set of data to store in the user. */ - constructor(attributes: ?AttributeMap) { + constructor(attributes?: AttributeMap) { super('_User'); if (attributes && typeof attributes === 'object') { if (!this.set(attributes || {})) { @@ -54,7 +57,7 @@ class ParseUser extends ParseObject { _upgradeToRevocableSession(options: RequestOptions): Promise { options = options || {}; - const upgradeOptions = {}; + const upgradeOptions: RequestOptions = {}; if (options.hasOwnProperty('useMasterKey')) { upgradeOptions.useMasterKey = options.useMasterKey; } @@ -79,9 +82,9 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled with the user is linked */ linkWith( - provider: any, + provider: AuthProviderType, options: { authData?: AuthData }, - saveOpts?: FullOptions = {} + saveOpts: FullOptions = {} ): Promise { saveOpts.sessionToken = saveOpts.sessionToken || this.getSessionToken() || ''; let authType; @@ -123,7 +126,7 @@ class ParseUser extends ParseObject { return new Promise((resolve, reject) => { provider.authenticate({ success: (provider, result) => { - const opts = {}; + const opts: { authData?: AuthData } = {}; opts.authData = result; this.linkWith(provider, opts, saveOpts).then( () => { @@ -152,7 +155,7 @@ class ParseUser extends ParseObject { _linkWith( provider: any, options: { authData?: AuthData }, - saveOpts?: FullOptions = {} + saveOpts: FullOptions = {} ): Promise { return this.linkWith(provider, options, saveOpts); } @@ -163,7 +166,7 @@ class ParseUser extends ParseObject { * * @param provider */ - _synchronizeAuthData(provider: string) { + _synchronizeAuthData(provider: string | AuthProviderType) { if (!this.isCurrent() || !provider) { return; } @@ -336,7 +339,7 @@ class ParseUser extends ParseObject { * * @returns {string} */ - getUsername(): ?string { + getUsername(): string | null { const username = this.get('username'); if (username == null || typeof username === 'string') { return username; @@ -368,7 +371,7 @@ class ParseUser extends ParseObject { * * @returns {string} User's Email */ - getEmail(): ?string { + getEmail(): string | null { const email = this.get('email'); if (email == null || typeof email === 'string') { return email; @@ -393,7 +396,7 @@ class ParseUser extends ParseObject { * * @returns {string} the session token, or undefined */ - getSessionToken(): ?string { + getSessionToken(): string | null{ const token = this.get('sessionToken'); if (token == null || typeof token === 'string') { return token; @@ -424,10 +427,10 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled when the signup * finishes. */ - signUp(attrs: AttributeMap, options?: FullOptions): Promise { + signUp(attrs: AttributeMap, options?: FullOptions & { context?: AttributeMap }): Promise { options = options || {}; - const signupOptions = {}; + const signupOptions: FullOptions & { context?: AttributeMap } = {}; if (options.hasOwnProperty('useMasterKey')) { signupOptions.useMasterKey = options.useMasterKey; } @@ -456,10 +459,10 @@ class ParseUser extends ParseObject { * @returns {Promise} A promise that is fulfilled with the user when * the login is complete. */ - logIn(options?: FullOptions): Promise { + logIn(options: FullOptions & { context?: AttributeMap } = {}): Promise { options = options || {}; - const loginOptions = { usePost: true }; + const loginOptions: FullOptions & { context?: AttributeMap } = { usePost: true }; if (options.hasOwnProperty('useMasterKey')) { loginOptions.useMasterKey = options.useMasterKey; } @@ -486,11 +489,11 @@ class ParseUser extends ParseObject { * @param {...any} args * @returns {Promise} */ - async save(...args: Array): Promise { + async save(...args: Array): Promise { await super.save.apply(this, args); const current = await this.isCurrentAsync(); if (current) { - return CoreManager.getUserController().updateUserOnDisk(this); + return CoreManager.getUserController().updateUserOnDisk(this) as Promise; } return this; } @@ -502,7 +505,7 @@ class ParseUser extends ParseObject { * @param {...any} args * @returns {Parse.User} */ - async destroy(...args: Array): Promise { + async destroy(...args: Array): Promise { await super.destroy.apply(this, args); const current = await this.isCurrentAsync(); if (current) { @@ -607,7 +610,7 @@ class ParseUser extends ParseObject { * @static * @returns {Parse.Object} The currently logged in Parse.User. */ - static current(): ?ParseUser { + static current(): ParseUser | null { if (!canUseCurrentUser) { return null; } @@ -622,7 +625,7 @@ class ParseUser extends ParseObject { * @returns {Promise} A Promise that is resolved with the currently * logged in Parse User */ - static currentAsync(): Promise { + static currentAsync(): Promise { if (!canUseCurrentUser) { return Promise.resolve(null); } @@ -759,7 +762,7 @@ class ParseUser extends ParseObject { * @static * @returns {Promise} A promise that is fulfilled with the user is fetched. */ - static me(sessionToken: string, options?: RequestOptions = {}) { + static me(sessionToken: string, options: RequestOptions = {}) { const controller = CoreManager.getUserController(); const meOptions: RequestOptions = { sessionToken: sessionToken, @@ -834,7 +837,7 @@ class ParseUser extends ParseObject { static requestPasswordReset(email: string, options?: RequestOptions) { options = options || {}; - const requestOptions = {}; + const requestOptions: RequestOptions = {}; if (options.hasOwnProperty('useMasterKey')) { requestOptions.useMasterKey = options.useMasterKey; } @@ -855,7 +858,7 @@ class ParseUser extends ParseObject { static requestEmailVerification(email: string, options?: RequestOptions) { options = options || {}; - const requestOptions = {}; + const requestOptions: RequestOptions = {}; if (options.hasOwnProperty('useMasterKey')) { requestOptions.useMasterKey = options.useMasterKey; } @@ -1027,7 +1030,7 @@ const DefaultController = { return DefaultController.updateUserOnDisk(user); }, - currentUser(): ?ParseUser { + currentUser(): ParseUser | null{ if (currentUserCache) { return currentUserCache; } @@ -1065,13 +1068,13 @@ const DefaultController = { userData.sessionToken = userData._sessionToken; delete userData._sessionToken; } - const current = ParseObject.fromJSON(userData); + const current = ParseObject.fromJSON(userData) as ParseUser; currentUserCache = current; current._synchronizeAllAuthData(); return current; }, - currentUserAsync(): Promise { + currentUserAsync(): Promise { if (currentUserCache) { return Promise.resolve(currentUserCache); } @@ -1103,7 +1106,7 @@ const DefaultController = { userData.sessionToken = userData._sessionToken; delete userData._sessionToken; } - const current = ParseObject.fromJSON(userData); + const current = ParseObject.fromJSON(userData) as ParseUser; currentUserCache = current; current._synchronizeAllAuthData(); return Promise.resolve(current); @@ -1201,7 +1204,7 @@ const DefaultController = { }); }, - logOut(options: RequestOptions): Promise { + logOut(options: RequestOptions): Promise { const RESTController = CoreManager.getRESTController(); if (options.sessionToken) { return RESTController.request('POST', 'logout', {}, options); @@ -1243,9 +1246,7 @@ const DefaultController = { const RESTController = CoreManager.getRESTController(); const result = await RESTController.request('POST', 'upgradeToRevocableSession', {}, options); - const session = new ParseSession(); - session._finishFetch(result); - user._finishFetch({ sessionToken: session.getSessionToken() }); + user._finishFetch({ sessionToken: result?.sessionToken || '' }); const current = await user.isCurrentAsync(); if (current) { return DefaultController.setCurrentUser(user); diff --git a/src/Push.js b/src/Push.ts similarity index 92% rename from src/Push.js rename to src/Push.ts index a565396be..2c0581921 100644 --- a/src/Push.js +++ b/src/Push.ts @@ -1,10 +1,7 @@ -/** - * @flow - */ - import CoreManager from './CoreManager'; import ParseQuery from './ParseQuery'; +import type ParseObject from './ParseObject'; import type { WhereClause } from './ParseQuery'; import type { FullOptions } from './RESTController'; @@ -49,9 +46,9 @@ export type PushData = { * be used for this request. * * @returns {Promise} A promise that is fulfilled when the push request - * completes. + * completes and returns `pushStatusId`. */ -export function send(data: PushData, options?: FullOptions = {}): Promise { +export function send(data: PushData, options: FullOptions = {}): Promise { if (data.where && data.where instanceof ParseQuery) { data.where = data.where.toJSON().where; } @@ -89,7 +86,7 @@ export function send(data: PushData, options?: FullOptions = {}): Promise { * * @returns {Parse.Object} Status of Push. */ -export function getPushStatus(pushStatusId: string, options?: FullOptions = {}): Promise { +export function getPushStatus(pushStatusId: string, options: FullOptions = {}): Promise { const pushOptions = { useMasterKey: true }; if (options.hasOwnProperty('useMasterKey')) { pushOptions.useMasterKey = options.useMasterKey; diff --git a/src/TaskQueue.js b/src/TaskQueue.ts similarity index 83% rename from src/TaskQueue.js rename to src/TaskQueue.ts index eedd769fe..0d14c32d4 100644 --- a/src/TaskQueue.js +++ b/src/TaskQueue.ts @@ -1,11 +1,8 @@ -/** - * @flow - */ import { resolvingPromise } from './promiseUtils'; type Task = { - task: () => Promise, - _completion: Promise, + task: () => Promise, + _completion: any, }; class TaskQueue { @@ -15,8 +12,8 @@ class TaskQueue { this.queue = []; } - enqueue(task: () => Promise): Promise { - const taskComplete = new resolvingPromise(); + enqueue(task: () => Promise): Promise { + const taskComplete = resolvingPromise(); this.queue.push({ task: task, _completion: taskComplete, @@ -55,3 +52,4 @@ class TaskQueue { } module.exports = TaskQueue; +export default TaskQueue; diff --git a/tsconfig.json b/tsconfig.json index b5166cc62..1b20e1a56 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,6 +2,7 @@ "compilerOptions": { "module": "commonjs", "target": "es2015", + "lib": ["dom"], "declaration": true, "emitDeclarationOnly": true, "outDir": "types", diff --git a/types/CoreManager.d.ts b/types/CoreManager.d.ts index dcf8cfcf4..d2bbd484f 100644 --- a/types/CoreManager.d.ts +++ b/types/CoreManager.d.ts @@ -60,7 +60,7 @@ type InstallationController = { }; type ObjectController = { fetch: (object: ParseObject | Array, forceFetch: boolean, options: RequestOptions) => Promise | ParseObject | undefined>; - save: (object: ParseObject | Array | null, options: RequestOptions) => Promise | ParseFile>; + save: (object: ParseObject | Array | null, options: RequestOptions) => Promise | ParseFile | undefined>; destroy: (object: ParseObject | Array, options: RequestOptions) => Promise>; }; type ObjectStateController = { diff --git a/types/ObjectStateMutations.d.ts b/types/ObjectStateMutations.d.ts index c82bd0d6c..7a2086d80 100644 --- a/types/ObjectStateMutations.d.ts +++ b/types/ObjectStateMutations.d.ts @@ -1,28 +1,28 @@ -// @ts-nocheck -export function defaultState(): State; -export function setServerData(serverData: AttributeMap, attributes: AttributeMap): void; -export function setPendingOp(pendingOps: Array, attr: string, op: Op | null): void; -export function pushPendingState(pendingOps: Array): void; -export function popPendingState(pendingOps: Array): OpsMap; -export function mergeFirstPendingState(pendingOps: Array): void; -export function estimateAttribute(serverData: AttributeMap, pendingOps: Array, className: string, id: string | null, attr: string): mixed; -export function estimateAttributes(serverData: AttributeMap, pendingOps: Array, className: string, id: string | null): AttributeMap; -export function commitServerChanges(serverData: AttributeMap, objectCache: ObjectCache, changes: AttributeMap): void; -type AttributeMap = { +import TaskQueue from './TaskQueue'; +import type { Op } from './ParseOp'; +import type ParseObject from './ParseObject'; +export type AttributeMap = { [attr: string]: any; }; -type OpsMap = { +export type OpsMap = { [attr: string]: Op; }; -type ObjectCache = { +export type ObjectCache = { [attr: string]: string; }; -type State = { +export type State = { serverData: AttributeMap; - pendingOps: OpsMap[]; + pendingOps: Array; objectCache: ObjectCache; tasks: TaskQueue; existed: boolean; }; -import { Op } from './ParseOp'; -export {}; +export declare function defaultState(): State; +export declare function setServerData(serverData: AttributeMap, attributes: AttributeMap): void; +export declare function setPendingOp(pendingOps: Array, attr: string, op?: Op): void; +export declare function pushPendingState(pendingOps: Array): void; +export declare function popPendingState(pendingOps: Array): OpsMap; +export declare function mergeFirstPendingState(pendingOps: Array): void; +export declare function estimateAttribute(serverData: AttributeMap, pendingOps: Array, object: ParseObject, attr: string): any; +export declare function estimateAttributes(serverData: AttributeMap, pendingOps: Array, object: ParseObject): AttributeMap; +export declare function commitServerChanges(serverData: AttributeMap, objectCache: ObjectCache, changes: AttributeMap): void; diff --git a/types/Parse.d.ts b/types/Parse.d.ts index ecb89e504..407bdb7c2 100644 --- a/types/Parse.d.ts +++ b/types/Parse.d.ts @@ -32,7 +32,7 @@ import LiveQueryClient from './LiveQueryClient'; * @global * @class * @hideconstructor -*/ + */ interface ParseType { ACL: typeof ACL; Parse?: ParseType; diff --git a/types/ParseFile.d.ts b/types/ParseFile.d.ts index 704384901..ce3a09942 100644 --- a/types/ParseFile.d.ts +++ b/types/ParseFile.d.ts @@ -1,18 +1,32 @@ -// @ts-nocheck -type FileSource = { - format: "file"; +import type { FullOptions } from './RESTController'; +type Base64 = { + base64: string; +}; +type Uri = { + uri: string; +}; +type FileData = Array | Base64 | Blob | Uri; +export type FileSaveOptions = FullOptions & { + metadata?: { + [key: string]: any; + }; + tags?: { + [key: string]: any; + }; +}; +export type FileSource = { + format: 'file'; file: Blob; type: string; } | { - format: "base64"; + format: 'base64'; base64: string; type: string; } | { - format: "uri"; + format: 'uri'; uri: string; type: string; }; -export default ParseFile; /** * A Parse.File is a local representation of a file that is saved to the Parse * cloud. @@ -20,8 +34,14 @@ export default ParseFile; * @alias Parse.File */ declare class ParseFile { - static fromJSON(obj: any): ParseFile; - static encodeBase64(bytes: Array): string; + _name: string; + _url?: string; + _source: FileSource; + _previousSave?: Promise; + _data?: string; + _requestTask?: any; + _metadata?: Object; + _tags?: Object; /** * @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 @@ -53,14 +73,6 @@ declare class ParseFile { * @param tags {Object} Optional key value pairs to be stored with file object */ constructor(name: string, data?: FileData, type?: string, metadata?: Object, tags?: Object); - _name: string; - _url: string | null; - _source: FileSource; - _previousSave: Promise | null; - _data: string | null; - _requestTask: any | null; - _metadata: Object | null; - _tags: Object | null; /** * 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. @@ -68,7 +80,7 @@ declare class ParseFile { * * @returns {Promise} Promise that is resolve with base64 data */ - getData(): Promise; + getData(): Promise; /** * Gets the name of the file. Before save is called, this is the filename * given by the user. After save is called, that name gets prefixed with a @@ -86,7 +98,7 @@ declare class ParseFile { */ url(options?: { forceSecure?: boolean; - }): string | null; + }): string | undefined; /** * Gets the metadata of the file. * @@ -122,7 +134,7 @@ declare class ParseFile { * * @returns {Promise | undefined} Promise that is resolved when the save finishes. */ - save(options?: FullOptions): Promise | null; + save(options?: FileSaveOptions): Promise | undefined; /** * Aborts the request if it has already been sent. */ @@ -138,12 +150,13 @@ declare class ParseFile { *

      * @returns {Promise} Promise that is resolved when the delete finishes.
      */
-    destroy(options?: FullOptions): Promise;
+    destroy(options?: FullOptions): Promise;
     toJSON(): {
-        name: string | null;
-        url: string | null;
+        __type: 'File';
+        name?: string;
+        url?: string;
     };
-    equals(other: mixed): boolean;
+    equals(other: any): boolean;
     /**
      * Sets metadata to be saved with file object. Overwrites existing metadata
      *
@@ -170,12 +183,7 @@ declare class ParseFile {
      * @param {*} value tag
      */
     addTag(key: string, value: string): void;
+    static fromJSON(obj: any): ParseFile;
+    static encodeBase64(bytes: Array | Uint8Array): string;
 }
-import { FullOptions } from './RESTController';
-type FileData = number[] | Blob | Base64 | Uri;
-type Base64 = {
-    base64: string;
-};
-type Uri = {
-    uri: string;
-};
+export default ParseFile;
diff --git a/types/ParseGeoPoint.d.ts b/types/ParseGeoPoint.d.ts
index a48a469d9..8ca122d5a 100644
--- a/types/ParseGeoPoint.d.ts
+++ b/types/ParseGeoPoint.d.ts
@@ -87,9 +87,15 @@ declare class ParseGeoPoint {
      * Creates a GeoPoint with the user's current location, if available.
      *
      * @param {object} options The options.
-     * @param {boolean} [options.enableHighAccuracy=false] A boolean value that indicates the application would like to receive the best possible results. If true and if the device is able to provide a more accurate position, it will do so. Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example). On the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power. Default: false.
-     * @param {number} [options.timeout=Infinity] A positive long value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position. The default value is Infinity, meaning that getCurrentPosition() won't return until the position is available.
-     * @param {number} [options.maximumAge=0] A positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device must return a cached position regardless of its age. Default: 0.
+     * @param {boolean} [options.enableHighAccuracy=false] A boolean value that indicates the application would like to receive the best possible results.
+     *  If true and if the device is able to provide a more accurate position, it will do so.
+     *  Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example).
+     *  On the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power. Default: false.
+     * @param {number} [options.timeout=Infinity] A positive long value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position.
+     *  The default value is Infinity, meaning that getCurrentPosition() won't return until the position is available.
+     * @param {number} [options.maximumAge=0] A positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return.
+     *  If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position.
+     *  If set to Infinity the device must return a cached position regardless of its age. Default: 0.
      * @static
      * @returns {Promise} User's current location
      */
diff --git a/types/ParseHooks.d.ts b/types/ParseHooks.d.ts
new file mode 100644
index 000000000..e854b0d76
--- /dev/null
+++ b/types/ParseHooks.d.ts
@@ -0,0 +1,27 @@
+export type HookDeclaration = {
+    functionName: string;
+    url: string;
+} | {
+    className: string;
+    triggerName: string;
+    url: string;
+};
+export type HookDeleteArg = {
+    functionName: string;
+} | {
+    className: string;
+    triggerName: string;
+};
+export declare function getFunctions(): Promise;
+export declare function getTriggers(): Promise;
+export declare function getFunction(name: string): Promise;
+export declare function getTrigger(className: string, triggerName: string): Promise;
+export declare function createFunction(functionName: string, url: string): Promise;
+export declare function createTrigger(className: string, triggerName: string, url: string): Promise;
+export declare function create(hook: HookDeclaration): Promise;
+export declare function updateFunction(functionName: string, url: string): Promise;
+export declare function updateTrigger(className: string, triggerName: string, url: string): Promise;
+export declare function update(hook: HookDeclaration): Promise;
+export declare function removeFunction(functionName: string): Promise;
+export declare function removeTrigger(className: string, triggerName: string): Promise;
+export declare function remove(hook: HookDeleteArg): Promise;
diff --git a/types/ParseObject.d.ts b/types/ParseObject.d.ts
index 56fbcd11c..00c400d14 100644
--- a/types/ParseObject.d.ts
+++ b/types/ParseObject.d.ts
@@ -1,5 +1,6 @@
 import ParseACL from './ParseACL';
 import ParseError from './ParseError';
+import ParseFile from './ParseFile';
 import { Op } from './ParseOp';
 import ParseRelation from './ParseRelation';
 import type { AttributeMap, OpsMap } from './ObjectStateMutations';
@@ -824,7 +825,7 @@ declare class ParseObject {
      * @static
      * @returns {Parse.Object[]}
      */
-    static saveAll(list: Array, options?: SaveOptions): Promise;
+    static saveAll(list: Array, options?: SaveOptions): Promise;
     /**
      * Creates a reference to a subclass of Parse.Object with the given id. This
      * does not exist on Parse.Object, only on subclasses.
diff --git a/types/ParseQuery.d.ts b/types/ParseQuery.d.ts
index 60b0bbb5e..0892a5bc0 100644
--- a/types/ParseQuery.d.ts
+++ b/types/ParseQuery.d.ts
@@ -1,8 +1,33 @@
-// @ts-nocheck
-type WhereClause = {
-    [attr: string]: mixed;
+import ParseGeoPoint from './ParseGeoPoint';
+import ParseObject from './ParseObject';
+import type LiveQuerySubscription from './LiveQuerySubscription';
+import type { FullOptions } from './RESTController';
+type BatchOptions = FullOptions & {
+    batchSize?: number;
+    useMasterKey?: boolean;
+    sessionToken?: string;
+    context?: {
+        [key: string]: any;
+    };
+    json?: boolean;
+};
+export type WhereClause = {
+    [attr: string]: any;
+};
+type QueryOptions = {
+    useMasterKey?: boolean;
+    sessionToken?: string;
+    context?: {
+        [key: string]: any;
+    };
+    json?: boolean;
 };
-type QueryJSON = {
+type FullTextQueryOptions = {
+    language?: string;
+    caseSensitive?: boolean;
+    diacriticSensitive?: boolean;
+};
+export type QueryJSON = {
     where: WhereClause;
     watch?: string;
     include?: string;
@@ -13,14 +38,13 @@ type QueryJSON = {
     order?: string;
     className?: string;
     count?: number;
-    hint?: mixed;
+    hint?: any;
     explain?: boolean;
     readPreference?: string;
     includeReadPreference?: string;
     subqueryReadPreference?: string;
-    comment?: string,
+    comment?: string;
 };
-export default ParseQuery;
 /**
  * Creates a new parse Parse.Query for the given Parse.Object subclass.
  *
@@ -65,58 +89,6 @@ export default ParseQuery;
  * @alias Parse.Query
  */
 declare class ParseQuery {
-    /**
-     * Static method to restore Parse.Query by json representation
-     * Internally calling Parse.Query.withJSON
-     *
-     * @param {string} className
-     * @param {QueryJSON} json from Parse.Query.toJSON() method
-     * @returns {Parse.Query} new created query
-     */
-    static fromJSON(className: string, json: QueryJSON): ParseQuery;
-    /**
-     * Constructs a Parse.Query that is the OR of the passed in queries.  For
-     * example:
-     * 
var compoundQuery = Parse.Query.or(query1, query2, query3);
- * - * will create a compoundQuery that is an or of the query1, query2, and - * query3. - * - * @param {...Parse.Query} queries The list of queries to OR. - * @static - * @returns {Parse.Query} The query that is the OR of the passed in queries. - */ - static or(...queries: Array): ParseQuery; - /** - * Constructs a Parse.Query that is the AND of the passed in queries. For - * example: - *
var compoundQuery = Parse.Query.and(query1, query2, query3);
- * - * will create a compoundQuery that is an and of the query1, query2, and - * query3. - * - * @param {...Parse.Query} queries The list of queries to AND. - * @static - * @returns {Parse.Query} The query that is the AND of the passed in queries. - */ - static and(...queries: Array): ParseQuery; - /** - * Constructs a Parse.Query that is the NOR of the passed in queries. For - * example: - *
const compoundQuery = Parse.Query.nor(query1, query2, query3);
- * - * will create a compoundQuery that is a nor of the query1, query2, and - * query3. - * - * @param {...Parse.Query} queries The list of queries to NOR. - * @static - * @returns {Parse.Query} The query that is the NOR of the passed in queries. - */ - static nor(...queries: Array): ParseQuery; - /** - * @param {(string | Parse.Object)} objectClass An instance of a subclass of Parse.Object, or a Parse className string. - */ - constructor(objectClass: string | ParseObject); /** * @property {string} className */ @@ -130,18 +102,22 @@ declare class ParseQuery { _skip: number; _count: boolean; _order: Array; - _readPreference: string; - _includeReadPreference: string; - _subqueryReadPreference: string; + _readPreference: string | null; + _includeReadPreference: string | null; + _subqueryReadPreference: string | null; _queriesLocalDatastore: boolean; _localDatastorePinName: any; _extraOptions: { - [key: string]: mixed; + [key: string]: any; }; - _hint: mixed; + _hint: any; _explain: boolean; _xhrRequest: any; _comment: string; + /** + * @param {(string | Parse.Object)} objectClass An instance of a subclass of Parse.Object, or a Parse className string. + */ + constructor(objectClass: string | ParseObject); /** * Adds constraint that at least one of the passed in queries matches. * @@ -171,7 +147,7 @@ declare class ParseQuery { * @param value * @returns {Parse.Query} */ - _addCondition(key: string, condition: string, value: mixed): ParseQuery; + _addCondition(key: string, condition: string, value: any): ParseQuery; /** * Converts string for regular expression at the beginning * @@ -179,7 +155,7 @@ declare class ParseQuery { * @returns {string} */ _regexStartWith(string: string): string; - _handleOfflineQuery(params: any): Promise; + _handleOfflineQuery(params: QueryJSON): Promise; /** * Returns a JSON representation of this query. * @@ -208,6 +184,15 @@ declare class ParseQuery { * @returns {Parse.Query} Returns the query, so you can chain this call. */ withJSON(json: QueryJSON): ParseQuery; + /** + * Static method to restore Parse.Query by json representation + * Internally calling Parse.Query.withJSON + * + * @param {string} className + * @param {QueryJSON} json from Parse.Query.toJSON() method + * @returns {Parse.Query} new created query + */ + static fromJSON(className: string, json: QueryJSON): ParseQuery; /** * Constructs a Parse.Object whose id is already known by fetching data from * the server. Unlike the first method, it never returns undefined. @@ -225,7 +210,7 @@ declare class ParseQuery { * @returns {Promise} A promise that is resolved with the result when * the query completes. */ - get(objectId: string, options?: FullOptions): Promise; + get(objectId: string, options?: QueryOptions): Promise; /** * Retrieves a list of ParseObjects that satisfy this query. * @@ -241,7 +226,7 @@ declare class ParseQuery { * @returns {Promise} A promise that is resolved with the results when * the query completes. */ - find(options?: FullOptions): Promise>; + find(options?: QueryOptions): Promise>; /** * Retrieves a complete list of ParseObjects that satisfy this query. * Using `eachBatch` under the hood to fetch all the valid objects. @@ -270,7 +255,10 @@ declare class ParseQuery { * @returns {Promise} A promise that is resolved with the count when * the query completes. */ - count(options?: FullOptions): Promise; + count(options?: { + useMasterKey?: boolean; + sessionToken?: string; + }): Promise; /** * Executes a distinct query and returns unique values * @@ -282,7 +270,9 @@ declare class ParseQuery { * * @returns {Promise} A promise that is resolved with the query completes. */ - distinct(key: string, options?: FullOptions): Promise>; + distinct(key: string, options?: { + sessionToken?: string; + }): Promise>; /** * Executes an aggregate query and returns aggregate results * @@ -293,7 +283,9 @@ declare class ParseQuery { * * @returns {Promise} A promise that is resolved with the query completes. */ - aggregate(pipeline: mixed, options?: FullOptions): Promise>; + aggregate(pipeline: any, options?: { + sessionToken?: string; + }): Promise>; /** * Retrieves at most one Parse.Object that satisfies this query. * @@ -310,7 +302,7 @@ declare class ParseQuery { * @returns {Promise} A promise that is resolved with the object when * the query completes. */ - first(options?: FullOptions): Promise; + first(options?: QueryOptions): Promise; /** * Iterates over objects matching a query, calling a callback for each batch. * If the callback returns a promise, the iteration will not continue until @@ -332,7 +324,7 @@ declare class ParseQuery { * @returns {Promise} A promise that will be fulfilled once the * iteration has completed. */ - eachBatch(callback: (objs: Array) => Promise, options?: BatchOptions): Promise; + eachBatch(callback: (objs: Array) => void, options?: BatchOptions): Promise; /** * Iterates over each result of a query, calling a callback for each one. If * the callback returns a promise, the iteration will not continue until @@ -360,7 +352,7 @@ declare class ParseQuery { * @param {(string|object)} value String or Object of index that should be used when executing query * @returns {Parse.Query} Returns the query, so you can chain this call. */ - hint(value: mixed): ParseQuery; + hint(value: any): ParseQuery; /** * Investigates the query execution plan. Useful for optimizing queries. (https://docs.mongodb.com/manual/reference/operator/meta/explain/) * @@ -448,7 +440,7 @@ declare class ParseQuery { */ equalTo(key: string | { [key: string]: any; - }, value: mixed): ParseQuery; + }, value?: any): ParseQuery; /** * Adds a constraint to the query that requires a particular key's value to * be not equal to the provided value. @@ -459,7 +451,7 @@ declare class ParseQuery { */ notEqualTo(key: string | { [key: string]: any; - }, value: mixed): ParseQuery; + }, value?: any): ParseQuery; /** * Adds a constraint to the query that requires a particular key's value to * be less than the provided value. @@ -468,7 +460,7 @@ declare class ParseQuery { * @param value The value that provides an upper bound. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - lessThan(key: string, value: mixed): ParseQuery; + lessThan(key: string, value: any): ParseQuery; /** * Adds a constraint to the query that requires a particular key's value to * be greater than the provided value. @@ -477,7 +469,7 @@ declare class ParseQuery { * @param value The value that provides an lower bound. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - greaterThan(key: string, value: mixed): ParseQuery; + greaterThan(key: string, value: any): ParseQuery; /** * Adds a constraint to the query that requires a particular key's value to * be less than or equal to the provided value. @@ -486,7 +478,7 @@ declare class ParseQuery { * @param value The value that provides an upper bound. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - lessThanOrEqualTo(key: string, value: mixed): ParseQuery; + lessThanOrEqualTo(key: string, value: any): ParseQuery; /** * Adds a constraint to the query that requires a particular key's value to * be greater than or equal to the provided value. @@ -495,7 +487,7 @@ declare class ParseQuery { * @param {*} value The value that provides an lower bound. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - greaterThanOrEqualTo(key: string, value: mixed): ParseQuery; + greaterThanOrEqualTo(key: string, value: any): ParseQuery; /** * Adds a constraint to the query that requires a particular key's value to * be contained in the provided list of values. @@ -504,7 +496,7 @@ declare class ParseQuery { * @param {Array<*>} value The values that will match. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - containedIn(key: string, value: Array): ParseQuery; + containedIn(key: string, value: Array): ParseQuery; /** * Adds a constraint to the query that requires a particular key's value to * not be contained in the provided list of values. @@ -513,7 +505,7 @@ declare class ParseQuery { * @param {Array<*>} value The values that will not match. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - notContainedIn(key: string, value: Array): ParseQuery; + notContainedIn(key: string, value: Array): ParseQuery; /** * Adds a constraint to the query that requires a particular key's value to * be contained by the provided list of values. Get objects where all array elements match. @@ -522,7 +514,7 @@ declare class ParseQuery { * @param {Array} values The values that will match. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - containedBy(key: string, values: Array): ParseQuery; + containedBy(key: string, values: Array): ParseQuery; /** * Adds a constraint to the query that requires a particular key's value to * contain each one of the provided list of values. @@ -531,7 +523,7 @@ declare class ParseQuery { * @param {Array} values The values that will match. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - containsAll(key: string, values: Array): ParseQuery; + containsAll(key: string, values: Array): ParseQuery; /** * Adds a constraint to the query that requires a particular key's value to * contain each one of the provided list of values starting with given strings. @@ -561,11 +553,11 @@ declare class ParseQuery { * This may be slow for large datasets. * * @param {string} key The key that the string to match is stored in. - * @param {RegExp} regex The regular expression pattern to match. + * @param {RegExp | string} regex The regular expression pattern to match. * @param {string} modifiers The regular expression mode. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - matches(key: string, regex: RegExp, modifiers: string): ParseQuery; + matches(key: string, regex: RegExp | string, modifiers: string): ParseQuery; /** * Adds a constraint that requires that a key's value matches a Parse.Query * constraint. @@ -648,13 +640,13 @@ declare class ParseQuery { * @param {boolean} options.diacriticSensitive A boolean flag to enable or disable diacritic sensitive search. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - fullText(key: string, value: string, options: Object | null): ParseQuery; + fullText(key: string, value: string, options?: FullTextQueryOptions): ParseQuery; /** * Method to sort the full text search by text score * * @returns {Parse.Query} Returns the query, so you can chain this call. */ - sortByTextScore(): Parse.Query; + sortByTextScore(): this; /** * Adds a constraint for finding string values that start with a provided * string. This query will use the backend index, so it will be fast even @@ -885,6 +877,45 @@ declare class ParseQuery { * which can be used to get liveQuery updates. */ subscribe(sessionToken?: string): Promise; + /** + * Constructs a Parse.Query that is the OR of the passed in queries. For + * example: + *
var compoundQuery = Parse.Query.or(query1, query2, query3);
+ * + * will create a compoundQuery that is an or of the query1, query2, and + * query3. + * + * @param {...Parse.Query} queries The list of queries to OR. + * @static + * @returns {Parse.Query} The query that is the OR of the passed in queries. + */ + static or(...queries: Array): ParseQuery; + /** + * Constructs a Parse.Query that is the AND of the passed in queries. For + * example: + *
var compoundQuery = Parse.Query.and(query1, query2, query3);
+ * + * will create a compoundQuery that is an and of the query1, query2, and + * query3. + * + * @param {...Parse.Query} queries The list of queries to AND. + * @static + * @returns {Parse.Query} The query that is the AND of the passed in queries. + */ + static and(...queries: Array): ParseQuery; + /** + * Constructs a Parse.Query that is the NOR of the passed in queries. For + * example: + *
const compoundQuery = Parse.Query.nor(query1, query2, query3);
+ * + * will create a compoundQuery that is a nor of the query1, query2, and + * query3. + * + * @param {...Parse.Query} queries The list of queries to NOR. + * @static + * @returns {Parse.Query} The query that is the NOR of the passed in queries. + */ + static nor(...queries: Array): ParseQuery; /** * Change the source of this query to the server. * @@ -909,7 +940,7 @@ declare class ParseQuery { * @param {string} name The name of query source. * @returns {Parse.Query} Returns the query, so you can chain this call. */ - fromPinWithName(name?: string): ParseQuery; + fromPinWithName(name?: string | null): ParseQuery; /** * Cancels the current network request (if any is running). * @@ -918,7 +949,7 @@ declare class ParseQuery { cancel(): ParseQuery; _setRequestTask(options: any): void; /** - * Sets a comment to the query so that the query + * Sets a comment to the query so that the query * can be identified when using a the profiler for MongoDB. * * @param {string} value a comment can make your profile data easier to interpret and trace. @@ -926,10 +957,4 @@ declare class ParseQuery { */ comment(value: string): ParseQuery; } -import { FullOptions } from './RESTController'; -import ParseObject from './ParseObject'; -type BatchOptions = FullOptions & { - batchSize?: number; -}; -import ParseGeoPoint from './ParseGeoPoint'; -import LiveQuerySubscription from './LiveQuerySubscription'; +export default ParseQuery; diff --git a/types/ParseRole.d.ts b/types/ParseRole.d.ts index fe82fd571..32da55c56 100644 --- a/types/ParseRole.d.ts +++ b/types/ParseRole.d.ts @@ -1,5 +1,8 @@ -// @ts-nocheck -export default ParseRole; +import ParseACL from './ParseACL'; +import ParseError from './ParseError'; +import ParseObject from './ParseObject'; +import type { AttributeMap } from './ObjectStateMutations'; +import type ParseRelation from './ParseRelation'; /** * Represents a Role on the Parse server. Roles represent groupings of * Users for the purposes of granting permissions (e.g. specifying an ACL @@ -13,7 +16,7 @@ export default ParseRole; * @alias Parse.Role * @augments Parse.Object */ -declare class ParseRole { +declare class ParseRole extends ParseObject { /** * @param {string} name The name of the Role to create. * @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL. @@ -44,7 +47,7 @@ declare class ParseRole { * callbacks. * @returns {(ParseObject|boolean)} true if the set succeeded. */ - setName(name: string, options?: mixed): ParseObject | boolean; + setName(name: string, options?: any): ParseObject | boolean; /** * Gets the Parse.Relation for the Parse.Users that are direct * children of this role. These users are granted any privileges that this @@ -70,10 +73,6 @@ declare class ParseRole { */ getRoles(): ParseRelation; _validateName(newName: any): void; - validate(attrs: AttributeMap, options?: mixed): ParseError | boolean; + validate(attrs: AttributeMap, options?: any): ParseError | boolean; } -import ParseObject from './ParseObject'; -import ParseRelation from './ParseRelation'; -import { AttributeMap } from './ObjectStateMutations'; -import ParseError from './ParseError'; -import ParseACL from './ParseACL'; +export default ParseRole; diff --git a/types/ParseSession.d.ts b/types/ParseSession.d.ts index ce17eb974..aeb0d8c43 100644 --- a/types/ParseSession.d.ts +++ b/types/ParseSession.d.ts @@ -29,7 +29,7 @@ declare class ParseSession extends ParseObject { * object after it has been fetched. If there is no current user, the * promise will be rejected. */ - static current(options: FullOptions): any; + static current(options: FullOptions): Promise; /** * Determines whether the current session token is revocable. * This method is useful for migrating Express.js or Node.js web apps to diff --git a/types/ParseUser.d.ts b/types/ParseUser.d.ts index 5a425bc55..c705f7e71 100644 --- a/types/ParseUser.d.ts +++ b/types/ParseUser.d.ts @@ -1,8 +1,18 @@ -// @ts-nocheck -type AuthData = { - [key: string]: mixed; +import ParseObject from './ParseObject'; +import type { AttributeMap } from './ObjectStateMutations'; +import type { RequestOptions, FullOptions } from './RESTController'; +export type AuthData = { + [key: string]: any; +}; +export type AuthProviderType = { + authenticate?(options: { + error?: (provider: AuthProviderType, error: string | any) => void; + success?: (provider: AuthProviderType, result: AuthData) => void; + }): void; + restoreAuthentication(authData: any): boolean; + getAuthType(): string; + deauthenticate?(): void; }; -export default ParseUser; /** *

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 @@ -13,7 +23,227 @@ export default ParseUser; * @alias Parse.User * @augments Parse.Object */ -declare class ParseUser { +declare class ParseUser extends ParseObject { + /** + * @param {object} attributes The initial set of data to store in the user. + */ + constructor(attributes?: AttributeMap); + /** + * Request a revocable session token to replace the older style of token. + * + * @param {object} options + * @returns {Promise} A promise that is resolved when the replacement + * token has been fetched. + */ + _upgradeToRevocableSession(options: RequestOptions): Promise; + /** + * Parse allows you to link your users with {@link https://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication 3rd party authentication}, enabling + * your users to sign up or log into your application using their existing identities. + * Since 2.9.0 + * + * @see {@link https://docs.parseplatform.org/js/guide/#linking-users Linking Users} + * @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider} + * @param {object} options + *

    + *
  • If provider is string, options is {@link http://docs.parseplatform.org/parse-server/guide/#supported-3rd-party-authentications authData} + *
  • If provider is AuthProvider, options is saveOpts + *
+ * @param {object} saveOpts useMasterKey / sessionToken + * @returns {Promise} A promise that is fulfilled with the user is linked + */ + linkWith(provider: AuthProviderType, options: { + authData?: AuthData; + }, saveOpts?: FullOptions): Promise; + /** + * @param provider + * @param options + * @param saveOpts + * @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} + * @returns {Promise} + */ + _linkWith(provider: any, options: { + authData?: AuthData; + }, saveOpts?: FullOptions): Promise; + /** + * Synchronizes auth data for a provider (e.g. puts the access token in the + * right place to be used by the Facebook SDK). + * + * @param provider + */ + _synchronizeAuthData(provider: string | AuthProviderType): void; + /** + * Synchronizes authData for all providers. + */ + _synchronizeAllAuthData(): void; + /** + * Removes null values from authData (which exist temporarily for unlinking) + */ + _cleanupAuthData(): void; + /** + * Unlinks a user from a service. + * + * @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider} + * @param {object} options MasterKey / SessionToken + * @returns {Promise} A promise that is fulfilled when the unlinking + * finishes. + */ + _unlinkFrom(provider: any, options?: FullOptions): Promise; + /** + * Checks whether a user is linked to a service. + * + * @param {object} provider service to link to + * @returns {boolean} true if link was successful + */ + _isLinked(provider: any): boolean; + /** + * Deauthenticates all providers. + */ + _logOutWithAll(): void; + /** + * Deauthenticates a single provider (e.g. removing access tokens from the + * Facebook SDK). + * + * @param {object} provider service to logout of + */ + _logOutWith(provider: any): void; + /** + * Class instance method used to maintain specific keys when a fetch occurs. + * Used to ensure that the session token is not lost. + * + * @returns {object} sessionToken + */ + _preserveFieldsOnFetch(): AttributeMap; + /** + * Returns true if current would return this user. + * + * @returns {boolean} true if user is cached on disk + */ + isCurrent(): boolean; + /** + * Returns true if current would return this user. + * + * @returns {Promise} true if user is cached on disk + */ + isCurrentAsync(): Promise; + stripAnonymity(): void; + restoreAnonimity(anonymousData: any): void; + /** + * Returns get("username"). + * + * @returns {string} + */ + getUsername(): string | null; + /** + * Calls set("username", username, options) and returns the result. + * + * @param {string} username + */ + setUsername(username: string): void; + /** + * Calls set("password", password, options) and returns the result. + * + * @param {string} password User's Password + */ + setPassword(password: string): void; + /** + * Returns get("email"). + * + * @returns {string} User's Email + */ + getEmail(): string | null; + /** + * Calls set("email", email) and returns the result. + * + * @param {string} email + * @returns {boolean} + */ + setEmail(email: string): boolean | ParseObject; + /** + * Returns the session token for this user, if the user has been logged in, + * or if it is the result of a query with the master key. Otherwise, returns + * undefined. + * + * @returns {string} the session token, or undefined + */ + getSessionToken(): string | null; + /** + * Checks whether this user is the current user and has been authenticated. + * + * @returns {boolean} whether this user is the current user and is logged in. + */ + authenticated(): boolean; + /** + * Signs up a new user. You should call this instead of save for + * new Parse.Users. This will create a new Parse.User on the server, and + * also persist the session on disk so that you can access the user using + * current. + * + *

A username and password must be set before calling signUp.

+ * + * @param {object} attrs Extra fields to set on the new user, or null. + * @param {object} options + * @returns {Promise} A promise that is fulfilled when the signup + * finishes. + */ + signUp(attrs: AttributeMap, options?: FullOptions & { + context?: AttributeMap; + }): Promise; + /** + * Logs in a Parse.User. On success, this saves the session to disk, + * so you can retrieve the currently logged in user using + * current. + * + *

A username and password must be set before calling logIn.

+ * + * @param {object} options + * @returns {Promise} A promise that is fulfilled with the user when + * the login is complete. + */ + logIn(options?: FullOptions & { + context?: AttributeMap; + }): Promise; + /** + * Wrap the default save behavior with functionality to save to local + * storage if this is current user. + * + * @param {...any} args + * @returns {Promise} + */ + save(...args: Array): Promise; + /** + * Wrap the default destroy behavior with functionality that logs out + * the current user when it is destroyed + * + * @param {...any} args + * @returns {Parse.User} + */ + destroy(...args: Array): Promise; + /** + * Wrap the default fetch behavior with functionality to save to local + * storage if this is current user. + * + * @param {...any} args + * @returns {Parse.User} + */ + fetch(...args: Array): Promise; + /** + * Wrap the default fetchWithInclude behavior with functionality to save to local + * storage if this is current user. + * + * @param {...any} args + * @returns {Parse.User} + */ + fetchWithInclude(...args: Array): Promise; + /** + * Verify whether a given password is the password of the current user. + * + * @param {string} password The password to be verified. + * @param {object} options The options. + * @param {boolean} [options.ignoreEmailVerification=false] Set to `true` to bypass email verification and verify + * the password regardless of whether the email has been verified. This requires the master key. + * @returns {Promise} A promise that is fulfilled with a user when the password is correct. + */ + verifyPassword(password: string, options?: RequestOptions): Promise; static readOnlyAttributes(): string[]; /** * Adds functionality to the existing Parse.User class. @@ -27,7 +257,7 @@ declare class ParseUser { [prop: string]: any; }, classProps: { [prop: string]: any; - }): Parse.User; + }): typeof ParseUser; /** * Retrieves the currently logged in ParseUser with a valid session, * either from memory or localStorage, if necessary. @@ -58,7 +288,7 @@ declare class ParseUser { * @returns {Promise} A promise that is fulfilled with the user when * the signup completes. */ - static signUp(username: string, password: string, attrs: AttributeMap, options?: FullOptions): Promise; + static signUp(username: string, password: string, attrs: AttributeMap, options?: FullOptions): Promise; /** * Logs in a user with a username (or email) and password. On success, this * saves the session to disk, so you can retrieve the currently logged in @@ -71,7 +301,7 @@ declare class ParseUser { * @returns {Promise} A promise that is fulfilled with the user when * the login completes. */ - static logIn(username: string, password: string, options?: FullOptions): Promise; + static logIn(username: string, password: string, options?: FullOptions): Promise; /** * Logs in a user with a username (or email) and password, and authData. On success, this * saves the session to disk, so you can retrieve the currently logged in @@ -85,7 +315,7 @@ declare class ParseUser { * @returns {Promise} A promise that is fulfilled with the user when * the login completes. */ - static logInWithAdditionalAuth(username: string, password: string, authData: AuthData, options?: FullOptions): Promise; + static logInWithAdditionalAuth(username: string, password: string, authData: AuthData, options?: FullOptions): Promise; /** * Logs in a user with an objectId. On success, this saves the session * to disk, so you can retrieve the currently logged in user using @@ -96,7 +326,7 @@ declare class ParseUser { * @returns {Promise} A promise that is fulfilled with the user when * the login completes. */ - static loginAs(userId: string): Promise; + static loginAs(userId: string): Promise; /** * Logs in a user with a session token. On success, this saves the session * to disk, so you can retrieve the currently logged in user using @@ -108,7 +338,7 @@ declare class ParseUser { * @returns {Promise} A promise that is fulfilled with the user when * the login completes. */ - static become(sessionToken: string, options?: RequestOptions): Promise; + static become(sessionToken: string, options?: RequestOptions): Promise; /** * Retrieves a user with a session token. * @@ -117,7 +347,7 @@ declare class ParseUser { * @static * @returns {Promise} A promise that is fulfilled with the user is fetched. */ - static me(sessionToken: string, options?: RequestOptions): Promise; + static me(sessionToken: string, options?: RequestOptions): Promise; /** * Logs in a user with a session token. On success, this saves the session * to disk, so you can retrieve the currently logged in user using @@ -128,7 +358,7 @@ declare class ParseUser { * @returns {Promise} A promise that is fulfilled with the user when * the login completes. */ - static hydrate(userJSON: AttributeMap): Promise; + static hydrate(userJSON: AttributeMap): Promise; /** * Static version of {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} * @@ -151,7 +381,7 @@ declare class ParseUser { * @returns {Promise} A promise that is resolved when the session is * destroyed on the server. */ - static logOut(options?: RequestOptions): Promise; + static logOut(options?: RequestOptions): Promise; /** * Requests a password reset email to be sent to the specified email address * associated with the user account. This email allows the user to securely @@ -163,7 +393,7 @@ declare class ParseUser { * @static * @returns {Promise} */ - static requestPasswordReset(email: string, options?: RequestOptions): Promise; + static requestPasswordReset(email: string, options?: RequestOptions): Promise; /** * Request an email verification. * @@ -173,18 +403,19 @@ declare class ParseUser { * @static * @returns {Promise} */ - static requestEmailVerification(email: string, options?: RequestOptions): Promise; + static requestEmailVerification(email: string, options?: RequestOptions): Promise; /** * Verify whether a given password is the password of the current user. - * - * @param {string} username A username to be used for identificaiton - * @param {string} password A password to be verified - * @param {object} options * @static - * @returns {Promise} A promise that is fulfilled with a user - * when the password is correct. + * + * @param {string} username The username of the user whose password should be verified. + * @param {string} password The password to be verified. + * @param {object} options The options. + * @param {boolean} [options.ignoreEmailVerification=false] Set to `true` to bypass email verification and verify + * the password regardless of whether the email has been verified. This requires the master key. + * @returns {Promise} A promise that is fulfilled with a user when the password is correct. */ - static verifyPassword(username: string, password: string, options?: RequestOptions): Promise; + static verifyPassword(username: string, password: string, options?: RequestOptions): Promise; /** * Allow someone to define a custom User class without className * being rewritten to _User. The default behavior is to rewrite @@ -209,7 +440,7 @@ declare class ParseUser { * completed. If a replacement session token is requested, the promise * will be resolved after a new token has been fetched. */ - static enableRevocableSession(options?: RequestOptions): Promise; + static enableRevocableSession(options?: RequestOptions): Promise; /** * Enables the use of become or the current user in a server * environment. These features are disabled by default, since they depend on @@ -249,223 +480,8 @@ declare class ParseUser { */ static _logInWith(provider: any, options: { authData?: AuthData; - }, saveOpts?: FullOptions): Promise; + }, saveOpts?: FullOptions): Promise; static _clearCache(): void; static _setCurrentUserCache(user: ParseUser): void; - /** - * @param {object} attributes The initial set of data to store in the user. - */ - constructor(attributes: AttributeMap | null); - /** - * Request a revocable session token to replace the older style of token. - * - * @param {object} options - * @returns {Promise} A promise that is resolved when the replacement - * token has been fetched. - */ - _upgradeToRevocableSession(options: RequestOptions): Promise; - /** - * Parse allows you to link your users with {@link https://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication 3rd party authentication}, enabling - * your users to sign up or log into your application using their existing identities. - * Since 2.9.0 - * - * @see {@link https://docs.parseplatform.org/js/guide/#linking-users Linking Users} - * @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider} - * @param {object} options - *
    - *
  • If provider is string, options is {@link http://docs.parseplatform.org/parse-server/guide/#supported-3rd-party-authentications authData} - *
  • If provider is AuthProvider, options is saveOpts - *
- * @param {object} saveOpts useMasterKey / sessionToken - * @returns {Promise} A promise that is fulfilled with the user is linked - */ - linkWith(provider: any, options: { - authData?: AuthData; - }, saveOpts?: FullOptions): Promise; - /** - * @param provider - * @param options - * @param saveOpts - * @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} - * @returns {Promise} - */ - _linkWith(provider: any, options: { - authData?: AuthData; - }, saveOpts?: FullOptions): Promise; - /** - * Synchronizes auth data for a provider (e.g. puts the access token in the - * right place to be used by the Facebook SDK). - * - * @param provider - */ - _synchronizeAuthData(provider: string): void; - /** - * Synchronizes authData for all providers. - */ - _synchronizeAllAuthData(): void; - /** - * Removes null values from authData (which exist temporarily for unlinking) - */ - _cleanupAuthData(): void; - /** - * Unlinks a user from a service. - * - * @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider} - * @param {object} options MasterKey / SessionToken - * @returns {Promise} A promise that is fulfilled when the unlinking - * finishes. - */ - _unlinkFrom(provider: any, options?: FullOptions): Promise; - /** - * Checks whether a user is linked to a service. - * - * @param {object} provider service to link to - * @returns {boolean} true if link was successful - */ - _isLinked(provider: any): boolean; - /** - * Deauthenticates all providers. - */ - _logOutWithAll(): void; - /** - * Deauthenticates a single provider (e.g. removing access tokens from the - * Facebook SDK). - * - * @param {object} provider service to logout of - */ - _logOutWith(provider: any): void; - /** - * Class instance method used to maintain specific keys when a fetch occurs. - * Used to ensure that the session token is not lost. - * - * @returns {object} sessionToken - */ - _preserveFieldsOnFetch(): AttributeMap; - /** - * Returns true if current would return this user. - * - * @returns {boolean} true if user is cached on disk - */ - isCurrent(): boolean; - /** - * Returns true if current would return this user. - * - * @returns {Promise} true if user is cached on disk - */ - isCurrentAsync(): Promise; - /** - * Returns get("username"). - * - * @returns {string} - */ - getUsername(): string | null; - /** - * Calls set("username", username, options) and returns the result. - * - * @param {string} username - */ - setUsername(username: string): void; - /** - * Calls set("password", password, options) and returns the result. - * - * @param {string} password User's Password - */ - setPassword(password: string): void; - /** - * Returns get("email"). - * - * @returns {string} User's Email - */ - getEmail(): string | null; - /** - * Calls set("email", email) and returns the result. - * - * @param {string} email - * @returns {boolean} - */ - setEmail(email: string): boolean; - /** - * Returns the session token for this user, if the user has been logged in, - * or if it is the result of a query with the master key. Otherwise, returns - * undefined. - * - * @returns {string} the session token, or undefined - */ - getSessionToken(): string | null; - /** - * Checks whether this user is the current user and has been authenticated. - * - * @returns {boolean} whether this user is the current user and is logged in. - */ - authenticated(): boolean; - /** - * Signs up a new user. You should call this instead of save for - * new Parse.Users. This will create a new Parse.User on the server, and - * also persist the session on disk so that you can access the user using - * current. - * - *

A username and password must be set before calling signUp.

- * - * @param {object} attrs Extra fields to set on the new user, or null. - * @param {object} options - * @returns {Promise} A promise that is fulfilled when the signup - * finishes. - */ - signUp(attrs: AttributeMap, options?: FullOptions): Promise; - /** - * Logs in a Parse.User. On success, this saves the session to disk, - * so you can retrieve the currently logged in user using - * current. - * - *

A username and password must be set before calling logIn.

- * - * @param {object} options - * @returns {Promise} A promise that is fulfilled with the user when - * the login is complete. - */ - logIn(options?: FullOptions): Promise; - /** - * Wrap the default save behavior with functionality to save to local - * storage if this is current user. - * - * @param {...any} args - * @returns {Promise} - */ - save(...args: Array): Promise; - /** - * Wrap the default destroy behavior with functionality that logs out - * the current user when it is destroyed - * - * @param {...any} args - * @returns {Parse.User} - */ - destroy(...args: Array): Promise; - /** - * Wrap the default fetch behavior with functionality to save to local - * storage if this is current user. - * - * @param {...any} args - * @returns {Parse.User} - */ - fetch(...args: Array): Promise; - /** - * Wrap the default fetchWithInclude behavior with functionality to save to local - * storage if this is current user. - * - * @param {...any} args - * @returns {Parse.User} - */ - fetchWithInclude(...args: Array): Promise; - /** - * Verify whether a given password is the password of the current user. - * - * @param {string} password A password to be verified - * @param {object} options - * @returns {Promise} A promise that is fulfilled with a user - * when the password is correct. - */ - verifyPassword(password: string, options?: RequestOptions): Promise; } -import { RequestOptions } from './RESTController'; -import { FullOptions } from './RESTController'; -import { AttributeMap } from './ObjectStateMutations'; +export default ParseUser; diff --git a/types/Push.d.ts b/types/Push.d.ts index 3108e0d24..367171126 100644 --- a/types/Push.d.ts +++ b/types/Push.d.ts @@ -1,4 +1,13 @@ -// @ts-nocheck +import ParseQuery from './ParseQuery'; +import type ParseObject from './ParseObject'; +import type { WhereClause } from './ParseQuery'; +import type { FullOptions } from './RESTController'; +export type PushData = { + where?: WhereClause | ParseQuery; + push_time?: Date | string; + expiration_time?: Date | string; + expiration_interval?: number; +}; /** * Contains functions to deal with Push in Parse. * @@ -32,9 +41,9 @@ * be used for this request. * * @returns {Promise} A promise that is fulfilled when the push request - * completes. + * completes and returns `pushStatusId`. */ -export function send(data: PushData, options?: FullOptions): Promise; +export declare function send(data: PushData, options?: FullOptions): Promise; /** * Gets push status by Id * @@ -48,12 +57,4 @@ export function send(data: PushData, options?: FullOptions): Promise; * * @returns {Parse.Object} Status of Push. */ -export function getPushStatus(pushStatusId: string, options?: FullOptions): Promise; -type PushData = { - where?: WhereClause | ParseQuery; - push_time?: string | Date; - expiration_time?: string | Date; - expiration_interval?: number; -}; -import { FullOptions } from './RESTController'; -export {}; +export declare function getPushStatus(pushStatusId: string, options?: FullOptions): Promise; diff --git a/types/TaskQueue.d.ts b/types/TaskQueue.d.ts index cb0ff5c3b..ae7e55fe9 100644 --- a/types/TaskQueue.d.ts +++ b/types/TaskQueue.d.ts @@ -1 +1,11 @@ -export {}; +type Task = { + task: () => Promise; + _completion: any; +}; +declare class TaskQueue { + queue: Array; + constructor(); + enqueue(task: () => Promise): Promise; + _dequeue(): void; +} +export default TaskQueue; diff --git a/types/tsconfig.json b/types/tsconfig.json index 2edb2f209..d18d38fbe 100644 --- a/types/tsconfig.json +++ b/types/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "module": "commonjs", - "lib": ["es6"], + "lib": ["es6", "dom"], "noImplicitAny": true, "noImplicitThis": true, "strictFunctionTypes": true, diff --git a/types/tslint.json b/types/tslint.json index e5fa37117..044192939 100644 --- a/types/tslint.json +++ b/types/tslint.json @@ -5,6 +5,10 @@ "ban-types": false, "no-unnecessary-generics": false, "no-redundant-jsdoc": false, - "strict-export-declare-modifiers": false + "strict-export-declare-modifiers": false, + "interface-over-type-literal": false, + "no-duplicate-imports": false, + "array-type": false, + "void-return": false } }