/**
* Parse JavaScript SDK v5.3.0
*
* The source tree of this library can be found at
* https://github.com/ParsePlatform/Parse-SDK-JS
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Parse = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i
* var dimensions = {
* gender: 'm',
* source: 'web',
* dayType: 'weekend'
* };
* Parse.Analytics.track('signup', dimensions);
*
*
* There is a default limit of 8 dimensions per event tracked.
*
* @function track
* @name Parse.Analytics.track
* @param {string} name The name of the custom event to report to Parse as
* having happened.
* @param {object} dimensions The dictionary of information by which to
* segment this event.
* @returns {Promise} A promise that is resolved when the round-trip
* to the server completes.
*/
function track(name, dimensions) {
name = name || '';
name = name.replace(/^\s*/, '');
name = name.replace(/\s*$/, '');
if (name.length === 0) {
throw new TypeError('A name for the custom event must be provided');
}
for (const key in dimensions) {
if (typeof key !== 'string' || typeof dimensions[key] !== 'string') {
throw new TypeError('track() dimensions expects keys and values of type "string".');
}
}
return _CoreManager.default.getAnalyticsController().track(name, dimensions);
}
const DefaultController = {
track(name, dimensions) {
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('POST', 'events/' + name, {
dimensions
});
}
};
_CoreManager.default.setAnalyticsController(DefaultController);
},{"./CoreManager":4,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],2:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
var _uuid = _interopRequireDefault(_dereq_("./uuid"));
let registered = false;
/**
* Provides utility functions for working with Anonymously logged-in users.
* Anonymous users have some unique characteristics:
*
* - Anonymous users don't need a user name or password.
*
* - Once logged out, an anonymous user cannot be recovered.
*
* - signUp converts an anonymous user to a standard user with the given username and password.
*
* - Data associated with the anonymous user is retained.
*
* - logIn switches users without converting the anonymous user.
*
* - Data associated with the anonymous user will be lost.
*
* - Service logIn (e.g. Facebook, Twitter) will attempt to convert
* the anonymous user into a standard user by linking it to the service.
*
* - If a user already exists that is linked to the service, it will instead switch to the existing user.
*
* - Service linking (e.g. Facebook, Twitter) will convert the anonymous user
* into a standard user by linking it to the service.
*
*
* @class Parse.AnonymousUtils
* @static
*/
const AnonymousUtils = {
/**
* Gets whether the user has their account linked to anonymous user.
*
* @function isLinked
* @name Parse.AnonymousUtils.isLinked
* @param {Parse.User} user User to check for.
* The user must be logged in on this device.
* @returns {boolean} true
if the user has their account
* linked to an anonymous user.
* @static
*/
isLinked(user) {
const provider = this._getAuthProvider();
return user._isLinked(provider.getAuthType());
},
/**
* Logs in a user Anonymously.
*
* @function logIn
* @name Parse.AnonymousUtils.logIn
* @param {object} options MasterKey / SessionToken.
* @returns {Promise} Logged in user
* @static
*/
logIn(options) {
const provider = this._getAuthProvider();
return _ParseUser.default.logInWith(provider.getAuthType(), provider.getAuthData(), options);
},
/**
* Links Anonymous User to an existing PFUser.
*
* @function link
* @name Parse.AnonymousUtils.link
* @param {Parse.User} user User to link. This must be the current user.
* @param {object} options MasterKey / SessionToken.
* @returns {Promise} Linked with User
* @static
*/
link(user, options) {
const provider = this._getAuthProvider();
return user.linkWith(provider.getAuthType(), provider.getAuthData(), options);
},
/**
* Returns true if Authentication Provider has been registered for use.
*
* @function isRegistered
* @name Parse.AnonymousUtils.isRegistered
* @returns {boolean}
* @static
*/
isRegistered() {
return registered;
},
_getAuthProvider() {
const provider = {
restoreAuthentication() {
return true;
},
getAuthType() {
return 'anonymous';
},
getAuthData() {
return {
authData: {
id: (0, _uuid.default)()
}
};
}
};
if (!registered) {
_ParseUser.default._registerAuthenticationProvider(provider);
registered = true;
}
return provider;
}
};
var _default = exports.default = AnonymousUtils;
},{"./ParseUser":38,"./uuid":64,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],3:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.getJobStatus = getJobStatus;
exports.getJobsData = getJobsData;
exports.run = run;
exports.startJob = startJob;
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _decode = _interopRequireDefault(_dereq_("./decode"));
var _encode = _interopRequireDefault(_dereq_("./encode"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
/**
* Contains functions for calling and declaring
* cloud functions.
*
* Some functions are only available from Cloud Code.
*
*
* @class Parse.Cloud
* @static
* @hideconstructor
*/
/**
* Makes a call to a cloud function.
*
* @function run
* @name Parse.Cloud.run
* @param {string} name The function name.
* @param {object} data The parameters to send to the cloud function.
* @param {object} options
* @returns {Promise} A promise that will be resolved with the result
* of the function.
*/
function run(name, data, options) {
options = options || {};
if (typeof name !== 'string' || name.length === 0) {
throw new TypeError('Cloud function name must be a string.');
}
const requestOptions = {};
if (options.useMasterKey) {
requestOptions.useMasterKey = options.useMasterKey;
}
if (options.sessionToken) {
requestOptions.sessionToken = options.sessionToken;
}
if (options.installationId) {
requestOptions.installationId = options.installationId;
}
if (options.context && typeof options.context === 'object') {
requestOptions.context = options.context;
}
return _CoreManager.default.getCloudController().run(name, data, requestOptions);
}
/**
* Gets data for the current set of cloud jobs.
*
* @function getJobsData
* @name Parse.Cloud.getJobsData
* @returns {Promise} A promise that will be resolved with the result
* of the function.
*/
function getJobsData() {
return _CoreManager.default.getCloudController().getJobsData({
useMasterKey: true
});
}
/**
* Starts a given cloud job, which will process asynchronously.
*
* @function startJob
* @name Parse.Cloud.startJob
* @param {string} name The function name.
* @param {object} data The parameters to send to the cloud function.
* @returns {Promise} A promise that will be resolved with the jobStatusId
* of the job.
*/
function startJob(name, data) {
if (typeof name !== 'string' || name.length === 0) {
throw new TypeError('Cloud job name must be a string.');
}
return _CoreManager.default.getCloudController().startJob(name, data, {
useMasterKey: true
});
}
/**
* Gets job status by Id
*
* @function getJobStatus
* @name Parse.Cloud.getJobStatus
* @param {string} jobStatusId The Id of Job Status.
* @returns {Parse.Object} Status of Job.
*/
function getJobStatus(jobStatusId) {
const query = new _ParseQuery.default('_JobStatus');
return query.get(jobStatusId, {
useMasterKey: true
});
}
const DefaultController = {
run(name, data, options) {
const RESTController = _CoreManager.default.getRESTController();
const payload = (0, _encode.default)(data, true);
const request = RESTController.request('POST', 'functions/' + name, payload, options);
return request.then(res => {
if (typeof res === 'object' && (0, _keys.default)(res).length > 0 && !res.hasOwnProperty('result')) {
throw new _ParseError.default(_ParseError.default.INVALID_JSON, 'The server returned an invalid response.');
}
const decoded = (0, _decode.default)(res);
if (decoded && decoded.hasOwnProperty('result')) {
return _promise.default.resolve(decoded.result);
}
return _promise.default.resolve(undefined);
});
},
getJobsData(options) {
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('GET', 'cloud_code/jobs/data', null, options);
},
async startJob(name, data, options) {
const RESTController = _CoreManager.default.getRESTController();
const payload = (0, _encode.default)(data, true);
options.returnStatus = true;
const response = await RESTController.request('POST', 'jobs/' + name, payload, options);
return response._headers?.['X-Parse-Job-Status-Id'];
}
};
_CoreManager.default.setCloudController(DefaultController);
},{"./CoreManager":4,"./ParseError":24,"./ParseQuery":33,"./decode":55,"./encode":56,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],4:[function(_dereq_,module,exports){
(function (process){(function (){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
/** Based on https://github.com/react-native-async-storage/async-storage/blob/main/packages/default-storage-backend/src/types.ts */
const config = {
IS_NODE: typeof process !== 'undefined' && !!process.versions && !!process.versions.node && !process.versions.electron,
REQUEST_ATTEMPT_LIMIT: 5,
REQUEST_BATCH_SIZE: 20,
REQUEST_HEADERS: {},
SERVER_URL: 'https://api.parse.com/1',
SERVER_AUTH_TYPE: null,
SERVER_AUTH_TOKEN: null,
LIVEQUERY_SERVER_URL: null,
ENCRYPTED_KEY: null,
VERSION: 'js' + "5.3.0",
APPLICATION_ID: null,
JAVASCRIPT_KEY: null,
MASTER_KEY: null,
USE_MASTER_KEY: false,
PERFORM_USER_REWRITE: true,
FORCE_REVOCABLE_SESSION: false,
ENCRYPTED_USER: false,
IDEMPOTENCY: false,
ALLOW_CUSTOM_OBJECT_ID: false,
PARSE_ERRORS: []
};
function requireMethods(name, methods, controller) {
(0, _forEach.default)(methods).call(methods, func => {
if (typeof controller[func] !== 'function') {
throw new Error(`${name} must implement ${func}()`);
}
});
}
const CoreManager = {
get: function (key) {
if (config.hasOwnProperty(key)) {
return config[key];
}
throw new Error('Configuration key not found: ' + key);
},
set: function (key, value) {
config[key] = value;
},
setIfNeeded: function (key, value) {
if (!config.hasOwnProperty(key)) {
config[key] = value;
}
return config[key];
},
/* Specialized Controller Setters/Getters */
setAnalyticsController(controller) {
requireMethods('AnalyticsController', ['track'], controller);
config['AnalyticsController'] = controller;
},
getAnalyticsController() {
return config['AnalyticsController'];
},
setCloudController(controller) {
requireMethods('CloudController', ['run', 'getJobsData', 'startJob'], controller);
config['CloudController'] = controller;
},
getCloudController() {
return config['CloudController'];
},
setConfigController(controller) {
requireMethods('ConfigController', ['current', 'get', 'save'], controller);
config['ConfigController'] = controller;
},
getConfigController() {
return config['ConfigController'];
},
setCryptoController(controller) {
requireMethods('CryptoController', ['encrypt', 'decrypt'], controller);
config['CryptoController'] = controller;
},
getCryptoController() {
return config['CryptoController'];
},
setEventEmitter(eventEmitter) {
config['EventEmitter'] = eventEmitter;
},
getEventEmitter() {
return config['EventEmitter'];
},
setFileController(controller) {
requireMethods('FileController', ['saveFile', 'saveBase64'], controller);
config['FileController'] = controller;
},
setEventuallyQueue(controller) {
requireMethods('EventuallyQueue', ['poll', 'save', 'destroy'], controller);
config['EventuallyQueue'] = controller;
},
getEventuallyQueue() {
return config['EventuallyQueue'];
},
getFileController() {
return config['FileController'];
},
setInstallationController(controller) {
requireMethods('InstallationController', ['currentInstallationId', 'currentInstallation', 'updateInstallationOnDisk'], controller);
config['InstallationController'] = controller;
},
getInstallationController() {
return config['InstallationController'];
},
setLiveQuery(liveQuery) {
config['LiveQuery'] = liveQuery;
},
getLiveQuery() {
return config['LiveQuery'];
},
setObjectController(controller) {
requireMethods('ObjectController', ['save', 'fetch', 'destroy'], controller);
config['ObjectController'] = controller;
},
getObjectController() {
return config['ObjectController'];
},
setObjectStateController(controller) {
requireMethods('ObjectStateController', ['getState', 'initializeState', 'removeState', 'getServerData', 'setServerData', 'getPendingOps', 'setPendingOp', 'pushPendingState', 'popPendingState', 'mergeFirstPendingState', 'getObjectCache', 'estimateAttribute', 'estimateAttributes', 'commitServerChanges', 'enqueueTask', 'clearAllState'], controller);
config['ObjectStateController'] = controller;
},
getObjectStateController() {
return config['ObjectStateController'];
},
setPushController(controller) {
requireMethods('PushController', ['send'], controller);
config['PushController'] = controller;
},
getPushController() {
return config['PushController'];
},
setQueryController(controller) {
requireMethods('QueryController', ['find', 'aggregate'], controller);
config['QueryController'] = controller;
},
getQueryController() {
return config['QueryController'];
},
setRESTController(controller) {
requireMethods('RESTController', ['request', 'ajax'], controller);
config['RESTController'] = controller;
},
getRESTController() {
return config['RESTController'];
},
setSchemaController(controller) {
requireMethods('SchemaController', ['get', 'create', 'update', 'delete', 'send', 'purge'], controller);
config['SchemaController'] = controller;
},
getSchemaController() {
return config['SchemaController'];
},
setSessionController(controller) {
requireMethods('SessionController', ['getSession'], controller);
config['SessionController'] = controller;
},
getSessionController() {
return config['SessionController'];
},
setStorageController(controller) {
if (controller.async) {
requireMethods('An async StorageController', ['getItemAsync', 'setItemAsync', 'removeItemAsync', 'getAllKeysAsync'], controller);
} else {
requireMethods('A synchronous StorageController', ['getItem', 'setItem', 'removeItem', 'getAllKeys'], controller);
}
config['StorageController'] = controller;
},
setLocalDatastoreController(controller) {
requireMethods('LocalDatastoreController', ['pinWithName', 'fromPinWithName', 'unPinWithName', 'getAllContents', 'clear'], controller);
config['LocalDatastoreController'] = controller;
},
getLocalDatastoreController() {
return config['LocalDatastoreController'];
},
setLocalDatastore(store) {
config['LocalDatastore'] = store;
},
getLocalDatastore() {
return config['LocalDatastore'];
},
getStorageController() {
return config['StorageController'];
},
setAsyncStorage(storage) {
config['AsyncStorage'] = storage;
},
getAsyncStorage() {
return config['AsyncStorage'];
},
setWebSocketController(controller) {
config['WebSocketController'] = controller;
},
getWebSocketController() {
return config['WebSocketController'];
},
setUserController(controller) {
requireMethods('UserController', ['setCurrentUser', 'currentUser', 'currentUserAsync', 'signUp', 'logIn', 'become', 'logOut', 'me', 'requestPasswordReset', 'upgradeToRevocableSession', 'requestEmailVerification', 'verifyPassword', 'linkWith'], controller);
config['UserController'] = controller;
},
getUserController() {
return config['UserController'];
},
setLiveQueryController(controller) {
requireMethods('LiveQueryController', ['setDefaultLiveQueryClient', 'getDefaultLiveQueryClient', '_clearCachedDefaultClient'], controller);
config['LiveQueryController'] = controller;
},
getLiveQueryController() {
return config['LiveQueryController'];
},
setHooksController(controller) {
requireMethods('HooksController', ['create', 'get', 'update', 'remove'], controller);
config['HooksController'] = controller;
},
getHooksController() {
return config['HooksController'];
},
setParseOp(op) {
config['ParseOp'] = op;
},
getParseOp() {
return config['ParseOp'];
},
setParseObject(object) {
config['ParseObject'] = object;
},
getParseObject() {
return config['ParseObject'];
},
setParseQuery(query) {
config['ParseQuery'] = query;
},
getParseQuery() {
return config['ParseQuery'];
},
setParseRole(role) {
config['ParseRole'] = role;
},
getParseRole() {
return config['ParseRole'];
},
setParseUser(user) {
config['ParseUser'] = user;
},
getParseUser() {
return config['ParseUser'];
}
};
module.exports = CoreManager;
var _default = exports.default = CoreManager;
}).call(this)}).call(this,_dereq_('_process'))
},{"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103,"_process":107}],5:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
let AES;
let ENC;
AES = _dereq_('crypto-js/aes');
ENC = _dereq_('crypto-js/enc-utf8');
const CryptoController = {
encrypt(obj, secretKey) {
const encrypted = AES.encrypt((0, _stringify.default)(obj), secretKey);
return encrypted.toString();
},
decrypt(encryptedText, secretKey) {
const decryptedStr = AES.decrypt(encryptedText, secretKey).toString(ENC);
return decryptedStr;
}
};
module.exports = CryptoController;
var _default = exports.default = CryptoController;
},{"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103,"crypto-js/aes":476,"crypto-js/enc-utf8":480}],6:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* This is a simple wrapper to unify EventEmitter implementations across platforms.
*/
let EventEmitter;
try {
EventEmitter = _dereq_('events').EventEmitter;
} catch (_) {
// EventEmitter unavailable
}
module.exports = EventEmitter;
var _default = exports.default = EventEmitter;
},{"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"events":485}],7:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _splice = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/splice"));
var _findIndex = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/find-index"));
var _setInterval2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/set-interval"));
var _find = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/find"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
var _Storage = _interopRequireDefault(_dereq_("./Storage"));
const QUEUE_KEY = 'Parse/Eventually/Queue';
let queueCache = [];
let dirtyCache = true;
let polling = undefined;
/**
* Provides utility functions to queue objects that will be
* saved to the server at a later date.
*
* @class Parse.EventuallyQueue
* @static
*/
const EventuallyQueue = {
/**
* Add object to queue with save operation.
*
* @function save
* @name Parse.EventuallyQueue.save
* @param {ParseObject} object Parse.Object to be saved eventually
* @param {object} [serverOptions] See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#save Parse.Object.save} options.
* @returns {Promise} A promise that is fulfilled if object is added to queue.
* @static
* @see Parse.Object#saveEventually
*/
save(object) {
let serverOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.enqueue('save', object, serverOptions);
},
/**
* Add object to queue with save operation.
*
* @function destroy
* @name Parse.EventuallyQueue.destroy
* @param {ParseObject} object Parse.Object to be destroyed eventually
* @param {object} [serverOptions] See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Object.html#destroy Parse.Object.destroy} options
* @returns {Promise} A promise that is fulfilled if object is added to queue.
* @static
* @see Parse.Object#destroyEventually
*/
destroy(object) {
let serverOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.enqueue('destroy', object, serverOptions);
},
/**
* Generate unique identifier to avoid duplicates and maintain previous state.
*
* @param {string} action save / destroy
* @param {object} object Parse.Object to be queued
* @returns {string}
* @static
* @ignore
*/
generateQueueId(action, object) {
object._getId();
const {
className,
id,
_localId
} = object;
const uniqueId = object.get('hash') || _localId;
return [action, className, id, uniqueId].join('_');
},
/**
* Build queue object and add to queue.
*
* @param {string} action save / destroy
* @param {object} object Parse.Object to be queued
* @param {object} [serverOptions]
* @returns {Promise} A promise that is fulfilled if object is added to queue.
* @static
* @ignore
*/
async enqueue(action, object, serverOptions) {
const queueData = await this.getQueue();
const queueId = this.generateQueueId(action, object);
let index = this.queueItemExists(queueData, queueId);
if (index > -1) {
// Add cached values to new object if they don't exist
for (const prop in queueData[index].object) {
if (typeof object.get(prop) === 'undefined') {
object.set(prop, queueData[index].object[prop]);
}
}
} else {
index = queueData.length;
}
queueData[index] = {
queueId,
action,
object: object.toJSON(),
serverOptions,
id: object.id,
className: object.className,
hash: object.get('hash'),
createdAt: new Date()
};
return this.setQueue(queueData);
},
store(data) {
return _Storage.default.setItemAsync(QUEUE_KEY, (0, _stringify.default)(data));
},
load() {
return _Storage.default.getItemAsync(QUEUE_KEY);
},
/**
* Sets the in-memory queue from local storage and returns.
*
* @function getQueue
* @name Parse.EventuallyQueue.getQueue
* @returns {Promise}
* @static
*/
async getQueue() {
if (dirtyCache) {
queueCache = JSON.parse((await this.load()) || '[]');
dirtyCache = false;
}
return queueCache;
},
/**
* Saves the queue to local storage
*
* @param {Queue} queue Queue containing Parse.Object data.
* @returns {Promise} A promise that is fulfilled when queue is stored.
* @static
* @ignore
*/
setQueue(queue) {
queueCache = queue;
return this.store(queueCache);
},
/**
* Removes Parse.Object data from queue.
*
* @param {string} queueId Unique identifier for Parse.Object data.
* @returns {Promise} A promise that is fulfilled when queue is stored.
* @static
* @ignore
*/
async remove(queueId) {
const queueData = await this.getQueue();
const index = this.queueItemExists(queueData, queueId);
if (index > -1) {
(0, _splice.default)(queueData).call(queueData, index, 1);
await this.setQueue(queueData);
}
},
/**
* Removes all objects from queue.
*
* @function clear
* @name Parse.EventuallyQueue.clear
* @returns {Promise} A promise that is fulfilled when queue is cleared.
* @static
*/
clear() {
queueCache = [];
return this.store([]);
},
/**
* Return the index of a queueId in the queue. Returns -1 if not found.
*
* @param {Queue} queue Queue containing Parse.Object data.
* @param {string} queueId Unique identifier for Parse.Object data.
* @returns {number}
* @static
* @ignore
*/
queueItemExists(queue, queueId) {
return (0, _findIndex.default)(queue).call(queue, data => data.queueId === queueId);
},
/**
* Return the number of objects in the queue.
*
* @function length
* @name Parse.EventuallyQueue.length
* @returns {Promise}
* @static
*/
async length() {
const queueData = await this.getQueue();
return queueData.length;
},
/**
* Sends the queue to the server.
*
* @function sendQueue
* @name Parse.EventuallyQueue.sendQueue
* @returns {Promise} Returns true if queue was sent successfully.
* @static
*/
async sendQueue() {
const queue = await this.getQueue();
const queueData = [...queue];
if (queueData.length === 0) {
return false;
}
for (let i = 0; i < queueData.length; i += 1) {
const queueObject = queueData[i];
const {
id,
hash,
className
} = queueObject;
const ObjectType = _ParseObject.default.extend(className);
if (id) {
await this.process.byId(ObjectType, queueObject);
} else if (hash) {
await this.process.byHash(ObjectType, queueObject);
} else {
await this.process.create(ObjectType, queueObject);
}
}
return true;
},
/**
* Build queue object and add to queue.
*
* @param {ParseObject} object Parse.Object to be processed
* @param {QueueObject} queueObject Parse.Object data from the queue
* @returns {Promise} A promise that is fulfilled when operation is performed.
* @static
* @ignore
*/
async sendQueueCallback(object, queueObject) {
if (!object) {
return this.remove(queueObject.queueId);
}
switch (queueObject.action) {
case 'save':
// Queued update was overwritten by other request. Do not save
if (typeof object.updatedAt !== 'undefined' && object.updatedAt > new Date(queueObject.object.createdAt)) {
return this.remove(queueObject.queueId);
}
try {
await object.save(queueObject.object, queueObject.serverOptions);
await this.remove(queueObject.queueId);
} catch (e) {
if (e.code !== _ParseError.default.CONNECTION_FAILED) {
await this.remove(queueObject.queueId);
}
}
break;
case 'destroy':
try {
await object.destroy(queueObject.serverOptions);
await this.remove(queueObject.queueId);
} catch (e) {
if (e.code !== _ParseError.default.CONNECTION_FAILED) {
await this.remove(queueObject.queueId);
}
}
break;
}
},
/**
* Start polling server for network connection.
* Will send queue if connection is established.
*
* @function poll
* @name Parse.EventuallyQueue.poll
* @param [ms] Milliseconds to ping the server. Default 2000ms
* @static
*/
poll() {
let ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2000;
if (polling) {
return;
}
polling = (0, _setInterval2.default)(() => {
const RESTController = _CoreManager.default.getRESTController();
RESTController.request('GET', 'health').then(_ref => {
let {
status
} = _ref;
if (status === 'ok') {
this.stopPoll();
return this.sendQueue();
}
}).catch(e => e);
}, ms);
},
/**
* Turns off polling.
*
* @function stopPoll
* @name Parse.EventuallyQueue.stopPoll
* @static
*/
stopPoll() {
clearInterval(polling);
polling = undefined;
},
/**
* Return true if pinging the server.
*
* @function isPolling
* @name Parse.EventuallyQueue.isPolling
* @returns {boolean}
* @static
*/
isPolling() {
return !!polling;
},
_setPolling(flag) {
polling = flag;
},
process: {
create(ObjectType, queueObject) {
const object = new ObjectType();
return EventuallyQueue.sendQueueCallback(object, queueObject);
},
async byId(ObjectType, queueObject) {
const {
sessionToken
} = queueObject.serverOptions;
const query = new _ParseQuery.default(ObjectType);
query.equalTo('objectId', queueObject.id);
const results = await (0, _find.default)(query).call(query, {
sessionToken
});
return EventuallyQueue.sendQueueCallback(results[0], queueObject);
},
async byHash(ObjectType, queueObject) {
const {
sessionToken
} = queueObject.serverOptions;
const query = new _ParseQuery.default(ObjectType);
query.equalTo('hash', queueObject.hash);
const results = await (0, _find.default)(query).call(query, {
sessionToken
});
if (results.length > 0) {
return EventuallyQueue.sendQueueCallback(results[0], queueObject);
}
return EventuallyQueue.process.create(ObjectType, queueObject);
}
}
};
module.exports = EventuallyQueue;
var _default = exports.default = EventuallyQueue;
},{"./CoreManager":4,"./ParseError":24,"./ParseObject":30,"./ParseQuery":33,"./Storage":43,"@babel/runtime-corejs3/core-js-stable/instance/find":73,"@babel/runtime-corejs3/core-js-stable/instance/find-index":72,"@babel/runtime-corejs3/core-js-stable/instance/splice":82,"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/set-interval":98,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],8:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
/* global FB */
let initialized = false;
let requestedPermissions;
let initOptions;
const provider = {
authenticate(options) {
if (typeof FB === 'undefined') {
options.error(this, 'Facebook SDK not found.');
}
FB.login(response => {
if (response.authResponse) {
if (options.success) {
options.success(this, {
id: response.authResponse.userID,
access_token: response.authResponse.accessToken,
expiration_date: new Date(response.authResponse.expiresIn * 1000 + new Date().getTime()).toJSON()
});
}
} else {
if (options.error) {
options.error(this, response);
}
}
}, {
scope: requestedPermissions
});
},
restoreAuthentication(authData) {
if (authData) {
const newOptions = {};
if (initOptions) {
for (const key in initOptions) {
newOptions[key] = initOptions[key];
}
}
// Suppress checks for login status from the browser.
newOptions.status = false;
// If the user doesn't match the one known by the FB SDK, log out.
// Most of the time, the users will match -- it's only in cases where
// the FB SDK knows of a different user than the one being restored
// from a Parse User that logged in with username/password.
const existingResponse = FB.getAuthResponse();
if (existingResponse && existingResponse.userID !== authData.id) {
FB.logout();
}
FB.init(newOptions);
}
return true;
},
getAuthType() {
return 'facebook';
},
deauthenticate() {
this.restoreAuthentication(null);
}
};
/**
* Provides a set of utilities for using Parse with Facebook.
*
* @class Parse.FacebookUtils
* @static
* @hideconstructor
*/
const FacebookUtils = {
/**
* Initializes Parse Facebook integration. Call this function after you
* have loaded the Facebook Javascript SDK with the same parameters
* as you would pass to
*
* FB.init()
. Parse.FacebookUtils will invoke FB.init() for you
* with these arguments.
*
* @function init
* @name Parse.FacebookUtils.init
* @param {object} options Facebook options argument as described here:
*
* FB.init(). The status flag will be coerced to 'false' because it
* interferes with Parse Facebook integration. Call FB.getLoginStatus()
* explicitly if this behavior is required by your application.
*/
init(options) {
if (typeof FB === 'undefined') {
throw new Error('The Facebook JavaScript SDK must be loaded before calling init.');
}
initOptions = {};
if (options) {
for (const key in options) {
initOptions[key] = options[key];
}
}
if (initOptions.status && typeof console !== 'undefined') {
const warn = console.warn || console.log || function () {}; // eslint-disable-line no-console
warn.call(console, 'The "status" flag passed into' + ' FB.init, when set to true, can interfere with Parse Facebook' + ' integration, so it has been suppressed. Please call' + ' FB.getLoginStatus() explicitly if you require this behavior.');
}
initOptions.status = false;
FB.init(initOptions);
_ParseUser.default._registerAuthenticationProvider(provider);
initialized = true;
},
/**
* Gets whether the user has their account linked to Facebook.
*
* @function isLinked
* @name Parse.FacebookUtils.isLinked
* @param {Parse.User} user User to check for a facebook link.
* The user must be logged in on this device.
* @returns {boolean} true
if the user has their account
* linked to Facebook.
*/
isLinked(user) {
return user._isLinked('facebook');
},
/**
* Logs in a user using Facebook. This method delegates to the Facebook
* SDK to authenticate the user, and then automatically logs in (or
* creates, in the case where it is a new user) a Parse.User.
*
* Standard API:
*
* logIn(permission: string, authData: Object);
*
* Advanced API: Used for handling your own oAuth tokens
* {@link https://docs.parseplatform.org/rest/guide/#linking-users}
*
* logIn(authData: Object, options?: Object);
*
* @function logIn
* @name Parse.FacebookUtils.logIn
* @param {(string | object)} permissions The permissions required for Facebook
* log in. This is a comma-separated string of permissions.
* Alternatively, supply a Facebook authData object as described in our
* REST API docs if you want to handle getting facebook auth tokens
* yourself.
* @param {object} options MasterKey / SessionToken. Alternatively can be used for authData if permissions is a string
* @returns {Promise}
*/
logIn(permissions, options) {
if (!permissions || typeof permissions === 'string') {
if (!initialized) {
throw new Error('You must initialize FacebookUtils before calling logIn.');
}
requestedPermissions = permissions;
return _ParseUser.default.logInWith('facebook', options);
}
return _ParseUser.default.logInWith('facebook', {
authData: permissions
}, options);
},
/**
* Links Facebook to an existing PFUser. This method delegates to the
* Facebook SDK to authenticate the user, and then automatically links
* the account to the Parse.User.
*
* Standard API:
*
* link(user: Parse.User, permission: string, authData?: Object);
*
* Advanced API: Used for handling your own oAuth tokens
* {@link https://docs.parseplatform.org/rest/guide/#linking-users}
*
* link(user: Parse.User, authData: Object, options?: FullOptions);
*
* @function link
* @name Parse.FacebookUtils.link
* @param {Parse.User} user User to link to Facebook. This must be the
* current user.
* @param {(string | object)} permissions The permissions required for Facebook
* log in. This is a comma-separated string of permissions.
* Alternatively, supply a Facebook authData object as described in our
* REST API docs if you want to handle getting facebook auth tokens
* yourself.
* @param {object} options MasterKey / SessionToken. Alternatively can be used for authData if permissions is a string
* @returns {Promise}
*/
link(user, permissions, options) {
if (!permissions || typeof permissions === 'string') {
if (!initialized) {
throw new Error('You must initialize FacebookUtils before calling link.');
}
requestedPermissions = permissions;
return user.linkWith('facebook', options);
}
return user.linkWith('facebook', {
authData: permissions
}, options);
},
/**
* Unlinks the Parse.User from a Facebook account.
*
* @function unlink
* @name Parse.FacebookUtils.unlink
* @param {Parse.User} user User to unlink from Facebook. This must be the
* current user.
* @param {object} options Standard options object with success and error
* callbacks.
* @returns {Promise}
*/
unlink: function (user, options) {
if (!initialized) {
throw new Error('You must initialize FacebookUtils before calling unlink.');
}
return user._unlinkFrom('facebook', options);
},
// Used for testing purposes
_getAuthProvider() {
return provider;
}
};
var _default = exports.default = FacebookUtils;
},{"./ParseUser":38,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],9:[function(_dereq_,module,exports){
"use strict";
var _keysInstanceProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/instance/keys");
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _idbKeyval = _dereq_("idb-keyval");
/* global window */
let IndexedDBStorageController;
if (typeof window !== 'undefined' && window.indexedDB) {
try {
const ParseStore = (0, _idbKeyval.createStore)('parseDB', 'parseStore');
IndexedDBStorageController = {
async: 1,
getItemAsync(path) {
return (0, _idbKeyval.get)(path, ParseStore);
},
setItemAsync(path, value) {
return (0, _idbKeyval.set)(path, value, ParseStore);
},
removeItemAsync(path) {
return (0, _idbKeyval.del)(path, ParseStore);
},
getAllKeysAsync() {
return (0, _keysInstanceProperty(_idbKeyval))(ParseStore);
},
clear() {
return (0, _idbKeyval.clear)(ParseStore);
}
};
} catch (_) {
// IndexedDB not accessible
IndexedDBStorageController = undefined;
}
} else {
// IndexedDB not supported
IndexedDBStorageController = undefined;
}
module.exports = IndexedDBStorageController;
var _default = exports.default = IndexedDBStorageController;
},{"@babel/runtime-corejs3/core-js-stable/instance/keys":77,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"idb-keyval":486}],10:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _Storage = _interopRequireDefault(_dereq_("./Storage"));
var _ParseInstallation = _interopRequireDefault(_dereq_("./ParseInstallation"));
var _uuid = _interopRequireDefault(_dereq_("./uuid"));
const CURRENT_INSTALLATION_KEY = 'currentInstallation';
const CURRENT_INSTALLATION_ID_KEY = 'currentInstallationId';
let iidCache = null;
let currentInstallationCache = null;
let currentInstallationCacheMatchesDisk = false;
const InstallationController = {
async updateInstallationOnDisk(installation) {
const path = _Storage.default.generatePath(CURRENT_INSTALLATION_KEY);
await _Storage.default.setItemAsync(path, (0, _stringify.default)(installation.toJSON()));
this._setCurrentInstallationCache(installation);
},
async currentInstallationId() {
if (typeof iidCache === 'string') {
return iidCache;
}
const path = _Storage.default.generatePath(CURRENT_INSTALLATION_ID_KEY);
let iid = await _Storage.default.getItemAsync(path);
if (!iid) {
iid = (0, _uuid.default)();
return _Storage.default.setItemAsync(path, iid).then(() => {
iidCache = iid;
return iid;
});
}
iidCache = iid;
return iid;
},
async currentInstallation() {
if (currentInstallationCache) {
return currentInstallationCache;
}
if (currentInstallationCacheMatchesDisk) {
return null;
}
const path = _Storage.default.generatePath(CURRENT_INSTALLATION_KEY);
let installationData = await _Storage.default.getItemAsync(path);
currentInstallationCacheMatchesDisk = true;
if (installationData) {
installationData = JSON.parse(installationData);
installationData.className = '_Installation';
const current = _ParseInstallation.default.fromJSON(installationData);
currentInstallationCache = current;
return current;
}
const installationId = await this.currentInstallationId();
const installation = new _ParseInstallation.default();
installation.set('deviceType', _ParseInstallation.default.DEVICE_TYPES.WEB);
installation.set('installationId', installationId);
installation.set('parseVersion', _CoreManager.default.get('VERSION'));
currentInstallationCache = installation;
await _Storage.default.setItemAsync(path, (0, _stringify.default)(installation.toJSON()));
return installation;
},
_clearCache() {
iidCache = null;
currentInstallationCache = null;
currentInstallationCacheMatchesDisk = false;
},
_setInstallationIdCache(iid) {
iidCache = iid;
},
_setCurrentInstallationCache(installation) {
let matchesDisk = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
currentInstallationCache = installation;
currentInstallationCacheMatchesDisk = matchesDisk;
}
};
module.exports = InstallationController;
var _default = exports.default = InstallationController;
},{"./CoreManager":4,"./ParseInstallation":28,"./Storage":43,"./uuid":64,"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],11:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _map = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/map"));
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/keys"));
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _values = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/values"));
var _setTimeout2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/set-timeout"));
var _bind = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/bind"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
var _LiveQuerySubscription = _interopRequireDefault(_dereq_("./LiveQuerySubscription"));
var _promiseUtils = _dereq_("./promiseUtils");
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
// The LiveQuery client inner state
const CLIENT_STATE = {
INITIALIZED: 'initialized',
CONNECTING: 'connecting',
CONNECTED: 'connected',
CLOSED: 'closed',
RECONNECTING: 'reconnecting',
DISCONNECTED: 'disconnected'
};
// The event type the LiveQuery client should sent to server
const OP_TYPES = {
CONNECT: 'connect',
SUBSCRIBE: 'subscribe',
UNSUBSCRIBE: 'unsubscribe',
ERROR: 'error'
};
// The event we get back from LiveQuery server
const OP_EVENTS = {
CONNECTED: 'connected',
SUBSCRIBED: 'subscribed',
UNSUBSCRIBED: 'unsubscribed',
ERROR: 'error',
CREATE: 'create',
UPDATE: 'update',
ENTER: 'enter',
LEAVE: 'leave',
DELETE: 'delete'
};
// The event the LiveQuery client should emit
const CLIENT_EMMITER_TYPES = {
CLOSE: 'close',
ERROR: 'error',
OPEN: 'open'
};
// The event the LiveQuery subscription should emit
const SUBSCRIPTION_EMMITER_TYPES = {
OPEN: 'open',
CLOSE: 'close',
ERROR: 'error',
CREATE: 'create',
UPDATE: 'update',
ENTER: 'enter',
LEAVE: 'leave',
DELETE: 'delete'
};
// Exponentially-growing random delay
const generateInterval = k => {
return Math.random() * Math.min(30, Math.pow(2, k) - 1) * 1000;
};
/**
* Creates a new LiveQueryClient.
* cloud functions.
*
* A wrapper of a standard WebSocket client. We add several useful methods to
* help you connect/disconnect to LiveQueryServer, subscribe/unsubscribe a ParseQuery easily.
*
* javascriptKey and masterKey are used for verifying the LiveQueryClient when it tries
* to connect to the LiveQuery server
*
* We expose three events to help you monitor the status of the LiveQueryClient.
*
*
* const LiveQueryClient = Parse.LiveQueryClient;
* const client = new LiveQueryClient({
* applicationId: '',
* serverURL: '',
* javascriptKey: '',
* masterKey: ''
* });
*
*
* Open - When we establish the WebSocket connection to the LiveQuery server, you'll get this event.
*
* client.on('open', () => {
*
* });
*
* Close - When we lose the WebSocket connection to the LiveQuery server, you'll get this event.
*
* client.on('close', () => {
*
* });
*
* Error - When some network error or LiveQuery server error happens, you'll get this event.
*
* client.on('error', (error) => {
*
* });
*
* @alias Parse.LiveQueryClient
*/
class LiveQueryClient {
/**
* @param {object} options
* @param {string} options.applicationId - applicationId of your Parse app
* @param {string} options.serverURL - the URL of your LiveQuery server
* @param {string} options.javascriptKey (optional)
* @param {string} options.masterKey (optional) Your Parse Master Key. (Node.js only!)
* @param {string} options.sessionToken (optional)
* @param {string} options.installationId (optional)
*/
constructor(_ref) {
var _this = this;
let {
applicationId,
serverURL,
javascriptKey,
masterKey,
sessionToken,
installationId
} = _ref;
(0, _defineProperty2.default)(this, "attempts", void 0);
(0, _defineProperty2.default)(this, "id", void 0);
(0, _defineProperty2.default)(this, "requestId", void 0);
(0, _defineProperty2.default)(this, "applicationId", void 0);
(0, _defineProperty2.default)(this, "serverURL", void 0);
(0, _defineProperty2.default)(this, "javascriptKey", void 0);
(0, _defineProperty2.default)(this, "masterKey", void 0);
(0, _defineProperty2.default)(this, "sessionToken", void 0);
(0, _defineProperty2.default)(this, "installationId", void 0);
(0, _defineProperty2.default)(this, "additionalProperties", void 0);
(0, _defineProperty2.default)(this, "connectPromise", void 0);
(0, _defineProperty2.default)(this, "subscriptions", void 0);
(0, _defineProperty2.default)(this, "socket", void 0);
(0, _defineProperty2.default)(this, "state", void 0);
(0, _defineProperty2.default)(this, "reconnectHandle", void 0);
(0, _defineProperty2.default)(this, "emitter", void 0);
(0, _defineProperty2.default)(this, "on", void 0);
(0, _defineProperty2.default)(this, "emit", void 0);
if (!serverURL || (0, _indexOf.default)(serverURL).call(serverURL, 'ws') !== 0) {
throw new Error('You need to set a proper Parse LiveQuery server url before using LiveQueryClient');
}
this.reconnectHandle = null;
this.attempts = 1;
this.id = 0;
this.requestId = 1;
this.serverURL = serverURL;
this.applicationId = applicationId;
this.javascriptKey = javascriptKey || undefined;
this.masterKey = masterKey || undefined;
this.sessionToken = sessionToken || undefined;
this.installationId = installationId || undefined;
this.additionalProperties = true;
this.connectPromise = (0, _promiseUtils.resolvingPromise)();
this.subscriptions = new _map.default();
this.state = CLIENT_STATE.INITIALIZED;
const EventEmitter = _CoreManager.default.getEventEmitter();
this.emitter = new EventEmitter();
this.on = (eventName, listener) => this.emitter.on(eventName, listener);
this.emit = function (eventName) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return _this.emitter.emit(eventName, ...args);
};
// adding listener so process does not crash
// best practice is for developer to register their own listener
this.on('error', () => {});
}
shouldOpen() {
return this.state === CLIENT_STATE.INITIALIZED || this.state === CLIENT_STATE.DISCONNECTED;
}
/**
* Subscribes to a ParseQuery
*
* If you provide the sessionToken, when the LiveQuery server gets ParseObject's
* updates from parse server, it'll try to check whether the sessionToken fulfills
* the ParseObject's ACL. The LiveQuery server will only send updates to clients whose
* sessionToken is fit for the ParseObject's ACL. You can check the LiveQuery protocol
* here for more details. The subscription you get is the same subscription you get
* from our Standard API.
*
* @param {ParseQuery} query - the ParseQuery you want to subscribe to
* @param {string} sessionToken (optional)
* @returns {LiveQuerySubscription | undefined}
*/
subscribe(query, sessionToken) {
if (!query) {
return;
}
const className = query.className;
const queryJSON = query.toJSON();
const where = queryJSON.where;
const keys = (0, _keys.default)(queryJSON)?.split(',');
const watch = queryJSON.watch?.split(',');
const subscribeRequest = {
op: OP_TYPES.SUBSCRIBE,
requestId: this.requestId,
query: {
className,
where,
keys,
watch
},
sessionToken: undefined
};
if (sessionToken) {
subscribeRequest.sessionToken = sessionToken;
}
const subscription = new _LiveQuerySubscription.default(this.requestId, query, sessionToken);
this.subscriptions.set(this.requestId, subscription);
this.requestId += 1;
this.connectPromise.then(() => {
this.socket.send((0, _stringify.default)(subscribeRequest));
}).catch(error => {
subscription.subscribePromise.reject(error);
});
return subscription;
}
/**
* After calling unsubscribe you'll stop receiving events from the subscription object.
*
* @param {object} subscription - subscription you would like to unsubscribe from.
* @returns {Promise | undefined}
*/
async unsubscribe(subscription) {
if (!subscription) {
return;
}
const unsubscribeRequest = {
op: OP_TYPES.UNSUBSCRIBE,
requestId: subscription.id
};
return this.connectPromise.then(() => {
return this.socket.send((0, _stringify.default)(unsubscribeRequest));
}).then(() => {
return subscription.unsubscribePromise;
});
}
/**
* After open is called, the LiveQueryClient will try to send a connect request
* to the LiveQuery server.
*
*/
open() {
const WebSocketImplementation = _CoreManager.default.getWebSocketController();
if (!WebSocketImplementation) {
this.emit(CLIENT_EMMITER_TYPES.ERROR, 'Can not find WebSocket implementation');
return;
}
if (this.state !== CLIENT_STATE.RECONNECTING) {
this.state = CLIENT_STATE.CONNECTING;
}
this.socket = new WebSocketImplementation(this.serverURL);
this.socket.closingPromise = (0, _promiseUtils.resolvingPromise)();
// Bind WebSocket callbacks
this.socket.onopen = () => {
this._handleWebSocketOpen();
};
this.socket.onmessage = event => {
this._handleWebSocketMessage(event);
};
this.socket.onclose = event => {
this.socket.closingPromise?.resolve(event);
this._handleWebSocketClose();
};
this.socket.onerror = error => {
this._handleWebSocketError(error);
};
}
resubscribe() {
var _context;
(0, _forEach.default)(_context = this.subscriptions).call(_context, (subscription, requestId) => {
const query = subscription.query;
const queryJSON = query.toJSON();
const where = queryJSON.where;
const keys = (0, _keys.default)(queryJSON)?.split(',');
const watch = queryJSON.watch?.split(',');
const className = query.className;
const sessionToken = subscription.sessionToken;
const subscribeRequest = {
op: OP_TYPES.SUBSCRIBE,
requestId,
query: {
className,
where,
keys,
watch
},
sessionToken: undefined
};
if (sessionToken) {
subscribeRequest.sessionToken = sessionToken;
}
this.connectPromise.then(() => {
this.socket.send((0, _stringify.default)(subscribeRequest));
});
});
}
/**
* This method will close the WebSocket connection to this LiveQueryClient,
* cancel the auto reconnect and unsubscribe all subscriptions based on it.
*
* @returns {Promise | undefined} CloseEvent {@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close_event}
*/
async close() {
if (this.state === CLIENT_STATE.INITIALIZED || this.state === CLIENT_STATE.DISCONNECTED) {
return;
}
this.state = CLIENT_STATE.DISCONNECTED;
this.socket?.close();
// Notify each subscription about the close
for (const subscription of (0, _values.default)(_context2 = this.subscriptions).call(_context2)) {
var _context2;
subscription.subscribed = false;
subscription.emit(SUBSCRIPTION_EMMITER_TYPES.CLOSE);
}
this._handleReset();
this.emit(CLIENT_EMMITER_TYPES.CLOSE);
return this.socket?.closingPromise;
}
// ensure we start with valid state if connect is called again after close
_handleReset() {
this.attempts = 1;
this.id = 0;
this.requestId = 1;
this.connectPromise = (0, _promiseUtils.resolvingPromise)();
this.subscriptions = new _map.default();
}
_handleWebSocketOpen() {
const connectRequest = {
op: OP_TYPES.CONNECT,
applicationId: this.applicationId,
javascriptKey: this.javascriptKey,
masterKey: this.masterKey,
sessionToken: this.sessionToken,
installationId: undefined
};
if (this.additionalProperties) {
connectRequest.installationId = this.installationId;
}
this.socket.send((0, _stringify.default)(connectRequest));
}
_handleWebSocketMessage(event) {
let data = event.data;
if (typeof data === 'string') {
data = JSON.parse(data);
}
let subscription = null;
if (data.requestId) {
subscription = this.subscriptions.get(data.requestId) || null;
}
const response = {
clientId: data.clientId,
installationId: data.installationId
};
switch (data.op) {
case OP_EVENTS.CONNECTED:
if (this.state === CLIENT_STATE.RECONNECTING) {
this.resubscribe();
}
this.emit(CLIENT_EMMITER_TYPES.OPEN);
this.id = data.clientId;
this.connectPromise.resolve();
this.state = CLIENT_STATE.CONNECTED;
break;
case OP_EVENTS.SUBSCRIBED:
if (subscription) {
this.attempts = 1;
subscription.subscribed = true;
subscription.subscribePromise.resolve();
(0, _setTimeout2.default)(() => subscription.emit(SUBSCRIPTION_EMMITER_TYPES.OPEN, response), 200);
}
break;
case OP_EVENTS.ERROR:
{
const parseError = new _ParseError.default(data.code, data.error);
if (!this.id) {
this.connectPromise.reject(parseError);
this.state = CLIENT_STATE.DISCONNECTED;
}
if (data.requestId) {
if (subscription) {
subscription.subscribePromise.reject(parseError);
(0, _setTimeout2.default)(() => subscription.emit(SUBSCRIPTION_EMMITER_TYPES.ERROR, data.error), 200);
}
} else {
this.emit(CLIENT_EMMITER_TYPES.ERROR, data.error);
}
if (data.error === 'Additional properties not allowed') {
this.additionalProperties = false;
}
if (data.reconnect) {
this._handleReconnect();
}
break;
}
case OP_EVENTS.UNSUBSCRIBED:
{
if (subscription) {
this.subscriptions.delete(data.requestId);
subscription.subscribed = false;
subscription.unsubscribePromise.resolve();
}
break;
}
default:
{
// create, update, enter, leave, delete cases
if (!subscription) {
break;
}
let override = false;
if (data.original) {
override = true;
delete data.original.__type;
// Check for removed fields
for (const field in data.original) {
if (!(field in data.object)) {
data.object[field] = undefined;
}
}
data.original = _ParseObject.default.fromJSON(data.original, false);
}
delete data.object.__type;
const parseObject = _ParseObject.default.fromJSON(data.object, !(subscription.query && subscription.query._select) ? override : false);
if (data.original) {
subscription.emit(data.op, parseObject, data.original, response);
} else {
subscription.emit(data.op, parseObject, response);
}
const localDatastore = _CoreManager.default.getLocalDatastore();
if (override && localDatastore.isEnabled) {
localDatastore._updateObjectIfPinned(parseObject).then(() => {});
}
}
}
}
_handleWebSocketClose() {
if (this.state === CLIENT_STATE.DISCONNECTED) {
return;
}
this.state = CLIENT_STATE.CLOSED;
this.emit(CLIENT_EMMITER_TYPES.CLOSE);
// Notify each subscription about the close
for (const subscription of (0, _values.default)(_context3 = this.subscriptions).call(_context3)) {
var _context3;
subscription.emit(SUBSCRIPTION_EMMITER_TYPES.CLOSE);
}
this._handleReconnect();
}
_handleWebSocketError(error) {
this.emit(CLIENT_EMMITER_TYPES.ERROR, error);
for (const subscription of (0, _values.default)(_context4 = this.subscriptions).call(_context4)) {
var _context4;
subscription.emit(SUBSCRIPTION_EMMITER_TYPES.ERROR, error);
}
this._handleReconnect();
}
_handleReconnect() {
var _context5;
// if closed or currently reconnecting we stop attempting to reconnect
if (this.state === CLIENT_STATE.DISCONNECTED) {
return;
}
this.state = CLIENT_STATE.RECONNECTING;
const time = generateInterval(this.attempts);
// handle case when both close/error occur at frequent rates we ensure we do not reconnect unnecessarily.
// we're unable to distinguish different between close/error when we're unable to reconnect therefore
// we try to reconnect in both cases
// server side ws and browser WebSocket behave differently in when close/error get triggered
if (this.reconnectHandle) {
clearTimeout(this.reconnectHandle);
}
this.reconnectHandle = (0, _setTimeout2.default)((0, _bind.default)(_context5 = () => {
this.attempts++;
this.connectPromise = (0, _promiseUtils.resolvingPromise)();
this.open();
}).call(_context5, this), time);
}
}
var _default = exports.default = LiveQueryClient;
},{"./CoreManager":4,"./LiveQuerySubscription":12,"./ParseError":24,"./ParseObject":30,"./promiseUtils":61,"@babel/runtime-corejs3/core-js-stable/instance/bind":67,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/instance/keys":77,"@babel/runtime-corejs3/core-js-stable/instance/values":84,"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/map":86,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/set-timeout":99,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],12:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _promiseUtils = _dereq_("./promiseUtils");
/**
* Creates a new LiveQuery Subscription.
* cloud functions.
*
* Response Object - Contains data from the client that made the request
*
* - clientId
* - installationId - requires Parse Server 4.0.0+
*
*
*
* Open Event - When you call query.subscribe(), we send a subscribe request to
* the LiveQuery server, when we get the confirmation from the LiveQuery server,
* this event will be emitted. When the client loses WebSocket connection to the
* LiveQuery server, we will try to auto reconnect the LiveQuery server. If we
* reconnect the LiveQuery server and successfully resubscribe the ParseQuery,
* you'll also get this event.
*
*
* subscription.on('open', (response) => {
*
* });
*
* Create Event - When a new ParseObject is created and it fulfills the ParseQuery you subscribe,
* you'll get this event. The object is the ParseObject which is created.
*
*
* subscription.on('create', (object, response) => {
*
* });
*
* Update Event - When an existing ParseObject (original) which fulfills the ParseQuery you subscribe
* is updated (The ParseObject fulfills the ParseQuery before and after changes),
* you'll get this event. The object is the ParseObject which is updated.
* Its content is the latest value of the ParseObject.
*
* Parse-Server 3.1.3+ Required for original object parameter
*
*
* subscription.on('update', (object, original, response) => {
*
* });
*
* Enter Event - When an existing ParseObject's (original) old value doesn't fulfill the ParseQuery
* but its new value fulfills the ParseQuery, you'll get this event. The object is the
* ParseObject which enters the ParseQuery. Its content is the latest value of the ParseObject.
*
* Parse-Server 3.1.3+ Required for original object parameter
*
*
* subscription.on('enter', (object, original, response) => {
*
* });
*
*
* Update Event - When an existing ParseObject's old value fulfills the ParseQuery but its new value
* doesn't fulfill the ParseQuery, you'll get this event. The object is the ParseObject
* which leaves the ParseQuery. Its content is the latest value of the ParseObject.
*
*
* subscription.on('leave', (object, response) => {
*
* });
*
*
* Delete Event - When an existing ParseObject which fulfills the ParseQuery is deleted, you'll
* get this event. The object is the ParseObject which is deleted.
*
*
* subscription.on('delete', (object, response) => {
*
* });
*
*
* Close Event - When the client loses the WebSocket connection to the LiveQuery
* server and we stop receiving events, you'll get this event.
*
*
* subscription.on('close', () => {
*
* });
*/
class Subscription {
/*
* @param {string | number} id - subscription id
* @param {string} query - query to subscribe to
* @param {string} sessionToken - optional session token
*/
constructor(id, query, sessionToken) {
var _this = this;
(0, _defineProperty2.default)(this, "id", void 0);
(0, _defineProperty2.default)(this, "query", void 0);
(0, _defineProperty2.default)(this, "sessionToken", void 0);
(0, _defineProperty2.default)(this, "subscribePromise", void 0);
(0, _defineProperty2.default)(this, "unsubscribePromise", void 0);
(0, _defineProperty2.default)(this, "subscribed", void 0);
(0, _defineProperty2.default)(this, "emitter", void 0);
(0, _defineProperty2.default)(this, "on", void 0);
(0, _defineProperty2.default)(this, "emit", void 0);
this.id = id;
this.query = query;
this.sessionToken = sessionToken;
this.subscribePromise = (0, _promiseUtils.resolvingPromise)();
this.unsubscribePromise = (0, _promiseUtils.resolvingPromise)();
this.subscribed = false;
const EventEmitter = _CoreManager.default.getEventEmitter();
this.emitter = new EventEmitter();
this.on = (eventName, listener) => this.emitter.on(eventName, listener);
this.emit = function (eventName) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return _this.emitter.emit(eventName, ...args);
};
// adding listener so process does not crash
// best practice is for developer to register their own listener
this.on('error', () => {});
}
/**
* Close the subscription
*
* @returns {Promise}
*/
unsubscribe() {
return _CoreManager.default.getLiveQueryController().getDefaultLiveQueryClient().then(liveQueryClient => {
this.emit('close');
return liveQueryClient.unsubscribe(this);
});
}
}
var _default = exports.default = Subscription;
},{"./CoreManager":4,"./promiseUtils":61,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],13:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _set = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/set"));
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _filter = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/filter"));
var _includes = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/includes"));
var _startsWith = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/starts-with"));
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _map = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _concat = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _from = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/from"));
var _find = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/find"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _LocalDatastoreController = _interopRequireDefault(_dereq_("./LocalDatastoreController"));
var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
/**
* Provides a local datastore which can be used to store and retrieve Parse.Object
.
* To enable this functionality, call Parse.enableLocalDatastore()
.
*
* Pin object to add to local datastore
*
* await object.pin();
* await object.pinWithName('pinName');
*
* Query pinned objects
*
* query.fromLocalDatastore();
* query.fromPin();
* query.fromPinWithName();
*
* const localObjects = await query.find();
*
* @class Parse.LocalDatastore
* @static
*/
const LocalDatastore = {
isEnabled: false,
isSyncing: false,
fromPinWithName(name) {
const controller = _CoreManager.default.getLocalDatastoreController();
return controller.fromPinWithName(name);
},
async pinWithName(name, value) {
const controller = _CoreManager.default.getLocalDatastoreController();
return controller.pinWithName(name, value);
},
async unPinWithName(name) {
const controller = _CoreManager.default.getLocalDatastoreController();
return controller.unPinWithName(name);
},
_getAllContents() {
const controller = _CoreManager.default.getLocalDatastoreController();
return controller.getAllContents();
},
// Use for testing
async _getRawStorage() {
const controller = _CoreManager.default.getLocalDatastoreController();
return controller.getRawStorage();
},
async _clear() {
const controller = _CoreManager.default.getLocalDatastoreController();
return controller.clear();
},
// Pin the object and children recursively
// Saves the object and children key to Pin Name
async _handlePinAllWithName(name, objects) {
const pinName = this.getPinName(name);
const toPinPromises = [];
const objectKeys = [];
for (const parent of objects) {
const children = this._getChildren(parent);
const parentKey = this.getKeyForObject(parent);
const json = parent._toFullJSON(undefined, true);
if (parent._localId) {
json._localId = parent._localId;
}
children[parentKey] = json;
for (const objectKey in children) {
objectKeys.push(objectKey);
toPinPromises.push(this.pinWithName(objectKey, [children[objectKey]]));
}
}
const fromPinPromise = this.fromPinWithName(pinName);
const [pinned] = await _promise.default.all([fromPinPromise, toPinPromises]);
const toPin = [...new _set.default([...(pinned || []), ...objectKeys])];
return this.pinWithName(pinName, toPin);
},
// Removes object and children keys from pin name
// Keeps the object and children pinned
async _handleUnPinAllWithName(name, objects) {
const localDatastore = await this._getAllContents();
const pinName = this.getPinName(name);
const promises = [];
let objectKeys = [];
for (const parent of objects) {
const children = this._getChildren(parent);
const parentKey = this.getKeyForObject(parent);
objectKeys.push(parentKey, ...(0, _keys.default)(children));
}
objectKeys = [...new _set.default(objectKeys)];
let pinned = localDatastore[pinName] || [];
pinned = (0, _filter.default)(pinned).call(pinned, item => !(0, _includes.default)(objectKeys).call(objectKeys, item));
if (pinned.length == 0) {
promises.push(this.unPinWithName(pinName));
delete localDatastore[pinName];
} else {
promises.push(this.pinWithName(pinName, pinned));
localDatastore[pinName] = pinned;
}
for (const objectKey of objectKeys) {
let hasReference = false;
for (const key in localDatastore) {
if (key === _LocalDatastoreUtils.DEFAULT_PIN || (0, _startsWith.default)(key).call(key, _LocalDatastoreUtils.PIN_PREFIX)) {
const pinnedObjects = localDatastore[key] || [];
if ((0, _includes.default)(pinnedObjects).call(pinnedObjects, objectKey)) {
hasReference = true;
break;
}
}
}
if (!hasReference) {
promises.push(this.unPinWithName(objectKey));
}
}
return _promise.default.all(promises);
},
// Retrieve all pointer fields from object recursively
_getChildren(object) {
const encountered = {};
const json = object._toFullJSON(undefined, true);
for (const key in json) {
if (json[key] && json[key].__type && json[key].__type === 'Object') {
this._traverse(json[key], encountered);
}
}
return encountered;
},
_traverse(object, encountered) {
if (!object.objectId) {
return;
} else {
const objectKey = this.getKeyForObject(object);
if (encountered[objectKey]) {
return;
}
encountered[objectKey] = object;
}
for (const key in object) {
let json = object[key];
if (!object[key]) {
json = object;
}
if (json.__type && json.__type === 'Object') {
this._traverse(json, encountered);
}
}
},
// Transform keys in pin name to objects
async _serializeObjectsFromPinName(name) {
var _context;
const localDatastore = await this._getAllContents();
const allObjects = [];
for (const key in localDatastore) {
if ((0, _startsWith.default)(key).call(key, _LocalDatastoreUtils.OBJECT_PREFIX)) {
allObjects.push(localDatastore[key][0]);
}
}
if (!name) {
return allObjects;
}
const pinName = this.getPinName(name);
const pinned = localDatastore[pinName];
if (!(0, _isArray.default)(pinned)) {
return [];
}
const promises = (0, _map.default)(pinned).call(pinned, objectKey => this.fromPinWithName(objectKey));
let objects = await _promise.default.all(promises);
objects = (0, _concat.default)(_context = []).call(_context, ...objects);
return (0, _filter.default)(objects).call(objects, object => object != null);
},
// Replaces object pointers with pinned pointers
// The object pointers may contain old data
// Uses Breadth First Search Algorithm
async _serializeObject(objectKey, localDatastore) {
let LDS = localDatastore;
if (!LDS) {
LDS = await this._getAllContents();
}
if (!LDS[objectKey] || LDS[objectKey].length === 0) {
return null;
}
const root = LDS[objectKey][0];
const queue = [];
const meta = {};
let uniqueId = 0;
meta[uniqueId] = root;
queue.push(uniqueId);
while (queue.length !== 0) {
const nodeId = queue.shift();
const subTreeRoot = meta[nodeId];
for (const field in subTreeRoot) {
const value = subTreeRoot[field];
if (value.__type && value.__type === 'Object') {
const key = this.getKeyForObject(value);
if (LDS[key] && LDS[key].length > 0) {
const pointer = LDS[key][0];
uniqueId++;
meta[uniqueId] = pointer;
subTreeRoot[field] = pointer;
queue.push(uniqueId);
}
}
}
}
return root;
},
// Called when an object is save / fetched
// Update object pin value
async _updateObjectIfPinned(object) {
if (!this.isEnabled) {
return;
}
const objectKey = this.getKeyForObject(object);
const pinned = await this.fromPinWithName(objectKey);
if (!pinned || pinned.length === 0) {
return;
}
return this.pinWithName(objectKey, [object._toFullJSON()]);
},
// Called when object is destroyed
// Unpin object and remove all references from pin names
// TODO: Destroy children?
async _destroyObjectIfPinned(object) {
if (!this.isEnabled) {
return;
}
const localDatastore = await this._getAllContents();
const objectKey = this.getKeyForObject(object);
const pin = localDatastore[objectKey];
if (!pin) {
return;
}
const promises = [this.unPinWithName(objectKey)];
delete localDatastore[objectKey];
for (const key in localDatastore) {
if (key === _LocalDatastoreUtils.DEFAULT_PIN || (0, _startsWith.default)(key).call(key, _LocalDatastoreUtils.PIN_PREFIX)) {
let pinned = localDatastore[key] || [];
if ((0, _includes.default)(pinned).call(pinned, objectKey)) {
pinned = (0, _filter.default)(pinned).call(pinned, item => item !== objectKey);
if (pinned.length == 0) {
promises.push(this.unPinWithName(key));
delete localDatastore[key];
} else {
promises.push(this.pinWithName(key, pinned));
localDatastore[key] = pinned;
}
}
}
}
return _promise.default.all(promises);
},
// Update pin and references of the unsaved object
async _updateLocalIdForObject(localId, object) {
if (!this.isEnabled) {
return;
}
const localKey = `${_LocalDatastoreUtils.OBJECT_PREFIX}${object.className}_${localId}`;
const objectKey = this.getKeyForObject(object);
const unsaved = await this.fromPinWithName(localKey);
if (!unsaved || unsaved.length === 0) {
return;
}
const promises = [this.unPinWithName(localKey), this.pinWithName(objectKey, unsaved)];
const localDatastore = await this._getAllContents();
for (const key in localDatastore) {
if (key === _LocalDatastoreUtils.DEFAULT_PIN || (0, _startsWith.default)(key).call(key, _LocalDatastoreUtils.PIN_PREFIX)) {
let pinned = localDatastore[key] || [];
if ((0, _includes.default)(pinned).call(pinned, localKey)) {
pinned = (0, _filter.default)(pinned).call(pinned, item => item !== localKey);
pinned.push(objectKey);
promises.push(this.pinWithName(key, pinned));
localDatastore[key] = pinned;
}
}
}
return _promise.default.all(promises);
},
/**
* Updates Local Datastore from Server
*
*
* await Parse.LocalDatastore.updateFromServer();
*
*
* @function updateFromServer
* @name Parse.LocalDatastore.updateFromServer
* @static
*/
async updateFromServer() {
var _context2;
if (!this.checkIfEnabled() || this.isSyncing) {
return;
}
const localDatastore = await this._getAllContents();
const keys = [];
for (const key in localDatastore) {
if ((0, _startsWith.default)(key).call(key, _LocalDatastoreUtils.OBJECT_PREFIX)) {
keys.push(key);
}
}
if (keys.length === 0) {
return;
}
this.isSyncing = true;
const pointersHash = {};
for (const key of keys) {
// Ignore the OBJECT_PREFIX
let [,, className, objectId] = key.split('_');
// User key is split into [ 'Parse', 'LDS', '', 'User', 'objectId' ]
if (key.split('_').length === 5 && key.split('_')[3] === 'User') {
className = '_User';
objectId = key.split('_')[4];
}
if ((0, _startsWith.default)(objectId).call(objectId, 'local')) {
continue;
}
if (!(className in pointersHash)) {
pointersHash[className] = new _set.default();
}
pointersHash[className].add(objectId);
}
const queryPromises = (0, _map.default)(_context2 = (0, _keys.default)(pointersHash)).call(_context2, className => {
const objectIds = (0, _from.default)(pointersHash[className]);
const query = new _ParseQuery.default(className);
query.limit(objectIds.length);
if (objectIds.length === 1) {
query.equalTo('objectId', objectIds[0]);
} else {
query.containedIn('objectId', objectIds);
}
return (0, _find.default)(query).call(query);
});
try {
const responses = await _promise.default.all(queryPromises);
const objects = (0, _concat.default)([]).apply([], responses);
const pinPromises = (0, _map.default)(objects).call(objects, object => {
const objectKey = this.getKeyForObject(object);
return this.pinWithName(objectKey, object._toFullJSON());
});
await _promise.default.all(pinPromises);
this.isSyncing = false;
} catch (error) {
console.error('Error syncing LocalDatastore: ', error);
this.isSyncing = false;
}
},
getKeyForObject(object) {
const objectId = object.objectId || object._getId();
return `${_LocalDatastoreUtils.OBJECT_PREFIX}${object.className}_${objectId}`;
},
getPinName(pinName) {
if (!pinName || pinName === _LocalDatastoreUtils.DEFAULT_PIN) {
return _LocalDatastoreUtils.DEFAULT_PIN;
}
return _LocalDatastoreUtils.PIN_PREFIX + pinName;
},
checkIfEnabled() {
if (!this.isEnabled) {
console.error('Parse.enableLocalDatastore() must be called first');
}
return this.isEnabled;
}
};
module.exports = LocalDatastore;
var _default = exports.default = LocalDatastore;
_CoreManager.default.setLocalDatastoreController(_LocalDatastoreController.default);
_CoreManager.default.setLocalDatastore(LocalDatastore);
},{"./CoreManager":4,"./LocalDatastoreController":15,"./LocalDatastoreUtils":17,"./ParseQuery":33,"@babel/runtime-corejs3/core-js-stable/array/from":65,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/concat":68,"@babel/runtime-corejs3/core-js-stable/instance/filter":71,"@babel/runtime-corejs3/core-js-stable/instance/find":73,"@babel/runtime-corejs3/core-js-stable/instance/includes":75,"@babel/runtime-corejs3/core-js-stable/instance/map":78,"@babel/runtime-corejs3/core-js-stable/instance/starts-with":83,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/core-js-stable/set":100,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],14:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _reduce = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/reduce"));
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _map = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
var _Storage = _interopRequireDefault(_dereq_("./Storage"));
const LocalDatastoreController = {
async fromPinWithName(name) {
const values = await _Storage.default.getItemAsync(name);
if (!values) {
return [];
}
const objects = JSON.parse(values);
return objects;
},
pinWithName(name, value) {
const values = (0, _stringify.default)(value);
return _Storage.default.setItemAsync(name, values);
},
unPinWithName(name) {
return _Storage.default.removeItemAsync(name);
},
async getAllContents() {
const keys = await _Storage.default.getAllKeysAsync();
return (0, _reduce.default)(keys).call(keys, async (previousPromise, key) => {
const LDS = await previousPromise;
if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
const value = await _Storage.default.getItemAsync(key);
try {
LDS[key] = JSON.parse(value);
} catch (error) {
console.error('Error getAllContents: ', error);
}
}
return LDS;
}, _promise.default.resolve({}));
},
// Used for testing
async getRawStorage() {
const keys = await _Storage.default.getAllKeysAsync();
return (0, _reduce.default)(keys).call(keys, async (previousPromise, key) => {
const LDS = await previousPromise;
const value = await _Storage.default.getItemAsync(key);
LDS[key] = value;
return LDS;
}, _promise.default.resolve({}));
},
async clear() {
const keys = await _Storage.default.getAllKeysAsync();
const toRemove = [];
for (const key of keys) {
if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
toRemove.push(key);
}
}
const promises = (0, _map.default)(toRemove).call(toRemove, this.unPinWithName);
return _promise.default.all(promises);
}
};
module.exports = LocalDatastoreController;
var _default = exports.default = LocalDatastoreController;
},{"./LocalDatastoreUtils":17,"./Storage":43,"@babel/runtime-corejs3/core-js-stable/instance/map":78,"@babel/runtime-corejs3/core-js-stable/instance/reduce":79,"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],15:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _LocalDatastoreController = _interopRequireDefault(_dereq_("./LocalDatastoreController.react-native"));
var _LocalDatastoreController2 = _interopRequireDefault(_dereq_("./LocalDatastoreController.default"));
let LocalDatastoreController = _LocalDatastoreController2.default;
module.exports = LocalDatastoreController;
var _default = exports.default = LocalDatastoreController;
},{"./LocalDatastoreController.default":14,"./LocalDatastoreController.react-native":16,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],16:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _map = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
var _StorageController = _interopRequireDefault(_dereq_("./StorageController.react-native"));
const LocalDatastoreController = {
async fromPinWithName(name) {
const values = await _StorageController.default.getItemAsync(name);
if (!values) {
return [];
}
const objects = JSON.parse(values);
return objects;
},
async pinWithName(name, value) {
try {
const values = (0, _stringify.default)(value);
await _StorageController.default.setItemAsync(name, values);
} catch (e) {
// Quota exceeded, possibly due to Safari Private Browsing mode
console.error(e.message);
}
},
unPinWithName(name) {
return _StorageController.default.removeItemAsync(name);
},
async getAllContents() {
const keys = await _StorageController.default.getAllKeysAsync();
const batch = [];
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
batch.push(key);
}
}
const LDS = {};
let results = [];
try {
results = await _StorageController.default.multiGet(batch);
} catch (error) {
console.error('Error getAllContents: ', error);
return {};
}
(0, _forEach.default)(results).call(results, pair => {
const [key, value] = pair;
try {
LDS[key] = JSON.parse(value);
} catch (error) {
LDS[key] = null;
}
});
return LDS;
},
// Used for testing
async getRawStorage() {
var _context;
const keys = await _StorageController.default.getAllKeysAsync();
const storage = {};
const results = await _StorageController.default.multiGet(keys);
(0, _map.default)(_context = results).call(_context, pair => {
const [key, value] = pair;
storage[key] = value;
});
return storage;
},
async clear() {
const keys = await _StorageController.default.getAllKeysAsync();
const batch = [];
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
batch.push(key);
}
}
await _StorageController.default.multiRemove(batch).catch(error => console.error('Error clearing local datastore: ', error));
}
};
module.exports = LocalDatastoreController;
var _default = exports.default = LocalDatastoreController;
},{"./LocalDatastoreUtils":17,"./StorageController.react-native":47,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/instance/map":78,"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],17:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.PIN_PREFIX = exports.OBJECT_PREFIX = exports.DEFAULT_PIN = void 0;
exports.isLocalDatastoreKey = isLocalDatastoreKey;
var _startsWith = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/starts-with"));
const DEFAULT_PIN = exports.DEFAULT_PIN = '_default';
const PIN_PREFIX = exports.PIN_PREFIX = 'parsePin_';
const OBJECT_PREFIX = exports.OBJECT_PREFIX = 'Parse_LDS_';
function isLocalDatastoreKey(key) {
return !!(key && (key === DEFAULT_PIN || (0, _startsWith.default)(key).call(key, PIN_PREFIX) || (0, _startsWith.default)(key).call(key, OBJECT_PREFIX)));
}
},{"@babel/runtime-corejs3/core-js-stable/instance/starts-with":83,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],18:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.commitServerChanges = commitServerChanges;
exports.defaultState = defaultState;
exports.estimateAttribute = estimateAttribute;
exports.estimateAttributes = estimateAttributes;
exports.mergeFirstPendingState = mergeFirstPendingState;
exports.popPendingState = popPendingState;
exports.pushPendingState = pushPendingState;
exports.setPendingOp = setPendingOp;
exports.setServerData = setServerData;
var _includes = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/includes"));
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _encode = _interopRequireDefault(_dereq_("./encode"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
var _TaskQueue = _interopRequireDefault(_dereq_("./TaskQueue"));
var _ParseOp = _dereq_("./ParseOp");
function defaultState() {
return {
serverData: {},
pendingOps: [{}],
objectCache: {},
tasks: new _TaskQueue.default(),
existed: false
};
}
function setServerData(serverData, attributes) {
for (const attr in attributes) {
if (typeof attributes[attr] !== 'undefined') {
serverData[attr] = attributes[attr];
} else {
delete serverData[attr];
}
}
}
function setPendingOp(pendingOps, attr, op) {
const last = pendingOps.length - 1;
if (op) {
pendingOps[last][attr] = op;
} else {
delete pendingOps[last][attr];
}
}
function pushPendingState(pendingOps) {
pendingOps.push({});
}
function popPendingState(pendingOps) {
const first = pendingOps.shift();
if (!pendingOps.length) {
pendingOps[0] = {};
}
return first;
}
function mergeFirstPendingState(pendingOps) {
const first = popPendingState(pendingOps);
const next = pendingOps[0];
for (const attr in first) {
if (next[attr] && first[attr]) {
const merged = next[attr].mergeWith(first[attr]);
if (merged) {
next[attr] = merged;
}
} else {
next[attr] = first[attr];
}
}
}
function estimateAttribute(serverData, pendingOps, object, attr) {
let value = serverData[attr];
for (let i = 0; i < pendingOps.length; i++) {
if (pendingOps[i][attr]) {
if (pendingOps[i][attr] instanceof _ParseOp.RelationOp) {
if (object.id) {
value = pendingOps[i][attr].applyTo(value, object, attr);
}
} else {
value = pendingOps[i][attr].applyTo(value);
}
}
}
return value;
}
function estimateAttributes(serverData, pendingOps, object) {
const data = {};
for (var attr in serverData) {
data[attr] = serverData[attr];
}
for (let i = 0; i < pendingOps.length; i++) {
for (attr in pendingOps[i]) {
if (pendingOps[i][attr] instanceof _ParseOp.RelationOp) {
if (object.id) {
data[attr] = pendingOps[i][attr].applyTo(data[attr], object, attr);
}
} else {
if ((0, _includes.default)(attr).call(attr, '.')) {
// similar to nestedSet function
const fields = attr.split('.');
const last = fields[fields.length - 1];
let object = data;
for (let i = 0; i < fields.length - 1; i++) {
const key = fields[i];
if (!(key in object)) {
const nextKey = fields[i + 1];
if (!isNaN(nextKey)) {
object[key] = [];
} else {
object[key] = {};
}
} else {
if ((0, _isArray.default)(object[key])) {
object[key] = [...object[key]];
} else {
object[key] = {
...object[key]
};
}
}
object = object[key];
}
object[last] = pendingOps[i][attr].applyTo(object[last]);
} else {
data[attr] = pendingOps[i][attr].applyTo(data[attr]);
}
}
}
}
return data;
}
/**
* Allows setting properties/variables deep in an object.
* Converts a.b into { a: { b: value } } for dot notation on Objects
* Converts a.0.b into { a: [{ b: value }] } for dot notation on Arrays
*
* @param obj The object to assign the value to
* @param key The key to assign. If it's in a deeper path, then use dot notation (`prop1.prop2.prop3`)
* Note that intermediate object(s) in the nested path are automatically created if they don't exist.
* @param value The value to assign. If it's an `undefined` then the key is deleted.
*/
function nestedSet(obj, key, value) {
const paths = key.split('.');
for (let i = 0; i < paths.length - 1; i++) {
const path = paths[i];
if (!(path in obj)) {
const nextPath = paths[i + 1];
if (!isNaN(nextPath)) {
obj[path] = [];
} else {
obj[path] = {};
}
}
obj = obj[path];
}
if (typeof value === 'undefined') {
delete obj[paths[paths.length - 1]];
} else {
obj[paths[paths.length - 1]] = value;
}
}
function commitServerChanges(serverData, objectCache, changes) {
const ParseObject = _CoreManager.default.getParseObject();
for (const attr in changes) {
const val = changes[attr];
nestedSet(serverData, attr, val);
if (val && typeof val === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
const json = (0, _encode.default)(val, false, true);
objectCache[attr] = (0, _stringify.default)(json);
}
}
}
},{"./CoreManager":4,"./ParseFile":25,"./ParseOp":31,"./ParseRelation":34,"./TaskQueue":49,"./encode":56,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/includes":75,"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],19:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _filter = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/filter"));
var _slice = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/slice"));
var _isInteger = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/number/is-integer"));
var _map = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _equals = _interopRequireDefault(_dereq_("./equals"));
var _decode = _interopRequireDefault(_dereq_("./decode"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _ParsePolygon = _interopRequireDefault(_dereq_("./ParsePolygon"));
var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
/**
* contains -- Determines if an object is contained in a list with special handling for Parse pointers.
*
* @param haystack
* @param needle
* @private
* @returns {boolean}
*/
function contains(haystack, needle) {
if (needle && needle.__type && (needle.__type === 'Pointer' || needle.__type === 'Object')) {
for (const i in haystack) {
const ptr = haystack[i];
if (typeof ptr === 'string' && ptr === needle.objectId) {
return true;
}
if (ptr.className === needle.className && ptr.objectId === needle.objectId) {
return true;
}
}
return false;
}
if ((0, _isArray.default)(needle)) {
for (const need of needle) {
if (contains(haystack, need)) {
return true;
}
}
}
return (0, _indexOf.default)(haystack).call(haystack, needle) > -1;
}
function transformObject(object) {
if (object._toFullJSON) {
return object._toFullJSON();
}
return object;
}
/**
* matchesQuery -- Determines if an object would be returned by a Parse Query
* It's a lightweight, where-clause only implementation of a full query engine.
* Since we find queries that match objects, rather than objects that match
* queries, we can avoid building a full-blown query tool.
*
* @param className
* @param object
* @param objects
* @param query
* @private
* @returns {boolean}
*/
function matchesQuery(className, object, objects, query) {
if (object.className !== className) {
return false;
}
let obj = object;
let q = query;
if (object.toJSON) {
obj = object.toJSON();
}
if (query.toJSON) {
q = query.toJSON().where;
}
obj.className = className;
for (const field in q) {
if (!matchesKeyConstraints(className, obj, objects, field, q[field])) {
return false;
}
}
return true;
}
function equalObjectsGeneric(obj, compareTo, eqlFn) {
if ((0, _isArray.default)(obj)) {
for (let i = 0; i < obj.length; i++) {
if (eqlFn(obj[i], compareTo)) {
return true;
}
}
return false;
}
return eqlFn(obj, compareTo);
}
/**
* @typedef RelativeTimeToDateResult
* @property {string} status The conversion status, `error` if conversion failed or
* `success` if conversion succeeded.
* @property {string} info The error message if conversion failed, or the relative
* time indication (`past`, `present`, `future`) if conversion succeeded.
* @property {Date|undefined} result The converted date, or `undefined` if conversion
* failed.
*/
/**
* Converts human readable relative date string, for example, 'in 10 days' to a date
* relative to now.
*
* @param {string} text The text to convert.
* @param {Date} [now] The date from which add or subtract. Default is now.
* @returns {RelativeTimeToDateResult}
*/
function relativeTimeToDate(text) {
let now = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Date();
text = text.toLowerCase();
let parts = text.split(' ');
// Filter out whitespace
parts = (0, _filter.default)(parts).call(parts, part => part !== '');
const future = parts[0] === 'in';
const past = parts[parts.length - 1] === 'ago';
if (!future && !past && text !== 'now') {
return {
status: 'error',
info: "Time should either start with 'in' or end with 'ago'"
};
}
if (future && past) {
return {
status: 'error',
info: "Time cannot have both 'in' and 'ago'"
};
}
// strip the 'ago' or 'in'
if (future) {
parts = (0, _slice.default)(parts).call(parts, 1);
} else {
// past
parts = (0, _slice.default)(parts).call(parts, 0, parts.length - 1);
}
if (parts.length % 2 !== 0 && text !== 'now') {
return {
status: 'error',
info: 'Invalid time string. Dangling unit or number.'
};
}
const pairs = [];
while (parts.length) {
pairs.push([parts.shift(), parts.shift()]);
}
let seconds = 0;
for (const [num, interval] of pairs) {
const val = Number(num);
if (!(0, _isInteger.default)(val)) {
return {
status: 'error',
info: `'${num}' is not an integer.`
};
}
switch (interval) {
case 'yr':
case 'yrs':
case 'year':
case 'years':
seconds += val * 31536000; // 365 * 24 * 60 * 60
break;
case 'wk':
case 'wks':
case 'week':
case 'weeks':
seconds += val * 604800; // 7 * 24 * 60 * 60
break;
case 'd':
case 'day':
case 'days':
seconds += val * 86400; // 24 * 60 * 60
break;
case 'hr':
case 'hrs':
case 'hour':
case 'hours':
seconds += val * 3600; // 60 * 60
break;
case 'min':
case 'mins':
case 'minute':
case 'minutes':
seconds += val * 60;
break;
case 'sec':
case 'secs':
case 'second':
case 'seconds':
seconds += val;
break;
default:
return {
status: 'error',
info: `Invalid interval: '${interval}'`
};
}
}
const milliseconds = seconds * 1000;
if (future) {
return {
status: 'success',
info: 'future',
result: new Date(now.valueOf() + milliseconds)
};
} else if (past) {
return {
status: 'success',
info: 'past',
result: new Date(now.valueOf() - milliseconds)
};
} else {
return {
status: 'success',
info: 'present',
result: new Date(now.valueOf())
};
}
}
/**
* Determines whether an object matches a single key's constraints
*
* @param className
* @param object
* @param objects
* @param key
* @param constraints
* @private
* @returns {boolean}
*/
function matchesKeyConstraints(className, object, objects, key, constraints) {
if (constraints === null) {
return false;
}
if ((0, _indexOf.default)(key).call(key, '.') >= 0) {
// Key references a subobject
const keyComponents = key.split('.');
const subObjectKey = keyComponents[0];
const keyRemainder = (0, _slice.default)(keyComponents).call(keyComponents, 1).join('.');
return matchesKeyConstraints(className, object[subObjectKey] || {}, objects, keyRemainder, constraints);
}
let i;
if (key === '$or') {
for (i = 0; i < constraints.length; i++) {
if (matchesQuery(className, object, objects, constraints[i])) {
return true;
}
}
return false;
}
if (key === '$and') {
for (i = 0; i < constraints.length; i++) {
if (!matchesQuery(className, object, objects, constraints[i])) {
return false;
}
}
return true;
}
if (key === '$nor') {
for (i = 0; i < constraints.length; i++) {
if (matchesQuery(className, object, objects, constraints[i])) {
return false;
}
}
return true;
}
if (key === '$relatedTo') {
// Bail! We can't handle relational queries locally
return false;
}
if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(key)) {
throw new _ParseError.default(_ParseError.default.INVALID_KEY_NAME, `Invalid Key: ${key}`);
}
// Equality (or Array contains) cases
if (typeof constraints !== 'object') {
if ((0, _isArray.default)(object[key])) {
var _context;
return (0, _indexOf.default)(_context = object[key]).call(_context, constraints) > -1;
}
return object[key] === constraints;
}
let compareTo;
if (constraints.__type) {
if (constraints.__type === 'Pointer') {
return equalObjectsGeneric(object[key], constraints, function (obj, ptr) {
return typeof obj !== 'undefined' && ptr.className === obj.className && ptr.objectId === obj.objectId;
});
}
return equalObjectsGeneric((0, _decode.default)(object[key]), (0, _decode.default)(constraints), _equals.default);
}
// More complex cases
for (const condition in constraints) {
compareTo = constraints[condition];
if (compareTo?.__type) {
compareTo = (0, _decode.default)(compareTo);
}
// is it a $relativeTime? convert to date
if (compareTo?.['$relativeTime']) {
const parserResult = relativeTimeToDate(compareTo['$relativeTime']);
if (parserResult.status !== 'success') {
throw new _ParseError.default(_ParseError.default.INVALID_JSON, `bad $relativeTime (${key}) value. ${parserResult.info}`);
}
compareTo = parserResult.result;
}
// Compare Date Object or Date String
if (toString.call(compareTo) === '[object Date]' || typeof compareTo === 'string' &&
// @ts-ignore
new Date(compareTo) !== 'Invalid Date' &&
// @ts-ignore
!isNaN(new Date(compareTo))) {
object[key] = new Date(object[key].iso ? object[key].iso : object[key]);
}
switch (condition) {
case '$lt':
if (object[key] >= compareTo) {
return false;
}
break;
case '$lte':
if (object[key] > compareTo) {
return false;
}
break;
case '$gt':
if (object[key] <= compareTo) {
return false;
}
break;
case '$gte':
if (object[key] < compareTo) {
return false;
}
break;
case '$ne':
if ((0, _equals.default)(object[key], compareTo)) {
return false;
}
break;
case '$in':
if (!contains(compareTo, object[key])) {
return false;
}
break;
case '$nin':
if (contains(compareTo, object[key])) {
return false;
}
break;
case '$all':
for (i = 0; i < compareTo.length; i++) {
var _context2;
if ((0, _indexOf.default)(_context2 = object[key]).call(_context2, compareTo[i]) < 0) {
return false;
}
}
break;
case '$exists':
{
const propertyExists = typeof object[key] !== 'undefined';
const existenceIsRequired = constraints['$exists'];
if (typeof constraints['$exists'] !== 'boolean') {
// The SDK will never submit a non-boolean for $exists, but if someone
// tries to submit a non-boolean for $exits outside the SDKs, just ignore it.
break;
}
if (!propertyExists && existenceIsRequired || propertyExists && !existenceIsRequired) {
return false;
}
break;
}
case '$regex':
{
if (typeof compareTo === 'object') {
return compareTo.test(object[key]);
}
// JS doesn't support perl-style escaping
let expString = '';
let escapeEnd = -2;
let escapeStart = (0, _indexOf.default)(compareTo).call(compareTo, '\\Q');
while (escapeStart > -1) {
// Add the unescaped portion
expString += compareTo.substring(escapeEnd + 2, escapeStart);
escapeEnd = (0, _indexOf.default)(compareTo).call(compareTo, '\\E', escapeStart);
if (escapeEnd > -1) {
expString += compareTo.substring(escapeStart + 2, escapeEnd).replace(/\\\\\\\\E/g, '\\E').replace(/\W/g, '\\$&');
}
escapeStart = (0, _indexOf.default)(compareTo).call(compareTo, '\\Q', escapeEnd);
}
expString += compareTo.substring(Math.max(escapeStart, escapeEnd + 2));
let modifiers = constraints.$options || '';
modifiers = modifiers.replace('x', '').replace('s', '');
// Parse Server / Mongo support x and s modifiers but JS RegExp doesn't
const exp = new RegExp(expString, modifiers);
if (!exp.test(object[key])) {
return false;
}
break;
}
case '$nearSphere':
{
if (!compareTo || !object[key]) {
return false;
}
const distance = compareTo.radiansTo(object[key]);
const max = constraints.$maxDistance || Infinity;
return distance <= max;
}
case '$within':
{
if (!compareTo || !object[key]) {
return false;
}
const southWest = compareTo.$box[0];
const northEast = compareTo.$box[1];
if (southWest.latitude > northEast.latitude || southWest.longitude > northEast.longitude) {
// Invalid box, crosses the date line
return false;
}
return object[key].latitude > southWest.latitude && object[key].latitude < northEast.latitude && object[key].longitude > southWest.longitude && object[key].longitude < northEast.longitude;
}
case '$options':
// Not a query type, but a way to add options to $regex. Ignore and
// avoid the default
break;
case '$maxDistance':
// Not a query type, but a way to add a cap to $nearSphere. Ignore and
// avoid the default
break;
case '$select':
{
const subQueryObjects = (0, _filter.default)(objects).call(objects, (obj, index, arr) => {
return matchesQuery(compareTo.query.className, obj, arr, compareTo.query.where);
});
for (let i = 0; i < subQueryObjects.length; i += 1) {
const subObject = transformObject(subQueryObjects[i]);
return (0, _equals.default)(object[key], subObject[compareTo.key]);
}
return false;
}
case '$dontSelect':
{
const subQueryObjects = (0, _filter.default)(objects).call(objects, (obj, index, arr) => {
return matchesQuery(compareTo.query.className, obj, arr, compareTo.query.where);
});
for (let i = 0; i < subQueryObjects.length; i += 1) {
const subObject = transformObject(subQueryObjects[i]);
return !(0, _equals.default)(object[key], subObject[compareTo.key]);
}
return false;
}
case '$inQuery':
{
const subQueryObjects = (0, _filter.default)(objects).call(objects, (obj, index, arr) => {
return matchesQuery(compareTo.className, obj, arr, compareTo.where);
});
for (let i = 0; i < subQueryObjects.length; i += 1) {
const subObject = transformObject(subQueryObjects[i]);
if (object[key].className === subObject.className && object[key].objectId === subObject.objectId) {
return true;
}
}
return false;
}
case '$notInQuery':
{
const subQueryObjects = (0, _filter.default)(objects).call(objects, (obj, index, arr) => {
return matchesQuery(compareTo.className, obj, arr, compareTo.where);
});
for (let i = 0; i < subQueryObjects.length; i += 1) {
const subObject = transformObject(subQueryObjects[i]);
if (object[key].className === subObject.className && object[key].objectId === subObject.objectId) {
return false;
}
}
return true;
}
case '$containedBy':
{
for (const value of object[key]) {
if (!contains(compareTo, value)) {
return false;
}
}
return true;
}
case '$geoWithin':
{
if (compareTo.$polygon) {
var _context3;
const points = (0, _map.default)(_context3 = compareTo.$polygon).call(_context3, geoPoint => [geoPoint.latitude, geoPoint.longitude]);
const polygon = new _ParsePolygon.default(points);
return polygon.containsPoint(object[key]);
}
if (compareTo.$centerSphere) {
const [WGS84Point, maxDistance] = compareTo.$centerSphere;
const centerPoint = new _ParseGeoPoint.default({
latitude: WGS84Point[1],
longitude: WGS84Point[0]
});
const point = new _ParseGeoPoint.default(object[key]);
const distance = point.radiansTo(centerPoint);
return distance <= maxDistance;
}
return false;
}
case '$geoIntersects':
{
const polygon = new _ParsePolygon.default(object[key].coordinates);
const point = new _ParseGeoPoint.default(compareTo.$point);
return polygon.containsPoint(point);
}
default:
return false;
}
}
return true;
}
function validateQuery(query) {
var _context4;
let q = query;
if (query.toJSON) {
q = query.toJSON().where;
}
const specialQuerykeys = ['$and', '$or', '$nor', '_rperm', '_wperm', '_perishable_token', '_email_verify_token', '_email_verify_token_expires_at', '_account_lockout_expires_at', '_failed_login_count'];
(0, _forEach.default)(_context4 = (0, _keys.default)(q)).call(_context4, key => {
if (q && q[key] && q[key].$regex) {
if (typeof q[key].$options === 'string') {
if (!q[key].$options.match(/^[imxs]+$/)) {
throw new _ParseError.default(_ParseError.default.INVALID_QUERY, `Bad $options value for query: ${q[key].$options}`);
}
}
}
if ((0, _indexOf.default)(specialQuerykeys).call(specialQuerykeys, key) < 0 && !key.match(/^[a-zA-Z][a-zA-Z0-9_\.]*$/)) {
throw new _ParseError.default(_ParseError.default.INVALID_KEY_NAME, `Invalid key name: ${key}`);
}
});
}
const OfflineQuery = {
matchesQuery: matchesQuery,
validateQuery: validateQuery
};
module.exports = OfflineQuery;
var _default = exports.default = OfflineQuery;
},{"./ParseError":24,"./ParseGeoPoint":26,"./ParsePolygon":32,"./decode":55,"./equals":57,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/filter":71,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/instance/map":78,"@babel/runtime-corejs3/core-js-stable/instance/slice":80,"@babel/runtime-corejs3/core-js-stable/number/is-integer":87,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],20:[function(_dereq_,module,exports){
"use strict";
var _WeakMap = _dereq_("@babel/runtime-corejs3/core-js-stable/weak-map");
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _Object$getOwnPropertyDescriptor = _dereq_("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _decode2 = _interopRequireDefault(_dereq_("./decode"));
var _encode2 = _interopRequireDefault(_dereq_("./encode"));
var _CryptoController = _interopRequireDefault(_dereq_("./CryptoController"));
var _EventuallyQueue = _interopRequireDefault(_dereq_("./EventuallyQueue"));
var _IndexedDBStorageController = _interopRequireDefault(_dereq_("./IndexedDBStorageController"));
var _InstallationController = _interopRequireDefault(_dereq_("./InstallationController"));
var ParseOp = _interopRequireWildcard(_dereq_("./ParseOp"));
var _RESTController = _interopRequireDefault(_dereq_("./RESTController"));
var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
var Analytics = _interopRequireWildcard(_dereq_("./Analytics"));
var _AnonymousUtils = _interopRequireDefault(_dereq_("./AnonymousUtils"));
var Cloud = _interopRequireWildcard(_dereq_("./Cloud"));
var _ParseCLP = _interopRequireDefault(_dereq_("./ParseCLP"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _EventEmitter = _interopRequireDefault(_dereq_("./EventEmitter"));
var _ParseConfig = _interopRequireDefault(_dereq_("./ParseConfig"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _FacebookUtils = _interopRequireDefault(_dereq_("./FacebookUtils"));
var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
var Hooks = _interopRequireWildcard(_dereq_("./ParseHooks"));
var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
var _ParsePolygon = _interopRequireDefault(_dereq_("./ParsePolygon"));
var _ParseInstallation = _interopRequireDefault(_dereq_("./ParseInstallation"));
var _LocalDatastore = _interopRequireDefault(_dereq_("./LocalDatastore"));
var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
var Push = _interopRequireWildcard(_dereq_("./Push"));
var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
var _ParseRole = _interopRequireDefault(_dereq_("./ParseRole"));
var _ParseSchema = _interopRequireDefault(_dereq_("./ParseSchema"));
var _ParseSession = _interopRequireDefault(_dereq_("./ParseSession"));
var _Storage = _interopRequireDefault(_dereq_("./Storage"));
var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
var _ParseLiveQuery = _interopRequireDefault(_dereq_("./ParseLiveQuery"));
var _LiveQueryClient = _interopRequireDefault(_dereq_("./LiveQueryClient"));
var _LocalDatastoreController = _interopRequireDefault(_dereq_("./LocalDatastoreController"));
var _StorageController = _interopRequireDefault(_dereq_("./StorageController"));
var _WebSocketController = _interopRequireDefault(_dereq_("./WebSocketController"));
function _getRequireWildcardCache(e) {
if ("function" != typeof _WeakMap) return null;
var r = new _WeakMap(),
t = new _WeakMap();
return (_getRequireWildcardCache = function (e) {
return e ? t : r;
})(e);
}
function _interopRequireWildcard(e, r) {
if (!r && e && e.__esModule) return e;
if (null === e || "object" != typeof e && "function" != typeof e) return {
default: e
};
var t = _getRequireWildcardCache(r);
if (t && t.has(e)) return t.get(e);
var n = {
__proto__: null
};
for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
var i = _Object$defineProperty && _Object$getOwnPropertyDescriptor ? _Object$getOwnPropertyDescriptor(e, u) : null;
i && (i.get || i.set) ? _Object$defineProperty(n, u, i) : n[u] = e[u];
}
return n.default = e, t && t.set(e, n), n;
}
/**
* Contains all Parse API classes and functions.
*
* @static
* @global
* @class
* @hideconstructor
*/
const Parse = {
ACL: _ParseACL.default,
Analytics: Analytics,
AnonymousUtils: _AnonymousUtils.default,
Cloud: Cloud,
CLP: _ParseCLP.default,
CoreManager: _CoreManager.default,
Config: _ParseConfig.default,
Error: _ParseError.default,
FacebookUtils: _FacebookUtils.default,
File: _ParseFile.default,
GeoPoint: _ParseGeoPoint.default,
Polygon: _ParsePolygon.default,
Installation: _ParseInstallation.default,
LocalDatastore: _LocalDatastore.default,
Object: _ParseObject.default,
Op: {
Set: ParseOp.SetOp,
Unset: ParseOp.UnsetOp,
Increment: ParseOp.IncrementOp,
Add: ParseOp.AddOp,
Remove: ParseOp.RemoveOp,
AddUnique: ParseOp.AddUniqueOp,
Relation: ParseOp.RelationOp
},
Push: Push,
Query: _ParseQuery.default,
Relation: _ParseRelation.default,
Role: _ParseRole.default,
Schema: _ParseSchema.default,
Session: _ParseSession.default,
Storage: _Storage.default,
User: _ParseUser.default,
LiveQueryClient: _LiveQueryClient.default,
IndexedDB: undefined,
Hooks: undefined,
Parse: undefined,
/**
* @member {EventuallyQueue} Parse.EventuallyQueue
* @static
*/
set EventuallyQueue(queue) {
_CoreManager.default.setEventuallyQueue(queue);
},
get EventuallyQueue() {
return _CoreManager.default.getEventuallyQueue();
},
/**
* Call this method first to set up your authentication tokens for Parse.
*
* @param {string} applicationId Your Parse Application ID.
* @param {string} [javaScriptKey] Your Parse JavaScript Key (Not needed for parse-server)
* @param {string} [masterKey] Your Parse Master Key. (Node.js only!)
* @static
*/
initialize(applicationId, javaScriptKey) {
Parse._initialize(applicationId, javaScriptKey);
},
_initialize(applicationId, javaScriptKey, masterKey) {
_CoreManager.default.set('APPLICATION_ID', applicationId);
_CoreManager.default.set('JAVASCRIPT_KEY', javaScriptKey);
_CoreManager.default.set('MASTER_KEY', masterKey);
_CoreManager.default.set('USE_MASTER_KEY', false);
_CoreManager.default.setIfNeeded('EventEmitter', _EventEmitter.default);
_CoreManager.default.setIfNeeded('LiveQuery', new _ParseLiveQuery.default());
_CoreManager.default.setIfNeeded('CryptoController', _CryptoController.default);
_CoreManager.default.setIfNeeded('EventuallyQueue', _EventuallyQueue.default);
_CoreManager.default.setIfNeeded('InstallationController', _InstallationController.default);
_CoreManager.default.setIfNeeded('LocalDatastoreController', _LocalDatastoreController.default);
_CoreManager.default.setIfNeeded('StorageController', _StorageController.default);
_CoreManager.default.setIfNeeded('WebSocketController', _WebSocketController.default);
},
/**
* Call this method to set your AsyncStorage engine
* Starting Parse@1.11, the ParseSDK do not provide a React AsyncStorage as the ReactNative module
* is not provided at a stable path and changes over versions.
*
* @param {AsyncStorage} storage a react native async storage.
* @static
*/
setAsyncStorage(storage) {
_CoreManager.default.setAsyncStorage(storage);
},
/**
* Call this method to set your LocalDatastoreStorage engine
* If using React-Native use {@link Parse.setAsyncStorage Parse.setAsyncStorage()}
*
* @param {LocalDatastoreController} controller a data storage.
* @static
*/
setLocalDatastoreController(controller) {
_CoreManager.default.setLocalDatastoreController(controller);
},
/**
* Returns information regarding the current server's health
*
* @returns {Promise}
* @static
*/
getServerHealth() {
return _CoreManager.default.getRESTController().request('GET', 'health');
},
/**
* @member {string} Parse.applicationId
* @static
*/
set applicationId(value) {
_CoreManager.default.set('APPLICATION_ID', value);
},
get applicationId() {
return _CoreManager.default.get('APPLICATION_ID');
},
/**
* @member {string} Parse.javaScriptKey
* @static
*/
set javaScriptKey(value) {
_CoreManager.default.set('JAVASCRIPT_KEY', value);
},
get javaScriptKey() {
return _CoreManager.default.get('JAVASCRIPT_KEY');
},
/**
* @member {string} Parse.masterKey
* @static
*/
set masterKey(value) {
_CoreManager.default.set('MASTER_KEY', value);
},
get masterKey() {
return _CoreManager.default.get('MASTER_KEY');
},
/**
* @member {string} Parse.serverURL
* @static
*/
set serverURL(value) {
_CoreManager.default.set('SERVER_URL', value);
},
get serverURL() {
return _CoreManager.default.get('SERVER_URL');
},
/**
* @member {string} Parse.serverAuthToken
* @static
*/
set serverAuthToken(value) {
_CoreManager.default.set('SERVER_AUTH_TOKEN', value);
},
get serverAuthToken() {
return _CoreManager.default.get('SERVER_AUTH_TOKEN');
},
/**
* @member {string} Parse.serverAuthType
* @static
*/
set serverAuthType(value) {
_CoreManager.default.set('SERVER_AUTH_TYPE', value);
},
get serverAuthType() {
return _CoreManager.default.get('SERVER_AUTH_TYPE');
},
/**
* @member {ParseLiveQuery} Parse.LiveQuery
* @static
*/
set LiveQuery(liveQuery) {
_CoreManager.default.setLiveQuery(liveQuery);
},
get LiveQuery() {
return _CoreManager.default.getLiveQuery();
},
/**
* @member {string} Parse.liveQueryServerURL
* @static
*/
set liveQueryServerURL(value) {
_CoreManager.default.set('LIVEQUERY_SERVER_URL', value);
},
get liveQueryServerURL() {
return _CoreManager.default.get('LIVEQUERY_SERVER_URL');
},
/**
* @member {boolean} Parse.encryptedUser
* @static
*/
set encryptedUser(value) {
_CoreManager.default.set('ENCRYPTED_USER', value);
},
get encryptedUser() {
return _CoreManager.default.get('ENCRYPTED_USER');
},
/**
* @member {string} Parse.secret
* @static
*/
set secret(value) {
_CoreManager.default.set('ENCRYPTED_KEY', value);
},
get secret() {
return _CoreManager.default.get('ENCRYPTED_KEY');
},
/**
* @member {boolean} Parse.idempotency
* @static
*/
set idempotency(value) {
_CoreManager.default.set('IDEMPOTENCY', value);
},
get idempotency() {
return _CoreManager.default.get('IDEMPOTENCY');
},
/**
* @member {boolean} Parse.allowCustomObjectId
* @static
*/
set allowCustomObjectId(value) {
_CoreManager.default.set('ALLOW_CUSTOM_OBJECT_ID', value);
},
get allowCustomObjectId() {
return _CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID');
},
_request() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _CoreManager.default.getRESTController().request.apply(null, args);
},
_ajax() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _CoreManager.default.getRESTController().ajax.apply(null, args);
},
// We attempt to match the signatures of the legacy versions of these methods
_decode(_, value) {
return (0, _decode2.default)(value);
},
_encode(value, _, disallowObjects) {
return (0, _encode2.default)(value, disallowObjects);
},
_getInstallationId() {
return _CoreManager.default.getInstallationController().currentInstallationId();
},
/**
* Enable pinning in your application.
* This must be called after `Parse.initialize` in your application.
*
* @param [polling] Allow pinging the server /health endpoint. Default true
* @param [ms] Milliseconds to ping the server. Default 2000ms
* @static
*/
enableLocalDatastore() {
let polling = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
let ms = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2000;
if (!this.applicationId) {
console.log("'enableLocalDataStore' must be called after 'initialize'");
return;
}
if (!this.LocalDatastore.isEnabled) {
this.LocalDatastore.isEnabled = true;
if (polling) {
_CoreManager.default.getEventuallyQueue().poll(ms);
}
}
},
/**
* Flag that indicates whether Local Datastore is enabled.
*
* @static
* @returns {boolean}
*/
isLocalDatastoreEnabled() {
return this.LocalDatastore.isEnabled;
},
/**
* Gets all contents from Local Datastore
*
*
* await Parse.dumpLocalDatastore();
*
*
* @static
* @returns {object}
*/
dumpLocalDatastore() {
if (!this.LocalDatastore.isEnabled) {
console.log('Parse.enableLocalDatastore() must be called first'); // eslint-disable-line no-console
return _promise.default.resolve({});
} else {
return Parse.LocalDatastore._getAllContents();
}
},
/**
* Enable the current user encryption.
* This must be called before login any user.
*
* @static
*/
enableEncryptedUser() {
this.encryptedUser = true;
},
/**
* Flag that indicates whether Encrypted User is enabled.
*
* @static
* @returns {boolean}
*/
isEncryptedUserEnabled() {
return this.encryptedUser;
}
};
_CoreManager.default.setRESTController(_RESTController.default);
// For legacy requires, of the form `var Parse = require('parse').Parse`
Parse.Parse = Parse;
module.exports = Parse;
var _default = exports.default = Parse;
},{"./Analytics":1,"./AnonymousUtils":2,"./Cloud":3,"./CoreManager":4,"./CryptoController":5,"./EventEmitter":6,"./EventuallyQueue":7,"./FacebookUtils":8,"./IndexedDBStorageController":9,"./InstallationController":10,"./LiveQueryClient":11,"./LocalDatastore":13,"./LocalDatastoreController":15,"./ParseACL":21,"./ParseCLP":22,"./ParseConfig":23,"./ParseError":24,"./ParseFile":25,"./ParseGeoPoint":26,"./ParseHooks":27,"./ParseInstallation":28,"./ParseLiveQuery":29,"./ParseObject":30,"./ParseOp":31,"./ParsePolygon":32,"./ParseQuery":33,"./ParseRelation":34,"./ParseRole":35,"./ParseSchema":36,"./ParseSession":37,"./ParseUser":38,"./Push":39,"./RESTController":40,"./Storage":43,"./StorageController":46,"./WebSocketController":51,"./decode":55,"./encode":56,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor":93,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/core-js-stable/weak-map":101,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],21:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
const PUBLIC_KEY = '*';
/**
* Creates a new ACL.
* If no argument is given, the ACL has no permissions for anyone.
* If the argument is a Parse.User, the ACL will have read and write
* permission for only that user.
* If the argument is any other JSON object, that object will be interpretted
* as a serialized ACL created with toJSON().
*
* An ACL, or Access Control List can be added to any
* Parse.Object
to restrict access to only a subset of users
* of your application.
*
* @alias Parse.ACL
*/
class ParseACL {
/**
* @param {(Parse.User | object)} arg1 The user to initialize the ACL for
*/
constructor(arg1) {
(0, _defineProperty2.default)(this, "permissionsById", void 0);
this.permissionsById = {};
if (arg1 && typeof arg1 === 'object') {
const ParseUser = _CoreManager.default.getParseUser();
if (arg1 instanceof ParseUser) {
this.setReadAccess(arg1, true);
this.setWriteAccess(arg1, true);
} else {
for (const userId in arg1) {
const accessList = arg1[userId];
this.permissionsById[userId] = {};
for (const permission in accessList) {
const allowed = accessList[permission];
if (permission !== 'read' && permission !== 'write') {
throw new TypeError('Tried to create an ACL with an invalid permission type.');
}
if (typeof allowed !== 'boolean') {
throw new TypeError('Tried to create an ACL with an invalid permission value.');
}
this.permissionsById[userId][permission] = allowed;
}
}
}
} else if (typeof arg1 === 'function') {
throw new TypeError('ParseACL constructed with a function. Did you forget ()?');
}
}
/**
* Returns a JSON-encoded version of the ACL.
*
* @returns {object}
*/
toJSON() {
const permissions = {};
for (const p in this.permissionsById) {
permissions[p] = this.permissionsById[p];
}
return permissions;
}
/**
* Returns whether this ACL is equal to another object
*
* @param {ParseACL} other The other object's ACL to compare to
* @returns {boolean}
*/
equals(other) {
if (!(other instanceof ParseACL)) {
return false;
}
const users = (0, _keys.default)(this.permissionsById);
const otherUsers = (0, _keys.default)(other.permissionsById);
if (users.length !== otherUsers.length) {
return false;
}
for (const u in this.permissionsById) {
if (!other.permissionsById[u]) {
return false;
}
if (this.permissionsById[u].read !== other.permissionsById[u].read) {
return false;
}
if (this.permissionsById[u].write !== other.permissionsById[u].write) {
return false;
}
}
return true;
}
_setAccess(accessType, userId, allowed) {
const ParseRole = _CoreManager.default.getParseRole();
const ParseUser = _CoreManager.default.getParseUser();
if (userId instanceof ParseUser) {
userId = userId.id;
} else if (userId instanceof ParseRole) {
const name = userId.getName();
if (!name) {
throw new TypeError('Role must have a name');
}
userId = 'role:' + name;
}
if (typeof userId !== 'string') {
throw new TypeError('userId must be a string.');
}
if (typeof allowed !== 'boolean') {
throw new TypeError('allowed must be either true or false.');
}
let permissions = this.permissionsById[userId];
if (!permissions) {
if (!allowed) {
// The user already doesn't have this permission, so no action is needed
return;
} else {
permissions = {};
this.permissionsById[userId] = permissions;
}
}
if (allowed) {
this.permissionsById[userId][accessType] = true;
} else {
delete permissions[accessType];
if ((0, _keys.default)(permissions).length === 0) {
delete this.permissionsById[userId];
}
}
}
_getAccess(accessType, userId) {
const ParseRole = _CoreManager.default.getParseRole();
const ParseUser = _CoreManager.default.getParseUser();
if (userId instanceof ParseUser) {
userId = userId.id;
if (!userId) {
throw new Error('Cannot get access for a ParseUser without an ID');
}
} else if (userId instanceof ParseRole) {
const name = userId.getName();
if (!name) {
throw new TypeError('Role must have a name');
}
userId = 'role:' + name;
}
const permissions = this.permissionsById[userId];
if (!permissions) {
return false;
}
return !!permissions[accessType];
}
/**
* Sets whether the given user is allowed to read this object.
*
* @param userId An instance of Parse.User or its objectId.
* @param {boolean} allowed Whether that user should have read access.
*/
setReadAccess(userId, allowed) {
this._setAccess('read', userId, allowed);
}
/**
* Get whether the given user id is *explicitly* allowed to read this object.
* Even if this returns false, the user may still be able to access it if
* getPublicReadAccess returns true or a role that the user belongs to has
* write access.
*
* @param userId An instance of Parse.User or its objectId, or a Parse.Role.
* @returns {boolean}
*/
getReadAccess(userId) {
return this._getAccess('read', userId);
}
/**
* Sets whether the given user id is allowed to write this object.
*
* @param userId An instance of Parse.User or its objectId, or a Parse.Role..
* @param {boolean} allowed Whether that user should have write access.
*/
setWriteAccess(userId, allowed) {
this._setAccess('write', userId, allowed);
}
/**
* Gets whether the given user id is *explicitly* allowed to write this object.
* Even if this returns false, the user may still be able to write it if
* getPublicWriteAccess returns true or a role that the user belongs to has
* write access.
*
* @param userId An instance of Parse.User or its objectId, or a Parse.Role.
* @returns {boolean}
*/
getWriteAccess(userId) {
return this._getAccess('write', userId);
}
/**
* Sets whether the public is allowed to read this object.
*
* @param {boolean} allowed
*/
setPublicReadAccess(allowed) {
this.setReadAccess(PUBLIC_KEY, allowed);
}
/**
* Gets whether the public is allowed to read this object.
*
* @returns {boolean}
*/
getPublicReadAccess() {
return this.getReadAccess(PUBLIC_KEY);
}
/**
* Sets whether the public is allowed to write this object.
*
* @param {boolean} allowed
*/
setPublicWriteAccess(allowed) {
this.setWriteAccess(PUBLIC_KEY, allowed);
}
/**
* Gets whether the public is allowed to write this object.
*
* @returns {boolean}
*/
getPublicWriteAccess() {
return this.getWriteAccess(PUBLIC_KEY);
}
/**
* Gets whether users belonging to the given role are allowed
* to read this object. Even if this returns false, the role may
* still be able to write it if a parent role has read access.
*
* @param role The name of the role, or a Parse.Role object.
* @returns {boolean} true if the role has read access. false otherwise.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
getRoleReadAccess(role) {
const ParseRole = _CoreManager.default.getParseRole();
if (role instanceof ParseRole) {
// Normalize to the String name
role = role.getName();
}
if (typeof role !== 'string') {
throw new TypeError('role must be a ParseRole or a String');
}
return this.getReadAccess('role:' + role);
}
/**
* Gets whether users belonging to the given role are allowed
* to write this object. Even if this returns false, the role may
* still be able to write it if a parent role has write access.
*
* @param role The name of the role, or a Parse.Role object.
* @returns {boolean} true if the role has write access. false otherwise.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
getRoleWriteAccess(role) {
const ParseRole = _CoreManager.default.getParseRole();
if (role instanceof ParseRole) {
// Normalize to the String name
role = role.getName();
}
if (typeof role !== 'string') {
throw new TypeError('role must be a ParseRole or a String');
}
return this.getWriteAccess('role:' + role);
}
/**
* Sets whether users belonging to the given role are allowed
* to read this object.
*
* @param role The name of the role, or a Parse.Role object.
* @param {boolean} allowed Whether the given role can read this object.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
setRoleReadAccess(role, allowed) {
const ParseRole = _CoreManager.default.getParseRole();
if (role instanceof ParseRole) {
// Normalize to the String name
role = role.getName();
}
if (typeof role !== 'string') {
throw new TypeError('role must be a ParseRole or a String');
}
this.setReadAccess('role:' + role, allowed);
}
/**
* Sets whether users belonging to the given role are allowed
* to write this object.
*
* @param role The name of the role, or a Parse.Role object.
* @param {boolean} allowed Whether the given role can write this object.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
setRoleWriteAccess(role, allowed) {
const ParseRole = _CoreManager.default.getParseRole();
if (role instanceof ParseRole) {
// Normalize to the String name
role = role.getName();
}
if (typeof role !== 'string') {
throw new TypeError('role must be a ParseRole or a String');
}
this.setWriteAccess('role:' + role, allowed);
}
}
var _default = exports.default = ParseACL;
},{"./CoreManager":4,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],22:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _map = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/map"));
var _entries = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/entries"));
var _assign = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/assign"));
var _slice = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/slice"));
var _includes = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/includes"));
var _every = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/every"));
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _ParseRole = _interopRequireDefault(_dereq_("./ParseRole"));
var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
const PUBLIC_KEY = '*';
const VALID_PERMISSIONS = new _map.default();
VALID_PERMISSIONS.set('get', {});
VALID_PERMISSIONS.set('find', {});
VALID_PERMISSIONS.set('count', {});
VALID_PERMISSIONS.set('create', {});
VALID_PERMISSIONS.set('update', {});
VALID_PERMISSIONS.set('delete', {});
VALID_PERMISSIONS.set('addField', {});
const VALID_PERMISSIONS_EXTENDED = new _map.default();
VALID_PERMISSIONS_EXTENDED.set('protectedFields', {});
/**
* Creates a new CLP.
* If no argument is given, the CLP has no permissions for anyone.
* If the argument is a Parse.User or Parse.Role, the CLP will have read and write
* permission for only that user or role.
* If the argument is any other JSON object, that object will be interpretted
* as a serialized CLP created with toJSON().
*
* A CLP, or Class Level Permissions can be added to any
* Parse.Schema
to restrict access to only a subset of users
* of your application.
*
*
* For get/count/find/create/update/delete/addField using the following functions:
*
* Entity is type Parse.User or Parse.Role or string
* Role is type Parse.Role or Name of Parse.Role
*
* getGetRequiresAuthentication()
* setGetRequiresAuthentication(allowed: boolean)
* getGetPointerFields()
* setGetPointerFields(pointerFields: string[])
* getGetAccess(entity: Entity)
* setGetAccess(entity: Entity, allowed: boolean)
* getPublicGetAccess()
* setPublicGetAccess(allowed: boolean)
* getRoleGetAccess(role: Role)
* setRoleGetAccess(role: Role, allowed: boolean)
* getFindRequiresAuthentication()
* setFindRequiresAuthentication(allowed: boolean)
* getFindPointerFields()
* setFindPointerFields(pointerFields: string[])
* getFindAccess(entity: Entity)
* setFindAccess(entity: Entity, allowed: boolean)
* getPublicFindAccess()
* setPublicFindAccess(allowed: boolean)
* getRoleFindAccess(role: Role)
* setRoleFindAccess(role: Role, allowed: boolean)
* getCountRequiresAuthentication()
* setCountRequiresAuthentication(allowed: boolean)
* getCountPointerFields()
* setCountPointerFields(pointerFields: string[])
* getCountAccess(entity: Entity)
* setCountAccess(entity: Entity, allowed: boolean)
* getPublicCountAccess()
* setPublicCountAccess(allowed: boolean)
* getRoleCountAccess(role: Role)
* setRoleCountAccess(role: Role, allowed: boolean)
* getCreateRequiresAuthentication()
* setCreateRequiresAuthentication(allowed: boolean)
* getCreatePointerFields()
* setCreatePointerFields(pointerFields: string[])
* getCreateAccess(entity: Entity)
* setCreateAccess(entity: Entity, allowed: boolean)
* getPublicCreateAccess()
* setPublicCreateAccess(allowed: Boolean)
* getRoleCreateAccess(role: Role)
* setRoleCreateAccess(role: Role, allowed: boolean)
* getUpdateRequiresAuthentication()
* setUpdateRequiresAuthentication(allowed: boolean)
* getUpdatePointerFields()
* setUpdatePointerFields(pointerFields: string[])
* getUpdateAccess(entity: Entity)
* setUpdateAccess(entity: Entity, allowed: boolean)
* getPublicUpdateAccess()
* setPublicUpdateAccess(allowed: boolean)
* getRoleUpdateAccess(role: Role)
* setRoleUpdateAccess(role: Role, allowed: boolean)
* getDeleteRequiresAuthentication()
* setDeleteRequiresAuthentication(allowed: boolean)
* getDeletePointerFields()
* setDeletePointerFields(pointerFields: string[])
* getDeleteAccess(entity: Entity)
* setDeleteAccess(entity: Entity, allowed: boolean)
* getPublicDeleteAccess()
* setPublicDeleteAccess(allowed: boolean)
* getRoleDeleteAccess(role: Role)
* setRoleDeleteAccess(role: Role, allowed: boolean)
* getAddFieldRequiresAuthentication()
* setAddFieldRequiresAuthentication(allowed: boolean)
* getAddFieldPointerFields()
* setAddFieldPointerFields(pointerFields: string[])
* getAddFieldAccess(entity: Entity)
* setAddFieldAccess(entity: Entity, allowed: boolean)
* getPublicAddFieldAccess()
* setPublicAddFieldAccess(allowed: boolean)
* getRoleAddFieldAccess(role: Role)
* setRoleAddFieldAccess(role: Role, allowed: boolean)
*
*
* @alias Parse.CLP
*/
class ParseCLP {
/**
* @param {(Parse.User | Parse.Role | object)} userId The user to initialize the CLP for
*/
constructor(userId) {
(0, _defineProperty2.default)(this, "permissionsMap", void 0);
this.permissionsMap = {};
// Initialize permissions Map with default permissions
for (const [operation, group] of (0, _entries.default)(VALID_PERMISSIONS).call(VALID_PERMISSIONS)) {
this.permissionsMap[operation] = (0, _assign.default)({}, group);
const action = operation.charAt(0).toUpperCase() + (0, _slice.default)(operation).call(operation, 1);
this[`get${action}RequiresAuthentication`] = function () {
return this._getAccess(operation, 'requiresAuthentication');
};
this[`set${action}RequiresAuthentication`] = function (allowed) {
this._setAccess(operation, 'requiresAuthentication', allowed);
};
this[`get${action}PointerFields`] = function () {
return this._getAccess(operation, 'pointerFields', false);
};
this[`set${action}PointerFields`] = function (pointerFields) {
this._setArrayAccess(operation, 'pointerFields', pointerFields);
};
this[`get${action}Access`] = function (entity) {
return this._getAccess(operation, entity);
};
this[`set${action}Access`] = function (entity, allowed) {
this._setAccess(operation, entity, allowed);
};
this[`getPublic${action}Access`] = function () {
return this[`get${action}Access`](PUBLIC_KEY);
};
this[`setPublic${action}Access`] = function (allowed) {
this[`set${action}Access`](PUBLIC_KEY, allowed);
};
this[`getRole${action}Access`] = function (role) {
return this[`get${action}Access`](this._getRoleName(role));
};
this[`setRole${action}Access`] = function (role, allowed) {
this[`set${action}Access`](this._getRoleName(role), allowed);
};
}
// Initialize permissions Map with default extended permissions
for (const [operation, group] of (0, _entries.default)(VALID_PERMISSIONS_EXTENDED).call(VALID_PERMISSIONS_EXTENDED)) {
this.permissionsMap[operation] = (0, _assign.default)({}, group);
}
if (userId && typeof userId === 'object') {
if (userId instanceof _ParseUser.default) {
this.setReadAccess(userId, true);
this.setWriteAccess(userId, true);
} else if (userId instanceof _ParseRole.default) {
this.setRoleReadAccess(userId, true);
this.setRoleWriteAccess(userId, true);
} else {
for (const permission in userId) {
var _context;
const users = userId[permission];
const isValidPermission = !!VALID_PERMISSIONS.get(permission);
const isValidPermissionExtended = !!VALID_PERMISSIONS_EXTENDED.get(permission);
const isValidGroupPermission = (0, _includes.default)(_context = ['readUserFields', 'writeUserFields']).call(_context, permission);
if (typeof permission !== 'string' || !(isValidPermission || isValidPermissionExtended || isValidGroupPermission)) {
throw new TypeError('Tried to create an CLP with an invalid permission type.');
}
if (isValidGroupPermission) {
if ((0, _every.default)(users).call(users, pointer => typeof pointer === 'string')) {
this.permissionsMap[permission] = users;
continue;
} else {
throw new TypeError('Tried to create an CLP with an invalid permission value.');
}
}
for (const user in users) {
const allowed = users[user];
if (typeof allowed !== 'boolean' && !isValidPermissionExtended && user !== 'pointerFields') {
throw new TypeError('Tried to create an CLP with an invalid permission value.');
}
this.permissionsMap[permission][user] = allowed;
}
}
}
} else if (typeof userId === 'function') {
throw new TypeError('ParseCLP constructed with a function. Did you forget ()?');
}
}
/**
* Returns a JSON-encoded version of the CLP.
*
* @returns {object}
*/
toJSON() {
return {
...this.permissionsMap
};
}
/**
* Returns whether this CLP is equal to another object
*
* @param other The other object to compare to
* @returns {boolean}
*/
equals(other) {
if (!(other instanceof ParseCLP)) {
return false;
}
const permissions = (0, _keys.default)(this.permissionsMap);
const otherPermissions = (0, _keys.default)(other.permissionsMap);
if (permissions.length !== otherPermissions.length) {
return false;
}
for (const permission in this.permissionsMap) {
if (!other.permissionsMap[permission]) {
return false;
}
const users = (0, _keys.default)(this.permissionsMap[permission]);
const otherUsers = (0, _keys.default)(other.permissionsMap[permission]);
if (users.length !== otherUsers.length) {
return false;
}
for (const user in this.permissionsMap[permission]) {
if (!other.permissionsMap[permission][user]) {
return false;
}
if (this.permissionsMap[permission][user] !== other.permissionsMap[permission][user]) {
return false;
}
}
}
return true;
}
_getRoleName(role) {
let name = role;
if (role instanceof _ParseRole.default) {
// Normalize to the String name
name = role.getName();
}
if (typeof name !== 'string') {
throw new TypeError('role must be a Parse.Role or a String');
}
return `role:${name}`;
}
_parseEntity(entity) {
let userId = entity;
if (userId instanceof _ParseUser.default) {
userId = userId.id;
if (!userId) {
throw new Error('Cannot get access for a Parse.User without an id.');
}
} else if (userId instanceof _ParseRole.default) {
userId = this._getRoleName(userId);
}
if (typeof userId !== 'string') {
throw new TypeError('userId must be a string.');
}
return userId;
}
_setAccess(permission, userId, allowed) {
userId = this._parseEntity(userId);
if (typeof allowed !== 'boolean') {
throw new TypeError('allowed must be either true or false.');
}
const permissions = this.permissionsMap[permission][userId];
if (!permissions) {
if (!allowed) {
// The user already doesn't have this permission, so no action is needed
return;
} else {
this.permissionsMap[permission][userId] = {};
}
}
if (allowed) {
this.permissionsMap[permission][userId] = true;
} else {
delete this.permissionsMap[permission][userId];
}
}
_getAccess(permission, userId) {
let returnBoolean = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
userId = this._parseEntity(userId);
const permissions = this.permissionsMap[permission][userId];
if (returnBoolean) {
if (!permissions) {
return false;
}
return !!this.permissionsMap[permission][userId];
}
return permissions;
}
_setArrayAccess(permission, userId, fields) {
userId = this._parseEntity(userId);
const permissions = this.permissionsMap[permission][userId];
if (!permissions) {
this.permissionsMap[permission][userId] = [];
}
if (!fields || (0, _isArray.default)(fields) && fields.length === 0) {
delete this.permissionsMap[permission][userId];
} else if ((0, _isArray.default)(fields) && (0, _every.default)(fields).call(fields, field => typeof field === 'string')) {
this.permissionsMap[permission][userId] = fields;
} else {
throw new TypeError('fields must be an array of strings or undefined.');
}
}
_setGroupPointerPermission(operation, pointerFields) {
const fields = this.permissionsMap[operation];
if (!fields) {
this.permissionsMap[operation] = [];
}
if (!pointerFields || (0, _isArray.default)(pointerFields) && pointerFields.length === 0) {
delete this.permissionsMap[operation];
} else if ((0, _isArray.default)(pointerFields) && (0, _every.default)(pointerFields).call(pointerFields, field => typeof field === 'string')) {
this.permissionsMap[operation] = pointerFields;
} else {
throw new TypeError(`${operation}.pointerFields must be an array of strings or undefined.`);
}
}
_getGroupPointerPermissions(operation) {
return this.permissionsMap[operation] || [];
}
/**
* Sets user pointer fields to allow permission for get/count/find operations.
*
* @param {string[]} pointerFields User pointer fields
*/
setReadUserFields(pointerFields) {
this._setGroupPointerPermission('readUserFields', pointerFields);
}
/**
* @returns {string[]} User pointer fields
*/
getReadUserFields() {
return this._getGroupPointerPermissions('readUserFields') || [];
}
/**
* Sets user pointer fields to allow permission for create/delete/update/addField operations
*
* @param {string[]} pointerFields User pointer fields
*/
setWriteUserFields(pointerFields) {
this._setGroupPointerPermission('writeUserFields', pointerFields);
}
/**
* @returns {string[]} User pointer fields
*/
getWriteUserFields() {
return this._getGroupPointerPermissions('writeUserFields') || [];
}
/**
* Sets whether the given user is allowed to retrieve fields from this class.
*
* @param userId An instance of Parse.User or its objectId.
* @param {string[]} fields fields to be protected
*/
setProtectedFields(userId, fields) {
this._setArrayAccess('protectedFields', userId, fields);
}
/**
* Returns array of fields are accessable to this user.
*
* @param userId An instance of Parse.User or its objectId, or a Parse.Role.
* @returns {string[]}
*/
getProtectedFields(userId) {
return this._getAccess('protectedFields', userId, false);
}
/**
* Sets whether the given user is allowed to read from this class.
*
* @param userId An instance of Parse.User or its objectId.
* @param {boolean} allowed whether that user should have read access.
*/
setReadAccess(userId, allowed) {
this._setAccess('find', userId, allowed);
this._setAccess('get', userId, allowed);
this._setAccess('count', userId, allowed);
}
/**
* Get whether the given user id is *explicitly* allowed to read from this class.
* Even if this returns false, the user may still be able to access it if
* getPublicReadAccess returns true or a role that the user belongs to has
* write access.
*
* @param userId An instance of Parse.User or its objectId, or a Parse.Role.
* @returns {boolean}
*/
getReadAccess(userId) {
return this._getAccess('find', userId) && this._getAccess('get', userId) && this._getAccess('count', userId);
}
/**
* Sets whether the given user id is allowed to write to this class.
*
* @param userId An instance of Parse.User or its objectId, or a Parse.Role..
* @param {boolean} allowed Whether that user should have write access.
*/
setWriteAccess(userId, allowed) {
this._setAccess('create', userId, allowed);
this._setAccess('update', userId, allowed);
this._setAccess('delete', userId, allowed);
this._setAccess('addField', userId, allowed);
}
/**
* Gets whether the given user id is *explicitly* allowed to write to this class.
* Even if this returns false, the user may still be able to write it if
* getPublicWriteAccess returns true or a role that the user belongs to has
* write access.
*
* @param userId An instance of Parse.User or its objectId, or a Parse.Role.
* @returns {boolean}
*/
getWriteAccess(userId) {
return this._getAccess('create', userId) && this._getAccess('update', userId) && this._getAccess('delete', userId) && this._getAccess('addField', userId);
}
/**
* Sets whether the public is allowed to read from this class.
*
* @param {boolean} allowed
*/
setPublicReadAccess(allowed) {
this.setReadAccess(PUBLIC_KEY, allowed);
}
/**
* Gets whether the public is allowed to read from this class.
*
* @returns {boolean}
*/
getPublicReadAccess() {
return this.getReadAccess(PUBLIC_KEY);
}
/**
* Sets whether the public is allowed to write to this class.
*
* @param {boolean} allowed
*/
setPublicWriteAccess(allowed) {
this.setWriteAccess(PUBLIC_KEY, allowed);
}
/**
* Gets whether the public is allowed to write to this class.
*
* @returns {boolean}
*/
getPublicWriteAccess() {
return this.getWriteAccess(PUBLIC_KEY);
}
/**
* Sets whether the public is allowed to protect fields in this class.
*
* @param {string[]} fields
*/
setPublicProtectedFields(fields) {
this.setProtectedFields(PUBLIC_KEY, fields);
}
/**
* Gets whether the public is allowed to read fields from this class.
*
* @returns {string[]}
*/
getPublicProtectedFields() {
return this.getProtectedFields(PUBLIC_KEY);
}
/**
* Gets whether users belonging to the given role are allowed
* to read from this class. Even if this returns false, the role may
* still be able to write it if a parent role has read access.
*
* @param role The name of the role, or a Parse.Role object.
* @returns {boolean} true if the role has read access. false otherwise.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
getRoleReadAccess(role) {
return this.getReadAccess(this._getRoleName(role));
}
/**
* Gets whether users belonging to the given role are allowed
* to write to this user. Even if this returns false, the role may
* still be able to write it if a parent role has write access.
*
* @param role The name of the role, or a Parse.Role object.
* @returns {boolean} true if the role has write access. false otherwise.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
getRoleWriteAccess(role) {
return this.getWriteAccess(this._getRoleName(role));
}
/**
* Sets whether users belonging to the given role are allowed
* to read from this class.
*
* @param role The name of the role, or a Parse.Role object.
* @param {boolean} allowed Whether the given role can read this object.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
setRoleReadAccess(role, allowed) {
this.setReadAccess(this._getRoleName(role), allowed);
}
/**
* Sets whether users belonging to the given role are allowed
* to write to this class.
*
* @param role The name of the role, or a Parse.Role object.
* @param {boolean} allowed Whether the given role can write this object.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
setRoleWriteAccess(role, allowed) {
this.setWriteAccess(this._getRoleName(role), allowed);
}
/**
* Gets whether users belonging to the given role are allowed
* to count to this user. Even if this returns false, the role may
* still be able to count it if a parent role has count access.
*
* @param role The name of the role, or a Parse.Role object.
* @returns {string[]}
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
getRoleProtectedFields(role) {
return this.getProtectedFields(this._getRoleName(role));
}
/**
* Sets whether users belonging to the given role are allowed
* to set access field in this class.
*
* @param role The name of the role, or a Parse.Role object.
* @param {string[]} fields Fields to be protected by Role.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
setRoleProtectedFields(role, fields) {
this.setProtectedFields(this._getRoleName(role), fields);
}
}
var _default = exports.default = ParseCLP;
},{"./ParseRole":35,"./ParseUser":38,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/entries":69,"@babel/runtime-corejs3/core-js-stable/instance/every":70,"@babel/runtime-corejs3/core-js-stable/instance/includes":75,"@babel/runtime-corejs3/core-js-stable/instance/slice":80,"@babel/runtime-corejs3/core-js-stable/map":86,"@babel/runtime-corejs3/core-js-stable/object/assign":88,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],23:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _decode = _interopRequireDefault(_dereq_("./decode"));
var _encode = _interopRequireDefault(_dereq_("./encode"));
var _escape = _interopRequireDefault(_dereq_("./escape"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _Storage = _interopRequireDefault(_dereq_("./Storage"));
/**
* Parse.Config is a local representation of configuration data that
* can be set from the Parse dashboard.
*
* @alias Parse.Config
*/
class ParseConfig {
constructor() {
(0, _defineProperty2.default)(this, "attributes", void 0);
(0, _defineProperty2.default)(this, "_escapedAttributes", void 0);
this.attributes = {};
this._escapedAttributes = {};
}
/**
* Gets the value of an attribute.
*
* @param {string} attr The name of an attribute.
* @returns {*}
*/
get(attr) {
return this.attributes[attr];
}
/**
* Gets the HTML-escaped value of an attribute.
*
* @param {string} attr The name of an attribute.
* @returns {string}
*/
escape(attr) {
const html = this._escapedAttributes[attr];
if (html) {
return html;
}
const val = this.attributes[attr];
let escaped = '';
if (val != null) {
escaped = (0, _escape.default)(val.toString());
}
this._escapedAttributes[attr] = escaped;
return escaped;
}
/**
* Retrieves the most recently-fetched configuration object, either from
* memory or from local storage if necessary.
*
* @static
* @returns {Parse.Config} The most recently-fetched Parse.Config if it
* exists, else an empty Parse.Config.
*/
static current() {
const controller = _CoreManager.default.getConfigController();
return controller.current();
}
/**
* Gets a new configuration object from the server.
*
* @static
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
* @returns {Promise} A promise that is resolved with a newly-created
* configuration object when the get completes.
*/
static get() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const controller = _CoreManager.default.getConfigController();
return controller.get(options);
}
/**
* Save value keys to the server.
*
* @static
* @param {object} attrs The config parameters and values.
* @param {object} masterKeyOnlyFlags The flags that define whether config parameters listed
* in `attrs` should be retrievable only by using the master key.
* For example: `param1: true` makes `param1` only retrievable by using the master key.
* If a parameter is not provided or set to `false`, it can be retrieved without
* using the master key.
* @returns {Promise} A promise that is resolved with a newly-created
* configuration object or with the current with the update.
*/
static save(attrs, masterKeyOnlyFlags) {
const controller = _CoreManager.default.getConfigController();
//To avoid a mismatch with the local and the cloud config we get a new version
return controller.save(attrs, masterKeyOnlyFlags).then(() => {
return controller.get({
useMasterKey: true
});
}, error => {
return _promise.default.reject(error);
});
}
/**
* Used for testing
*
* @private
*/
static _clearCache() {
currentConfig = null;
}
}
let currentConfig = null;
const CURRENT_CONFIG_KEY = 'currentConfig';
function decodePayload(data) {
try {
const json = JSON.parse(data);
if (json && typeof json === 'object') {
return (0, _decode.default)(json);
}
} catch (e) {
return null;
}
}
const DefaultController = {
current() {
if (currentConfig) {
return currentConfig;
}
const config = new ParseConfig();
const storagePath = _Storage.default.generatePath(CURRENT_CONFIG_KEY);
if (!_Storage.default.async()) {
const configData = _Storage.default.getItem(storagePath);
if (configData) {
const attributes = decodePayload(configData);
if (attributes) {
config.attributes = attributes;
currentConfig = config;
}
}
return config;
}
// Return a promise for async storage controllers
return _Storage.default.getItemAsync(storagePath).then(configData => {
if (configData) {
const attributes = decodePayload(configData);
if (attributes) {
config.attributes = attributes;
currentConfig = config;
}
}
return config;
});
},
get() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('GET', 'config', {}, options).then(response => {
if (!response || !response.params) {
const error = new _ParseError.default(_ParseError.default.INVALID_JSON, 'Config JSON response invalid.');
return _promise.default.reject(error);
}
const config = new ParseConfig();
config.attributes = {};
for (const attr in response.params) {
config.attributes[attr] = (0, _decode.default)(response.params[attr]);
}
currentConfig = config;
return _Storage.default.setItemAsync(_Storage.default.generatePath(CURRENT_CONFIG_KEY), (0, _stringify.default)(response.params)).then(() => {
return config;
});
});
},
save(attrs, masterKeyOnlyFlags) {
const RESTController = _CoreManager.default.getRESTController();
const encodedAttrs = {};
for (const key in attrs) {
encodedAttrs[key] = (0, _encode.default)(attrs[key]);
}
return RESTController.request('PUT', 'config', {
params: encodedAttrs,
masterKeyOnly: masterKeyOnlyFlags
}, {
useMasterKey: true
}).then(response => {
if (response && response.result) {
return _promise.default.resolve();
} else {
const error = new _ParseError.default(_ParseError.default.INTERNAL_SERVER_ERROR, 'Error occured updating Config.');
return _promise.default.reject(error);
}
});
}
};
_CoreManager.default.setConfigController(DefaultController);
var _default = exports.default = ParseConfig;
},{"./CoreManager":4,"./ParseError":24,"./Storage":43,"./decode":55,"./encode":56,"./escape":58,"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],24:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty2 = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty2(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property"));
var _defineProperty3 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
/**
* Constructs a new Parse.Error object with the given code and message.
*
* Parse.CoreManager.set('PARSE_ERRORS', [{ code, message }]) can be use to override error messages.
*
* @alias Parse.Error
*/
class ParseError extends Error {
/**
* @param {number} code An error code constant from Parse.Error
.
* @param {string} message A detailed description of the error.
*/
constructor(code, message) {
var _context;
super(message);
(0, _defineProperty3.default)(this, "code", void 0);
(0, _defineProperty3.default)(this, "message", void 0);
(0, _defineProperty3.default)(this, "object", void 0);
(0, _defineProperty3.default)(this, "errors", void 0);
this.code = code;
let customMessage = message;
(0, _forEach.default)(_context = _CoreManager.default.get('PARSE_ERRORS')).call(_context, error => {
if (error.code === code && error.code) {
customMessage = error.message;
}
});
(0, _defineProperty2.default)(this, 'message', {
enumerable: true,
value: customMessage
});
}
toString() {
return 'ParseError: ' + this.code + ' ' + this.message;
}
/**
* Error code indicating some error other than those enumerated here.
*
* @property {number} OTHER_CAUSE
* @static
*/
}
(0, _defineProperty3.default)(ParseError, "OTHER_CAUSE", -1);
/**
* Error code indicating that something has gone wrong with the server.
*
* @property {number} INTERNAL_SERVER_ERROR
* @static
*/
(0, _defineProperty3.default)(ParseError, "INTERNAL_SERVER_ERROR", 1);
/**
* Error code indicating the connection to the Parse servers failed.
*
* @property {number} CONNECTION_FAILED
* @static
*/
(0, _defineProperty3.default)(ParseError, "CONNECTION_FAILED", 100);
/**
* Error code indicating the specified object doesn't exist.
*
* @property {number} OBJECT_NOT_FOUND
* @static
*/
(0, _defineProperty3.default)(ParseError, "OBJECT_NOT_FOUND", 101);
/**
* Error code indicating you tried to query with a datatype that doesn't
* support it, like exact matching an array or object.
*
* @property {number} INVALID_QUERY
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_QUERY", 102);
/**
* Error code indicating a missing or invalid classname. Classnames are
* case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the
* only valid characters.
*
* @property {number} INVALID_CLASS_NAME
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_CLASS_NAME", 103);
/**
* Error code indicating an unspecified object id.
*
* @property {number} MISSING_OBJECT_ID
* @static
*/
(0, _defineProperty3.default)(ParseError, "MISSING_OBJECT_ID", 104);
/**
* Error code indicating an invalid key name. Keys are case-sensitive. They
* must start with a letter, and a-zA-Z0-9_ are the only valid characters.
*
* @property {number} INVALID_KEY_NAME
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_KEY_NAME", 105);
/**
* Error code indicating a malformed pointer. You should not see this unless
* you have been mucking about changing internal Parse code.
*
* @property {number} INVALID_POINTER
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_POINTER", 106);
/**
* Error code indicating that badly formed JSON was received upstream. This
* either indicates you have done something unusual with modifying how
* things encode to JSON, or the network is failing badly.
*
* @property {number} INVALID_JSON
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_JSON", 107);
/**
* Error code indicating that the feature you tried to access is only
* available internally for testing purposes.
*
* @property {number} COMMAND_UNAVAILABLE
* @static
*/
(0, _defineProperty3.default)(ParseError, "COMMAND_UNAVAILABLE", 108);
/**
* You must call Parse.initialize before using the Parse library.
*
* @property {number} NOT_INITIALIZED
* @static
*/
(0, _defineProperty3.default)(ParseError, "NOT_INITIALIZED", 109);
/**
* Error code indicating that a field was set to an inconsistent type.
*
* @property {number} INCORRECT_TYPE
* @static
*/
(0, _defineProperty3.default)(ParseError, "INCORRECT_TYPE", 111);
/**
* Error code indicating an invalid channel name. A channel name is either
* an empty string (the broadcast channel) or contains only a-zA-Z0-9_
* characters and starts with a letter.
*
* @property {number} INVALID_CHANNEL_NAME
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_CHANNEL_NAME", 112);
/**
* Error code indicating that push is misconfigured.
*
* @property {number} PUSH_MISCONFIGURED
* @static
*/
(0, _defineProperty3.default)(ParseError, "PUSH_MISCONFIGURED", 115);
/**
* Error code indicating that the object is too large.
*
* @property {number} OBJECT_TOO_LARGE
* @static
*/
(0, _defineProperty3.default)(ParseError, "OBJECT_TOO_LARGE", 116);
/**
* Error code indicating that the operation isn't allowed for clients.
*
* @property {number} OPERATION_FORBIDDEN
* @static
*/
(0, _defineProperty3.default)(ParseError, "OPERATION_FORBIDDEN", 119);
/**
* Error code indicating the result was not found in the cache.
*
* @property {number} CACHE_MISS
* @static
*/
(0, _defineProperty3.default)(ParseError, "CACHE_MISS", 120);
/**
* Error code indicating that an invalid key was used in a nested
* JSONObject.
*
* @property {number} INVALID_NESTED_KEY
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_NESTED_KEY", 121);
/**
* Error code indicating that an invalid filename was used for ParseFile.
* A valid file name contains only a-zA-Z0-9_. characters and is between 1
* and 128 characters.
*
* @property {number} INVALID_FILE_NAME
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_FILE_NAME", 122);
/**
* Error code indicating an invalid ACL was provided.
*
* @property {number} INVALID_ACL
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_ACL", 123);
/**
* Error code indicating that the request timed out on the server. Typically
* this indicates that the request is too expensive to run.
*
* @property {number} TIMEOUT
* @static
*/
(0, _defineProperty3.default)(ParseError, "TIMEOUT", 124);
/**
* Error code indicating that the email address was invalid.
*
* @property {number} INVALID_EMAIL_ADDRESS
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_EMAIL_ADDRESS", 125);
/**
* Error code indicating a missing content type.
*
* @property {number} MISSING_CONTENT_TYPE
* @static
*/
(0, _defineProperty3.default)(ParseError, "MISSING_CONTENT_TYPE", 126);
/**
* Error code indicating a missing content length.
*
* @property {number} MISSING_CONTENT_LENGTH
* @static
*/
(0, _defineProperty3.default)(ParseError, "MISSING_CONTENT_LENGTH", 127);
/**
* Error code indicating an invalid content length.
*
* @property {number} INVALID_CONTENT_LENGTH
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_CONTENT_LENGTH", 128);
/**
* Error code indicating a file that was too large.
*
* @property {number} FILE_TOO_LARGE
* @static
*/
(0, _defineProperty3.default)(ParseError, "FILE_TOO_LARGE", 129);
/**
* Error code indicating an error saving a file.
*
* @property {number} FILE_SAVE_ERROR
* @static
*/
(0, _defineProperty3.default)(ParseError, "FILE_SAVE_ERROR", 130);
/**
* Error code indicating that a unique field was given a value that is
* already taken.
*
* @property {number} DUPLICATE_VALUE
* @static
*/
(0, _defineProperty3.default)(ParseError, "DUPLICATE_VALUE", 137);
/**
* Error code indicating that a role's name is invalid.
*
* @property {number} INVALID_ROLE_NAME
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_ROLE_NAME", 139);
/**
* Error code indicating that an application quota was exceeded. Upgrade to
* resolve.
*
* @property {number} EXCEEDED_QUOTA
* @static
*/
(0, _defineProperty3.default)(ParseError, "EXCEEDED_QUOTA", 140);
/**
* Error code indicating that a Cloud Code script failed.
*
* @property {number} SCRIPT_FAILED
* @static
*/
(0, _defineProperty3.default)(ParseError, "SCRIPT_FAILED", 141);
/**
* Error code indicating that a Cloud Code validation failed.
*
* @property {number} VALIDATION_ERROR
* @static
*/
(0, _defineProperty3.default)(ParseError, "VALIDATION_ERROR", 142);
/**
* Error code indicating that invalid image data was provided.
*
* @property {number} INVALID_IMAGE_DATA
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_IMAGE_DATA", 143);
/**
* Error code indicating an unsaved file.
*
* @property {number} UNSAVED_FILE_ERROR
* @static
*/
(0, _defineProperty3.default)(ParseError, "UNSAVED_FILE_ERROR", 151);
/**
* Error code indicating an invalid push time.
*
* @property {number} INVALID_PUSH_TIME_ERROR
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_PUSH_TIME_ERROR", 152);
/**
* Error code indicating an error deleting a file.
*
* @property {number} FILE_DELETE_ERROR
* @static
*/
(0, _defineProperty3.default)(ParseError, "FILE_DELETE_ERROR", 153);
/**
* Error code indicating an error deleting an unnamed file.
*
* @property {number} FILE_DELETE_UNNAMED_ERROR
* @static
*/
(0, _defineProperty3.default)(ParseError, "FILE_DELETE_UNNAMED_ERROR", 161);
/**
* Error code indicating that the application has exceeded its request
* limit.
*
* @property {number} REQUEST_LIMIT_EXCEEDED
* @static
*/
(0, _defineProperty3.default)(ParseError, "REQUEST_LIMIT_EXCEEDED", 155);
/**
* Error code indicating that the request was a duplicate and has been discarded due to
* idempotency rules.
*
* @property {number} DUPLICATE_REQUEST
* @static
*/
(0, _defineProperty3.default)(ParseError, "DUPLICATE_REQUEST", 159);
/**
* Error code indicating an invalid event name.
*
* @property {number} INVALID_EVENT_NAME
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_EVENT_NAME", 160);
/**
* Error code indicating that a field had an invalid value.
*
* @property {number} INVALID_VALUE
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_VALUE", 162);
/**
* Error code indicating that the username is missing or empty.
*
* @property {number} USERNAME_MISSING
* @static
*/
(0, _defineProperty3.default)(ParseError, "USERNAME_MISSING", 200);
/**
* Error code indicating that the password is missing or empty.
*
* @property {number} PASSWORD_MISSING
* @static
*/
(0, _defineProperty3.default)(ParseError, "PASSWORD_MISSING", 201);
/**
* Error code indicating that the username has already been taken.
*
* @property {number} USERNAME_TAKEN
* @static
*/
(0, _defineProperty3.default)(ParseError, "USERNAME_TAKEN", 202);
/**
* Error code indicating that the email has already been taken.
*
* @property {number} EMAIL_TAKEN
* @static
*/
(0, _defineProperty3.default)(ParseError, "EMAIL_TAKEN", 203);
/**
* Error code indicating that the email is missing, but must be specified.
*
* @property {number} EMAIL_MISSING
* @static
*/
(0, _defineProperty3.default)(ParseError, "EMAIL_MISSING", 204);
/**
* Error code indicating that a user with the specified email was not found.
*
* @property {number} EMAIL_NOT_FOUND
* @static
*/
(0, _defineProperty3.default)(ParseError, "EMAIL_NOT_FOUND", 205);
/**
* Error code indicating that a user object without a valid session could
* not be altered.
*
* @property {number} SESSION_MISSING
* @static
*/
(0, _defineProperty3.default)(ParseError, "SESSION_MISSING", 206);
/**
* Error code indicating that a user can only be created through signup.
*
* @property {number} MUST_CREATE_USER_THROUGH_SIGNUP
* @static
*/
(0, _defineProperty3.default)(ParseError, "MUST_CREATE_USER_THROUGH_SIGNUP", 207);
/**
* Error code indicating that an an account being linked is already linked
* to another user.
*
* @property {number} ACCOUNT_ALREADY_LINKED
* @static
*/
(0, _defineProperty3.default)(ParseError, "ACCOUNT_ALREADY_LINKED", 208);
/**
* Error code indicating that the current session token is invalid.
*
* @property {number} INVALID_SESSION_TOKEN
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_SESSION_TOKEN", 209);
/**
* Error code indicating an error enabling or verifying MFA
*
* @property {number} MFA_ERROR
* @static
*/
(0, _defineProperty3.default)(ParseError, "MFA_ERROR", 210);
/**
* Error code indicating that a valid MFA token must be provided
*
* @property {number} MFA_TOKEN_REQUIRED
* @static
*/
(0, _defineProperty3.default)(ParseError, "MFA_TOKEN_REQUIRED", 211);
/**
* Error code indicating that a user cannot be linked to an account because
* that account's id could not be found.
*
* @property {number} LINKED_ID_MISSING
* @static
*/
(0, _defineProperty3.default)(ParseError, "LINKED_ID_MISSING", 250);
/**
* Error code indicating that a user with a linked (e.g. Facebook) account
* has an invalid session.
*
* @property {number} INVALID_LINKED_SESSION
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_LINKED_SESSION", 251);
/**
* Error code indicating that a service being linked (e.g. Facebook or
* Twitter) is unsupported.
*
* @property {number} UNSUPPORTED_SERVICE
* @static
*/
(0, _defineProperty3.default)(ParseError, "UNSUPPORTED_SERVICE", 252);
/**
* Error code indicating an invalid operation occured on schema
*
* @property {number} INVALID_SCHEMA_OPERATION
* @static
*/
(0, _defineProperty3.default)(ParseError, "INVALID_SCHEMA_OPERATION", 255);
/**
* Error code indicating that there were multiple errors. Aggregate errors
* have an "errors" property, which is an array of error objects with more
* detail about each error that occurred.
*
* @property {number} AGGREGATE_ERROR
* @static
*/
(0, _defineProperty3.default)(ParseError, "AGGREGATE_ERROR", 600);
/**
* Error code indicating the client was unable to read an input file.
*
* @property {number} FILE_READ_ERROR
* @static
*/
(0, _defineProperty3.default)(ParseError, "FILE_READ_ERROR", 601);
/**
* Error code indicating a real error code is unavailable because
* we had to use an XDomainRequest object to allow CORS requests in
* Internet Explorer, which strips the body from HTTP responses that have
* a non-2XX status code.
*
* @property {number} X_DOMAIN_REQUEST
* @static
*/
(0, _defineProperty3.default)(ParseError, "X_DOMAIN_REQUEST", 602);
var _default = exports.default = ParseError;
},{"./CoreManager":4,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],25:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _slice = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/slice"));
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _Xhr = _interopRequireDefault(_dereq_("./Xhr.weapp"));
/* global XMLHttpRequest, Blob */
let XHR = null;
if (typeof XMLHttpRequest !== 'undefined') {
XHR = XMLHttpRequest;
}
XHR = _Xhr.default;
function b64Digit(number) {
if (number < 26) {
return String.fromCharCode(65 + number);
}
if (number < 52) {
return String.fromCharCode(97 + (number - 26));
}
if (number < 62) {
return String.fromCharCode(48 + (number - 52));
}
if (number === 62) {
return '+';
}
if (number === 63) {
return '/';
}
throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
}
/**
* A Parse.File is a local representation of a file that is saved to the Parse
* cloud.
*
* @alias Parse.File
*/
class ParseFile {
/**
* @param name {String} The file's name. This will be prefixed by a unique
* value once the file has finished saving. The file name must begin with
* an alphanumeric character, and consist of alphanumeric characters,
* periods, spaces, underscores, or dashes.
* @param data {Array} The data for the file, as either:
* 1. an Array of byte value Numbers, or
* 2. an Object like { base64: "..." } with a base64-encoded String.
* 3. an Object like { uri: "..." } with a uri String.
* 4. a File object selected with a file upload control. (3) only works
* in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
* For example:
*
* var fileUploadControl = $("#profilePhotoFileUpload")[0];
* if (fileUploadControl.files.length > 0) {
* var file = fileUploadControl.files[0];
* var name = "photo.jpg";
* var parseFile = new Parse.File(name, file);
* parseFile.save().then(function() {
* // The file has been saved to Parse.
* }, function(error) {
* // The file either could not be read, or could not be saved to Parse.
* });
* }
* @param type {String} Optional Content-Type header to use for the file. If
* this is omitted, the content type will be inferred from the name's
* extension.
* @param metadata {object} Optional key value pairs to be stored with file object
* @param tags {object} Optional key value pairs to be stored with file object
*/
constructor(name, data, type, metadata, tags) {
(0, _defineProperty2.default)(this, "_name", void 0);
(0, _defineProperty2.default)(this, "_url", void 0);
(0, _defineProperty2.default)(this, "_source", void 0);
(0, _defineProperty2.default)(this, "_previousSave", void 0);
(0, _defineProperty2.default)(this, "_data", void 0);
(0, _defineProperty2.default)(this, "_requestTask", void 0);
(0, _defineProperty2.default)(this, "_metadata", void 0);
(0, _defineProperty2.default)(this, "_tags", void 0);
const specifiedType = type || '';
this._name = name;
this._metadata = metadata || {};
this._tags = tags || {};
if (data !== undefined) {
if ((0, _isArray.default)(data)) {
this._data = ParseFile.encodeBase64(data);
this._source = {
format: 'base64',
base64: this._data,
type: specifiedType
};
} else if (typeof Blob !== 'undefined' && data instanceof Blob) {
this._source = {
format: 'file',
file: data,
type: specifiedType
};
} else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
this._source = {
format: 'uri',
uri: data.uri,
type: specifiedType
};
} else if (data && typeof data.base64 === 'string') {
var _context, _context2, _context3;
const base64 = (0, _slice.default)(_context = data.base64.split(',')).call(_context, -1)[0];
const dataType = specifiedType || (0, _slice.default)(_context2 = (0, _slice.default)(_context3 = data.base64.split(';')).call(_context3, 0, 1)[0].split(':')).call(_context2, 1, 2)[0] || 'text/plain';
this._data = base64;
this._source = {
format: 'base64',
base64,
type: dataType
};
} else {
throw new TypeError('Cannot create a Parse.File with that data.');
}
}
}
/**
* Return the data for the file, downloading it if not already present.
* Data is present if initialized with Byte Array, Base64 or Saved with Uri.
* Data is cleared if saved with File object selected with a file upload control
*
* @returns {Promise} Promise that is resolve with base64 data
*/
async getData() {
if (this._data) {
return this._data;
}
if (!this._url) {
throw new Error('Cannot retrieve data for unsaved ParseFile.');
}
const controller = _CoreManager.default.getFileController();
const result = await controller.download(this._url, {
requestTask: task => this._requestTask = task
});
this._data = result.base64;
return this._data;
}
/**
* 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
* unique identifier.
*
* @returns {string}
*/
name() {
return this._name;
}
/**
* Gets the url of the file. It is only available after you save the file or
* after you get the file from a Parse.Object.
*
* @param {object} options An object to specify url options
* @param {boolean} [options.forceSecure] force the url to be secure
* @returns {string | undefined}
*/
url(options) {
options = options || {};
if (!this._url) {
return;
}
if (options.forceSecure) {
return this._url.replace(/^http:\/\//i, 'https://');
} else {
return this._url;
}
}
/**
* Gets the metadata of the file.
*
* @returns {object}
*/
metadata() {
return this._metadata;
}
/**
* Gets the tags of the file.
*
* @returns {object}
*/
tags() {
return this._tags;
}
/**
* Saves the file to the Parse cloud.
*
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- progress: In Browser only, callback for upload progress. For example:
*
* let parseFile = new Parse.File(name, file);
* parseFile.save({
* progress: (progressValue, loaded, total, { type }) => {
* if (type === "upload" && progressValue !== null) {
* // Update the UI using progressValue
* }
* }
* });
*
*
* @returns {Promise | undefined} Promise that is resolved when the save finishes.
*/
save(options) {
options = options || {};
options.requestTask = task => this._requestTask = task;
options.metadata = this._metadata;
options.tags = this._tags;
const controller = _CoreManager.default.getFileController();
if (!this._previousSave) {
if (this._source.format === 'file') {
this._previousSave = controller.saveFile(this._name, this._source, options).then(res => {
this._name = res.name;
this._url = res.url;
this._data = null;
this._requestTask = null;
return this;
});
} else if (this._source.format === 'uri') {
this._previousSave = controller.download(this._source.uri, options).then(result => {
if (!(result && result.base64)) {
return {};
}
const newSource = {
format: 'base64',
base64: result.base64,
type: result.contentType
};
this._data = result.base64;
this._requestTask = null;
return controller.saveBase64(this._name, newSource, options);
}).then(res => {
this._name = res.name;
this._url = res.url;
this._requestTask = null;
return this;
});
} else {
this._previousSave = controller.saveBase64(this._name, this._source, options).then(res => {
this._name = res.name;
this._url = res.url;
this._requestTask = null;
return this;
});
}
}
if (this._previousSave) {
return this._previousSave;
}
}
/**
* Aborts the request if it has already been sent.
*/
cancel() {
if (this._requestTask && typeof this._requestTask.abort === 'function') {
this._requestTask._aborted = true;
this._requestTask.abort();
}
this._requestTask = null;
}
/**
* Deletes the file from the Parse cloud.
* In Cloud Code and Node only with Master Key.
*
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
* @returns {Promise} Promise that is resolved when the delete finishes.
*/
destroy() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!this._name) {
throw new _ParseError.default(_ParseError.default.FILE_DELETE_UNNAMED_ERROR, 'Cannot delete an unnamed file.');
}
const destroyOptions = {
useMasterKey: true
};
if (options.hasOwnProperty('useMasterKey')) {
destroyOptions.useMasterKey = !!options.useMasterKey;
}
const controller = _CoreManager.default.getFileController();
return controller.deleteFile(this._name, destroyOptions).then(() => {
this._data = undefined;
this._requestTask = null;
return this;
});
}
toJSON() {
return {
__type: 'File',
name: this._name,
url: this._url
};
}
equals(other) {
if (this === other) {
return true;
}
// Unsaved Files are never equal, since they will be saved to different URLs
return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
}
/**
* Sets metadata to be saved with file object. Overwrites existing metadata
*
* @param {object} metadata Key value pairs to be stored with file object
*/
setMetadata(metadata) {
if (metadata && typeof metadata === 'object') {
var _context4;
(0, _forEach.default)(_context4 = (0, _keys.default)(metadata)).call(_context4, key => {
this.addMetadata(key, metadata[key]);
});
}
}
/**
* Sets metadata to be saved with file object. Adds to existing metadata.
*
* @param {string} key key to store the metadata
* @param {*} value metadata
*/
addMetadata(key, value) {
if (typeof key === 'string') {
this._metadata[key] = value;
}
}
/**
* Sets tags to be saved with file object. Overwrites existing tags
*
* @param {object} tags Key value pairs to be stored with file object
*/
setTags(tags) {
if (tags && typeof tags === 'object') {
var _context5;
(0, _forEach.default)(_context5 = (0, _keys.default)(tags)).call(_context5, key => {
this.addTag(key, tags[key]);
});
}
}
/**
* Sets tags to be saved with file object. Adds to existing tags.
*
* @param {string} key key to store tags
* @param {*} value tag
*/
addTag(key, value) {
if (typeof key === 'string') {
this._tags[key] = value;
}
}
static fromJSON(obj) {
if (obj.__type !== 'File') {
throw new TypeError('JSON object does not represent a ParseFile');
}
const file = new ParseFile(obj.name);
file._url = obj.url;
return file;
}
static encodeBase64(bytes) {
const chunks = [];
chunks.length = Math.ceil(bytes.length / 3);
for (let i = 0; i < chunks.length; i++) {
const b1 = bytes[i * 3];
const b2 = bytes[i * 3 + 1] || 0;
const b3 = bytes[i * 3 + 2] || 0;
const has2 = i * 3 + 1 < bytes.length;
const has3 = i * 3 + 2 < bytes.length;
chunks[i] = [b64Digit(b1 >> 2 & 0x3f), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0f), has2 ? b64Digit(b2 << 2 & 0x3c | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3f) : '='].join('');
}
return chunks.join('');
}
}
const DefaultController = {
saveFile: async function (name, source, options) {
if (source.format !== 'file') {
throw new Error('saveFile can only be used with File-type sources.');
}
const base64Data = await new _promise.default((res, rej) => {
// eslint-disable-next-line no-undef
const reader = new FileReader();
reader.onload = () => res(reader.result);
reader.onerror = error => rej(error);
reader.readAsDataURL(source.file);
});
// we only want the data after the comma
// For example: "data:application/pdf;base64,JVBERi0xLjQKJ..." we would only want "JVBERi0xLjQKJ..."
const [first, second] = base64Data.split(',');
// in the event there is no 'data:application/pdf;base64,' at the beginning of the base64 string
// use the entire string instead
const data = second ? second : first;
const newSource = {
format: 'base64',
base64: data,
type: source.type || (source.file ? source.file.type : undefined)
};
return await DefaultController.saveBase64(name, newSource, options);
},
saveBase64: function (name, source) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (source.format !== 'base64') {
throw new Error('saveBase64 can only be used with Base64-type sources.');
}
const data = {
base64: source.base64,
fileData: {
metadata: {
...options.metadata
},
tags: {
...options.tags
}
}
};
delete options.metadata;
delete options.tags;
if (source.type) {
data._ContentType = source.type;
}
return _CoreManager.default.getRESTController().request('POST', 'files/' + name, data, options);
},
download: function (uri, options) {
if (XHR) {
return this.downloadAjax(uri, options);
} else {
return _promise.default.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
}
},
downloadAjax: function (uri, options) {
return new _promise.default((resolve, reject) => {
const xhr = new XHR();
xhr.open('GET', uri, true);
xhr.responseType = 'arraybuffer';
xhr.onerror = function (e) {
reject(e);
};
xhr.onreadystatechange = function () {
if (xhr.readyState !== xhr.DONE) {
return;
}
if (!this.response) {
return resolve({});
}
const bytes = new Uint8Array(this.response);
resolve({
base64: ParseFile.encodeBase64(bytes),
contentType: xhr.getResponseHeader('content-type')
});
};
options.requestTask(xhr);
xhr.send();
});
},
deleteFile: function (name, options) {
const headers = {
'X-Parse-Application-ID': _CoreManager.default.get('APPLICATION_ID')
};
if (options.useMasterKey) {
headers['X-Parse-Master-Key'] = _CoreManager.default.get('MASTER_KEY');
}
let url = _CoreManager.default.get('SERVER_URL');
if (url[url.length - 1] !== '/') {
url += '/';
}
url += 'files/' + name;
return _CoreManager.default.getRESTController().ajax('DELETE', url, '', headers).catch(response => {
// TODO: return JSON object in server
if (!response || response === 'SyntaxError: Unexpected end of JSON input') {
return _promise.default.resolve();
} else {
return _CoreManager.default.getRESTController().handleError(response);
}
});
},
_setXHR(xhr) {
XHR = xhr;
},
_getXHR() {
return XHR;
}
};
_CoreManager.default.setFileController(DefaultController);
var _default = exports.default = ParseFile;
exports.b64Digit = b64Digit;
},{"./CoreManager":4,"./ParseError":24,"./Xhr.weapp":52,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/instance/slice":80,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],26:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
/**
* Creates a new GeoPoint with any of the following forms:
*
* new GeoPoint(otherGeoPoint)
* new GeoPoint(30, 30)
* new GeoPoint([30, 30])
* new GeoPoint({latitude: 30, longitude: 30})
* new GeoPoint() // defaults to (0, 0)
*
* Represents a latitude / longitude point that may be associated
* with a key in a ParseObject or used as a reference point for geo queries.
* This allows proximity-based queries on the key.
*
* Only one key in a class may contain a GeoPoint.
*
* Example:
* var point = new Parse.GeoPoint(30.0, -20.0);
* var object = new Parse.Object("PlaceObject");
* object.set("location", point);
* object.save();
*
* @alias Parse.GeoPoint
*/
/* global navigator */
class ParseGeoPoint {
/**
* @param {(number[] | object | number)} arg1 Either a list of coordinate pairs, an object with `latitude`, `longitude`, or the latitude or the point.
* @param {number} arg2 The longitude of the GeoPoint
*/
constructor(arg1, arg2) {
(0, _defineProperty2.default)(this, "_latitude", void 0);
(0, _defineProperty2.default)(this, "_longitude", void 0);
if ((0, _isArray.default)(arg1)) {
ParseGeoPoint._validate(arg1[0], arg1[1]);
this._latitude = arg1[0];
this._longitude = arg1[1];
} else if (typeof arg1 === 'object') {
ParseGeoPoint._validate(arg1.latitude, arg1.longitude);
this._latitude = arg1.latitude;
this._longitude = arg1.longitude;
} else if (arg1 !== undefined && arg2 !== undefined) {
ParseGeoPoint._validate(arg1, arg2);
this._latitude = arg1;
this._longitude = arg2;
} else {
this._latitude = 0;
this._longitude = 0;
}
}
/**
* North-south portion of the coordinate, in range [-90, 90].
* Throws an exception if set out of range in a modern browser.
*
* @property {number} latitude
* @returns {number}
*/
get latitude() {
return this._latitude;
}
set latitude(val) {
ParseGeoPoint._validate(val, this.longitude);
this._latitude = val;
}
/**
* East-west portion of the coordinate, in range [-180, 180].
* Throws if set out of range in a modern browser.
*
* @property {number} longitude
* @returns {number}
*/
get longitude() {
return this._longitude;
}
set longitude(val) {
ParseGeoPoint._validate(this.latitude, val);
this._longitude = val;
}
/**
* Returns a JSON representation of the GeoPoint, suitable for Parse.
*
* @returns {object}
*/
toJSON() {
ParseGeoPoint._validate(this._latitude, this._longitude);
return {
__type: 'GeoPoint',
latitude: this._latitude,
longitude: this._longitude
};
}
equals(other) {
return other instanceof ParseGeoPoint && this.latitude === other.latitude && this.longitude === other.longitude;
}
/**
* Returns the distance from this GeoPoint to another in radians.
*
* @param {Parse.GeoPoint} point the other Parse.GeoPoint.
* @returns {number}
*/
radiansTo(point) {
const d2r = Math.PI / 180.0;
const lat1rad = this.latitude * d2r;
const long1rad = this.longitude * d2r;
const lat2rad = point.latitude * d2r;
const long2rad = point.longitude * d2r;
const sinDeltaLatDiv2 = Math.sin((lat1rad - lat2rad) / 2);
const sinDeltaLongDiv2 = Math.sin((long1rad - long2rad) / 2);
// Square of half the straight line chord distance between both points.
let a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2;
a = Math.min(1.0, a);
return 2 * Math.asin(Math.sqrt(a));
}
/**
* Returns the distance from this GeoPoint to another in kilometers.
*
* @param {Parse.GeoPoint} point the other Parse.GeoPoint.
* @returns {number}
*/
kilometersTo(point) {
return this.radiansTo(point) * 6371.0;
}
/**
* Returns the distance from this GeoPoint to another in miles.
*
* @param {Parse.GeoPoint} point the other Parse.GeoPoint.
* @returns {number}
*/
milesTo(point) {
return this.radiansTo(point) * 3958.8;
}
/*
* Throws an exception if the given lat-long is out of bounds.
*/
static _validate(latitude, longitude) {
if (isNaN(latitude) || isNaN(longitude) || typeof latitude !== 'number' || typeof longitude !== 'number') {
throw new TypeError('GeoPoint latitude and longitude must be valid numbers');
}
if (latitude < -90.0) {
throw new TypeError('GeoPoint latitude out of bounds: ' + latitude + ' < -90.0.');
}
if (latitude > 90.0) {
throw new TypeError('GeoPoint latitude out of bounds: ' + latitude + ' > 90.0.');
}
if (longitude < -180.0) {
throw new TypeError('GeoPoint longitude out of bounds: ' + longitude + ' < -180.0.');
}
if (longitude > 180.0) {
throw new TypeError('GeoPoint longitude out of bounds: ' + longitude + ' > 180.0.');
}
}
/**
* Creates a GeoPoint with the user's current location, if available.
*
* @param {object} options The options.
* @param {boolean} [options.enableHighAccuracy] 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] 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] 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
*/
static current(options) {
return new _promise.default((resolve, reject) => {
navigator.geolocation.getCurrentPosition(location => {
resolve(new ParseGeoPoint(location.coords.latitude, location.coords.longitude));
}, reject, options);
});
}
}
var _default = exports.default = ParseGeoPoint;
},{"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],27:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.create = create;
exports.createFunction = createFunction;
exports.createTrigger = createTrigger;
exports.getFunction = getFunction;
exports.getFunctions = getFunctions;
exports.getTrigger = getTrigger;
exports.getTriggers = getTriggers;
exports.remove = remove;
exports.removeFunction = removeFunction;
exports.removeTrigger = removeTrigger;
exports.update = update;
exports.updateFunction = updateFunction;
exports.updateTrigger = updateTrigger;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _decode = _interopRequireDefault(_dereq_("./decode"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
function getFunctions() {
return _CoreManager.default.getHooksController().get('functions');
}
function getTriggers() {
return _CoreManager.default.getHooksController().get('triggers');
}
function getFunction(name) {
return _CoreManager.default.getHooksController().get('functions', name);
}
function getTrigger(className, triggerName) {
return _CoreManager.default.getHooksController().get('triggers', className, triggerName);
}
function createFunction(functionName, url) {
return create({
functionName: functionName,
url: url
});
}
function createTrigger(className, triggerName, url) {
return create({
className: className,
triggerName: triggerName,
url: url
});
}
function create(hook) {
return _CoreManager.default.getHooksController().create(hook);
}
function updateFunction(functionName, url) {
return update({
functionName: functionName,
url: url
});
}
function updateTrigger(className, triggerName, url) {
return update({
className: className,
triggerName: triggerName,
url: url
});
}
function update(hook) {
return _CoreManager.default.getHooksController().update(hook);
}
function removeFunction(functionName) {
return remove({
functionName: functionName
});
}
function removeTrigger(className, triggerName) {
return remove({
className: className,
triggerName: triggerName
});
}
function remove(hook) {
return _CoreManager.default.getHooksController().remove(hook);
}
const DefaultController = {
get(type, functionName, triggerName) {
let url = '/hooks/' + type;
if (functionName) {
url += '/' + functionName;
if (triggerName) {
url += '/' + triggerName;
}
}
return this.sendRequest('GET', url);
},
create(hook) {
let url;
if (hook.functionName && hook.url) {
url = '/hooks/functions';
} else if (hook.className && hook.triggerName && hook.url) {
url = '/hooks/triggers';
} else {
return _promise.default.reject({
error: 'invalid hook declaration',
code: 143
});
}
return this.sendRequest('POST', url, hook);
},
remove(hook) {
let url;
if (hook.functionName) {
url = '/hooks/functions/' + hook.functionName;
delete hook.functionName;
} else if (hook.className && hook.triggerName) {
url = '/hooks/triggers/' + hook.className + '/' + hook.triggerName;
delete hook.className;
delete hook.triggerName;
} else {
return _promise.default.reject({
error: 'invalid hook declaration',
code: 143
});
}
return this.sendRequest('PUT', url, {
__op: 'Delete'
});
},
update(hook) {
let url;
if (hook.functionName && hook.url) {
url = '/hooks/functions/' + hook.functionName;
delete hook.functionName;
} else if (hook.className && hook.triggerName && hook.url) {
url = '/hooks/triggers/' + hook.className + '/' + hook.triggerName;
delete hook.className;
delete hook.triggerName;
} else {
return _promise.default.reject({
error: 'invalid hook declaration',
code: 143
});
}
return this.sendRequest('PUT', url, hook);
},
sendRequest(method, url, body) {
return _CoreManager.default.getRESTController().request(method, url, body, {
useMasterKey: true
}).then(res => {
const decoded = (0, _decode.default)(res);
if (decoded) {
return _promise.default.resolve(decoded);
}
return _promise.default.reject(new _ParseError.default(_ParseError.default.INVALID_JSON, 'The server returned an invalid response.'));
});
}
};
_CoreManager.default.setHooksController(DefaultController);
},{"./CoreManager":4,"./ParseError":24,"./decode":55,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],28:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _entries = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/entries"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
const DEVICE_TYPES = {
IOS: 'ios',
MACOS: 'macos',
TVOS: 'tvos',
FCM: 'fcm',
ANDROID: 'android',
WEB: 'web'
};
/**
* Parse.Installation is a local representation of installation data that can be saved and retrieved from the Parse cloud.
* This class is a subclass of a Parse.Object, and retains the same functionality of a Parse.Object, but also extends it with installation-specific features.
*
* A valid Parse.Installation can only be instantiated via Parse.Installation.currentInstallation()
*
* Parse.Installation objects which have a valid deviceToken
and are saved to the Parse cloud can be used to target push notifications.
*
*
* @alias Parse.Installation
*/
class ParseInstallation extends _ParseObject.default {
/**
* @param {object} attributes The initial set of data to store in the object.
*/
constructor(attributes) {
super('_Installation');
if (attributes && typeof attributes === 'object') {
if (!this.set(attributes)) {
throw new Error("Can't create an invalid Installation");
}
}
}
/**
* A unique identifier for this installation’s client application. In iOS, this is the Bundle Identifier.
*
* @property {string} appIdentifier
* @static
* @returns {string}
*/
get appIdentifier() {
return this.get('appIdentifier');
}
/**
* The version string of the client application to which this installation belongs.
*
* @property {string} appVersion
* @static
* @returns {string}
*/
get appVersion() {
return this.get('appVersion');
}
/**
* The display name of the client application to which this installation belongs.
*
* @property {string} appName
* @static
* @returns {string}
*/
get appName() {
return this.get('appName');
}
/**
* The current value of the icon badge for iOS apps.
* Changes to this value on the server will be used
* for future badge-increment push notifications.
*
* @property {number} badge
* @static
* @returns {number}
*/
get badge() {
return this.get('badge');
}
/**
* An array of the channels to which a device is currently subscribed.
*
* @property {string[]} channels
* @static
* @returns {string[]}
*/
get channels() {
return this.get('channels');
}
/**
* Token used to deliver push notifications to the device.
*
* @property {string} deviceToken
* @static
* @returns {string}
*/
get deviceToken() {
return this.get('deviceToken');
}
/**
* The type of device, “ios”, “android”, “web”, etc.
*
* @property {string} deviceType
* @static
* @returns {string}
*/
get deviceType() {
return this.get('deviceType');
}
/**
* Gets the GCM sender identifier for this installation
*
* @property {string} GCMSenderId
* @static
* @returns {string}
*/
get GCMSenderId() {
return this.get('GCMSenderId');
}
/**
* Universally Unique Identifier (UUID) for the device used by Parse. It must be unique across all of an app’s installations.
*
* @property {string} installationId
* @static
* @returns {string}
*/
get installationId() {
return this.get('installationId');
}
/**
* Gets the local identifier for this installation
*
* @property {string} localeIdentifier
* @static
* @returns {string}
*/
get localeIdentifier() {
return this.get('localeIdentifier');
}
/**
* Gets the parse server version for this installation
*
* @property {string} parseVersion
* @static
* @returns {string}
*/
get parseVersion() {
return this.get('parseVersion');
}
/**
* This field is reserved for directing Parse to the push delivery network to be used.
*
* @property {string} pushType
* @static
* @returns {string}
*/
get pushType() {
return this.get('pushType');
}
/**
* Gets the time zone for this installation
*
* @property {string} timeZone
* @static
* @returns {string}
*/
get timeZone() {
return this.get('timeZone');
}
/**
* Returns the device types for used for Push Notifications.
*
*
* Parse.Installation.DEVICE_TYPES.IOS
* Parse.Installation.DEVICE_TYPES.MACOS
* Parse.Installation.DEVICE_TYPES.TVOS
* Parse.Installation.DEVICE_TYPES.FCM
* Parse.Installation.DEVICE_TYPES.ANDROID
* Parse.Installation.DEVICE_TYPES.WEB
*
* const installation = await Parse.Installation.currentInstallation();
* installation.set('deviceToken', '123');
* await installation.save();
*
*
* @returns {Promise} A promise that resolves to the local installation object.
*/
static currentInstallation() {
return _CoreManager.default.getInstallationController().currentInstallation();
}
}
_ParseObject.default.registerSubclass('_Installation', ParseInstallation);
module.exports = ParseInstallation;
var _default = exports.default = ParseInstallation;
},{"./CoreManager":4,"./ParseError":24,"./ParseObject":30,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/entries":91,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],29:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _LiveQueryClient = _interopRequireDefault(_dereq_("./LiveQueryClient"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
function getLiveQueryClient() {
return _CoreManager.default.getLiveQueryController().getDefaultLiveQueryClient();
}
/**
* We expose three events to help you monitor the status of the WebSocket connection:
*
* Open - When we establish the WebSocket connection to the LiveQuery server, you'll get this event.
*
*
* Parse.LiveQuery.on('open', () => {
*
* });
*
* Close - When we lose the WebSocket connection to the LiveQuery server, you'll get this event.
*
*
* Parse.LiveQuery.on('close', () => {
*
* });
*
* Error - When some network error or LiveQuery server error happens, you'll get this event.
*
*
* Parse.LiveQuery.on('error', (error) => {
*
* });
*
* @class Parse.LiveQuery
* @static
*/
class LiveQuery {
constructor() {
var _this = this;
(0, _defineProperty2.default)(this, "emitter", void 0);
(0, _defineProperty2.default)(this, "on", void 0);
(0, _defineProperty2.default)(this, "emit", void 0);
const EventEmitter = _CoreManager.default.getEventEmitter();
this.emitter = new EventEmitter();
this.on = (eventName, listener) => this.emitter.on(eventName, listener);
this.emit = function (eventName) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return _this.emitter.emit(eventName, ...args);
};
// adding listener so process does not crash
// best practice is for developer to register their own listener
this.on('error', () => {});
}
/**
* After open is called, the LiveQuery will try to send a connect request
* to the LiveQuery server.
*/
async open() {
const liveQueryClient = await getLiveQueryClient();
liveQueryClient.open();
}
/**
* When you're done using LiveQuery, you can call Parse.LiveQuery.close().
* This function will close the WebSocket connection to the LiveQuery server,
* cancel the auto reconnect, and unsubscribe all subscriptions based on it.
* If you call query.subscribe() after this, we'll create a new WebSocket
* connection to the LiveQuery server.
*/
async close() {
const liveQueryClient = await getLiveQueryClient();
liveQueryClient.close();
}
}
var _default = exports.default = LiveQuery;
let defaultLiveQueryClient;
const DefaultLiveQueryController = {
setDefaultLiveQueryClient(liveQueryClient) {
defaultLiveQueryClient = liveQueryClient;
},
async getDefaultLiveQueryClient() {
if (defaultLiveQueryClient) {
return defaultLiveQueryClient;
}
const [currentUser, installationId] = await _promise.default.all([_CoreManager.default.getUserController().currentUserAsync(), _CoreManager.default.getInstallationController().currentInstallationId()]);
const sessionToken = currentUser ? currentUser.getSessionToken() : undefined;
let liveQueryServerURL = _CoreManager.default.get('LIVEQUERY_SERVER_URL');
if (liveQueryServerURL && (0, _indexOf.default)(liveQueryServerURL).call(liveQueryServerURL, 'ws') !== 0) {
throw new Error('You need to set a proper Parse LiveQuery server url before using LiveQueryClient');
}
// If we can not find Parse.liveQueryServerURL, we try to extract it from Parse.serverURL
if (!liveQueryServerURL) {
const serverURL = _CoreManager.default.get('SERVER_URL');
const protocol = (0, _indexOf.default)(serverURL).call(serverURL, 'https') === 0 ? 'wss://' : 'ws://';
const host = serverURL.replace(/^https?:\/\//, '');
liveQueryServerURL = protocol + host;
_CoreManager.default.set('LIVEQUERY_SERVER_URL', liveQueryServerURL);
}
const applicationId = _CoreManager.default.get('APPLICATION_ID');
const javascriptKey = _CoreManager.default.get('JAVASCRIPT_KEY');
const masterKey = _CoreManager.default.get('MASTER_KEY');
defaultLiveQueryClient = new _LiveQueryClient.default({
applicationId,
serverURL: liveQueryServerURL,
javascriptKey,
masterKey,
sessionToken,
installationId
});
const LiveQuery = _CoreManager.default.getLiveQuery();
defaultLiveQueryClient.on('error', error => {
LiveQuery.emit('error', error);
});
defaultLiveQueryClient.on('open', () => {
LiveQuery.emit('open');
});
defaultLiveQueryClient.on('close', () => {
LiveQuery.emit('close');
});
return defaultLiveQueryClient;
},
_clearCachedDefaultClient() {
defaultLiveQueryClient = null;
}
};
_CoreManager.default.setLiveQueryController(DefaultLiveQueryController);
},{"./CoreManager":4,"./LiveQueryClient":11,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],30:[function(_dereq_,module,exports){
"use strict";
var _WeakMap = _dereq_("@babel/runtime-corejs3/core-js-stable/weak-map");
var _Object$defineProperty2 = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _Object$getOwnPropertyDescriptor = _dereq_("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty2(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _freeze = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/freeze"));
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _includes = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/includes"));
var _getPrototypeOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/get-prototype-of"));
var _concat = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _create = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/create"));
var _defineProperty3 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property"));
var _find = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/find"));
var _map = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _canBeSerialized = _interopRequireDefault(_dereq_("./canBeSerialized"));
var _decode = _interopRequireDefault(_dereq_("./decode"));
var _encode = _interopRequireDefault(_dereq_("./encode"));
var _escape = _interopRequireDefault(_dereq_("./escape"));
var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
var _parseDate = _interopRequireDefault(_dereq_("./parseDate"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
var _promiseUtils = _dereq_("./promiseUtils");
var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
var _uuid = _interopRequireDefault(_dereq_("./uuid"));
var _ParseOp = _dereq_("./ParseOp");
var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
var SingleInstanceStateController = _interopRequireWildcard(_dereq_("./SingleInstanceStateController"));
var _unique = _interopRequireDefault(_dereq_("./unique"));
var UniqueInstanceStateController = _interopRequireWildcard(_dereq_("./UniqueInstanceStateController"));
var _unsavedChildren = _interopRequireDefault(_dereq_("./unsavedChildren"));
function _getRequireWildcardCache(e) {
if ("function" != typeof _WeakMap) return null;
var r = new _WeakMap(),
t = new _WeakMap();
return (_getRequireWildcardCache = function (e) {
return e ? t : r;
})(e);
}
function _interopRequireWildcard(e, r) {
if (!r && e && e.__esModule) return e;
if (null === e || "object" != typeof e && "function" != typeof e) return {
default: e
};
var t = _getRequireWildcardCache(r);
if (t && t.has(e)) return t.get(e);
var n = {
__proto__: null
};
for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
var i = _Object$defineProperty2 && _Object$getOwnPropertyDescriptor ? _Object$getOwnPropertyDescriptor(e, u) : null;
i && (i.get || i.set) ? _Object$defineProperty2(n, u, i) : n[u] = e[u];
}
return n.default = e, t && t.set(e, n), n;
}
// Mapping of class names to constructors, so we can populate objects from the
// server with appropriate subclasses of ParseObject
const classMap = {};
// Global counter for generating unique Ids for non-single-instance objects
let objectCount = 0;
// On web clients, objects are single-instance: any two objects with the same Id
// will have the same attributes. However, this may be dangerous default
// behavior in a server scenario
let singleInstance = !_CoreManager.default.get('IS_NODE');
if (singleInstance) {
_CoreManager.default.setObjectStateController(SingleInstanceStateController);
} else {
_CoreManager.default.setObjectStateController(UniqueInstanceStateController);
}
function getServerUrlPath() {
let serverUrl = _CoreManager.default.get('SERVER_URL');
if (serverUrl[serverUrl.length - 1] !== '/') {
serverUrl += '/';
}
const url = serverUrl.replace(/https?:\/\//, '');
return url.substr((0, _indexOf.default)(url).call(url, '/'));
}
/**
* Creates a new model with defined attributes.
*
* You won't normally call this method directly. It is recommended that
* you use a subclass of Parse.Object
instead, created by calling
* extend
.
*
* However, if you don't want to use a subclass, or aren't sure which
* subclass is appropriate, you can use this form:
* var object = new Parse.Object("ClassName");
*
* That is basically equivalent to:
* var MyClass = Parse.Object.extend("ClassName");
* var object = new MyClass();
*
*
* @alias Parse.Object
*/
class ParseObject {
/**
* @param {string} className The class name for the object
* @param {object} attributes The initial set of data to store in the object.
* @param {object} options The options for this object instance.
* @param {boolean} [options.ignoreValidation] Set to `true` ignore any attribute validation errors.
*/
constructor(className, attributes, options) {
/**
* The ID of this object, unique within its class.
*
* @property {string} id
*/
(0, _defineProperty2.default)(this, "id", void 0);
(0, _defineProperty2.default)(this, "_localId", void 0);
(0, _defineProperty2.default)(this, "_objCount", void 0);
(0, _defineProperty2.default)(this, "className", void 0);
// Enable legacy initializers
if (typeof this.initialize === 'function') {
this.initialize.apply(this, arguments);
}
let toSet = null;
this._objCount = objectCount++;
if (typeof className === 'string') {
this.className = className;
if (attributes && typeof attributes === 'object') {
toSet = attributes;
}
} else if (className && typeof className === 'object') {
this.className = className.className;
toSet = {};
for (const attr in className) {
if (attr !== 'className') {
toSet[attr] = className[attr];
}
}
if (attributes && typeof attributes === 'object') {
options = attributes;
}
}
if (toSet && !this.set(toSet, options)) {
throw new Error("Can't create an invalid Parse Object");
}
}
/* Prototype getters / setters */
get attributes() {
const stateController = _CoreManager.default.getObjectStateController();
return (0, _freeze.default)(stateController.estimateAttributes(this._getStateIdentifier()));
}
/**
* The first time this object was saved on the server.
*
* @property {Date} createdAt
* @returns {Date}
*/
get createdAt() {
return this._getServerData().createdAt;
}
/**
* The last time this object was updated on the server.
*
* @property {Date} updatedAt
* @returns {Date}
*/
get updatedAt() {
return this._getServerData().updatedAt;
}
/* Private methods */
/**
* Returns a local or server Id used uniquely identify this object
*
* @returns {string}
*/
_getId() {
if (typeof this.id === 'string') {
return this.id;
}
if (typeof this._localId === 'string') {
return this._localId;
}
const localId = 'local' + (0, _uuid.default)();
this._localId = localId;
return localId;
}
/**
* Returns a unique identifier used to pull data from the State Controller.
*
* @returns {Parse.Object|object}
*/
_getStateIdentifier() {
if (singleInstance) {
let id = this.id;
if (!id) {
id = this._getId();
}
return {
id: id,
className: this.className
};
} else {
return this;
}
}
_getServerData() {
const stateController = _CoreManager.default.getObjectStateController();
return stateController.getServerData(this._getStateIdentifier());
}
_clearServerData() {
const serverData = this._getServerData();
const unset = {};
for (const attr in serverData) {
unset[attr] = undefined;
}
const stateController = _CoreManager.default.getObjectStateController();
stateController.setServerData(this._getStateIdentifier(), unset);
}
_getPendingOps() {
const stateController = _CoreManager.default.getObjectStateController();
return stateController.getPendingOps(this._getStateIdentifier());
}
/**
* @param {Array} [keysToClear] - if specified, only ops matching
* these fields will be cleared
*/
_clearPendingOps(keysToClear) {
const pending = this._getPendingOps();
const latest = pending[pending.length - 1];
const keys = keysToClear || (0, _keys.default)(latest);
(0, _forEach.default)(keys).call(keys, key => {
delete latest[key];
});
}
_getDirtyObjectAttributes() {
const attributes = this.attributes;
const stateController = _CoreManager.default.getObjectStateController();
const objectCache = stateController.getObjectCache(this._getStateIdentifier());
const dirty = {};
for (const attr in attributes) {
const val = attributes[attr];
if (val && typeof val === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
// Due to the way browsers construct maps, the key order will not change
// unless the object is changed
try {
const json = (0, _encode.default)(val, false, true);
const stringified = (0, _stringify.default)(json);
if (objectCache[attr] !== stringified) {
dirty[attr] = val;
}
} catch (e) {
// Error occurred, possibly by a nested unsaved pointer in a mutable container
// No matter how it happened, it indicates a change in the attribute
dirty[attr] = val;
}
}
}
return dirty;
}
_toFullJSON(seen, offline) {
const json = this.toJSON(seen, offline);
json.__type = 'Object';
json.className = this.className;
return json;
}
_getSaveJSON() {
const pending = this._getPendingOps();
const dirtyObjects = this._getDirtyObjectAttributes();
const json = {};
for (var attr in dirtyObjects) {
let isDotNotation = false;
for (let i = 0; i < pending.length; i += 1) {
for (const field in pending[i]) {
// Dot notation operations are handled later
if ((0, _includes.default)(field).call(field, '.')) {
const fieldName = field.split('.')[0];
if (fieldName === attr) {
isDotNotation = true;
break;
}
}
}
}
if (!isDotNotation) {
json[attr] = new _ParseOp.SetOp(dirtyObjects[attr]).toJSON();
}
}
for (attr in pending[0]) {
json[attr] = pending[0][attr].toJSON();
}
return json;
}
_getSaveParams() {
let method = this.id ? 'PUT' : 'POST';
const body = this._getSaveJSON();
let path = 'classes/' + this.className;
if (_CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID')) {
if (!this.createdAt) {
method = 'POST';
body.objectId = this.id;
} else {
method = 'PUT';
path += '/' + this.id;
}
} else if (this.id) {
path += '/' + this.id;
} else if (this.className === '_User') {
path = 'users';
}
return {
method,
body,
path
};
}
_finishFetch(serverData) {
if (!this.id && serverData.objectId) {
this.id = serverData.objectId;
}
const stateController = _CoreManager.default.getObjectStateController();
stateController.initializeState(this._getStateIdentifier());
const decoded = {};
for (const attr in serverData) {
if (attr === 'ACL') {
decoded[attr] = new _ParseACL.default(serverData[attr]);
} else if (attr !== 'objectId') {
decoded[attr] = (0, _decode.default)(serverData[attr]);
if (decoded[attr] instanceof _ParseRelation.default) {
decoded[attr]._ensureParentAndKey(this, attr);
}
}
}
if (decoded.createdAt && typeof decoded.createdAt === 'string') {
decoded.createdAt = (0, _parseDate.default)(decoded.createdAt);
}
if (decoded.updatedAt && typeof decoded.updatedAt === 'string') {
decoded.updatedAt = (0, _parseDate.default)(decoded.updatedAt);
}
if (!decoded.updatedAt && decoded.createdAt) {
decoded.updatedAt = decoded.createdAt;
}
stateController.commitServerChanges(this._getStateIdentifier(), decoded);
}
_setExisted(existed) {
const stateController = _CoreManager.default.getObjectStateController();
const state = stateController.getState(this._getStateIdentifier());
if (state) {
state.existed = existed;
}
}
_migrateId(serverId) {
if (this._localId && serverId) {
if (singleInstance) {
const stateController = _CoreManager.default.getObjectStateController();
const oldState = stateController.removeState(this._getStateIdentifier());
this.id = serverId;
delete this._localId;
if (oldState) {
stateController.initializeState(this._getStateIdentifier(), oldState);
}
} else {
this.id = serverId;
delete this._localId;
}
}
}
_handleSaveResponse(response, status) {
const changes = {};
const stateController = _CoreManager.default.getObjectStateController();
const pending = stateController.popPendingState(this._getStateIdentifier());
for (var attr in pending) {
if (pending[attr] instanceof _ParseOp.RelationOp) {
changes[attr] = pending[attr].applyTo(undefined, this, attr);
} else if (!(attr in response)) {
// Only SetOps and UnsetOps should not come back with results
changes[attr] = pending[attr].applyTo(undefined);
}
}
for (attr in response) {
if ((attr === 'createdAt' || attr === 'updatedAt') && typeof response[attr] === 'string') {
changes[attr] = (0, _parseDate.default)(response[attr]);
} else if (attr === 'ACL') {
changes[attr] = new _ParseACL.default(response[attr]);
} else if (attr !== 'objectId') {
const val = (0, _decode.default)(response[attr]);
if (val && (0, _getPrototypeOf.default)(val) === Object.prototype) {
changes[attr] = {
...this.attributes[attr],
...val
};
} else {
changes[attr] = val;
}
if (changes[attr] instanceof _ParseOp.UnsetOp) {
changes[attr] = undefined;
}
}
}
if (changes.createdAt && !changes.updatedAt) {
changes.updatedAt = changes.createdAt;
}
this._migrateId(response.objectId);
if (status !== 201) {
this._setExisted(true);
}
stateController.commitServerChanges(this._getStateIdentifier(), changes);
}
_handleSaveError() {
const stateController = _CoreManager.default.getObjectStateController();
stateController.mergeFirstPendingState(this._getStateIdentifier());
}
static _getClassMap() {
return classMap;
}
/* Public methods */
initialize() {
// NOOP
}
/**
* Returns a JSON version of the object suitable for saving to Parse.
*
* @param seen
* @param offline
* @returns {object}
*/
toJSON(seen, offline) {
const seenEntry = this.id ? this.className + ':' + this.id : this;
seen = seen || [seenEntry];
const json = {};
const attrs = this.attributes;
for (const attr in attrs) {
if ((attr === 'createdAt' || attr === 'updatedAt') && attrs[attr].toJSON) {
json[attr] = attrs[attr].toJSON();
} else {
json[attr] = (0, _encode.default)(attrs[attr], false, false, seen, offline);
}
}
const pending = this._getPendingOps();
for (const attr in pending[0]) {
if ((0, _indexOf.default)(attr).call(attr, '.') < 0) {
json[attr] = pending[0][attr].toJSON(offline);
}
}
if (this.id) {
json.objectId = this.id;
}
return json;
}
/**
* Determines whether this ParseObject is equal to another ParseObject
*
* @param {object} other - An other object ot compare
* @returns {boolean}
*/
equals(other) {
if (this === other) {
return true;
}
return other instanceof ParseObject && this.className === other.className && this.id === other.id && typeof this.id !== 'undefined';
}
/**
* Returns true if this object has been modified since its last
* save/refresh. If an attribute is specified, it returns true only if that
* particular attribute has been modified since the last save/refresh.
*
* @param {string} attr An attribute name (optional).
* @returns {boolean}
*/
dirty(attr) {
if (!this.id) {
return true;
}
const pendingOps = this._getPendingOps();
const dirtyObjects = this._getDirtyObjectAttributes();
if (attr) {
if (dirtyObjects.hasOwnProperty(attr)) {
return true;
}
for (let i = 0; i < pendingOps.length; i++) {
if (pendingOps[i].hasOwnProperty(attr)) {
return true;
}
}
return false;
}
if ((0, _keys.default)(pendingOps[0]).length !== 0) {
return true;
}
if ((0, _keys.default)(dirtyObjects).length !== 0) {
return true;
}
return false;
}
/**
* Returns an array of keys that have been modified since last save/refresh
*
* @returns {string[]}
*/
dirtyKeys() {
const pendingOps = this._getPendingOps();
const keys = {};
for (let i = 0; i < pendingOps.length; i++) {
for (const attr in pendingOps[i]) {
keys[attr] = true;
}
}
const dirtyObjects = this._getDirtyObjectAttributes();
for (const attr in dirtyObjects) {
keys[attr] = true;
}
return (0, _keys.default)(keys);
}
/**
* Returns true if the object has been fetched.
*
* @returns {boolean}
*/
isDataAvailable() {
const serverData = this._getServerData();
return !!(0, _keys.default)(serverData).length;
}
/**
* Gets a Pointer referencing this Object.
*
* @returns {Pointer}
*/
toPointer() {
if (!this.id) {
throw new Error('Cannot create a pointer to an unsaved ParseObject');
}
return {
__type: 'Pointer',
className: this.className,
objectId: this.id
};
}
/**
* Gets a Pointer referencing this Object.
*
* @returns {Pointer}
*/
toOfflinePointer() {
if (!this._localId) {
throw new Error('Cannot create a offline pointer to a saved ParseObject');
}
return {
__type: 'Object',
className: this.className,
_localId: this._localId
};
}
/**
* Gets the value of an attribute.
*
* @param {string} attr The string name of an attribute.
* @returns {*}
*/
get(attr) {
return this.attributes[attr];
}
/**
* Gets a relation on the given class for the attribute.
*
* @param {string} attr The attribute to get the relation for.
* @returns {Parse.Relation}
*/
relation(attr) {
const value = this.get(attr);
if (value) {
if (!(value instanceof _ParseRelation.default)) {
throw new Error('Called relation() on non-relation field ' + attr);
}
value._ensureParentAndKey(this, attr);
return value;
}
return new _ParseRelation.default(this, attr);
}
/**
* Gets the HTML-escaped value of an attribute.
*
* @param {string} attr The string name of an attribute.
* @returns {string}
*/
escape(attr) {
let val = this.attributes[attr];
if (val == null) {
return '';
}
if (typeof val !== 'string') {
if (typeof val.toString !== 'function') {
return '';
}
val = val.toString();
}
return (0, _escape.default)(val);
}
/**
* Returns true
if the attribute contains a value that is not
* null or undefined.
*
* @param {string} attr The string name of the attribute.
* @returns {boolean}
*/
has(attr) {
const attributes = this.attributes;
if (attributes.hasOwnProperty(attr)) {
return attributes[attr] != null;
}
return false;
}
/**
* Sets a hash of model attributes on the object.
*
* You can call it with an object containing keys and values, with one
* key and value, or dot notation. For example:
* gameTurn.set({
* player: player1,
* diceRoll: 2
* }, {
* error: function(gameTurnAgain, error) {
* // The set failed validation.
* }
* });
*
* game.set("currentPlayer", player2, {
* error: function(gameTurnAgain, error) {
* // The set failed validation.
* }
* });
*
* game.set("finished", true);
*
* game.set("player.score", 10);
*
* @param {(string|object)} key The key to set.
* @param {(string|object)} value The value to give it.
* @param {object} options A set of options for the set.
* The only supported option is error
.
* @returns {(ParseObject|boolean)} true if the set succeeded.
*/
set(key, value, options) {
let changes = {};
const newOps = {};
if (key && typeof key === 'object') {
changes = key;
options = value;
} else if (typeof key === 'string') {
changes[key] = value;
} else {
return this;
}
options = options || {};
let readonly = [];
if (typeof this.constructor.readOnlyAttributes === 'function') {
readonly = (0, _concat.default)(readonly).call(readonly, this.constructor.readOnlyAttributes());
}
for (const k in changes) {
if (k === 'createdAt' || k === 'updatedAt') {
// This property is read-only, but for legacy reasons we silently
// ignore it
continue;
}
if ((0, _indexOf.default)(readonly).call(readonly, k) > -1) {
throw new Error('Cannot modify readonly attribute: ' + k);
}
if (options.unset) {
newOps[k] = new _ParseOp.UnsetOp();
} else if (changes[k] instanceof _ParseOp.Op) {
newOps[k] = changes[k];
} else if (changes[k] && typeof changes[k] === 'object' && typeof changes[k].__op === 'string') {
newOps[k] = (0, _ParseOp.opFromJSON)(changes[k]);
} else if (k === 'objectId' || k === 'id') {
if (typeof changes[k] === 'string') {
this.id = changes[k];
}
} else if (k === 'ACL' && typeof changes[k] === 'object' && !(changes[k] instanceof _ParseACL.default)) {
newOps[k] = new _ParseOp.SetOp(new _ParseACL.default(changes[k]));
} else if (changes[k] instanceof _ParseRelation.default) {
const relation = new _ParseRelation.default(this, k);
relation.targetClassName = changes[k].targetClassName;
newOps[k] = new _ParseOp.SetOp(relation);
} else {
newOps[k] = new _ParseOp.SetOp(changes[k]);
}
}
const currentAttributes = this.attributes;
// Calculate new values
const newValues = {};
for (const attr in newOps) {
if (newOps[attr] instanceof _ParseOp.RelationOp) {
newValues[attr] = newOps[attr].applyTo(currentAttributes[attr], this, attr);
} else if (!(newOps[attr] instanceof _ParseOp.UnsetOp)) {
newValues[attr] = newOps[attr].applyTo(currentAttributes[attr]);
}
}
// Validate changes
if (!options.ignoreValidation) {
const validation = this.validate(newValues);
if (validation) {
if (typeof options.error === 'function') {
options.error(this, validation);
}
return false;
}
}
// Consolidate Ops
const pendingOps = this._getPendingOps();
const last = pendingOps.length - 1;
const stateController = _CoreManager.default.getObjectStateController();
for (const attr in newOps) {
const nextOp = newOps[attr].mergeWith(pendingOps[last][attr]);
stateController.setPendingOp(this._getStateIdentifier(), attr, nextOp);
}
return this;
}
/**
* Remove an attribute from the model. This is a noop if the attribute doesn't
* exist.
*
* @param {string} attr The string name of an attribute.
* @param options
* @returns {(ParseObject | boolean)}
*/
unset(attr, options) {
options = options || {};
options.unset = true;
return this.set(attr, null, options);
}
/**
* Atomically increments the value of the given attribute the next time the
* object is saved. If no amount is specified, 1 is used by default.
*
* @param attr {String} The key.
* @param amount {Number} The amount to increment by (optional).
* @returns {(ParseObject|boolean)}
*/
increment(attr, amount) {
if (typeof amount === 'undefined') {
amount = 1;
}
if (typeof amount !== 'number') {
throw new Error('Cannot increment by a non-numeric amount.');
}
return this.set(attr, new _ParseOp.IncrementOp(amount));
}
/**
* Atomically decrements the value of the given attribute the next time the
* object is saved. If no amount is specified, 1 is used by default.
*
* @param attr {String} The key.
* @param amount {Number} The amount to decrement by (optional).
* @returns {(ParseObject | boolean)}
*/
decrement(attr, amount) {
if (typeof amount === 'undefined') {
amount = 1;
}
if (typeof amount !== 'number') {
throw new Error('Cannot decrement by a non-numeric amount.');
}
return this.set(attr, new _ParseOp.IncrementOp(amount * -1));
}
/**
* Atomically add an object to the end of the array associated with a given
* key.
*
* @param attr {String} The key.
* @param item {} The item to add.
* @returns {(ParseObject | boolean)}
*/
add(attr, item) {
return this.set(attr, new _ParseOp.AddOp([item]));
}
/**
* Atomically add the objects to the end of the array associated with a given
* key.
*
* @param attr {String} The key.
* @param items {Object[]} The items to add.
* @returns {(ParseObject | boolean)}
*/
addAll(attr, items) {
return this.set(attr, new _ParseOp.AddOp(items));
}
/**
* Atomically add an object to the array associated with a given key, only
* if it is not already present in the array. The position of the insert is
* not guaranteed.
*
* @param attr {String} The key.
* @param item {} The object to add.
* @returns {(ParseObject | boolean)}
*/
addUnique(attr, item) {
return this.set(attr, new _ParseOp.AddUniqueOp([item]));
}
/**
* Atomically add the objects to the array associated with a given key, only
* if it is not already present in the array. The position of the insert is
* not guaranteed.
*
* @param attr {String} The key.
* @param items {Object[]} The objects to add.
* @returns {(ParseObject | boolean)}
*/
addAllUnique(attr, items) {
return this.set(attr, new _ParseOp.AddUniqueOp(items));
}
/**
* Atomically remove all instances of an object from the array associated
* with a given key.
*
* @param attr {String} The key.
* @param item {} The object to remove.
* @returns {(ParseObject | boolean)}
*/
remove(attr, item) {
return this.set(attr, new _ParseOp.RemoveOp([item]));
}
/**
* Atomically remove all instances of the objects from the array associated
* with a given key.
*
* @param attr {String} The key.
* @param items {Object[]} The object to remove.
* @returns {(ParseObject | boolean)}
*/
removeAll(attr, items) {
return this.set(attr, new _ParseOp.RemoveOp(items));
}
/**
* Returns an instance of a subclass of Parse.Op describing what kind of
* modification has been performed on this field since the last time it was
* saved. For example, after calling object.increment("x"), calling
* object.op("x") would return an instance of Parse.Op.Increment.
*
* @param attr {String} The key.
* @returns {Parse.Op | undefined} The operation, or undefined if none.
*/
op(attr) {
const pending = this._getPendingOps();
for (let i = pending.length; i--;) {
if (pending[i][attr]) {
return pending[i][attr];
}
}
}
/**
* Creates a new model with identical attributes to this one.
*
* @returns {Parse.Object}
*/
clone() {
const clone = new this.constructor(this.className);
let attributes = this.attributes;
if (typeof this.constructor.readOnlyAttributes === 'function') {
const readonly = this.constructor.readOnlyAttributes() || [];
// Attributes are frozen, so we have to rebuild an object,
// rather than delete readonly keys
const copy = {};
for (const a in attributes) {
if ((0, _indexOf.default)(readonly).call(readonly, a) < 0) {
copy[a] = attributes[a];
}
}
attributes = copy;
}
if (clone.set) {
clone.set(attributes);
}
return clone;
}
/**
* Creates a new instance of this object. Not to be confused with clone()
*
* @returns {Parse.Object}
*/
newInstance() {
const clone = new this.constructor(this.className);
clone.id = this.id;
if (singleInstance) {
// Just return an object with the right id
return clone;
}
const stateController = _CoreManager.default.getObjectStateController();
if (stateController) {
stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
}
return clone;
}
/**
* Returns true if this object has never been saved to Parse.
*
* @returns {boolean}
*/
isNew() {
return !this.id;
}
/**
* Returns true if this object was created by the Parse server when the
* object might have already been there (e.g. in the case of a Facebook
* login)
*
* @returns {boolean}
*/
existed() {
if (!this.id) {
return false;
}
const stateController = _CoreManager.default.getObjectStateController();
const state = stateController.getState(this._getStateIdentifier());
if (state) {
return state.existed;
}
return false;
}
/**
* Returns true if this object exists on the Server
*
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
* @returns {Promise} A boolean promise that is fulfilled if object exists.
*/
async exists(options) {
if (!this.id) {
return false;
}
try {
const ParseQuery = _CoreManager.default.getParseQuery();
const query = new ParseQuery(this.className);
await query.get(this.id, options);
return true;
} catch (e) {
if (e.code === _ParseError.default.OBJECT_NOT_FOUND) {
return false;
}
throw e;
}
}
/**
* Checks if the model is currently in a valid state.
*
* @returns {boolean}
*/
isValid() {
return !this.validate(this.attributes);
}
/**
* You should not call this function directly unless you subclass
* Parse.Object
, in which case you can override this method
* to provide additional validation on set
and
* save
. Your implementation should return
*
* @param {object} attrs The current data to validate.
* @returns {Parse.Error|boolean} False if the data is valid. An error object otherwise.
* @see Parse.Object#set
*/
validate(attrs) {
if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof _ParseACL.default)) {
return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'ACL must be a Parse ACL.');
}
for (const key in attrs) {
if (!/^[A-Za-z][0-9A-Za-z_.]*$/.test(key)) {
return new _ParseError.default(_ParseError.default.INVALID_KEY_NAME);
}
}
return false;
}
/**
* Returns the ACL for this object.
*
* @returns {Parse.ACL|null} An instance of Parse.ACL.
* @see Parse.Object#get
*/
getACL() {
const acl = this.get('ACL');
if (acl instanceof _ParseACL.default) {
return acl;
}
return null;
}
/**
* Sets the ACL to be used for this object.
*
* @param {Parse.ACL} acl An instance of Parse.ACL.
* @param {object} options
* @returns {(ParseObject | boolean)} Whether the set passed validation.
* @see Parse.Object#set
*/
setACL(acl, options) {
return this.set('ACL', acl, options);
}
/**
* Clears any (or specific) changes to this object made since the last call to save()
*
* @param {string} [keys] - specify which fields to revert
*/
revert() {
let keysToRevert;
for (var _len = arguments.length, keys = new Array(_len), _key = 0; _key < _len; _key++) {
keys[_key] = arguments[_key];
}
if (keys.length) {
keysToRevert = [];
for (const key of keys) {
if (typeof key === 'string') {
keysToRevert.push(key);
} else {
throw new Error('Parse.Object#revert expects either no, or a list of string, arguments.');
}
}
}
this._clearPendingOps(keysToRevert);
}
/**
* Clears all attributes on a model
*
* @returns {(ParseObject | boolean)}
*/
clear() {
const attributes = this.attributes;
const erasable = {};
let readonly = ['createdAt', 'updatedAt'];
if (typeof this.constructor.readOnlyAttributes === 'function') {
readonly = (0, _concat.default)(readonly).call(readonly, this.constructor.readOnlyAttributes());
}
for (const attr in attributes) {
if ((0, _indexOf.default)(readonly).call(readonly, attr) < 0) {
erasable[attr] = true;
}
}
return this.set(erasable, {
unset: true
});
}
/**
* Fetch the model from the server. If the server's representation of the
* model differs from its current attributes, they will be overriden.
*
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- include: The name(s) of the key(s) to include. Can be a string, an array of strings,
* or an array of array of strings.
*
- context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
*
* @returns {Promise} A promise that is fulfilled when the fetch
* completes.
*/
fetch(options) {
options = options || {};
const fetchOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
fetchOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
fetchOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('context') && typeof options.context === 'object') {
fetchOptions.context = options.context;
}
if (options.hasOwnProperty('include')) {
fetchOptions.include = [];
if ((0, _isArray.default)(options.include)) {
var _context;
(0, _forEach.default)(_context = options.include).call(_context, key => {
if ((0, _isArray.default)(key)) {
var _context2;
fetchOptions.include = (0, _concat.default)(_context2 = fetchOptions.include).call(_context2, key);
} else {
fetchOptions.include.push(key);
}
});
} else {
fetchOptions.include.push(options.include);
}
}
const controller = _CoreManager.default.getObjectController();
return controller.fetch(this, true, fetchOptions);
}
/**
* Fetch the model from the server. If the server's representation of the
* model differs from its current attributes, they will be overriden.
*
* Includes nested Parse.Objects for the provided key. You can use dot
* notation to specify which fields in the included object are also fetched.
*
* @param {string | Array>} keys The name(s) of the key(s) to include.
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
* @returns {Promise} A promise that is fulfilled when the fetch
* completes.
*/
fetchWithInclude(keys, options) {
options = options || {};
options.include = keys;
return this.fetch(options);
}
/**
* Saves this object to the server at some unspecified time in the future,
* even if Parse is currently inaccessible.
*
* Use this when you may not have a solid network connection, and don't need to know when the save completes.
* If there is some problem with the object such that it can't be saved, it will be silently discarded.
*
* Objects saved with this method will be stored locally in an on-disk cache until they can be delivered to Parse.
* They will be sent immediately if possible. Otherwise, they will be sent the next time a network connection is
* available. Objects saved this way will persist even after the app is closed, in which case they will be sent the
* next time the app is opened.
*
* @param {object} [options]
* Used to pass option parameters to method if arg1 and arg2 were both passed as strings.
* Valid options are:
*
* - sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- cascadeSave: If `false`, nested objects will not be saved (default is `true`).
*
- context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers.
*
* @returns {Promise} A promise that is fulfilled when the save
* completes.
*/
async saveEventually(options) {
try {
await this.save(null, options);
} catch (e) {
if (e.code === _ParseError.default.CONNECTION_FAILED) {
await _CoreManager.default.getEventuallyQueue().save(this, options);
_CoreManager.default.getEventuallyQueue().poll();
}
}
return this;
}
/**
* Set a hash of model attributes, and save the model to the server.
* updatedAt will be updated when the request returns.
* You can either call it as:
* object.save();
* or
* object.save(attrs);
* or
* object.save(null, options);
* or
* object.save(attrs, options);
* or
* object.save(key, value);
* or
* object.save(key, value, options);
*
* Example 1:
* gameTurn.save({
* player: "Jake Cutter",
* diceRoll: 2
* }).then(function(gameTurnAgain) {
* // The save was successful.
* }, function(error) {
* // The save failed. Error is an instance of Parse.Error.
* });
*
* Example 2:
* gameTurn.save("player", "Jake Cutter");
*
* @param {string | object | null} [arg1]
* Valid options are:
* - `Object` - Key/value pairs to update on the object.
* - `String` Key - Key of attribute to update (requires arg2 to also be string)
* - `null` - Passing null for arg1 allows you to save the object with options passed in arg2.
*
* @param {string | object} [arg2]
*
* - `String` Value - If arg1 was passed as a key, arg2 is the value that should be set on that key.
* - `Object` Options - Valid options are:
*
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- cascadeSave: If `false`, nested objects will not be saved (default is `true`).
*
- context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers.
*
*
*
* @param {object} [arg3]
* Used to pass option parameters to method if arg1 and arg2 were both passed as strings.
* Valid options are:
*
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- cascadeSave: If `false`, nested objects will not be saved (default is `true`).
*
- context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers.
*
* @returns {Promise} A promise that is fulfilled when the save
* completes.
*/
save(arg1, arg2, arg3) {
let attrs;
let options;
if (typeof arg1 === 'object' || typeof arg1 === 'undefined') {
attrs = arg1;
if (typeof arg2 === 'object') {
options = arg2;
}
} else {
attrs = {};
attrs[arg1] = arg2;
options = arg3;
}
options = options || {};
if (attrs) {
let validationError;
options.error = (_, validation) => {
validationError = validation;
};
const success = this.set(attrs, options);
if (!success) {
return _promise.default.reject(validationError);
}
}
const saveOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
saveOptions.useMasterKey = !!options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken') && typeof options.sessionToken === 'string') {
saveOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('installationId') && typeof options.installationId === 'string') {
saveOptions.installationId = options.installationId;
}
if (options.hasOwnProperty('context') && typeof options.context === 'object') {
saveOptions.context = options.context;
}
const controller = _CoreManager.default.getObjectController();
const unsaved = options.cascadeSave !== false ? (0, _unsavedChildren.default)(this) : null;
return controller.save(unsaved, saveOptions).then(() => {
return controller.save(this, saveOptions);
});
}
/**
* Deletes this object from the server at some unspecified time in the future,
* even if Parse is currently inaccessible.
*
* Use this when you may not have a solid network connection,
* and don't need to know when the delete completes. If there is some problem with the object
* such that it can't be deleted, the request will be silently discarded.
*
* Delete instructions made with this method will be stored locally in an on-disk cache until they can be transmitted
* to Parse. They will be sent immediately if possible. Otherwise, they will be sent the next time a network connection
* is available. Delete requests will persist even after the app is closed, in which case they will be sent the
* next time the app is opened.
*
* @param {object} [options]
* Valid options are:
* - sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers.
*
* @returns {Promise} A promise that is fulfilled when the destroy
* completes.
*/
async destroyEventually(options) {
try {
await this.destroy(options);
} catch (e) {
if (e.code === _ParseError.default.CONNECTION_FAILED) {
await _CoreManager.default.getEventuallyQueue().destroy(this, options);
_CoreManager.default.getEventuallyQueue().poll();
}
}
return this;
}
/**
* Destroy this model on the server if it was already persisted.
*
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers.
*
* @returns {Promise} A promise that is fulfilled when the destroy
* completes.
*/
destroy(options) {
options = options || {};
const destroyOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
destroyOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
destroyOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('context') && typeof options.context === 'object') {
destroyOptions.context = options.context;
}
if (!this.id) {
return _promise.default.resolve();
}
return _CoreManager.default.getObjectController().destroy(this, destroyOptions);
}
/**
* Asynchronously stores the object and every object it points to in the local datastore,
* recursively, using a default pin name: _default.
*
* If those other objects have not been fetched from Parse, they will not be stored.
* However, if they have changed data, all the changes will be retained.
*
*
* await object.pin();
*
*
* To retrieve object:
* query.fromLocalDatastore()
or query.fromPin()
*
* @returns {Promise} A promise that is fulfilled when the pin completes.
*/
pin() {
return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
}
/**
* Asynchronously removes the object and every object it points to in the local datastore,
* recursively, using a default pin name: _default.
*
*
* await object.unPin();
*
*
* @returns {Promise} A promise that is fulfilled when the unPin completes.
*/
unPin() {
return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
}
/**
* Asynchronously returns if the object is pinned
*
*
* const isPinned = await object.isPinned();
*
*
* @returns {Promise} A boolean promise that is fulfilled if object is pinned.
*/
async isPinned() {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
}
const objectKey = localDatastore.getKeyForObject(this);
const pin = await localDatastore.fromPinWithName(objectKey);
return pin.length > 0;
}
/**
* Asynchronously stores the objects and every object they point to in the local datastore, recursively.
*
* If those other objects have not been fetched from Parse, they will not be stored.
* However, if they have changed data, all the changes will be retained.
*
*
* await object.pinWithName(name);
*
*
* To retrieve object:
* query.fromLocalDatastore()
or query.fromPinWithName(name)
*
* @param {string} name Name of Pin.
* @returns {Promise} A promise that is fulfilled when the pin completes.
*/
pinWithName(name) {
return ParseObject.pinAllWithName(name, [this]);
}
/**
* Asynchronously removes the object and every object it points to in the local datastore, recursively.
*
*
* await object.unPinWithName(name);
*
*
* @param {string} name Name of Pin.
* @returns {Promise} A promise that is fulfilled when the unPin completes.
*/
unPinWithName(name) {
return ParseObject.unPinAllWithName(name, [this]);
}
/**
* Asynchronously loads data from the local datastore into this object.
*
*
* await object.fetchFromLocalDatastore();
*
*
* You can create an unfetched pointer with Parse.Object.createWithoutData()
* and then call fetchFromLocalDatastore()
on it.
*
* @returns {Promise} A promise that is fulfilled when the fetch completes.
*/
async fetchFromLocalDatastore() {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
throw new Error('Parse.enableLocalDatastore() must be called first');
}
const objectKey = localDatastore.getKeyForObject(this);
const pinned = await localDatastore._serializeObject(objectKey);
if (!pinned) {
throw new Error('Cannot fetch an unsaved ParseObject');
}
const result = ParseObject.fromJSON(pinned);
this._finishFetch(result.toJSON());
return this;
}
/* Static methods */
static _clearAllState() {
const stateController = _CoreManager.default.getObjectStateController();
stateController.clearAllState();
}
/**
* Fetches the given list of Parse.Object.
* If any error is encountered, stops and calls the error handler.
*
*
* Parse.Object.fetchAll([object1, object2, ...])
* .then((list) => {
* // All the objects were fetched.
* }, (error) => {
* // An error occurred while fetching one of the objects.
* });
*
*
* @param {Array} list A list of Parse.Object
.
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- include: The name(s) of the key(s) to include. Can be a string, an array of strings,
* or an array of array of strings.
*
* @static
* @returns {Parse.Object[]}
*/
static fetchAll(list) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const queryOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
queryOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
queryOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('include')) {
queryOptions.include = ParseObject.handleIncludeOptions(options);
}
return _CoreManager.default.getObjectController().fetch(list, true, queryOptions);
}
/**
* Fetches the given list of Parse.Object.
*
* Includes nested Parse.Objects for the provided key. You can use dot
* notation to specify which fields in the included object are also fetched.
*
* If any error is encountered, stops and calls the error handler.
*
*
* Parse.Object.fetchAllWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
* .then((list) => {
* // All the objects were fetched.
* }, (error) => {
* // An error occurred while fetching one of the objects.
* });
*
*
* @param {Array} list A list of Parse.Object
.
* @param {string | Array>} keys The name(s) of the key(s) to include.
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
* @static
* @returns {Parse.Object[]}
*/
static fetchAllWithInclude(list, keys, options) {
options = options || {};
options.include = keys;
return ParseObject.fetchAll(list, options);
}
/**
* Fetches the given list of Parse.Object if needed.
* If any error is encountered, stops and calls the error handler.
*
* Includes nested Parse.Objects for the provided key. You can use dot
* notation to specify which fields in the included object are also fetched.
*
* If any error is encountered, stops and calls the error handler.
*
*
* Parse.Object.fetchAllIfNeededWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
* .then((list) => {
* // All the objects were fetched.
* }, (error) => {
* // An error occurred while fetching one of the objects.
* });
*
*
* @param {Array} list A list of Parse.Object
.
* @param {string | Array>} keys The name(s) of the key(s) to include.
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
* @static
* @returns {Parse.Object[]}
*/
static fetchAllIfNeededWithInclude(list, keys, options) {
options = options || {};
options.include = keys;
return ParseObject.fetchAllIfNeeded(list, options);
}
/**
* Fetches the given list of Parse.Object if needed.
* If any error is encountered, stops and calls the error handler.
*
*
* Parse.Object.fetchAllIfNeeded([object1, ...])
* .then((list) => {
* // Objects were fetched and updated.
* }, (error) => {
* // An error occurred while fetching one of the objects.
* });
*
*
* @param {Array} list A list of Parse.Object
.
* @param {object} options
* @static
* @returns {Parse.Object[]}
*/
static fetchAllIfNeeded(list, options) {
options = options || {};
const queryOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
queryOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
queryOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('include')) {
queryOptions.include = ParseObject.handleIncludeOptions(options);
}
return _CoreManager.default.getObjectController().fetch(list, false, queryOptions);
}
static handleIncludeOptions(options) {
let include = [];
if ((0, _isArray.default)(options.include)) {
var _context3;
(0, _forEach.default)(_context3 = options.include).call(_context3, key => {
if ((0, _isArray.default)(key)) {
include = (0, _concat.default)(include).call(include, key);
} else {
include.push(key);
}
});
} else {
include.push(options.include);
}
return include;
}
/**
* Destroy the given list of models on the server if it was already persisted.
*
* Unlike saveAll, if an error occurs while deleting an individual model,
* this method will continue trying to delete the rest of the models if
* possible, except in the case of a fatal error like a connection error.
*
*
In particular, the Parse.Error object returned in the case of error may
* be one of two types:
*
*
* - A Parse.Error.AGGREGATE_ERROR. This object's "errors" property is an
* array of other Parse.Error objects. Each error object in this array
* has an "object" property that references the object that could not be
* deleted (for instance, because that object could not be found).
* - A non-aggregate Parse.Error. This indicates a serious error that
* caused the delete operation to be aborted partway through (for
* instance, a connection failure in the middle of the delete).
*
*
*
* Parse.Object.destroyAll([object1, object2, ...])
* .then((list) => {
* // All the objects were deleted.
* }, (error) => {
* // An error occurred while deleting one or more of the objects.
* // If this is an aggregate error, then we can inspect each error
* // object individually to determine the reason why a particular
* // object was not deleted.
* if (error.code === Parse.Error.AGGREGATE_ERROR) {
* for (var i = 0; i < error.errors.length; i++) {
* console.log("Couldn't delete " + error.errors[i].object.id +
* "due to " + error.errors[i].message);
* }
* } else {
* console.log("Delete aborted because of " + error.message);
* }
* });
*
*
* @param {Array} list A list of Parse.Object
.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled when the destroyAll
* completes.
*/
static destroyAll(list) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const destroyOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
destroyOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
destroyOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
destroyOptions.batchSize = options.batchSize;
}
if (options.hasOwnProperty('context') && typeof options.context === 'object') {
destroyOptions.context = options.context;
}
return _CoreManager.default.getObjectController().destroy(list, destroyOptions);
}
/**
* Saves the given list of Parse.Object.
* If any error is encountered, stops and calls the error handler.
*
*
* Parse.Object.saveAll([object1, object2, ...])
* .then((list) => {
* // All the objects were saved.
* }, (error) => {
* // An error occurred while saving one of the objects.
* });
*
*
* @param {Array} list A list of Parse.Object
.
* @param {object} options
* @static
* @returns {Parse.Object[]}
*/
static saveAll(list) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const saveOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
saveOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
saveOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
saveOptions.batchSize = options.batchSize;
}
if (options.hasOwnProperty('context') && typeof options.context === 'object') {
saveOptions.context = options.context;
}
return _CoreManager.default.getObjectController().save(list, saveOptions);
}
/**
* Creates a reference to a subclass of Parse.Object with the given id. This
* does not exist on Parse.Object, only on subclasses.
*
* A shortcut for:
* var Foo = Parse.Object.extend("Foo");
* var pointerToFoo = new Foo();
* pointerToFoo.id = "myObjectId";
*
*
* @param {string} id The ID of the object to create a reference to.
* @static
* @returns {Parse.Object} A Parse.Object reference.
*/
static createWithoutData(id) {
const obj = new this();
obj.id = id;
return obj;
}
/**
* Creates a new instance of a Parse Object from a JSON representation.
*
* @param {object} json The JSON map of the Object's data
* @param {boolean} override In single instance mode, all old server data
* is overwritten if this is set to true
* @param {boolean} dirty Whether the Parse.Object should set JSON keys to dirty
* @static
* @returns {Parse.Object} A Parse.Object reference
*/
static fromJSON(json, override, dirty) {
if (!json.className) {
throw new Error('Cannot create an object without a className');
}
const constructor = classMap[json.className];
const o = constructor ? new constructor(json.className) : new ParseObject(json.className);
const otherAttributes = {};
for (const attr in json) {
if (attr !== 'className' && attr !== '__type') {
otherAttributes[attr] = json[attr];
if (dirty) {
o.set(attr, json[attr]);
}
}
}
if (override) {
// id needs to be set before clearServerData can work
if (otherAttributes.objectId) {
o.id = otherAttributes.objectId;
}
let preserved = null;
if (typeof o._preserveFieldsOnFetch === 'function') {
preserved = o._preserveFieldsOnFetch();
}
o._clearServerData();
if (preserved) {
o._finishFetch(preserved);
}
}
o._finishFetch(otherAttributes);
if (json.objectId) {
o._setExisted(true);
}
return o;
}
/**
* Registers a subclass of Parse.Object with a specific class name.
* When objects of that class are retrieved from a query, they will be
* instantiated with this subclass.
* This is only necessary when using ES6 subclassing.
*
* @param {string} className The class name of the subclass
* @param {Function} constructor The subclass
*/
static registerSubclass(className, constructor) {
if (typeof className !== 'string') {
throw new TypeError('The first argument must be a valid class name.');
}
if (typeof constructor === 'undefined') {
throw new TypeError('You must supply a subclass constructor.');
}
if (typeof constructor !== 'function') {
throw new TypeError('You must register the subclass constructor. ' + 'Did you attempt to register an instance of the subclass?');
}
classMap[className] = constructor;
if (!constructor.className) {
constructor.className = className;
}
}
/**
* Unegisters a subclass of Parse.Object with a specific class name.
*
* @param {string} className The class name of the subclass
*/
static unregisterSubclass(className) {
if (typeof className !== 'string') {
throw new TypeError('The first argument must be a valid class name.');
}
delete classMap[className];
}
/**
* Creates a new subclass of Parse.Object for the given Parse class name.
*
* Every extension of a Parse class will inherit from the most recent
* previous extension of that class. When a Parse.Object is automatically
* created by parsing JSON, it will use the most recent extension of that
* class.
*
* You should call either:
* var MyClass = Parse.Object.extend("MyClass", {
* Instance methods,
* initialize: function(attrs, options) {
* this.someInstanceProperty = [],
* Other instance properties
* }
* }, {
* Class properties
* });
* or, for Backbone compatibility:
* var MyClass = Parse.Object.extend({
* className: "MyClass",
* Instance methods,
* initialize: function(attrs, options) {
* this.someInstanceProperty = [],
* Other instance properties
* }
* }, {
* Class properties
* });
*
* @param {string} className The name of the Parse class backing this model.
* @param {object} [protoProps] Instance properties to add to instances of the
* class returned from this method.
* @param {object} [classProps] Class properties to add the class returned from
* this method.
* @returns {Parse.Object} A new subclass of Parse.Object.
*/
static extend(className, protoProps, classProps) {
if (typeof className !== 'string') {
if (className && typeof className.className === 'string') {
return ParseObject.extend(className.className, className, protoProps);
} else {
throw new Error("Parse.Object.extend's first argument should be the className.");
}
}
let adjustedClassName = className;
if (adjustedClassName === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
adjustedClassName = '_User';
}
let parentProto = ParseObject.prototype;
if (this.hasOwnProperty('__super__') && this.__super__) {
parentProto = this.prototype;
}
let ParseObjectSubclass = function (attributes, options) {
this.className = adjustedClassName;
this._objCount = objectCount++;
// Enable legacy initializers
if (typeof this.initialize === 'function') {
this.initialize.apply(this, arguments);
}
if (this._initializers) {
for (const initializer of this._initializers) {
initializer.apply(this, arguments);
}
}
if (attributes && typeof attributes === 'object') {
if (!this.set(attributes || {}, options)) {
throw new Error("Can't create an invalid Parse Object");
}
}
};
if (classMap[adjustedClassName]) {
ParseObjectSubclass = classMap[adjustedClassName];
} else {
ParseObjectSubclass.extend = function (name, protoProps, classProps) {
if (typeof name === 'string') {
return ParseObject.extend.call(ParseObjectSubclass, name, protoProps, classProps);
}
return ParseObject.extend.call(ParseObjectSubclass, adjustedClassName, name, protoProps);
};
ParseObjectSubclass.createWithoutData = ParseObject.createWithoutData;
ParseObjectSubclass.className = adjustedClassName;
ParseObjectSubclass.__super__ = parentProto;
ParseObjectSubclass.prototype = (0, _create.default)(parentProto, {
constructor: {
value: ParseObjectSubclass,
enumerable: false,
writable: true,
configurable: true
}
});
}
if (protoProps) {
for (const prop in protoProps) {
if (prop === 'initialize') {
(0, _defineProperty3.default)(ParseObjectSubclass.prototype, '_initializers', {
value: [...(ParseObjectSubclass.prototype._initializers || []), protoProps[prop]],
enumerable: false,
writable: true,
configurable: true
});
continue;
}
if (prop !== 'className') {
(0, _defineProperty3.default)(ParseObjectSubclass.prototype, prop, {
value: protoProps[prop],
enumerable: false,
writable: true,
configurable: true
});
}
}
}
if (classProps) {
for (const prop in classProps) {
if (prop !== 'className') {
(0, _defineProperty3.default)(ParseObjectSubclass, prop, {
value: classProps[prop],
enumerable: false,
writable: true,
configurable: true
});
}
}
}
classMap[adjustedClassName] = ParseObjectSubclass;
return ParseObjectSubclass;
}
/**
* Enable single instance objects, where any local objects with the same Id
* share the same attributes, and stay synchronized with each other.
* This is disabled by default in server environments, since it can lead to
* security issues.
*
* @static
*/
static enableSingleInstance() {
singleInstance = true;
_CoreManager.default.setObjectStateController(SingleInstanceStateController);
}
/**
* Disable single instance objects, where any local objects with the same Id
* share the same attributes, and stay synchronized with each other.
* When disabled, you can have two instances of the same object in memory
* without them sharing attributes.
*
* @static
*/
static disableSingleInstance() {
singleInstance = false;
_CoreManager.default.setObjectStateController(UniqueInstanceStateController);
}
/**
* Asynchronously stores the objects and every object they point to in the local datastore,
* recursively, using a default pin name: _default.
*
* If those other objects have not been fetched from Parse, they will not be stored.
* However, if they have changed data, all the changes will be retained.
*
*
* await Parse.Object.pinAll([...]);
*
*
* To retrieve object:
* query.fromLocalDatastore()
or query.fromPin()
*
* @param {Array} objects A list of Parse.Object
.
* @returns {Promise} A promise that is fulfilled when the pin completes.
* @static
*/
static pinAll(objects) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
}
return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
}
/**
* Asynchronously stores the objects and every object they point to in the local datastore, recursively.
*
* If those other objects have not been fetched from Parse, they will not be stored.
* However, if they have changed data, all the changes will be retained.
*
*
* await Parse.Object.pinAllWithName(name, [obj1, obj2, ...]);
*
*
* To retrieve object:
* query.fromLocalDatastore()
or query.fromPinWithName(name)
*
* @param {string} name Name of Pin.
* @param {Array} objects A list of Parse.Object
.
* @returns {Promise} A promise that is fulfilled when the pin completes.
* @static
*/
static pinAllWithName(name, objects) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
}
return localDatastore._handlePinAllWithName(name, objects);
}
/**
* Asynchronously removes the objects and every object they point to in the local datastore,
* recursively, using a default pin name: _default.
*
*
* await Parse.Object.unPinAll([...]);
*
*
* @param {Array} objects A list of Parse.Object
.
* @returns {Promise} A promise that is fulfilled when the unPin completes.
* @static
*/
static unPinAll(objects) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
}
return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
}
/**
* Asynchronously removes the objects and every object they point to in the local datastore, recursively.
*
*
* await Parse.Object.unPinAllWithName(name, [obj1, obj2, ...]);
*
*
* @param {string} name Name of Pin.
* @param {Array} objects A list of Parse.Object
.
* @returns {Promise} A promise that is fulfilled when the unPin completes.
* @static
*/
static unPinAllWithName(name, objects) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
}
return localDatastore._handleUnPinAllWithName(name, objects);
}
/**
* Asynchronously removes all objects in the local datastore using a default pin name: _default.
*
*
* await Parse.Object.unPinAllObjects();
*
*
* @returns {Promise} A promise that is fulfilled when the unPin completes.
* @static
*/
static unPinAllObjects() {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
}
return localDatastore.unPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
}
/**
* Asynchronously removes all objects with the specified pin name.
* Deletes the pin name also.
*
*
* await Parse.Object.unPinAllObjectsWithName(name);
*
*
* @param {string} name Name of Pin.
* @returns {Promise} A promise that is fulfilled when the unPin completes.
* @static
*/
static unPinAllObjectsWithName(name) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return _promise.default.reject('Parse.enableLocalDatastore() must be called first');
}
return localDatastore.unPinWithName(_LocalDatastoreUtils.PIN_PREFIX + name);
}
}
const DefaultController = {
fetch(target, forceFetch, options) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if ((0, _isArray.default)(target)) {
if (target.length < 1) {
return _promise.default.resolve([]);
}
const objs = [];
const ids = [];
let className = null;
const results = [];
let error = null;
(0, _forEach.default)(target).call(target, el => {
if (error) {
return;
}
if (!className) {
className = el.className;
}
if (className !== el.className) {
error = new _ParseError.default(_ParseError.default.INVALID_CLASS_NAME, 'All objects should be of the same class');
}
if (!el.id) {
error = new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'All objects must have an ID');
}
if (forceFetch || !el.isDataAvailable()) {
ids.push(el.id);
objs.push(el);
}
results.push(el);
});
if (error) {
return _promise.default.reject(error);
}
const ParseQuery = _CoreManager.default.getParseQuery();
const query = new ParseQuery(className);
query.containedIn('objectId', ids);
if (options && options.include) {
query.include(options.include);
}
query._limit = ids.length;
return (0, _find.default)(query).call(query, options).then(async objects => {
const idMap = {};
(0, _forEach.default)(objects).call(objects, o => {
idMap[o.id] = o;
});
for (let i = 0; i < objs.length; i++) {
const obj = objs[i];
if (!obj || !obj.id || !idMap[obj.id]) {
if (forceFetch) {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'All objects must exist on the server.'));
}
}
}
if (!singleInstance) {
// If single instance objects are disabled, we need to replace the
for (let i = 0; i < results.length; i++) {
const obj = results[i];
if (obj && obj.id && idMap[obj.id]) {
const id = obj.id;
obj._finishFetch(idMap[id].toJSON());
results[i] = idMap[id];
}
}
}
for (const object of results) {
await localDatastore._updateObjectIfPinned(object);
}
return _promise.default.resolve(results);
});
} else if (target instanceof ParseObject) {
if (!target.id) {
return _promise.default.reject(new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'Object does not have an ID'));
}
const RESTController = _CoreManager.default.getRESTController();
const params = {};
if (options && options.include) {
params.include = options.include.join();
}
return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), params, options).then(async response => {
target._clearPendingOps();
target._clearServerData();
target._finishFetch(response);
await localDatastore._updateObjectIfPinned(target);
return target;
});
}
return _promise.default.resolve(undefined);
},
async destroy(target, options) {
const batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
const localDatastore = _CoreManager.default.getLocalDatastore();
const RESTController = _CoreManager.default.getRESTController();
if ((0, _isArray.default)(target)) {
if (target.length < 1) {
return _promise.default.resolve([]);
}
const batches = [[]];
(0, _forEach.default)(target).call(target, obj => {
if (!obj.id) {
return;
}
batches[batches.length - 1].push(obj);
if (batches[batches.length - 1].length >= batchSize) {
batches.push([]);
}
});
if (batches[batches.length - 1].length === 0) {
// If the last batch is empty, remove it
batches.pop();
}
let deleteCompleted = _promise.default.resolve();
const errors = [];
(0, _forEach.default)(batches).call(batches, batch => {
deleteCompleted = deleteCompleted.then(() => {
return RESTController.request('POST', 'batch', {
requests: (0, _map.default)(batch).call(batch, obj => {
return {
method: 'DELETE',
path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(),
body: {}
};
})
}, options).then(results => {
for (let i = 0; i < results.length; i++) {
if (results[i] && results[i].hasOwnProperty('error')) {
const err = new _ParseError.default(results[i].error.code, results[i].error.error);
err.object = batch[i];
errors.push(err);
}
}
});
});
});
return deleteCompleted.then(async () => {
if (errors.length) {
const aggregate = new _ParseError.default(_ParseError.default.AGGREGATE_ERROR);
aggregate.errors = errors;
return _promise.default.reject(aggregate);
}
for (const object of target) {
await localDatastore._destroyObjectIfPinned(object);
}
return _promise.default.resolve(target);
});
} else if (target instanceof ParseObject) {
return RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then(async () => {
await localDatastore._destroyObjectIfPinned(target);
return _promise.default.resolve(target);
});
}
return _promise.default.resolve(target);
},
save(target, options) {
const batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
const localDatastore = _CoreManager.default.getLocalDatastore();
const mapIdForPin = {};
const RESTController = _CoreManager.default.getRESTController();
const stateController = _CoreManager.default.getObjectStateController();
const allowCustomObjectId = _CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID');
options = options || {};
options.returnStatus = options.returnStatus || true;
if ((0, _isArray.default)(target)) {
if (target.length < 1) {
return _promise.default.resolve([]);
}
let unsaved = (0, _concat.default)(target).call(target);
for (let i = 0; i < target.length; i++) {
const target_i = target[i];
if (target_i instanceof ParseObject) {
unsaved = (0, _concat.default)(unsaved).call(unsaved, (0, _unsavedChildren.default)(target_i, true));
}
}
unsaved = (0, _unique.default)(unsaved);
const filesSaved = [];
let pending = [];
(0, _forEach.default)(unsaved).call(unsaved, el => {
if (el instanceof _ParseFile.default) {
filesSaved.push(el.save(options));
} else if (el instanceof ParseObject) {
pending.push(el);
}
});
return _promise.default.all(filesSaved).then(() => {
let objectError = null;
return (0, _promiseUtils.continueWhile)(() => {
return pending.length > 0;
}, () => {
const batch = [];
const nextPending = [];
(0, _forEach.default)(pending).call(pending, el => {
if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(el, 'id') && !el.id) {
throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null');
}
if (batch.length < batchSize && (0, _canBeSerialized.default)(el)) {
batch.push(el);
} else {
nextPending.push(el);
}
});
pending = nextPending;
if (batch.length < 1) {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Tried to save a batch with a cycle.'));
}
// Queue up tasks for each object in the batch.
// When every task is ready, the API request will execute
const batchReturned = (0, _promiseUtils.resolvingPromise)();
const batchReady = [];
const batchTasks = [];
(0, _forEach.default)(batch).call(batch, (obj, index) => {
const ready = (0, _promiseUtils.resolvingPromise)();
batchReady.push(ready);
stateController.pushPendingState(obj._getStateIdentifier());
batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), function () {
ready.resolve();
return batchReturned.then(responses => {
if (responses[index].hasOwnProperty('success')) {
const objectId = responses[index].success.objectId;
const status = responses[index]._status;
delete responses[index]._status;
delete responses[index]._headers;
delete responses[index]._xhr;
mapIdForPin[objectId] = obj._localId;
obj._handleSaveResponse(responses[index].success, status);
} else {
if (!objectError && responses[index].hasOwnProperty('error')) {
const serverError = responses[index].error;
objectError = new _ParseError.default(serverError.code, serverError.error);
// Cancel the rest of the save
pending = [];
}
obj._handleSaveError();
}
});
}));
});
(0, _promiseUtils.when)(batchReady).then(() => {
// Kick off the batch request
return RESTController.request('POST', 'batch', {
requests: (0, _map.default)(batch).call(batch, obj => {
const params = obj._getSaveParams();
params.path = getServerUrlPath() + params.path;
return params;
})
}, options);
}).then(batchReturned.resolve, error => {
batchReturned.reject(new _ParseError.default(_ParseError.default.INCORRECT_TYPE, error.message));
});
return (0, _promiseUtils.when)(batchTasks);
}).then(async () => {
if (objectError) {
return _promise.default.reject(objectError);
}
for (const object of target) {
// Make sure that it is a ParseObject before updating it into the localDataStore
if (object instanceof ParseObject) {
await localDatastore._updateLocalIdForObject(mapIdForPin[object.id], object);
await localDatastore._updateObjectIfPinned(object);
}
}
return _promise.default.resolve(target);
});
});
} else if (target instanceof ParseObject) {
if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(target, 'id') && !target.id) {
throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null');
}
// generate _localId in case if cascadeSave=false
target._getId();
const localId = target._localId;
// copying target lets guarantee the pointer isn't modified elsewhere
const targetCopy = target;
const task = function () {
const params = targetCopy._getSaveParams();
return RESTController.request(params.method, params.path, params.body, options).then(response => {
const status = response._status;
delete response._status;
delete response._headers;
delete response._xhr;
targetCopy._handleSaveResponse(response, status);
}, error => {
targetCopy._handleSaveError();
return _promise.default.reject(error);
});
};
stateController.pushPendingState(target._getStateIdentifier());
return stateController.enqueueTask(target._getStateIdentifier(), task).then(async () => {
await localDatastore._updateLocalIdForObject(localId, target);
await localDatastore._updateObjectIfPinned(target);
return target;
}, error => {
return _promise.default.reject(error);
});
}
return _promise.default.resolve(undefined);
}
};
_CoreManager.default.setParseObject(ParseObject);
_CoreManager.default.setObjectController(DefaultController);
var _default = exports.default = ParseObject;
},{"./CoreManager":4,"./LocalDatastoreUtils":17,"./ParseACL":21,"./ParseError":24,"./ParseFile":25,"./ParseOp":31,"./ParseRelation":34,"./SingleInstanceStateController":41,"./UniqueInstanceStateController":50,"./canBeSerialized":54,"./decode":55,"./encode":56,"./escape":58,"./parseDate":60,"./promiseUtils":61,"./unique":62,"./unsavedChildren":63,"./uuid":64,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/concat":68,"@babel/runtime-corejs3/core-js-stable/instance/find":73,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/instance/includes":75,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/instance/map":78,"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/create":89,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/freeze":92,"@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor":93,"@babel/runtime-corejs3/core-js-stable/object/get-prototype-of":94,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/core-js-stable/weak-map":101,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],31:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.UnsetOp = exports.SetOp = exports.RemoveOp = exports.RelationOp = exports.Op = exports.IncrementOp = exports.AddUniqueOp = exports.AddOp = void 0;
exports.opFromJSON = opFromJSON;
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _concat = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _splice = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/splice"));
var _map = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _arrayContainsObject = _interopRequireDefault(_dereq_("./arrayContainsObject"));
var _decode = _interopRequireDefault(_dereq_("./decode"));
var _encode = _interopRequireDefault(_dereq_("./encode"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
var _unique = _interopRequireDefault(_dereq_("./unique"));
function opFromJSON(json) {
if (!json || !json.__op) {
return null;
}
switch (json.__op) {
case 'Delete':
return new UnsetOp();
case 'Increment':
return new IncrementOp(json.amount);
case 'Add':
return new AddOp((0, _decode.default)(json.objects));
case 'AddUnique':
return new AddUniqueOp((0, _decode.default)(json.objects));
case 'Remove':
return new RemoveOp((0, _decode.default)(json.objects));
case 'AddRelation':
{
const toAdd = (0, _decode.default)(json.objects);
if (!(0, _isArray.default)(toAdd)) {
return new RelationOp([], []);
}
return new RelationOp(toAdd, []);
}
case 'RemoveRelation':
{
const toRemove = (0, _decode.default)(json.objects);
if (!(0, _isArray.default)(toRemove)) {
return new RelationOp([], []);
}
return new RelationOp([], toRemove);
}
case 'Batch':
{
let toAdd = [];
let toRemove = [];
for (let i = 0; i < json.ops.length; i++) {
if (json.ops[i].__op === 'AddRelation') {
toAdd = (0, _concat.default)(toAdd).call(toAdd, (0, _decode.default)(json.ops[i].objects));
} else if (json.ops[i].__op === 'RemoveRelation') {
toRemove = (0, _concat.default)(toRemove).call(toRemove, (0, _decode.default)(json.ops[i].objects));
}
}
return new RelationOp(toAdd, toRemove);
}
}
return null;
}
class Op {
// Empty parent class
applyTo() {} /* eslint-disable-line @typescript-eslint/no-unused-vars */
mergeWith() {} /* eslint-disable-line @typescript-eslint/no-unused-vars */
toJSON() {} /* eslint-disable-line @typescript-eslint/no-unused-vars */
}
exports.Op = Op;
class SetOp extends Op {
constructor(value) {
super();
(0, _defineProperty2.default)(this, "_value", void 0);
this._value = value;
}
applyTo() {
return this._value;
}
mergeWith() {
return new SetOp(this._value);
}
toJSON(offline) {
return (0, _encode.default)(this._value, false, true, undefined, offline);
}
}
exports.SetOp = SetOp;
class UnsetOp extends Op {
applyTo() {
return undefined;
}
mergeWith() {
return new UnsetOp();
}
toJSON() {
return {
__op: 'Delete'
};
}
}
exports.UnsetOp = UnsetOp;
class IncrementOp extends Op {
constructor(amount) {
super();
(0, _defineProperty2.default)(this, "_amount", void 0);
if (typeof amount !== 'number') {
throw new TypeError('Increment Op must be initialized with a numeric amount.');
}
this._amount = amount;
}
applyTo(value) {
if (typeof value === 'undefined') {
return this._amount;
}
if (typeof value !== 'number') {
throw new TypeError('Cannot increment a non-numeric value.');
}
return this._amount + value;
}
mergeWith(previous) {
if (!previous) {
return this;
}
if (previous instanceof SetOp) {
return new SetOp(this.applyTo(previous._value));
}
if (previous instanceof UnsetOp) {
return new SetOp(this._amount);
}
if (previous instanceof IncrementOp) {
return new IncrementOp(this.applyTo(previous._amount));
}
throw new Error('Cannot merge Increment Op with the previous Op');
}
toJSON() {
return {
__op: 'Increment',
amount: this._amount
};
}
}
exports.IncrementOp = IncrementOp;
class AddOp extends Op {
constructor(value) {
super();
(0, _defineProperty2.default)(this, "_value", void 0);
this._value = (0, _isArray.default)(value) ? value : [value];
}
applyTo(value) {
if (value == null) {
return this._value;
}
if ((0, _isArray.default)(value)) {
return (0, _concat.default)(value).call(value, this._value);
}
throw new Error('Cannot add elements to a non-array value');
}
mergeWith(previous) {
if (!previous) {
return this;
}
if (previous instanceof SetOp) {
return new SetOp(this.applyTo(previous._value));
}
if (previous instanceof UnsetOp) {
return new SetOp(this._value);
}
if (previous instanceof AddOp) {
return new AddOp(this.applyTo(previous._value));
}
throw new Error('Cannot merge Add Op with the previous Op');
}
toJSON() {
return {
__op: 'Add',
objects: (0, _encode.default)(this._value, false, true)
};
}
}
exports.AddOp = AddOp;
class AddUniqueOp extends Op {
constructor(value) {
super();
(0, _defineProperty2.default)(this, "_value", void 0);
this._value = (0, _unique.default)((0, _isArray.default)(value) ? value : [value]);
}
applyTo(value) {
if (value == null) {
return this._value || [];
}
if ((0, _isArray.default)(value)) {
var _context;
const ParseObject = _CoreManager.default.getParseObject();
const toAdd = [];
(0, _forEach.default)(_context = this._value).call(_context, v => {
if (v instanceof ParseObject) {
if (!(0, _arrayContainsObject.default)(value, v)) {
toAdd.push(v);
}
} else {
if ((0, _indexOf.default)(value).call(value, v) < 0) {
toAdd.push(v);
}
}
});
return (0, _concat.default)(value).call(value, toAdd);
}
throw new Error('Cannot add elements to a non-array value');
}
mergeWith(previous) {
if (!previous) {
return this;
}
if (previous instanceof SetOp) {
return new SetOp(this.applyTo(previous._value));
}
if (previous instanceof UnsetOp) {
return new SetOp(this._value);
}
if (previous instanceof AddUniqueOp) {
return new AddUniqueOp(this.applyTo(previous._value));
}
throw new Error('Cannot merge AddUnique Op with the previous Op');
}
toJSON() {
return {
__op: 'AddUnique',
objects: (0, _encode.default)(this._value, false, true)
};
}
}
exports.AddUniqueOp = AddUniqueOp;
class RemoveOp extends Op {
constructor(value) {
super();
(0, _defineProperty2.default)(this, "_value", void 0);
this._value = (0, _unique.default)((0, _isArray.default)(value) ? value : [value]);
}
applyTo(value) {
if (value == null) {
return [];
}
if ((0, _isArray.default)(value)) {
const ParseObject = _CoreManager.default.getParseObject();
// var i = value.indexOf(this._value);
const removed = (0, _concat.default)(value).call(value, []);
for (let i = 0; i < this._value.length; i++) {
let index = (0, _indexOf.default)(removed).call(removed, this._value[i]);
while (index > -1) {
(0, _splice.default)(removed).call(removed, index, 1);
index = (0, _indexOf.default)(removed).call(removed, this._value[i]);
}
if (this._value[i] instanceof ParseObject && this._value[i].id) {
for (let j = 0; j < removed.length; j++) {
if (removed[j] instanceof ParseObject && this._value[i].id === removed[j].id) {
(0, _splice.default)(removed).call(removed, j, 1);
j--;
}
}
}
}
return removed;
}
throw new Error('Cannot remove elements from a non-array value');
}
mergeWith(previous) {
if (!previous) {
return this;
}
if (previous instanceof SetOp) {
return new SetOp(this.applyTo(previous._value));
}
if (previous instanceof UnsetOp) {
return new UnsetOp();
}
if (previous instanceof RemoveOp) {
var _context2;
const ParseObject = _CoreManager.default.getParseObject();
const uniques = (0, _concat.default)(_context2 = previous._value).call(_context2, []);
for (let i = 0; i < this._value.length; i++) {
if (this._value[i] instanceof ParseObject) {
if (!(0, _arrayContainsObject.default)(uniques, this._value[i])) {
uniques.push(this._value[i]);
}
} else {
if ((0, _indexOf.default)(uniques).call(uniques, this._value[i]) < 0) {
uniques.push(this._value[i]);
}
}
}
return new RemoveOp(uniques);
}
throw new Error('Cannot merge Remove Op with the previous Op');
}
toJSON() {
return {
__op: 'Remove',
objects: (0, _encode.default)(this._value, false, true)
};
}
}
exports.RemoveOp = RemoveOp;
class RelationOp extends Op {
constructor(adds, removes) {
super();
(0, _defineProperty2.default)(this, "_targetClassName", void 0);
(0, _defineProperty2.default)(this, "relationsToAdd", void 0);
(0, _defineProperty2.default)(this, "relationsToRemove", void 0);
this._targetClassName = null;
if ((0, _isArray.default)(adds)) {
this.relationsToAdd = (0, _unique.default)((0, _map.default)(adds).call(adds, this._extractId, this));
}
if ((0, _isArray.default)(removes)) {
this.relationsToRemove = (0, _unique.default)((0, _map.default)(removes).call(removes, this._extractId, this));
}
}
_extractId(obj) {
if (typeof obj === 'string') {
return obj;
}
if (!obj.id) {
throw new Error('You cannot add or remove an unsaved Parse Object from a relation');
}
if (!this._targetClassName) {
this._targetClassName = obj.className;
}
if (this._targetClassName !== obj.className) {
throw new Error('Tried to create a Relation with 2 different object types: ' + this._targetClassName + ' and ' + obj.className + '.');
}
return obj.id;
}
applyTo(value, parent, key) {
if (!value) {
if (!parent || !key) {
throw new Error('Cannot apply a RelationOp without either a previous value, or an object and a key');
}
const relation = new _ParseRelation.default(parent, key);
relation.targetClassName = this._targetClassName;
return relation;
}
if (value instanceof _ParseRelation.default) {
if (this._targetClassName) {
if (value.targetClassName) {
if (this._targetClassName !== value.targetClassName) {
throw new Error('Related object must be a ' + value.targetClassName + ', but a ' + this._targetClassName + ' was passed in.');
}
} else {
value.targetClassName = this._targetClassName;
}
}
return value;
} else {
throw new Error('Relation cannot be applied to a non-relation field');
}
}
mergeWith(previous) {
if (!previous) {
return this;
} else if (previous instanceof UnsetOp) {
throw new Error('You cannot modify a relation after deleting it.');
} else if (previous instanceof SetOp && previous._value instanceof _ParseRelation.default) {
return this;
} else if (previous instanceof RelationOp) {
var _context3, _context4, _context5, _context6, _context7, _context8;
if (previous._targetClassName && previous._targetClassName !== this._targetClassName) {
throw new Error('Related object must be of class ' + previous._targetClassName + ', but ' + (this._targetClassName || 'null') + ' was passed in.');
}
const newAdd = (0, _concat.default)(_context3 = previous.relationsToAdd).call(_context3, []);
(0, _forEach.default)(_context4 = this.relationsToRemove).call(_context4, r => {
const index = (0, _indexOf.default)(newAdd).call(newAdd, r);
if (index > -1) {
(0, _splice.default)(newAdd).call(newAdd, index, 1);
}
});
(0, _forEach.default)(_context5 = this.relationsToAdd).call(_context5, r => {
const index = (0, _indexOf.default)(newAdd).call(newAdd, r);
if (index < 0) {
newAdd.push(r);
}
});
const newRemove = (0, _concat.default)(_context6 = previous.relationsToRemove).call(_context6, []);
(0, _forEach.default)(_context7 = this.relationsToAdd).call(_context7, r => {
const index = (0, _indexOf.default)(newRemove).call(newRemove, r);
if (index > -1) {
(0, _splice.default)(newRemove).call(newRemove, index, 1);
}
});
(0, _forEach.default)(_context8 = this.relationsToRemove).call(_context8, r => {
const index = (0, _indexOf.default)(newRemove).call(newRemove, r);
if (index < 0) {
newRemove.push(r);
}
});
const newRelation = new RelationOp(newAdd, newRemove);
newRelation._targetClassName = this._targetClassName;
return newRelation;
}
throw new Error('Cannot merge Relation Op with the previous Op');
}
toJSON() {
const idToPointer = id => {
return {
__type: 'Pointer',
className: this._targetClassName,
objectId: id
};
};
let pointers = null;
let adds = null;
let removes = null;
if (this.relationsToAdd.length > 0) {
var _context9;
pointers = (0, _map.default)(_context9 = this.relationsToAdd).call(_context9, idToPointer);
adds = {
__op: 'AddRelation',
objects: pointers
};
}
if (this.relationsToRemove.length > 0) {
var _context10;
pointers = (0, _map.default)(_context10 = this.relationsToRemove).call(_context10, idToPointer);
removes = {
__op: 'RemoveRelation',
objects: pointers
};
}
if (adds && removes) {
return {
__op: 'Batch',
ops: [adds, removes]
};
}
return adds || removes || {};
}
}
exports.RelationOp = RelationOp;
_CoreManager.default.setParseOp({
Op,
opFromJSON,
SetOp,
UnsetOp,
IncrementOp,
AddOp,
RelationOp,
RemoveOp,
AddUniqueOp
});
},{"./CoreManager":4,"./ParseRelation":34,"./arrayContainsObject":53,"./decode":55,"./encode":56,"./unique":62,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/concat":68,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/instance/map":78,"@babel/runtime-corejs3/core-js-stable/instance/splice":82,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],32:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
/**
* Creates a new Polygon with any of the following forms:
*
* new Polygon([[0,0],[0,1],[1,1],[1,0]])
* new Polygon([GeoPoint, GeoPoint, GeoPoint])
*
*
* Represents a coordinates that may be associated
* with a key in a ParseObject or used as a reference point for geo queries.
* This allows proximity-based queries on the key.
*
* Example:
* var polygon = new Parse.Polygon([[0,0],[0,1],[1,1],[1,0]]);
* var object = new Parse.Object("PlaceObject");
* object.set("area", polygon);
* object.save();
*
* @alias Parse.Polygon
*/
class ParsePolygon {
/**
* @param {(Coordinates | Parse.GeoPoint[])} coordinates An Array of coordinate pairs
*/
constructor(coordinates) {
(0, _defineProperty2.default)(this, "_coordinates", void 0);
this._coordinates = ParsePolygon._validate(coordinates);
}
/**
* Coordinates value for this Polygon.
* Throws an exception if not valid type.
*
* @property {(Coordinates | Parse.GeoPoint[])} coordinates list of coordinates
* @returns {Coordinates}
*/
get coordinates() {
return this._coordinates;
}
set coordinates(coords) {
this._coordinates = ParsePolygon._validate(coords);
}
/**
* Returns a JSON representation of the Polygon, suitable for Parse.
*
* @returns {object}
*/
toJSON() {
ParsePolygon._validate(this._coordinates);
return {
__type: 'Polygon',
coordinates: this._coordinates
};
}
/**
* Checks if two polygons are equal
*
* @param {(Parse.Polygon | object)} other
* @returns {boolean}
*/
equals(other) {
if (!(other instanceof ParsePolygon) || this.coordinates.length !== other.coordinates.length) {
return false;
}
let isEqual = true;
for (let i = 1; i < this._coordinates.length; i += 1) {
if (this._coordinates[i][0] != other.coordinates[i][0] || this._coordinates[i][1] != other.coordinates[i][1]) {
isEqual = false;
break;
}
}
return isEqual;
}
/**
*
* @param {Parse.GeoPoint} point
* @returns {boolean} Returns if the point is contained in the polygon
*/
containsPoint(point) {
let minX = this._coordinates[0][0];
let maxX = this._coordinates[0][0];
let minY = this._coordinates[0][1];
let maxY = this._coordinates[0][1];
for (let i = 1; i < this._coordinates.length; i += 1) {
const p = this._coordinates[i];
minX = Math.min(p[0], minX);
maxX = Math.max(p[0], maxX);
minY = Math.min(p[1], minY);
maxY = Math.max(p[1], maxY);
}
const outside = point.latitude < minX || point.latitude > maxX || point.longitude < minY || point.longitude > maxY;
if (outside) {
return false;
}
let inside = false;
for (let i = 0, j = this._coordinates.length - 1; i < this._coordinates.length; j = i++) {
const startX = this._coordinates[i][0];
const startY = this._coordinates[i][1];
const endX = this._coordinates[j][0];
const endY = this._coordinates[j][1];
const intersect = startY > point.longitude != endY > point.longitude && point.latitude < (endX - startX) * (point.longitude - startY) / (endY - startY) + startX;
if (intersect) {
inside = !inside;
}
}
return inside;
}
/**
* Validates that the list of coordinates can form a valid polygon
*
* @param {Array} coords the list of coordinates to validate as a polygon
* @throws {TypeError}
* @returns {number[][]} Array of coordinates if validated.
*/
static _validate(coords) {
if (!(0, _isArray.default)(coords)) {
throw new TypeError('Coordinates must be an Array');
}
if (coords.length < 3) {
throw new TypeError('Polygon must have at least 3 GeoPoints or Points');
}
const points = [];
for (let i = 0; i < coords.length; i += 1) {
const coord = coords[i];
let geoPoint;
if (coord instanceof _ParseGeoPoint.default) {
geoPoint = coord;
} else if ((0, _isArray.default)(coord) && coord.length === 2) {
geoPoint = new _ParseGeoPoint.default(coord[0], coord[1]);
} else {
throw new TypeError('Coordinates must be an Array of GeoPoints or Points');
}
points.push([geoPoint.latitude, geoPoint.longitude]);
}
return points;
}
}
var _default = exports.default = ParsePolygon;
},{"./ParseGeoPoint":26,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],33:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _slice = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/slice"));
var _map = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _filter = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/filter"));
var _keys2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/keys"));
var _concat = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _includes = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/includes"));
var _sort = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/sort"));
var _splice = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/splice"));
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _find = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/find"));
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _entries = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/entries"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _encode = _interopRequireDefault(_dereq_("./encode"));
var _promiseUtils = _dereq_("./promiseUtils");
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
var _OfflineQuery = _interopRequireDefault(_dereq_("./OfflineQuery"));
var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
/**
* Converts a string into a regex that matches it.
* Surrounding with \Q .. \E does this, we just need to escape any \E's in
* the text separately.
*
* @param s
* @private
* @returns {string}
*/
function quote(s) {
return '\\Q' + s.replace('\\E', '\\E\\\\E\\Q') + '\\E';
}
/**
* Extracts the class name from queries. If not all queries have the same
* class name an error will be thrown.
*
* @param queries
* @private
* @returns {string}
*/
function _getClassNameFromQueries(queries) {
let className = null;
(0, _forEach.default)(queries).call(queries, q => {
if (!className) {
className = q.className;
}
if (className !== q.className) {
throw new Error('All queries must be for the same class.');
}
});
return className;
}
/*
* Handles pre-populating the result data of a query with select fields,
* making sure that the data object contains keys for all objects that have
* been requested with a select, so that our cached state updates correctly.
*/
function handleSelectResult(data, select) {
const serverDataMask = {};
(0, _forEach.default)(select).call(select, field => {
const hasSubObjectSelect = (0, _indexOf.default)(field).call(field, '.') !== -1;
if (!hasSubObjectSelect && !data.hasOwnProperty(field)) {
// this field was selected, but is missing from the retrieved data
data[field] = undefined;
} else if (hasSubObjectSelect) {
// this field references a sub-object,
// so we need to walk down the path components
const pathComponents = field.split('.');
let obj = data;
let serverMask = serverDataMask;
(0, _forEach.default)(pathComponents).call(pathComponents, (component, index, arr) => {
// add keys if the expected data is missing
if (obj && !obj.hasOwnProperty(component)) {
obj[component] = undefined;
}
if (obj && typeof obj === 'object') {
obj = obj[component];
}
//add this path component to the server mask so we can fill it in later if needed
if (index < arr.length - 1) {
if (!serverMask[component]) {
serverMask[component] = {};
}
serverMask = serverMask[component];
}
});
}
});
if ((0, _keys.default)(serverDataMask).length > 0) {
// When selecting from sub-objects, we don't want to blow away the missing
// information that we may have retrieved before. We've already added any
// missing selected keys to sub-objects, but we still need to add in the
// data for any previously retrieved sub-objects that were not selected.
const serverData = _CoreManager.default.getObjectStateController().getServerData({
id: data.objectId,
className: data.className
});
copyMissingDataWithMask(serverData, data, serverDataMask, false);
}
}
function copyMissingDataWithMask(src, dest, mask, copyThisLevel) {
//copy missing elements at this level
if (copyThisLevel) {
for (const key in src) {
if (src.hasOwnProperty(key) && !dest.hasOwnProperty(key)) {
dest[key] = src[key];
}
}
}
for (const key in mask) {
if (dest[key] !== undefined && dest[key] !== null && src !== undefined && src !== null) {
//traverse into objects as needed
copyMissingDataWithMask(src[key], dest[key], mask[key], true);
}
}
}
function handleOfflineSort(a, b, sorts) {
let order = sorts[0];
const operator = (0, _slice.default)(order).call(order, 0, 1);
const isDescending = operator === '-';
if (isDescending) {
order = order.substring(1);
}
if (order === '_created_at') {
order = 'createdAt';
}
if (order === '_updated_at') {
order = 'updatedAt';
}
if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(order) || order === 'password') {
throw new _ParseError.default(_ParseError.default.INVALID_KEY_NAME, `Invalid Key: ${order}`);
}
const field1 = a.get(order);
const field2 = b.get(order);
if (field1 < field2) {
return isDescending ? 1 : -1;
}
if (field1 > field2) {
return isDescending ? -1 : 1;
}
if (sorts.length > 1) {
const remainingSorts = (0, _slice.default)(sorts).call(sorts, 1);
return handleOfflineSort(a, b, remainingSorts);
}
return 0;
}
/**
* Creates a new parse Parse.Query for the given Parse.Object subclass.
*
* Parse.Query defines a query that is used to fetch Parse.Objects. The
* most common use case is finding all objects that match a query through the
* find
method. for example, this sample code fetches all objects
* of class myclass
. it calls a different function depending on
* whether the fetch succeeded or not.
*
*
* var query = new Parse.Query(myclass);
* query.find().then((results) => {
* // results is an array of parse.object.
* }).catch((error) => {
* // error is an instance of parse.error.
* });
*
* a Parse.Query can also be used to retrieve a single object whose id is
* known, through the get method. for example, this sample code fetches an
* object of class myclass
and id myid
. it calls a
* different function depending on whether the fetch succeeded or not.
*
*
* var query = new Parse.Query(myclass);
* query.get(myid).then((object) => {
* // object is an instance of parse.object.
* }).catch((error) => {
* // error is an instance of parse.error.
* });
*
* a Parse.Query can also be used to count the number of objects that match
* the query without retrieving all of those objects. for example, this
* sample code counts the number of objects of the class myclass
*
* var query = new Parse.Query(myclass);
* query.count().then((number) => {
* // there are number instances of myclass.
* }).catch((error) => {
* // error is an instance of Parse.Error.
* });
*
* @alias Parse.Query
*/
class ParseQuery {
/**
* @param {(string | Parse.Object)} objectClass An instance of a subclass of Parse.Object, or a Parse className string.
*/
constructor(objectClass) {
/**
* @property {string} className
*/
(0, _defineProperty2.default)(this, "className", void 0);
(0, _defineProperty2.default)(this, "_where", void 0);
(0, _defineProperty2.default)(this, "_watch", void 0);
(0, _defineProperty2.default)(this, "_include", void 0);
(0, _defineProperty2.default)(this, "_exclude", void 0);
(0, _defineProperty2.default)(this, "_select", void 0);
(0, _defineProperty2.default)(this, "_limit", void 0);
(0, _defineProperty2.default)(this, "_skip", void 0);
(0, _defineProperty2.default)(this, "_count", void 0);
(0, _defineProperty2.default)(this, "_order", void 0);
(0, _defineProperty2.default)(this, "_readPreference", void 0);
(0, _defineProperty2.default)(this, "_includeReadPreference", void 0);
(0, _defineProperty2.default)(this, "_subqueryReadPreference", void 0);
(0, _defineProperty2.default)(this, "_queriesLocalDatastore", void 0);
(0, _defineProperty2.default)(this, "_localDatastorePinName", void 0);
(0, _defineProperty2.default)(this, "_extraOptions", void 0);
(0, _defineProperty2.default)(this, "_hint", void 0);
(0, _defineProperty2.default)(this, "_explain", void 0);
(0, _defineProperty2.default)(this, "_xhrRequest", void 0);
(0, _defineProperty2.default)(this, "_comment", void 0);
if (typeof objectClass === 'string') {
if (objectClass === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
this.className = '_User';
} else {
this.className = objectClass;
}
} else if (objectClass instanceof _ParseObject.default) {
this.className = objectClass.className;
} else if (typeof objectClass === 'function') {
const objClass = objectClass;
if (typeof objClass.className === 'string') {
this.className = objClass.className;
} else {
const obj = new objClass();
this.className = obj.className;
}
} else {
throw new TypeError('A ParseQuery must be constructed with a ParseObject or class name.');
}
this._where = {};
this._watch = [];
this._include = [];
this._exclude = [];
this._count = false;
this._limit = -1; // negative limit is not sent in the server request
this._skip = 0;
this._readPreference = null;
this._includeReadPreference = null;
this._subqueryReadPreference = null;
this._queriesLocalDatastore = false;
this._localDatastorePinName = null;
this._extraOptions = {};
this._xhrRequest = {
task: null,
onchange: () => {}
};
this._comment = null;
}
/**
* Adds constraint that at least one of the passed in queries matches.
*
* @param {Array} queries
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
_orQuery(queries) {
const queryJSON = (0, _map.default)(queries).call(queries, q => {
return q.toJSON().where;
});
this._where.$or = queryJSON;
return this;
}
/**
* Adds constraint that all of the passed in queries match.
*
* @param {Array} queries
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
_andQuery(queries) {
const queryJSON = (0, _map.default)(queries).call(queries, q => {
return q.toJSON().where;
});
this._where.$and = queryJSON;
return this;
}
/**
* Adds constraint that none of the passed in queries match.
*
* @param {Array} queries
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
_norQuery(queries) {
const queryJSON = (0, _map.default)(queries).call(queries, q => {
return q.toJSON().where;
});
this._where.$nor = queryJSON;
return this;
}
/**
* Helper for condition queries
*
* @param key
* @param condition
* @param value
* @returns {Parse.Query}
*/
_addCondition(key, condition, value) {
if (!this._where[key] || typeof this._where[key] === 'string') {
this._where[key] = {};
}
this._where[key][condition] = (0, _encode.default)(value, false, true);
return this;
}
/**
* Converts string for regular expression at the beginning
*
* @param string
* @returns {string}
*/
_regexStartWith(string) {
return '^' + quote(string);
}
async _handleOfflineQuery(params) {
var _context;
_OfflineQuery.default.validateQuery(this);
const localDatastore = _CoreManager.default.getLocalDatastore();
const objects = await localDatastore._serializeObjectsFromPinName(this._localDatastorePinName);
let results = (0, _filter.default)(_context = (0, _map.default)(objects).call(objects, (json, index, arr) => {
const object = _ParseObject.default.fromJSON(json, false);
if (json._localId && !json.objectId) {
object._localId = json._localId;
}
if (!_OfflineQuery.default.matchesQuery(this.className, object, arr, this)) {
return null;
}
return object;
})).call(_context, object => object !== null);
if ((0, _keys2.default)(params)) {
let keys = (0, _keys2.default)(params).split(',');
keys = (0, _concat.default)(keys).call(keys, ['className', 'objectId', 'createdAt', 'updatedAt', 'ACL']);
results = (0, _map.default)(results).call(results, object => {
var _context2;
const json = object._toFullJSON();
(0, _forEach.default)(_context2 = (0, _keys.default)(json)).call(_context2, key => {
if (!(0, _includes.default)(keys).call(keys, key)) {
delete json[key];
}
});
return _ParseObject.default.fromJSON(json, false);
});
}
if (params.order) {
const sorts = params.order.split(',');
(0, _sort.default)(results).call(results, (a, b) => {
return handleOfflineSort(a, b, sorts);
});
}
let count; // count total before applying limit/skip
if (params.count) {
count = results.length; // total count from response
}
if (params.skip) {
if (params.skip >= results.length) {
results = [];
} else {
results = (0, _splice.default)(results).call(results, params.skip, results.length);
}
}
let limit = results.length;
if (params.limit !== 0 && params.limit < results.length) {
limit = params.limit;
}
results = (0, _splice.default)(results).call(results, 0, limit);
if (typeof count === 'number') {
return {
results,
count
};
}
return results;
}
/**
* Returns a JSON representation of this query.
*
* @returns {object} The JSON representation of the query.
*/
toJSON() {
const params = {
where: this._where
};
if (this._watch.length) {
params.watch = this._watch.join(',');
}
if (this._include.length) {
params.include = this._include.join(',');
}
if (this._exclude.length) {
params.excludeKeys = this._exclude.join(',');
}
if (this._select) {
params.keys = this._select.join(',');
}
if (this._count) {
params.count = 1;
}
if (this._limit >= 0) {
params.limit = this._limit;
}
if (this._skip > 0) {
params.skip = this._skip;
}
if (this._order) {
params.order = this._order.join(',');
}
if (this._readPreference) {
params.readPreference = this._readPreference;
}
if (this._includeReadPreference) {
params.includeReadPreference = this._includeReadPreference;
}
if (this._subqueryReadPreference) {
params.subqueryReadPreference = this._subqueryReadPreference;
}
if (this._hint) {
params.hint = this._hint;
}
if (this._explain) {
params.explain = true;
}
if (this._comment) {
params.comment = this._comment;
}
for (const key in this._extraOptions) {
params[key] = this._extraOptions[key];
}
return params;
}
/**
* Return a query with conditions from json, can be useful to send query from server side to client
* Not static, all query conditions was set before calling this method will be deleted.
* For example on the server side we have
* var query = new Parse.Query("className");
* query.equalTo(key: value);
* query.limit(100);
* ... (others queries)
* Create JSON representation of Query Object
* var jsonFromServer = query.fromJSON();
*
* On client side getting query:
* var query = new Parse.Query("className");
* query.fromJSON(jsonFromServer);
*
* and continue to query...
* query.skip(100).find().then(...);
*
* @param {QueryJSON} json from Parse.Query.toJSON() method
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
withJSON(json) {
if (json.where) {
this._where = json.where;
}
if (json.watch) {
this._watch = json.watch.split(',');
}
if (json.include) {
this._include = json.include.split(',');
}
if ((0, _keys2.default)(json)) {
this._select = (0, _keys2.default)(json).split(',');
}
if (json.excludeKeys) {
this._exclude = json.excludeKeys.split(',');
}
if (json.count) {
this._count = json.count === 1;
}
if (json.limit) {
this._limit = json.limit;
}
if (json.skip) {
this._skip = json.skip;
}
if (json.order) {
this._order = json.order.split(',');
}
if (json.readPreference) {
this._readPreference = json.readPreference;
}
if (json.includeReadPreference) {
this._includeReadPreference = json.includeReadPreference;
}
if (json.subqueryReadPreference) {
this._subqueryReadPreference = json.subqueryReadPreference;
}
if (json.hint) {
this._hint = json.hint;
}
if (json.explain) {
this._explain = !!json.explain;
}
if (json.comment) {
this._comment = json.comment;
}
for (const key in json) {
if (json.hasOwnProperty(key)) {
var _context3;
if ((0, _indexOf.default)(_context3 = ['where', 'include', 'keys', 'count', 'limit', 'skip', 'order', 'readPreference', 'includeReadPreference', 'subqueryReadPreference', 'hint', 'explain', 'comment']).call(_context3, key) === -1) {
this._extraOptions[key] = json[key];
}
}
}
return this;
}
/**
* 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, json) {
const query = new ParseQuery(className);
return query.withJSON(json);
}
/**
* Constructs a Parse.Object whose id is already known by fetching data from
* the server. Unlike the first
method, it never returns undefined.
*
* @param {string} objectId The id of the object to be fetched.
* @param {object} options
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
*
- json: Return raw json without converting to Parse.Object
*
* @returns {Promise} A promise that is resolved with the result when
* the query completes.
*/
get(objectId, options) {
this.equalTo('objectId', objectId);
const firstOptions = {};
if (options && options.hasOwnProperty('useMasterKey')) {
firstOptions.useMasterKey = options.useMasterKey;
}
if (options && options.hasOwnProperty('sessionToken')) {
firstOptions.sessionToken = options.sessionToken;
}
if (options && options.hasOwnProperty('context') && typeof options.context === 'object') {
firstOptions.context = options.context;
}
if (options && options.hasOwnProperty('json')) {
firstOptions.json = options.json;
}
return this.first(firstOptions).then(response => {
if (response) {
return response;
}
const errorObject = new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'Object not found.');
return _promise.default.reject(errorObject);
});
}
/**
* Retrieves a list of ParseObjects that satisfy this query.
*
* @param {object} options Valid options
* are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
*
- json: Return raw json without converting to Parse.Object
*
* @returns {Promise} A promise that is resolved with the results when
* the query completes.
*/
find(options) {
options = options || {};
const findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('context') && typeof options.context === 'object') {
findOptions.context = options.context;
}
this._setRequestTask(findOptions);
const controller = _CoreManager.default.getQueryController();
const select = this._select;
if (this._queriesLocalDatastore) {
return this._handleOfflineQuery(this.toJSON());
}
return (0, _find.default)(controller).call(controller, this.className, this.toJSON(), findOptions).then(response => {
// Return generic object when explain is used
if (this._explain) {
return response.results;
}
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;
if (!data.className) {
data.className = override;
}
// Make sure the data object contains keys for all objects that
// have been requested with a select, so that our cached state
// updates correctly.
if (select) {
handleSelectResult(data, select);
}
if (options.json) {
return data;
} else {
return _ParseObject.default.fromJSON(data, !select);
}
});
const count = response.count;
if (typeof count === 'number') {
return {
results,
count
};
} else {
return results;
}
});
}
/**
* Retrieves a complete list of ParseObjects that satisfy this query.
* Using `eachBatch` under the hood to fetch all the valid objects.
*
* @param {object} options Valid options are:
* - batchSize: How many objects to yield in each batch (default: 100)
*
- useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
* @returns {Promise} A promise that is resolved with the results when
* the query completes.
*/
async findAll(options) {
let result = [];
await this.eachBatch(objects => {
result = [...result, ...objects];
}, options);
return result;
}
/**
* Counts the number of objects that match this query.
*
* @param {object} options
* @param {boolean} [options.useMasterKey]
* @param {string} [options.sessionToken]
* Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
* @returns {Promise} A promise that is resolved with the count when
* the query completes.
*/
count(options) {
options = options || {};
const findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
this._setRequestTask(findOptions);
const controller = _CoreManager.default.getQueryController();
const params = this.toJSON();
params.limit = 0;
params.count = 1;
return (0, _find.default)(controller).call(controller, this.className, params, findOptions).then(result => {
return result.count;
});
}
/**
* Executes a distinct query and returns unique values
*
* @param {string} key A field to find distinct values
* @param {object} options
* @param {string} [options.sessionToken] A valid session token, used for making a request on behalf of a specific user.
* @returns {Promise} A promise that is resolved with the query completes.
*/
distinct(key, options) {
options = options || {};
const distinctOptions = {
useMasterKey: true
};
if (options.hasOwnProperty('sessionToken')) {
distinctOptions.sessionToken = options.sessionToken;
}
this._setRequestTask(distinctOptions);
const controller = _CoreManager.default.getQueryController();
const params = {
distinct: key,
where: this._where,
hint: this._hint
};
return controller.aggregate(this.className, params, distinctOptions).then(results => {
return results.results;
});
}
/**
* Executes an aggregate query and returns aggregate results
*
* @param {(Array|object)} pipeline Array or Object of stages to process query
* @param {object} options
* @param {string} [options.sessionToken] A valid session token, used for making a request on behalf of a specific user.
* @returns {Promise} A promise that is resolved with the query completes.
*/
aggregate(pipeline, options) {
options = options || {};
const aggregateOptions = {
useMasterKey: true
};
if (options.hasOwnProperty('sessionToken')) {
aggregateOptions.sessionToken = options.sessionToken;
}
this._setRequestTask(aggregateOptions);
const controller = _CoreManager.default.getQueryController();
if (!(0, _isArray.default)(pipeline) && typeof pipeline !== 'object') {
throw new Error('Invalid pipeline must be Array or Object');
}
if ((0, _keys.default)(this._where || {}).length) {
if (!(0, _isArray.default)(pipeline)) {
pipeline = [pipeline];
}
pipeline.unshift({
$match: this._where
});
}
const params = {
pipeline,
hint: this._hint,
explain: this._explain,
readPreference: this._readPreference
};
return controller.aggregate(this.className, params, aggregateOptions).then(results => {
return results.results;
});
}
/**
* Retrieves at most one Parse.Object that satisfies this query.
*
* Returns the object if there is one, otherwise undefined.
*
* @param {object} options Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
*
- json: Return raw json without converting to Parse.Object
*
* @returns {Promise} A promise that is resolved with the object when
* the query completes.
*/
first() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('context') && typeof options.context === 'object') {
findOptions.context = options.context;
}
this._setRequestTask(findOptions);
const controller = _CoreManager.default.getQueryController();
const params = this.toJSON();
params.limit = 1;
const select = this._select;
if (this._queriesLocalDatastore) {
return this._handleOfflineQuery(params).then(objects => {
if (!objects[0]) {
return undefined;
}
return objects[0];
});
}
return (0, _find.default)(controller).call(controller, this.className, params, findOptions).then(response => {
const objects = response.results;
if (!objects[0]) {
return undefined;
}
if (!objects[0].className) {
objects[0].className = this.className;
}
// Make sure the data object contains keys for all objects that
// have been requested with a select, so that our cached state
// updates correctly.
if (select) {
handleSelectResult(objects[0], select);
}
if (options.json) {
return objects[0];
} else {
return _ParseObject.default.fromJSON(objects[0], !select);
}
});
}
/**
* Iterates over objects matching a query, calling a callback for each batch.
* If the callback returns a promise, the iteration will not continue until
* that promise has been fulfilled. If the callback returns a rejected
* promise, then iteration will stop with that error. The items are processed
* in an unspecified order. The query may not have any sort order, and may
* not use limit or skip.
*
* @param {Function} callback Callback that will be called with each result
* of the query.
* @param {object} options Valid options are:
* - batchSize: How many objects to yield in each batch (default: 100)
*
- useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
*
* @returns {Promise} A promise that will be fulfilled once the
* iteration has completed.
*/
eachBatch(callback, options) {
options = options || {};
if (this._order || this._skip || this._limit >= 0) {
return _promise.default.reject('Cannot iterate on a query with sort, skip, or limit.');
}
const query = new ParseQuery(this.className);
query._limit = options.batchSize || 100;
query._include = [...this._include];
query._exclude = [...this._exclude];
if (this._select) {
query._select = [...this._select];
}
query._hint = this._hint;
query._where = {};
for (const attr in this._where) {
const val = this._where[attr];
if ((0, _isArray.default)(val)) {
query._where[attr] = (0, _map.default)(val).call(val, v => {
return v;
});
} else if (val && typeof val === 'object') {
const conditionMap = {};
query._where[attr] = conditionMap;
for (const cond in val) {
conditionMap[cond] = val[cond];
}
} else {
query._where[attr] = val;
}
}
query.ascending('objectId');
const findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('context') && typeof options.context === 'object') {
findOptions.context = options.context;
}
if (options.hasOwnProperty('json')) {
findOptions.json = options.json;
}
let finished = false;
let previousResults = [];
return (0, _promiseUtils.continueWhile)(() => {
return !finished;
}, async () => {
const [results] = await _promise.default.all([(0, _find.default)(query).call(query, findOptions), _promise.default.resolve(previousResults.length > 0 && callback(previousResults))]);
if (results.length >= query._limit) {
query.greaterThan('objectId', results[results.length - 1].id);
previousResults = results;
} else if (results.length > 0) {
await _promise.default.resolve(callback(results));
finished = true;
} else {
finished = true;
}
});
}
/**
* 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
* that promise has been fulfilled. If the callback returns a rejected
* promise, then iteration will stop with that error. The items are
* processed in an unspecified order. The query may not have any sort order,
* and may not use limit or skip.
*
* @param {Function} callback Callback that will be called with each result
* of the query.
* @param {object} options Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
- json: Return raw json without converting to Parse.Object
*
* @returns {Promise} A promise that will be fulfilled once the
* iteration has completed.
*/
each(callback, options) {
return this.eachBatch(results => {
let callbacksDone = _promise.default.resolve();
(0, _forEach.default)(results).call(results, result => {
callbacksDone = callbacksDone.then(() => {
return callback(result);
});
});
return callbacksDone;
}, options);
}
/**
* Adds a hint to force index selection. (https://docs.mongodb.com/manual/reference/operator/meta/hint/)
*
* @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) {
if (typeof value === 'undefined') {
delete this._hint;
}
this._hint = value;
return this;
}
/**
* Investigates the query execution plan. Useful for optimizing queries. (https://docs.mongodb.com/manual/reference/operator/meta/explain/)
*
* @param {boolean} explain Used to toggle the information on the query plan.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
explain() {
let explain = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
if (typeof explain !== 'boolean') {
throw new Error('You can only set explain to a boolean value');
}
this._explain = explain;
return this;
}
/**
* 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
* that promise has been fulfilled. If the callback returns a rejected
* promise, then iteration will stop with that error. The items are
* processed in an unspecified order. The query may not have any sort order,
* and may not use limit or skip.
*
* @param {Function} callback Callback
* - currentObject: The current Parse.Object being processed in the array.
* - index: The index of the current Parse.Object being processed in the array.
* - query: The query map was called upon.
*
* @param {object} options Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
* @returns {Promise} A promise that will be fulfilled once the
* iteration has completed.
*/
async map(callback, options) {
const array = [];
let index = 0;
await this.each(object => {
return _promise.default.resolve(callback(object, index, this)).then(result => {
array.push(result);
index += 1;
});
}, options);
return array;
}
/**
* 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
* that promise has been fulfilled. If the callback returns a rejected
* promise, then iteration will stop with that error. The items are
* processed in an unspecified order. The query may not have any sort order,
* and may not use limit or skip.
*
* @param {Function} callback Callback
* - accumulator: The accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback.
* - currentObject: The current Parse.Object being processed in the array.
* - index: The index of the current Parse.Object being processed in the array.
*
* @param {*} initialValue A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first object in the query will be used and skipped.
* @param {object} options Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
* @returns {Promise} A promise that will be fulfilled once the
* iteration has completed.
*/
async reduce(callback, initialValue, options) {
let accumulator = initialValue;
let index = 0;
await this.each(object => {
// If no initial value was given, we take the first object from the query
// as the initial value and don't call the callback with it.
if (index === 0 && initialValue === undefined) {
accumulator = object;
index += 1;
return;
}
return _promise.default.resolve(callback(accumulator, object, index)).then(result => {
accumulator = result;
index += 1;
});
}, options);
if (index === 0 && initialValue === undefined) {
// Match Array.reduce behavior: "Calling reduce() on an empty array
// without an initialValue will throw a TypeError".
throw new TypeError('Reducing empty query result set with no initial value');
}
return accumulator;
}
/**
* 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
* that promise has been fulfilled. If the callback returns a rejected
* promise, then iteration will stop with that error. The items are
* processed in an unspecified order. The query may not have any sort order,
* and may not use limit or skip.
*
* @param {Function} callback Callback
* - currentObject: The current Parse.Object being processed in the array.
* - index: The index of the current Parse.Object being processed in the array.
* - query: The query filter was called upon.
*
* @param {object} options Valid options are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
- sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
*
* @returns {Promise} A promise that will be fulfilled once the
* iteration has completed.
*/
async filter(callback, options) {
const array = [];
let index = 0;
await this.each(object => {
return _promise.default.resolve(callback(object, index, this)).then(flag => {
if (flag) {
array.push(object);
}
index += 1;
});
}, options);
return array;
}
/* Query Conditions */
/**
* Adds a constraint to the query that requires a particular key's value to
* be equal to the provided value.
*
* @param {string} key The key to check.
* @param value The value that the Parse.Object must contain.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
equalTo(key, value) {
if (key && typeof key === 'object') {
var _context4;
(0, _forEach.default)(_context4 = (0, _entries.default)(key)).call(_context4, _ref => {
let [k, val] = _ref;
return this.equalTo(k, val);
});
return this;
}
if (typeof value === 'undefined') {
return this.doesNotExist(key);
}
this._where[key] = (0, _encode.default)(value, false, true);
return this;
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be not equal to the provided value.
*
* @param {string} key The key to check.
* @param value The value that must not be equalled.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
notEqualTo(key, value) {
if (key && typeof key === 'object') {
var _context5;
(0, _forEach.default)(_context5 = (0, _entries.default)(key)).call(_context5, _ref2 => {
let [k, val] = _ref2;
return this.notEqualTo(k, val);
});
return this;
}
return this._addCondition(key, '$ne', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be less than the provided value.
*
* @param {string} key The key to check.
* @param value The value that provides an upper bound.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
lessThan(key, value) {
return this._addCondition(key, '$lt', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be greater than the provided value.
*
* @param {string} key The key to check.
* @param value The value that provides an lower bound.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
greaterThan(key, value) {
return this._addCondition(key, '$gt', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be less than or equal to the provided value.
*
* @param {string} key The key to check.
* @param value The value that provides an upper bound.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
lessThanOrEqualTo(key, value) {
return this._addCondition(key, '$lte', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be greater than or equal to the provided value.
*
* @param {string} key The key to check.
* @param {*} value The value that provides an lower bound.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
greaterThanOrEqualTo(key, value) {
return this._addCondition(key, '$gte', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be contained in the provided list of values.
*
* @param {string} key The key to check.
* @param {Array<*>} value The values that will match.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
containedIn(key, value) {
return this._addCondition(key, '$in', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* not be contained in the provided list of values.
*
* @param {string} key The key to check.
* @param {Array<*>} value The values that will not match.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
notContainedIn(key, value) {
return this._addCondition(key, '$nin', value);
}
/**
* 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.
*
* @param {string} key The key to check.
* @param {Array} values The values that will match.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
containedBy(key, values) {
return this._addCondition(key, '$containedBy', values);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* contain each one of the provided list of values.
*
* @param {string} key The key to check. This key's value must be an array.
* @param {Array} values The values that will match.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
containsAll(key, values) {
return this._addCondition(key, '$all', values);
}
/**
* 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.
*
* @param {string} key The key to check. This key's value must be an array.
* @param {Array} values The string values that will match as starting string.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
containsAllStartingWith(key, values) {
if (!(0, _isArray.default)(values)) {
values = [values];
}
const regexObject = (0, _map.default)(values).call(values, value => {
return {
$regex: this._regexStartWith(value)
};
});
return this.containsAll(key, regexObject);
}
/**
* Adds a constraint for finding objects that contain the given key.
*
* @param {string} key The key that should exist.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
exists(key) {
return this._addCondition(key, '$exists', true);
}
/**
* Adds a constraint for finding objects that do not contain a given key.
*
* @param {string} key The key that should not exist
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotExist(key) {
return this._addCondition(key, '$exists', false);
}
/**
* Adds a regular expression constraint for finding string values that match
* the provided regular expression.
* This may be slow for large datasets.
*
* @param {string} key The key that the string to match is stored in.
* @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, regex, modifiers) {
this._addCondition(key, '$regex', regex);
if (!modifiers) {
modifiers = '';
}
if (typeof regex !== 'string') {
if (regex.ignoreCase) {
modifiers += 'i';
}
if (regex.multiline) {
modifiers += 'm';
}
}
if (modifiers.length) {
this._addCondition(key, '$options', modifiers);
}
return this;
}
/**
* Adds a constraint that requires that a key's value matches a Parse.Query
* constraint.
*
* @param {string} key The key that the contains the object to match the
* query.
* @param {Parse.Query} query The query that should match.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
matchesQuery(key, query) {
const queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$inQuery', queryJSON);
}
/**
* Adds a constraint that requires that a key's value not matches a
* Parse.Query constraint.
*
* @param {string} key The key that the contains the object to match the
* query.
* @param {Parse.Query} query The query that should not match.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotMatchQuery(key, query) {
const queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$notInQuery', queryJSON);
}
/**
* Adds a constraint that requires that a key's value matches a value in
* an object returned by a different Parse.Query.
*
* @param {string} key The key that contains the value that is being
* matched.
* @param {string} queryKey The key in the objects returned by the query to
* match against.
* @param {Parse.Query} query The query to run.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
matchesKeyInQuery(key, queryKey, query) {
const queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$select', {
key: queryKey,
query: queryJSON
});
}
/**
* Adds a constraint that requires that a key's value not match a value in
* an object returned by a different Parse.Query.
*
* @param {string} key The key that contains the value that is being
* excluded.
* @param {string} queryKey The key in the objects returned by the query to
* match against.
* @param {Parse.Query} query The query to run.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotMatchKeyInQuery(key, queryKey, query) {
const queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$dontSelect', {
key: queryKey,
query: queryJSON
});
}
/**
* Adds a constraint for finding string values that contain a provided
* string. This may be slow for large datasets.
*
* @param {string} key The key that the string to match is stored in.
* @param {string} substring The substring that the value must contain.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
contains(key, substring) {
if (typeof substring !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this._addCondition(key, '$regex', quote(substring));
}
/**
* Adds a constraint for finding string values that contain a provided
* string. This may be slow for large datasets. Requires Parse-Server > 2.5.0
*
* In order to sort you must use select and ascending ($score is required)
*
* query.fullText('field', 'term');
* query.ascending('$score');
* query.select('$score');
*
*
* To retrieve the weight / rank
*
* object->get('score');
*
*
* You can define optionals by providing an object as a third parameter
*
* query.fullText('field', 'term', { language: 'es', diacriticSensitive: true });
*
*
* @param {string} key The key that the string to match is stored in.
* @param {string} value The string to search
* @param {object} options (Optional)
* @param {string} options.language The language that determines the list of stop words for the search and the rules for the stemmer and tokenizer.
* @param {boolean} options.caseSensitive A boolean flag to enable or disable case sensitive search.
* @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, value) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
options = options || {};
if (!key) {
throw new Error('A key is required.');
}
if (!value) {
throw new Error('A search term is required');
}
if (typeof value !== 'string') {
throw new Error('The value being searched for must be a string.');
}
const fullOptions = {};
fullOptions.$term = value;
for (const option in options) {
switch (option) {
case 'language':
fullOptions.$language = options[option];
break;
case 'caseSensitive':
fullOptions.$caseSensitive = options[option];
break;
case 'diacriticSensitive':
fullOptions.$diacriticSensitive = options[option];
break;
default:
throw new Error(`Unknown option: ${option}`);
}
}
return this._addCondition(key, '$text', {
$search: fullOptions
});
}
/**
* Method to sort the full text search by text score
*
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
sortByTextScore() {
this.ascending('$score');
this.select(['$score']);
return 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
* for large datasets.
*
* @param {string} key The key that the string to match is stored in.
* @param {string} prefix The substring that the value must start with.
* @param {string} modifiers The regular expression mode.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
startsWith(key, prefix, modifiers) {
if (typeof prefix !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this.matches(key, this._regexStartWith(prefix), modifiers);
}
/**
* Adds a constraint for finding string values that end with a provided
* string. This will be slow for large datasets.
*
* @param {string} key The key that the string to match is stored in.
* @param {string} suffix The substring that the value must end with.
* @param {string} modifiers The regular expression mode.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
endsWith(key, suffix, modifiers) {
if (typeof suffix !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this.matches(key, quote(suffix) + '$', modifiers);
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given.
*
* @param {string} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
near(key, point) {
if (!(point instanceof _ParseGeoPoint.default)) {
// Try to cast it as a GeoPoint
point = new _ParseGeoPoint.default(point);
}
return this._addCondition(key, '$nearSphere', point);
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
*
* @param {string} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {number} maxDistance Maximum distance (in radians) of results to return.
* @param {boolean} sorted A Bool value that is true if results should be
* sorted by distance ascending, false is no sorting is required,
* defaults to true.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
withinRadians(key, point, maxDistance, sorted) {
if (sorted || sorted === undefined) {
this.near(key, point);
return this._addCondition(key, '$maxDistance', maxDistance);
} else {
return this._addCondition(key, '$geoWithin', {
$centerSphere: [[point.longitude, point.latitude], maxDistance]
});
}
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* Radius of earth used is 3958.8 miles.
*
* @param {string} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {number} maxDistance Maximum distance (in miles) of results to return.
* @param {boolean} sorted A Bool value that is true if results should be
* sorted by distance ascending, false is no sorting is required,
* defaults to true.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
withinMiles(key, point, maxDistance, sorted) {
return this.withinRadians(key, point, maxDistance / 3958.8, sorted);
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* Radius of earth used is 6371.0 kilometers.
*
* @param {string} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {number} maxDistance Maximum distance (in kilometers) of results to return.
* @param {boolean} sorted A Bool value that is true if results should be
* sorted by distance ascending, false is no sorting is required,
* defaults to true.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
withinKilometers(key, point, maxDistance, sorted) {
return this.withinRadians(key, point, maxDistance / 6371.0, sorted);
}
/**
* Adds a constraint to the query that requires a particular key's
* coordinates be contained within a given rectangular geographic bounding
* box.
*
* @param {string} key The key to be constrained.
* @param {Parse.GeoPoint} southwest
* The lower-left inclusive corner of the box.
* @param {Parse.GeoPoint} northeast
* The upper-right inclusive corner of the box.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
withinGeoBox(key, southwest, northeast) {
if (!(southwest instanceof _ParseGeoPoint.default)) {
southwest = new _ParseGeoPoint.default(southwest);
}
if (!(northeast instanceof _ParseGeoPoint.default)) {
northeast = new _ParseGeoPoint.default(northeast);
}
this._addCondition(key, '$within', {
$box: [southwest, northeast]
});
return this;
}
/**
* Adds a constraint to the query that requires a particular key's
* coordinates be contained within and on the bounds of a given polygon.
* Supports closed and open (last point is connected to first) paths
*
* Polygon must have at least 3 points
*
* @param {string} key The key to be constrained.
* @param {Array} points Array of Coordinates / GeoPoints
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
withinPolygon(key, points) {
return this._addCondition(key, '$geoWithin', {
$polygon: points
});
}
/**
* Add a constraint to the query that requires a particular key's
* coordinates that contains a ParseGeoPoint
*
* @param {string} key The key to be constrained.
* @param {Parse.GeoPoint} point
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
polygonContains(key, point) {
return this._addCondition(key, '$geoIntersects', {
$point: point
});
}
/* Query Orderings */
/**
* Sorts the results in ascending order by the given key.
*
* @param {(string|string[])} keys The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
ascending() {
this._order = [];
for (var _len = arguments.length, keys = new Array(_len), _key = 0; _key < _len; _key++) {
keys[_key] = arguments[_key];
}
return this.addAscending.apply(this, keys);
}
/**
* Sorts the results in ascending order by the given key,
* but can also add secondary sort descriptors without overwriting _order.
*
* @param {(string|string[])} keys The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
addAscending() {
if (!this._order) {
this._order = [];
}
for (var _len2 = arguments.length, keys = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
keys[_key2] = arguments[_key2];
}
(0, _forEach.default)(keys).call(keys, key => {
var _context6;
if ((0, _isArray.default)(key)) {
key = key.join();
}
this._order = (0, _concat.default)(_context6 = this._order).call(_context6, key.replace(/\s/g, '').split(','));
});
return this;
}
/**
* Sorts the results in descending order by the given key.
*
* @param {(string|string[])} keys The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
descending() {
this._order = [];
for (var _len3 = arguments.length, keys = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
keys[_key3] = arguments[_key3];
}
return this.addDescending.apply(this, keys);
}
/**
* Sorts the results in descending order by the given key,
* but can also add secondary sort descriptors without overwriting _order.
*
* @param {(string|string[])} keys The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
addDescending() {
if (!this._order) {
this._order = [];
}
for (var _len4 = arguments.length, keys = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
keys[_key4] = arguments[_key4];
}
(0, _forEach.default)(keys).call(keys, key => {
var _context7, _context8;
if ((0, _isArray.default)(key)) {
key = key.join();
}
this._order = (0, _concat.default)(_context7 = this._order).call(_context7, (0, _map.default)(_context8 = key.replace(/\s/g, '').split(',')).call(_context8, k => {
return '-' + k;
}));
});
return this;
}
/* Query Options */
/**
* Sets the number of results to skip before returning any results.
* This is useful for pagination.
* Default is to skip zero results.
*
* @param {number} n the number of results to skip.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
skip(n) {
if (typeof n !== 'number' || n < 0) {
throw new Error('You can only skip by a positive number');
}
this._skip = n;
return this;
}
/**
* Sets the limit of the number of results to return. The default limit is 100.
*
* @param {number} n the number of results to limit to.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
limit(n) {
if (typeof n !== 'number') {
throw new Error('You can only set the limit to a numeric value');
}
this._limit = n;
return this;
}
/**
* Sets the flag to include with response the total number of objects satisfying this query,
* despite limits/skip. Might be useful for pagination.
* Note that result of this query will be wrapped as an object with
* `results`: holding {ParseObject} array and `count`: integer holding total number
*
* @param {boolean} includeCount false - disable, true - enable.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
withCount() {
let includeCount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
if (typeof includeCount !== 'boolean') {
throw new Error('You can only set withCount to a boolean value');
}
this._count = includeCount;
return this;
}
/**
* Includes nested Parse.Objects for the provided key. You can use dot
* notation to specify which fields in the included object are also fetched.
*
* You can include all nested Parse.Objects by passing in '*'.
* Requires Parse Server 3.0.0+
* query.include('*');
*
* @param {...string|Array} keys The name(s) of the key(s) to include.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
include() {
for (var _len5 = arguments.length, keys = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
keys[_key5] = arguments[_key5];
}
(0, _forEach.default)(keys).call(keys, key => {
if ((0, _isArray.default)(key)) {
var _context9;
this._include = (0, _concat.default)(_context9 = this._include).call(_context9, key);
} else {
this._include.push(key);
}
});
return this;
}
/**
* Includes all nested Parse.Objects one level deep.
*
* Requires Parse Server 3.0.0+
*
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
includeAll() {
return this.include('*');
}
/**
* Restricts the fields of the returned Parse.Objects to include only the
* provided keys. If this is called multiple times, then all of the keys
* specified in each of the calls will be included.
*
* @param {...string|Array} keys The name(s) of the key(s) to include.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
select() {
if (!this._select) {
this._select = [];
}
for (var _len6 = arguments.length, keys = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
keys[_key6] = arguments[_key6];
}
(0, _forEach.default)(keys).call(keys, key => {
if ((0, _isArray.default)(key)) {
var _context10;
this._select = (0, _concat.default)(_context10 = this._select).call(_context10, key);
} else {
this._select.push(key);
}
});
return this;
}
/**
* Restricts the fields of the returned Parse.Objects to all keys except the
* provided keys. Exclude takes precedence over select and include.
*
* Requires Parse Server 3.6.0+
*
* @param {...string|Array} keys The name(s) of the key(s) to exclude.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
exclude() {
for (var _len7 = arguments.length, keys = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
keys[_key7] = arguments[_key7];
}
(0, _forEach.default)(keys).call(keys, key => {
if ((0, _isArray.default)(key)) {
var _context11;
this._exclude = (0, _concat.default)(_context11 = this._exclude).call(_context11, key);
} else {
this._exclude.push(key);
}
});
return this;
}
/**
* Restricts live query to trigger only for watched fields.
*
* Requires Parse Server 6.0.0+
*
* @param {...string|Array} keys The name(s) of the key(s) to watch.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
watch() {
for (var _len8 = arguments.length, keys = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
keys[_key8] = arguments[_key8];
}
(0, _forEach.default)(keys).call(keys, key => {
if ((0, _isArray.default)(key)) {
var _context12;
this._watch = (0, _concat.default)(_context12 = this._watch).call(_context12, key);
} else {
this._watch.push(key);
}
});
return this;
}
/**
* Changes the read preference that the backend will use when performing the query to the database.
*
* @param {string} readPreference The read preference for the main query.
* @param {string} includeReadPreference The read preference for the queries to include pointers.
* @param {string} subqueryReadPreference The read preference for the sub queries.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
readPreference(readPreference, includeReadPreference, subqueryReadPreference) {
this._readPreference = readPreference;
this._includeReadPreference = includeReadPreference || null;
this._subqueryReadPreference = subqueryReadPreference || null;
return this;
}
/**
* Subscribe this query to get liveQuery updates
*
* @param {string} sessionToken (optional) Defaults to the currentUser
* @returns {Promise} Returns the liveQuerySubscription, it's an event emitter
* which can be used to get liveQuery updates.
*/
async subscribe(sessionToken) {
const currentUser = await _CoreManager.default.getUserController().currentUserAsync();
if (!sessionToken) {
sessionToken = currentUser ? currentUser.getSessionToken() || undefined : undefined;
}
const liveQueryClient = await _CoreManager.default.getLiveQueryController().getDefaultLiveQueryClient();
if (liveQueryClient.shouldOpen()) {
liveQueryClient.open();
}
const subscription = liveQueryClient.subscribe(this, sessionToken);
return subscription.subscribePromise.then(() => {
return subscription;
});
}
/**
* 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() {
for (var _len9 = arguments.length, queries = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
queries[_key9] = arguments[_key9];
}
const className = _getClassNameFromQueries(queries);
const query = new ParseQuery(className);
query._orQuery(queries);
return query;
}
/**
* 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() {
for (var _len10 = arguments.length, queries = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
queries[_key10] = arguments[_key10];
}
const className = _getClassNameFromQueries(queries);
const query = new ParseQuery(className);
query._andQuery(queries);
return query;
}
/**
* 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() {
for (var _len11 = arguments.length, queries = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
queries[_key11] = arguments[_key11];
}
const className = _getClassNameFromQueries(queries);
const query = new ParseQuery(className);
query._norQuery(queries);
return query;
}
/**
* Change the source of this query to the server.
*
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
fromNetwork() {
this._queriesLocalDatastore = false;
this._localDatastorePinName = null;
return this;
}
/**
* Changes the source of this query to all pinned objects.
*
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
fromLocalDatastore() {
return this.fromPinWithName(null);
}
/**
* Changes the source of this query to the default group of pinned objects.
*
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
fromPin() {
return this.fromPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
}
/**
* Changes the source of this query to a specific group of pinned objects.
*
* @param {string} name The name of query source.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
fromPinWithName(name) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (localDatastore.checkIfEnabled()) {
this._queriesLocalDatastore = true;
this._localDatastorePinName = name;
}
return this;
}
/**
* Cancels the current network request (if any is running).
*
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
cancel() {
if (this._xhrRequest.task && typeof this._xhrRequest.task.abort === 'function') {
this._xhrRequest.task._aborted = true;
this._xhrRequest.task.abort();
this._xhrRequest.task = null;
this._xhrRequest.onchange = () => {};
return this;
}
this._xhrRequest.onchange = () => this.cancel();
return this;
}
_setRequestTask(options) {
options.requestTask = task => {
this._xhrRequest.task = task;
this._xhrRequest.onchange();
};
}
/**
* 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.
* @returns {Parse.Query} Returns the query, so you can chain this call.
*/
comment(value) {
if (value == null) {
delete this._comment;
return this;
}
if (typeof value !== 'string') {
throw new Error('The value of a comment to be sent with this query must be a string.');
}
this._comment = value;
return this;
}
}
const DefaultController = {
find(className, params, options) {
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('GET', 'classes/' + className, params, options);
},
aggregate(className, params, options) {
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('GET', 'aggregate/' + className, params, options);
}
};
_CoreManager.default.setParseQuery(ParseQuery);
_CoreManager.default.setQueryController(DefaultController);
var _default = exports.default = ParseQuery;
},{"./CoreManager":4,"./LocalDatastoreUtils":17,"./OfflineQuery":19,"./ParseError":24,"./ParseGeoPoint":26,"./ParseObject":30,"./encode":56,"./promiseUtils":61,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/concat":68,"@babel/runtime-corejs3/core-js-stable/instance/filter":71,"@babel/runtime-corejs3/core-js-stable/instance/find":73,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/instance/includes":75,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/instance/keys":77,"@babel/runtime-corejs3/core-js-stable/instance/map":78,"@babel/runtime-corejs3/core-js-stable/instance/slice":80,"@babel/runtime-corejs3/core-js-stable/instance/sort":81,"@babel/runtime-corejs3/core-js-stable/instance/splice":82,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/entries":91,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],34:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
/**
* Creates a new Relation for the given parent object and key. This
* constructor should rarely be used directly, but rather created by
* Parse.Object.relation.
*
*
* A class that is used to access all of the children of a many-to-many
* relationship. Each instance of Parse.Relation is associated with a
* particular parent object and key.
*
*
* @alias Parse.Relation
*/
class ParseRelation {
/**
* @param {Parse.Object} parent The parent of this relation.
* @param {string} key The key for this relation on the parent.
*/
constructor(parent, key) {
(0, _defineProperty2.default)(this, "parent", void 0);
(0, _defineProperty2.default)(this, "key", void 0);
(0, _defineProperty2.default)(this, "targetClassName", void 0);
this.parent = parent;
this.key = key;
this.targetClassName = null;
}
/*
* Makes sure that this relation has the right parent and key.
*/
_ensureParentAndKey(parent, key) {
this.key = this.key || key;
if (this.key !== key) {
throw new Error('Internal Error. Relation retrieved from two different keys.');
}
if (this.parent) {
if (this.parent.className !== parent.className) {
throw new Error('Internal Error. Relation retrieved from two different Objects.');
}
if (this.parent.id) {
if (this.parent.id !== parent.id) {
throw new Error('Internal Error. Relation retrieved from two different Objects.');
}
} else if (parent.id) {
this.parent = parent;
}
} else {
this.parent = parent;
}
}
/**
* Adds a Parse.Object or an array of Parse.Objects to the relation.
*
* @param {(Parse.Object|Array)} objects The item or items to add.
* @returns {Parse.Object} The parent of the relation.
*/
add(objects) {
if (!(0, _isArray.default)(objects)) {
objects = [objects];
}
const {
RelationOp
} = _CoreManager.default.getParseOp();
const change = new RelationOp(objects, []);
const parent = this.parent;
if (!parent) {
throw new Error('Cannot add to a Relation without a parent');
}
if (objects.length === 0) {
return parent;
}
parent.set(this.key, change);
this.targetClassName = change._targetClassName;
return parent;
}
/**
* Removes a Parse.Object or an array of Parse.Objects from this relation.
*
* @param {(Parse.Object|Array)} objects The item or items to remove.
*/
remove(objects) {
if (!(0, _isArray.default)(objects)) {
objects = [objects];
}
const {
RelationOp
} = _CoreManager.default.getParseOp();
const change = new RelationOp([], objects);
if (!this.parent) {
throw new Error('Cannot remove from a Relation without a parent');
}
if (objects.length === 0) {
return;
}
this.parent.set(this.key, change);
this.targetClassName = change._targetClassName;
}
/**
* Returns a JSON version of the object suitable for saving to disk.
*
* @returns {object} JSON representation of Relation
*/
toJSON() {
return {
__type: 'Relation',
className: this.targetClassName
};
}
/**
* Returns a Parse.Query that is limited to objects in this
* relation.
*
* @returns {Parse.Query} Relation Query
*/
query() {
let query;
const parent = this.parent;
if (!parent) {
throw new Error('Cannot construct a query for a Relation without a parent');
}
const ParseQuery = _CoreManager.default.getParseQuery();
if (!this.targetClassName) {
query = new ParseQuery(parent.className);
query._extraOptions.redirectClassNameForKey = this.key;
} else {
query = new ParseQuery(this.targetClassName);
}
query._addCondition('$relatedTo', 'object', {
__type: 'Pointer',
className: parent.className,
objectId: parent.id
});
query._addCondition('$relatedTo', 'key', this.key);
return query;
}
}
var _default = exports.default = ParseRelation;
},{"./CoreManager":4,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],35:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
/**
* Represents a Role on the Parse server. Roles represent groupings of
* Users for the purposes of granting permissions (e.g. specifying an ACL
* for an Object). Roles are specified by their sets of child users and
* child roles, all of which are granted any permissions that the parent
* role has.
*
* Roles must have a name (which cannot be changed after creation of the
* role), and must specify an ACL.
*
* @alias Parse.Role
* @augments Parse.Object
*/
class ParseRole extends _ParseObject.default {
/**
* @param {string} name The name of the Role to create.
* @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL.
* A Parse.Role is a local representation of a role persisted to the Parse
* cloud.
*/
constructor(name, acl) {
super('_Role');
if (typeof name === 'string' && acl instanceof _ParseACL.default) {
this.setName(name);
this.setACL(acl);
}
}
/**
* Gets the name of the role. You can alternatively call role.get("name")
*
* @returns {string} the name of the role.
*/
getName() {
const name = this.get('name');
if (name == null || typeof name === 'string') {
return name;
}
return '';
}
/**
* Sets the name for a role. This value must be set before the role has
* been saved to the server, and cannot be set once the role has been
* saved.
*
*
* A role's name can only contain alphanumeric characters, _, -, and
* spaces.
*
*
* This is equivalent to calling role.set("name", name)
*
* @param {string} name The name of the role.
* @param {object} options Standard options object with success and error
* callbacks.
* @returns {(ParseObject|boolean)} true if the set succeeded.
*/
setName(name, options) {
this._validateName(name);
return this.set('name', name, options);
}
/**
* Gets the Parse.Relation for the Parse.Users that are direct
* children of this role. These users are granted any privileges that this
* role has been granted (e.g. read or write access through ACLs). You can
* add or remove users from the role through this relation.
*
* This is equivalent to calling role.relation("users")
*
* @returns {Parse.Relation} the relation for the users belonging to this
* role.
*/
getUsers() {
return this.relation('users');
}
/**
* Gets the Parse.Relation for the Parse.Roles that are direct
* children of this role. These roles' users are granted any privileges that
* this role has been granted (e.g. read or write access through ACLs). You
* can add or remove child roles from this role through this relation.
*
* This is equivalent to calling role.relation("roles")
*
* @returns {Parse.Relation} the relation for the roles belonging to this
* role.
*/
getRoles() {
return this.relation('roles');
}
_validateName(newName) {
if (typeof newName !== 'string') {
throw new _ParseError.default(_ParseError.default.OTHER_CAUSE, "A role's name must be a String.");
}
if (!/^[0-9a-zA-Z\-_ ]+$/.test(newName)) {
throw new _ParseError.default(_ParseError.default.OTHER_CAUSE, "A role's name can be only contain alphanumeric characters, _, " + '-, and spaces.');
}
}
validate(attrs, options) {
const isInvalid = super.validate(attrs, options);
if (isInvalid) {
return isInvalid;
}
if ('name' in attrs && attrs.name !== this.getName()) {
const newName = attrs.name;
if (this.id && this.id !== attrs.objectId) {
// Check to see if the objectId being set matches this.id
// This happens during a fetch -- the id is set before calling fetch
// Let the name be set in this case
return new _ParseError.default(_ParseError.default.OTHER_CAUSE, "A role's name can only be set before it has been saved.");
}
try {
this._validateName(newName);
} catch (e) {
return e;
}
}
return false;
}
}
_CoreManager.default.setParseRole(ParseRole);
_ParseObject.default.registerSubclass('_Role', ParseRole);
var _default = exports.default = ParseRole;
},{"./CoreManager":4,"./ParseACL":21,"./ParseError":24,"./ParseObject":30,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],36:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
var _ParseCLP = _interopRequireDefault(_dereq_("./ParseCLP"));
const FIELD_TYPES = ['String', 'Number', 'Boolean', 'Bytes', 'Date', 'File', 'GeoPoint', 'Polygon', 'Array', 'Object', 'Pointer', 'Relation'];
/**
* A Parse.Schema object is for handling schema data from Parse.
* All the schemas methods require MasterKey.
*
* When adding fields, you may set required and default values. (Requires Parse Server 3.7.0+)
*
*
* const options = { required: true, defaultValue: 'hello world' };
* const schema = new Parse.Schema('MyClass');
* schema.addString('field', options);
* schema.addIndex('index_name', { 'field': 1 });
* schema.save();
*
*
*
* @alias Parse.Schema
*/
class ParseSchema {
/**
* @param {string} className Parse Class string.
*/
constructor(className) {
(0, _defineProperty2.default)(this, "className", void 0);
(0, _defineProperty2.default)(this, "_fields", void 0);
(0, _defineProperty2.default)(this, "_indexes", void 0);
(0, _defineProperty2.default)(this, "_clp", void 0);
if (typeof className === 'string') {
if (className === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
this.className = '_User';
} else {
this.className = className;
}
}
this._fields = {};
this._indexes = {};
}
/**
* Static method to get all schemas
*
* @returns {Promise} A promise that is resolved with the result when
* the query completes.
*/
static all() {
const controller = _CoreManager.default.getSchemaController();
return controller.get('').then(response => {
if (response.results.length === 0) {
throw new Error('Schema not found.');
}
return response.results;
});
}
/**
* Get the Schema from Parse
*
* @returns {Promise} A promise that is resolved with the result when
* the query completes.
*/
get() {
this.assertClassName();
const controller = _CoreManager.default.getSchemaController();
return controller.get(this.className).then(response => {
if (!response) {
throw new Error('Schema not found.');
}
return response;
});
}
/**
* Create a new Schema on Parse
*
* @returns {Promise} A promise that is resolved with the result when
* the query completes.
*/
save() {
this.assertClassName();
const controller = _CoreManager.default.getSchemaController();
const params = {
className: this.className,
fields: this._fields,
indexes: this._indexes,
classLevelPermissions: this._clp
};
return controller.create(this.className, params);
}
/**
* Update a Schema on Parse
*
* @returns {Promise} A promise that is resolved with the result when
* the query completes.
*/
update() {
this.assertClassName();
const controller = _CoreManager.default.getSchemaController();
const params = {
className: this.className,
fields: this._fields,
indexes: this._indexes,
classLevelPermissions: this._clp
};
this._fields = {};
this._indexes = {};
return controller.update(this.className, params);
}
/**
* Removing a Schema from Parse
* Can only be used on Schema without objects
*
* @returns {Promise} A promise that is resolved with the result when
* the query completes.
*/
delete() {
this.assertClassName();
const controller = _CoreManager.default.getSchemaController();
return controller.delete(this.className);
}
/**
* Removes all objects from a Schema (class) in Parse.
* EXERCISE CAUTION, running this will delete all objects for this schema and cannot be reversed
*
* @returns {Promise} A promise that is resolved with the result when
* the query completes.
*/
purge() {
this.assertClassName();
const controller = _CoreManager.default.getSchemaController();
return controller.purge(this.className);
}
/**
* Assert if ClassName has been filled
*
* @private
*/
assertClassName() {
if (!this.className) {
throw new Error('You must set a Class Name before making any request.');
}
}
/**
* Sets Class Level Permissions when creating / updating a Schema.
* EXERCISE CAUTION, running this may override CLP for this schema and cannot be reversed
*
* @param {object | Parse.CLP} clp Class Level Permissions
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
setCLP(clp) {
if (clp instanceof _ParseCLP.default) {
this._clp = clp.toJSON();
} else {
this._clp = clp;
}
return this;
}
/**
* Adding a Field to Create / Update a Schema
*
* @param {string} name Name of the field that will be created on Parse
* @param {string} type Can be a (String|Number|Boolean|Date|Parse.File|Parse.GeoPoint|Array|Object|Pointer|Parse.Relation)
* @param {object} options
* Valid options are:
* - required: If field is not set, save operation fails (Requires Parse Server 3.7.0+)
*
- defaultValue: If field is not set, a default value is selected (Requires Parse Server 3.7.0+)
*
- targetClass: Required if type is Pointer or Parse.Relation
*
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addField(name, type) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
type = type || 'String';
if (!name) {
throw new Error('field name may not be null.');
}
if ((0, _indexOf.default)(FIELD_TYPES).call(FIELD_TYPES, type) === -1) {
throw new Error(`${type} is not a valid type.`);
}
if (type === 'Pointer') {
return this.addPointer(name, options.targetClass, options);
}
if (type === 'Relation') {
return this.addRelation(name, options.targetClass);
}
const fieldOptions = {
type
};
if (typeof options.required === 'boolean') {
fieldOptions.required = options.required;
}
if (options.defaultValue !== undefined) {
fieldOptions.defaultValue = options.defaultValue;
}
if (type === 'Date') {
if (options && options.defaultValue) {
fieldOptions.defaultValue = {
__type: 'Date',
iso: new Date(options.defaultValue)
};
}
}
if (type === 'Bytes') {
if (options && options.defaultValue) {
fieldOptions.defaultValue = {
__type: 'Bytes',
base64: options.defaultValue
};
}
}
this._fields[name] = fieldOptions;
return this;
}
/**
* Adding an Index to Create / Update a Schema
*
* @param {string} name Name of the index
* @param {object} index { field: value }
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*
*
* schema.addIndex('index_name', { 'field': 1 });
*
*/
addIndex(name, index) {
if (!name) {
throw new Error('index name may not be null.');
}
if (!index) {
throw new Error('index may not be null.');
}
this._indexes[name] = index;
return this;
}
/**
* Adding String Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addString(name, options) {
return this.addField(name, 'String', options);
}
/**
* Adding Number Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addNumber(name, options) {
return this.addField(name, 'Number', options);
}
/**
* Adding Boolean Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addBoolean(name, options) {
return this.addField(name, 'Boolean', options);
}
/**
* Adding Bytes Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addBytes(name, options) {
return this.addField(name, 'Bytes', options);
}
/**
* Adding Date Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addDate(name, options) {
return this.addField(name, 'Date', options);
}
/**
* Adding File Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addFile(name, options) {
return this.addField(name, 'File', options);
}
/**
* Adding GeoPoint Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addGeoPoint(name, options) {
return this.addField(name, 'GeoPoint', options);
}
/**
* Adding Polygon Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addPolygon(name, options) {
return this.addField(name, 'Polygon', options);
}
/**
* Adding Array Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addArray(name, options) {
return this.addField(name, 'Array', options);
}
/**
* Adding Object Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addObject(name, options) {
return this.addField(name, 'Object', options);
}
/**
* Adding Pointer Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {string} targetClass Name of the target Pointer Class
* @param {object} options See {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.Schema.html#addField addField}
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addPointer(name, targetClass) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (!name) {
throw new Error('field name may not be null.');
}
if (!targetClass) {
throw new Error('You need to set the targetClass of the Pointer.');
}
const fieldOptions = {
type: 'Pointer',
targetClass
};
if (typeof options.required === 'boolean') {
fieldOptions.required = options.required;
}
if (options.defaultValue !== undefined) {
fieldOptions.defaultValue = options.defaultValue;
if (options.defaultValue instanceof _ParseObject.default) {
fieldOptions.defaultValue = options.defaultValue.toPointer();
}
}
this._fields[name] = fieldOptions;
return this;
}
/**
* Adding Relation Field
*
* @param {string} name Name of the field that will be created on Parse
* @param {string} targetClass Name of the target Pointer Class
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
addRelation(name, targetClass) {
if (!name) {
throw new Error('field name may not be null.');
}
if (!targetClass) {
throw new Error('You need to set the targetClass of the Relation.');
}
this._fields[name] = {
type: 'Relation',
targetClass
};
return this;
}
/**
* Deleting a Field to Update on a Schema
*
* @param {string} name Name of the field
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
deleteField(name) {
this._fields[name] = {
__op: 'Delete'
};
return this;
}
/**
* Deleting an Index to Update on a Schema
*
* @param {string} name Name of the field
* @returns {Parse.Schema} Returns the schema, so you can chain this call.
*/
deleteIndex(name) {
this._indexes[name] = {
__op: 'Delete'
};
return this;
}
}
const DefaultController = {
send(className, method) {
let params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request(method, `schemas/${className}`, params, {
useMasterKey: true
});
},
get(className) {
return this.send(className, 'GET');
},
create(className, params) {
return this.send(className, 'POST', params);
},
update(className, params) {
return this.send(className, 'PUT', params);
},
delete(className) {
return this.send(className, 'DELETE');
},
purge(className) {
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('DELETE', `purge/${className}`, {}, {
useMasterKey: true
});
}
};
_CoreManager.default.setSchemaController(DefaultController);
var _default = exports.default = ParseSchema;
},{"./CoreManager":4,"./ParseCLP":22,"./ParseObject":30,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],37:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _isRevocableSession = _interopRequireDefault(_dereq_("./isRevocableSession"));
var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
/**
* A Parse.Session object is a local representation of a revocable session.
* This class is a subclass of a Parse.Object, and retains the same
* functionality of a Parse.Object.
*
* @alias Parse.Session
* @augments Parse.Object
*/
class ParseSession extends _ParseObject.default {
/**
* @param {object} attributes The initial set of data to store in the user.
*/
constructor(attributes) {
super('_Session');
if (attributes && typeof attributes === 'object') {
if (!this.set(attributes || {})) {
throw new Error("Can't create an invalid Session");
}
}
}
/**
* Returns the session token string.
*
* @returns {string}
*/
getSessionToken() {
const token = this.get('sessionToken');
if (typeof token === 'string') {
return token;
}
return '';
}
static readOnlyAttributes() {
return ['createdWith', 'expiresAt', 'installationId', 'restricted', 'sessionToken', 'user'];
}
/**
* Retrieves the Session object for the currently logged in session.
*
* @param {object} options useMasterKey
* @static
* @returns {Promise} A promise that is resolved with the Parse.Session
* object after it has been fetched. If there is no current user, the
* promise will be rejected.
*/
static current(options) {
options = options || {};
const controller = _CoreManager.default.getSessionController();
const sessionOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
sessionOptions.useMasterKey = options.useMasterKey;
}
return _ParseUser.default.currentAsync().then(user => {
if (!user) {
return _promise.default.reject('There is no current user.');
}
sessionOptions.sessionToken = user.getSessionToken();
return controller.getSession(sessionOptions);
});
}
/**
* Determines whether the current session token is revocable.
* This method is useful for migrating Express.js or Node.js web apps to
* use revocable sessions. If you are migrating an app that uses the Parse
* SDK in the browser only, please use Parse.User.enableRevocableSession()
* instead, so that sessions can be automatically upgraded.
*
* @static
* @returns {boolean}
*/
static isCurrentSessionRevocable() {
const currentUser = _ParseUser.default.current();
if (currentUser) {
return (0, _isRevocableSession.default)(currentUser.getSessionToken() || '');
}
return false;
}
}
_ParseObject.default.registerSubclass('_Session', ParseSession);
const DefaultController = {
getSession(options) {
const RESTController = _CoreManager.default.getRESTController();
const session = new ParseSession();
return RESTController.request('GET', 'sessions/me', {}, options).then(sessionData => {
session._finishFetch(sessionData);
session._setExisted(true);
return session;
});
}
};
_CoreManager.default.setSessionController(DefaultController);
var _default = exports.default = ParseSession;
},{"./CoreManager":4,"./ParseObject":30,"./ParseUser":38,"./isRevocableSession":59,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],38:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty2 = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty2(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _defineProperty = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property"));
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _isRevocableSession = _interopRequireDefault(_dereq_("./isRevocableSession"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
var _Storage = _interopRequireDefault(_dereq_("./Storage"));
const CURRENT_USER_KEY = 'currentUser';
let canUseCurrentUser = !_CoreManager.default.get('IS_NODE');
let currentUserCacheMatchesDisk = false;
let currentUserCache = null;
const authProviders = {};
/**
* A Parse.User object is a local representation of a user persisted to the
* Parse cloud. This class is a subclass of a Parse.Object, and retains the
* same functionality of a Parse.Object, but also extends it with various
* user specific methods, like authentication, signing up, and validation of
* uniqueness.
*
* @alias Parse.User
* @augments Parse.Object
*/
class ParseUser extends _ParseObject.default {
/**
* @param {object} attributes The initial set of data to store in the user.
*/
constructor(attributes) {
super('_User');
if (attributes && typeof attributes === 'object') {
if (!this.set(attributes || {})) {
throw new Error("Can't create an invalid Parse User");
}
}
}
/**
* 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) {
options = options || {};
const upgradeOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
upgradeOptions.useMasterKey = options.useMasterKey;
}
const controller = _CoreManager.default.getUserController();
return controller.upgradeToRevocableSession(this, upgradeOptions);
}
/**
* 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
* @param {object} [options.authData] AuthData to link with
*
* - 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, options) {
let saveOpts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
saveOpts.sessionToken = saveOpts.sessionToken || this.getSessionToken() || '';
let authType;
if (typeof provider === 'string') {
authType = provider;
if (authProviders[provider]) {
provider = authProviders[provider];
} else {
const authProvider = {
restoreAuthentication() {
return true;
},
getAuthType() {
return authType;
}
};
authProviders[authProvider.getAuthType()] = authProvider;
provider = authProvider;
}
} else {
authType = provider.getAuthType();
}
if (options && options.hasOwnProperty('authData')) {
const authData = this.get('authData') || {};
if (typeof authData !== 'object') {
throw new Error('Invalid type: authData field should be an object');
}
authData[authType] = options.authData;
const oldAnonymousData = authData.anonymous;
this.stripAnonymity();
const controller = _CoreManager.default.getUserController();
return controller.linkWith(this, authData, saveOpts).catch(e => {
delete authData[authType];
this.restoreAnonimity(oldAnonymousData);
throw e;
});
} else {
return new _promise.default((resolve, reject) => {
provider.authenticate({
success: (provider, result) => {
const opts = {};
opts.authData = result;
this.linkWith(provider, opts, saveOpts).then(() => {
resolve(this);
}, error => {
reject(error);
});
},
error: (provider, error) => {
reject(error);
}
});
});
}
}
/**
* @param provider
* @param options
* @param {object} [options.authData]
* @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, options) {
let saveOpts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
return this.linkWith(provider, options, saveOpts);
}
/**
* 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) {
if (!this.isCurrent() || !provider) {
return;
}
let authType;
if (typeof provider === 'string') {
authType = provider;
provider = authProviders[authType];
} else {
authType = provider.getAuthType();
}
const authData = this.get('authData');
if (!provider || !authData || typeof authData !== 'object') {
return;
}
const success = provider.restoreAuthentication(authData[authType]);
if (!success) {
this._unlinkFrom(provider);
}
}
/**
* Synchronizes authData for all providers.
*/
_synchronizeAllAuthData() {
const authData = this.get('authData');
if (typeof authData !== 'object') {
return;
}
for (const key in authData) {
this._synchronizeAuthData(key);
}
}
/**
* Removes null values from authData (which exist temporarily for unlinking)
*/
_cleanupAuthData() {
if (!this.isCurrent()) {
return;
}
const authData = this.get('authData');
if (typeof authData !== 'object') {
return;
}
for (const key in authData) {
if (!authData[key]) {
delete authData[key];
}
}
}
/**
* 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, options) {
return this.linkWith(provider, {
authData: null
}, options).then(() => {
this._synchronizeAuthData(provider);
return _promise.default.resolve(this);
});
}
/**
* 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) {
let authType;
if (typeof provider === 'string') {
authType = provider;
} else {
authType = provider.getAuthType();
}
const authData = this.get('authData') || {};
if (typeof authData !== 'object') {
return false;
}
return !!authData[authType];
}
/**
* Deauthenticates all providers.
*/
_logOutWithAll() {
const authData = this.get('authData');
if (typeof authData !== 'object') {
return;
}
for (const key in authData) {
this._logOutWith(key);
}
}
/**
* Deauthenticates a single provider (e.g. removing access tokens from the
* Facebook SDK).
*
* @param {object} provider service to logout of
*/
_logOutWith(provider) {
if (!this.isCurrent()) {
return;
}
if (typeof provider === 'string') {
provider = authProviders[provider];
}
if (provider && provider.deauthenticate) {
provider.deauthenticate();
}
}
/**
* 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() {
return {
sessionToken: this.get('sessionToken')
};
}
/**
* Returns true if current
would return this user.
*
* @returns {boolean} true if user is cached on disk
*/
isCurrent() {
const current = ParseUser.current();
return !!current && current.id === this.id;
}
/**
* Returns true if current
would return this user.
*
* @returns {Promise} true if user is cached on disk
*/
async isCurrentAsync() {
const current = await ParseUser.currentAsync();
return !!current && current.id === this.id;
}
stripAnonymity() {
const authData = this.get('authData');
if (authData && typeof authData === 'object' && authData.hasOwnProperty('anonymous')) {
// We need to set anonymous to null instead of deleting it in order to remove it from Parse.
authData.anonymous = null;
}
}
restoreAnonimity(anonymousData) {
if (anonymousData) {
const authData = this.get('authData');
authData.anonymous = anonymousData;
}
}
/**
* Returns get("username").
*
* @returns {string}
*/
getUsername() {
const username = this.get('username');
if (username == null || typeof username === 'string') {
return username;
}
return '';
}
/**
* Calls set("username", username, options) and returns the result.
*
* @param {string} username
*/
setUsername(username) {
this.stripAnonymity();
this.set('username', username);
}
/**
* Calls set("password", password, options) and returns the result.
*
* @param {string} password User's Password
*/
setPassword(password) {
this.set('password', password);
}
/**
* Returns get("email").
*
* @returns {string} User's Email
*/
getEmail() {
const email = this.get('email');
if (email == null || typeof email === 'string') {
return email;
}
return '';
}
/**
* Calls set("email", email) and returns the result.
*
* @param {string} email
* @returns {boolean}
*/
setEmail(email) {
return this.set('email', email);
}
/**
* 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() {
const token = this.get('sessionToken');
if (token == null || typeof token === 'string') {
return token;
}
return '';
}
/**
* 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() {
const current = ParseUser.current();
return !!this.get('sessionToken') && !!current && current.id === this.id;
}
/**
* 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, options) {
options = options || {};
const signupOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
signupOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('installationId')) {
signupOptions.installationId = options.installationId;
}
if (options.hasOwnProperty('context') && Object.prototype.toString.call(options.context) === '[object Object]') {
signupOptions.context = options.context;
}
const controller = _CoreManager.default.getUserController();
return controller.signUp(this, attrs, signupOptions);
}
/**
* 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() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
options = options || {};
const loginOptions = {
usePost: true
};
if (options.hasOwnProperty('useMasterKey')) {
loginOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('installationId')) {
loginOptions.installationId = options.installationId;
}
if (options.hasOwnProperty('usePost')) {
loginOptions.usePost = options.usePost;
}
if (options.hasOwnProperty('context') && Object.prototype.toString.call(options.context) === '[object Object]') {
loginOptions.context = options.context;
}
const controller = _CoreManager.default.getUserController();
return controller.logIn(this, loginOptions);
}
/**
* Wrap the default save behavior with functionality to save to local
* storage if this is current user.
*
* @param {...any} args
* @returns {Promise}
*/
async save() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
await super.save.apply(this, args);
const current = await this.isCurrentAsync();
if (current) {
return _CoreManager.default.getUserController().updateUserOnDisk(this);
}
return this;
}
/**
* Wrap the default destroy behavior with functionality that logs out
* the current user when it is destroyed
*
* @param {...any} args
* @returns {Parse.User}
*/
async destroy() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
await super.destroy.apply(this, args);
const current = await this.isCurrentAsync();
if (current) {
return _CoreManager.default.getUserController().removeUserFromDisk();
}
return this;
}
/**
* Wrap the default fetch behavior with functionality to save to local
* storage if this is current user.
*
* @param {...any} args
* @returns {Parse.User}
*/
async fetch() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
await super.fetch.apply(this, args);
const current = await this.isCurrentAsync();
if (current) {
return _CoreManager.default.getUserController().updateUserOnDisk(this);
}
return this;
}
/**
* Wrap the default fetchWithInclude behavior with functionality to save to local
* storage if this is current user.
*
* @param {...any} args
* @returns {Parse.User}
*/
async fetchWithInclude() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
await super.fetchWithInclude.apply(this, args);
const current = await this.isCurrentAsync();
if (current) {
return _CoreManager.default.getUserController().updateUserOnDisk(this);
}
return this;
}
/**
* 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] 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, options) {
const username = this.getUsername() || '';
return ParseUser.verifyPassword(username, password, options);
}
static readOnlyAttributes() {
return ['sessionToken'];
}
/**
* Adds functionality to the existing Parse.User class.
*
* @param {object} protoProps A set of properties to add to the prototype
* @param {object} classProps A set of static properties to add to the class
* @static
* @returns {Parse.User} The newly extended Parse.User class
*/
static extend(protoProps, classProps) {
if (protoProps) {
for (const prop in protoProps) {
if (prop !== 'className') {
(0, _defineProperty.default)(ParseUser.prototype, prop, {
value: protoProps[prop],
enumerable: false,
writable: true,
configurable: true
});
}
}
}
if (classProps) {
for (const prop in classProps) {
if (prop !== 'className') {
(0, _defineProperty.default)(ParseUser, prop, {
value: classProps[prop],
enumerable: false,
writable: true,
configurable: true
});
}
}
}
return ParseUser;
}
/**
* Retrieves the currently logged in ParseUser with a valid session,
* either from memory or localStorage, if necessary.
*
* @static
* @returns {Parse.Object} The currently logged in Parse.User.
*/
static current() {
if (!canUseCurrentUser) {
return null;
}
const controller = _CoreManager.default.getUserController();
return controller.currentUser();
}
/**
* Retrieves the currently logged in ParseUser from asynchronous Storage.
*
* @static
* @returns {Promise} A Promise that is resolved with the currently
* logged in Parse User
*/
static currentAsync() {
if (!canUseCurrentUser) {
return _promise.default.resolve(null);
}
const controller = _CoreManager.default.getUserController();
return controller.currentUserAsync();
}
/**
* Signs up a new user with a username (or email) and password.
* This will create a new Parse.User on the server, and also persist the
* session in localStorage so that you can access the user using
* {@link #current}.
*
* @param {string} username The username (or email) to sign up with.
* @param {string} password The password to sign up with.
* @param {object} attrs Extra fields to set on the new user.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the signup completes.
*/
static signUp(username, password, attrs, options) {
attrs = attrs || {};
attrs.username = username;
attrs.password = password;
const user = new this(attrs);
return user.signUp({}, options);
}
/**
* 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
* user using current
.
*
* @param {string} username The username (or email) to log in with.
* @param {string} password The password to log in with.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the login completes.
*/
static logIn(username, password, options) {
if (typeof username !== 'string') {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Username must be a string.'));
} else if (typeof password !== 'string') {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Password must be a string.'));
}
const user = new this();
user._finishFetch({
username: username,
password: password
});
return user.logIn(options);
}
/**
* 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
* user using current
.
*
* @param {string} username The username (or email) to log in with.
* @param {string} password The password to log in with.
* @param {object} authData The authData to log in with.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the login completes.
*/
static logInWithAdditionalAuth(username, password, authData, options) {
if (typeof username !== 'string') {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Username must be a string.'));
}
if (typeof password !== 'string') {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Password must be a string.'));
}
if (Object.prototype.toString.call(authData) !== '[object Object]') {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Auth must be an object.'));
}
const user = new this();
user._finishFetch({
username: username,
password: password,
authData
});
return user.logIn(options);
}
/**
* 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
* current
.
*
* @param {string} userId The objectId for the user.
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the login completes.
*/
static loginAs(userId) {
if (!userId) {
throw new _ParseError.default(_ParseError.default.USERNAME_MISSING, 'Cannot log in as user with an empty user id');
}
const controller = _CoreManager.default.getUserController();
const user = new this();
return controller.loginAs(user, userId);
}
/**
* 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
* current
.
*
* @param {string} sessionToken The sessionToken to log in with.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the login completes.
*/
static become(sessionToken, options) {
if (!canUseCurrentUser) {
throw new Error('It is not memory-safe to become a user in a server environment');
}
options = options || {};
const becomeOptions = {
sessionToken: sessionToken
};
if (options.hasOwnProperty('useMasterKey')) {
becomeOptions.useMasterKey = options.useMasterKey;
}
const controller = _CoreManager.default.getUserController();
const user = new this();
return controller.become(user, becomeOptions);
}
/**
* Retrieves a user with a session token.
*
* @param {string} sessionToken The sessionToken to get user with.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with the user is fetched.
*/
static me(sessionToken) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const controller = _CoreManager.default.getUserController();
const meOptions = {
sessionToken: sessionToken
};
if (options.useMasterKey) {
meOptions.useMasterKey = options.useMasterKey;
}
const user = new this();
return controller.me(user, meOptions);
}
/**
* 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
* current
. If there is no session token the user will not logged in.
*
* @param {object} userJSON The JSON map of the User's data
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the login completes.
*/
static hydrate(userJSON) {
const controller = _CoreManager.default.getUserController();
const user = new this();
return controller.hydrate(user, userJSON);
}
/**
* Static version of {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith}
*
* @param provider
* @param options
* @param {object} [options.authData]
* @param saveOpts
* @static
* @returns {Promise}
*/
static logInWith(provider, options, saveOpts) {
const user = new this();
return user.linkWith(provider, options, saveOpts);
}
/**
* Logs out the currently logged in user session. This will remove the
* session from disk, log out of linked services, and future calls to
* current
will return null
.
*
* @param {object} options
* @static
* @returns {Promise} A promise that is resolved when the session is
* destroyed on the server.
*/
static logOut() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const controller = _CoreManager.default.getUserController();
return controller.logOut(options);
}
/**
* 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
* reset their password on the Parse site.
*
* @param {string} email The email address associated with the user that
* forgot their password.
* @param {object} options
* @static
* @returns {Promise}
*/
static requestPasswordReset(email, options) {
options = options || {};
const requestOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
requestOptions.useMasterKey = options.useMasterKey;
}
const controller = _CoreManager.default.getUserController();
return controller.requestPasswordReset(email, requestOptions);
}
/**
* Request an email verification.
*
* @param {string} email The email address associated with the user that
* needs to verify their email.
* @param {object} options
* @static
* @returns {Promise}
*/
static requestEmailVerification(email, options) {
options = options || {};
const requestOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
requestOptions.useMasterKey = options.useMasterKey;
}
const controller = _CoreManager.default.getUserController();
return controller.requestEmailVerification(email, requestOptions);
}
/**
* Verify whether a given password is the password of the current user.
* @static
*
* @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] 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, password, options) {
if (typeof username !== 'string') {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Username must be a string.'));
}
if (typeof password !== 'string') {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Password must be a string.'));
}
const controller = _CoreManager.default.getUserController();
return controller.verifyPassword(username, password, options || {});
}
/**
* Allow someone to define a custom User class without className
* being rewritten to _User. The default behavior is to rewrite
* User to _User for legacy reasons. This allows developers to
* override that behavior.
*
* @param {boolean} isAllowed Whether or not to allow custom User class
* @static
*/
static allowCustomUserClass(isAllowed) {
_CoreManager.default.set('PERFORM_USER_REWRITE', !isAllowed);
}
/**
* Allows a legacy application to start using revocable sessions. If the
* current session token is not revocable, a request will be made for a new,
* revocable session.
* It is not necessary to call this method from cloud code unless you are
* handling user signup or login from the server side. In a cloud code call,
* this function will not attempt to upgrade the current token.
*
* @param {object} options
* @static
* @returns {Promise} A promise that is resolved when the process has
* completed. If a replacement session token is requested, the promise
* will be resolved after a new token has been fetched.
*/
static enableRevocableSession(options) {
options = options || {};
_CoreManager.default.set('FORCE_REVOCABLE_SESSION', true);
if (canUseCurrentUser) {
const current = ParseUser.current();
if (current) {
return current._upgradeToRevocableSession(options);
}
}
return _promise.default.resolve();
}
/**
* Enables the use of become or the current user in a server
* environment. These features are disabled by default, since they depend on
* global objects that are not memory-safe for most servers.
*
* @static
*/
static enableUnsafeCurrentUser() {
canUseCurrentUser = true;
}
/**
* Disables the use of become or the current user in any environment.
* These features are disabled on servers by default, since they depend on
* global objects that are not memory-safe for most servers.
*
* @static
*/
static disableUnsafeCurrentUser() {
canUseCurrentUser = false;
}
/**
* When registering users with {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} a basic auth provider
* is automatically created for you.
*
* For advanced authentication, you can register an Auth provider to
* implement custom authentication, deauthentication.
*
* @param provider
* @see {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider}
* @see {@link https://docs.parseplatform.org/js/guide/#custom-authentication-module Custom Authentication Module}
* @static
*/
static _registerAuthenticationProvider(provider) {
authProviders[provider.getAuthType()] = provider;
// Synchronize the current user with the auth provider.
ParseUser.currentAsync().then(current => {
if (current) {
current._synchronizeAuthData(provider.getAuthType());
}
});
}
/**
* @param provider
* @param options
* @param {object} [options.authData]
* @param saveOpts
* @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#logInWith logInWith}
* @static
* @returns {Promise}
*/
static _logInWith(provider, options, saveOpts) {
const user = new this();
return user.linkWith(provider, options, saveOpts);
}
static _clearCache() {
currentUserCache = null;
currentUserCacheMatchesDisk = false;
}
static _setCurrentUserCache(user) {
currentUserCache = user;
}
}
_ParseObject.default.registerSubclass('_User', ParseUser);
const DefaultController = {
updateUserOnDisk(user) {
const path = _Storage.default.generatePath(CURRENT_USER_KEY);
const json = user.toJSON();
delete json.password;
json.className = '_User';
let userData = (0, _stringify.default)(json);
if (_CoreManager.default.get('ENCRYPTED_USER')) {
const crypto = _CoreManager.default.getCryptoController();
userData = crypto.encrypt(json, _CoreManager.default.get('ENCRYPTED_KEY'));
}
return _Storage.default.setItemAsync(path, userData).then(() => {
return user;
});
},
removeUserFromDisk() {
const path = _Storage.default.generatePath(CURRENT_USER_KEY);
currentUserCacheMatchesDisk = true;
currentUserCache = null;
return _Storage.default.removeItemAsync(path);
},
setCurrentUser(user) {
currentUserCache = user;
user._cleanupAuthData();
user._synchronizeAllAuthData();
return DefaultController.updateUserOnDisk(user);
},
currentUser() {
if (currentUserCache) {
return currentUserCache;
}
if (currentUserCacheMatchesDisk) {
return null;
}
if (_Storage.default.async()) {
throw new Error('Cannot call currentUser() when using a platform with an async ' + 'storage system. Call currentUserAsync() instead.');
}
const path = _Storage.default.generatePath(CURRENT_USER_KEY);
let userData = _Storage.default.getItem(path);
currentUserCacheMatchesDisk = true;
if (!userData) {
currentUserCache = null;
return null;
}
if (_CoreManager.default.get('ENCRYPTED_USER')) {
const crypto = _CoreManager.default.getCryptoController();
userData = crypto.decrypt(userData, _CoreManager.default.get('ENCRYPTED_KEY'));
}
userData = JSON.parse(userData);
if (!userData.className) {
userData.className = '_User';
}
if (userData._id) {
if (userData.objectId !== userData._id) {
userData.objectId = userData._id;
}
delete userData._id;
}
if (userData._sessionToken) {
userData.sessionToken = userData._sessionToken;
delete userData._sessionToken;
}
const current = _ParseObject.default.fromJSON(userData);
currentUserCache = current;
current._synchronizeAllAuthData();
return current;
},
currentUserAsync() {
if (currentUserCache) {
return _promise.default.resolve(currentUserCache);
}
if (currentUserCacheMatchesDisk) {
return _promise.default.resolve(null);
}
const path = _Storage.default.generatePath(CURRENT_USER_KEY);
return _Storage.default.getItemAsync(path).then(userData => {
currentUserCacheMatchesDisk = true;
if (!userData) {
currentUserCache = null;
return _promise.default.resolve(null);
}
if (_CoreManager.default.get('ENCRYPTED_USER')) {
const crypto = _CoreManager.default.getCryptoController();
userData = crypto.decrypt(userData.toString(), _CoreManager.default.get('ENCRYPTED_KEY'));
}
userData = JSON.parse(userData);
if (!userData.className) {
userData.className = '_User';
}
if (userData._id) {
if (userData.objectId !== userData._id) {
userData.objectId = userData._id;
}
delete userData._id;
}
if (userData._sessionToken) {
userData.sessionToken = userData._sessionToken;
delete userData._sessionToken;
}
const current = _ParseObject.default.fromJSON(userData);
currentUserCache = current;
current._synchronizeAllAuthData();
return _promise.default.resolve(current);
});
},
signUp(user, attrs, options) {
const username = attrs && attrs.username || user.get('username');
const password = attrs && attrs.password || user.get('password');
if (!username || !username.length) {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Cannot sign up user with an empty username.'));
}
if (!password || !password.length) {
return _promise.default.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Cannot sign up user with an empty password.'));
}
return user.save(attrs, options).then(() => {
// Clear the password field
user._finishFetch({
password: undefined
});
if (canUseCurrentUser) {
return DefaultController.setCurrentUser(user);
}
return user;
});
},
logIn(user, options) {
const RESTController = _CoreManager.default.getRESTController();
const stateController = _CoreManager.default.getObjectStateController();
const auth = {
username: user.get('username'),
password: user.get('password'),
authData: user.get('authData')
};
return RESTController.request(options.usePost ? 'POST' : 'GET', 'login', auth, options).then(response => {
user._migrateId(response.objectId);
user._setExisted(true);
stateController.setPendingOp(user._getStateIdentifier(), 'username', undefined);
stateController.setPendingOp(user._getStateIdentifier(), 'password', undefined);
response.password = undefined;
user._finishFetch(response);
if (!canUseCurrentUser) {
// We can't set the current user, so just return the one we logged in
return _promise.default.resolve(user);
}
return DefaultController.setCurrentUser(user);
});
},
loginAs(user, userId) {
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('POST', 'loginAs', {
userId
}, {
useMasterKey: true
}).then(response => {
user._finishFetch(response);
user._setExisted(true);
if (!canUseCurrentUser) {
return _promise.default.resolve(user);
}
return DefaultController.setCurrentUser(user);
});
},
become(user, options) {
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('GET', 'users/me', {}, options).then(response => {
user._finishFetch(response);
user._setExisted(true);
return DefaultController.setCurrentUser(user);
});
},
hydrate(user, userJSON) {
user._finishFetch(userJSON);
user._setExisted(true);
if (userJSON.sessionToken && canUseCurrentUser) {
return DefaultController.setCurrentUser(user);
} else {
return _promise.default.resolve(user);
}
},
me(user, options) {
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('GET', 'users/me', {}, options).then(response => {
user._finishFetch(response);
user._setExisted(true);
return user;
});
},
logOut(options) {
const RESTController = _CoreManager.default.getRESTController();
if (options.sessionToken) {
return RESTController.request('POST', 'logout', {}, options);
}
return DefaultController.currentUserAsync().then(currentUser => {
const path = _Storage.default.generatePath(CURRENT_USER_KEY);
let promise = _Storage.default.removeItemAsync(path);
if (currentUser !== null) {
const currentSession = currentUser.getSessionToken();
if (currentSession && (0, _isRevocableSession.default)(currentSession)) {
promise = promise.then(() => {
return RESTController.request('POST', 'logout', {}, {
sessionToken: currentSession
});
});
}
currentUser._logOutWithAll();
currentUser._finishFetch({
sessionToken: undefined
});
}
currentUserCacheMatchesDisk = true;
currentUserCache = null;
return promise;
});
},
requestPasswordReset(email, options) {
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('POST', 'requestPasswordReset', {
email: email
}, options);
},
async upgradeToRevocableSession(user, options) {
const token = user.getSessionToken();
if (!token) {
return _promise.default.reject(new _ParseError.default(_ParseError.default.SESSION_MISSING, 'Cannot upgrade a user with no session token'));
}
options.sessionToken = token;
const RESTController = _CoreManager.default.getRESTController();
const result = await RESTController.request('POST', 'upgradeToRevocableSession', {}, options);
user._finishFetch({
sessionToken: result?.sessionToken || ''
});
const current = await user.isCurrentAsync();
if (current) {
return DefaultController.setCurrentUser(user);
}
return _promise.default.resolve(user);
},
linkWith(user, authData, options) {
return user.save({
authData
}, options).then(() => {
if (canUseCurrentUser) {
return DefaultController.setCurrentUser(user);
}
return user;
});
},
verifyPassword(username, password, options) {
const RESTController = _CoreManager.default.getRESTController();
const data = {
username,
password,
...(options.ignoreEmailVerification !== undefined && {
ignoreEmailVerification: options.ignoreEmailVerification
})
};
return RESTController.request('GET', 'verifyPassword', data, options);
},
requestEmailVerification(email, options) {
const RESTController = _CoreManager.default.getRESTController();
return RESTController.request('POST', 'verificationEmailRequest', {
email: email
}, options);
}
};
_CoreManager.default.setParseUser(ParseUser);
_CoreManager.default.setUserController(DefaultController);
var _default = exports.default = ParseUser;
},{"./CoreManager":4,"./ParseError":24,"./ParseObject":30,"./Storage":43,"./isRevocableSession":59,"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],39:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.getPushStatus = getPushStatus;
exports.send = send;
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
/**
* Contains functions to deal with Push in Parse.
*
* @class Parse.Push
* @static
* @hideconstructor
*/
/**
* Sends a push notification.
* **Available in Cloud Code only.**
*
* See {@link https://docs.parseplatform.org/js/guide/#push-notifications Push Notification Guide}
*
* @function send
* @name Parse.Push.send
* @param {object} data - The data of the push notification. Valid fields
* are:
*
* - channels - An Array of channels to push to.
* - push_time - A Date object for when to send the push.
* - expiration_time - A Date object for when to expire
* the push.
* - expiration_interval - The seconds from now to expire the push.
* - where - A Parse.Query over Parse.Installation that is used to match
* a set of installations to push to.
* - data - The data to send as part of the push.
*
* @param {object} options Valid options
* are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
* @returns {Promise} A promise that is fulfilled when the push request
* completes and returns `pushStatusId`.
*/
function send(data) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (data.where && data.where instanceof _ParseQuery.default) {
data.where = data.where.toJSON().where;
}
if (data.push_time && typeof data.push_time === 'object') {
data.push_time = data.push_time.toJSON();
}
if (data.expiration_time && typeof data.expiration_time === 'object') {
data.expiration_time = data.expiration_time.toJSON();
}
if (data.expiration_time && data.expiration_interval) {
throw new Error('expiration_time and expiration_interval cannot both be set.');
}
const pushOptions = {
useMasterKey: true
};
if (options.hasOwnProperty('useMasterKey')) {
pushOptions.useMasterKey = options.useMasterKey;
}
return _CoreManager.default.getPushController().send(data, pushOptions);
}
/**
* Gets push status by Id
*
* @function getPushStatus
* @name Parse.Push.getPushStatus
* @param {string} pushStatusId The Id of Push Status.
* @param {object} options Valid options
* are:
* - useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
*
* @returns {Parse.Object} Status of Push.
*/
function getPushStatus(pushStatusId) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const pushOptions = {
useMasterKey: true
};
if (options.hasOwnProperty('useMasterKey')) {
pushOptions.useMasterKey = options.useMasterKey;
}
const query = new _ParseQuery.default('_PushStatus');
return query.get(pushStatusId, pushOptions);
}
const DefaultController = {
async send(data, options) {
options.returnStatus = true;
const response = await _CoreManager.default.getRESTController().request('POST', 'push', data, options);
return response._headers?.['X-Parse-Push-Status-Id'];
}
};
_CoreManager.default.setPushController(DefaultController);
},{"./CoreManager":4,"./ParseQuery":33,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],40:[function(_dereq_,module,exports){
(function (process){(function (){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _includes = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/includes"));
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _setTimeout2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/set-timeout"));
var _uuid = _interopRequireDefault(_dereq_("./uuid"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
var _promiseUtils = _dereq_("./promiseUtils");
var _Xhr = _interopRequireDefault(_dereq_("./Xhr.weapp"));
/* global XMLHttpRequest, XDomainRequest */
let XHR = null;
if (typeof XMLHttpRequest !== 'undefined') {
XHR = XMLHttpRequest;
}
XHR = _Xhr.default;
let useXDomainRequest = false;
// @ts-ignore
if (typeof XDomainRequest !== 'undefined' && !('withCredentials' in new XMLHttpRequest())) {
useXDomainRequest = true;
}
function ajaxIE9(method, url, data, headers, options) {
return new _promise.default((resolve, reject) => {
// @ts-ignore
const xdr = new XDomainRequest();
xdr.onload = function () {
let response;
try {
response = JSON.parse(xdr.responseText);
} catch (e) {
reject(e);
}
if (response) {
resolve({
response
});
}
};
xdr.onerror = xdr.ontimeout = function () {
// Let's fake a real error message.
const fakeResponse = {
responseText: (0, _stringify.default)({
code: _ParseError.default.X_DOMAIN_REQUEST,
error: "IE's XDomainRequest does not supply error info."
})
};
reject(fakeResponse);
};
xdr.onprogress = function () {
if (options && typeof options.progress === 'function') {
options.progress(xdr.responseText);
}
};
xdr.open(method, url);
xdr.send(data);
// @ts-ignore
if (options && typeof options.requestTask === 'function') {
// @ts-ignore
options.requestTask(xdr);
}
});
}
const RESTController = {
ajax(method, url, data, headers, options) {
var _context;
if (useXDomainRequest) {
return ajaxIE9(method, url, data, headers, options);
}
const promise = (0, _promiseUtils.resolvingPromise)();
const isIdempotent = _CoreManager.default.get('IDEMPOTENCY') && (0, _includes.default)(_context = ['POST', 'PUT']).call(_context, method);
const requestId = isIdempotent ? (0, _uuid.default)() : '';
let attempts = 0;
const dispatch = function () {
if (XHR == null) {
throw new Error('Cannot make a request: No definition of XMLHttpRequest was found.');
}
let handled = false;
const xhr = new XHR();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4 || handled || xhr._aborted) {
return;
}
handled = true;
if (xhr.status >= 200 && xhr.status < 300) {
let response;
try {
response = JSON.parse(xhr.responseText);
const availableHeaders = typeof xhr.getAllResponseHeaders === 'function' ? xhr.getAllResponseHeaders() : '';
headers = {};
if (typeof xhr.getResponseHeader === 'function' && availableHeaders?.indexOf('access-control-expose-headers') >= 0) {
const responseHeaders = xhr.getResponseHeader('access-control-expose-headers').split(', ');
(0, _forEach.default)(responseHeaders).call(responseHeaders, header => {
if ((0, _indexOf.default)(availableHeaders).call(availableHeaders, header.toLowerCase()) >= 0) {
headers[header] = xhr.getResponseHeader(header.toLowerCase());
}
});
}
} catch (e) {
promise.reject(e.toString());
}
if (response) {
promise.resolve({
response,
headers,
status: xhr.status,
xhr
});
}
} else if (xhr.status >= 500 || xhr.status === 0) {
// retry on 5XX or node-xmlhttprequest error
if (++attempts < _CoreManager.default.get('REQUEST_ATTEMPT_LIMIT')) {
// Exponentially-growing random delay
const delay = Math.round(Math.random() * 125 * Math.pow(2, attempts));
(0, _setTimeout2.default)(dispatch, delay);
} else if (xhr.status === 0) {
promise.reject('Unable to connect to the Parse API');
} else {
// After the retry limit is reached, fail
promise.reject(xhr);
}
} else {
promise.reject(xhr);
}
};
headers = headers || {};
if (typeof headers['Content-Type'] !== 'string') {
headers['Content-Type'] = 'text/plain'; // Avoid pre-flight
}
if (_CoreManager.default.get('IS_NODE')) {
headers['User-Agent'] = 'Parse/' + _CoreManager.default.get('VERSION') + ' (NodeJS ' + process.versions.node + ')';
}
if (isIdempotent) {
headers['X-Parse-Request-Id'] = requestId;
}
if (_CoreManager.default.get('SERVER_AUTH_TYPE') && _CoreManager.default.get('SERVER_AUTH_TOKEN')) {
headers['Authorization'] = _CoreManager.default.get('SERVER_AUTH_TYPE') + ' ' + _CoreManager.default.get('SERVER_AUTH_TOKEN');
}
const customHeaders = _CoreManager.default.get('REQUEST_HEADERS');
for (const key in customHeaders) {
headers[key] = customHeaders[key];
}
if (options && typeof options.progress === 'function') {
const handleProgress = function (type, event) {
if (event.lengthComputable) {
options.progress(event.loaded / event.total, event.loaded, event.total, {
type
});
} else {
options.progress(null, null, null, {
type
});
}
};
xhr.onprogress = event => {
handleProgress('download', event);
};
if (xhr.upload) {
xhr.upload.onprogress = event => {
handleProgress('upload', event);
};
}
}
xhr.open(method, url, true);
for (const h in headers) {
xhr.setRequestHeader(h, headers[h]);
}
xhr.onabort = function () {
promise.resolve({
response: {
results: []
},
status: 0,
xhr
});
};
xhr.send(data);
// @ts-ignore
if (options && typeof options.requestTask === 'function') {
// @ts-ignore
options.requestTask(xhr);
}
};
dispatch();
return promise;
},
request(method, path, data, options) {
options = options || {};
let url = _CoreManager.default.get('SERVER_URL');
if (url[url.length - 1] !== '/') {
url += '/';
}
url += path;
const payload = {};
if (data && typeof data === 'object') {
for (const k in data) {
payload[k] = data[k];
}
}
// Add context
const context = options.context;
if (context !== undefined) {
payload._context = context;
}
if (method !== 'POST') {
payload._method = method;
method = 'POST';
}
payload._ApplicationId = _CoreManager.default.get('APPLICATION_ID');
const jsKey = _CoreManager.default.get('JAVASCRIPT_KEY');
if (jsKey) {
payload._JavaScriptKey = jsKey;
}
payload._ClientVersion = _CoreManager.default.get('VERSION');
let useMasterKey = options.useMasterKey;
if (typeof useMasterKey === 'undefined') {
useMasterKey = _CoreManager.default.get('USE_MASTER_KEY');
}
if (useMasterKey) {
if (_CoreManager.default.get('MASTER_KEY')) {
delete payload._JavaScriptKey;
payload._MasterKey = _CoreManager.default.get('MASTER_KEY');
} else {
throw new Error('Cannot use the Master Key, it has not been provided.');
}
}
if (_CoreManager.default.get('FORCE_REVOCABLE_SESSION')) {
payload._RevocableSession = '1';
}
const installationId = options.installationId;
let installationIdPromise;
if (installationId && typeof installationId === 'string') {
installationIdPromise = _promise.default.resolve(installationId);
} else {
const installationController = _CoreManager.default.getInstallationController();
installationIdPromise = installationController.currentInstallationId();
}
return installationIdPromise.then(iid => {
payload._InstallationId = iid;
const userController = _CoreManager.default.getUserController();
if (options && typeof options.sessionToken === 'string') {
return _promise.default.resolve(options.sessionToken);
} else if (userController) {
return userController.currentUserAsync().then(user => {
if (user) {
return _promise.default.resolve(user.getSessionToken());
}
return _promise.default.resolve(null);
});
}
return _promise.default.resolve(null);
}).then(token => {
if (token) {
payload._SessionToken = token;
}
const payloadString = (0, _stringify.default)(payload);
return RESTController.ajax(method, url, payloadString, {}, options).then(_ref => {
let {
response,
status,
headers,
xhr
} = _ref;
if (options.returnStatus) {
return {
...response,
_status: status,
_headers: headers,
_xhr: xhr
};
} else {
return response;
}
});
}).catch(RESTController.handleError);
},
handleError(response) {
// Transform the error into an instance of ParseError by trying to parse
// the error string as JSON
let error;
if (response && response.responseText) {
try {
const errorJSON = JSON.parse(response.responseText);
error = new _ParseError.default(errorJSON.code, errorJSON.error);
} catch (e) {
// If we fail to parse the error text, that's okay.
error = new _ParseError.default(_ParseError.default.INVALID_JSON, 'Received an error with invalid JSON from Parse: ' + response.responseText);
}
} else {
const message = response.message ? response.message : response;
error = new _ParseError.default(_ParseError.default.CONNECTION_FAILED, 'XMLHttpRequest failed: ' + (0, _stringify.default)(message));
}
return _promise.default.reject(error);
},
_setXHR(xhr) {
XHR = xhr;
},
_getXHR() {
return XHR;
}
};
module.exports = RESTController;
var _default = exports.default = RESTController;
}).call(this)}).call(this,_dereq_('_process'))
},{"./CoreManager":4,"./ParseError":24,"./Xhr.weapp":52,"./promiseUtils":61,"./uuid":64,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/instance/includes":75,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/core-js-stable/set-timeout":99,"@babel/runtime-corejs3/helpers/interopRequireDefault":103,"_process":107}],41:[function(_dereq_,module,exports){
"use strict";
var _WeakMap = _dereq_("@babel/runtime-corejs3/core-js-stable/weak-map");
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _Object$getOwnPropertyDescriptor = _dereq_("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.clearAllState = clearAllState;
exports.commitServerChanges = commitServerChanges;
exports.duplicateState = duplicateState;
exports.enqueueTask = enqueueTask;
exports.estimateAttribute = estimateAttribute;
exports.estimateAttributes = estimateAttributes;
exports.getObjectCache = getObjectCache;
exports.getPendingOps = getPendingOps;
exports.getServerData = getServerData;
exports.getState = getState;
exports.initializeState = initializeState;
exports.mergeFirstPendingState = mergeFirstPendingState;
exports.popPendingState = popPendingState;
exports.pushPendingState = pushPendingState;
exports.removeState = removeState;
exports.setPendingOp = setPendingOp;
exports.setServerData = setServerData;
var ObjectStateMutations = _interopRequireWildcard(_dereq_("./ObjectStateMutations"));
function _getRequireWildcardCache(e) {
if ("function" != typeof _WeakMap) return null;
var r = new _WeakMap(),
t = new _WeakMap();
return (_getRequireWildcardCache = function (e) {
return e ? t : r;
})(e);
}
function _interopRequireWildcard(e, r) {
if (!r && e && e.__esModule) return e;
if (null === e || "object" != typeof e && "function" != typeof e) return {
default: e
};
var t = _getRequireWildcardCache(r);
if (t && t.has(e)) return t.get(e);
var n = {
__proto__: null
};
for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
var i = _Object$defineProperty && _Object$getOwnPropertyDescriptor ? _Object$getOwnPropertyDescriptor(e, u) : null;
i && (i.get || i.set) ? _Object$defineProperty(n, u, i) : n[u] = e[u];
}
return n.default = e, t && t.set(e, n), n;
}
let objectState = {};
function getState(obj) {
const classData = objectState[obj.className];
if (classData) {
return classData[obj.id] || null;
}
return null;
}
function initializeState(obj, initial) {
let state = getState(obj);
if (state) {
return state;
}
if (!objectState[obj.className]) {
objectState[obj.className] = {};
}
if (!initial) {
initial = ObjectStateMutations.defaultState();
}
state = objectState[obj.className][obj.id] = initial;
return state;
}
function removeState(obj) {
const state = getState(obj);
if (state === null) {
return null;
}
delete objectState[obj.className][obj.id];
return state;
}
function getServerData(obj) {
const state = getState(obj);
if (state) {
return state.serverData;
}
return {};
}
function setServerData(obj, attributes) {
const serverData = initializeState(obj).serverData;
ObjectStateMutations.setServerData(serverData, attributes);
}
function getPendingOps(obj) {
const state = getState(obj);
if (state) {
return state.pendingOps;
}
return [{}];
}
function setPendingOp(obj, attr, op) {
const pendingOps = initializeState(obj).pendingOps;
ObjectStateMutations.setPendingOp(pendingOps, attr, op);
}
function pushPendingState(obj) {
const pendingOps = initializeState(obj).pendingOps;
ObjectStateMutations.pushPendingState(pendingOps);
}
function popPendingState(obj) {
const pendingOps = initializeState(obj).pendingOps;
return ObjectStateMutations.popPendingState(pendingOps);
}
function mergeFirstPendingState(obj) {
const pendingOps = getPendingOps(obj);
ObjectStateMutations.mergeFirstPendingState(pendingOps);
}
function getObjectCache(obj) {
const state = getState(obj);
if (state) {
return state.objectCache;
}
return {};
}
function estimateAttribute(obj, attr) {
const serverData = getServerData(obj);
const pendingOps = getPendingOps(obj);
return ObjectStateMutations.estimateAttribute(serverData, pendingOps, obj, attr);
}
function estimateAttributes(obj) {
const serverData = getServerData(obj);
const pendingOps = getPendingOps(obj);
return ObjectStateMutations.estimateAttributes(serverData, pendingOps, obj);
}
function commitServerChanges(obj, changes) {
const state = initializeState(obj);
ObjectStateMutations.commitServerChanges(state.serverData, state.objectCache, changes);
}
function enqueueTask(obj, task) {
const state = initializeState(obj);
return state.tasks.enqueue(task);
}
function clearAllState() {
objectState = {};
}
function duplicateState(source, dest) {
dest.id = source.id;
}
},{"./ObjectStateMutations":18,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor":93,"@babel/runtime-corejs3/core-js-stable/weak-map":101}],42:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
class SocketWeapp {
constructor(serverURL) {
(0, _defineProperty2.default)(this, "onopen", void 0);
(0, _defineProperty2.default)(this, "onmessage", void 0);
(0, _defineProperty2.default)(this, "onclose", void 0);
(0, _defineProperty2.default)(this, "onerror", void 0);
this.onopen = () => {};
this.onmessage = () => {};
this.onclose = () => {};
this.onerror = () => {};
// @ts-ignore
wx.onSocketOpen(() => {
this.onopen();
});
// @ts-ignore
wx.onSocketMessage(msg => {
// @ts-ignore
this.onmessage(msg);
});
// @ts-ignore
wx.onSocketClose(event => {
// @ts-ignore
this.onclose(event);
});
// @ts-ignore
wx.onSocketError(error => {
// @ts-ignore
this.onerror(error);
});
// @ts-ignore
wx.connectSocket({
url: serverURL
});
}
send(data) {
// @ts-ignore
wx.sendSocketMessage({
data
});
}
close() {
// @ts-ignore
wx.closeSocket();
}
}
module.exports = SocketWeapp;
var _default = exports.default = SocketWeapp;
},{"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],43:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
const Storage = {
async() {
const controller = _CoreManager.default.getStorageController();
return !!controller.async;
},
getItem(path) {
const controller = _CoreManager.default.getStorageController();
if (controller.async === 1) {
throw new Error('Synchronous storage is not supported by the current storage controller');
}
return controller.getItem(path);
},
getItemAsync(path) {
const controller = _CoreManager.default.getStorageController();
if (controller.async === 1) {
return controller.getItemAsync(path);
}
return _promise.default.resolve(controller.getItem(path));
},
setItem(path, value) {
const controller = _CoreManager.default.getStorageController();
if (controller.async === 1) {
throw new Error('Synchronous storage is not supported by the current storage controller');
}
return controller.setItem(path, value);
},
setItemAsync(path, value) {
const controller = _CoreManager.default.getStorageController();
if (controller.async === 1) {
return controller.setItemAsync(path, value);
}
return _promise.default.resolve(controller.setItem(path, value));
},
removeItem(path) {
const controller = _CoreManager.default.getStorageController();
if (controller.async === 1) {
throw new Error('Synchronous storage is not supported by the current storage controller');
}
return controller.removeItem(path);
},
removeItemAsync(path) {
const controller = _CoreManager.default.getStorageController();
if (controller.async === 1) {
return controller.removeItemAsync(path);
}
return _promise.default.resolve(controller.removeItem(path));
},
getAllKeys() {
const controller = _CoreManager.default.getStorageController();
if (controller.async === 1) {
throw new Error('Synchronous storage is not supported by the current storage controller');
}
return controller.getAllKeys();
},
getAllKeysAsync() {
const controller = _CoreManager.default.getStorageController();
if (controller.async === 1) {
return controller.getAllKeysAsync();
}
return _promise.default.resolve(controller.getAllKeys());
},
generatePath(path) {
if (!_CoreManager.default.get('APPLICATION_ID')) {
throw new Error('You need to call Parse.initialize before using Parse.');
}
if (typeof path !== 'string') {
throw new Error('Tried to get a Storage path that was not a String.');
}
if (path[0] === '/') {
path = path.substr(1);
}
return 'Parse/' + _CoreManager.default.get('APPLICATION_ID') + '/' + path;
},
_clear() {
const controller = _CoreManager.default.getStorageController();
if (controller.hasOwnProperty('clear')) {
controller.clear();
}
}
};
module.exports = Storage;
var _default = exports.default = Storage;
},{"./CoreManager":4,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],44:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/* global localStorage */
const StorageController = {
async: 0,
getItem(path) {
return localStorage.getItem(path);
},
setItem(path, value) {
try {
localStorage.setItem(path, value);
} catch (e) {
// Quota exceeded, possibly due to Safari Private Browsing mode
console.log(e.message);
}
},
removeItem(path) {
localStorage.removeItem(path);
},
getAllKeys() {
const keys = [];
for (let i = 0; i < localStorage.length; i += 1) {
keys.push(localStorage.key(i));
}
return keys;
},
clear() {
localStorage.clear();
}
};
module.exports = StorageController;
var _default = exports.default = StorageController;
},{"@babel/runtime-corejs3/core-js-stable/object/define-property":90}],45:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
// When there is no native storage interface, we default to an in-memory map
const memMap = {};
const StorageController = {
async: 0,
getItem(path) {
if (memMap.hasOwnProperty(path)) {
return memMap[path];
}
return null;
},
setItem(path, value) {
memMap[path] = String(value);
},
removeItem(path) {
delete memMap[path];
},
getAllKeys() {
return (0, _keys.default)(memMap);
},
clear() {
for (const key in memMap) {
if (memMap.hasOwnProperty(key)) {
delete memMap[key];
}
}
}
};
module.exports = StorageController;
var _default = exports.default = StorageController;
},{"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],46:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _StorageController = _interopRequireDefault(_dereq_("./StorageController.react-native"));
var _StorageController2 = _interopRequireDefault(_dereq_("./StorageController.browser"));
var _StorageController3 = _interopRequireDefault(_dereq_("./StorageController.weapp"));
var _StorageController4 = _interopRequireDefault(_dereq_("./StorageController.default"));
let StorageController = _StorageController4.default;
StorageController = _StorageController3.default;
module.exports = StorageController;
var _default = exports.default = StorageController;
},{"./StorageController.browser":44,"./StorageController.default":45,"./StorageController.react-native":47,"./StorageController.weapp":48,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],47:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
const StorageController = {
async: 1,
getItemAsync(path) {
return new _promise.default((resolve, reject) => {
_CoreManager.default.getAsyncStorage().getItem(path, (err, value) => {
if (err) {
reject(err);
} else {
resolve(value || null);
}
});
});
},
setItemAsync(path, value) {
return new _promise.default((resolve, reject) => {
_CoreManager.default.getAsyncStorage().setItem(path, value, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
},
removeItemAsync(path) {
return new _promise.default((resolve, reject) => {
_CoreManager.default.getAsyncStorage().removeItem(path, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
},
getAllKeysAsync() {
return new _promise.default((resolve, reject) => {
_CoreManager.default.getAsyncStorage().getAllKeys((err, keys) => {
if (err) {
reject(err);
} else {
resolve(keys || []);
}
});
});
},
multiGet(keys) {
return new _promise.default((resolve, reject) => {
_CoreManager.default.getAsyncStorage().multiGet(keys, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result || null);
}
});
});
},
multiRemove(keys) {
return new _promise.default((resolve, reject) => {
_CoreManager.default.getAsyncStorage().multiRemove(keys, err => {
if (err) {
reject(err);
} else {
resolve(keys);
}
});
});
},
clear() {
return _CoreManager.default.getAsyncStorage().clear();
}
};
module.exports = StorageController;
var _default = exports.default = StorageController;
},{"./CoreManager":4,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],48:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/keys"));
const StorageController = {
async: 0,
getItem(path) {
// @ts-ignore
return wx.getStorageSync(path);
},
setItem(path, value) {
try {
// @ts-ignore
wx.setStorageSync(path, value);
} catch (e) {
// Quota exceeded
}
},
removeItem(path) {
// @ts-ignore
wx.removeStorageSync(path);
},
getAllKeys() {
// @ts-ignore
const res = wx.getStorageInfoSync();
return (0, _keys.default)(res);
},
clear() {
// @ts-ignore
wx.clearStorageSync();
}
};
module.exports = StorageController;
var _default = exports.default = StorageController;
},{"@babel/runtime-corejs3/core-js-stable/instance/keys":77,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],49:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
var _promiseUtils = _dereq_("./promiseUtils");
class TaskQueue {
constructor() {
(0, _defineProperty2.default)(this, "queue", void 0);
this.queue = [];
}
enqueue(task) {
const taskComplete = (0, _promiseUtils.resolvingPromise)();
this.queue.push({
task: task,
_completion: taskComplete
});
if (this.queue.length === 1) {
task().then(() => {
this._dequeue();
taskComplete.resolve();
}, error => {
this._dequeue();
taskComplete.reject(error);
});
}
return taskComplete;
}
_dequeue() {
this.queue.shift();
if (this.queue.length) {
const next = this.queue[0];
next.task().then(() => {
this._dequeue();
next._completion.resolve();
}, error => {
this._dequeue();
next._completion.reject(error);
});
}
}
}
module.exports = TaskQueue;
var _default = exports.default = TaskQueue;
},{"./promiseUtils":61,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],50:[function(_dereq_,module,exports){
"use strict";
var _WeakMap2 = _dereq_("@babel/runtime-corejs3/core-js-stable/weak-map");
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _Object$getOwnPropertyDescriptor = _dereq_("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.clearAllState = clearAllState;
exports.commitServerChanges = commitServerChanges;
exports.duplicateState = duplicateState;
exports.enqueueTask = enqueueTask;
exports.estimateAttribute = estimateAttribute;
exports.estimateAttributes = estimateAttributes;
exports.getObjectCache = getObjectCache;
exports.getPendingOps = getPendingOps;
exports.getServerData = getServerData;
exports.getState = getState;
exports.initializeState = initializeState;
exports.mergeFirstPendingState = mergeFirstPendingState;
exports.popPendingState = popPendingState;
exports.pushPendingState = pushPendingState;
exports.removeState = removeState;
exports.setPendingOp = setPendingOp;
exports.setServerData = setServerData;
var _weakMap = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/weak-map"));
var ObjectStateMutations = _interopRequireWildcard(_dereq_("./ObjectStateMutations"));
var _TaskQueue = _interopRequireDefault(_dereq_("./TaskQueue"));
function _getRequireWildcardCache(e) {
if ("function" != typeof _WeakMap2) return null;
var r = new _WeakMap2(),
t = new _WeakMap2();
return (_getRequireWildcardCache = function (e) {
return e ? t : r;
})(e);
}
function _interopRequireWildcard(e, r) {
if (!r && e && e.__esModule) return e;
if (null === e || "object" != typeof e && "function" != typeof e) return {
default: e
};
var t = _getRequireWildcardCache(r);
if (t && t.has(e)) return t.get(e);
var n = {
__proto__: null
};
for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
var i = _Object$defineProperty && _Object$getOwnPropertyDescriptor ? _Object$getOwnPropertyDescriptor(e, u) : null;
i && (i.get || i.set) ? _Object$defineProperty(n, u, i) : n[u] = e[u];
}
return n.default = e, t && t.set(e, n), n;
}
let objectState = new _weakMap.default();
function getState(obj) {
const classData = objectState.get(obj);
return classData || null;
}
function initializeState(obj, initial) {
let state = getState(obj);
if (state) {
return state;
}
if (!initial) {
initial = {
serverData: {},
pendingOps: [{}],
objectCache: {},
tasks: new _TaskQueue.default(),
existed: false
};
}
state = initial;
objectState.set(obj, state);
return state;
}
function removeState(obj) {
const state = getState(obj);
if (state === null) {
return null;
}
objectState.delete(obj);
return state;
}
function getServerData(obj) {
const state = getState(obj);
if (state) {
return state.serverData;
}
return {};
}
function setServerData(obj, attributes) {
const serverData = initializeState(obj).serverData;
ObjectStateMutations.setServerData(serverData, attributes);
}
function getPendingOps(obj) {
const state = getState(obj);
if (state) {
return state.pendingOps;
}
return [{}];
}
function setPendingOp(obj, attr, op) {
const pendingOps = initializeState(obj).pendingOps;
ObjectStateMutations.setPendingOp(pendingOps, attr, op);
}
function pushPendingState(obj) {
const pendingOps = initializeState(obj).pendingOps;
ObjectStateMutations.pushPendingState(pendingOps);
}
function popPendingState(obj) {
const pendingOps = initializeState(obj).pendingOps;
return ObjectStateMutations.popPendingState(pendingOps);
}
function mergeFirstPendingState(obj) {
const pendingOps = getPendingOps(obj);
ObjectStateMutations.mergeFirstPendingState(pendingOps);
}
function getObjectCache(obj) {
const state = getState(obj);
if (state) {
return state.objectCache;
}
return {};
}
function estimateAttribute(obj, attr) {
const serverData = getServerData(obj);
const pendingOps = getPendingOps(obj);
return ObjectStateMutations.estimateAttribute(serverData, pendingOps, obj, attr);
}
function estimateAttributes(obj) {
const serverData = getServerData(obj);
const pendingOps = getPendingOps(obj);
return ObjectStateMutations.estimateAttributes(serverData, pendingOps, obj);
}
function commitServerChanges(obj, changes) {
const state = initializeState(obj);
ObjectStateMutations.commitServerChanges(state.serverData, state.objectCache, changes);
}
function enqueueTask(obj, task) {
const state = initializeState(obj);
return state.tasks.enqueue(task);
}
function duplicateState(source, dest) {
const oldState = initializeState(source);
const newState = initializeState(dest);
for (const key in oldState.serverData) {
newState.serverData[key] = oldState.serverData[key];
}
for (let index = 0; index < oldState.pendingOps.length; index++) {
for (const key in oldState.pendingOps[index]) {
newState.pendingOps[index][key] = oldState.pendingOps[index][key];
}
}
for (const key in oldState.objectCache) {
newState.objectCache[key] = oldState.objectCache[key];
}
newState.existed = oldState.existed;
}
function clearAllState() {
objectState = new _weakMap.default();
}
},{"./ObjectStateMutations":18,"./TaskQueue":49,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor":93,"@babel/runtime-corejs3/core-js-stable/weak-map":101,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],51:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _ws = _interopRequireDefault(_dereq_("ws"));
var _Socket = _interopRequireDefault(_dereq_("./Socket.weapp"));
/* global WebSocket */
let WebSocketController;
try {
WebSocketController = _Socket.default;
} catch (_) {
// WebSocket unavailable
}
module.exports = WebSocketController;
var _default = exports.default = WebSocketController;
},{"./Socket.weapp":42,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103,"ws":508}],52:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stringify = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/json/stringify"));
var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/helpers/defineProperty"));
class XhrWeapp {
constructor() {
(0, _defineProperty2.default)(this, "UNSENT", void 0);
(0, _defineProperty2.default)(this, "OPENED", void 0);
(0, _defineProperty2.default)(this, "HEADERS_RECEIVED", void 0);
(0, _defineProperty2.default)(this, "LOADING", void 0);
(0, _defineProperty2.default)(this, "DONE", void 0);
(0, _defineProperty2.default)(this, "header", void 0);
(0, _defineProperty2.default)(this, "readyState", void 0);
(0, _defineProperty2.default)(this, "status", void 0);
(0, _defineProperty2.default)(this, "response", void 0);
(0, _defineProperty2.default)(this, "responseType", void 0);
(0, _defineProperty2.default)(this, "responseText", void 0);
(0, _defineProperty2.default)(this, "responseHeader", void 0);
(0, _defineProperty2.default)(this, "method", void 0);
(0, _defineProperty2.default)(this, "url", void 0);
(0, _defineProperty2.default)(this, "onabort", void 0);
(0, _defineProperty2.default)(this, "onprogress", void 0);
(0, _defineProperty2.default)(this, "onerror", void 0);
(0, _defineProperty2.default)(this, "onreadystatechange", void 0);
(0, _defineProperty2.default)(this, "requestTask", void 0);
this.UNSENT = 0;
this.OPENED = 1;
this.HEADERS_RECEIVED = 2;
this.LOADING = 3;
this.DONE = 4;
this.header = {};
this.readyState = this.DONE;
this.status = 0;
this.response = '';
this.responseType = '';
this.responseText = '';
this.responseHeader = {};
this.method = '';
this.url = '';
this.onabort = () => {};
this.onprogress = () => {};
this.onerror = () => {};
this.onreadystatechange = () => {};
this.requestTask = null;
}
getAllResponseHeaders() {
let header = '';
for (const key in this.responseHeader) {
header += key + ':' + this.getResponseHeader(key) + '\r\n';
}
return header;
}
getResponseHeader(key) {
return this.responseHeader[key];
}
setRequestHeader(key, value) {
this.header[key] = value;
}
open(method, url) {
this.method = method;
this.url = url;
}
abort() {
if (!this.requestTask) {
return;
}
this.requestTask.abort();
this.status = 0;
this.response = undefined;
this.onabort();
this.onreadystatechange();
}
send(data) {
// @ts-ignore
this.requestTask = wx.request({
url: this.url,
method: this.method,
data: data,
header: this.header,
responseType: this.responseType,
success: res => {
this.status = res.statusCode;
this.response = res.data;
this.responseHeader = res.header;
this.responseText = (0, _stringify.default)(res.data);
this.requestTask = null;
this.onreadystatechange();
},
fail: err => {
this.requestTask = null;
// @ts-ignore
this.onerror(err);
}
});
this.requestTask.onProgressUpdate(res => {
const event = {
lengthComputable: res.totalBytesExpectedToWrite !== 0,
loaded: res.totalBytesWritten,
total: res.totalBytesExpectedToWrite
};
// @ts-ignore
this.onprogress(event);
});
}
}
module.exports = XhrWeapp;
var _default = exports.default = XhrWeapp;
},{"@babel/runtime-corejs3/core-js-stable/json/stringify":85,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/defineProperty":102,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],53:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = arrayContainsObject;
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
function arrayContainsObject(array, object) {
if ((0, _indexOf.default)(array).call(array, object) > -1) {
return true;
}
const ParseObject = _CoreManager.default.getParseObject();
for (let i = 0; i < array.length; i++) {
if (array[i] instanceof ParseObject && array[i].className === object.className && array[i]._getId() === object._getId()) {
return true;
}
}
return false;
}
},{"./CoreManager":4,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],54:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = canBeSerialized;
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
function canBeSerialized(obj) {
const ParseObject = _CoreManager.default.getParseObject();
if (!(obj instanceof ParseObject)) {
return true;
}
const attributes = obj.attributes;
for (const attr in attributes) {
const val = attributes[attr];
if (!canBeSerializedHelper(val)) {
return false;
}
}
return true;
}
function canBeSerializedHelper(value) {
if (typeof value !== 'object') {
return true;
}
if (value instanceof _ParseRelation.default) {
return true;
}
const ParseObject = _CoreManager.default.getParseObject();
if (value instanceof ParseObject) {
return !!value.id;
}
if (value instanceof _ParseFile.default) {
if (value.url()) {
return true;
}
return false;
}
if ((0, _isArray.default)(value)) {
for (let i = 0; i < value.length; i++) {
if (!canBeSerializedHelper(value[i])) {
return false;
}
}
return true;
}
for (const k in value) {
if (!canBeSerializedHelper(value[k])) {
return false;
}
}
return true;
}
},{"./CoreManager":4,"./ParseFile":25,"./ParseRelation":34,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],55:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = decode;
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
var _ParsePolygon = _interopRequireDefault(_dereq_("./ParsePolygon"));
var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
function decode(value) {
if (value === null || typeof value !== 'object' || value instanceof Date) {
return value;
}
if ((0, _isArray.default)(value)) {
const dup = [];
(0, _forEach.default)(value).call(value, (v, i) => {
dup[i] = decode(v);
});
return dup;
}
if (typeof value.__op === 'string') {
const {
opFromJSON
} = _CoreManager.default.getParseOp();
return opFromJSON(value);
}
const ParseObject = _CoreManager.default.getParseObject();
if (value.__type === 'Pointer' && value.className) {
return ParseObject.fromJSON(value);
}
if (value.__type === 'Object' && value.className) {
return ParseObject.fromJSON(value);
}
if (value.__type === 'Relation') {
// The parent and key fields will be populated by the parent
const relation = new _ParseRelation.default(null, null);
relation.targetClassName = value.className;
return relation;
}
if (value.__type === 'Date') {
return new Date(value.iso);
}
if (value.__type === 'File') {
return _ParseFile.default.fromJSON(value);
}
if (value.__type === 'GeoPoint') {
return new _ParseGeoPoint.default({
latitude: value.latitude,
longitude: value.longitude
});
}
if (value.__type === 'Polygon') {
return new _ParsePolygon.default(value.coordinates);
}
const copy = {};
for (const k in value) {
copy[k] = decode(value[k]);
}
return copy;
}
},{"./CoreManager":4,"./ParseFile":25,"./ParseGeoPoint":26,"./ParsePolygon":32,"./ParseRelation":34,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],56:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _startsWith = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/starts-with"));
var _concat = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _map = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
var _ParsePolygon = _interopRequireDefault(_dereq_("./ParsePolygon"));
var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
function encode(value, disallowObjects, forcePointers, seen, offline) {
const ParseObject = _CoreManager.default.getParseObject();
if (value instanceof ParseObject) {
if (disallowObjects) {
throw new Error('Parse Objects not allowed here');
}
const seenEntry = value.id ? value.className + ':' + value.id : value;
if (forcePointers || !seen || (0, _indexOf.default)(seen).call(seen, seenEntry) > -1 || value.dirty() || (0, _keys.default)(value._getServerData()).length < 1) {
var _context;
if (offline && (0, _startsWith.default)(_context = value._getId()).call(_context, 'local')) {
return value.toOfflinePointer();
}
return value.toPointer();
}
seen = (0, _concat.default)(seen).call(seen, seenEntry);
return value._toFullJSON(seen, offline);
}
const {
Op
} = _CoreManager.default.getParseOp();
if (value instanceof Op || value instanceof _ParseACL.default || value instanceof _ParseGeoPoint.default || value instanceof _ParsePolygon.default || value instanceof _ParseRelation.default) {
return value.toJSON();
}
if (value instanceof _ParseFile.default) {
if (!value.url()) {
throw new Error('Tried to encode an unsaved file.');
}
return value.toJSON();
}
if (Object.prototype.toString.call(value) === '[object Date]') {
if (isNaN(value)) {
throw new Error('Tried to encode an invalid date.');
}
return {
__type: 'Date',
iso: value.toJSON()
};
}
if (Object.prototype.toString.call(value) === '[object RegExp]' && typeof value.source === 'string') {
return value.source;
}
if ((0, _isArray.default)(value)) {
return (0, _map.default)(value).call(value, v => {
return encode(v, disallowObjects, forcePointers, seen, offline);
});
}
if (value && typeof value === 'object') {
const output = {};
for (const k in value) {
output[k] = encode(value[k], disallowObjects, forcePointers, seen, offline);
}
return output;
}
return value;
}
function _default(value, disallowObjects, forcePointers, seen, offline) {
return encode(value, !!disallowObjects, !!forcePointers, seen || [], offline);
}
},{"./CoreManager":4,"./ParseACL":21,"./ParseFile":25,"./ParseGeoPoint":26,"./ParsePolygon":32,"./ParseRelation":34,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/concat":68,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/instance/map":78,"@babel/runtime-corejs3/core-js-stable/instance/starts-with":83,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],57:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = equals;
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _keys = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
function equals(a, b) {
const toString = Object.prototype.toString;
if (toString.call(a) === '[object Date]' || toString.call(b) === '[object Date]') {
const dateA = new Date(a);
const dateB = new Date(b);
return +dateA === +dateB;
}
if (typeof a !== typeof b) {
return false;
}
if (!a || typeof a !== 'object') {
// a is a primitive
return a === b;
}
if ((0, _isArray.default)(a) || (0, _isArray.default)(b)) {
if (!(0, _isArray.default)(a) || !(0, _isArray.default)(b)) {
return false;
}
if (a.length !== b.length) {
return false;
}
for (let i = a.length; i--;) {
if (!equals(a[i], b[i])) {
return false;
}
}
return true;
}
const ParseObject = _CoreManager.default.getParseObject();
if (a instanceof _ParseACL.default || a instanceof _ParseFile.default || a instanceof _ParseGeoPoint.default || a instanceof ParseObject) {
return a.equals(b);
}
if (b instanceof ParseObject) {
if (a.__type === 'Object' || a.__type === 'Pointer') {
return a.objectId === b.id && a.className === b.className;
}
}
if ((0, _keys.default)(a).length !== (0, _keys.default)(b).length) {
return false;
}
for (const k in a) {
if (!equals(a[k], b[k])) {
return false;
}
}
return true;
}
},{"./CoreManager":4,"./ParseACL":21,"./ParseFile":25,"./ParseGeoPoint":26,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/object/keys":95,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],58:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = escape;
const encoded = {
'&': '&',
'<': '<',
'>': '>',
'/': '/',
"'": ''',
'"': '"'
};
function escape(str) {
return str.replace(/[&<>\/'"]/g, function (char) {
return encoded[char];
});
}
},{"@babel/runtime-corejs3/core-js-stable/object/define-property":90}],59:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = isRevocableSession;
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
function isRevocableSession(token) {
return (0, _indexOf.default)(token).call(token, 'r:') > -1;
}
},{"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],60:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = parseDate;
var _parseInt2 = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/parse-int"));
function parseDate(iso8601) {
const regexp = new RegExp('^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})' + 'T' + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})' + '(.([0-9]+))?' + 'Z$');
const match = regexp.exec(iso8601);
if (!match) {
return null;
}
const year = (0, _parseInt2.default)(match[1]) || 0;
const month = ((0, _parseInt2.default)(match[2]) || 1) - 1;
const day = (0, _parseInt2.default)(match[3]) || 0;
const hour = (0, _parseInt2.default)(match[4]) || 0;
const minute = (0, _parseInt2.default)(match[5]) || 0;
const second = (0, _parseInt2.default)(match[6]) || 0;
const milli = (0, _parseInt2.default)(match[8]) || 0;
return new Date(Date.UTC(year, month, day, hour, minute, second, milli));
}
},{"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/parse-int":96,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],61:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.continueWhile = continueWhile;
exports.resolvingPromise = resolvingPromise;
exports.when = when;
var _promise = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/promise"));
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
// Create Deferred Promise
function resolvingPromise() {
let res;
let rej;
const promise = new _promise.default((resolve, reject) => {
res = resolve;
rej = reject;
});
const defer = promise;
defer.resolve = res;
defer.reject = rej;
return defer;
}
function when(promises) {
let objects;
const arrayArgument = (0, _isArray.default)(promises);
if (arrayArgument) {
objects = promises;
} else {
objects = arguments;
}
let total = objects.length;
let hadError = false;
const results = [];
const returnValue = arrayArgument ? [results] : results;
const errors = [];
results.length = objects.length;
errors.length = objects.length;
if (total === 0) {
return _promise.default.resolve(returnValue);
}
const promise = resolvingPromise();
const resolveOne = function () {
total--;
if (total <= 0) {
if (hadError) {
promise.reject(errors);
} else {
promise.resolve(returnValue);
}
}
};
const chain = function (object, index) {
if (object && typeof object.then === 'function') {
object.then(function (result) {
results[index] = result;
resolveOne();
}, function (error) {
errors[index] = error;
hadError = true;
resolveOne();
});
} else {
results[index] = object;
resolveOne();
}
};
for (let i = 0; i < objects.length; i++) {
chain(objects[i], i);
}
return promise;
}
function continueWhile(test, emitter) {
if (test()) {
return emitter().then(() => {
return continueWhile(test, emitter);
});
}
return _promise.default.resolve();
}
},{"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/core-js-stable/promise":97,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],62:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = unique;
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _arrayContainsObject = _interopRequireDefault(_dereq_("./arrayContainsObject"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
function unique(arr) {
const uniques = [];
(0, _forEach.default)(arr).call(arr, value => {
const ParseObject = _CoreManager.default.getParseObject();
if (value instanceof ParseObject) {
if (!(0, _arrayContainsObject.default)(uniques, value)) {
uniques.push(value);
}
} else {
if ((0, _indexOf.default)(uniques).call(uniques, value) < 0) {
uniques.push(value);
}
}
});
return uniques;
}
},{"./CoreManager":4,"./arrayContainsObject":53,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],63:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = _dereq_("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = unsavedChildren;
var _concat = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _indexOf = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
var _isArray = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/array/is-array"));
var _forEach = _interopRequireDefault(_dereq_("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
/**
* Return an array of unsaved children, which are either Parse Objects or Files.
* If it encounters any dirty Objects without Ids, it will throw an exception.
*
* @param {Parse.Object} obj
* @param {boolean} allowDeepUnsaved
* @returns {Array}
*/
function unsavedChildren(obj, allowDeepUnsaved) {
const encountered = {
objects: {},
files: []
};
const identifier = obj.className + ':' + obj._getId();
encountered.objects[identifier] = obj.dirty() ? obj : true;
const attributes = obj.attributes;
for (const attr in attributes) {
if (typeof attributes[attr] === 'object') {
traverse(attributes[attr], encountered, false, !!allowDeepUnsaved);
}
}
const unsaved = [];
for (const id in encountered.objects) {
if (id !== identifier && encountered.objects[id] !== true) {
unsaved.push(encountered.objects[id]);
}
}
return (0, _concat.default)(unsaved).call(unsaved, encountered.files);
}
function traverse(obj, encountered, shouldThrow, allowDeepUnsaved) {
const ParseObject = _CoreManager.default.getParseObject();
if (obj instanceof ParseObject) {
if (!obj.id && shouldThrow) {
throw new Error('Cannot create a pointer to an unsaved Object.');
}
const identifier = obj.className + ':' + obj._getId();
if (!encountered.objects[identifier]) {
encountered.objects[identifier] = obj.dirty() ? obj : true;
const attributes = obj.attributes;
for (const attr in attributes) {
if (typeof attributes[attr] === 'object') {
traverse(attributes[attr], encountered, !allowDeepUnsaved, allowDeepUnsaved);
}
}
}
return;
}
if (obj instanceof _ParseFile.default) {
var _context;
if (!obj.url() && (0, _indexOf.default)(_context = encountered.files).call(_context, obj) < 0) {
encountered.files.push(obj);
}
return;
}
if (obj instanceof _ParseRelation.default) {
return;
}
if ((0, _isArray.default)(obj)) {
(0, _forEach.default)(obj).call(obj, el => {
if (typeof el === 'object') {
traverse(el, encountered, shouldThrow, allowDeepUnsaved);
}
});
}
for (const k in obj) {
if (typeof obj[k] === 'object') {
traverse(obj[k], encountered, shouldThrow, allowDeepUnsaved);
}
}
}
},{"./CoreManager":4,"./ParseFile":25,"./ParseRelation":34,"@babel/runtime-corejs3/core-js-stable/array/is-array":66,"@babel/runtime-corejs3/core-js-stable/instance/concat":68,"@babel/runtime-corejs3/core-js-stable/instance/for-each":74,"@babel/runtime-corejs3/core-js-stable/instance/index-of":76,"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"@babel/runtime-corejs3/helpers/interopRequireDefault":103}],64:[function(_dereq_,module,exports){
"use strict";
var _Object$defineProperty = _dereq_("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _uuid = _dereq_("uuid");
let uuid = function () {
const s = [];
const hexDigits = '0123456789abcdef';
for (let i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr(Number(s[19]) & 0x3 | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = '-';
return s.join('');
};
module.exports = uuid;
var _default = exports.default = uuid;
},{"@babel/runtime-corejs3/core-js-stable/object/define-property":90,"uuid":487}],65:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/array/from");
},{"core-js-pure/stable/array/from":432}],66:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/array/is-array");
},{"core-js-pure/stable/array/is-array":433}],67:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/bind");
},{"core-js-pure/stable/instance/bind":438}],68:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/concat");
},{"core-js-pure/stable/instance/concat":439}],69:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/entries");
},{"core-js-pure/stable/instance/entries":440}],70:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/every");
},{"core-js-pure/stable/instance/every":441}],71:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/filter");
},{"core-js-pure/stable/instance/filter":442}],72:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/find-index");
},{"core-js-pure/stable/instance/find-index":443}],73:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/find");
},{"core-js-pure/stable/instance/find":444}],74:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/for-each");
},{"core-js-pure/stable/instance/for-each":445}],75:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/includes");
},{"core-js-pure/stable/instance/includes":446}],76:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/index-of");
},{"core-js-pure/stable/instance/index-of":447}],77:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/keys");
},{"core-js-pure/stable/instance/keys":448}],78:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/map");
},{"core-js-pure/stable/instance/map":449}],79:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/reduce");
},{"core-js-pure/stable/instance/reduce":450}],80:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/slice");
},{"core-js-pure/stable/instance/slice":451}],81:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/sort");
},{"core-js-pure/stable/instance/sort":452}],82:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/splice");
},{"core-js-pure/stable/instance/splice":453}],83:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/starts-with");
},{"core-js-pure/stable/instance/starts-with":454}],84:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/instance/values");
},{"core-js-pure/stable/instance/values":455}],85:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/json/stringify");
},{"core-js-pure/stable/json/stringify":456}],86:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/map");
},{"core-js-pure/stable/map":457}],87:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/number/is-integer");
},{"core-js-pure/stable/number/is-integer":458}],88:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/object/assign");
},{"core-js-pure/stable/object/assign":459}],89:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/object/create");
},{"core-js-pure/stable/object/create":460}],90:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/object/define-property");
},{"core-js-pure/stable/object/define-property":461}],91:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/object/entries");
},{"core-js-pure/stable/object/entries":462}],92:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/object/freeze");
},{"core-js-pure/stable/object/freeze":463}],93:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/object/get-own-property-descriptor");
},{"core-js-pure/stable/object/get-own-property-descriptor":464}],94:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/object/get-prototype-of");
},{"core-js-pure/stable/object/get-prototype-of":465}],95:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/object/keys");
},{"core-js-pure/stable/object/keys":466}],96:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/parse-int");
},{"core-js-pure/stable/parse-int":467}],97:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/promise");
},{"core-js-pure/stable/promise":468}],98:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/set-interval");
},{"core-js-pure/stable/set-interval":469}],99:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/set-timeout");
},{"core-js-pure/stable/set-timeout":470}],100:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/set");
},{"core-js-pure/stable/set":471}],101:[function(_dereq_,module,exports){
module.exports = _dereq_("core-js-pure/stable/weak-map");
},{"core-js-pure/stable/weak-map":475}],102:[function(_dereq_,module,exports){
var _Object$defineProperty = _dereq_("core-js-pure/features/object/define-property.js");
var toPropertyKey = _dereq_("./toPropertyKey.js");
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? _Object$defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./toPropertyKey.js":105,"core-js-pure/features/object/define-property.js":165}],103:[function(_dereq_,module,exports){
function _interopRequireDefault(e) {
return e && e.__esModule ? e : {
"default": e
};
}
module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],104:[function(_dereq_,module,exports){
var _Symbol$toPrimitive = _dereq_("core-js-pure/features/symbol/to-primitive.js");
var _typeof = _dereq_("./typeof.js")["default"];
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[_Symbol$toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./typeof.js":106,"core-js-pure/features/symbol/to-primitive.js":168}],105:[function(_dereq_,module,exports){
var _typeof = _dereq_("./typeof.js")["default"];
var toPrimitive = _dereq_("./toPrimitive.js");
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./toPrimitive.js":104,"./typeof.js":106}],106:[function(_dereq_,module,exports){
var _Symbol = _dereq_("core-js-pure/features/symbol/index.js");
var _Symbol$iterator = _dereq_("core-js-pure/features/symbol/iterator.js");
function _typeof(o) {
"@babel/helpers - typeof";
return (module.exports = _typeof = "function" == typeof _Symbol && "symbol" == typeof _Symbol$iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof _Symbol && o.constructor === _Symbol && o !== _Symbol.prototype ? "symbol" : typeof o;
}, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"core-js-pure/features/symbol/index.js":166,"core-js-pure/features/symbol/iterator.js":167}],107:[function(_dereq_,module,exports){
},{}],108:[function(_dereq_,module,exports){
var parent = _dereq_('../../stable/object/define-property');
module.exports = parent;
},{"../../stable/object/define-property":461}],109:[function(_dereq_,module,exports){
var parent = _dereq_('../../stable/symbol');
_dereq_('../../modules/esnext.symbol.dispose');
module.exports = parent;
},{"../../modules/esnext.symbol.dispose":419,"../../stable/symbol":472}],110:[function(_dereq_,module,exports){
var parent = _dereq_('../../stable/symbol/iterator');
module.exports = parent;
},{"../../stable/symbol/iterator":473}],111:[function(_dereq_,module,exports){
var parent = _dereq_('../../stable/symbol/to-primitive');
module.exports = parent;
},{"../../stable/symbol/to-primitive":474}],112:[function(_dereq_,module,exports){
_dereq_('../../modules/es.string.iterator');
_dereq_('../../modules/es.array.from');
var path = _dereq_('../../internals/path');
module.exports = path.Array.from;
},{"../../internals/path":305,"../../modules/es.array.from":353,"../../modules/es.string.iterator":396}],113:[function(_dereq_,module,exports){
_dereq_('../../modules/es.array.is-array');
var path = _dereq_('../../internals/path');
module.exports = path.Array.isArray;
},{"../../internals/path":305,"../../modules/es.array.is-array":356}],114:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.concat');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').concat;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.concat":347}],115:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.iterator');
_dereq_('../../../modules/es.object.to-string');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').entries;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.iterator":357,"../../../modules/es.object.to-string":380}],116:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.every');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').every;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.every":348}],117:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.filter');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').filter;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.filter":349}],118:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.find-index');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').findIndex;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.find-index":350}],119:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.find');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').find;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.find":351}],120:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.for-each');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').forEach;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.for-each":352}],121:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.includes');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').includes;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.includes":354}],122:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.index-of');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').indexOf;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.index-of":355}],123:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.iterator');
_dereq_('../../../modules/es.object.to-string');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').keys;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.iterator":357,"../../../modules/es.object.to-string":380}],124:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.map');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').map;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.map":358}],125:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.reduce');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').reduce;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.reduce":359}],126:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.slice');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').slice;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.slice":360}],127:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.sort');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').sort;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.sort":361}],128:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.splice');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').splice;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.splice":362}],129:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.array.iterator');
_dereq_('../../../modules/es.object.to-string');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Array').values;
},{"../../../internals/entry-virtual":229,"../../../modules/es.array.iterator":357,"../../../modules/es.object.to-string":380}],130:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.function.bind');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('Function').bind;
},{"../../../internals/entry-virtual":229,"../../../modules/es.function.bind":364}],131:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../function/virtual/bind');
var FunctionPrototype = Function.prototype;
module.exports = function (it) {
var own = it.bind;
return it === FunctionPrototype || (isPrototypeOf(FunctionPrototype, it) && own === FunctionPrototype.bind) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../function/virtual/bind":130}],132:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/concat');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.concat;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.concat) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/concat":114}],133:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/every');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.every;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.every) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/every":116}],134:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/filter');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.filter;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.filter) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/filter":117}],135:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/find-index');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.findIndex;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.findIndex) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/find-index":118}],136:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/find');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.find;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.find) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/find":119}],137:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var arrayMethod = _dereq_('../array/virtual/includes');
var stringMethod = _dereq_('../string/virtual/includes');
var ArrayPrototype = Array.prototype;
var StringPrototype = String.prototype;
module.exports = function (it) {
var own = it.includes;
if (it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.includes)) return arrayMethod;
if (typeof it == 'string' || it === StringPrototype || (isPrototypeOf(StringPrototype, it) && own === StringPrototype.includes)) {
return stringMethod;
} return own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/includes":121,"../string/virtual/includes":159}],138:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/index-of');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.indexOf;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.indexOf) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/index-of":122}],139:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/map');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.map;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.map) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/map":124}],140:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/reduce');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.reduce;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.reduce) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/reduce":125}],141:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/slice');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.slice;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.slice) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/slice":126}],142:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/sort');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.sort;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.sort) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/sort":127}],143:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/splice');
var ArrayPrototype = Array.prototype;
module.exports = function (it) {
var own = it.splice;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.splice) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../array/virtual/splice":128}],144:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../string/virtual/starts-with');
var StringPrototype = String.prototype;
module.exports = function (it) {
var own = it.startsWith;
return typeof it == 'string' || it === StringPrototype
|| (isPrototypeOf(StringPrototype, it) && own === StringPrototype.startsWith) ? method : own;
};
},{"../../internals/object-is-prototype-of":296,"../string/virtual/starts-with":160}],145:[function(_dereq_,module,exports){
_dereq_('../../modules/es.json.stringify');
var path = _dereq_('../../internals/path');
var apply = _dereq_('../../internals/function-apply');
// eslint-disable-next-line es/no-json -- safe
if (!path.JSON) path.JSON = { stringify: JSON.stringify };
// eslint-disable-next-line no-unused-vars -- required for `.length`
module.exports = function stringify(it, replacer, space) {
return apply(path.JSON.stringify, null, arguments);
};
},{"../../internals/function-apply":237,"../../internals/path":305,"../../modules/es.json.stringify":365}],146:[function(_dereq_,module,exports){
_dereq_('../../modules/es.array.iterator');
_dereq_('../../modules/es.map');
_dereq_('../../modules/es.object.to-string');
_dereq_('../../modules/es.string.iterator');
var path = _dereq_('../../internals/path');
module.exports = path.Map;
},{"../../internals/path":305,"../../modules/es.array.iterator":357,"../../modules/es.map":368,"../../modules/es.object.to-string":380,"../../modules/es.string.iterator":396}],147:[function(_dereq_,module,exports){
_dereq_('../../modules/es.number.is-integer');
var path = _dereq_('../../internals/path');
module.exports = path.Number.isInteger;
},{"../../internals/path":305,"../../modules/es.number.is-integer":370}],148:[function(_dereq_,module,exports){
_dereq_('../../modules/es.object.assign');
var path = _dereq_('../../internals/path');
module.exports = path.Object.assign;
},{"../../internals/path":305,"../../modules/es.object.assign":371}],149:[function(_dereq_,module,exports){
_dereq_('../../modules/es.object.create');
var path = _dereq_('../../internals/path');
var Object = path.Object;
module.exports = function create(P, D) {
return Object.create(P, D);
};
},{"../../internals/path":305,"../../modules/es.object.create":372}],150:[function(_dereq_,module,exports){
_dereq_('../../modules/es.object.define-property');
var path = _dereq_('../../internals/path');
var Object = path.Object;
var defineProperty = module.exports = function defineProperty(it, key, desc) {
return Object.defineProperty(it, key, desc);
};
if (Object.defineProperty.sham) defineProperty.sham = true;
},{"../../internals/path":305,"../../modules/es.object.define-property":373}],151:[function(_dereq_,module,exports){
_dereq_('../../modules/es.object.entries');
var path = _dereq_('../../internals/path');
module.exports = path.Object.entries;
},{"../../internals/path":305,"../../modules/es.object.entries":374}],152:[function(_dereq_,module,exports){
_dereq_('../../modules/es.object.freeze');
var path = _dereq_('../../internals/path');
module.exports = path.Object.freeze;
},{"../../internals/path":305,"../../modules/es.object.freeze":375}],153:[function(_dereq_,module,exports){
_dereq_('../../modules/es.object.get-own-property-descriptor');
var path = _dereq_('../../internals/path');
var Object = path.Object;
var getOwnPropertyDescriptor = module.exports = function getOwnPropertyDescriptor(it, key) {
return Object.getOwnPropertyDescriptor(it, key);
};
if (Object.getOwnPropertyDescriptor.sham) getOwnPropertyDescriptor.sham = true;
},{"../../internals/path":305,"../../modules/es.object.get-own-property-descriptor":376}],154:[function(_dereq_,module,exports){
_dereq_('../../modules/es.object.get-prototype-of');
var path = _dereq_('../../internals/path');
module.exports = path.Object.getPrototypeOf;
},{"../../internals/path":305,"../../modules/es.object.get-prototype-of":378}],155:[function(_dereq_,module,exports){
_dereq_('../../modules/es.object.keys');
var path = _dereq_('../../internals/path');
module.exports = path.Object.keys;
},{"../../internals/path":305,"../../modules/es.object.keys":379}],156:[function(_dereq_,module,exports){
_dereq_('../modules/es.parse-int');
var path = _dereq_('../internals/path');
module.exports = path.parseInt;
},{"../internals/path":305,"../modules/es.parse-int":381}],157:[function(_dereq_,module,exports){
_dereq_('../../modules/es.aggregate-error');
_dereq_('../../modules/es.array.iterator');
_dereq_('../../modules/es.object.to-string');
_dereq_('../../modules/es.promise');
_dereq_('../../modules/es.promise.all-settled');
_dereq_('../../modules/es.promise.any');
_dereq_('../../modules/es.promise.finally');
_dereq_('../../modules/es.string.iterator');
var path = _dereq_('../../internals/path');
module.exports = path.Promise;
},{"../../internals/path":305,"../../modules/es.aggregate-error":346,"../../modules/es.array.iterator":357,"../../modules/es.object.to-string":380,"../../modules/es.promise":388,"../../modules/es.promise.all-settled":382,"../../modules/es.promise.any":384,"../../modules/es.promise.finally":387,"../../modules/es.string.iterator":396}],158:[function(_dereq_,module,exports){
_dereq_('../../modules/es.array.iterator');
_dereq_('../../modules/es.object.to-string');
_dereq_('../../modules/es.set');
_dereq_('../../modules/es.string.iterator');
var path = _dereq_('../../internals/path');
module.exports = path.Set;
},{"../../internals/path":305,"../../modules/es.array.iterator":357,"../../modules/es.object.to-string":380,"../../modules/es.set":394,"../../modules/es.string.iterator":396}],159:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.string.includes');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('String').includes;
},{"../../../internals/entry-virtual":229,"../../../modules/es.string.includes":395}],160:[function(_dereq_,module,exports){
_dereq_('../../../modules/es.string.starts-with');
var entryVirtual = _dereq_('../../../internals/entry-virtual');
module.exports = entryVirtual('String').startsWith;
},{"../../../internals/entry-virtual":229,"../../../modules/es.string.starts-with":397}],161:[function(_dereq_,module,exports){
_dereq_('../../modules/es.array.concat');
_dereq_('../../modules/es.object.to-string');
_dereq_('../../modules/es.symbol');
_dereq_('../../modules/es.symbol.async-iterator');
_dereq_('../../modules/es.symbol.description');
_dereq_('../../modules/es.symbol.has-instance');
_dereq_('../../modules/es.symbol.is-concat-spreadable');
_dereq_('../../modules/es.symbol.iterator');
_dereq_('../../modules/es.symbol.match');
_dereq_('../../modules/es.symbol.match-all');
_dereq_('../../modules/es.symbol.replace');
_dereq_('../../modules/es.symbol.search');
_dereq_('../../modules/es.symbol.species');
_dereq_('../../modules/es.symbol.split');
_dereq_('../../modules/es.symbol.to-primitive');
_dereq_('../../modules/es.symbol.to-string-tag');
_dereq_('../../modules/es.symbol.unscopables');
_dereq_('../../modules/es.json.to-string-tag');
_dereq_('../../modules/es.math.to-string-tag');
_dereq_('../../modules/es.reflect.to-string-tag');
var path = _dereq_('../../internals/path');
module.exports = path.Symbol;
},{"../../internals/path":305,"../../modules/es.array.concat":347,"../../modules/es.json.to-string-tag":366,"../../modules/es.math.to-string-tag":369,"../../modules/es.object.to-string":380,"../../modules/es.reflect.to-string-tag":392,"../../modules/es.symbol":405,"../../modules/es.symbol.async-iterator":398,"../../modules/es.symbol.description":400,"../../modules/es.symbol.has-instance":402,"../../modules/es.symbol.is-concat-spreadable":403,"../../modules/es.symbol.iterator":404,"../../modules/es.symbol.match":408,"../../modules/es.symbol.match-all":407,"../../modules/es.symbol.replace":409,"../../modules/es.symbol.search":410,"../../modules/es.symbol.species":411,"../../modules/es.symbol.split":412,"../../modules/es.symbol.to-primitive":413,"../../modules/es.symbol.to-string-tag":414,"../../modules/es.symbol.unscopables":415}],162:[function(_dereq_,module,exports){
_dereq_('../../modules/es.array.iterator');
_dereq_('../../modules/es.object.to-string');
_dereq_('../../modules/es.string.iterator');
_dereq_('../../modules/es.symbol.iterator');
var WrappedWellKnownSymbolModule = _dereq_('../../internals/well-known-symbol-wrapped');
module.exports = WrappedWellKnownSymbolModule.f('iterator');
},{"../../internals/well-known-symbol-wrapped":342,"../../modules/es.array.iterator":357,"../../modules/es.object.to-string":380,"../../modules/es.string.iterator":396,"../../modules/es.symbol.iterator":404}],163:[function(_dereq_,module,exports){
_dereq_('../../modules/es.date.to-primitive');
_dereq_('../../modules/es.symbol.to-primitive');
var WrappedWellKnownSymbolModule = _dereq_('../../internals/well-known-symbol-wrapped');
module.exports = WrappedWellKnownSymbolModule.f('toPrimitive');
},{"../../internals/well-known-symbol-wrapped":342,"../../modules/es.date.to-primitive":363,"../../modules/es.symbol.to-primitive":413}],164:[function(_dereq_,module,exports){
_dereq_('../../modules/es.array.iterator');
_dereq_('../../modules/es.object.to-string');
_dereq_('../../modules/es.weak-map');
var path = _dereq_('../../internals/path');
module.exports = path.WeakMap;
},{"../../internals/path":305,"../../modules/es.array.iterator":357,"../../modules/es.object.to-string":380,"../../modules/es.weak-map":417}],165:[function(_dereq_,module,exports){
module.exports = _dereq_('../../full/object/define-property');
},{"../../full/object/define-property":169}],166:[function(_dereq_,module,exports){
module.exports = _dereq_('../../full/symbol');
},{"../../full/symbol":170}],167:[function(_dereq_,module,exports){
module.exports = _dereq_('../../full/symbol/iterator');
},{"../../full/symbol/iterator":171}],168:[function(_dereq_,module,exports){
module.exports = _dereq_('../../full/symbol/to-primitive');
},{"../../full/symbol/to-primitive":172}],169:[function(_dereq_,module,exports){
var parent = _dereq_('../../actual/object/define-property');
module.exports = parent;
},{"../../actual/object/define-property":108}],170:[function(_dereq_,module,exports){
var parent = _dereq_('../../actual/symbol');
_dereq_('../../modules/esnext.symbol.async-dispose');
_dereq_('../../modules/esnext.symbol.is-registered');
_dereq_('../../modules/esnext.symbol.is-well-known');
_dereq_('../../modules/esnext.symbol.matcher');
_dereq_('../../modules/esnext.symbol.metadata-key');
_dereq_('../../modules/esnext.symbol.observable');
// TODO: Remove from `core-js@4`
_dereq_('../../modules/esnext.symbol.metadata');
_dereq_('../../modules/esnext.symbol.pattern-match');
_dereq_('../../modules/esnext.symbol.replace-all');
module.exports = parent;
},{"../../actual/symbol":109,"../../modules/esnext.symbol.async-dispose":418,"../../modules/esnext.symbol.is-registered":420,"../../modules/esnext.symbol.is-well-known":421,"../../modules/esnext.symbol.matcher":422,"../../modules/esnext.symbol.metadata":424,"../../modules/esnext.symbol.metadata-key":423,"../../modules/esnext.symbol.observable":425,"../../modules/esnext.symbol.pattern-match":426,"../../modules/esnext.symbol.replace-all":427}],171:[function(_dereq_,module,exports){
var parent = _dereq_('../../actual/symbol/iterator');
module.exports = parent;
},{"../../actual/symbol/iterator":110}],172:[function(_dereq_,module,exports){
var parent = _dereq_('../../actual/symbol/to-primitive');
module.exports = parent;
},{"../../actual/symbol/to-primitive":111}],173:[function(_dereq_,module,exports){
var isCallable = _dereq_('../internals/is-callable');
var tryToString = _dereq_('../internals/try-to-string');
var $TypeError = TypeError;
// `Assert: IsCallable(argument) is true`
module.exports = function (argument) {
if (isCallable(argument)) return argument;
throw $TypeError(tryToString(argument) + ' is not a function');
};
},{"../internals/is-callable":264,"../internals/try-to-string":335}],174:[function(_dereq_,module,exports){
var isConstructor = _dereq_('../internals/is-constructor');
var tryToString = _dereq_('../internals/try-to-string');
var $TypeError = TypeError;
// `Assert: IsConstructor(argument) is true`
module.exports = function (argument) {
if (isConstructor(argument)) return argument;
throw $TypeError(tryToString(argument) + ' is not a constructor');
};
},{"../internals/is-constructor":265,"../internals/try-to-string":335}],175:[function(_dereq_,module,exports){
var isCallable = _dereq_('../internals/is-callable');
var $String = String;
var $TypeError = TypeError;
module.exports = function (argument) {
if (typeof argument == 'object' || isCallable(argument)) return argument;
throw $TypeError("Can't set " + $String(argument) + ' as a prototype');
};
},{"../internals/is-callable":264}],176:[function(_dereq_,module,exports){
module.exports = function () { /* empty */ };
},{}],177:[function(_dereq_,module,exports){
var isPrototypeOf = _dereq_('../internals/object-is-prototype-of');
var $TypeError = TypeError;
module.exports = function (it, Prototype) {
if (isPrototypeOf(Prototype, it)) return it;
throw $TypeError('Incorrect invocation');
};
},{"../internals/object-is-prototype-of":296}],178:[function(_dereq_,module,exports){
var isObject = _dereq_('../internals/is-object');
var $String = String;
var $TypeError = TypeError;
// `Assert: Type(argument) is Object`
module.exports = function (argument) {
if (isObject(argument)) return argument;
throw $TypeError($String(argument) + ' is not an object');
};
},{"../internals/is-object":269}],179:[function(_dereq_,module,exports){
// FF26- bug: ArrayBuffers are non-extensible, but Object.isExtensible does not report it
var fails = _dereq_('../internals/fails');
module.exports = fails(function () {
if (typeof ArrayBuffer == 'function') {
var buffer = new ArrayBuffer(8);
// eslint-disable-next-line es/no-object-isextensible, es/no-object-defineproperty -- safe
if (Object.isExtensible(buffer)) Object.defineProperty(buffer, 'a', { value: 8 });
}
});
},{"../internals/fails":235}],180:[function(_dereq_,module,exports){
'use strict';
var $forEach = _dereq_('../internals/array-iteration').forEach;
var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict');
var STRICT_METHOD = arrayMethodIsStrict('forEach');
// `Array.prototype.forEach` method implementation
// https://tc39.es/ecma262/#sec-array.prototype.foreach
module.exports = !STRICT_METHOD ? function forEach(callbackfn /* , thisArg */) {
return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
// eslint-disable-next-line es/no-array-prototype-foreach -- safe
} : [].forEach;
},{"../internals/array-iteration":183,"../internals/array-method-is-strict":185}],181:[function(_dereq_,module,exports){
'use strict';
var bind = _dereq_('../internals/function-bind-context');
var call = _dereq_('../internals/function-call');
var toObject = _dereq_('../internals/to-object');
var callWithSafeIterationClosing = _dereq_('../internals/call-with-safe-iteration-closing');
var isArrayIteratorMethod = _dereq_('../internals/is-array-iterator-method');
var isConstructor = _dereq_('../internals/is-constructor');
var lengthOfArrayLike = _dereq_('../internals/length-of-array-like');
var createProperty = _dereq_('../internals/create-property');
var getIterator = _dereq_('../internals/get-iterator');
var getIteratorMethod = _dereq_('../internals/get-iterator-method');
var $Array = Array;
// `Array.from` method implementation
// https://tc39.es/ecma262/#sec-array.from
module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var IS_CONSTRUCTOR = isConstructor(this);
var argumentsLength = arguments.length;
var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined);
var iteratorMethod = getIteratorMethod(O);
var index = 0;
var length, result, step, iterator, next, value;
// if the target is not iterable or it's an array with the default iterator - use a simple case
if (iteratorMethod && !(this === $Array && isArrayIteratorMethod(iteratorMethod))) {
iterator = getIterator(O, iteratorMethod);
next = iterator.next;
result = IS_CONSTRUCTOR ? new this() : [];
for (;!(step = call(next, iterator)).done; index++) {
value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
createProperty(result, index, value);
}
} else {
length = lengthOfArrayLike(O);
result = IS_CONSTRUCTOR ? new this(length) : $Array(length);
for (;length > index; index++) {
value = mapping ? mapfn(O[index], index) : O[index];
createProperty(result, index, value);
}
}
result.length = index;
return result;
};
},{"../internals/call-with-safe-iteration-closing":193,"../internals/create-property":206,"../internals/function-bind-context":238,"../internals/function-call":241,"../internals/get-iterator":248,"../internals/get-iterator-method":247,"../internals/is-array-iterator-method":262,"../internals/is-constructor":265,"../internals/length-of-array-like":279,"../internals/to-object":330}],182:[function(_dereq_,module,exports){
var toIndexedObject = _dereq_('../internals/to-indexed-object');
var toAbsoluteIndex = _dereq_('../internals/to-absolute-index');
var lengthOfArrayLike = _dereq_('../internals/length-of-array-like');
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject($this);
var length = lengthOfArrayLike(O);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare -- NaN check
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare -- NaN check
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
module.exports = {
// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
includes: createMethod(true),
// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
indexOf: createMethod(false)
};
},{"../internals/length-of-array-like":279,"../internals/to-absolute-index":326,"../internals/to-indexed-object":327}],183:[function(_dereq_,module,exports){
var bind = _dereq_('../internals/function-bind-context');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var IndexedObject = _dereq_('../internals/indexed-object');
var toObject = _dereq_('../internals/to-object');
var lengthOfArrayLike = _dereq_('../internals/length-of-array-like');
var arraySpeciesCreate = _dereq_('../internals/array-species-create');
var push = uncurryThis([].push);
// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterReject }` methods implementation
var createMethod = function (TYPE) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var IS_FILTER_REJECT = TYPE == 7;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
return function ($this, callbackfn, that, specificCreate) {
var O = toObject($this);
var self = IndexedObject(O);
var boundFunction = bind(callbackfn, that);
var length = lengthOfArrayLike(self);
var index = 0;
var create = specificCreate || arraySpeciesCreate;
var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_REJECT ? create($this, 0) : undefined;
var value, result;
for (;length > index; index++) if (NO_HOLES || index in self) {
value = self[index];
result = boundFunction(value, index, O);
if (TYPE) {
if (IS_MAP) target[index] = result; // map
else if (result) switch (TYPE) {
case 3: return true; // some
case 5: return value; // find
case 6: return index; // findIndex
case 2: push(target, value); // filter
} else switch (TYPE) {
case 4: return false; // every
case 7: push(target, value); // filterReject
}
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
};
};
module.exports = {
// `Array.prototype.forEach` method
// https://tc39.es/ecma262/#sec-array.prototype.foreach
forEach: createMethod(0),
// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
map: createMethod(1),
// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
filter: createMethod(2),
// `Array.prototype.some` method
// https://tc39.es/ecma262/#sec-array.prototype.some
some: createMethod(3),
// `Array.prototype.every` method
// https://tc39.es/ecma262/#sec-array.prototype.every
every: createMethod(4),
// `Array.prototype.find` method
// https://tc39.es/ecma262/#sec-array.prototype.find
find: createMethod(5),
// `Array.prototype.findIndex` method
// https://tc39.es/ecma262/#sec-array.prototype.findIndex
findIndex: createMethod(6),
// `Array.prototype.filterReject` method
// https://github.com/tc39/proposal-array-filtering
filterReject: createMethod(7)
};
},{"../internals/array-species-create":192,"../internals/function-bind-context":238,"../internals/function-uncurry-this":245,"../internals/indexed-object":257,"../internals/length-of-array-like":279,"../internals/to-object":330}],184:[function(_dereq_,module,exports){
var fails = _dereq_('../internals/fails');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var V8_VERSION = _dereq_('../internals/engine-v8-version');
var SPECIES = wellKnownSymbol('species');
module.exports = function (METHOD_NAME) {
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/677
return V8_VERSION >= 51 || !fails(function () {
var array = [];
var constructor = array.constructor = {};
constructor[SPECIES] = function () {
return { foo: 1 };
};
return array[METHOD_NAME](Boolean).foo !== 1;
});
};
},{"../internals/engine-v8-version":227,"../internals/fails":235,"../internals/well-known-symbol":343}],185:[function(_dereq_,module,exports){
'use strict';
var fails = _dereq_('../internals/fails');
module.exports = function (METHOD_NAME, argument) {
var method = [][METHOD_NAME];
return !!method && fails(function () {
// eslint-disable-next-line no-useless-call -- required for testing
method.call(null, argument || function () { return 1; }, 1);
});
};
},{"../internals/fails":235}],186:[function(_dereq_,module,exports){
var aCallable = _dereq_('../internals/a-callable');
var toObject = _dereq_('../internals/to-object');
var IndexedObject = _dereq_('../internals/indexed-object');
var lengthOfArrayLike = _dereq_('../internals/length-of-array-like');
var $TypeError = TypeError;
// `Array.prototype.{ reduce, reduceRight }` methods implementation
var createMethod = function (IS_RIGHT) {
return function (that, callbackfn, argumentsLength, memo) {
aCallable(callbackfn);
var O = toObject(that);
var self = IndexedObject(O);
var length = lengthOfArrayLike(O);
var index = IS_RIGHT ? length - 1 : 0;
var i = IS_RIGHT ? -1 : 1;
if (argumentsLength < 2) while (true) {
if (index in self) {
memo = self[index];
index += i;
break;
}
index += i;
if (IS_RIGHT ? index < 0 : length <= index) {
throw $TypeError('Reduce of empty array with no initial value');
}
}
for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
};
module.exports = {
// `Array.prototype.reduce` method
// https://tc39.es/ecma262/#sec-array.prototype.reduce
left: createMethod(false),
// `Array.prototype.reduceRight` method
// https://tc39.es/ecma262/#sec-array.prototype.reduceright
right: createMethod(true)
};
},{"../internals/a-callable":173,"../internals/indexed-object":257,"../internals/length-of-array-like":279,"../internals/to-object":330}],187:[function(_dereq_,module,exports){
'use strict';
var DESCRIPTORS = _dereq_('../internals/descriptors');
var isArray = _dereq_('../internals/is-array');
var $TypeError = TypeError;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Safari < 13 does not throw an error in this case
var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
// makes no sense without proper strict mode support
if (this !== undefined) return true;
try {
// eslint-disable-next-line es/no-object-defineproperty -- safe
Object.defineProperty([], 'length', { writable: false }).length = 1;
} catch (error) {
return error instanceof TypeError;
}
}();
module.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
throw $TypeError('Cannot set read only .length');
} return O.length = length;
} : function (O, length) {
return O.length = length;
};
},{"../internals/descriptors":212,"../internals/is-array":263}],188:[function(_dereq_,module,exports){
var toAbsoluteIndex = _dereq_('../internals/to-absolute-index');
var lengthOfArrayLike = _dereq_('../internals/length-of-array-like');
var createProperty = _dereq_('../internals/create-property');
var $Array = Array;
var max = Math.max;
module.exports = function (O, start, end) {
var length = lengthOfArrayLike(O);
var k = toAbsoluteIndex(start, length);
var fin = toAbsoluteIndex(end === undefined ? length : end, length);
var result = $Array(max(fin - k, 0));
for (var n = 0; k < fin; k++, n++) createProperty(result, n, O[k]);
result.length = n;
return result;
};
},{"../internals/create-property":206,"../internals/length-of-array-like":279,"../internals/to-absolute-index":326}],189:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
module.exports = uncurryThis([].slice);
},{"../internals/function-uncurry-this":245}],190:[function(_dereq_,module,exports){
var arraySlice = _dereq_('../internals/array-slice-simple');
var floor = Math.floor;
var mergeSort = function (array, comparefn) {
var length = array.length;
var middle = floor(length / 2);
return length < 8 ? insertionSort(array, comparefn) : merge(
array,
mergeSort(arraySlice(array, 0, middle), comparefn),
mergeSort(arraySlice(array, middle), comparefn),
comparefn
);
};
var insertionSort = function (array, comparefn) {
var length = array.length;
var i = 1;
var element, j;
while (i < length) {
j = i;
element = array[i];
while (j && comparefn(array[j - 1], element) > 0) {
array[j] = array[--j];
}
if (j !== i++) array[j] = element;
} return array;
};
var merge = function (array, left, right, comparefn) {
var llength = left.length;
var rlength = right.length;
var lindex = 0;
var rindex = 0;
while (lindex < llength || rindex < rlength) {
array[lindex + rindex] = (lindex < llength && rindex < rlength)
? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++]
: lindex < llength ? left[lindex++] : right[rindex++];
} return array;
};
module.exports = mergeSort;
},{"../internals/array-slice-simple":188}],191:[function(_dereq_,module,exports){
var isArray = _dereq_('../internals/is-array');
var isConstructor = _dereq_('../internals/is-constructor');
var isObject = _dereq_('../internals/is-object');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var SPECIES = wellKnownSymbol('species');
var $Array = Array;
// a part of `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
module.exports = function (originalArray) {
var C;
if (isArray(originalArray)) {
C = originalArray.constructor;
// cross-realm fallback
if (isConstructor(C) && (C === $Array || isArray(C.prototype))) C = undefined;
else if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return C === undefined ? $Array : C;
};
},{"../internals/is-array":263,"../internals/is-constructor":265,"../internals/is-object":269,"../internals/well-known-symbol":343}],192:[function(_dereq_,module,exports){
var arraySpeciesConstructor = _dereq_('../internals/array-species-constructor');
// `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
module.exports = function (originalArray, length) {
return new (arraySpeciesConstructor(originalArray))(length === 0 ? 0 : length);
};
},{"../internals/array-species-constructor":191}],193:[function(_dereq_,module,exports){
var anObject = _dereq_('../internals/an-object');
var iteratorClose = _dereq_('../internals/iterator-close');
// call something on iterator step with safe closing on error
module.exports = function (iterator, fn, value, ENTRIES) {
try {
return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
} catch (error) {
iteratorClose(iterator, 'throw', error);
}
};
},{"../internals/an-object":178,"../internals/iterator-close":274}],194:[function(_dereq_,module,exports){
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var ITERATOR = wellKnownSymbol('iterator');
var SAFE_CLOSING = false;
try {
var called = 0;
var iteratorWithReturn = {
next: function () {
return { done: !!called++ };
},
'return': function () {
SAFE_CLOSING = true;
}
};
iteratorWithReturn[ITERATOR] = function () {
return this;
};
// eslint-disable-next-line es/no-array-from, no-throw-literal -- required for testing
Array.from(iteratorWithReturn, function () { throw 2; });
} catch (error) { /* empty */ }
module.exports = function (exec, SKIP_CLOSING) {
if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
var ITERATION_SUPPORT = false;
try {
var object = {};
object[ITERATOR] = function () {
return {
next: function () {
return { done: ITERATION_SUPPORT = true };
}
};
};
exec(object);
} catch (error) { /* empty */ }
return ITERATION_SUPPORT;
};
},{"../internals/well-known-symbol":343}],195:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var toString = uncurryThis({}.toString);
var stringSlice = uncurryThis(''.slice);
module.exports = function (it) {
return stringSlice(toString(it), 8, -1);
};
},{"../internals/function-uncurry-this":245}],196:[function(_dereq_,module,exports){
var TO_STRING_TAG_SUPPORT = _dereq_('../internals/to-string-tag-support');
var isCallable = _dereq_('../internals/is-callable');
var classofRaw = _dereq_('../internals/classof-raw');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var $Object = Object;
// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (error) { /* empty */ }
};
// getting tag from ES6+ `Object.prototype.toString`
module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
var O, tag, result;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
// builtinTag case
: CORRECT_ARGUMENTS ? classofRaw(O)
// ES3 arguments fallback
: (result = classofRaw(O)) == 'Object' && isCallable(O.callee) ? 'Arguments' : result;
};
},{"../internals/classof-raw":195,"../internals/is-callable":264,"../internals/to-string-tag-support":333,"../internals/well-known-symbol":343}],197:[function(_dereq_,module,exports){
'use strict';
var create = _dereq_('../internals/object-create');
var defineBuiltInAccessor = _dereq_('../internals/define-built-in-accessor');
var defineBuiltIns = _dereq_('../internals/define-built-ins');
var bind = _dereq_('../internals/function-bind-context');
var anInstance = _dereq_('../internals/an-instance');
var isNullOrUndefined = _dereq_('../internals/is-null-or-undefined');
var iterate = _dereq_('../internals/iterate');
var defineIterator = _dereq_('../internals/iterator-define');
var createIterResultObject = _dereq_('../internals/create-iter-result-object');
var setSpecies = _dereq_('../internals/set-species');
var DESCRIPTORS = _dereq_('../internals/descriptors');
var fastKey = _dereq_('../internals/internal-metadata').fastKey;
var InternalStateModule = _dereq_('../internals/internal-state');
var setInternalState = InternalStateModule.set;
var internalStateGetterFor = InternalStateModule.getterFor;
module.exports = {
getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {
var Constructor = wrapper(function (that, iterable) {
anInstance(that, Prototype);
setInternalState(that, {
type: CONSTRUCTOR_NAME,
index: create(null),
first: undefined,
last: undefined,
size: 0
});
if (!DESCRIPTORS) that.size = 0;
if (!isNullOrUndefined(iterable)) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });
});
var Prototype = Constructor.prototype;
var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);
var define = function (that, key, value) {
var state = getInternalState(that);
var entry = getEntry(that, key);
var previous, index;
// change existing entry
if (entry) {
entry.value = value;
// create new entry
} else {
state.last = entry = {
index: index = fastKey(key, true),
key: key,
value: value,
previous: previous = state.last,
next: undefined,
removed: false
};
if (!state.first) state.first = entry;
if (previous) previous.next = entry;
if (DESCRIPTORS) state.size++;
else that.size++;
// add to index
if (index !== 'F') state.index[index] = entry;
} return that;
};
var getEntry = function (that, key) {
var state = getInternalState(that);
// fast case
var index = fastKey(key);
var entry;
if (index !== 'F') return state.index[index];
// frozen object case
for (entry = state.first; entry; entry = entry.next) {
if (entry.key == key) return entry;
}
};
defineBuiltIns(Prototype, {
// `{ Map, Set }.prototype.clear()` methods
// https://tc39.es/ecma262/#sec-map.prototype.clear
// https://tc39.es/ecma262/#sec-set.prototype.clear
clear: function clear() {
var that = this;
var state = getInternalState(that);
var data = state.index;
var entry = state.first;
while (entry) {
entry.removed = true;
if (entry.previous) entry.previous = entry.previous.next = undefined;
delete data[entry.index];
entry = entry.next;
}
state.first = state.last = undefined;
if (DESCRIPTORS) state.size = 0;
else that.size = 0;
},
// `{ Map, Set }.prototype.delete(key)` methods
// https://tc39.es/ecma262/#sec-map.prototype.delete
// https://tc39.es/ecma262/#sec-set.prototype.delete
'delete': function (key) {
var that = this;
var state = getInternalState(that);
var entry = getEntry(that, key);
if (entry) {
var next = entry.next;
var prev = entry.previous;
delete state.index[entry.index];
entry.removed = true;
if (prev) prev.next = next;
if (next) next.previous = prev;
if (state.first == entry) state.first = next;
if (state.last == entry) state.last = prev;
if (DESCRIPTORS) state.size--;
else that.size--;
} return !!entry;
},
// `{ Map, Set }.prototype.forEach(callbackfn, thisArg = undefined)` methods
// https://tc39.es/ecma262/#sec-map.prototype.foreach
// https://tc39.es/ecma262/#sec-set.prototype.foreach
forEach: function forEach(callbackfn /* , that = undefined */) {
var state = getInternalState(this);
var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
var entry;
while (entry = entry ? entry.next : state.first) {
boundFunction(entry.value, entry.key, this);
// revert to the last existing entry
while (entry && entry.removed) entry = entry.previous;
}
},
// `{ Map, Set}.prototype.has(key)` methods
// https://tc39.es/ecma262/#sec-map.prototype.has
// https://tc39.es/ecma262/#sec-set.prototype.has
has: function has(key) {
return !!getEntry(this, key);
}
});
defineBuiltIns(Prototype, IS_MAP ? {
// `Map.prototype.get(key)` method
// https://tc39.es/ecma262/#sec-map.prototype.get
get: function get(key) {
var entry = getEntry(this, key);
return entry && entry.value;
},
// `Map.prototype.set(key, value)` method
// https://tc39.es/ecma262/#sec-map.prototype.set
set: function set(key, value) {
return define(this, key === 0 ? 0 : key, value);
}
} : {
// `Set.prototype.add(value)` method
// https://tc39.es/ecma262/#sec-set.prototype.add
add: function add(value) {
return define(this, value = value === 0 ? 0 : value, value);
}
});
if (DESCRIPTORS) defineBuiltInAccessor(Prototype, 'size', {
configurable: true,
get: function () {
return getInternalState(this).size;
}
});
return Constructor;
},
setStrong: function (Constructor, CONSTRUCTOR_NAME, IS_MAP) {
var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator';
var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME);
var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME);
// `{ Map, Set }.prototype.{ keys, values, entries, @@iterator }()` methods
// https://tc39.es/ecma262/#sec-map.prototype.entries
// https://tc39.es/ecma262/#sec-map.prototype.keys
// https://tc39.es/ecma262/#sec-map.prototype.values
// https://tc39.es/ecma262/#sec-map.prototype-@@iterator
// https://tc39.es/ecma262/#sec-set.prototype.entries
// https://tc39.es/ecma262/#sec-set.prototype.keys
// https://tc39.es/ecma262/#sec-set.prototype.values
// https://tc39.es/ecma262/#sec-set.prototype-@@iterator
defineIterator(Constructor, CONSTRUCTOR_NAME, function (iterated, kind) {
setInternalState(this, {
type: ITERATOR_NAME,
target: iterated,
state: getInternalCollectionState(iterated),
kind: kind,
last: undefined
});
}, function () {
var state = getInternalIteratorState(this);
var kind = state.kind;
var entry = state.last;
// revert to the last existing entry
while (entry && entry.removed) entry = entry.previous;
// get next entry
if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) {
// or finish the iteration
state.target = undefined;
return createIterResultObject(undefined, true);
}
// return step by kind
if (kind == 'keys') return createIterResultObject(entry.key, false);
if (kind == 'values') return createIterResultObject(entry.value, false);
return createIterResultObject([entry.key, entry.value], false);
}, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
// `{ Map, Set }.prototype[@@species]` accessors
// https://tc39.es/ecma262/#sec-get-map-@@species
// https://tc39.es/ecma262/#sec-get-set-@@species
setSpecies(CONSTRUCTOR_NAME);
}
};
},{"../internals/an-instance":177,"../internals/create-iter-result-object":203,"../internals/define-built-in-accessor":207,"../internals/define-built-ins":209,"../internals/descriptors":212,"../internals/function-bind-context":238,"../internals/internal-metadata":260,"../internals/internal-state":261,"../internals/is-null-or-undefined":268,"../internals/iterate":273,"../internals/iterator-define":276,"../internals/object-create":287,"../internals/set-species":314}],198:[function(_dereq_,module,exports){
'use strict';
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var defineBuiltIns = _dereq_('../internals/define-built-ins');
var getWeakData = _dereq_('../internals/internal-metadata').getWeakData;
var anInstance = _dereq_('../internals/an-instance');
var anObject = _dereq_('../internals/an-object');
var isNullOrUndefined = _dereq_('../internals/is-null-or-undefined');
var isObject = _dereq_('../internals/is-object');
var iterate = _dereq_('../internals/iterate');
var ArrayIterationModule = _dereq_('../internals/array-iteration');
var hasOwn = _dereq_('../internals/has-own-property');
var InternalStateModule = _dereq_('../internals/internal-state');
var setInternalState = InternalStateModule.set;
var internalStateGetterFor = InternalStateModule.getterFor;
var find = ArrayIterationModule.find;
var findIndex = ArrayIterationModule.findIndex;
var splice = uncurryThis([].splice);
var id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function (state) {
return state.frozen || (state.frozen = new UncaughtFrozenStore());
};
var UncaughtFrozenStore = function () {
this.entries = [];
};
var findUncaughtFrozen = function (store, key) {
return find(store.entries, function (it) {
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function (key) {
var entry = findUncaughtFrozen(this, key);
if (entry) return entry[1];
},
has: function (key) {
return !!findUncaughtFrozen(this, key);
},
set: function (key, value) {
var entry = findUncaughtFrozen(this, key);
if (entry) entry[1] = value;
else this.entries.push([key, value]);
},
'delete': function (key) {
var index = findIndex(this.entries, function (it) {
return it[0] === key;
});
if (~index) splice(this.entries, index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {
var Constructor = wrapper(function (that, iterable) {
anInstance(that, Prototype);
setInternalState(that, {
type: CONSTRUCTOR_NAME,
id: id++,
frozen: undefined
});
if (!isNullOrUndefined(iterable)) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });
});
var Prototype = Constructor.prototype;
var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);
var define = function (that, key, value) {
var state = getInternalState(that);
var data = getWeakData(anObject(key), true);
if (data === true) uncaughtFrozenStore(state).set(key, value);
else data[state.id] = value;
return that;
};
defineBuiltIns(Prototype, {
// `{ WeakMap, WeakSet }.prototype.delete(key)` methods
// https://tc39.es/ecma262/#sec-weakmap.prototype.delete
// https://tc39.es/ecma262/#sec-weakset.prototype.delete
'delete': function (key) {
var state = getInternalState(this);
if (!isObject(key)) return false;
var data = getWeakData(key);
if (data === true) return uncaughtFrozenStore(state)['delete'](key);
return data && hasOwn(data, state.id) && delete data[state.id];
},
// `{ WeakMap, WeakSet }.prototype.has(key)` methods
// https://tc39.es/ecma262/#sec-weakmap.prototype.has
// https://tc39.es/ecma262/#sec-weakset.prototype.has
has: function has(key) {
var state = getInternalState(this);
if (!isObject(key)) return false;
var data = getWeakData(key);
if (data === true) return uncaughtFrozenStore(state).has(key);
return data && hasOwn(data, state.id);
}
});
defineBuiltIns(Prototype, IS_MAP ? {
// `WeakMap.prototype.get(key)` method
// https://tc39.es/ecma262/#sec-weakmap.prototype.get
get: function get(key) {
var state = getInternalState(this);
if (isObject(key)) {
var data = getWeakData(key);
if (data === true) return uncaughtFrozenStore(state).get(key);
return data ? data[state.id] : undefined;
}
},
// `WeakMap.prototype.set(key, value)` method
// https://tc39.es/ecma262/#sec-weakmap.prototype.set
set: function set(key, value) {
return define(this, key, value);
}
} : {
// `WeakSet.prototype.add(value)` method
// https://tc39.es/ecma262/#sec-weakset.prototype.add
add: function add(value) {
return define(this, value, true);
}
});
return Constructor;
}
};
},{"../internals/an-instance":177,"../internals/an-object":178,"../internals/array-iteration":183,"../internals/define-built-ins":209,"../internals/function-uncurry-this":245,"../internals/has-own-property":252,"../internals/internal-metadata":260,"../internals/internal-state":261,"../internals/is-null-or-undefined":268,"../internals/is-object":269,"../internals/iterate":273}],199:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var global = _dereq_('../internals/global');
var InternalMetadataModule = _dereq_('../internals/internal-metadata');
var fails = _dereq_('../internals/fails');
var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property');
var iterate = _dereq_('../internals/iterate');
var anInstance = _dereq_('../internals/an-instance');
var isCallable = _dereq_('../internals/is-callable');
var isObject = _dereq_('../internals/is-object');
var setToStringTag = _dereq_('../internals/set-to-string-tag');
var defineProperty = _dereq_('../internals/object-define-property').f;
var forEach = _dereq_('../internals/array-iteration').forEach;
var DESCRIPTORS = _dereq_('../internals/descriptors');
var InternalStateModule = _dereq_('../internals/internal-state');
var setInternalState = InternalStateModule.set;
var internalStateGetterFor = InternalStateModule.getterFor;
module.exports = function (CONSTRUCTOR_NAME, wrapper, common) {
var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1;
var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1;
var ADDER = IS_MAP ? 'set' : 'add';
var NativeConstructor = global[CONSTRUCTOR_NAME];
var NativePrototype = NativeConstructor && NativeConstructor.prototype;
var exported = {};
var Constructor;
if (!DESCRIPTORS || !isCallable(NativeConstructor)
|| !(IS_WEAK || NativePrototype.forEach && !fails(function () { new NativeConstructor().entries().next(); }))
) {
// create collection constructor
Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER);
InternalMetadataModule.enable();
} else {
Constructor = wrapper(function (target, iterable) {
setInternalState(anInstance(target, Prototype), {
type: CONSTRUCTOR_NAME,
collection: new NativeConstructor()
});
if (iterable != undefined) iterate(iterable, target[ADDER], { that: target, AS_ENTRIES: IS_MAP });
});
var Prototype = Constructor.prototype;
var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);
forEach(['add', 'clear', 'delete', 'forEach', 'get', 'has', 'set', 'keys', 'values', 'entries'], function (KEY) {
var IS_ADDER = KEY == 'add' || KEY == 'set';
if (KEY in NativePrototype && !(IS_WEAK && KEY == 'clear')) {
createNonEnumerableProperty(Prototype, KEY, function (a, b) {
var collection = getInternalState(this).collection;
if (!IS_ADDER && IS_WEAK && !isObject(a)) return KEY == 'get' ? undefined : false;
var result = collection[KEY](a === 0 ? 0 : a, b);
return IS_ADDER ? this : result;
});
}
});
IS_WEAK || defineProperty(Prototype, 'size', {
configurable: true,
get: function () {
return getInternalState(this).collection.size;
}
});
}
setToStringTag(Constructor, CONSTRUCTOR_NAME, false, true);
exported[CONSTRUCTOR_NAME] = Constructor;
$({ global: true, forced: true }, exported);
if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP);
return Constructor;
};
},{"../internals/an-instance":177,"../internals/array-iteration":183,"../internals/create-non-enumerable-property":204,"../internals/descriptors":212,"../internals/export":234,"../internals/fails":235,"../internals/global":251,"../internals/internal-metadata":260,"../internals/internal-state":261,"../internals/is-callable":264,"../internals/is-object":269,"../internals/iterate":273,"../internals/object-define-property":289,"../internals/set-to-string-tag":315}],200:[function(_dereq_,module,exports){
var hasOwn = _dereq_('../internals/has-own-property');
var ownKeys = _dereq_('../internals/own-keys');
var getOwnPropertyDescriptorModule = _dereq_('../internals/object-get-own-property-descriptor');
var definePropertyModule = _dereq_('../internals/object-define-property');
module.exports = function (target, source, exceptions) {
var keys = ownKeys(source);
var defineProperty = definePropertyModule.f;
var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
}
};
},{"../internals/has-own-property":252,"../internals/object-define-property":289,"../internals/object-get-own-property-descriptor":290,"../internals/own-keys":304}],201:[function(_dereq_,module,exports){
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var MATCH = wellKnownSymbol('match');
module.exports = function (METHOD_NAME) {
var regexp = /./;
try {
'/./'[METHOD_NAME](regexp);
} catch (error1) {
try {
regexp[MATCH] = false;
return '/./'[METHOD_NAME](regexp);
} catch (error2) { /* empty */ }
} return false;
};
},{"../internals/well-known-symbol":343}],202:[function(_dereq_,module,exports){
var fails = _dereq_('../internals/fails');
module.exports = !fails(function () {
function F() { /* empty */ }
F.prototype.constructor = null;
// eslint-disable-next-line es/no-object-getprototypeof -- required for testing
return Object.getPrototypeOf(new F()) !== F.prototype;
});
},{"../internals/fails":235}],203:[function(_dereq_,module,exports){
// `CreateIterResultObject` abstract operation
// https://tc39.es/ecma262/#sec-createiterresultobject
module.exports = function (value, done) {
return { value: value, done: done };
};
},{}],204:[function(_dereq_,module,exports){
var DESCRIPTORS = _dereq_('../internals/descriptors');
var definePropertyModule = _dereq_('../internals/object-define-property');
var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor');
module.exports = DESCRIPTORS ? function (object, key, value) {
return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
},{"../internals/create-property-descriptor":205,"../internals/descriptors":212,"../internals/object-define-property":289}],205:[function(_dereq_,module,exports){
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
},{}],206:[function(_dereq_,module,exports){
'use strict';
var toPropertyKey = _dereq_('../internals/to-property-key');
var definePropertyModule = _dereq_('../internals/object-define-property');
var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor');
module.exports = function (object, key, value) {
var propertyKey = toPropertyKey(key);
if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value));
else object[propertyKey] = value;
};
},{"../internals/create-property-descriptor":205,"../internals/object-define-property":289,"../internals/to-property-key":332}],207:[function(_dereq_,module,exports){
var defineProperty = _dereq_('../internals/object-define-property');
module.exports = function (target, name, descriptor) {
return defineProperty.f(target, name, descriptor);
};
},{"../internals/object-define-property":289}],208:[function(_dereq_,module,exports){
var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property');
module.exports = function (target, key, value, options) {
if (options && options.enumerable) target[key] = value;
else createNonEnumerableProperty(target, key, value);
return target;
};
},{"../internals/create-non-enumerable-property":204}],209:[function(_dereq_,module,exports){
var defineBuiltIn = _dereq_('../internals/define-built-in');
module.exports = function (target, src, options) {
for (var key in src) {
if (options && options.unsafe && target[key]) target[key] = src[key];
else defineBuiltIn(target, key, src[key], options);
} return target;
};
},{"../internals/define-built-in":208}],210:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
// eslint-disable-next-line es/no-object-defineproperty -- safe
var defineProperty = Object.defineProperty;
module.exports = function (key, value) {
try {
defineProperty(global, key, { value: value, configurable: true, writable: true });
} catch (error) {
global[key] = value;
} return value;
};
},{"../internals/global":251}],211:[function(_dereq_,module,exports){
'use strict';
var tryToString = _dereq_('../internals/try-to-string');
var $TypeError = TypeError;
module.exports = function (O, P) {
if (!delete O[P]) throw $TypeError('Cannot delete property ' + tryToString(P) + ' of ' + tryToString(O));
};
},{"../internals/try-to-string":335}],212:[function(_dereq_,module,exports){
var fails = _dereq_('../internals/fails');
// Detect IE8's incomplete defineProperty implementation
module.exports = !fails(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
});
},{"../internals/fails":235}],213:[function(_dereq_,module,exports){
var documentAll = typeof document == 'object' && document.all;
// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
// eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
var IS_HTMLDDA = typeof documentAll == 'undefined' && documentAll !== undefined;
module.exports = {
all: documentAll,
IS_HTMLDDA: IS_HTMLDDA
};
},{}],214:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
var isObject = _dereq_('../internals/is-object');
var document = global.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return EXISTS ? document.createElement(it) : {};
};
},{"../internals/global":251,"../internals/is-object":269}],215:[function(_dereq_,module,exports){
var $TypeError = TypeError;
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
module.exports = function (it) {
if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
return it;
};
},{}],216:[function(_dereq_,module,exports){
// iterable DOM collections
// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
module.exports = {
CSSRuleList: 0,
CSSStyleDeclaration: 0,
CSSValueList: 0,
ClientRectList: 0,
DOMRectList: 0,
DOMStringList: 0,
DOMTokenList: 1,
DataTransferItemList: 0,
FileList: 0,
HTMLAllCollection: 0,
HTMLCollection: 0,
HTMLFormElement: 0,
HTMLSelectElement: 0,
MediaList: 0,
MimeTypeArray: 0,
NamedNodeMap: 0,
NodeList: 1,
PaintRequestList: 0,
Plugin: 0,
PluginArray: 0,
SVGLengthList: 0,
SVGNumberList: 0,
SVGPathSegList: 0,
SVGPointList: 0,
SVGStringList: 0,
SVGTransformList: 0,
SourceBufferList: 0,
StyleSheetList: 0,
TextTrackCueList: 0,
TextTrackList: 0,
TouchList: 0
};
},{}],217:[function(_dereq_,module,exports){
var userAgent = _dereq_('../internals/engine-user-agent');
var firefox = userAgent.match(/firefox\/(\d+)/i);
module.exports = !!firefox && +firefox[1];
},{"../internals/engine-user-agent":226}],218:[function(_dereq_,module,exports){
var IS_DENO = _dereq_('../internals/engine-is-deno');
var IS_NODE = _dereq_('../internals/engine-is-node');
module.exports = !IS_DENO && !IS_NODE
&& typeof window == 'object'
&& typeof document == 'object';
},{"../internals/engine-is-deno":220,"../internals/engine-is-node":224}],219:[function(_dereq_,module,exports){
/* global Bun -- Deno case */
module.exports = typeof Bun == 'function' && Bun && typeof Bun.version == 'string';
},{}],220:[function(_dereq_,module,exports){
/* global Deno -- Deno case */
module.exports = typeof Deno == 'object' && Deno && typeof Deno.version == 'object';
},{}],221:[function(_dereq_,module,exports){
var UA = _dereq_('../internals/engine-user-agent');
module.exports = /MSIE|Trident/.test(UA);
},{"../internals/engine-user-agent":226}],222:[function(_dereq_,module,exports){
var userAgent = _dereq_('../internals/engine-user-agent');
module.exports = /ipad|iphone|ipod/i.test(userAgent) && typeof Pebble != 'undefined';
},{"../internals/engine-user-agent":226}],223:[function(_dereq_,module,exports){
var userAgent = _dereq_('../internals/engine-user-agent');
// eslint-disable-next-line redos/no-vulnerable -- safe
module.exports = /(?:ipad|iphone|ipod).*applewebkit/i.test(userAgent);
},{"../internals/engine-user-agent":226}],224:[function(_dereq_,module,exports){
(function (process){(function (){
var classof = _dereq_('../internals/classof-raw');
module.exports = typeof process != 'undefined' && classof(process) == 'process';
}).call(this)}).call(this,_dereq_('_process'))
},{"../internals/classof-raw":195,"_process":107}],225:[function(_dereq_,module,exports){
var userAgent = _dereq_('../internals/engine-user-agent');
module.exports = /web0s(?!.*chrome)/i.test(userAgent);
},{"../internals/engine-user-agent":226}],226:[function(_dereq_,module,exports){
module.exports = typeof navigator != 'undefined' && String(navigator.userAgent) || '';
},{}],227:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
var userAgent = _dereq_('../internals/engine-user-agent');
var process = global.process;
var Deno = global.Deno;
var versions = process && process.versions || Deno && Deno.version;
var v8 = versions && versions.v8;
var match, version;
if (v8) {
match = v8.split('.');
// in old Chrome, versions of V8 isn't V8 = Chrome / 10
// but their correct versions are not interesting for us
version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
}
// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
// so check `userAgent` even if `.v8` exists, but 0
if (!version && userAgent) {
match = userAgent.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = userAgent.match(/Chrome\/(\d+)/);
if (match) version = +match[1];
}
}
module.exports = version;
},{"../internals/engine-user-agent":226,"../internals/global":251}],228:[function(_dereq_,module,exports){
var userAgent = _dereq_('../internals/engine-user-agent');
var webkit = userAgent.match(/AppleWebKit\/(\d+)\./);
module.exports = !!webkit && +webkit[1];
},{"../internals/engine-user-agent":226}],229:[function(_dereq_,module,exports){
var path = _dereq_('../internals/path');
module.exports = function (CONSTRUCTOR) {
return path[CONSTRUCTOR + 'Prototype'];
};
},{"../internals/path":305}],230:[function(_dereq_,module,exports){
// IE8- don't enum bug keys
module.exports = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
},{}],231:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var $Error = Error;
var replace = uncurryThis(''.replace);
var TEST = (function (arg) { return String($Error(arg).stack); })('zxcasd');
// eslint-disable-next-line redos/no-vulnerable -- safe
var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
module.exports = function (stack, dropEntries) {
if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
} return stack;
};
},{"../internals/function-uncurry-this":245}],232:[function(_dereq_,module,exports){
var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property');
var clearErrorStack = _dereq_('../internals/error-stack-clear');
var ERROR_STACK_INSTALLABLE = _dereq_('../internals/error-stack-installable');
// non-standard V8
var captureStackTrace = Error.captureStackTrace;
module.exports = function (error, C, stack, dropEntries) {
if (ERROR_STACK_INSTALLABLE) {
if (captureStackTrace) captureStackTrace(error, C);
else createNonEnumerableProperty(error, 'stack', clearErrorStack(stack, dropEntries));
}
};
},{"../internals/create-non-enumerable-property":204,"../internals/error-stack-clear":231,"../internals/error-stack-installable":233}],233:[function(_dereq_,module,exports){
var fails = _dereq_('../internals/fails');
var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor');
module.exports = !fails(function () {
var error = Error('a');
if (!('stack' in error)) return true;
// eslint-disable-next-line es/no-object-defineproperty -- safe
Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7));
return error.stack !== 7;
});
},{"../internals/create-property-descriptor":205,"../internals/fails":235}],234:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_('../internals/global');
var apply = _dereq_('../internals/function-apply');
var uncurryThis = _dereq_('../internals/function-uncurry-this-clause');
var isCallable = _dereq_('../internals/is-callable');
var getOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f;
var isForced = _dereq_('../internals/is-forced');
var path = _dereq_('../internals/path');
var bind = _dereq_('../internals/function-bind-context');
var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property');
var hasOwn = _dereq_('../internals/has-own-property');
var wrapConstructor = function (NativeConstructor) {
var Wrapper = function (a, b, c) {
if (this instanceof Wrapper) {
switch (arguments.length) {
case 0: return new NativeConstructor();
case 1: return new NativeConstructor(a);
case 2: return new NativeConstructor(a, b);
} return new NativeConstructor(a, b, c);
} return apply(NativeConstructor, this, arguments);
};
Wrapper.prototype = NativeConstructor.prototype;
return Wrapper;
};
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.dontCallGetSet - prevent calling a getter on target
options.name - the .name of the function if it does not match the key
*/
module.exports = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var PROTO = options.proto;
var nativeSource = GLOBAL ? global : STATIC ? global[TARGET] : (global[TARGET] || {}).prototype;
var target = GLOBAL ? path : path[TARGET] || createNonEnumerableProperty(path, TARGET, {})[TARGET];
var targetPrototype = target.prototype;
var FORCED, USE_NATIVE, VIRTUAL_PROTOTYPE;
var key, sourceProperty, targetProperty, nativeProperty, resultProperty, descriptor;
for (key in source) {
FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contains in native
USE_NATIVE = !FORCED && nativeSource && hasOwn(nativeSource, key);
targetProperty = target[key];
if (USE_NATIVE) if (options.dontCallGetSet) {
descriptor = getOwnPropertyDescriptor(nativeSource, key);
nativeProperty = descriptor && descriptor.value;
} else nativeProperty = nativeSource[key];
// export native or implementation
sourceProperty = (USE_NATIVE && nativeProperty) ? nativeProperty : source[key];
if (USE_NATIVE && typeof targetProperty == typeof sourceProperty) continue;
// bind methods to global for calling from export context
if (options.bind && USE_NATIVE) resultProperty = bind(sourceProperty, global);
// wrap global constructors for prevent changes in this version
else if (options.wrap && USE_NATIVE) resultProperty = wrapConstructor(sourceProperty);
// make static versions for prototype methods
else if (PROTO && isCallable(sourceProperty)) resultProperty = uncurryThis(sourceProperty);
// default case
else resultProperty = sourceProperty;
// add a flag to not completely full polyfills
if (options.sham || (sourceProperty && sourceProperty.sham) || (targetProperty && targetProperty.sham)) {
createNonEnumerableProperty(resultProperty, 'sham', true);
}
createNonEnumerableProperty(target, key, resultProperty);
if (PROTO) {
VIRTUAL_PROTOTYPE = TARGET + 'Prototype';
if (!hasOwn(path, VIRTUAL_PROTOTYPE)) {
createNonEnumerableProperty(path, VIRTUAL_PROTOTYPE, {});
}
// export virtual prototype methods
createNonEnumerableProperty(path[VIRTUAL_PROTOTYPE], key, sourceProperty);
// export real prototype methods
if (options.real && targetPrototype && (FORCED || !targetPrototype[key])) {
createNonEnumerableProperty(targetPrototype, key, sourceProperty);
}
}
}
};
},{"../internals/create-non-enumerable-property":204,"../internals/function-apply":237,"../internals/function-bind-context":238,"../internals/function-uncurry-this-clause":244,"../internals/global":251,"../internals/has-own-property":252,"../internals/is-callable":264,"../internals/is-forced":266,"../internals/object-get-own-property-descriptor":290,"../internals/path":305}],235:[function(_dereq_,module,exports){
module.exports = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
},{}],236:[function(_dereq_,module,exports){
var fails = _dereq_('../internals/fails');
module.exports = !fails(function () {
// eslint-disable-next-line es/no-object-isextensible, es/no-object-preventextensions -- required for testing
return Object.isExtensible(Object.preventExtensions({}));
});
},{"../internals/fails":235}],237:[function(_dereq_,module,exports){
var NATIVE_BIND = _dereq_('../internals/function-bind-native');
var FunctionPrototype = Function.prototype;
var apply = FunctionPrototype.apply;
var call = FunctionPrototype.call;
// eslint-disable-next-line es/no-reflect -- safe
module.exports = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () {
return call.apply(apply, arguments);
});
},{"../internals/function-bind-native":239}],238:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this-clause');
var aCallable = _dereq_('../internals/a-callable');
var NATIVE_BIND = _dereq_('../internals/function-bind-native');
var bind = uncurryThis(uncurryThis.bind);
// optional / simple context binding
module.exports = function (fn, that) {
aCallable(fn);
return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {
return fn.apply(that, arguments);
};
};
},{"../internals/a-callable":173,"../internals/function-bind-native":239,"../internals/function-uncurry-this-clause":244}],239:[function(_dereq_,module,exports){
var fails = _dereq_('../internals/fails');
module.exports = !fails(function () {
// eslint-disable-next-line es/no-function-prototype-bind -- safe
var test = (function () { /* empty */ }).bind();
// eslint-disable-next-line no-prototype-builtins -- safe
return typeof test != 'function' || test.hasOwnProperty('prototype');
});
},{"../internals/fails":235}],240:[function(_dereq_,module,exports){
'use strict';
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var aCallable = _dereq_('../internals/a-callable');
var isObject = _dereq_('../internals/is-object');
var hasOwn = _dereq_('../internals/has-own-property');
var arraySlice = _dereq_('../internals/array-slice');
var NATIVE_BIND = _dereq_('../internals/function-bind-native');
var $Function = Function;
var concat = uncurryThis([].concat);
var join = uncurryThis([].join);
var factories = {};
var construct = function (C, argsLength, args) {
if (!hasOwn(factories, argsLength)) {
for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']';
factories[argsLength] = $Function('C,a', 'return new C(' + join(list, ',') + ')');
} return factories[argsLength](C, args);
};
// `Function.prototype.bind` method implementation
// https://tc39.es/ecma262/#sec-function.prototype.bind
// eslint-disable-next-line es/no-function-prototype-bind -- detection
module.exports = NATIVE_BIND ? $Function.bind : function bind(that /* , ...args */) {
var F = aCallable(this);
var Prototype = F.prototype;
var partArgs = arraySlice(arguments, 1);
var boundFunction = function bound(/* args... */) {
var args = concat(partArgs, arraySlice(arguments));
return this instanceof boundFunction ? construct(F, args.length, args) : F.apply(that, args);
};
if (isObject(Prototype)) boundFunction.prototype = Prototype;
return boundFunction;
};
},{"../internals/a-callable":173,"../internals/array-slice":189,"../internals/function-bind-native":239,"../internals/function-uncurry-this":245,"../internals/has-own-property":252,"../internals/is-object":269}],241:[function(_dereq_,module,exports){
var NATIVE_BIND = _dereq_('../internals/function-bind-native');
var call = Function.prototype.call;
module.exports = NATIVE_BIND ? call.bind(call) : function () {
return call.apply(call, arguments);
};
},{"../internals/function-bind-native":239}],242:[function(_dereq_,module,exports){
var DESCRIPTORS = _dereq_('../internals/descriptors');
var hasOwn = _dereq_('../internals/has-own-property');
var FunctionPrototype = Function.prototype;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
var EXISTS = hasOwn(FunctionPrototype, 'name');
// additional protection from minified / mangled / dropped function names
var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
module.exports = {
EXISTS: EXISTS,
PROPER: PROPER,
CONFIGURABLE: CONFIGURABLE
};
},{"../internals/descriptors":212,"../internals/has-own-property":252}],243:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var aCallable = _dereq_('../internals/a-callable');
module.exports = function (object, key, method) {
try {
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));
} catch (error) { /* empty */ }
};
},{"../internals/a-callable":173,"../internals/function-uncurry-this":245}],244:[function(_dereq_,module,exports){
var classofRaw = _dereq_('../internals/classof-raw');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
module.exports = function (fn) {
// Nashorn bug:
// https://github.com/zloirock/core-js/issues/1128
// https://github.com/zloirock/core-js/issues/1130
if (classofRaw(fn) === 'Function') return uncurryThis(fn);
};
},{"../internals/classof-raw":195,"../internals/function-uncurry-this":245}],245:[function(_dereq_,module,exports){
var NATIVE_BIND = _dereq_('../internals/function-bind-native');
var FunctionPrototype = Function.prototype;
var call = FunctionPrototype.call;
var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);
module.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
return function () {
return call.apply(fn, arguments);
};
};
},{"../internals/function-bind-native":239}],246:[function(_dereq_,module,exports){
var path = _dereq_('../internals/path');
var global = _dereq_('../internals/global');
var isCallable = _dereq_('../internals/is-callable');
var aFunction = function (variable) {
return isCallable(variable) ? variable : undefined;
};
module.exports = function (namespace, method) {
return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])
: path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];
};
},{"../internals/global":251,"../internals/is-callable":264,"../internals/path":305}],247:[function(_dereq_,module,exports){
var classof = _dereq_('../internals/classof');
var getMethod = _dereq_('../internals/get-method');
var isNullOrUndefined = _dereq_('../internals/is-null-or-undefined');
var Iterators = _dereq_('../internals/iterators');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var ITERATOR = wellKnownSymbol('iterator');
module.exports = function (it) {
if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)
|| getMethod(it, '@@iterator')
|| Iterators[classof(it)];
};
},{"../internals/classof":196,"../internals/get-method":250,"../internals/is-null-or-undefined":268,"../internals/iterators":278,"../internals/well-known-symbol":343}],248:[function(_dereq_,module,exports){
var call = _dereq_('../internals/function-call');
var aCallable = _dereq_('../internals/a-callable');
var anObject = _dereq_('../internals/an-object');
var tryToString = _dereq_('../internals/try-to-string');
var getIteratorMethod = _dereq_('../internals/get-iterator-method');
var $TypeError = TypeError;
module.exports = function (argument, usingIterator) {
var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
throw $TypeError(tryToString(argument) + ' is not iterable');
};
},{"../internals/a-callable":173,"../internals/an-object":178,"../internals/function-call":241,"../internals/get-iterator-method":247,"../internals/try-to-string":335}],249:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var isArray = _dereq_('../internals/is-array');
var isCallable = _dereq_('../internals/is-callable');
var classof = _dereq_('../internals/classof-raw');
var toString = _dereq_('../internals/to-string');
var push = uncurryThis([].push);
module.exports = function (replacer) {
if (isCallable(replacer)) return replacer;
if (!isArray(replacer)) return;
var rawLength = replacer.length;
var keys = [];
for (var i = 0; i < rawLength; i++) {
var element = replacer[i];
if (typeof element == 'string') push(keys, element);
else if (typeof element == 'number' || classof(element) == 'Number' || classof(element) == 'String') push(keys, toString(element));
}
var keysLength = keys.length;
var root = true;
return function (key, value) {
if (root) {
root = false;
return value;
}
if (isArray(this)) return value;
for (var j = 0; j < keysLength; j++) if (keys[j] === key) return value;
};
};
},{"../internals/classof-raw":195,"../internals/function-uncurry-this":245,"../internals/is-array":263,"../internals/is-callable":264,"../internals/to-string":334}],250:[function(_dereq_,module,exports){
var aCallable = _dereq_('../internals/a-callable');
var isNullOrUndefined = _dereq_('../internals/is-null-or-undefined');
// `GetMethod` abstract operation
// https://tc39.es/ecma262/#sec-getmethod
module.exports = function (V, P) {
var func = V[P];
return isNullOrUndefined(func) ? undefined : aCallable(func);
};
},{"../internals/a-callable":173,"../internals/is-null-or-undefined":268}],251:[function(_dereq_,module,exports){
(function (global){(function (){
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
module.exports =
// eslint-disable-next-line es/no-global-this -- safe
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
// eslint-disable-next-line no-restricted-globals -- safe
check(typeof self == 'object' && self) ||
check(typeof global == 'object' && global) ||
// eslint-disable-next-line no-new-func -- fallback
(function () { return this; })() || this || Function('return this')();
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],252:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var toObject = _dereq_('../internals/to-object');
var hasOwnProperty = uncurryThis({}.hasOwnProperty);
// `HasOwnProperty` abstract operation
// https://tc39.es/ecma262/#sec-hasownproperty
// eslint-disable-next-line es/no-object-hasown -- safe
module.exports = Object.hasOwn || function hasOwn(it, key) {
return hasOwnProperty(toObject(it), key);
};
},{"../internals/function-uncurry-this":245,"../internals/to-object":330}],253:[function(_dereq_,module,exports){
module.exports = {};
},{}],254:[function(_dereq_,module,exports){
module.exports = function (a, b) {
try {
// eslint-disable-next-line no-console -- safe
arguments.length == 1 ? console.error(a) : console.error(a, b);
} catch (error) { /* empty */ }
};
},{}],255:[function(_dereq_,module,exports){
var getBuiltIn = _dereq_('../internals/get-built-in');
module.exports = getBuiltIn('document', 'documentElement');
},{"../internals/get-built-in":246}],256:[function(_dereq_,module,exports){
var DESCRIPTORS = _dereq_('../internals/descriptors');
var fails = _dereq_('../internals/fails');
var createElement = _dereq_('../internals/document-create-element');
// Thanks to IE8 for its funny defineProperty
module.exports = !DESCRIPTORS && !fails(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty(createElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
},{"../internals/descriptors":212,"../internals/document-create-element":214,"../internals/fails":235}],257:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var fails = _dereq_('../internals/fails');
var classof = _dereq_('../internals/classof-raw');
var $Object = Object;
var split = uncurryThis(''.split);
// fallback for non-array-like ES3 and non-enumerable old V8 strings
module.exports = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins -- safe
return !$Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classof(it) == 'String' ? split(it, '') : $Object(it);
} : $Object;
},{"../internals/classof-raw":195,"../internals/fails":235,"../internals/function-uncurry-this":245}],258:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var isCallable = _dereq_('../internals/is-callable');
var store = _dereq_('../internals/shared-store');
var functionToString = uncurryThis(Function.toString);
// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
if (!isCallable(store.inspectSource)) {
store.inspectSource = function (it) {
return functionToString(it);
};
}
module.exports = store.inspectSource;
},{"../internals/function-uncurry-this":245,"../internals/is-callable":264,"../internals/shared-store":317}],259:[function(_dereq_,module,exports){
var isObject = _dereq_('../internals/is-object');
var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property');
// `InstallErrorCause` abstract operation
// https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause
module.exports = function (O, options) {
if (isObject(options) && 'cause' in options) {
createNonEnumerableProperty(O, 'cause', options.cause);
}
};
},{"../internals/create-non-enumerable-property":204,"../internals/is-object":269}],260:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var hiddenKeys = _dereq_('../internals/hidden-keys');
var isObject = _dereq_('../internals/is-object');
var hasOwn = _dereq_('../internals/has-own-property');
var defineProperty = _dereq_('../internals/object-define-property').f;
var getOwnPropertyNamesModule = _dereq_('../internals/object-get-own-property-names');
var getOwnPropertyNamesExternalModule = _dereq_('../internals/object-get-own-property-names-external');
var isExtensible = _dereq_('../internals/object-is-extensible');
var uid = _dereq_('../internals/uid');
var FREEZING = _dereq_('../internals/freezing');
var REQUIRED = false;
var METADATA = uid('meta');
var id = 0;
var setMetadata = function (it) {
defineProperty(it, METADATA, { value: {
objectID: 'O' + id++, // object ID
weakData: {} // weak collections IDs
} });
};
var fastKey = function (it, create) {
// return a primitive with prefix
if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if (!hasOwn(it, METADATA)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMetadata(it);
// return object ID
} return it[METADATA].objectID;
};
var getWeakData = function (it, create) {
if (!hasOwn(it, METADATA)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMetadata(it);
// return the store of weak collections IDs
} return it[METADATA].weakData;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (FREEZING && REQUIRED && isExtensible(it) && !hasOwn(it, METADATA)) setMetadata(it);
return it;
};
var enable = function () {
meta.enable = function () { /* empty */ };
REQUIRED = true;
var getOwnPropertyNames = getOwnPropertyNamesModule.f;
var splice = uncurryThis([].splice);
var test = {};
test[METADATA] = 1;
// prevent exposing of metadata key
if (getOwnPropertyNames(test).length) {
getOwnPropertyNamesModule.f = function (it) {
var result = getOwnPropertyNames(it);
for (var i = 0, length = result.length; i < length; i++) {
if (result[i] === METADATA) {
splice(result, i, 1);
break;
}
} return result;
};
$({ target: 'Object', stat: true, forced: true }, {
getOwnPropertyNames: getOwnPropertyNamesExternalModule.f
});
}
};
var meta = module.exports = {
enable: enable,
fastKey: fastKey,
getWeakData: getWeakData,
onFreeze: onFreeze
};
hiddenKeys[METADATA] = true;
},{"../internals/export":234,"../internals/freezing":236,"../internals/function-uncurry-this":245,"../internals/has-own-property":252,"../internals/hidden-keys":253,"../internals/is-object":269,"../internals/object-define-property":289,"../internals/object-get-own-property-names":292,"../internals/object-get-own-property-names-external":291,"../internals/object-is-extensible":295,"../internals/uid":336}],261:[function(_dereq_,module,exports){
var NATIVE_WEAK_MAP = _dereq_('../internals/weak-map-basic-detection');
var global = _dereq_('../internals/global');
var isObject = _dereq_('../internals/is-object');
var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property');
var hasOwn = _dereq_('../internals/has-own-property');
var shared = _dereq_('../internals/shared-store');
var sharedKey = _dereq_('../internals/shared-key');
var hiddenKeys = _dereq_('../internals/hidden-keys');
var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
var TypeError = global.TypeError;
var WeakMap = global.WeakMap;
var set, get, has;
var enforce = function (it) {
return has(it) ? get(it) : set(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject(it) || (state = get(it)).type !== TYPE) {
throw TypeError('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (NATIVE_WEAK_MAP || shared.state) {
var store = shared.state || (shared.state = new WeakMap());
/* eslint-disable no-self-assign -- prototype methods protection */
store.get = store.get;
store.has = store.has;
store.set = store.set;
/* eslint-enable no-self-assign -- prototype methods protection */
set = function (it, metadata) {
if (store.has(it)) throw TypeError(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
store.set(it, metadata);
return metadata;
};
get = function (it) {
return store.get(it) || {};
};
has = function (it) {
return store.has(it);
};
} else {
var STATE = sharedKey('state');
hiddenKeys[STATE] = true;
set = function (it, metadata) {
if (hasOwn(it, STATE)) throw TypeError(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
createNonEnumerableProperty(it, STATE, metadata);
return metadata;
};
get = function (it) {
return hasOwn(it, STATE) ? it[STATE] : {};
};
has = function (it) {
return hasOwn(it, STATE);
};
}
module.exports = {
set: set,
get: get,
has: has,
enforce: enforce,
getterFor: getterFor
};
},{"../internals/create-non-enumerable-property":204,"../internals/global":251,"../internals/has-own-property":252,"../internals/hidden-keys":253,"../internals/is-object":269,"../internals/shared-key":316,"../internals/shared-store":317,"../internals/weak-map-basic-detection":340}],262:[function(_dereq_,module,exports){
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var Iterators = _dereq_('../internals/iterators');
var ITERATOR = wellKnownSymbol('iterator');
var ArrayPrototype = Array.prototype;
// check on default Array iterator
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
};
},{"../internals/iterators":278,"../internals/well-known-symbol":343}],263:[function(_dereq_,module,exports){
var classof = _dereq_('../internals/classof-raw');
// `IsArray` abstract operation
// https://tc39.es/ecma262/#sec-isarray
// eslint-disable-next-line es/no-array-isarray -- safe
module.exports = Array.isArray || function isArray(argument) {
return classof(argument) == 'Array';
};
},{"../internals/classof-raw":195}],264:[function(_dereq_,module,exports){
var $documentAll = _dereq_('../internals/document-all');
var documentAll = $documentAll.all;
// `IsCallable` abstract operation
// https://tc39.es/ecma262/#sec-iscallable
module.exports = $documentAll.IS_HTMLDDA ? function (argument) {
return typeof argument == 'function' || argument === documentAll;
} : function (argument) {
return typeof argument == 'function';
};
},{"../internals/document-all":213}],265:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var fails = _dereq_('../internals/fails');
var isCallable = _dereq_('../internals/is-callable');
var classof = _dereq_('../internals/classof');
var getBuiltIn = _dereq_('../internals/get-built-in');
var inspectSource = _dereq_('../internals/inspect-source');
var noop = function () { /* empty */ };
var empty = [];
var construct = getBuiltIn('Reflect', 'construct');
var constructorRegExp = /^\s*(?:class|function)\b/;
var exec = uncurryThis(constructorRegExp.exec);
var INCORRECT_TO_STRING = !constructorRegExp.exec(noop);
var isConstructorModern = function isConstructor(argument) {
if (!isCallable(argument)) return false;
try {
construct(noop, empty, argument);
return true;
} catch (error) {
return false;
}
};
var isConstructorLegacy = function isConstructor(argument) {
if (!isCallable(argument)) return false;
switch (classof(argument)) {
case 'AsyncFunction':
case 'GeneratorFunction':
case 'AsyncGeneratorFunction': return false;
}
try {
// we can't check .prototype since constructors produced by .bind haven't it
// `Function#toString` throws on some built-it function in some legacy engines
// (for example, `DOMQuad` and similar in FF41-)
return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument));
} catch (error) {
return true;
}
};
isConstructorLegacy.sham = true;
// `IsConstructor` abstract operation
// https://tc39.es/ecma262/#sec-isconstructor
module.exports = !construct || fails(function () {
var called;
return isConstructorModern(isConstructorModern.call)
|| !isConstructorModern(Object)
|| !isConstructorModern(function () { called = true; })
|| called;
}) ? isConstructorLegacy : isConstructorModern;
},{"../internals/classof":196,"../internals/fails":235,"../internals/function-uncurry-this":245,"../internals/get-built-in":246,"../internals/inspect-source":258,"../internals/is-callable":264}],266:[function(_dereq_,module,exports){
var fails = _dereq_('../internals/fails');
var isCallable = _dereq_('../internals/is-callable');
var replacement = /#|\.prototype\./;
var isForced = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: isCallable(detection) ? fails(detection)
: !!detection;
};
var normalize = isForced.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';
module.exports = isForced;
},{"../internals/fails":235,"../internals/is-callable":264}],267:[function(_dereq_,module,exports){
var isObject = _dereq_('../internals/is-object');
var floor = Math.floor;
// `IsIntegralNumber` abstract operation
// https://tc39.es/ecma262/#sec-isintegralnumber
// eslint-disable-next-line es/no-number-isinteger -- safe
module.exports = Number.isInteger || function isInteger(it) {
return !isObject(it) && isFinite(it) && floor(it) === it;
};
},{"../internals/is-object":269}],268:[function(_dereq_,module,exports){
// we can't use just `it == null` since of `document.all` special case
// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
module.exports = function (it) {
return it === null || it === undefined;
};
},{}],269:[function(_dereq_,module,exports){
var isCallable = _dereq_('../internals/is-callable');
var $documentAll = _dereq_('../internals/document-all');
var documentAll = $documentAll.all;
module.exports = $documentAll.IS_HTMLDDA ? function (it) {
return typeof it == 'object' ? it !== null : isCallable(it) || it === documentAll;
} : function (it) {
return typeof it == 'object' ? it !== null : isCallable(it);
};
},{"../internals/document-all":213,"../internals/is-callable":264}],270:[function(_dereq_,module,exports){
module.exports = true;
},{}],271:[function(_dereq_,module,exports){
var isObject = _dereq_('../internals/is-object');
var classof = _dereq_('../internals/classof-raw');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var MATCH = wellKnownSymbol('match');
// `IsRegExp` abstract operation
// https://tc39.es/ecma262/#sec-isregexp
module.exports = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) == 'RegExp');
};
},{"../internals/classof-raw":195,"../internals/is-object":269,"../internals/well-known-symbol":343}],272:[function(_dereq_,module,exports){
var getBuiltIn = _dereq_('../internals/get-built-in');
var isCallable = _dereq_('../internals/is-callable');
var isPrototypeOf = _dereq_('../internals/object-is-prototype-of');
var USE_SYMBOL_AS_UID = _dereq_('../internals/use-symbol-as-uid');
var $Object = Object;
module.exports = USE_SYMBOL_AS_UID ? function (it) {
return typeof it == 'symbol';
} : function (it) {
var $Symbol = getBuiltIn('Symbol');
return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
};
},{"../internals/get-built-in":246,"../internals/is-callable":264,"../internals/object-is-prototype-of":296,"../internals/use-symbol-as-uid":337}],273:[function(_dereq_,module,exports){
var bind = _dereq_('../internals/function-bind-context');
var call = _dereq_('../internals/function-call');
var anObject = _dereq_('../internals/an-object');
var tryToString = _dereq_('../internals/try-to-string');
var isArrayIteratorMethod = _dereq_('../internals/is-array-iterator-method');
var lengthOfArrayLike = _dereq_('../internals/length-of-array-like');
var isPrototypeOf = _dereq_('../internals/object-is-prototype-of');
var getIterator = _dereq_('../internals/get-iterator');
var getIteratorMethod = _dereq_('../internals/get-iterator-method');
var iteratorClose = _dereq_('../internals/iterator-close');
var $TypeError = TypeError;
var Result = function (stopped, result) {
this.stopped = stopped;
this.result = result;
};
var ResultPrototype = Result.prototype;
module.exports = function (iterable, unboundFunction, options) {
var that = options && options.that;
var AS_ENTRIES = !!(options && options.AS_ENTRIES);
var IS_RECORD = !!(options && options.IS_RECORD);
var IS_ITERATOR = !!(options && options.IS_ITERATOR);
var INTERRUPTED = !!(options && options.INTERRUPTED);
var fn = bind(unboundFunction, that);
var iterator, iterFn, index, length, result, next, step;
var stop = function (condition) {
if (iterator) iteratorClose(iterator, 'normal', condition);
return new Result(true, condition);
};
var callFn = function (value) {
if (AS_ENTRIES) {
anObject(value);
return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
} return INTERRUPTED ? fn(value, stop) : fn(value);
};
if (IS_RECORD) {
iterator = iterable.iterator;
} else if (IS_ITERATOR) {
iterator = iterable;
} else {
iterFn = getIteratorMethod(iterable);
if (!iterFn) throw $TypeError(tryToString(iterable) + ' is not iterable');
// optimisation for array iterators
if (isArrayIteratorMethod(iterFn)) {
for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
result = callFn(iterable[index]);
if (result && isPrototypeOf(ResultPrototype, result)) return result;
} return new Result(false);
}
iterator = getIterator(iterable, iterFn);
}
next = IS_RECORD ? iterable.next : iterator.next;
while (!(step = call(next, iterator)).done) {
try {
result = callFn(step.value);
} catch (error) {
iteratorClose(iterator, 'throw', error);
}
if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
} return new Result(false);
};
},{"../internals/an-object":178,"../internals/function-bind-context":238,"../internals/function-call":241,"../internals/get-iterator":248,"../internals/get-iterator-method":247,"../internals/is-array-iterator-method":262,"../internals/iterator-close":274,"../internals/length-of-array-like":279,"../internals/object-is-prototype-of":296,"../internals/try-to-string":335}],274:[function(_dereq_,module,exports){
var call = _dereq_('../internals/function-call');
var anObject = _dereq_('../internals/an-object');
var getMethod = _dereq_('../internals/get-method');
module.exports = function (iterator, kind, value) {
var innerResult, innerError;
anObject(iterator);
try {
innerResult = getMethod(iterator, 'return');
if (!innerResult) {
if (kind === 'throw') throw value;
return value;
}
innerResult = call(innerResult, iterator);
} catch (error) {
innerError = true;
innerResult = error;
}
if (kind === 'throw') throw value;
if (innerError) throw innerResult;
anObject(innerResult);
return value;
};
},{"../internals/an-object":178,"../internals/function-call":241,"../internals/get-method":250}],275:[function(_dereq_,module,exports){
'use strict';
var IteratorPrototype = _dereq_('../internals/iterators-core').IteratorPrototype;
var create = _dereq_('../internals/object-create');
var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor');
var setToStringTag = _dereq_('../internals/set-to-string-tag');
var Iterators = _dereq_('../internals/iterators');
var returnThis = function () { return this; };
module.exports = function (IteratorConstructor, NAME, next, ENUMERABLE_NEXT) {
var TO_STRING_TAG = NAME + ' Iterator';
IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(+!ENUMERABLE_NEXT, next) });
setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);
Iterators[TO_STRING_TAG] = returnThis;
return IteratorConstructor;
};
},{"../internals/create-property-descriptor":205,"../internals/iterators":278,"../internals/iterators-core":277,"../internals/object-create":287,"../internals/set-to-string-tag":315}],276:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var call = _dereq_('../internals/function-call');
var IS_PURE = _dereq_('../internals/is-pure');
var FunctionName = _dereq_('../internals/function-name');
var isCallable = _dereq_('../internals/is-callable');
var createIteratorConstructor = _dereq_('../internals/iterator-create-constructor');
var getPrototypeOf = _dereq_('../internals/object-get-prototype-of');
var setPrototypeOf = _dereq_('../internals/object-set-prototype-of');
var setToStringTag = _dereq_('../internals/set-to-string-tag');
var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property');
var defineBuiltIn = _dereq_('../internals/define-built-in');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var Iterators = _dereq_('../internals/iterators');
var IteratorsCore = _dereq_('../internals/iterators-core');
var PROPER_FUNCTION_NAME = FunctionName.PROPER;
var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE;
var IteratorPrototype = IteratorsCore.IteratorPrototype;
var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
var ITERATOR = wellKnownSymbol('iterator');
var KEYS = 'keys';
var VALUES = 'values';
var ENTRIES = 'entries';
var returnThis = function () { return this; };
module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
createIteratorConstructor(IteratorConstructor, NAME, next);
var getIterationMethod = function (KIND) {
if (KIND === DEFAULT && defaultIterator) return defaultIterator;
if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
switch (KIND) {
case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
} return function () { return new IteratorConstructor(this); };
};
var TO_STRING_TAG = NAME + ' Iterator';
var INCORRECT_VALUES_NAME = false;
var IterablePrototype = Iterable.prototype;
var nativeIterator = IterablePrototype[ITERATOR]
|| IterablePrototype['@@iterator']
|| DEFAULT && IterablePrototype[DEFAULT];
var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
var CurrentIteratorPrototype, methods, KEY;
// fix native
if (anyNativeIterator) {
CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));
if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {
if (setPrototypeOf) {
setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);
} else if (!isCallable(CurrentIteratorPrototype[ITERATOR])) {
defineBuiltIn(CurrentIteratorPrototype, ITERATOR, returnThis);
}
}
// Set @@toStringTag to native iterators
setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);
if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis;
}
}
// fix Array.prototype.{ values, @@iterator }.name in V8 / FF
if (PROPER_FUNCTION_NAME && DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
if (!IS_PURE && CONFIGURABLE_FUNCTION_NAME) {
createNonEnumerableProperty(IterablePrototype, 'name', VALUES);
} else {
INCORRECT_VALUES_NAME = true;
defaultIterator = function values() { return call(nativeIterator, this); };
}
}
// export additional methods
if (DEFAULT) {
methods = {
values: getIterationMethod(VALUES),
keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
entries: getIterationMethod(ENTRIES)
};
if (FORCED) for (KEY in methods) {
if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
defineBuiltIn(IterablePrototype, KEY, methods[KEY]);
}
} else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
}
// define iterator
if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) {
defineBuiltIn(IterablePrototype, ITERATOR, defaultIterator, { name: DEFAULT });
}
Iterators[NAME] = defaultIterator;
return methods;
};
},{"../internals/create-non-enumerable-property":204,"../internals/define-built-in":208,"../internals/export":234,"../internals/function-call":241,"../internals/function-name":242,"../internals/is-callable":264,"../internals/is-pure":270,"../internals/iterator-create-constructor":275,"../internals/iterators":278,"../internals/iterators-core":277,"../internals/object-get-prototype-of":294,"../internals/object-set-prototype-of":300,"../internals/set-to-string-tag":315,"../internals/well-known-symbol":343}],277:[function(_dereq_,module,exports){
'use strict';
var fails = _dereq_('../internals/fails');
var isCallable = _dereq_('../internals/is-callable');
var isObject = _dereq_('../internals/is-object');
var create = _dereq_('../internals/object-create');
var getPrototypeOf = _dereq_('../internals/object-get-prototype-of');
var defineBuiltIn = _dereq_('../internals/define-built-in');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var IS_PURE = _dereq_('../internals/is-pure');
var ITERATOR = wellKnownSymbol('iterator');
var BUGGY_SAFARI_ITERATORS = false;
// `%IteratorPrototype%` object
// https://tc39.es/ecma262/#sec-%iteratorprototype%-object
var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
/* eslint-disable es/no-array-prototype-keys -- safe */
if ([].keys) {
arrayIterator = [].keys();
// Safari 8 has buggy iterators w/o `next`
if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
else {
PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
}
}
var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {
var test = {};
// FF44- legacy iterators case
return IteratorPrototype[ITERATOR].call(test) !== test;
});
if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
// `%IteratorPrototype%[@@iterator]()` method
// https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
if (!isCallable(IteratorPrototype[ITERATOR])) {
defineBuiltIn(IteratorPrototype, ITERATOR, function () {
return this;
});
}
module.exports = {
IteratorPrototype: IteratorPrototype,
BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
};
},{"../internals/define-built-in":208,"../internals/fails":235,"../internals/is-callable":264,"../internals/is-object":269,"../internals/is-pure":270,"../internals/object-create":287,"../internals/object-get-prototype-of":294,"../internals/well-known-symbol":343}],278:[function(_dereq_,module,exports){
arguments[4][253][0].apply(exports,arguments)
},{"dup":253}],279:[function(_dereq_,module,exports){
var toLength = _dereq_('../internals/to-length');
// `LengthOfArrayLike` abstract operation
// https://tc39.es/ecma262/#sec-lengthofarraylike
module.exports = function (obj) {
return toLength(obj.length);
};
},{"../internals/to-length":329}],280:[function(_dereq_,module,exports){
var ceil = Math.ceil;
var floor = Math.floor;
// `Math.trunc` method
// https://tc39.es/ecma262/#sec-math.trunc
// eslint-disable-next-line es/no-math-trunc -- safe
module.exports = Math.trunc || function trunc(x) {
var n = +x;
return (n > 0 ? floor : ceil)(n);
};
},{}],281:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
var bind = _dereq_('../internals/function-bind-context');
var getOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f;
var macrotask = _dereq_('../internals/task').set;
var Queue = _dereq_('../internals/queue');
var IS_IOS = _dereq_('../internals/engine-is-ios');
var IS_IOS_PEBBLE = _dereq_('../internals/engine-is-ios-pebble');
var IS_WEBOS_WEBKIT = _dereq_('../internals/engine-is-webos-webkit');
var IS_NODE = _dereq_('../internals/engine-is-node');
var MutationObserver = global.MutationObserver || global.WebKitMutationObserver;
var document = global.document;
var process = global.process;
var Promise = global.Promise;
// Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
var queueMicrotaskDescriptor = getOwnPropertyDescriptor(global, 'queueMicrotask');
var microtask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;
var notify, toggle, node, promise, then;
// modern engines have queueMicrotask method
if (!microtask) {
var queue = new Queue();
var flush = function () {
var parent, fn;
if (IS_NODE && (parent = process.domain)) parent.exit();
while (fn = queue.get()) try {
fn();
} catch (error) {
if (queue.head) notify();
throw error;
}
if (parent) parent.enter();
};
// browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
// also except WebOS Webkit https://github.com/zloirock/core-js/issues/898
if (!IS_IOS && !IS_NODE && !IS_WEBOS_WEBKIT && MutationObserver && document) {
toggle = true;
node = document.createTextNode('');
new MutationObserver(flush).observe(node, { characterData: true });
notify = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (!IS_IOS_PEBBLE && Promise && Promise.resolve) {
// Promise.resolve without an argument throws an error in LG WebOS 2
promise = Promise.resolve(undefined);
// workaround of WebKit ~ iOS Safari 10.1 bug
promise.constructor = Promise;
then = bind(promise.then, promise);
notify = function () {
then(flush);
};
// Node.js without promises
} else if (IS_NODE) {
notify = function () {
process.nextTick(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessage
// - onreadystatechange
// - setTimeout
} else {
// `webpack` dev server bug on IE global methods - use bind(fn, global)
macrotask = bind(macrotask, global);
notify = function () {
macrotask(flush);
};
}
microtask = function (fn) {
if (!queue.head) notify();
queue.add(fn);
};
}
module.exports = microtask;
},{"../internals/engine-is-ios":223,"../internals/engine-is-ios-pebble":222,"../internals/engine-is-node":224,"../internals/engine-is-webos-webkit":225,"../internals/function-bind-context":238,"../internals/global":251,"../internals/object-get-own-property-descriptor":290,"../internals/queue":311,"../internals/task":325}],282:[function(_dereq_,module,exports){
'use strict';
var aCallable = _dereq_('../internals/a-callable');
var $TypeError = TypeError;
var PromiseCapability = function (C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw $TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aCallable(resolve);
this.reject = aCallable(reject);
};
// `NewPromiseCapability` abstract operation
// https://tc39.es/ecma262/#sec-newpromisecapability
module.exports.f = function (C) {
return new PromiseCapability(C);
};
},{"../internals/a-callable":173}],283:[function(_dereq_,module,exports){
var toString = _dereq_('../internals/to-string');
module.exports = function (argument, $default) {
return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument);
};
},{"../internals/to-string":334}],284:[function(_dereq_,module,exports){
var isRegExp = _dereq_('../internals/is-regexp');
var $TypeError = TypeError;
module.exports = function (it) {
if (isRegExp(it)) {
throw $TypeError("The method doesn't accept regular expressions");
} return it;
};
},{"../internals/is-regexp":271}],285:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
var fails = _dereq_('../internals/fails');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var toString = _dereq_('../internals/to-string');
var trim = _dereq_('../internals/string-trim').trim;
var whitespaces = _dereq_('../internals/whitespaces');
var $parseInt = global.parseInt;
var Symbol = global.Symbol;
var ITERATOR = Symbol && Symbol.iterator;
var hex = /^[+-]?0x/i;
var exec = uncurryThis(hex.exec);
var FORCED = $parseInt(whitespaces + '08') !== 8 || $parseInt(whitespaces + '0x16') !== 22
// MS Edge 18- broken with boxed symbols
|| (ITERATOR && !fails(function () { $parseInt(Object(ITERATOR)); }));
// `parseInt` method
// https://tc39.es/ecma262/#sec-parseint-string-radix
module.exports = FORCED ? function parseInt(string, radix) {
var S = trim(toString(string));
return $parseInt(S, (radix >>> 0) || (exec(hex, S) ? 16 : 10));
} : $parseInt;
},{"../internals/fails":235,"../internals/function-uncurry-this":245,"../internals/global":251,"../internals/string-trim":321,"../internals/to-string":334,"../internals/whitespaces":344}],286:[function(_dereq_,module,exports){
'use strict';
var DESCRIPTORS = _dereq_('../internals/descriptors');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var call = _dereq_('../internals/function-call');
var fails = _dereq_('../internals/fails');
var objectKeys = _dereq_('../internals/object-keys');
var getOwnPropertySymbolsModule = _dereq_('../internals/object-get-own-property-symbols');
var propertyIsEnumerableModule = _dereq_('../internals/object-property-is-enumerable');
var toObject = _dereq_('../internals/to-object');
var IndexedObject = _dereq_('../internals/indexed-object');
// eslint-disable-next-line es/no-object-assign -- safe
var $assign = Object.assign;
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
var defineProperty = Object.defineProperty;
var concat = uncurryThis([].concat);
// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
module.exports = !$assign || fails(function () {
// should have correct order of operations (Edge bug)
if (DESCRIPTORS && $assign({ b: 1 }, $assign(defineProperty({}, 'a', {
enumerable: true,
get: function () {
defineProperty(this, 'b', {
value: 3,
enumerable: false
});
}
}), { b: 2 })).b !== 1) return true;
// should work with symbols and should have deterministic property order (V8 bug)
var A = {};
var B = {};
// eslint-disable-next-line es/no-symbol -- safe
var symbol = Symbol();
var alphabet = 'abcdefghijklmnopqrst';
A[symbol] = 7;
alphabet.split('').forEach(function (chr) { B[chr] = chr; });
return $assign({}, A)[symbol] != 7 || objectKeys($assign({}, B)).join('') != alphabet;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars -- required for `.length`
var T = toObject(target);
var argumentsLength = arguments.length;
var index = 1;
var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
var propertyIsEnumerable = propertyIsEnumerableModule.f;
while (argumentsLength > index) {
var S = IndexedObject(arguments[index++]);
var keys = getOwnPropertySymbols ? concat(objectKeys(S), getOwnPropertySymbols(S)) : objectKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!DESCRIPTORS || call(propertyIsEnumerable, S, key)) T[key] = S[key];
}
} return T;
} : $assign;
},{"../internals/descriptors":212,"../internals/fails":235,"../internals/function-call":241,"../internals/function-uncurry-this":245,"../internals/indexed-object":257,"../internals/object-get-own-property-symbols":293,"../internals/object-keys":298,"../internals/object-property-is-enumerable":299,"../internals/to-object":330}],287:[function(_dereq_,module,exports){
/* global ActiveXObject -- old IE, WSH */
var anObject = _dereq_('../internals/an-object');
var definePropertiesModule = _dereq_('../internals/object-define-properties');
var enumBugKeys = _dereq_('../internals/enum-bug-keys');
var hiddenKeys = _dereq_('../internals/hidden-keys');
var html = _dereq_('../internals/html');
var documentCreateElement = _dereq_('../internals/document-create-element');
var sharedKey = _dereq_('../internals/shared-key');
var GT = '>';
var LT = '<';
var PROTOTYPE = 'prototype';
var SCRIPT = 'script';
var IE_PROTO = sharedKey('IE_PROTO');
var EmptyConstructor = function () { /* empty */ };
var scriptTag = function (content) {
return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
};
// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX = function (activeXDocument) {
activeXDocument.write(scriptTag(''));
activeXDocument.close();
var temp = activeXDocument.parentWindow.Object;
activeXDocument = null; // avoid memory leak
return temp;
};
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = documentCreateElement('iframe');
var JS = 'java' + SCRIPT + ':';
var iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
// https://github.com/zloirock/core-js/issues/475
iframe.src = String(JS);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(scriptTag('document.F=Object'));
iframeDocument.close();
return iframeDocument.F;
};
// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;
var NullProtoObject = function () {
try {
activeXDocument = new ActiveXObject('htmlfile');
} catch (error) { /* ignore */ }
NullProtoObject = typeof document != 'undefined'
? document.domain && activeXDocument
? NullProtoObjectViaActiveX(activeXDocument) // old IE
: NullProtoObjectViaIFrame()
: NullProtoObjectViaActiveX(activeXDocument); // WSH
var length = enumBugKeys.length;
while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
return NullProtoObject();
};
hiddenKeys[IE_PROTO] = true;
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
// eslint-disable-next-line es/no-object-create -- safe
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
EmptyConstructor[PROTOTYPE] = anObject(O);
result = new EmptyConstructor();
EmptyConstructor[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = NullProtoObject();
return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
};
},{"../internals/an-object":178,"../internals/document-create-element":214,"../internals/enum-bug-keys":230,"../internals/hidden-keys":253,"../internals/html":255,"../internals/object-define-properties":288,"../internals/shared-key":316}],288:[function(_dereq_,module,exports){
var DESCRIPTORS = _dereq_('../internals/descriptors');
var V8_PROTOTYPE_DEFINE_BUG = _dereq_('../internals/v8-prototype-define-bug');
var definePropertyModule = _dereq_('../internals/object-define-property');
var anObject = _dereq_('../internals/an-object');
var toIndexedObject = _dereq_('../internals/to-indexed-object');
var objectKeys = _dereq_('../internals/object-keys');
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es/no-object-defineproperties -- safe
exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var props = toIndexedObject(Properties);
var keys = objectKeys(Properties);
var length = keys.length;
var index = 0;
var key;
while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
return O;
};
},{"../internals/an-object":178,"../internals/descriptors":212,"../internals/object-define-property":289,"../internals/object-keys":298,"../internals/to-indexed-object":327,"../internals/v8-prototype-define-bug":338}],289:[function(_dereq_,module,exports){
var DESCRIPTORS = _dereq_('../internals/descriptors');
var IE8_DOM_DEFINE = _dereq_('../internals/ie8-dom-define');
var V8_PROTOTYPE_DEFINE_BUG = _dereq_('../internals/v8-prototype-define-bug');
var anObject = _dereq_('../internals/an-object');
var toPropertyKey = _dereq_('../internals/to-property-key');
var $TypeError = TypeError;
// eslint-disable-next-line es/no-object-defineproperty -- safe
var $defineProperty = Object.defineProperty;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var ENUMERABLE = 'enumerable';
var CONFIGURABLE = 'configurable';
var WRITABLE = 'writable';
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
anObject(O);
P = toPropertyKey(P);
anObject(Attributes);
if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
var current = $getOwnPropertyDescriptor(O, P);
if (current && current[WRITABLE]) {
O[P] = Attributes.value;
Attributes = {
configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
writable: false
};
}
} return $defineProperty(O, P, Attributes);
} : $defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPropertyKey(P);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return $defineProperty(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw $TypeError('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
},{"../internals/an-object":178,"../internals/descriptors":212,"../internals/ie8-dom-define":256,"../internals/to-property-key":332,"../internals/v8-prototype-define-bug":338}],290:[function(_dereq_,module,exports){
var DESCRIPTORS = _dereq_('../internals/descriptors');
var call = _dereq_('../internals/function-call');
var propertyIsEnumerableModule = _dereq_('../internals/object-property-is-enumerable');
var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor');
var toIndexedObject = _dereq_('../internals/to-indexed-object');
var toPropertyKey = _dereq_('../internals/to-property-key');
var hasOwn = _dereq_('../internals/has-own-property');
var IE8_DOM_DEFINE = _dereq_('../internals/ie8-dom-define');
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject(O);
P = toPropertyKey(P);
if (IE8_DOM_DEFINE) try {
return $getOwnPropertyDescriptor(O, P);
} catch (error) { /* empty */ }
if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
};
},{"../internals/create-property-descriptor":205,"../internals/descriptors":212,"../internals/function-call":241,"../internals/has-own-property":252,"../internals/ie8-dom-define":256,"../internals/object-property-is-enumerable":299,"../internals/to-indexed-object":327,"../internals/to-property-key":332}],291:[function(_dereq_,module,exports){
/* eslint-disable es/no-object-getownpropertynames -- safe */
var classof = _dereq_('../internals/classof-raw');
var toIndexedObject = _dereq_('../internals/to-indexed-object');
var $getOwnPropertyNames = _dereq_('../internals/object-get-own-property-names').f;
var arraySlice = _dereq_('../internals/array-slice-simple');
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return $getOwnPropertyNames(it);
} catch (error) {
return arraySlice(windowNames);
}
};
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
module.exports.f = function getOwnPropertyNames(it) {
return windowNames && classof(it) == 'Window'
? getWindowNames(it)
: $getOwnPropertyNames(toIndexedObject(it));
};
},{"../internals/array-slice-simple":188,"../internals/classof-raw":195,"../internals/object-get-own-property-names":292,"../internals/to-indexed-object":327}],292:[function(_dereq_,module,exports){
var internalObjectKeys = _dereq_('../internals/object-keys-internal');
var enumBugKeys = _dereq_('../internals/enum-bug-keys');
var hiddenKeys = enumBugKeys.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
// eslint-disable-next-line es/no-object-getownpropertynames -- safe
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return internalObjectKeys(O, hiddenKeys);
};
},{"../internals/enum-bug-keys":230,"../internals/object-keys-internal":297}],293:[function(_dereq_,module,exports){
// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
exports.f = Object.getOwnPropertySymbols;
},{}],294:[function(_dereq_,module,exports){
var hasOwn = _dereq_('../internals/has-own-property');
var isCallable = _dereq_('../internals/is-callable');
var toObject = _dereq_('../internals/to-object');
var sharedKey = _dereq_('../internals/shared-key');
var CORRECT_PROTOTYPE_GETTER = _dereq_('../internals/correct-prototype-getter');
var IE_PROTO = sharedKey('IE_PROTO');
var $Object = Object;
var ObjectPrototype = $Object.prototype;
// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
// eslint-disable-next-line es/no-object-getprototypeof -- safe
module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
var object = toObject(O);
if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
var constructor = object.constructor;
if (isCallable(constructor) && object instanceof constructor) {
return constructor.prototype;
} return object instanceof $Object ? ObjectPrototype : null;
};
},{"../internals/correct-prototype-getter":202,"../internals/has-own-property":252,"../internals/is-callable":264,"../internals/shared-key":316,"../internals/to-object":330}],295:[function(_dereq_,module,exports){
var fails = _dereq_('../internals/fails');
var isObject = _dereq_('../internals/is-object');
var classof = _dereq_('../internals/classof-raw');
var ARRAY_BUFFER_NON_EXTENSIBLE = _dereq_('../internals/array-buffer-non-extensible');
// eslint-disable-next-line es/no-object-isextensible -- safe
var $isExtensible = Object.isExtensible;
var FAILS_ON_PRIMITIVES = fails(function () { $isExtensible(1); });
// `Object.isExtensible` method
// https://tc39.es/ecma262/#sec-object.isextensible
module.exports = (FAILS_ON_PRIMITIVES || ARRAY_BUFFER_NON_EXTENSIBLE) ? function isExtensible(it) {
if (!isObject(it)) return false;
if (ARRAY_BUFFER_NON_EXTENSIBLE && classof(it) == 'ArrayBuffer') return false;
return $isExtensible ? $isExtensible(it) : true;
} : $isExtensible;
},{"../internals/array-buffer-non-extensible":179,"../internals/classof-raw":195,"../internals/fails":235,"../internals/is-object":269}],296:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
module.exports = uncurryThis({}.isPrototypeOf);
},{"../internals/function-uncurry-this":245}],297:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var hasOwn = _dereq_('../internals/has-own-property');
var toIndexedObject = _dereq_('../internals/to-indexed-object');
var indexOf = _dereq_('../internals/array-includes').indexOf;
var hiddenKeys = _dereq_('../internals/hidden-keys');
var push = uncurryThis([].push);
module.exports = function (object, names) {
var O = toIndexedObject(object);
var i = 0;
var result = [];
var key;
for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
// Don't enum bug & hidden keys
while (names.length > i) if (hasOwn(O, key = names[i++])) {
~indexOf(result, key) || push(result, key);
}
return result;
};
},{"../internals/array-includes":182,"../internals/function-uncurry-this":245,"../internals/has-own-property":252,"../internals/hidden-keys":253,"../internals/to-indexed-object":327}],298:[function(_dereq_,module,exports){
var internalObjectKeys = _dereq_('../internals/object-keys-internal');
var enumBugKeys = _dereq_('../internals/enum-bug-keys');
// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
// eslint-disable-next-line es/no-object-keys -- safe
module.exports = Object.keys || function keys(O) {
return internalObjectKeys(O, enumBugKeys);
};
},{"../internals/enum-bug-keys":230,"../internals/object-keys-internal":297}],299:[function(_dereq_,module,exports){
'use strict';
var $propertyIsEnumerable = {}.propertyIsEnumerable;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : $propertyIsEnumerable;
},{}],300:[function(_dereq_,module,exports){
/* eslint-disable no-proto -- safe */
var uncurryThisAccessor = _dereq_('../internals/function-uncurry-this-accessor');
var anObject = _dereq_('../internals/an-object');
var aPossiblePrototype = _dereq_('../internals/a-possible-prototype');
// `Object.setPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
// eslint-disable-next-line es/no-object-setprototypeof -- safe
module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
var CORRECT_SETTER = false;
var test = {};
var setter;
try {
setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
setter(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) { /* empty */ }
return function setPrototypeOf(O, proto) {
anObject(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
},{"../internals/a-possible-prototype":175,"../internals/an-object":178,"../internals/function-uncurry-this-accessor":243}],301:[function(_dereq_,module,exports){
var DESCRIPTORS = _dereq_('../internals/descriptors');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var objectKeys = _dereq_('../internals/object-keys');
var toIndexedObject = _dereq_('../internals/to-indexed-object');
var $propertyIsEnumerable = _dereq_('../internals/object-property-is-enumerable').f;
var propertyIsEnumerable = uncurryThis($propertyIsEnumerable);
var push = uncurryThis([].push);
// `Object.{ entries, values }` methods implementation
var createMethod = function (TO_ENTRIES) {
return function (it) {
var O = toIndexedObject(it);
var keys = objectKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) {
key = keys[i++];
if (!DESCRIPTORS || propertyIsEnumerable(O, key)) {
push(result, TO_ENTRIES ? [key, O[key]] : O[key]);
}
}
return result;
};
};
module.exports = {
// `Object.entries` method
// https://tc39.es/ecma262/#sec-object.entries
entries: createMethod(true),
// `Object.values` method
// https://tc39.es/ecma262/#sec-object.values
values: createMethod(false)
};
},{"../internals/descriptors":212,"../internals/function-uncurry-this":245,"../internals/object-keys":298,"../internals/object-property-is-enumerable":299,"../internals/to-indexed-object":327}],302:[function(_dereq_,module,exports){
'use strict';
var TO_STRING_TAG_SUPPORT = _dereq_('../internals/to-string-tag-support');
var classof = _dereq_('../internals/classof');
// `Object.prototype.toString` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.tostring
module.exports = TO_STRING_TAG_SUPPORT ? {}.toString : function toString() {
return '[object ' + classof(this) + ']';
};
},{"../internals/classof":196,"../internals/to-string-tag-support":333}],303:[function(_dereq_,module,exports){
var call = _dereq_('../internals/function-call');
var isCallable = _dereq_('../internals/is-callable');
var isObject = _dereq_('../internals/is-object');
var $TypeError = TypeError;
// `OrdinaryToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-ordinarytoprimitive
module.exports = function (input, pref) {
var fn, val;
if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
throw $TypeError("Can't convert object to primitive value");
};
},{"../internals/function-call":241,"../internals/is-callable":264,"../internals/is-object":269}],304:[function(_dereq_,module,exports){
var getBuiltIn = _dereq_('../internals/get-built-in');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var getOwnPropertyNamesModule = _dereq_('../internals/object-get-own-property-names');
var getOwnPropertySymbolsModule = _dereq_('../internals/object-get-own-property-symbols');
var anObject = _dereq_('../internals/an-object');
var concat = uncurryThis([].concat);
// all object keys, includes non-enumerable and symbols
module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = getOwnPropertyNamesModule.f(anObject(it));
var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
};
},{"../internals/an-object":178,"../internals/function-uncurry-this":245,"../internals/get-built-in":246,"../internals/object-get-own-property-names":292,"../internals/object-get-own-property-symbols":293}],305:[function(_dereq_,module,exports){
arguments[4][253][0].apply(exports,arguments)
},{"dup":253}],306:[function(_dereq_,module,exports){
module.exports = function (exec) {
try {
return { error: false, value: exec() };
} catch (error) {
return { error: true, value: error };
}
};
},{}],307:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
var NativePromiseConstructor = _dereq_('../internals/promise-native-constructor');
var isCallable = _dereq_('../internals/is-callable');
var isForced = _dereq_('../internals/is-forced');
var inspectSource = _dereq_('../internals/inspect-source');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var IS_BROWSER = _dereq_('../internals/engine-is-browser');
var IS_DENO = _dereq_('../internals/engine-is-deno');
var IS_PURE = _dereq_('../internals/is-pure');
var V8_VERSION = _dereq_('../internals/engine-v8-version');
var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype;
var SPECIES = wellKnownSymbol('species');
var SUBCLASSING = false;
var NATIVE_PROMISE_REJECTION_EVENT = isCallable(global.PromiseRejectionEvent);
var FORCED_PROMISE_CONSTRUCTOR = isForced('Promise', function () {
var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(NativePromiseConstructor);
var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(NativePromiseConstructor);
// V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
// https://bugs.chromium.org/p/chromium/issues/detail?id=830565
// We can't detect it synchronously, so just check versions
if (!GLOBAL_CORE_JS_PROMISE && V8_VERSION === 66) return true;
// We need Promise#{ catch, finally } in the pure version for preventing prototype pollution
if (IS_PURE && !(NativePromisePrototype['catch'] && NativePromisePrototype['finally'])) return true;
// We can't use @@species feature detection in V8 since it causes
// deoptimization and performance degradation
// https://github.com/zloirock/core-js/issues/679
if (!V8_VERSION || V8_VERSION < 51 || !/native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) {
// Detect correctness of subclassing with @@species support
var promise = new NativePromiseConstructor(function (resolve) { resolve(1); });
var FakePromise = function (exec) {
exec(function () { /* empty */ }, function () { /* empty */ });
};
var constructor = promise.constructor = {};
constructor[SPECIES] = FakePromise;
SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise;
if (!SUBCLASSING) return true;
// Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
} return !GLOBAL_CORE_JS_PROMISE && (IS_BROWSER || IS_DENO) && !NATIVE_PROMISE_REJECTION_EVENT;
});
module.exports = {
CONSTRUCTOR: FORCED_PROMISE_CONSTRUCTOR,
REJECTION_EVENT: NATIVE_PROMISE_REJECTION_EVENT,
SUBCLASSING: SUBCLASSING
};
},{"../internals/engine-is-browser":218,"../internals/engine-is-deno":220,"../internals/engine-v8-version":227,"../internals/global":251,"../internals/inspect-source":258,"../internals/is-callable":264,"../internals/is-forced":266,"../internals/is-pure":270,"../internals/promise-native-constructor":308,"../internals/well-known-symbol":343}],308:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
module.exports = global.Promise;
},{"../internals/global":251}],309:[function(_dereq_,module,exports){
var anObject = _dereq_('../internals/an-object');
var isObject = _dereq_('../internals/is-object');
var newPromiseCapability = _dereq_('../internals/new-promise-capability');
module.exports = function (C, x) {
anObject(C);
if (isObject(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
},{"../internals/an-object":178,"../internals/is-object":269,"../internals/new-promise-capability":282}],310:[function(_dereq_,module,exports){
var NativePromiseConstructor = _dereq_('../internals/promise-native-constructor');
var checkCorrectnessOfIteration = _dereq_('../internals/check-correctness-of-iteration');
var FORCED_PROMISE_CONSTRUCTOR = _dereq_('../internals/promise-constructor-detection').CONSTRUCTOR;
module.exports = FORCED_PROMISE_CONSTRUCTOR || !checkCorrectnessOfIteration(function (iterable) {
NativePromiseConstructor.all(iterable).then(undefined, function () { /* empty */ });
});
},{"../internals/check-correctness-of-iteration":194,"../internals/promise-constructor-detection":307,"../internals/promise-native-constructor":308}],311:[function(_dereq_,module,exports){
var Queue = function () {
this.head = null;
this.tail = null;
};
Queue.prototype = {
add: function (item) {
var entry = { item: item, next: null };
var tail = this.tail;
if (tail) tail.next = entry;
else this.head = entry;
this.tail = entry;
},
get: function () {
var entry = this.head;
if (entry) {
var next = this.head = entry.next;
if (next === null) this.tail = null;
return entry.item;
}
}
};
module.exports = Queue;
},{}],312:[function(_dereq_,module,exports){
var isNullOrUndefined = _dereq_('../internals/is-null-or-undefined');
var $TypeError = TypeError;
// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
module.exports = function (it) {
if (isNullOrUndefined(it)) throw $TypeError("Can't call method on " + it);
return it;
};
},{"../internals/is-null-or-undefined":268}],313:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_('../internals/global');
var apply = _dereq_('../internals/function-apply');
var isCallable = _dereq_('../internals/is-callable');
var ENGINE_IS_BUN = _dereq_('../internals/engine-is-bun');
var USER_AGENT = _dereq_('../internals/engine-user-agent');
var arraySlice = _dereq_('../internals/array-slice');
var validateArgumentsLength = _dereq_('../internals/validate-arguments-length');
var Function = global.Function;
// dirty IE9- and Bun 0.3.0- checks
var WRAP = /MSIE .\./.test(USER_AGENT) || ENGINE_IS_BUN && (function () {
var version = global.Bun.version.split('.');
return version.length < 3 || version[0] == 0 && (version[1] < 3 || version[1] == 3 && version[2] == 0);
})();
// IE9- / Bun 0.3.0- setTimeout / setInterval / setImmediate additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
// https://github.com/oven-sh/bun/issues/1633
module.exports = function (scheduler, hasTimeArg) {
var firstParamIndex = hasTimeArg ? 2 : 1;
return WRAP ? function (handler, timeout /* , ...arguments */) {
var boundArgs = validateArgumentsLength(arguments.length, 1) > firstParamIndex;
var fn = isCallable(handler) ? handler : Function(handler);
var params = boundArgs ? arraySlice(arguments, firstParamIndex) : [];
var callback = boundArgs ? function () {
apply(fn, this, params);
} : fn;
return hasTimeArg ? scheduler(callback, timeout) : scheduler(callback);
} : scheduler;
};
},{"../internals/array-slice":189,"../internals/engine-is-bun":219,"../internals/engine-user-agent":226,"../internals/function-apply":237,"../internals/global":251,"../internals/is-callable":264,"../internals/validate-arguments-length":339}],314:[function(_dereq_,module,exports){
'use strict';
var getBuiltIn = _dereq_('../internals/get-built-in');
var defineBuiltInAccessor = _dereq_('../internals/define-built-in-accessor');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var DESCRIPTORS = _dereq_('../internals/descriptors');
var SPECIES = wellKnownSymbol('species');
module.exports = function (CONSTRUCTOR_NAME) {
var Constructor = getBuiltIn(CONSTRUCTOR_NAME);
if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) {
defineBuiltInAccessor(Constructor, SPECIES, {
configurable: true,
get: function () { return this; }
});
}
};
},{"../internals/define-built-in-accessor":207,"../internals/descriptors":212,"../internals/get-built-in":246,"../internals/well-known-symbol":343}],315:[function(_dereq_,module,exports){
var TO_STRING_TAG_SUPPORT = _dereq_('../internals/to-string-tag-support');
var defineProperty = _dereq_('../internals/object-define-property').f;
var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property');
var hasOwn = _dereq_('../internals/has-own-property');
var toString = _dereq_('../internals/object-to-string');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
module.exports = function (it, TAG, STATIC, SET_METHOD) {
if (it) {
var target = STATIC ? it : it.prototype;
if (!hasOwn(target, TO_STRING_TAG)) {
defineProperty(target, TO_STRING_TAG, { configurable: true, value: TAG });
}
if (SET_METHOD && !TO_STRING_TAG_SUPPORT) {
createNonEnumerableProperty(target, 'toString', toString);
}
}
};
},{"../internals/create-non-enumerable-property":204,"../internals/has-own-property":252,"../internals/object-define-property":289,"../internals/object-to-string":302,"../internals/to-string-tag-support":333,"../internals/well-known-symbol":343}],316:[function(_dereq_,module,exports){
var shared = _dereq_('../internals/shared');
var uid = _dereq_('../internals/uid');
var keys = shared('keys');
module.exports = function (key) {
return keys[key] || (keys[key] = uid(key));
};
},{"../internals/shared":318,"../internals/uid":336}],317:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
var defineGlobalProperty = _dereq_('../internals/define-global-property');
var SHARED = '__core-js_shared__';
var store = global[SHARED] || defineGlobalProperty(SHARED, {});
module.exports = store;
},{"../internals/define-global-property":210,"../internals/global":251}],318:[function(_dereq_,module,exports){
var IS_PURE = _dereq_('../internals/is-pure');
var store = _dereq_('../internals/shared-store');
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.30.2',
mode: IS_PURE ? 'pure' : 'global',
copyright: '© 2014-2023 Denis Pushkarev (zloirock.ru)',
license: 'https://github.com/zloirock/core-js/blob/v3.30.2/LICENSE',
source: 'https://github.com/zloirock/core-js'
});
},{"../internals/is-pure":270,"../internals/shared-store":317}],319:[function(_dereq_,module,exports){
var anObject = _dereq_('../internals/an-object');
var aConstructor = _dereq_('../internals/a-constructor');
var isNullOrUndefined = _dereq_('../internals/is-null-or-undefined');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var SPECIES = wellKnownSymbol('species');
// `SpeciesConstructor` abstract operation
// https://tc39.es/ecma262/#sec-speciesconstructor
module.exports = function (O, defaultConstructor) {
var C = anObject(O).constructor;
var S;
return C === undefined || isNullOrUndefined(S = anObject(C)[SPECIES]) ? defaultConstructor : aConstructor(S);
};
},{"../internals/a-constructor":174,"../internals/an-object":178,"../internals/is-null-or-undefined":268,"../internals/well-known-symbol":343}],320:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var toIntegerOrInfinity = _dereq_('../internals/to-integer-or-infinity');
var toString = _dereq_('../internals/to-string');
var requireObjectCoercible = _dereq_('../internals/require-object-coercible');
var charAt = uncurryThis(''.charAt);
var charCodeAt = uncurryThis(''.charCodeAt);
var stringSlice = uncurryThis(''.slice);
var createMethod = function (CONVERT_TO_STRING) {
return function ($this, pos) {
var S = toString(requireObjectCoercible($this));
var position = toIntegerOrInfinity(pos);
var size = S.length;
var first, second;
if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
first = charCodeAt(S, position);
return first < 0xD800 || first > 0xDBFF || position + 1 === size
|| (second = charCodeAt(S, position + 1)) < 0xDC00 || second > 0xDFFF
? CONVERT_TO_STRING
? charAt(S, position)
: first
: CONVERT_TO_STRING
? stringSlice(S, position, position + 2)
: (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
};
};
module.exports = {
// `String.prototype.codePointAt` method
// https://tc39.es/ecma262/#sec-string.prototype.codepointat
codeAt: createMethod(false),
// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt: createMethod(true)
};
},{"../internals/function-uncurry-this":245,"../internals/require-object-coercible":312,"../internals/to-integer-or-infinity":328,"../internals/to-string":334}],321:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var requireObjectCoercible = _dereq_('../internals/require-object-coercible');
var toString = _dereq_('../internals/to-string');
var whitespaces = _dereq_('../internals/whitespaces');
var replace = uncurryThis(''.replace);
var ltrim = RegExp('^[' + whitespaces + ']+');
var rtrim = RegExp('(^|[^' + whitespaces + '])[' + whitespaces + ']+$');
// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
var createMethod = function (TYPE) {
return function ($this) {
var string = toString(requireObjectCoercible($this));
if (TYPE & 1) string = replace(string, ltrim, '');
if (TYPE & 2) string = replace(string, rtrim, '$1');
return string;
};
};
module.exports = {
// `String.prototype.{ trimLeft, trimStart }` methods
// https://tc39.es/ecma262/#sec-string.prototype.trimstart
start: createMethod(1),
// `String.prototype.{ trimRight, trimEnd }` methods
// https://tc39.es/ecma262/#sec-string.prototype.trimend
end: createMethod(2),
// `String.prototype.trim` method
// https://tc39.es/ecma262/#sec-string.prototype.trim
trim: createMethod(3)
};
},{"../internals/function-uncurry-this":245,"../internals/require-object-coercible":312,"../internals/to-string":334,"../internals/whitespaces":344}],322:[function(_dereq_,module,exports){
/* eslint-disable es/no-symbol -- required for testing */
var V8_VERSION = _dereq_('../internals/engine-v8-version');
var fails = _dereq_('../internals/fails');
var global = _dereq_('../internals/global');
var $String = global.String;
// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
var symbol = Symbol();
// Chrome 38 Symbol has incorrect toString conversion
// `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
// nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
// of course, fail.
return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
// Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
!Symbol.sham && V8_VERSION && V8_VERSION < 41;
});
},{"../internals/engine-v8-version":227,"../internals/fails":235,"../internals/global":251}],323:[function(_dereq_,module,exports){
var call = _dereq_('../internals/function-call');
var getBuiltIn = _dereq_('../internals/get-built-in');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var defineBuiltIn = _dereq_('../internals/define-built-in');
module.exports = function () {
var Symbol = getBuiltIn('Symbol');
var SymbolPrototype = Symbol && Symbol.prototype;
var valueOf = SymbolPrototype && SymbolPrototype.valueOf;
var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
if (SymbolPrototype && !SymbolPrototype[TO_PRIMITIVE]) {
// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
// eslint-disable-next-line no-unused-vars -- required for .length
defineBuiltIn(SymbolPrototype, TO_PRIMITIVE, function (hint) {
return call(valueOf, this);
}, { arity: 1 });
}
};
},{"../internals/define-built-in":208,"../internals/function-call":241,"../internals/get-built-in":246,"../internals/well-known-symbol":343}],324:[function(_dereq_,module,exports){
var NATIVE_SYMBOL = _dereq_('../internals/symbol-constructor-detection');
/* eslint-disable es/no-symbol -- safe */
module.exports = NATIVE_SYMBOL && !!Symbol['for'] && !!Symbol.keyFor;
},{"../internals/symbol-constructor-detection":322}],325:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
var apply = _dereq_('../internals/function-apply');
var bind = _dereq_('../internals/function-bind-context');
var isCallable = _dereq_('../internals/is-callable');
var hasOwn = _dereq_('../internals/has-own-property');
var fails = _dereq_('../internals/fails');
var html = _dereq_('../internals/html');
var arraySlice = _dereq_('../internals/array-slice');
var createElement = _dereq_('../internals/document-create-element');
var validateArgumentsLength = _dereq_('../internals/validate-arguments-length');
var IS_IOS = _dereq_('../internals/engine-is-ios');
var IS_NODE = _dereq_('../internals/engine-is-node');
var set = global.setImmediate;
var clear = global.clearImmediate;
var process = global.process;
var Dispatch = global.Dispatch;
var Function = global.Function;
var MessageChannel = global.MessageChannel;
var String = global.String;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var $location, defer, channel, port;
fails(function () {
// Deno throws a ReferenceError on `location` access without `--location` flag
$location = global.location;
});
var run = function (id) {
if (hasOwn(queue, id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
var runner = function (id) {
return function () {
run(id);
};
};
var eventListener = function (event) {
run(event.data);
};
var globalPostMessageDefer = function (id) {
// old engines have not location.origin
global.postMessage(String(id), $location.protocol + '//' + $location.host);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!set || !clear) {
set = function setImmediate(handler) {
validateArgumentsLength(arguments.length, 1);
var fn = isCallable(handler) ? handler : Function(handler);
var args = arraySlice(arguments, 1);
queue[++counter] = function () {
apply(fn, undefined, args);
};
defer(counter);
return counter;
};
clear = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (IS_NODE) {
defer = function (id) {
process.nextTick(runner(id));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(runner(id));
};
// Browsers with MessageChannel, includes WebWorkers
// except iOS - https://github.com/zloirock/core-js/issues/624
} else if (MessageChannel && !IS_IOS) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = eventListener;
defer = bind(port.postMessage, port);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (
global.addEventListener &&
isCallable(global.postMessage) &&
!global.importScripts &&
$location && $location.protocol !== 'file:' &&
!fails(globalPostMessageDefer)
) {
defer = globalPostMessageDefer;
global.addEventListener('message', eventListener, false);
// IE8-
} else if (ONREADYSTATECHANGE in createElement('script')) {
defer = function (id) {
html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(runner(id), 0);
};
}
}
module.exports = {
set: set,
clear: clear
};
},{"../internals/array-slice":189,"../internals/document-create-element":214,"../internals/engine-is-ios":223,"../internals/engine-is-node":224,"../internals/fails":235,"../internals/function-apply":237,"../internals/function-bind-context":238,"../internals/global":251,"../internals/has-own-property":252,"../internals/html":255,"../internals/is-callable":264,"../internals/validate-arguments-length":339}],326:[function(_dereq_,module,exports){
var toIntegerOrInfinity = _dereq_('../internals/to-integer-or-infinity');
var max = Math.max;
var min = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
module.exports = function (index, length) {
var integer = toIntegerOrInfinity(index);
return integer < 0 ? max(integer + length, 0) : min(integer, length);
};
},{"../internals/to-integer-or-infinity":328}],327:[function(_dereq_,module,exports){
// toObject with fallback for non-array-like ES3 strings
var IndexedObject = _dereq_('../internals/indexed-object');
var requireObjectCoercible = _dereq_('../internals/require-object-coercible');
module.exports = function (it) {
return IndexedObject(requireObjectCoercible(it));
};
},{"../internals/indexed-object":257,"../internals/require-object-coercible":312}],328:[function(_dereq_,module,exports){
var trunc = _dereq_('../internals/math-trunc');
// `ToIntegerOrInfinity` abstract operation
// https://tc39.es/ecma262/#sec-tointegerorinfinity
module.exports = function (argument) {
var number = +argument;
// eslint-disable-next-line no-self-compare -- NaN check
return number !== number || number === 0 ? 0 : trunc(number);
};
},{"../internals/math-trunc":280}],329:[function(_dereq_,module,exports){
var toIntegerOrInfinity = _dereq_('../internals/to-integer-or-infinity');
var min = Math.min;
// `ToLength` abstract operation
// https://tc39.es/ecma262/#sec-tolength
module.exports = function (argument) {
return argument > 0 ? min(toIntegerOrInfinity(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
},{"../internals/to-integer-or-infinity":328}],330:[function(_dereq_,module,exports){
var requireObjectCoercible = _dereq_('../internals/require-object-coercible');
var $Object = Object;
// `ToObject` abstract operation
// https://tc39.es/ecma262/#sec-toobject
module.exports = function (argument) {
return $Object(requireObjectCoercible(argument));
};
},{"../internals/require-object-coercible":312}],331:[function(_dereq_,module,exports){
var call = _dereq_('../internals/function-call');
var isObject = _dereq_('../internals/is-object');
var isSymbol = _dereq_('../internals/is-symbol');
var getMethod = _dereq_('../internals/get-method');
var ordinaryToPrimitive = _dereq_('../internals/ordinary-to-primitive');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var $TypeError = TypeError;
var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
module.exports = function (input, pref) {
if (!isObject(input) || isSymbol(input)) return input;
var exoticToPrim = getMethod(input, TO_PRIMITIVE);
var result;
if (exoticToPrim) {
if (pref === undefined) pref = 'default';
result = call(exoticToPrim, input, pref);
if (!isObject(result) || isSymbol(result)) return result;
throw $TypeError("Can't convert object to primitive value");
}
if (pref === undefined) pref = 'number';
return ordinaryToPrimitive(input, pref);
};
},{"../internals/function-call":241,"../internals/get-method":250,"../internals/is-object":269,"../internals/is-symbol":272,"../internals/ordinary-to-primitive":303,"../internals/well-known-symbol":343}],332:[function(_dereq_,module,exports){
var toPrimitive = _dereq_('../internals/to-primitive');
var isSymbol = _dereq_('../internals/is-symbol');
// `ToPropertyKey` abstract operation
// https://tc39.es/ecma262/#sec-topropertykey
module.exports = function (argument) {
var key = toPrimitive(argument, 'string');
return isSymbol(key) ? key : key + '';
};
},{"../internals/is-symbol":272,"../internals/to-primitive":331}],333:[function(_dereq_,module,exports){
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var test = {};
test[TO_STRING_TAG] = 'z';
module.exports = String(test) === '[object z]';
},{"../internals/well-known-symbol":343}],334:[function(_dereq_,module,exports){
var classof = _dereq_('../internals/classof');
var $String = String;
module.exports = function (argument) {
if (classof(argument) === 'Symbol') throw TypeError('Cannot convert a Symbol value to a string');
return $String(argument);
};
},{"../internals/classof":196}],335:[function(_dereq_,module,exports){
var $String = String;
module.exports = function (argument) {
try {
return $String(argument);
} catch (error) {
return 'Object';
}
};
},{}],336:[function(_dereq_,module,exports){
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var id = 0;
var postfix = Math.random();
var toString = uncurryThis(1.0.toString);
module.exports = function (key) {
return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
};
},{"../internals/function-uncurry-this":245}],337:[function(_dereq_,module,exports){
/* eslint-disable es/no-symbol -- required for testing */
var NATIVE_SYMBOL = _dereq_('../internals/symbol-constructor-detection');
module.exports = NATIVE_SYMBOL
&& !Symbol.sham
&& typeof Symbol.iterator == 'symbol';
},{"../internals/symbol-constructor-detection":322}],338:[function(_dereq_,module,exports){
var DESCRIPTORS = _dereq_('../internals/descriptors');
var fails = _dereq_('../internals/fails');
// V8 ~ Chrome 36-
// https://bugs.chromium.org/p/v8/issues/detail?id=3334
module.exports = DESCRIPTORS && fails(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty(function () { /* empty */ }, 'prototype', {
value: 42,
writable: false
}).prototype != 42;
});
},{"../internals/descriptors":212,"../internals/fails":235}],339:[function(_dereq_,module,exports){
var $TypeError = TypeError;
module.exports = function (passed, required) {
if (passed < required) throw $TypeError('Not enough arguments');
return passed;
};
},{}],340:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
var isCallable = _dereq_('../internals/is-callable');
var WeakMap = global.WeakMap;
module.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap));
},{"../internals/global":251,"../internals/is-callable":264}],341:[function(_dereq_,module,exports){
var path = _dereq_('../internals/path');
var hasOwn = _dereq_('../internals/has-own-property');
var wrappedWellKnownSymbolModule = _dereq_('../internals/well-known-symbol-wrapped');
var defineProperty = _dereq_('../internals/object-define-property').f;
module.exports = function (NAME) {
var Symbol = path.Symbol || (path.Symbol = {});
if (!hasOwn(Symbol, NAME)) defineProperty(Symbol, NAME, {
value: wrappedWellKnownSymbolModule.f(NAME)
});
};
},{"../internals/has-own-property":252,"../internals/object-define-property":289,"../internals/path":305,"../internals/well-known-symbol-wrapped":342}],342:[function(_dereq_,module,exports){
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
exports.f = wellKnownSymbol;
},{"../internals/well-known-symbol":343}],343:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
var shared = _dereq_('../internals/shared');
var hasOwn = _dereq_('../internals/has-own-property');
var uid = _dereq_('../internals/uid');
var NATIVE_SYMBOL = _dereq_('../internals/symbol-constructor-detection');
var USE_SYMBOL_AS_UID = _dereq_('../internals/use-symbol-as-uid');
var Symbol = global.Symbol;
var WellKnownSymbolsStore = shared('wks');
var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;
module.exports = function (name) {
if (!hasOwn(WellKnownSymbolsStore, name)) {
WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
? Symbol[name]
: createWellKnownSymbol('Symbol.' + name);
} return WellKnownSymbolsStore[name];
};
},{"../internals/global":251,"../internals/has-own-property":252,"../internals/shared":318,"../internals/symbol-constructor-detection":322,"../internals/uid":336,"../internals/use-symbol-as-uid":337}],344:[function(_dereq_,module,exports){
// a string of all valid unicode whitespaces
module.exports = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002' +
'\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
},{}],345:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var isPrototypeOf = _dereq_('../internals/object-is-prototype-of');
var getPrototypeOf = _dereq_('../internals/object-get-prototype-of');
var setPrototypeOf = _dereq_('../internals/object-set-prototype-of');
var copyConstructorProperties = _dereq_('../internals/copy-constructor-properties');
var create = _dereq_('../internals/object-create');
var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property');
var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor');
var installErrorCause = _dereq_('../internals/install-error-cause');
var installErrorStack = _dereq_('../internals/error-stack-install');
var iterate = _dereq_('../internals/iterate');
var normalizeStringArgument = _dereq_('../internals/normalize-string-argument');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var $Error = Error;
var push = [].push;
var $AggregateError = function AggregateError(errors, message /* , options */) {
var isInstance = isPrototypeOf(AggregateErrorPrototype, this);
var that;
if (setPrototypeOf) {
that = setPrototypeOf($Error(), isInstance ? getPrototypeOf(this) : AggregateErrorPrototype);
} else {
that = isInstance ? this : create(AggregateErrorPrototype);
createNonEnumerableProperty(that, TO_STRING_TAG, 'Error');
}
if (message !== undefined) createNonEnumerableProperty(that, 'message', normalizeStringArgument(message));
installErrorStack(that, $AggregateError, that.stack, 1);
if (arguments.length > 2) installErrorCause(that, arguments[2]);
var errorsArray = [];
iterate(errors, push, { that: errorsArray });
createNonEnumerableProperty(that, 'errors', errorsArray);
return that;
};
if (setPrototypeOf) setPrototypeOf($AggregateError, $Error);
else copyConstructorProperties($AggregateError, $Error, { name: true });
var AggregateErrorPrototype = $AggregateError.prototype = create($Error.prototype, {
constructor: createPropertyDescriptor(1, $AggregateError),
message: createPropertyDescriptor(1, ''),
name: createPropertyDescriptor(1, 'AggregateError')
});
// `AggregateError` constructor
// https://tc39.es/ecma262/#sec-aggregate-error-constructor
$({ global: true, constructor: true, arity: 2 }, {
AggregateError: $AggregateError
});
},{"../internals/copy-constructor-properties":200,"../internals/create-non-enumerable-property":204,"../internals/create-property-descriptor":205,"../internals/error-stack-install":232,"../internals/export":234,"../internals/install-error-cause":259,"../internals/iterate":273,"../internals/normalize-string-argument":283,"../internals/object-create":287,"../internals/object-get-prototype-of":294,"../internals/object-is-prototype-of":296,"../internals/object-set-prototype-of":300,"../internals/well-known-symbol":343}],346:[function(_dereq_,module,exports){
// TODO: Remove this module from `core-js@4` since it's replaced to module below
_dereq_('../modules/es.aggregate-error.constructor');
},{"../modules/es.aggregate-error.constructor":345}],347:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var fails = _dereq_('../internals/fails');
var isArray = _dereq_('../internals/is-array');
var isObject = _dereq_('../internals/is-object');
var toObject = _dereq_('../internals/to-object');
var lengthOfArrayLike = _dereq_('../internals/length-of-array-like');
var doesNotExceedSafeInteger = _dereq_('../internals/does-not-exceed-safe-integer');
var createProperty = _dereq_('../internals/create-property');
var arraySpeciesCreate = _dereq_('../internals/array-species-create');
var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var V8_VERSION = _dereq_('../internals/engine-v8-version');
var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/679
var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () {
var array = [];
array[IS_CONCAT_SPREADABLE] = false;
return array.concat()[0] !== array;
});
var isConcatSpreadable = function (O) {
if (!isObject(O)) return false;
var spreadable = O[IS_CONCAT_SPREADABLE];
return spreadable !== undefined ? !!spreadable : isArray(O);
};
var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !arrayMethodHasSpeciesSupport('concat');
// `Array.prototype.concat` method
// https://tc39.es/ecma262/#sec-array.prototype.concat
// with adding support of @@isConcatSpreadable and @@species
$({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
// eslint-disable-next-line no-unused-vars -- required for `.length`
concat: function concat(arg) {
var O = toObject(this);
var A = arraySpeciesCreate(O, 0);
var n = 0;
var i, k, length, len, E;
for (i = -1, length = arguments.length; i < length; i++) {
E = i === -1 ? O : arguments[i];
if (isConcatSpreadable(E)) {
len = lengthOfArrayLike(E);
doesNotExceedSafeInteger(n + len);
for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
} else {
doesNotExceedSafeInteger(n + 1);
createProperty(A, n++, E);
}
}
A.length = n;
return A;
}
});
},{"../internals/array-method-has-species-support":184,"../internals/array-species-create":192,"../internals/create-property":206,"../internals/does-not-exceed-safe-integer":215,"../internals/engine-v8-version":227,"../internals/export":234,"../internals/fails":235,"../internals/is-array":263,"../internals/is-object":269,"../internals/length-of-array-like":279,"../internals/to-object":330,"../internals/well-known-symbol":343}],348:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var $every = _dereq_('../internals/array-iteration').every;
var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict');
var STRICT_METHOD = arrayMethodIsStrict('every');
// `Array.prototype.every` method
// https://tc39.es/ecma262/#sec-array.prototype.every
$({ target: 'Array', proto: true, forced: !STRICT_METHOD }, {
every: function every(callbackfn /* , thisArg */) {
return $every(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
},{"../internals/array-iteration":183,"../internals/array-method-is-strict":185,"../internals/export":234}],349:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var $filter = _dereq_('../internals/array-iteration').filter;
var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support');
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter');
// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
// with adding support of @@species
$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, {
filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
},{"../internals/array-iteration":183,"../internals/array-method-has-species-support":184,"../internals/export":234}],350:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var $findIndex = _dereq_('../internals/array-iteration').findIndex;
var addToUnscopables = _dereq_('../internals/add-to-unscopables');
var FIND_INDEX = 'findIndex';
var SKIPS_HOLES = true;
// Shouldn't skip holes
// eslint-disable-next-line es/no-array-prototype-findindex -- testing
if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES = false; });
// `Array.prototype.findIndex` method
// https://tc39.es/ecma262/#sec-array.prototype.findindex
$({ target: 'Array', proto: true, forced: SKIPS_HOLES }, {
findIndex: function findIndex(callbackfn /* , that = undefined */) {
return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables(FIND_INDEX);
},{"../internals/add-to-unscopables":176,"../internals/array-iteration":183,"../internals/export":234}],351:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var $find = _dereq_('../internals/array-iteration').find;
var addToUnscopables = _dereq_('../internals/add-to-unscopables');
var FIND = 'find';
var SKIPS_HOLES = true;
// Shouldn't skip holes
// eslint-disable-next-line es/no-array-prototype-find -- testing
if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; });
// `Array.prototype.find` method
// https://tc39.es/ecma262/#sec-array.prototype.find
$({ target: 'Array', proto: true, forced: SKIPS_HOLES }, {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables(FIND);
},{"../internals/add-to-unscopables":176,"../internals/array-iteration":183,"../internals/export":234}],352:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var forEach = _dereq_('../internals/array-for-each');
// `Array.prototype.forEach` method
// https://tc39.es/ecma262/#sec-array.prototype.foreach
// eslint-disable-next-line es/no-array-prototype-foreach -- safe
$({ target: 'Array', proto: true, forced: [].forEach != forEach }, {
forEach: forEach
});
},{"../internals/array-for-each":180,"../internals/export":234}],353:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var from = _dereq_('../internals/array-from');
var checkCorrectnessOfIteration = _dereq_('../internals/check-correctness-of-iteration');
var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) {
// eslint-disable-next-line es/no-array-from -- required for testing
Array.from(iterable);
});
// `Array.from` method
// https://tc39.es/ecma262/#sec-array.from
$({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {
from: from
});
},{"../internals/array-from":181,"../internals/check-correctness-of-iteration":194,"../internals/export":234}],354:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var $includes = _dereq_('../internals/array-includes').includes;
var fails = _dereq_('../internals/fails');
var addToUnscopables = _dereq_('../internals/add-to-unscopables');
// FF99+ bug
var BROKEN_ON_SPARSE = fails(function () {
// eslint-disable-next-line es/no-array-prototype-includes -- detection
return !Array(1).includes();
});
// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
$({ target: 'Array', proto: true, forced: BROKEN_ON_SPARSE }, {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('includes');
},{"../internals/add-to-unscopables":176,"../internals/array-includes":182,"../internals/export":234,"../internals/fails":235}],355:[function(_dereq_,module,exports){
'use strict';
/* eslint-disable es/no-array-prototype-indexof -- required for testing */
var $ = _dereq_('../internals/export');
var uncurryThis = _dereq_('../internals/function-uncurry-this-clause');
var $indexOf = _dereq_('../internals/array-includes').indexOf;
var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict');
var nativeIndexOf = uncurryThis([].indexOf);
var NEGATIVE_ZERO = !!nativeIndexOf && 1 / nativeIndexOf([1], 1, -0) < 0;
var FORCED = NEGATIVE_ZERO || !arrayMethodIsStrict('indexOf');
// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
$({ target: 'Array', proto: true, forced: FORCED }, {
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
var fromIndex = arguments.length > 1 ? arguments[1] : undefined;
return NEGATIVE_ZERO
// convert -0 to +0
? nativeIndexOf(this, searchElement, fromIndex) || 0
: $indexOf(this, searchElement, fromIndex);
}
});
},{"../internals/array-includes":182,"../internals/array-method-is-strict":185,"../internals/export":234,"../internals/function-uncurry-this-clause":244}],356:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var isArray = _dereq_('../internals/is-array');
// `Array.isArray` method
// https://tc39.es/ecma262/#sec-array.isarray
$({ target: 'Array', stat: true }, {
isArray: isArray
});
},{"../internals/export":234,"../internals/is-array":263}],357:[function(_dereq_,module,exports){
'use strict';
var toIndexedObject = _dereq_('../internals/to-indexed-object');
var addToUnscopables = _dereq_('../internals/add-to-unscopables');
var Iterators = _dereq_('../internals/iterators');
var InternalStateModule = _dereq_('../internals/internal-state');
var defineProperty = _dereq_('../internals/object-define-property').f;
var defineIterator = _dereq_('../internals/iterator-define');
var createIterResultObject = _dereq_('../internals/create-iter-result-object');
var IS_PURE = _dereq_('../internals/is-pure');
var DESCRIPTORS = _dereq_('../internals/descriptors');
var ARRAY_ITERATOR = 'Array Iterator';
var setInternalState = InternalStateModule.set;
var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR);
// `Array.prototype.entries` method
// https://tc39.es/ecma262/#sec-array.prototype.entries
// `Array.prototype.keys` method
// https://tc39.es/ecma262/#sec-array.prototype.keys
// `Array.prototype.values` method
// https://tc39.es/ecma262/#sec-array.prototype.values
// `Array.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-array.prototype-@@iterator
// `CreateArrayIterator` internal method
// https://tc39.es/ecma262/#sec-createarrayiterator
module.exports = defineIterator(Array, 'Array', function (iterated, kind) {
setInternalState(this, {
type: ARRAY_ITERATOR,
target: toIndexedObject(iterated), // target
index: 0, // next index
kind: kind // kind
});
// `%ArrayIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next
}, function () {
var state = getInternalState(this);
var target = state.target;
var kind = state.kind;
var index = state.index++;
if (!target || index >= target.length) {
state.target = undefined;
return createIterResultObject(undefined, true);
}
if (kind == 'keys') return createIterResultObject(index, false);
if (kind == 'values') return createIterResultObject(target[index], false);
return createIterResultObject([index, target[index]], false);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values%
// https://tc39.es/ecma262/#sec-createunmappedargumentsobject
// https://tc39.es/ecma262/#sec-createmappedargumentsobject
var values = Iterators.Arguments = Iterators.Array;
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
// V8 ~ Chrome 45- bug
if (!IS_PURE && DESCRIPTORS && values.name !== 'values') try {
defineProperty(values, 'name', { value: 'values' });
} catch (error) { /* empty */ }
},{"../internals/add-to-unscopables":176,"../internals/create-iter-result-object":203,"../internals/descriptors":212,"../internals/internal-state":261,"../internals/is-pure":270,"../internals/iterator-define":276,"../internals/iterators":278,"../internals/object-define-property":289,"../internals/to-indexed-object":327}],358:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var $map = _dereq_('../internals/array-iteration').map;
var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support');
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map');
// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
// with adding support of @@species
$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, {
map: function map(callbackfn /* , thisArg */) {
return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
},{"../internals/array-iteration":183,"../internals/array-method-has-species-support":184,"../internals/export":234}],359:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var $reduce = _dereq_('../internals/array-reduce').left;
var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict');
var CHROME_VERSION = _dereq_('../internals/engine-v8-version');
var IS_NODE = _dereq_('../internals/engine-is-node');
// Chrome 80-82 has a critical bug
// https://bugs.chromium.org/p/chromium/issues/detail?id=1049982
var CHROME_BUG = !IS_NODE && CHROME_VERSION > 79 && CHROME_VERSION < 83;
var FORCED = CHROME_BUG || !arrayMethodIsStrict('reduce');
// `Array.prototype.reduce` method
// https://tc39.es/ecma262/#sec-array.prototype.reduce
$({ target: 'Array', proto: true, forced: FORCED }, {
reduce: function reduce(callbackfn /* , initialValue */) {
var length = arguments.length;
return $reduce(this, callbackfn, length, length > 1 ? arguments[1] : undefined);
}
});
},{"../internals/array-method-is-strict":185,"../internals/array-reduce":186,"../internals/engine-is-node":224,"../internals/engine-v8-version":227,"../internals/export":234}],360:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var isArray = _dereq_('../internals/is-array');
var isConstructor = _dereq_('../internals/is-constructor');
var isObject = _dereq_('../internals/is-object');
var toAbsoluteIndex = _dereq_('../internals/to-absolute-index');
var lengthOfArrayLike = _dereq_('../internals/length-of-array-like');
var toIndexedObject = _dereq_('../internals/to-indexed-object');
var createProperty = _dereq_('../internals/create-property');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support');
var nativeSlice = _dereq_('../internals/array-slice');
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('slice');
var SPECIES = wellKnownSymbol('species');
var $Array = Array;
var max = Math.max;
// `Array.prototype.slice` method
// https://tc39.es/ecma262/#sec-array.prototype.slice
// fallback for not array-like ES3 strings and DOM objects
$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, {
slice: function slice(start, end) {
var O = toIndexedObject(this);
var length = lengthOfArrayLike(O);
var k = toAbsoluteIndex(start, length);
var fin = toAbsoluteIndex(end === undefined ? length : end, length);
// inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
var Constructor, result, n;
if (isArray(O)) {
Constructor = O.constructor;
// cross-realm fallback
if (isConstructor(Constructor) && (Constructor === $Array || isArray(Constructor.prototype))) {
Constructor = undefined;
} else if (isObject(Constructor)) {
Constructor = Constructor[SPECIES];
if (Constructor === null) Constructor = undefined;
}
if (Constructor === $Array || Constructor === undefined) {
return nativeSlice(O, k, fin);
}
}
result = new (Constructor === undefined ? $Array : Constructor)(max(fin - k, 0));
for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
result.length = n;
return result;
}
});
},{"../internals/array-method-has-species-support":184,"../internals/array-slice":189,"../internals/create-property":206,"../internals/export":234,"../internals/is-array":263,"../internals/is-constructor":265,"../internals/is-object":269,"../internals/length-of-array-like":279,"../internals/to-absolute-index":326,"../internals/to-indexed-object":327,"../internals/well-known-symbol":343}],361:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var aCallable = _dereq_('../internals/a-callable');
var toObject = _dereq_('../internals/to-object');
var lengthOfArrayLike = _dereq_('../internals/length-of-array-like');
var deletePropertyOrThrow = _dereq_('../internals/delete-property-or-throw');
var toString = _dereq_('../internals/to-string');
var fails = _dereq_('../internals/fails');
var internalSort = _dereq_('../internals/array-sort');
var arrayMethodIsStrict = _dereq_('../internals/array-method-is-strict');
var FF = _dereq_('../internals/engine-ff-version');
var IE_OR_EDGE = _dereq_('../internals/engine-is-ie-or-edge');
var V8 = _dereq_('../internals/engine-v8-version');
var WEBKIT = _dereq_('../internals/engine-webkit-version');
var test = [];
var nativeSort = uncurryThis(test.sort);
var push = uncurryThis(test.push);
// IE8-
var FAILS_ON_UNDEFINED = fails(function () {
test.sort(undefined);
});
// V8 bug
var FAILS_ON_NULL = fails(function () {
test.sort(null);
});
// Old WebKit
var STRICT_METHOD = arrayMethodIsStrict('sort');
var STABLE_SORT = !fails(function () {
// feature detection can be too slow, so check engines versions
if (V8) return V8 < 70;
if (FF && FF > 3) return;
if (IE_OR_EDGE) return true;
if (WEBKIT) return WEBKIT < 603;
var result = '';
var code, chr, value, index;
// generate an array with more 512 elements (Chakra and old V8 fails only in this case)
for (code = 65; code < 76; code++) {
chr = String.fromCharCode(code);
switch (code) {
case 66: case 69: case 70: case 72: value = 3; break;
case 68: case 71: value = 4; break;
default: value = 2;
}
for (index = 0; index < 47; index++) {
test.push({ k: chr + index, v: value });
}
}
test.sort(function (a, b) { return b.v - a.v; });
for (index = 0; index < test.length; index++) {
chr = test[index].k.charAt(0);
if (result.charAt(result.length - 1) !== chr) result += chr;
}
return result !== 'DGBEFHACIJK';
});
var FORCED = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || !STRICT_METHOD || !STABLE_SORT;
var getSortCompare = function (comparefn) {
return function (x, y) {
if (y === undefined) return -1;
if (x === undefined) return 1;
if (comparefn !== undefined) return +comparefn(x, y) || 0;
return toString(x) > toString(y) ? 1 : -1;
};
};
// `Array.prototype.sort` method
// https://tc39.es/ecma262/#sec-array.prototype.sort
$({ target: 'Array', proto: true, forced: FORCED }, {
sort: function sort(comparefn) {
if (comparefn !== undefined) aCallable(comparefn);
var array = toObject(this);
if (STABLE_SORT) return comparefn === undefined ? nativeSort(array) : nativeSort(array, comparefn);
var items = [];
var arrayLength = lengthOfArrayLike(array);
var itemsLength, index;
for (index = 0; index < arrayLength; index++) {
if (index in array) push(items, array[index]);
}
internalSort(items, getSortCompare(comparefn));
itemsLength = lengthOfArrayLike(items);
index = 0;
while (index < itemsLength) array[index] = items[index++];
while (index < arrayLength) deletePropertyOrThrow(array, index++);
return array;
}
});
},{"../internals/a-callable":173,"../internals/array-method-is-strict":185,"../internals/array-sort":190,"../internals/delete-property-or-throw":211,"../internals/engine-ff-version":217,"../internals/engine-is-ie-or-edge":221,"../internals/engine-v8-version":227,"../internals/engine-webkit-version":228,"../internals/export":234,"../internals/fails":235,"../internals/function-uncurry-this":245,"../internals/length-of-array-like":279,"../internals/to-object":330,"../internals/to-string":334}],362:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var toObject = _dereq_('../internals/to-object');
var toAbsoluteIndex = _dereq_('../internals/to-absolute-index');
var toIntegerOrInfinity = _dereq_('../internals/to-integer-or-infinity');
var lengthOfArrayLike = _dereq_('../internals/length-of-array-like');
var setArrayLength = _dereq_('../internals/array-set-length');
var doesNotExceedSafeInteger = _dereq_('../internals/does-not-exceed-safe-integer');
var arraySpeciesCreate = _dereq_('../internals/array-species-create');
var createProperty = _dereq_('../internals/create-property');
var deletePropertyOrThrow = _dereq_('../internals/delete-property-or-throw');
var arrayMethodHasSpeciesSupport = _dereq_('../internals/array-method-has-species-support');
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('splice');
var max = Math.max;
var min = Math.min;
// `Array.prototype.splice` method
// https://tc39.es/ecma262/#sec-array.prototype.splice
// with adding support of @@species
$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, {
splice: function splice(start, deleteCount /* , ...items */) {
var O = toObject(this);
var len = lengthOfArrayLike(O);
var actualStart = toAbsoluteIndex(start, len);
var argumentsLength = arguments.length;
var insertCount, actualDeleteCount, A, k, from, to;
if (argumentsLength === 0) {
insertCount = actualDeleteCount = 0;
} else if (argumentsLength === 1) {
insertCount = 0;
actualDeleteCount = len - actualStart;
} else {
insertCount = argumentsLength - 2;
actualDeleteCount = min(max(toIntegerOrInfinity(deleteCount), 0), len - actualStart);
}
doesNotExceedSafeInteger(len + insertCount - actualDeleteCount);
A = arraySpeciesCreate(O, actualDeleteCount);
for (k = 0; k < actualDeleteCount; k++) {
from = actualStart + k;
if (from in O) createProperty(A, k, O[from]);
}
A.length = actualDeleteCount;
if (insertCount < actualDeleteCount) {
for (k = actualStart; k < len - actualDeleteCount; k++) {
from = k + actualDeleteCount;
to = k + insertCount;
if (from in O) O[to] = O[from];
else deletePropertyOrThrow(O, to);
}
for (k = len; k > len - actualDeleteCount + insertCount; k--) deletePropertyOrThrow(O, k - 1);
} else if (insertCount > actualDeleteCount) {
for (k = len - actualDeleteCount; k > actualStart; k--) {
from = k + actualDeleteCount - 1;
to = k + insertCount - 1;
if (from in O) O[to] = O[from];
else deletePropertyOrThrow(O, to);
}
}
for (k = 0; k < insertCount; k++) {
O[k + actualStart] = arguments[k + 2];
}
setArrayLength(O, len - actualDeleteCount + insertCount);
return A;
}
});
},{"../internals/array-method-has-species-support":184,"../internals/array-set-length":187,"../internals/array-species-create":192,"../internals/create-property":206,"../internals/delete-property-or-throw":211,"../internals/does-not-exceed-safe-integer":215,"../internals/export":234,"../internals/length-of-array-like":279,"../internals/to-absolute-index":326,"../internals/to-integer-or-infinity":328,"../internals/to-object":330}],363:[function(_dereq_,module,exports){
// empty
},{}],364:[function(_dereq_,module,exports){
// TODO: Remove from `core-js@4`
var $ = _dereq_('../internals/export');
var bind = _dereq_('../internals/function-bind');
// `Function.prototype.bind` method
// https://tc39.es/ecma262/#sec-function.prototype.bind
// eslint-disable-next-line es/no-function-prototype-bind -- detection
$({ target: 'Function', proto: true, forced: Function.bind !== bind }, {
bind: bind
});
},{"../internals/export":234,"../internals/function-bind":240}],365:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var getBuiltIn = _dereq_('../internals/get-built-in');
var apply = _dereq_('../internals/function-apply');
var call = _dereq_('../internals/function-call');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var fails = _dereq_('../internals/fails');
var isCallable = _dereq_('../internals/is-callable');
var isSymbol = _dereq_('../internals/is-symbol');
var arraySlice = _dereq_('../internals/array-slice');
var getReplacerFunction = _dereq_('../internals/get-json-replacer-function');
var NATIVE_SYMBOL = _dereq_('../internals/symbol-constructor-detection');
var $String = String;
var $stringify = getBuiltIn('JSON', 'stringify');
var exec = uncurryThis(/./.exec);
var charAt = uncurryThis(''.charAt);
var charCodeAt = uncurryThis(''.charCodeAt);
var replace = uncurryThis(''.replace);
var numberToString = uncurryThis(1.0.toString);
var tester = /[\uD800-\uDFFF]/g;
var low = /^[\uD800-\uDBFF]$/;
var hi = /^[\uDC00-\uDFFF]$/;
var WRONG_SYMBOLS_CONVERSION = !NATIVE_SYMBOL || fails(function () {
var symbol = getBuiltIn('Symbol')();
// MS Edge converts symbol values to JSON as {}
return $stringify([symbol]) != '[null]'
// WebKit converts symbol values to JSON as null
|| $stringify({ a: symbol }) != '{}'
// V8 throws on boxed symbols
|| $stringify(Object(symbol)) != '{}';
});
// https://github.com/tc39/proposal-well-formed-stringify
var ILL_FORMED_UNICODE = fails(function () {
return $stringify('\uDF06\uD834') !== '"\\udf06\\ud834"'
|| $stringify('\uDEAD') !== '"\\udead"';
});
var stringifyWithSymbolsFix = function (it, replacer) {
var args = arraySlice(arguments);
var $replacer = getReplacerFunction(replacer);
if (!isCallable($replacer) && (it === undefined || isSymbol(it))) return; // IE8 returns string on undefined
args[1] = function (key, value) {
// some old implementations (like WebKit) could pass numbers as keys
if (isCallable($replacer)) value = call($replacer, this, $String(key), value);
if (!isSymbol(value)) return value;
};
return apply($stringify, null, args);
};
var fixIllFormed = function (match, offset, string) {
var prev = charAt(string, offset - 1);
var next = charAt(string, offset + 1);
if ((exec(low, match) && !exec(hi, next)) || (exec(hi, match) && !exec(low, prev))) {
return '\\u' + numberToString(charCodeAt(match, 0), 16);
} return match;
};
if ($stringify) {
// `JSON.stringify` method
// https://tc39.es/ecma262/#sec-json.stringify
$({ target: 'JSON', stat: true, arity: 3, forced: WRONG_SYMBOLS_CONVERSION || ILL_FORMED_UNICODE }, {
// eslint-disable-next-line no-unused-vars -- required for `.length`
stringify: function stringify(it, replacer, space) {
var args = arraySlice(arguments);
var result = apply(WRONG_SYMBOLS_CONVERSION ? stringifyWithSymbolsFix : $stringify, null, args);
return ILL_FORMED_UNICODE && typeof result == 'string' ? replace(result, tester, fixIllFormed) : result;
}
});
}
},{"../internals/array-slice":189,"../internals/export":234,"../internals/fails":235,"../internals/function-apply":237,"../internals/function-call":241,"../internals/function-uncurry-this":245,"../internals/get-built-in":246,"../internals/get-json-replacer-function":249,"../internals/is-callable":264,"../internals/is-symbol":272,"../internals/symbol-constructor-detection":322}],366:[function(_dereq_,module,exports){
var global = _dereq_('../internals/global');
var setToStringTag = _dereq_('../internals/set-to-string-tag');
// JSON[@@toStringTag] property
// https://tc39.es/ecma262/#sec-json-@@tostringtag
setToStringTag(global.JSON, 'JSON', true);
},{"../internals/global":251,"../internals/set-to-string-tag":315}],367:[function(_dereq_,module,exports){
'use strict';
var collection = _dereq_('../internals/collection');
var collectionStrong = _dereq_('../internals/collection-strong');
// `Map` constructor
// https://tc39.es/ecma262/#sec-map-objects
collection('Map', function (init) {
return function Map() { return init(this, arguments.length ? arguments[0] : undefined); };
}, collectionStrong);
},{"../internals/collection":199,"../internals/collection-strong":197}],368:[function(_dereq_,module,exports){
// TODO: Remove this module from `core-js@4` since it's replaced to module below
_dereq_('../modules/es.map.constructor');
},{"../modules/es.map.constructor":367}],369:[function(_dereq_,module,exports){
arguments[4][363][0].apply(exports,arguments)
},{"dup":363}],370:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var isIntegralNumber = _dereq_('../internals/is-integral-number');
// `Number.isInteger` method
// https://tc39.es/ecma262/#sec-number.isinteger
$({ target: 'Number', stat: true }, {
isInteger: isIntegralNumber
});
},{"../internals/export":234,"../internals/is-integral-number":267}],371:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var assign = _dereq_('../internals/object-assign');
// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
// eslint-disable-next-line es/no-object-assign -- required for testing
$({ target: 'Object', stat: true, arity: 2, forced: Object.assign !== assign }, {
assign: assign
});
},{"../internals/export":234,"../internals/object-assign":286}],372:[function(_dereq_,module,exports){
// TODO: Remove from `core-js@4`
var $ = _dereq_('../internals/export');
var DESCRIPTORS = _dereq_('../internals/descriptors');
var create = _dereq_('../internals/object-create');
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
$({ target: 'Object', stat: true, sham: !DESCRIPTORS }, {
create: create
});
},{"../internals/descriptors":212,"../internals/export":234,"../internals/object-create":287}],373:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var DESCRIPTORS = _dereq_('../internals/descriptors');
var defineProperty = _dereq_('../internals/object-define-property').f;
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
// eslint-disable-next-line es/no-object-defineproperty -- safe
$({ target: 'Object', stat: true, forced: Object.defineProperty !== defineProperty, sham: !DESCRIPTORS }, {
defineProperty: defineProperty
});
},{"../internals/descriptors":212,"../internals/export":234,"../internals/object-define-property":289}],374:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var $entries = _dereq_('../internals/object-to-array').entries;
// `Object.entries` method
// https://tc39.es/ecma262/#sec-object.entries
$({ target: 'Object', stat: true }, {
entries: function entries(O) {
return $entries(O);
}
});
},{"../internals/export":234,"../internals/object-to-array":301}],375:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var FREEZING = _dereq_('../internals/freezing');
var fails = _dereq_('../internals/fails');
var isObject = _dereq_('../internals/is-object');
var onFreeze = _dereq_('../internals/internal-metadata').onFreeze;
// eslint-disable-next-line es/no-object-freeze -- safe
var $freeze = Object.freeze;
var FAILS_ON_PRIMITIVES = fails(function () { $freeze(1); });
// `Object.freeze` method
// https://tc39.es/ecma262/#sec-object.freeze
$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !FREEZING }, {
freeze: function freeze(it) {
return $freeze && isObject(it) ? $freeze(onFreeze(it)) : it;
}
});
},{"../internals/export":234,"../internals/fails":235,"../internals/freezing":236,"../internals/internal-metadata":260,"../internals/is-object":269}],376:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var fails = _dereq_('../internals/fails');
var toIndexedObject = _dereq_('../internals/to-indexed-object');
var nativeGetOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f;
var DESCRIPTORS = _dereq_('../internals/descriptors');
var FORCED = !DESCRIPTORS || fails(function () { nativeGetOwnPropertyDescriptor(1); });
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
$({ target: 'Object', stat: true, forced: FORCED, sham: !DESCRIPTORS }, {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) {
return nativeGetOwnPropertyDescriptor(toIndexedObject(it), key);
}
});
},{"../internals/descriptors":212,"../internals/export":234,"../internals/fails":235,"../internals/object-get-own-property-descriptor":290,"../internals/to-indexed-object":327}],377:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var NATIVE_SYMBOL = _dereq_('../internals/symbol-constructor-detection');
var fails = _dereq_('../internals/fails');
var getOwnPropertySymbolsModule = _dereq_('../internals/object-get-own-property-symbols');
var toObject = _dereq_('../internals/to-object');
// V8 ~ Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
var FORCED = !NATIVE_SYMBOL || fails(function () { getOwnPropertySymbolsModule.f(1); });
// `Object.getOwnPropertySymbols` method
// https://tc39.es/ecma262/#sec-object.getownpropertysymbols
$({ target: 'Object', stat: true, forced: FORCED }, {
getOwnPropertySymbols: function getOwnPropertySymbols(it) {
var $getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
return $getOwnPropertySymbols ? $getOwnPropertySymbols(toObject(it)) : [];
}
});
},{"../internals/export":234,"../internals/fails":235,"../internals/object-get-own-property-symbols":293,"../internals/symbol-constructor-detection":322,"../internals/to-object":330}],378:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var fails = _dereq_('../internals/fails');
var toObject = _dereq_('../internals/to-object');
var nativeGetPrototypeOf = _dereq_('../internals/object-get-prototype-of');
var CORRECT_PROTOTYPE_GETTER = _dereq_('../internals/correct-prototype-getter');
var FAILS_ON_PRIMITIVES = fails(function () { nativeGetPrototypeOf(1); });
// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !CORRECT_PROTOTYPE_GETTER }, {
getPrototypeOf: function getPrototypeOf(it) {
return nativeGetPrototypeOf(toObject(it));
}
});
},{"../internals/correct-prototype-getter":202,"../internals/export":234,"../internals/fails":235,"../internals/object-get-prototype-of":294,"../internals/to-object":330}],379:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var toObject = _dereq_('../internals/to-object');
var nativeKeys = _dereq_('../internals/object-keys');
var fails = _dereq_('../internals/fails');
var FAILS_ON_PRIMITIVES = fails(function () { nativeKeys(1); });
// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, {
keys: function keys(it) {
return nativeKeys(toObject(it));
}
});
},{"../internals/export":234,"../internals/fails":235,"../internals/object-keys":298,"../internals/to-object":330}],380:[function(_dereq_,module,exports){
arguments[4][363][0].apply(exports,arguments)
},{"dup":363}],381:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var $parseInt = _dereq_('../internals/number-parse-int');
// `parseInt` method
// https://tc39.es/ecma262/#sec-parseint-string-radix
$({ global: true, forced: parseInt != $parseInt }, {
parseInt: $parseInt
});
},{"../internals/export":234,"../internals/number-parse-int":285}],382:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var call = _dereq_('../internals/function-call');
var aCallable = _dereq_('../internals/a-callable');
var newPromiseCapabilityModule = _dereq_('../internals/new-promise-capability');
var perform = _dereq_('../internals/perform');
var iterate = _dereq_('../internals/iterate');
var PROMISE_STATICS_INCORRECT_ITERATION = _dereq_('../internals/promise-statics-incorrect-iteration');
// `Promise.allSettled` method
// https://tc39.es/ecma262/#sec-promise.allsettled
$({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION }, {
allSettled: function allSettled(iterable) {
var C = this;
var capability = newPromiseCapabilityModule.f(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var promiseResolve = aCallable(C.resolve);
var values = [];
var counter = 0;
var remaining = 1;
iterate(iterable, function (promise) {
var index = counter++;
var alreadyCalled = false;
remaining++;
call(promiseResolve, C, promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = { status: 'fulfilled', value: value };
--remaining || resolve(values);
}, function (error) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = { status: 'rejected', reason: error };
--remaining || resolve(values);
});
});
--remaining || resolve(values);
});
if (result.error) reject(result.value);
return capability.promise;
}
});
},{"../internals/a-callable":173,"../internals/export":234,"../internals/function-call":241,"../internals/iterate":273,"../internals/new-promise-capability":282,"../internals/perform":306,"../internals/promise-statics-incorrect-iteration":310}],383:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var call = _dereq_('../internals/function-call');
var aCallable = _dereq_('../internals/a-callable');
var newPromiseCapabilityModule = _dereq_('../internals/new-promise-capability');
var perform = _dereq_('../internals/perform');
var iterate = _dereq_('../internals/iterate');
var PROMISE_STATICS_INCORRECT_ITERATION = _dereq_('../internals/promise-statics-incorrect-iteration');
// `Promise.all` method
// https://tc39.es/ecma262/#sec-promise.all
$({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION }, {
all: function all(iterable) {
var C = this;
var capability = newPromiseCapabilityModule.f(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var $promiseResolve = aCallable(C.resolve);
var values = [];
var counter = 0;
var remaining = 1;
iterate(iterable, function (promise) {
var index = counter++;
var alreadyCalled = false;
remaining++;
call($promiseResolve, C, promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.error) reject(result.value);
return capability.promise;
}
});
},{"../internals/a-callable":173,"../internals/export":234,"../internals/function-call":241,"../internals/iterate":273,"../internals/new-promise-capability":282,"../internals/perform":306,"../internals/promise-statics-incorrect-iteration":310}],384:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var call = _dereq_('../internals/function-call');
var aCallable = _dereq_('../internals/a-callable');
var getBuiltIn = _dereq_('../internals/get-built-in');
var newPromiseCapabilityModule = _dereq_('../internals/new-promise-capability');
var perform = _dereq_('../internals/perform');
var iterate = _dereq_('../internals/iterate');
var PROMISE_STATICS_INCORRECT_ITERATION = _dereq_('../internals/promise-statics-incorrect-iteration');
var PROMISE_ANY_ERROR = 'No one promise resolved';
// `Promise.any` method
// https://tc39.es/ecma262/#sec-promise.any
$({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION }, {
any: function any(iterable) {
var C = this;
var AggregateError = getBuiltIn('AggregateError');
var capability = newPromiseCapabilityModule.f(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var promiseResolve = aCallable(C.resolve);
var errors = [];
var counter = 0;
var remaining = 1;
var alreadyResolved = false;
iterate(iterable, function (promise) {
var index = counter++;
var alreadyRejected = false;
remaining++;
call(promiseResolve, C, promise).then(function (value) {
if (alreadyRejected || alreadyResolved) return;
alreadyResolved = true;
resolve(value);
}, function (error) {
if (alreadyRejected || alreadyResolved) return;
alreadyRejected = true;
errors[index] = error;
--remaining || reject(new AggregateError(errors, PROMISE_ANY_ERROR));
});
});
--remaining || reject(new AggregateError(errors, PROMISE_ANY_ERROR));
});
if (result.error) reject(result.value);
return capability.promise;
}
});
},{"../internals/a-callable":173,"../internals/export":234,"../internals/function-call":241,"../internals/get-built-in":246,"../internals/iterate":273,"../internals/new-promise-capability":282,"../internals/perform":306,"../internals/promise-statics-incorrect-iteration":310}],385:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var IS_PURE = _dereq_('../internals/is-pure');
var FORCED_PROMISE_CONSTRUCTOR = _dereq_('../internals/promise-constructor-detection').CONSTRUCTOR;
var NativePromiseConstructor = _dereq_('../internals/promise-native-constructor');
var getBuiltIn = _dereq_('../internals/get-built-in');
var isCallable = _dereq_('../internals/is-callable');
var defineBuiltIn = _dereq_('../internals/define-built-in');
var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype;
// `Promise.prototype.catch` method
// https://tc39.es/ecma262/#sec-promise.prototype.catch
$({ target: 'Promise', proto: true, forced: FORCED_PROMISE_CONSTRUCTOR, real: true }, {
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
// makes sure that native promise-based APIs `Promise#catch` properly works with patched `Promise#then`
if (!IS_PURE && isCallable(NativePromiseConstructor)) {
var method = getBuiltIn('Promise').prototype['catch'];
if (NativePromisePrototype['catch'] !== method) {
defineBuiltIn(NativePromisePrototype, 'catch', method, { unsafe: true });
}
}
},{"../internals/define-built-in":208,"../internals/export":234,"../internals/get-built-in":246,"../internals/is-callable":264,"../internals/is-pure":270,"../internals/promise-constructor-detection":307,"../internals/promise-native-constructor":308}],386:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var IS_PURE = _dereq_('../internals/is-pure');
var IS_NODE = _dereq_('../internals/engine-is-node');
var global = _dereq_('../internals/global');
var call = _dereq_('../internals/function-call');
var defineBuiltIn = _dereq_('../internals/define-built-in');
var setPrototypeOf = _dereq_('../internals/object-set-prototype-of');
var setToStringTag = _dereq_('../internals/set-to-string-tag');
var setSpecies = _dereq_('../internals/set-species');
var aCallable = _dereq_('../internals/a-callable');
var isCallable = _dereq_('../internals/is-callable');
var isObject = _dereq_('../internals/is-object');
var anInstance = _dereq_('../internals/an-instance');
var speciesConstructor = _dereq_('../internals/species-constructor');
var task = _dereq_('../internals/task').set;
var microtask = _dereq_('../internals/microtask');
var hostReportErrors = _dereq_('../internals/host-report-errors');
var perform = _dereq_('../internals/perform');
var Queue = _dereq_('../internals/queue');
var InternalStateModule = _dereq_('../internals/internal-state');
var NativePromiseConstructor = _dereq_('../internals/promise-native-constructor');
var PromiseConstructorDetection = _dereq_('../internals/promise-constructor-detection');
var newPromiseCapabilityModule = _dereq_('../internals/new-promise-capability');
var PROMISE = 'Promise';
var FORCED_PROMISE_CONSTRUCTOR = PromiseConstructorDetection.CONSTRUCTOR;
var NATIVE_PROMISE_REJECTION_EVENT = PromiseConstructorDetection.REJECTION_EVENT;
var NATIVE_PROMISE_SUBCLASSING = PromiseConstructorDetection.SUBCLASSING;
var getInternalPromiseState = InternalStateModule.getterFor(PROMISE);
var setInternalState = InternalStateModule.set;
var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype;
var PromiseConstructor = NativePromiseConstructor;
var PromisePrototype = NativePromisePrototype;
var TypeError = global.TypeError;
var document = global.document;
var process = global.process;
var newPromiseCapability = newPromiseCapabilityModule.f;
var newGenericPromiseCapability = newPromiseCapability;
var DISPATCH_EVENT = !!(document && document.createEvent && global.dispatchEvent);
var UNHANDLED_REJECTION = 'unhandledrejection';
var REJECTION_HANDLED = 'rejectionhandled';
var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;
var HANDLED = 1;
var UNHANDLED = 2;
var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;
// helpers
var isThenable = function (it) {
var then;
return isObject(it) && isCallable(then = it.then) ? then : false;
};
var callReaction = function (reaction, state) {
var value = state.value;
var ok = state.state == FULFILLED;
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then, exited;
try {
if (handler) {
if (!ok) {
if (state.rejection === UNHANDLED) onHandleUnhandled(state);
state.rejection = HANDLED;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value); // can throw
if (domain) {
domain.exit();
exited = true;
}
}
if (result === reaction.promise) {
reject(TypeError('Promise-chain cycle'));
} else if (then = isThenable(result)) {
call(then, result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (error) {
if (domain && !exited) domain.exit();
reject(error);
}
};
var notify = function (state, isReject) {
if (state.notified) return;
state.notified = true;
microtask(function () {
var reactions = state.reactions;
var reaction;
while (reaction = reactions.get()) {
callReaction(reaction, state);
}
state.notified = false;
if (isReject && !state.rejection) onUnhandled(state);
});
};
var dispatchEvent = function (name, promise, reason) {
var event, handler;
if (DISPATCH_EVENT) {
event = document.createEvent('Event');
event.promise = promise;
event.reason = reason;
event.initEvent(name, false, true);
global.dispatchEvent(event);
} else event = { promise: promise, reason: reason };
if (!NATIVE_PROMISE_REJECTION_EVENT && (handler = global['on' + name])) handler(event);
else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
};
var onUnhandled = function (state) {
call(task, global, function () {
var promise = state.facade;
var value = state.value;
var IS_UNHANDLED = isUnhandled(state);
var result;
if (IS_UNHANDLED) {
result = perform(function () {
if (IS_NODE) {
process.emit('unhandledRejection', value, promise);
} else dispatchEvent(UNHANDLED_REJECTION, promise, value);
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED;
if (result.error) throw result.value;
}
});
};
var isUnhandled = function (state) {
return state.rejection !== HANDLED && !state.parent;
};
var onHandleUnhandled = function (state) {
call(task, global, function () {
var promise = state.facade;
if (IS_NODE) {
process.emit('rejectionHandled', promise);
} else dispatchEvent(REJECTION_HANDLED, promise, state.value);
});
};
var bind = function (fn, state, unwrap) {
return function (value) {
fn(state, value, unwrap);
};
};
var internalReject = function (state, value, unwrap) {
if (state.done) return;
state.done = true;
if (unwrap) state = unwrap;
state.value = value;
state.state = REJECTED;
notify(state, true);
};
var internalResolve = function (state, value, unwrap) {
if (state.done) return;
state.done = true;
if (unwrap) state = unwrap;
try {
if (state.facade === value) throw TypeError("Promise can't be resolved itself");
var then = isThenable(value);
if (then) {
microtask(function () {
var wrapper = { done: false };
try {
call(then, value,
bind(internalResolve, wrapper, state),
bind(internalReject, wrapper, state)
);
} catch (error) {
internalReject(wrapper, error, state);
}
});
} else {
state.value = value;
state.state = FULFILLED;
notify(state, false);
}
} catch (error) {
internalReject({ done: false }, error, state);
}
};
// constructor polyfill
if (FORCED_PROMISE_CONSTRUCTOR) {
// 25.4.3.1 Promise(executor)
PromiseConstructor = function Promise(executor) {
anInstance(this, PromisePrototype);
aCallable(executor);
call(Internal, this);
var state = getInternalPromiseState(this);
try {
executor(bind(internalResolve, state), bind(internalReject, state));
} catch (error) {
internalReject(state, error);
}
};
PromisePrototype = PromiseConstructor.prototype;
// eslint-disable-next-line no-unused-vars -- required for `.length`
Internal = function Promise(executor) {
setInternalState(this, {
type: PROMISE,
done: false,
notified: false,
parent: false,
reactions: new Queue(),
rejection: false,
state: PENDING,
value: undefined
});
};
// `Promise.prototype.then` method
// https://tc39.es/ecma262/#sec-promise.prototype.then
Internal.prototype = defineBuiltIn(PromisePrototype, 'then', function then(onFulfilled, onRejected) {
var state = getInternalPromiseState(this);
var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor));
state.parent = true;
reaction.ok = isCallable(onFulfilled) ? onFulfilled : true;
reaction.fail = isCallable(onRejected) && onRejected;
reaction.domain = IS_NODE ? process.domain : undefined;
if (state.state == PENDING) state.reactions.add(reaction);
else microtask(function () {
callReaction(reaction, state);
});
return reaction.promise;
});
OwnPromiseCapability = function () {
var promise = new Internal();
var state = getInternalPromiseState(promise);
this.promise = promise;
this.resolve = bind(internalResolve, state);
this.reject = bind(internalReject, state);
};
newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
return C === PromiseConstructor || C === PromiseWrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
if (!IS_PURE && isCallable(NativePromiseConstructor) && NativePromisePrototype !== Object.prototype) {
nativeThen = NativePromisePrototype.then;
if (!NATIVE_PROMISE_SUBCLASSING) {
// make `Promise#then` return a polyfilled `Promise` for native promise-based APIs
defineBuiltIn(NativePromisePrototype, 'then', function then(onFulfilled, onRejected) {
var that = this;
return new PromiseConstructor(function (resolve, reject) {
call(nativeThen, that, resolve, reject);
}).then(onFulfilled, onRejected);
// https://github.com/zloirock/core-js/issues/640
}, { unsafe: true });
}
// make `.constructor === Promise` work for native promise-based APIs
try {
delete NativePromisePrototype.constructor;
} catch (error) { /* empty */ }
// make `instanceof Promise` work for native promise-based APIs
if (setPrototypeOf) {
setPrototypeOf(NativePromisePrototype, PromisePrototype);
}
}
}
$({ global: true, constructor: true, wrap: true, forced: FORCED_PROMISE_CONSTRUCTOR }, {
Promise: PromiseConstructor
});
setToStringTag(PromiseConstructor, PROMISE, false, true);
setSpecies(PROMISE);
},{"../internals/a-callable":173,"../internals/an-instance":177,"../internals/define-built-in":208,"../internals/engine-is-node":224,"../internals/export":234,"../internals/function-call":241,"../internals/global":251,"../internals/host-report-errors":254,"../internals/internal-state":261,"../internals/is-callable":264,"../internals/is-object":269,"../internals/is-pure":270,"../internals/microtask":281,"../internals/new-promise-capability":282,"../internals/object-set-prototype-of":300,"../internals/perform":306,"../internals/promise-constructor-detection":307,"../internals/promise-native-constructor":308,"../internals/queue":311,"../internals/set-species":314,"../internals/set-to-string-tag":315,"../internals/species-constructor":319,"../internals/task":325}],387:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var IS_PURE = _dereq_('../internals/is-pure');
var NativePromiseConstructor = _dereq_('../internals/promise-native-constructor');
var fails = _dereq_('../internals/fails');
var getBuiltIn = _dereq_('../internals/get-built-in');
var isCallable = _dereq_('../internals/is-callable');
var speciesConstructor = _dereq_('../internals/species-constructor');
var promiseResolve = _dereq_('../internals/promise-resolve');
var defineBuiltIn = _dereq_('../internals/define-built-in');
var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype;
// Safari bug https://bugs.webkit.org/show_bug.cgi?id=200829
var NON_GENERIC = !!NativePromiseConstructor && fails(function () {
// eslint-disable-next-line unicorn/no-thenable -- required for testing
NativePromisePrototype['finally'].call({ then: function () { /* empty */ } }, function () { /* empty */ });
});
// `Promise.prototype.finally` method
// https://tc39.es/ecma262/#sec-promise.prototype.finally
$({ target: 'Promise', proto: true, real: true, forced: NON_GENERIC }, {
'finally': function (onFinally) {
var C = speciesConstructor(this, getBuiltIn('Promise'));
var isFunction = isCallable(onFinally);
return this.then(
isFunction ? function (x) {
return promiseResolve(C, onFinally()).then(function () { return x; });
} : onFinally,
isFunction ? function (e) {
return promiseResolve(C, onFinally()).then(function () { throw e; });
} : onFinally
);
}
});
// makes sure that native promise-based APIs `Promise#finally` properly works with patched `Promise#then`
if (!IS_PURE && isCallable(NativePromiseConstructor)) {
var method = getBuiltIn('Promise').prototype['finally'];
if (NativePromisePrototype['finally'] !== method) {
defineBuiltIn(NativePromisePrototype, 'finally', method, { unsafe: true });
}
}
},{"../internals/define-built-in":208,"../internals/export":234,"../internals/fails":235,"../internals/get-built-in":246,"../internals/is-callable":264,"../internals/is-pure":270,"../internals/promise-native-constructor":308,"../internals/promise-resolve":309,"../internals/species-constructor":319}],388:[function(_dereq_,module,exports){
// TODO: Remove this module from `core-js@4` since it's split to modules listed below
_dereq_('../modules/es.promise.constructor');
_dereq_('../modules/es.promise.all');
_dereq_('../modules/es.promise.catch');
_dereq_('../modules/es.promise.race');
_dereq_('../modules/es.promise.reject');
_dereq_('../modules/es.promise.resolve');
},{"../modules/es.promise.all":383,"../modules/es.promise.catch":385,"../modules/es.promise.constructor":386,"../modules/es.promise.race":389,"../modules/es.promise.reject":390,"../modules/es.promise.resolve":391}],389:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var call = _dereq_('../internals/function-call');
var aCallable = _dereq_('../internals/a-callable');
var newPromiseCapabilityModule = _dereq_('../internals/new-promise-capability');
var perform = _dereq_('../internals/perform');
var iterate = _dereq_('../internals/iterate');
var PROMISE_STATICS_INCORRECT_ITERATION = _dereq_('../internals/promise-statics-incorrect-iteration');
// `Promise.race` method
// https://tc39.es/ecma262/#sec-promise.race
$({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION }, {
race: function race(iterable) {
var C = this;
var capability = newPromiseCapabilityModule.f(C);
var reject = capability.reject;
var result = perform(function () {
var $promiseResolve = aCallable(C.resolve);
iterate(iterable, function (promise) {
call($promiseResolve, C, promise).then(capability.resolve, reject);
});
});
if (result.error) reject(result.value);
return capability.promise;
}
});
},{"../internals/a-callable":173,"../internals/export":234,"../internals/function-call":241,"../internals/iterate":273,"../internals/new-promise-capability":282,"../internals/perform":306,"../internals/promise-statics-incorrect-iteration":310}],390:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var call = _dereq_('../internals/function-call');
var newPromiseCapabilityModule = _dereq_('../internals/new-promise-capability');
var FORCED_PROMISE_CONSTRUCTOR = _dereq_('../internals/promise-constructor-detection').CONSTRUCTOR;
// `Promise.reject` method
// https://tc39.es/ecma262/#sec-promise.reject
$({ target: 'Promise', stat: true, forced: FORCED_PROMISE_CONSTRUCTOR }, {
reject: function reject(r) {
var capability = newPromiseCapabilityModule.f(this);
call(capability.reject, undefined, r);
return capability.promise;
}
});
},{"../internals/export":234,"../internals/function-call":241,"../internals/new-promise-capability":282,"../internals/promise-constructor-detection":307}],391:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var getBuiltIn = _dereq_('../internals/get-built-in');
var IS_PURE = _dereq_('../internals/is-pure');
var NativePromiseConstructor = _dereq_('../internals/promise-native-constructor');
var FORCED_PROMISE_CONSTRUCTOR = _dereq_('../internals/promise-constructor-detection').CONSTRUCTOR;
var promiseResolve = _dereq_('../internals/promise-resolve');
var PromiseConstructorWrapper = getBuiltIn('Promise');
var CHECK_WRAPPER = IS_PURE && !FORCED_PROMISE_CONSTRUCTOR;
// `Promise.resolve` method
// https://tc39.es/ecma262/#sec-promise.resolve
$({ target: 'Promise', stat: true, forced: IS_PURE || FORCED_PROMISE_CONSTRUCTOR }, {
resolve: function resolve(x) {
return promiseResolve(CHECK_WRAPPER && this === PromiseConstructorWrapper ? NativePromiseConstructor : this, x);
}
});
},{"../internals/export":234,"../internals/get-built-in":246,"../internals/is-pure":270,"../internals/promise-constructor-detection":307,"../internals/promise-native-constructor":308,"../internals/promise-resolve":309}],392:[function(_dereq_,module,exports){
arguments[4][363][0].apply(exports,arguments)
},{"dup":363}],393:[function(_dereq_,module,exports){
'use strict';
var collection = _dereq_('../internals/collection');
var collectionStrong = _dereq_('../internals/collection-strong');
// `Set` constructor
// https://tc39.es/ecma262/#sec-set-objects
collection('Set', function (init) {
return function Set() { return init(this, arguments.length ? arguments[0] : undefined); };
}, collectionStrong);
},{"../internals/collection":199,"../internals/collection-strong":197}],394:[function(_dereq_,module,exports){
// TODO: Remove this module from `core-js@4` since it's replaced to module below
_dereq_('../modules/es.set.constructor');
},{"../modules/es.set.constructor":393}],395:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var notARegExp = _dereq_('../internals/not-a-regexp');
var requireObjectCoercible = _dereq_('../internals/require-object-coercible');
var toString = _dereq_('../internals/to-string');
var correctIsRegExpLogic = _dereq_('../internals/correct-is-regexp-logic');
var stringIndexOf = uncurryThis(''.indexOf);
// `String.prototype.includes` method
// https://tc39.es/ecma262/#sec-string.prototype.includes
$({ target: 'String', proto: true, forced: !correctIsRegExpLogic('includes') }, {
includes: function includes(searchString /* , position = 0 */) {
return !!~stringIndexOf(
toString(requireObjectCoercible(this)),
toString(notARegExp(searchString)),
arguments.length > 1 ? arguments[1] : undefined
);
}
});
},{"../internals/correct-is-regexp-logic":201,"../internals/export":234,"../internals/function-uncurry-this":245,"../internals/not-a-regexp":284,"../internals/require-object-coercible":312,"../internals/to-string":334}],396:[function(_dereq_,module,exports){
'use strict';
var charAt = _dereq_('../internals/string-multibyte').charAt;
var toString = _dereq_('../internals/to-string');
var InternalStateModule = _dereq_('../internals/internal-state');
var defineIterator = _dereq_('../internals/iterator-define');
var createIterResultObject = _dereq_('../internals/create-iter-result-object');
var STRING_ITERATOR = 'String Iterator';
var setInternalState = InternalStateModule.set;
var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);
// `String.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-string.prototype-@@iterator
defineIterator(String, 'String', function (iterated) {
setInternalState(this, {
type: STRING_ITERATOR,
string: toString(iterated),
index: 0
});
// `%StringIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next
}, function next() {
var state = getInternalState(this);
var string = state.string;
var index = state.index;
var point;
if (index >= string.length) return createIterResultObject(undefined, true);
point = charAt(string, index);
state.index += point.length;
return createIterResultObject(point, false);
});
},{"../internals/create-iter-result-object":203,"../internals/internal-state":261,"../internals/iterator-define":276,"../internals/string-multibyte":320,"../internals/to-string":334}],397:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var uncurryThis = _dereq_('../internals/function-uncurry-this-clause');
var getOwnPropertyDescriptor = _dereq_('../internals/object-get-own-property-descriptor').f;
var toLength = _dereq_('../internals/to-length');
var toString = _dereq_('../internals/to-string');
var notARegExp = _dereq_('../internals/not-a-regexp');
var requireObjectCoercible = _dereq_('../internals/require-object-coercible');
var correctIsRegExpLogic = _dereq_('../internals/correct-is-regexp-logic');
var IS_PURE = _dereq_('../internals/is-pure');
// eslint-disable-next-line es/no-string-prototype-startswith -- safe
var nativeStartsWith = uncurryThis(''.startsWith);
var stringSlice = uncurryThis(''.slice);
var min = Math.min;
var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('startsWith');
// https://github.com/zloirock/core-js/pull/702
var MDN_POLYFILL_BUG = !IS_PURE && !CORRECT_IS_REGEXP_LOGIC && !!function () {
var descriptor = getOwnPropertyDescriptor(String.prototype, 'startsWith');
return descriptor && !descriptor.writable;
}();
// `String.prototype.startsWith` method
// https://tc39.es/ecma262/#sec-string.prototype.startswith
$({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = toString(requireObjectCoercible(this));
notARegExp(searchString);
var index = toLength(min(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = toString(searchString);
return nativeStartsWith
? nativeStartsWith(that, search, index)
: stringSlice(that, index, index + search.length) === search;
}
});
},{"../internals/correct-is-regexp-logic":201,"../internals/export":234,"../internals/function-uncurry-this-clause":244,"../internals/is-pure":270,"../internals/not-a-regexp":284,"../internals/object-get-own-property-descriptor":290,"../internals/require-object-coercible":312,"../internals/to-length":329,"../internals/to-string":334}],398:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.asyncIterator` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.asynciterator
defineWellKnownSymbol('asyncIterator');
},{"../internals/well-known-symbol-define":341}],399:[function(_dereq_,module,exports){
'use strict';
var $ = _dereq_('../internals/export');
var global = _dereq_('../internals/global');
var call = _dereq_('../internals/function-call');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var IS_PURE = _dereq_('../internals/is-pure');
var DESCRIPTORS = _dereq_('../internals/descriptors');
var NATIVE_SYMBOL = _dereq_('../internals/symbol-constructor-detection');
var fails = _dereq_('../internals/fails');
var hasOwn = _dereq_('../internals/has-own-property');
var isPrototypeOf = _dereq_('../internals/object-is-prototype-of');
var anObject = _dereq_('../internals/an-object');
var toIndexedObject = _dereq_('../internals/to-indexed-object');
var toPropertyKey = _dereq_('../internals/to-property-key');
var $toString = _dereq_('../internals/to-string');
var createPropertyDescriptor = _dereq_('../internals/create-property-descriptor');
var nativeObjectCreate = _dereq_('../internals/object-create');
var objectKeys = _dereq_('../internals/object-keys');
var getOwnPropertyNamesModule = _dereq_('../internals/object-get-own-property-names');
var getOwnPropertyNamesExternal = _dereq_('../internals/object-get-own-property-names-external');
var getOwnPropertySymbolsModule = _dereq_('../internals/object-get-own-property-symbols');
var getOwnPropertyDescriptorModule = _dereq_('../internals/object-get-own-property-descriptor');
var definePropertyModule = _dereq_('../internals/object-define-property');
var definePropertiesModule = _dereq_('../internals/object-define-properties');
var propertyIsEnumerableModule = _dereq_('../internals/object-property-is-enumerable');
var defineBuiltIn = _dereq_('../internals/define-built-in');
var defineBuiltInAccessor = _dereq_('../internals/define-built-in-accessor');
var shared = _dereq_('../internals/shared');
var sharedKey = _dereq_('../internals/shared-key');
var hiddenKeys = _dereq_('../internals/hidden-keys');
var uid = _dereq_('../internals/uid');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var wrappedWellKnownSymbolModule = _dereq_('../internals/well-known-symbol-wrapped');
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
var defineSymbolToPrimitive = _dereq_('../internals/symbol-define-to-primitive');
var setToStringTag = _dereq_('../internals/set-to-string-tag');
var InternalStateModule = _dereq_('../internals/internal-state');
var $forEach = _dereq_('../internals/array-iteration').forEach;
var HIDDEN = sharedKey('hidden');
var SYMBOL = 'Symbol';
var PROTOTYPE = 'prototype';
var setInternalState = InternalStateModule.set;
var getInternalState = InternalStateModule.getterFor(SYMBOL);
var ObjectPrototype = Object[PROTOTYPE];
var $Symbol = global.Symbol;
var SymbolPrototype = $Symbol && $Symbol[PROTOTYPE];
var TypeError = global.TypeError;
var QObject = global.QObject;
var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
var nativeDefineProperty = definePropertyModule.f;
var nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f;
var nativePropertyIsEnumerable = propertyIsEnumerableModule.f;
var push = uncurryThis([].push);
var AllSymbols = shared('symbols');
var ObjectPrototypeSymbols = shared('op-symbols');
var WellKnownSymbolsStore = shared('wks');
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDescriptor = DESCRIPTORS && fails(function () {
return nativeObjectCreate(nativeDefineProperty({}, 'a', {
get: function () { return nativeDefineProperty(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (O, P, Attributes) {
var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P);
if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];
nativeDefineProperty(O, P, Attributes);
if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {
nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor);
}
} : nativeDefineProperty;
var wrap = function (tag, description) {
var symbol = AllSymbols[tag] = nativeObjectCreate(SymbolPrototype);
setInternalState(symbol, {
type: SYMBOL,
tag: tag,
description: description
});
if (!DESCRIPTORS) symbol.description = description;
return symbol;
};
var $defineProperty = function defineProperty(O, P, Attributes) {
if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);
anObject(O);
var key = toPropertyKey(P);
anObject(Attributes);
if (hasOwn(AllSymbols, key)) {
if (!Attributes.enumerable) {
if (!hasOwn(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {}));
O[HIDDEN][key] = true;
} else {
if (hasOwn(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
Attributes = nativeObjectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });
} return setSymbolDescriptor(O, key, Attributes);
} return nativeDefineProperty(O, key, Attributes);
};
var $defineProperties = function defineProperties(O, Properties) {
anObject(O);
var properties = toIndexedObject(Properties);
var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));
$forEach(keys, function (key) {
if (!DESCRIPTORS || call($propertyIsEnumerable, properties, key)) $defineProperty(O, key, properties[key]);
});
return O;
};
var $create = function create(O, Properties) {
return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties);
};
var $propertyIsEnumerable = function propertyIsEnumerable(V) {
var P = toPropertyKey(V);
var enumerable = call(nativePropertyIsEnumerable, this, P);
if (this === ObjectPrototype && hasOwn(AllSymbols, P) && !hasOwn(ObjectPrototypeSymbols, P)) return false;
return enumerable || !hasOwn(this, P) || !hasOwn(AllSymbols, P) || hasOwn(this, HIDDEN) && this[HIDDEN][P]
? enumerable : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {
var it = toIndexedObject(O);
var key = toPropertyKey(P);
if (it === ObjectPrototype && hasOwn(AllSymbols, key) && !hasOwn(ObjectPrototypeSymbols, key)) return;
var descriptor = nativeGetOwnPropertyDescriptor(it, key);
if (descriptor && hasOwn(AllSymbols, key) && !(hasOwn(it, HIDDEN) && it[HIDDEN][key])) {
descriptor.enumerable = true;
}
return descriptor;
};
var $getOwnPropertyNames = function getOwnPropertyNames(O) {
var names = nativeGetOwnPropertyNames(toIndexedObject(O));
var result = [];
$forEach(names, function (key) {
if (!hasOwn(AllSymbols, key) && !hasOwn(hiddenKeys, key)) push(result, key);
});
return result;
};
var $getOwnPropertySymbols = function (O) {
var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;
var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));
var result = [];
$forEach(names, function (key) {
if (hasOwn(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || hasOwn(ObjectPrototype, key))) {
push(result, AllSymbols[key]);
}
});
return result;
};
// `Symbol` constructor
// https://tc39.es/ecma262/#sec-symbol-constructor
if (!NATIVE_SYMBOL) {
$Symbol = function Symbol() {
if (isPrototypeOf(SymbolPrototype, this)) throw TypeError('Symbol is not a constructor');
var description = !arguments.length || arguments[0] === undefined ? undefined : $toString(arguments[0]);
var tag = uid(description);
var setter = function (value) {
if (this === ObjectPrototype) call(setter, ObjectPrototypeSymbols, value);
if (hasOwn(this, HIDDEN) && hasOwn(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));
};
if (DESCRIPTORS && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter });
return wrap(tag, description);
};
SymbolPrototype = $Symbol[PROTOTYPE];
defineBuiltIn(SymbolPrototype, 'toString', function toString() {
return getInternalState(this).tag;
});
defineBuiltIn($Symbol, 'withoutSetter', function (description) {
return wrap(uid(description), description);
});
propertyIsEnumerableModule.f = $propertyIsEnumerable;
definePropertyModule.f = $defineProperty;
definePropertiesModule.f = $defineProperties;
getOwnPropertyDescriptorModule.f = $getOwnPropertyDescriptor;
getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames;
getOwnPropertySymbolsModule.f = $getOwnPropertySymbols;
wrappedWellKnownSymbolModule.f = function (name) {
return wrap(wellKnownSymbol(name), name);
};
if (DESCRIPTORS) {
// https://github.com/tc39/proposal-Symbol-description
defineBuiltInAccessor(SymbolPrototype, 'description', {
configurable: true,
get: function description() {
return getInternalState(this).description;
}
});
if (!IS_PURE) {
defineBuiltIn(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });
}
}
}
$({ global: true, constructor: true, wrap: true, forced: !NATIVE_SYMBOL, sham: !NATIVE_SYMBOL }, {
Symbol: $Symbol
});
$forEach(objectKeys(WellKnownSymbolsStore), function (name) {
defineWellKnownSymbol(name);
});
$({ target: SYMBOL, stat: true, forced: !NATIVE_SYMBOL }, {
useSetter: function () { USE_SETTER = true; },
useSimple: function () { USE_SETTER = false; }
});
$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL, sham: !DESCRIPTORS }, {
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
create: $create,
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
defineProperty: $defineProperty,
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
defineProperties: $defineProperties,
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptors
getOwnPropertyDescriptor: $getOwnPropertyDescriptor
});
$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL }, {
// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
getOwnPropertyNames: $getOwnPropertyNames
});
// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
defineSymbolToPrimitive();
// `Symbol.prototype[@@toStringTag]` property
// https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag
setToStringTag($Symbol, SYMBOL);
hiddenKeys[HIDDEN] = true;
},{"../internals/an-object":178,"../internals/array-iteration":183,"../internals/create-property-descriptor":205,"../internals/define-built-in":208,"../internals/define-built-in-accessor":207,"../internals/descriptors":212,"../internals/export":234,"../internals/fails":235,"../internals/function-call":241,"../internals/function-uncurry-this":245,"../internals/global":251,"../internals/has-own-property":252,"../internals/hidden-keys":253,"../internals/internal-state":261,"../internals/is-pure":270,"../internals/object-create":287,"../internals/object-define-properties":288,"../internals/object-define-property":289,"../internals/object-get-own-property-descriptor":290,"../internals/object-get-own-property-names":292,"../internals/object-get-own-property-names-external":291,"../internals/object-get-own-property-symbols":293,"../internals/object-is-prototype-of":296,"../internals/object-keys":298,"../internals/object-property-is-enumerable":299,"../internals/set-to-string-tag":315,"../internals/shared":318,"../internals/shared-key":316,"../internals/symbol-constructor-detection":322,"../internals/symbol-define-to-primitive":323,"../internals/to-indexed-object":327,"../internals/to-property-key":332,"../internals/to-string":334,"../internals/uid":336,"../internals/well-known-symbol":343,"../internals/well-known-symbol-define":341,"../internals/well-known-symbol-wrapped":342}],400:[function(_dereq_,module,exports){
arguments[4][363][0].apply(exports,arguments)
},{"dup":363}],401:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var getBuiltIn = _dereq_('../internals/get-built-in');
var hasOwn = _dereq_('../internals/has-own-property');
var toString = _dereq_('../internals/to-string');
var shared = _dereq_('../internals/shared');
var NATIVE_SYMBOL_REGISTRY = _dereq_('../internals/symbol-registry-detection');
var StringToSymbolRegistry = shared('string-to-symbol-registry');
var SymbolToStringRegistry = shared('symbol-to-string-registry');
// `Symbol.for` method
// https://tc39.es/ecma262/#sec-symbol.for
$({ target: 'Symbol', stat: true, forced: !NATIVE_SYMBOL_REGISTRY }, {
'for': function (key) {
var string = toString(key);
if (hasOwn(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
var symbol = getBuiltIn('Symbol')(string);
StringToSymbolRegistry[string] = symbol;
SymbolToStringRegistry[symbol] = string;
return symbol;
}
});
},{"../internals/export":234,"../internals/get-built-in":246,"../internals/has-own-property":252,"../internals/shared":318,"../internals/symbol-registry-detection":324,"../internals/to-string":334}],402:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.hasInstance` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.hasinstance
defineWellKnownSymbol('hasInstance');
},{"../internals/well-known-symbol-define":341}],403:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.isConcatSpreadable` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.isconcatspreadable
defineWellKnownSymbol('isConcatSpreadable');
},{"../internals/well-known-symbol-define":341}],404:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.iterator` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.iterator
defineWellKnownSymbol('iterator');
},{"../internals/well-known-symbol-define":341}],405:[function(_dereq_,module,exports){
// TODO: Remove this module from `core-js@4` since it's split to modules listed below
_dereq_('../modules/es.symbol.constructor');
_dereq_('../modules/es.symbol.for');
_dereq_('../modules/es.symbol.key-for');
_dereq_('../modules/es.json.stringify');
_dereq_('../modules/es.object.get-own-property-symbols');
},{"../modules/es.json.stringify":365,"../modules/es.object.get-own-property-symbols":377,"../modules/es.symbol.constructor":399,"../modules/es.symbol.for":401,"../modules/es.symbol.key-for":406}],406:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var hasOwn = _dereq_('../internals/has-own-property');
var isSymbol = _dereq_('../internals/is-symbol');
var tryToString = _dereq_('../internals/try-to-string');
var shared = _dereq_('../internals/shared');
var NATIVE_SYMBOL_REGISTRY = _dereq_('../internals/symbol-registry-detection');
var SymbolToStringRegistry = shared('symbol-to-string-registry');
// `Symbol.keyFor` method
// https://tc39.es/ecma262/#sec-symbol.keyfor
$({ target: 'Symbol', stat: true, forced: !NATIVE_SYMBOL_REGISTRY }, {
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(tryToString(sym) + ' is not a symbol');
if (hasOwn(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];
}
});
},{"../internals/export":234,"../internals/has-own-property":252,"../internals/is-symbol":272,"../internals/shared":318,"../internals/symbol-registry-detection":324,"../internals/try-to-string":335}],407:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.matchAll` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.matchall
defineWellKnownSymbol('matchAll');
},{"../internals/well-known-symbol-define":341}],408:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.match` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.match
defineWellKnownSymbol('match');
},{"../internals/well-known-symbol-define":341}],409:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.replace` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.replace
defineWellKnownSymbol('replace');
},{"../internals/well-known-symbol-define":341}],410:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.search` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.search
defineWellKnownSymbol('search');
},{"../internals/well-known-symbol-define":341}],411:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.species` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.species
defineWellKnownSymbol('species');
},{"../internals/well-known-symbol-define":341}],412:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.split` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.split
defineWellKnownSymbol('split');
},{"../internals/well-known-symbol-define":341}],413:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
var defineSymbolToPrimitive = _dereq_('../internals/symbol-define-to-primitive');
// `Symbol.toPrimitive` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.toprimitive
defineWellKnownSymbol('toPrimitive');
// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
defineSymbolToPrimitive();
},{"../internals/symbol-define-to-primitive":323,"../internals/well-known-symbol-define":341}],414:[function(_dereq_,module,exports){
var getBuiltIn = _dereq_('../internals/get-built-in');
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
var setToStringTag = _dereq_('../internals/set-to-string-tag');
// `Symbol.toStringTag` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.tostringtag
defineWellKnownSymbol('toStringTag');
// `Symbol.prototype[@@toStringTag]` property
// https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag
setToStringTag(getBuiltIn('Symbol'), 'Symbol');
},{"../internals/get-built-in":246,"../internals/set-to-string-tag":315,"../internals/well-known-symbol-define":341}],415:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.unscopables` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.unscopables
defineWellKnownSymbol('unscopables');
},{"../internals/well-known-symbol-define":341}],416:[function(_dereq_,module,exports){
'use strict';
var FREEZING = _dereq_('../internals/freezing');
var global = _dereq_('../internals/global');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var defineBuiltIns = _dereq_('../internals/define-built-ins');
var InternalMetadataModule = _dereq_('../internals/internal-metadata');
var collection = _dereq_('../internals/collection');
var collectionWeak = _dereq_('../internals/collection-weak');
var isObject = _dereq_('../internals/is-object');
var enforceInternalState = _dereq_('../internals/internal-state').enforce;
var fails = _dereq_('../internals/fails');
var NATIVE_WEAK_MAP = _dereq_('../internals/weak-map-basic-detection');
var $Object = Object;
// eslint-disable-next-line es/no-array-isarray -- safe
var isArray = Array.isArray;
// eslint-disable-next-line es/no-object-isextensible -- safe
var isExtensible = $Object.isExtensible;
// eslint-disable-next-line es/no-object-isfrozen -- safe
var isFrozen = $Object.isFrozen;
// eslint-disable-next-line es/no-object-issealed -- safe
var isSealed = $Object.isSealed;
// eslint-disable-next-line es/no-object-freeze -- safe
var freeze = $Object.freeze;
// eslint-disable-next-line es/no-object-seal -- safe
var seal = $Object.seal;
var FROZEN = {};
var SEALED = {};
var IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global;
var InternalWeakMap;
var wrapper = function (init) {
return function WeakMap() {
return init(this, arguments.length ? arguments[0] : undefined);
};
};
// `WeakMap` constructor
// https://tc39.es/ecma262/#sec-weakmap-constructor
var $WeakMap = collection('WeakMap', wrapper, collectionWeak);
var WeakMapPrototype = $WeakMap.prototype;
var nativeSet = uncurryThis(WeakMapPrototype.set);
// Chakra Edge bug: adding frozen arrays to WeakMap unfreeze them
var hasMSEdgeFreezingBug = function () {
return FREEZING && fails(function () {
var frozenArray = freeze([]);
nativeSet(new $WeakMap(), frozenArray, 1);
return !isFrozen(frozenArray);
});
};
// IE11 WeakMap frozen keys fix
// We can't use feature detection because it crash some old IE builds
// https://github.com/zloirock/core-js/issues/485
if (NATIVE_WEAK_MAP) if (IS_IE11) {
InternalWeakMap = collectionWeak.getConstructor(wrapper, 'WeakMap', true);
InternalMetadataModule.enable();
var nativeDelete = uncurryThis(WeakMapPrototype['delete']);
var nativeHas = uncurryThis(WeakMapPrototype.has);
var nativeGet = uncurryThis(WeakMapPrototype.get);
defineBuiltIns(WeakMapPrototype, {
'delete': function (key) {
if (isObject(key) && !isExtensible(key)) {
var state = enforceInternalState(this);
if (!state.frozen) state.frozen = new InternalWeakMap();
return nativeDelete(this, key) || state.frozen['delete'](key);
} return nativeDelete(this, key);
},
has: function has(key) {
if (isObject(key) && !isExtensible(key)) {
var state = enforceInternalState(this);
if (!state.frozen) state.frozen = new InternalWeakMap();
return nativeHas(this, key) || state.frozen.has(key);
} return nativeHas(this, key);
},
get: function get(key) {
if (isObject(key) && !isExtensible(key)) {
var state = enforceInternalState(this);
if (!state.frozen) state.frozen = new InternalWeakMap();
return nativeHas(this, key) ? nativeGet(this, key) : state.frozen.get(key);
} return nativeGet(this, key);
},
set: function set(key, value) {
if (isObject(key) && !isExtensible(key)) {
var state = enforceInternalState(this);
if (!state.frozen) state.frozen = new InternalWeakMap();
nativeHas(this, key) ? nativeSet(this, key, value) : state.frozen.set(key, value);
} else nativeSet(this, key, value);
return this;
}
});
// Chakra Edge frozen keys fix
} else if (hasMSEdgeFreezingBug()) {
defineBuiltIns(WeakMapPrototype, {
set: function set(key, value) {
var arrayIntegrityLevel;
if (isArray(key)) {
if (isFrozen(key)) arrayIntegrityLevel = FROZEN;
else if (isSealed(key)) arrayIntegrityLevel = SEALED;
}
nativeSet(this, key, value);
if (arrayIntegrityLevel == FROZEN) freeze(key);
if (arrayIntegrityLevel == SEALED) seal(key);
return this;
}
});
}
},{"../internals/collection":199,"../internals/collection-weak":198,"../internals/define-built-ins":209,"../internals/fails":235,"../internals/freezing":236,"../internals/function-uncurry-this":245,"../internals/global":251,"../internals/internal-metadata":260,"../internals/internal-state":261,"../internals/is-object":269,"../internals/weak-map-basic-detection":340}],417:[function(_dereq_,module,exports){
// TODO: Remove this module from `core-js@4` since it's replaced to module below
_dereq_('../modules/es.weak-map.constructor');
},{"../modules/es.weak-map.constructor":416}],418:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.asyncDispose` well-known symbol
// https://github.com/tc39/proposal-async-explicit-resource-management
defineWellKnownSymbol('asyncDispose');
},{"../internals/well-known-symbol-define":341}],419:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.dispose` well-known symbol
// https://github.com/tc39/proposal-explicit-resource-management
defineWellKnownSymbol('dispose');
},{"../internals/well-known-symbol-define":341}],420:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var getBuiltIn = _dereq_('../internals/get-built-in');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var Symbol = getBuiltIn('Symbol');
var keyFor = Symbol.keyFor;
var thisSymbolValue = uncurryThis(Symbol.prototype.valueOf);
// `Symbol.isRegistered` method
// https://tc39.es/proposal-symbol-predicates/#sec-symbol-isregistered
$({ target: 'Symbol', stat: true }, {
isRegistered: function isRegistered(value) {
try {
return keyFor(thisSymbolValue(value)) !== undefined;
} catch (error) {
return false;
}
}
});
},{"../internals/export":234,"../internals/function-uncurry-this":245,"../internals/get-built-in":246}],421:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var shared = _dereq_('../internals/shared');
var getBuiltIn = _dereq_('../internals/get-built-in');
var uncurryThis = _dereq_('../internals/function-uncurry-this');
var isSymbol = _dereq_('../internals/is-symbol');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var Symbol = getBuiltIn('Symbol');
var $isWellKnown = Symbol.isWellKnown;
var getOwnPropertyNames = getBuiltIn('Object', 'getOwnPropertyNames');
var thisSymbolValue = uncurryThis(Symbol.prototype.valueOf);
var WellKnownSymbolsStore = shared('wks');
for (var i = 0, symbolKeys = getOwnPropertyNames(Symbol), symbolKeysLength = symbolKeys.length; i < symbolKeysLength; i++) {
// some old engines throws on access to some keys like `arguments` or `caller`
try {
var symbolKey = symbolKeys[i];
if (isSymbol(Symbol[symbolKey])) wellKnownSymbol(symbolKey);
} catch (error) { /* empty */ }
}
// `Symbol.isWellKnown` method
// https://tc39.es/proposal-symbol-predicates/#sec-symbol-iswellknown
// We should patch it for newly added well-known symbols. If it's not required, this module just will not be injected
$({ target: 'Symbol', stat: true, forced: true }, {
isWellKnown: function isWellKnown(value) {
if ($isWellKnown && $isWellKnown(value)) return true;
try {
var symbol = thisSymbolValue(value);
for (var j = 0, keys = getOwnPropertyNames(WellKnownSymbolsStore), keysLength = keys.length; j < keysLength; j++) {
if (WellKnownSymbolsStore[keys[j]] == symbol) return true;
}
} catch (error) { /* empty */ }
return false;
}
});
},{"../internals/export":234,"../internals/function-uncurry-this":245,"../internals/get-built-in":246,"../internals/is-symbol":272,"../internals/shared":318,"../internals/well-known-symbol":343}],422:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.matcher` well-known symbol
// https://github.com/tc39/proposal-pattern-matching
defineWellKnownSymbol('matcher');
},{"../internals/well-known-symbol-define":341}],423:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.metadataKey` well-known symbol
// https://github.com/tc39/proposal-decorator-metadata
defineWellKnownSymbol('metadataKey');
},{"../internals/well-known-symbol-define":341}],424:[function(_dereq_,module,exports){
// TODO: Remove from `core-js@4`
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.metadata` well-known symbol
// https://github.com/tc39/proposal-decorators
defineWellKnownSymbol('metadata');
},{"../internals/well-known-symbol-define":341}],425:[function(_dereq_,module,exports){
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.observable` well-known symbol
// https://github.com/tc39/proposal-observable
defineWellKnownSymbol('observable');
},{"../internals/well-known-symbol-define":341}],426:[function(_dereq_,module,exports){
// TODO: remove from `core-js@4`
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
// `Symbol.patternMatch` well-known symbol
// https://github.com/tc39/proposal-pattern-matching
defineWellKnownSymbol('patternMatch');
},{"../internals/well-known-symbol-define":341}],427:[function(_dereq_,module,exports){
// TODO: remove from `core-js@4`
var defineWellKnownSymbol = _dereq_('../internals/well-known-symbol-define');
defineWellKnownSymbol('replaceAll');
},{"../internals/well-known-symbol-define":341}],428:[function(_dereq_,module,exports){
_dereq_('../modules/es.array.iterator');
var DOMIterables = _dereq_('../internals/dom-iterables');
var global = _dereq_('../internals/global');
var classof = _dereq_('../internals/classof');
var createNonEnumerableProperty = _dereq_('../internals/create-non-enumerable-property');
var Iterators = _dereq_('../internals/iterators');
var wellKnownSymbol = _dereq_('../internals/well-known-symbol');
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
for (var COLLECTION_NAME in DOMIterables) {
var Collection = global[COLLECTION_NAME];
var CollectionPrototype = Collection && Collection.prototype;
if (CollectionPrototype && classof(CollectionPrototype) !== TO_STRING_TAG) {
createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);
}
Iterators[COLLECTION_NAME] = Iterators.Array;
}
},{"../internals/classof":196,"../internals/create-non-enumerable-property":204,"../internals/dom-iterables":216,"../internals/global":251,"../internals/iterators":278,"../internals/well-known-symbol":343,"../modules/es.array.iterator":357}],429:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var global = _dereq_('../internals/global');
var schedulersFix = _dereq_('../internals/schedulers-fix');
var setInterval = schedulersFix(global.setInterval, true);
// Bun / IE9- setInterval additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
$({ global: true, bind: true, forced: global.setInterval !== setInterval }, {
setInterval: setInterval
});
},{"../internals/export":234,"../internals/global":251,"../internals/schedulers-fix":313}],430:[function(_dereq_,module,exports){
var $ = _dereq_('../internals/export');
var global = _dereq_('../internals/global');
var schedulersFix = _dereq_('../internals/schedulers-fix');
var setTimeout = schedulersFix(global.setTimeout, true);
// Bun / IE9- setTimeout additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
$({ global: true, bind: true, forced: global.setTimeout !== setTimeout }, {
setTimeout: setTimeout
});
},{"../internals/export":234,"../internals/global":251,"../internals/schedulers-fix":313}],431:[function(_dereq_,module,exports){
// TODO: Remove this module from `core-js@4` since it's split to modules listed below
_dereq_('../modules/web.set-interval');
_dereq_('../modules/web.set-timeout');
},{"../modules/web.set-interval":429,"../modules/web.set-timeout":430}],432:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/array/from');
module.exports = parent;
},{"../../es/array/from":112}],433:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/array/is-array');
module.exports = parent;
},{"../../es/array/is-array":113}],434:[function(_dereq_,module,exports){
var parent = _dereq_('../../../es/array/virtual/entries');
module.exports = parent;
},{"../../../es/array/virtual/entries":115}],435:[function(_dereq_,module,exports){
var parent = _dereq_('../../../es/array/virtual/for-each');
module.exports = parent;
},{"../../../es/array/virtual/for-each":120}],436:[function(_dereq_,module,exports){
var parent = _dereq_('../../../es/array/virtual/keys');
module.exports = parent;
},{"../../../es/array/virtual/keys":123}],437:[function(_dereq_,module,exports){
var parent = _dereq_('../../../es/array/virtual/values');
module.exports = parent;
},{"../../../es/array/virtual/values":129}],438:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/bind');
module.exports = parent;
},{"../../es/instance/bind":131}],439:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/concat');
module.exports = parent;
},{"../../es/instance/concat":132}],440:[function(_dereq_,module,exports){
_dereq_('../../modules/web.dom-collections.iterator');
var classof = _dereq_('../../internals/classof');
var hasOwn = _dereq_('../../internals/has-own-property');
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/entries');
var ArrayPrototype = Array.prototype;
var DOMIterables = {
DOMTokenList: true,
NodeList: true
};
module.exports = function (it) {
var own = it.entries;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.entries)
|| hasOwn(DOMIterables, classof(it)) ? method : own;
};
},{"../../internals/classof":196,"../../internals/has-own-property":252,"../../internals/object-is-prototype-of":296,"../../modules/web.dom-collections.iterator":428,"../array/virtual/entries":434}],441:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/every');
module.exports = parent;
},{"../../es/instance/every":133}],442:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/filter');
module.exports = parent;
},{"../../es/instance/filter":134}],443:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/find-index');
module.exports = parent;
},{"../../es/instance/find-index":135}],444:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/find');
module.exports = parent;
},{"../../es/instance/find":136}],445:[function(_dereq_,module,exports){
_dereq_('../../modules/web.dom-collections.iterator');
var classof = _dereq_('../../internals/classof');
var hasOwn = _dereq_('../../internals/has-own-property');
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/for-each');
var ArrayPrototype = Array.prototype;
var DOMIterables = {
DOMTokenList: true,
NodeList: true
};
module.exports = function (it) {
var own = it.forEach;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.forEach)
|| hasOwn(DOMIterables, classof(it)) ? method : own;
};
},{"../../internals/classof":196,"../../internals/has-own-property":252,"../../internals/object-is-prototype-of":296,"../../modules/web.dom-collections.iterator":428,"../array/virtual/for-each":435}],446:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/includes');
module.exports = parent;
},{"../../es/instance/includes":137}],447:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/index-of');
module.exports = parent;
},{"../../es/instance/index-of":138}],448:[function(_dereq_,module,exports){
_dereq_('../../modules/web.dom-collections.iterator');
var classof = _dereq_('../../internals/classof');
var hasOwn = _dereq_('../../internals/has-own-property');
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/keys');
var ArrayPrototype = Array.prototype;
var DOMIterables = {
DOMTokenList: true,
NodeList: true
};
module.exports = function (it) {
var own = it.keys;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.keys)
|| hasOwn(DOMIterables, classof(it)) ? method : own;
};
},{"../../internals/classof":196,"../../internals/has-own-property":252,"../../internals/object-is-prototype-of":296,"../../modules/web.dom-collections.iterator":428,"../array/virtual/keys":436}],449:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/map');
module.exports = parent;
},{"../../es/instance/map":139}],450:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/reduce');
module.exports = parent;
},{"../../es/instance/reduce":140}],451:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/slice');
module.exports = parent;
},{"../../es/instance/slice":141}],452:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/sort');
module.exports = parent;
},{"../../es/instance/sort":142}],453:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/splice');
module.exports = parent;
},{"../../es/instance/splice":143}],454:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/instance/starts-with');
module.exports = parent;
},{"../../es/instance/starts-with":144}],455:[function(_dereq_,module,exports){
_dereq_('../../modules/web.dom-collections.iterator');
var classof = _dereq_('../../internals/classof');
var hasOwn = _dereq_('../../internals/has-own-property');
var isPrototypeOf = _dereq_('../../internals/object-is-prototype-of');
var method = _dereq_('../array/virtual/values');
var ArrayPrototype = Array.prototype;
var DOMIterables = {
DOMTokenList: true,
NodeList: true
};
module.exports = function (it) {
var own = it.values;
return it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.values)
|| hasOwn(DOMIterables, classof(it)) ? method : own;
};
},{"../../internals/classof":196,"../../internals/has-own-property":252,"../../internals/object-is-prototype-of":296,"../../modules/web.dom-collections.iterator":428,"../array/virtual/values":437}],456:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/json/stringify');
module.exports = parent;
},{"../../es/json/stringify":145}],457:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/map');
_dereq_('../../modules/web.dom-collections.iterator');
module.exports = parent;
},{"../../es/map":146,"../../modules/web.dom-collections.iterator":428}],458:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/number/is-integer');
module.exports = parent;
},{"../../es/number/is-integer":147}],459:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/object/assign');
module.exports = parent;
},{"../../es/object/assign":148}],460:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/object/create');
module.exports = parent;
},{"../../es/object/create":149}],461:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/object/define-property');
module.exports = parent;
},{"../../es/object/define-property":150}],462:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/object/entries');
module.exports = parent;
},{"../../es/object/entries":151}],463:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/object/freeze');
module.exports = parent;
},{"../../es/object/freeze":152}],464:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/object/get-own-property-descriptor');
module.exports = parent;
},{"../../es/object/get-own-property-descriptor":153}],465:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/object/get-prototype-of');
module.exports = parent;
},{"../../es/object/get-prototype-of":154}],466:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/object/keys');
module.exports = parent;
},{"../../es/object/keys":155}],467:[function(_dereq_,module,exports){
var parent = _dereq_('../es/parse-int');
module.exports = parent;
},{"../es/parse-int":156}],468:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/promise');
_dereq_('../../modules/web.dom-collections.iterator');
module.exports = parent;
},{"../../es/promise":157,"../../modules/web.dom-collections.iterator":428}],469:[function(_dereq_,module,exports){
_dereq_('../modules/web.timers');
var path = _dereq_('../internals/path');
module.exports = path.setInterval;
},{"../internals/path":305,"../modules/web.timers":431}],470:[function(_dereq_,module,exports){
_dereq_('../modules/web.timers');
var path = _dereq_('../internals/path');
module.exports = path.setTimeout;
},{"../internals/path":305,"../modules/web.timers":431}],471:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/set');
_dereq_('../../modules/web.dom-collections.iterator');
module.exports = parent;
},{"../../es/set":158,"../../modules/web.dom-collections.iterator":428}],472:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/symbol');
_dereq_('../../modules/web.dom-collections.iterator');
module.exports = parent;
},{"../../es/symbol":161,"../../modules/web.dom-collections.iterator":428}],473:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/symbol/iterator');
_dereq_('../../modules/web.dom-collections.iterator');
module.exports = parent;
},{"../../es/symbol/iterator":162,"../../modules/web.dom-collections.iterator":428}],474:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/symbol/to-primitive');
module.exports = parent;
},{"../../es/symbol/to-primitive":163}],475:[function(_dereq_,module,exports){
var parent = _dereq_('../../es/weak-map');
_dereq_('../../modules/web.dom-collections.iterator');
module.exports = parent;
},{"../../es/weak-map":164,"../../modules/web.dom-collections.iterator":428}],476:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
var t;
// Skip reset of nRounds has been set before and key did not change
if (this._nRounds && this._keyPriorReset === this._key) {
return;
}
// Shortcuts
var key = this._keyPriorReset = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6;
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":477,"./core":478,"./enc-base64":479,"./evpkdf":481,"./md5":483}],477:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./evpkdf"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./evpkdf"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
var block;
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
var modeCreator;
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
if (this._mode && this._mode.__creator == modeCreator) {
this._mode.init(this, iv && iv.words);
} else {
this._mode = modeCreator.call(mode, this, iv && iv.words);
this._mode.__creator = modeCreator;
}
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
var finalProcessedBlocks;
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
var wordArray;
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
var salt;
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt, hasher) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
if (!hasher) {
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
} else {
var key = EvpKDF.create({ keySize: keySize + ivSize, hasher: hasher }).compute(password, salt);
}
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, cfg.salt, cfg.hasher);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt, cfg.hasher);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":478,"./evpkdf":481}],478:[function(_dereq_,module,exports){
(function (global){(function (){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/*globals window, global, require*/
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
var crypto;
// Native crypto from window (Browser)
if (typeof window !== 'undefined' && window.crypto) {
crypto = window.crypto;
}
// Native crypto in web worker (Browser)
if (typeof self !== 'undefined' && self.crypto) {
crypto = self.crypto;
}
// Native crypto from worker
if (typeof globalThis !== 'undefined' && globalThis.crypto) {
crypto = globalThis.crypto;
}
// Native (experimental IE 11) crypto from window (Browser)
if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
crypto = window.msCrypto;
}
// Native crypto from global (NodeJS)
if (!crypto && typeof global !== 'undefined' && global.crypto) {
crypto = global.crypto;
}
// Native crypto import via require (NodeJS)
if (!crypto && typeof _dereq_ === 'function') {
try {
crypto = _dereq_('crypto');
} catch (err) {}
}
/*
* Cryptographically secure pseudorandom number generator
*
* As Math.random() is cryptographically not safe to use
*/
var cryptoSecureRandomInt = function () {
if (crypto) {
// Use getRandomValues method (Browser)
if (typeof crypto.getRandomValues === 'function') {
try {
return crypto.getRandomValues(new Uint32Array(1))[0];
} catch (err) {}
}
// Use randomBytes method (NodeJS)
if (typeof crypto.randomBytes === 'function') {
try {
return crypto.randomBytes(4).readInt32LE();
} catch (err) {}
}
}
throw new Error('Native crypto module could not be used to get secure random number.');
};
/*
* Local polyfill of Object.create
*/
var create = Object.create || (function () {
function F() {}
return function (obj) {
var subtype;
F.prototype = obj;
subtype = new F();
F.prototype = null;
return subtype;
};
}());
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
var subtype = create(this);
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var j = 0; j < thatSigBytes; j += 4) {
thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
for (var i = 0; i < nBytes; i += 4) {
words.push(cryptoSecureRandomInt());
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
var processedWords;
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"crypto":undefined}],479:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
var reverseMap = this._reverseMap;
if (!reverseMap) {
reverseMap = this._reverseMap = [];
for (var j = 0; j < map.length; j++) {
reverseMap[map.charCodeAt(j)] = j;
}
}
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex !== -1) {
base64StrLength = paddingIndex;
}
}
// Convert
return parseLoop(base64Str, base64StrLength, reverseMap);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
function parseLoop(base64Str, base64StrLength, reverseMap) {
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
var bitsCombined = bits1 | bits2;
words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
}
}());
return CryptoJS.enc.Base64;
}));
},{"./core":478}],480:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS.enc.Utf8;
}));
},{"./core":478}],481:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
var block;
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":478,"./hmac":482,"./sha1":484}],482:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":478}],483:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":478}],484:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":478}],485:[function(_dereq_,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen for `error` events here.
emitter.addEventListener(name, function wrapListener(arg) {
// IE does not have builtin `{ once: true }` support so we
// have to do it manually.
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
},{}],486:[function(_dereq_,module,exports){
'use strict';
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
Object.defineProperty(exports, '__esModule', {
value: true
});
function promisifyRequest(request) {
return new Promise(function (resolve, reject) {
// @ts-ignore - file size hacks
request.oncomplete = request.onsuccess = function () {
return resolve(request.result);
}; // @ts-ignore - file size hacks
request.onabort = request.onerror = function () {
return reject(request.error);
};
});
}
function createStore(dbName, storeName) {
var request = indexedDB.open(dbName);
request.onupgradeneeded = function () {
return request.result.createObjectStore(storeName);
};
var dbp = promisifyRequest(request);
return function (txMode, callback) {
return dbp.then(function (db) {
return callback(db.transaction(storeName, txMode).objectStore(storeName));
});
};
}
var defaultGetStoreFunc;
function defaultGetStore() {
if (!defaultGetStoreFunc) {
defaultGetStoreFunc = createStore('keyval-store', 'keyval');
}
return defaultGetStoreFunc;
}
/**
* Get a value by its key.
*
* @param key
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function get(key) {
var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
return customStore('readonly', function (store) {
return promisifyRequest(store.get(key));
});
}
/**
* Set a value with a key.
*
* @param key
* @param value
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function set(key, value) {
var customStore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultGetStore();
return customStore('readwrite', function (store) {
store.put(value, key);
return promisifyRequest(store.transaction);
});
}
/**
* Set multiple values at once. This is faster than calling set() multiple times.
* It's also atomic – if one of the pairs can't be added, none will be added.
*
* @param entries Array of entries, where each entry is an array of `[key, value]`.
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function setMany(entries) {
var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
return customStore('readwrite', function (store) {
entries.forEach(function (entry) {
return store.put(entry[1], entry[0]);
});
return promisifyRequest(store.transaction);
});
}
/**
* Get multiple values by their keys
*
* @param keys
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function getMany(keys) {
var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
return customStore('readonly', function (store) {
return Promise.all(keys.map(function (key) {
return promisifyRequest(store.get(key));
}));
});
}
/**
* Update a value. This lets you see the old value and update it as an atomic operation.
*
* @param key
* @param updater A callback that takes the old value and returns a new value.
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function update(key, updater) {
var customStore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultGetStore();
return customStore('readwrite', function (store) {
return (// Need to create the promise manually.
// If I try to chain promises, the transaction closes in browsers
// that use a promise polyfill (IE10/11).
new Promise(function (resolve, reject) {
store.get(key).onsuccess = function () {
try {
store.put(updater(this.result), key);
resolve(promisifyRequest(store.transaction));
} catch (err) {
reject(err);
}
};
})
);
});
}
/**
* Delete a particular key from the store.
*
* @param key
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function del(key) {
var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
return customStore('readwrite', function (store) {
store.delete(key);
return promisifyRequest(store.transaction);
});
}
/**
* Delete multiple keys at once.
*
* @param keys List of keys to delete.
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function delMany(keys) {
var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
return customStore('readwrite', function (store) {
keys.forEach(function (key) {
return store.delete(key);
});
return promisifyRequest(store.transaction);
});
}
/**
* Clear all values in the store.
*
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function clear() {
var customStore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultGetStore();
return customStore('readwrite', function (store) {
store.clear();
return promisifyRequest(store.transaction);
});
}
function eachCursor(store, callback) {
store.openCursor().onsuccess = function () {
if (!this.result) return;
callback(this.result);
this.result.continue();
};
return promisifyRequest(store.transaction);
}
/**
* Get all keys in the store.
*
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function keys() {
var customStore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultGetStore();
return customStore('readonly', function (store) {
// Fast path for modern browsers
if (store.getAllKeys) {
return promisifyRequest(store.getAllKeys());
}
var items = [];
return eachCursor(store, function (cursor) {
return items.push(cursor.key);
}).then(function () {
return items;
});
});
}
/**
* Get all values in the store.
*
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function values() {
var customStore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultGetStore();
return customStore('readonly', function (store) {
// Fast path for modern browsers
if (store.getAll) {
return promisifyRequest(store.getAll());
}
var items = [];
return eachCursor(store, function (cursor) {
return items.push(cursor.value);
}).then(function () {
return items;
});
});
}
/**
* Get all entries in the store. Each entry is an array of `[key, value]`.
*
* @param customStore Method to get a custom store. Use with caution (see the docs).
*/
function entries() {
var customStore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultGetStore();
return customStore('readonly', function (store) {
// Fast path for modern browsers
// (although, hopefully we'll get a simpler path some day)
if (store.getAll && store.getAllKeys) {
return Promise.all([promisifyRequest(store.getAllKeys()), promisifyRequest(store.getAll())]).then(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
keys = _ref2[0],
values = _ref2[1];
return keys.map(function (key, i) {
return [key, values[i]];
});
});
}
var items = [];
return customStore('readonly', function (store) {
return eachCursor(store, function (cursor) {
return items.push([cursor.key, cursor.value]);
}).then(function () {
return items;
});
});
});
}
exports.clear = clear;
exports.createStore = createStore;
exports.del = del;
exports.delMany = delMany;
exports.entries = entries;
exports.get = get;
exports.getMany = getMany;
exports.keys = keys;
exports.promisifyRequest = promisifyRequest;
exports.set = set;
exports.setMany = setMany;
exports.update = update;
exports.values = values;
},{}],487:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "MAX", {
enumerable: true,
get: function () {
return _max.default;
}
});
Object.defineProperty(exports, "NIL", {
enumerable: true,
get: function () {
return _nil.default;
}
});
Object.defineProperty(exports, "parse", {
enumerable: true,
get: function () {
return _parse.default;
}
});
Object.defineProperty(exports, "stringify", {
enumerable: true,
get: function () {
return _stringify.default;
}
});
Object.defineProperty(exports, "v1", {
enumerable: true,
get: function () {
return _v.default;
}
});
Object.defineProperty(exports, "v1ToV6", {
enumerable: true,
get: function () {
return _v1ToV.default;
}
});
Object.defineProperty(exports, "v3", {
enumerable: true,
get: function () {
return _v2.default;
}
});
Object.defineProperty(exports, "v4", {
enumerable: true,
get: function () {
return _v3.default;
}
});
Object.defineProperty(exports, "v5", {
enumerable: true,
get: function () {
return _v4.default;
}
});
Object.defineProperty(exports, "v6", {
enumerable: true,
get: function () {
return _v5.default;
}
});
Object.defineProperty(exports, "v6ToV1", {
enumerable: true,
get: function () {
return _v6ToV.default;
}
});
Object.defineProperty(exports, "v7", {
enumerable: true,
get: function () {
return _v6.default;
}
});
Object.defineProperty(exports, "validate", {
enumerable: true,
get: function () {
return _validate.default;
}
});
Object.defineProperty(exports, "version", {
enumerable: true,
get: function () {
return _version.default;
}
});
var _max = _interopRequireDefault(_dereq_("./max.js"));
var _nil = _interopRequireDefault(_dereq_("./nil.js"));
var _parse = _interopRequireDefault(_dereq_("./parse.js"));
var _stringify = _interopRequireDefault(_dereq_("./stringify.js"));
var _v = _interopRequireDefault(_dereq_("./v1.js"));
var _v1ToV = _interopRequireDefault(_dereq_("./v1ToV6.js"));
var _v2 = _interopRequireDefault(_dereq_("./v3.js"));
var _v3 = _interopRequireDefault(_dereq_("./v4.js"));
var _v4 = _interopRequireDefault(_dereq_("./v5.js"));
var _v5 = _interopRequireDefault(_dereq_("./v6.js"));
var _v6ToV = _interopRequireDefault(_dereq_("./v6ToV1.js"));
var _v6 = _interopRequireDefault(_dereq_("./v7.js"));
var _validate = _interopRequireDefault(_dereq_("./validate.js"));
var _version = _interopRequireDefault(_dereq_("./version.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
},{"./max.js":488,"./nil.js":491,"./parse.js":492,"./stringify.js":496,"./v1.js":497,"./v1ToV6.js":498,"./v3.js":499,"./v4.js":501,"./v5.js":502,"./v6.js":503,"./v6ToV1.js":504,"./v7.js":505,"./validate.js":506,"./version.js":507}],488:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = exports.default = 'ffffffff-ffff-ffff-ffff-ffffffffffff';
},{}],489:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/*
* Browser-compatible JavaScript MD5
*
* Modification of JavaScript MD5
* https://github.com/blueimp/JavaScript-MD5
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
function md5(bytes) {
if (typeof bytes === 'string') {
const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
bytes = new Uint8Array(msg.length);
for (let i = 0; i < msg.length; ++i) {
bytes[i] = msg.charCodeAt(i);
}
}
return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
}
/*
* Convert an array of little-endian words to an array of bytes
*/
function md5ToHexEncodedArray(input) {
const output = [];
const length32 = input.length * 32;
const hexTab = '0123456789abcdef';
for (let i = 0; i < length32; i += 8) {
const x = input[i >> 5] >>> i % 32 & 0xff;
const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
output.push(hex);
}
return output;
}
/**
* Calculate output length with padding and bit length
*/
function getOutputLength(inputLength8) {
return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function wordsToMd5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << len % 32;
x[getOutputLength(len) - 1] = len;
let a = 1732584193;
let b = -271733879;
let c = -1732584194;
let d = 271733878;
for (let i = 0; i < x.length; i += 16) {
const olda = a;
const oldb = b;
const oldc = c;
const oldd = d;
a = md5ff(a, b, c, d, x[i], 7, -680876936);
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5gg(b, c, d, a, x[i], 20, -373897302);
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5hh(d, a, b, c, x[i], 11, -358537222);
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5ii(a, b, c, d, x[i], 6, -198630844);
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safeAdd(a, olda);
b = safeAdd(b, oldb);
c = safeAdd(c, oldc);
d = safeAdd(d, oldd);
}
return [a, b, c, d];
}
/*
* Convert an array bytes to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function bytesToWords(input) {
if (input.length === 0) {
return [];
}
const length8 = input.length * 8;
const output = new Uint32Array(getOutputLength(length8));
for (let i = 0; i < length8; i += 8) {
output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
}
return output;
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safeAdd(x, y) {
const lsw = (x & 0xffff) + (y & 0xffff);
const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return msw << 16 | lsw & 0xffff;
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bitRotateLeft(num, cnt) {
return num << cnt | num >>> 32 - cnt;
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5cmn(q, a, b, x, s, t) {
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
}
function md5ff(a, b, c, d, x, s, t) {
return md5cmn(b & c | ~b & d, a, b, x, s, t);
}
function md5gg(a, b, c, d, x, s, t) {
return md5cmn(b & d | c & ~d, a, b, x, s, t);
}
function md5hh(a, b, c, d, x, s, t) {
return md5cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5ii(a, b, c, d, x, s, t) {
return md5cmn(c ^ (b | ~d), a, b, x, s, t);
}
var _default = exports.default = md5;
},{}],490:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
var _default = exports.default = {
randomUUID
};
},{}],491:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = exports.default = '00000000-0000-0000-0000-000000000000';
},{}],492:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _validate = _interopRequireDefault(_dereq_("./validate.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function parse(uuid) {
if (!(0, _validate.default)(uuid)) {
throw TypeError('Invalid UUID');
}
let v;
const arr = new Uint8Array(16);
// Parse ########-....-....-....-............
arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
arr[1] = v >>> 16 & 0xff;
arr[2] = v >>> 8 & 0xff;
arr[3] = v & 0xff;
// Parse ........-####-....-....-............
arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
arr[5] = v & 0xff;
// Parse ........-....-####-....-............
arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
arr[7] = v & 0xff;
// Parse ........-....-....-####-............
arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
arr[9] = v & 0xff;
// Parse ........-....-....-....-############
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
arr[11] = v / 0x100000000 & 0xff;
arr[12] = v >>> 24 & 0xff;
arr[13] = v >>> 16 & 0xff;
arr[14] = v >>> 8 & 0xff;
arr[15] = v & 0xff;
return arr;
}
var _default = exports.default = parse;
},{"./validate.js":506}],493:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = exports.default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
},{}],494:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rng;
// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
let getRandomValues;
const rnds8 = new Uint8Array(16);
function rng() {
// lazy load so that environments that need to polyfill have a chance to do so
if (!getRandomValues) {
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
if (!getRandomValues) {
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
}
}
return getRandomValues(rnds8);
}
},{}],495:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
// Adapted from Chris Veness' SHA1 code at
// http://www.movable-type.co.uk/scripts/sha1.html
function f(s, x, y, z) {
switch (s) {
case 0:
return x & y ^ ~x & z;
case 1:
return x ^ y ^ z;
case 2:
return x & y ^ x & z ^ y & z;
case 3:
return x ^ y ^ z;
}
}
function ROTL(x, n) {
return x << n | x >>> 32 - n;
}
function sha1(bytes) {
const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
if (typeof bytes === 'string') {
const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
bytes = [];
for (let i = 0; i < msg.length; ++i) {
bytes.push(msg.charCodeAt(i));
}
} else if (!Array.isArray(bytes)) {
// Convert Array-like to Array
bytes = Array.prototype.slice.call(bytes);
}
bytes.push(0x80);
const l = bytes.length / 4 + 2;
const N = Math.ceil(l / 16);
const M = new Array(N);
for (let i = 0; i < N; ++i) {
const arr = new Uint32Array(16);
for (let j = 0; j < 16; ++j) {
arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];
}
M[i] = arr;
}
M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
M[N - 1][14] = Math.floor(M[N - 1][14]);
M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
for (let i = 0; i < N; ++i) {
const W = new Uint32Array(80);
for (let t = 0; t < 16; ++t) {
W[t] = M[i][t];
}
for (let t = 16; t < 80; ++t) {
W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
}
let a = H[0];
let b = H[1];
let c = H[2];
let d = H[3];
let e = H[4];
for (let t = 0; t < 80; ++t) {
const s = Math.floor(t / 20);
const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
e = d;
d = c;
c = ROTL(b, 30) >>> 0;
b = a;
a = T;
}
H[0] = H[0] + a >>> 0;
H[1] = H[1] + b >>> 0;
H[2] = H[2] + c >>> 0;
H[3] = H[3] + d >>> 0;
H[4] = H[4] + e >>> 0;
}
return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
}
var _default = exports.default = sha1;
},{}],496:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.unsafeStringify = unsafeStringify;
var _validate = _interopRequireDefault(_dereq_("./validate.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 0x100).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
//
// Note to future-self: No, you can't remove the `toLowerCase()` call.
// REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}
function stringify(arr, offset = 0) {
const uuid = unsafeStringify(arr, offset);
// Consistency check for valid UUID. If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if (!(0, _validate.default)(uuid)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
var _default = exports.default = stringify;
},{"./validate.js":506}],497:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rng = _interopRequireDefault(_dereq_("./rng.js"));
var _stringify = _dereq_("./stringify.js");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
let _nodeId;
let _clockseq;
// Previous uuid creation time
let _lastMSecs = 0;
let _lastNSecs = 0;
// See https://github.com/uuidjs/uuid for API details
function v1(options, buf, offset) {
let i = buf && offset || 0;
const b = buf || new Array(16);
options = options || {};
let node = options.node;
let clockseq = options.clockseq;
// v1 only: Use cached `node` and `clockseq` values
if (!options._v6) {
if (!node) {
node = _nodeId;
}
if (clockseq == null) {
clockseq = _clockseq;
}
}
// Handle cases where we need entropy. We do this lazily to minimize issues
// related to insufficient system entropy. See #189
if (node == null || clockseq == null) {
const seedBytes = options.random || (options.rng || _rng.default)();
// Randomize node
if (node == null) {
node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
// v1 only: cache node value for reuse
if (!_nodeId && !options._v6) {
// per RFC4122 4.5: Set MAC multicast bit (v1 only)
node[0] |= 0x01; // Set multicast bit
_nodeId = node;
}
}
// Randomize clockseq
if (clockseq == null) {
// Per 4.2.2, randomize (14 bit) clockseq
clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
if (_clockseq === undefined && !options._v6) {
_clockseq = clockseq;
}
}
}
// v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is
// handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
let msecs = options.msecs !== undefined ? options.msecs : Date.now();
// Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
// Time since last uuid creation (in msecs)
const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000;
// Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq === undefined) {
clockseq = clockseq + 1 & 0x3fff;
}
// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
nsecs = 0;
}
// Per 4.2.1.2 Throw error if too many uuids are requested
if (nsecs >= 10000) {
throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq;
// Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000;
// `time_low`
const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
b[i++] = tl >>> 24 & 0xff;
b[i++] = tl >>> 16 & 0xff;
b[i++] = tl >>> 8 & 0xff;
b[i++] = tl & 0xff;
// `time_mid`
const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff;
// `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff;
// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80;
// `clock_seq_low`
b[i++] = clockseq & 0xff;
// `node`
for (let n = 0; n < 6; ++n) {
b[i + n] = node[n];
}
return buf || (0, _stringify.unsafeStringify)(b);
}
var _default = exports.default = v1;
},{"./rng.js":494,"./stringify.js":496}],498:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = v1ToV6;
var _parse = _interopRequireDefault(_dereq_("./parse.js"));
var _stringify = _dereq_("./stringify.js");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* Convert a v1 UUID to a v6 UUID
*
* @param {string|Uint8Array} uuid - The v1 UUID to convert to v6
* @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg
* (string or Uint8Array)
*/
function v1ToV6(uuid) {
const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid;
const v6Bytes = _v1ToV6(v1Bytes);
return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes;
}
// Do the field transformation needed for v1 -> v6
function _v1ToV6(v1Bytes, randomize = false) {
return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]);
}
},{"./parse.js":492,"./stringify.js":496}],499:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _v = _interopRequireDefault(_dereq_("./v35.js"));
var _md = _interopRequireDefault(_dereq_("./md5.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const v3 = (0, _v.default)('v3', 0x30, _md.default);
var _default = exports.default = v3;
},{"./md5.js":489,"./v35.js":500}],500:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.URL = exports.DNS = void 0;
exports.default = v35;
var _stringify = _dereq_("./stringify.js");
var _parse = _interopRequireDefault(_dereq_("./parse.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function stringToBytes(str) {
str = unescape(encodeURIComponent(str)); // UTF8 escape
const bytes = [];
for (let i = 0; i < str.length; ++i) {
bytes.push(str.charCodeAt(i));
}
return bytes;
}
const DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
const URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
function v35(name, version, hashfunc) {
function generateUUID(value, namespace, buf, offset) {
var _namespace;
if (typeof value === 'string') {
value = stringToBytes(value);
}
if (typeof namespace === 'string') {
namespace = (0, _parse.default)(namespace);
}
if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
}
// Compute hash of namespace and value, Per 4.3
// Future: Use spread syntax when supported on all platforms, e.g. `bytes =
// hashfunc([...namespace, ... value])`
let bytes = new Uint8Array(16 + value.length);
bytes.set(namespace);
bytes.set(value, namespace.length);
bytes = hashfunc(bytes);
bytes[6] = bytes[6] & 0x0f | version;
bytes[8] = bytes[8] & 0x3f | 0x80;
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = bytes[i];
}
return buf;
}
return (0, _stringify.unsafeStringify)(bytes);
}
// Function#name is not settable on some platforms (#270)
try {
generateUUID.name = name;
} catch (err) {}
// For CommonJS default export support
generateUUID.DNS = DNS;
generateUUID.URL = URL;
return generateUUID;
}
},{"./parse.js":492,"./stringify.js":496}],501:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _native = _interopRequireDefault(_dereq_("./native.js"));
var _rng = _interopRequireDefault(_dereq_("./rng.js"));
var _stringify = _dereq_("./stringify.js");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function v4(options, buf, offset) {
if (_native.default.randomUUID && !buf && !options) {
return _native.default.randomUUID();
}
options = options || {};
const rnds = options.random || (options.rng || _rng.default)();
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80;
// Copy bytes to buffer, if provided
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return (0, _stringify.unsafeStringify)(rnds);
}
var _default = exports.default = v4;
},{"./native.js":490,"./rng.js":494,"./stringify.js":496}],502:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _v = _interopRequireDefault(_dereq_("./v35.js"));
var _sha = _interopRequireDefault(_dereq_("./sha1.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const v5 = (0, _v.default)('v5', 0x50, _sha.default);
var _default = exports.default = v5;
},{"./sha1.js":495,"./v35.js":500}],503:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = v6;
var _stringify = _dereq_("./stringify.js");
var _v = _interopRequireDefault(_dereq_("./v1.js"));
var _v1ToV = _interopRequireDefault(_dereq_("./v1ToV6.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
*
* @param {object} options
* @param {Uint8Array=} buf
* @param {number=} offset
* @returns
*/
function v6(options = {}, buf, offset = 0) {
// v6 is v1 with different field layout, so we start with a v1 UUID, albeit
// with slightly different behavior around how the clock_seq and node fields
// are randomized, which is why we call v1 with _v6: true.
let bytes = (0, _v.default)({
...options,
_v6: true
}, new Uint8Array(16));
// Reorder the fields to v6 layout.
bytes = (0, _v1ToV.default)(bytes);
// Return as a byte array if requested
if (buf) {
for (let i = 0; i < 16; i++) {
buf[offset + i] = bytes[i];
}
return buf;
}
return (0, _stringify.unsafeStringify)(bytes);
}
},{"./stringify.js":496,"./v1.js":497,"./v1ToV6.js":498}],504:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = v6ToV1;
var _parse = _interopRequireDefault(_dereq_("./parse.js"));
var _stringify = _dereq_("./stringify.js");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* Convert a v6 UUID to a v1 UUID
*
* @param {string|Uint8Array} uuid - The v6 UUID to convert to v6
* @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg
* (string or Uint8Array)
*/
function v6ToV1(uuid) {
const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid;
const v1Bytes = _v6ToV1(v6Bytes);
return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes;
}
// Do the field transformation needed for v6 -> v1
function _v6ToV1(v6Bytes) {
return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]);
}
},{"./parse.js":492,"./stringify.js":496}],505:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rng = _interopRequireDefault(_dereq_("./rng.js"));
var _stringify = _dereq_("./stringify.js");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* UUID V7 - Unix Epoch time-based UUID
*
* The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This
* implementation of V7 is based on the accepted, though not yet approved,
* revisions.
*
* RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique
* IDentifiers (UUIDs)
*
* Sample V7 value:
* https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value
*
* Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref:
* https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1
*
* 0 1 2 3 0 1 2 3 4 5 6
* 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | unix_ts_ms |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | unix_ts_ms | ver | seq_hi |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |var| seq_low | rand |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | rand |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit
* seq_low, and randomly initialized upon timestamp change. 31 bit counter size
* was selected as any bitwise operations in node are done as _signed_ 32 bit
* ints. we exclude the sign bit.
*/
let _seqLow = null;
let _seqHigh = null;
let _msecs = 0;
function v7(options, buf, offset) {
options = options || {};
// initialize buffer and pointer
let i = buf && offset || 0;
const b = buf || new Uint8Array(16);
// rnds is Uint8Array(16) filled with random bytes
const rnds = options.random || (options.rng || _rng.default)();
// milliseconds since unix epoch, 1970-01-01 00:00
const msecs = options.msecs !== undefined ? options.msecs : Date.now();
// seq is user provided 31 bit counter
let seq = options.seq !== undefined ? options.seq : null;
// initialize local seq high/low parts
let seqHigh = _seqHigh;
let seqLow = _seqLow;
// check if clock has advanced and user has not provided msecs
if (msecs > _msecs && options.msecs === undefined) {
_msecs = msecs;
// unless user provided seq, reset seq parts
if (seq !== null) {
seqHigh = null;
seqLow = null;
}
}
// if we have a user provided seq
if (seq !== null) {
// trim provided seq to 31 bits of value, avoiding overflow
if (seq > 0x7fffffff) {
seq = 0x7fffffff;
}
// split provided seq into high/low parts
seqHigh = seq >>> 19 & 0xfff;
seqLow = seq & 0x7ffff;
}
// randomly initialize seq
if (seqHigh === null || seqLow === null) {
seqHigh = rnds[6] & 0x7f;
seqHigh = seqHigh << 8 | rnds[7];
seqLow = rnds[8] & 0x3f; // pad for var
seqLow = seqLow << 8 | rnds[9];
seqLow = seqLow << 5 | rnds[10] >>> 3;
}
// increment seq if within msecs window
if (msecs + 10000 > _msecs && seq === null) {
if (++seqLow > 0x7ffff) {
seqLow = 0;
if (++seqHigh > 0xfff) {
seqHigh = 0;
// increment internal _msecs. this allows us to continue incrementing
// while staying monotonic. Note, once we hit 10k milliseconds beyond system
// clock, we will reset breaking monotonicity (after (2^31)*10000 generations)
_msecs++;
}
}
} else {
// resetting; we have advanced more than
// 10k milliseconds beyond system clock
_msecs = msecs;
}
_seqHigh = seqHigh;
_seqLow = seqLow;
// [bytes 0-5] 48 bits of local timestamp
b[i++] = _msecs / 0x10000000000 & 0xff;
b[i++] = _msecs / 0x100000000 & 0xff;
b[i++] = _msecs / 0x1000000 & 0xff;
b[i++] = _msecs / 0x10000 & 0xff;
b[i++] = _msecs / 0x100 & 0xff;
b[i++] = _msecs & 0xff;
// [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi
b[i++] = seqHigh >>> 4 & 0x0f | 0x70;
// [byte 7] remaining 8 bits of seq_hi
b[i++] = seqHigh & 0xff;
// [byte 8] - variant (2 bits), first 6 bits seq_low
b[i++] = seqLow >>> 13 & 0x3f | 0x80;
// [byte 9] 8 bits seq_low
b[i++] = seqLow >>> 5 & 0xff;
// [byte 10] remaining 5 bits seq_low, 3 bits random
b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07;
// [bytes 11-15] always random
b[i++] = rnds[11];
b[i++] = rnds[12];
b[i++] = rnds[13];
b[i++] = rnds[14];
b[i++] = rnds[15];
return buf || (0, _stringify.unsafeStringify)(b);
}
var _default = exports.default = v7;
},{"./rng.js":494,"./stringify.js":496}],506:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _regex = _interopRequireDefault(_dereq_("./regex.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function validate(uuid) {
return typeof uuid === 'string' && _regex.default.test(uuid);
}
var _default = exports.default = validate;
},{"./regex.js":493}],507:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _validate = _interopRequireDefault(_dereq_("./validate.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function version(uuid) {
if (!(0, _validate.default)(uuid)) {
throw TypeError('Invalid UUID');
}
return parseInt(uuid.slice(14, 15), 16);
}
var _default = exports.default = version;
},{"./validate.js":506}],508:[function(_dereq_,module,exports){
'use strict';
module.exports = function () {
throw new Error(
'ws does not work in the browser. Browser clients must use the native ' +
'WebSocket object'
);
};
},{}]},{},[20])(20)
});