mongodb-stitch
Version:
[](https://gitter.im/mongodb/stitch?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
1,475 lines (1,204 loc) • 470 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("stitch", [], factory);
else if(typeof exports === 'object')
exports["stitch"] = factory();
else
root["stitch"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 15);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.uriEncodeObject = exports.serviceResponse = undefined;
var _Base = __webpack_require__(12);
var base64 = _interopRequireWildcard(_Base);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* @namespace util
* @private
*/
/**
* Utility method for executing a service action as a function call.
*
* @memberof util
* @param {Object} service the service to execute the action on
* @param {String} action the service action to execute
* @param {Array} args the arguments to supply to the service action invocation
* @returns {Promise} the API response from the executed service action
*/
function serviceResponse(service, _ref) {
var _ref$serviceName = _ref.serviceName,
serviceName = _ref$serviceName === undefined ? service.serviceName : _ref$serviceName,
action = _ref.action,
args = _ref.args;
var client = service.client;
if (!client) {
throw new Error('Service has no client');
}
return client.executeServiceFunction(serviceName, action, args);
}
/**
* Utility function to encode a JSON object into a valid string that can be
* inserted in a URI. The object is first stringified, then encoded in base64,
* and finally encoded via the builtin encodeURIComponent function.
*
* @memberof util
* @param {Object} obj The object to encode
* @returns {String} The encoded object
*/
function uriEncodeObject(obj) {
return encodeURIComponent(base64.btoa(JSON.stringify(obj)));
}
exports.serviceResponse = serviceResponse;
exports.uriEncodeObject = uriEncodeObject;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var USER_AUTH_KEY = exports.USER_AUTH_KEY = '_stitch_ua';
var REFRESH_TOKEN_KEY = exports.REFRESH_TOKEN_KEY = '_stitch_rt';
var DEVICE_ID_KEY = exports.DEVICE_ID_KEY = '_stitch_did';
var STATE_KEY = exports.STATE_KEY = '_stitch_state';
var USER_AUTH_COOKIE_NAME = exports.USER_AUTH_COOKIE_NAME = 'stitch_ua';
var STITCH_ERROR_KEY = exports.STITCH_ERROR_KEY = '_stitch_error';
var STITCH_LINK_KEY = exports.STITCH_LINK_KEY = '_stitch_link';
var USER_LOGGED_IN_PT_KEY = exports.USER_LOGGED_IN_PT_KEY = '_stitch_pt';
var STITCH_REDIRECT_PROVIDER = exports.STITCH_REDIRECT_PROVIDER = '_stitch_rp';
var DEFAULT_ACCESS_TOKEN_EXPIRE_WITHIN_SECS = exports.DEFAULT_ACCESS_TOKEN_EXPIRE_WITHIN_SECS = 10;
var APP_CLIENT_CODEC = exports.APP_CLIENT_CODEC = {
'accessToken': 'access_token',
'refreshToken': 'refresh_token',
'deviceId': 'device_id',
'userId': 'user_id'
};
var ADMIN_CLIENT_CODEC = exports.ADMIN_CLIENT_CODEC = {
'accessToken': 'access_token',
'refreshToken': 'refresh_token',
'deviceId': 'device_id',
'userId': 'user_id'
};
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.makeFetchArgs = exports.checkStatus = exports.SDK_VERSION = exports.DEFAULT_STITCH_SERVER_URL = exports.ADMIN_CLIENT_TYPE = exports.APP_CLIENT_TYPE = exports.JSONTYPE = undefined;
var _errors = __webpack_require__(3);
var JSONTYPE = exports.JSONTYPE = 'application/json';
var APP_CLIENT_TYPE = exports.APP_CLIENT_TYPE = 'app';
var ADMIN_CLIENT_TYPE = exports.ADMIN_CLIENT_TYPE = 'admin';
var DEFAULT_STITCH_SERVER_URL = exports.DEFAULT_STITCH_SERVER_URL = 'https://stitch.mongodb.com';
// VERSION is substituted with the package.json version number at build time
var version = 'unknown';
if (true) {
version = "3.2.23";
}
var SDK_VERSION = exports.SDK_VERSION = version;
var checkStatus = exports.checkStatus = function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
if (response.headers.get('Content-Type') === JSONTYPE) {
return response.json().then(function (json) {
var error = new _errors.StitchError(json.error, json.error_code);
error.response = response;
error.json = json;
return Promise.reject(error);
});
}
var error = new Error(response.statusText);
error.response = response;
return Promise.reject(error);
};
var makeFetchArgs = exports.makeFetchArgs = function makeFetchArgs(method, body, options) {
var init = {
method: method,
headers: { 'Accept': JSONTYPE, 'Content-Type': JSONTYPE }
};
if (options) {
if (options.credentials) {
init.credentials = options.credentials;
}
}
if (body) {
init.body = body;
}
init.cors = true;
return init;
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _Error = function _Error(message, code) {
Error.call(this, message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
}
this.message = message;
this.name = this.constructor.name;
if (code !== undefined) {
this.code = code;
}
};
_Error.prototype = Object.create(Error.prototype);
var StitchError = function (_Error2) {
_inherits(StitchError, _Error2);
function StitchError() {
_classCallCheck(this, StitchError);
return _possibleConstructorReturn(this, (StitchError.__proto__ || Object.getPrototypeOf(StitchError)).apply(this, arguments));
}
return StitchError;
}(_Error);
var ErrAuthProviderNotFound = 'AuthProviderNotFound';
var ErrInvalidSession = 'InvalidSession';
var ErrUnauthorized = 'Unauthorized';
exports.StitchError = StitchError;
exports.ErrAuthProviderNotFound = ErrAuthProviderNotFound;
exports.ErrInvalidSession = ErrInvalidSession;
exports.ErrUnauthorized = ErrUnauthorized;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.StitchClient = exports.StitchClientFactory = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* global window, fetch */
/* eslint no-labels: ['error', { 'allowLoop': true }] */
exports.newStitchClient = newStitchClient;
__webpack_require__(9);
var _auth = __webpack_require__(13);
var _providers = __webpack_require__(7);
var _common = __webpack_require__(1);
var _services = __webpack_require__(19);
var _services2 = _interopRequireDefault(_services);
var _common2 = __webpack_require__(2);
var common = _interopRequireWildcard(_common2);
var _mongodbExtjson = __webpack_require__(5);
var _mongodbExtjson2 = _interopRequireDefault(_mongodbExtjson);
var _queryString = __webpack_require__(36);
var _queryString2 = _interopRequireDefault(_queryString);
var _errors = __webpack_require__(3);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var v1 = 1;
var v2 = 2;
var v3 = 3;
var API_TYPE_PUBLIC = 'public';
var API_TYPE_PRIVATE = 'private';
var API_TYPE_CLIENT = 'client';
var API_TYPE_APP = 'app';
/**
* StitchClientFactory is a singleton factory class which can be used to
* asynchronously create instances of {@link StitchClient}. StitchClientFactory
* is not meant to be instantiated. Use the static `create()` method to build
* a new StitchClient.
*/
var StitchClientFactory = exports.StitchClientFactory = function () {
/**
* @hideconstructor
*/
function StitchClientFactory() {
_classCallCheck(this, StitchClientFactory);
throw new _errors.StitchError('StitchClient can only be made from the StitchClientFactory.create function');
}
/**
* Creates a new {@link StitchClient}.
*
* @param {String} clientAppID the app ID of the Stitch application, which can be found in
* the "Clients" page of the Stitch admin console.
* @param {Object} [options = {}] additional options for creating the {@link StitchClient}.
*/
_createClass(StitchClientFactory, null, [{
key: 'create',
value: function create(clientAppID) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return newStitchClient(StitchClient.prototype, clientAppID, options);
}
}]);
return StitchClientFactory;
}();
function newStitchClient(prototype, clientAppID) {
var _v, _v2, _v3, _stitchClient$rootURL;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var stitchClient = Object.create(prototype);
var baseUrl = common.DEFAULT_STITCH_SERVER_URL;
if (options.baseUrl) {
baseUrl = options.baseUrl;
}
stitchClient.clientAppID = clientAppID;
stitchClient.authUrl = clientAppID ? baseUrl + '/api/client/v2.0/app/' + clientAppID + '/auth' : baseUrl + '/api/admin/v3.0/auth';
stitchClient.rootURLsByAPIVersion = (_stitchClient$rootURL = {}, _defineProperty(_stitchClient$rootURL, v1, (_v = {}, _defineProperty(_v, API_TYPE_PUBLIC, baseUrl + '/api/public/v1.0'), _defineProperty(_v, API_TYPE_CLIENT, baseUrl + '/api/client/v1.0'), _defineProperty(_v, API_TYPE_PRIVATE, baseUrl + '/api/private/v1.0'), _defineProperty(_v, API_TYPE_APP, clientAppID ? baseUrl + '/api/client/v1.0/app/' + clientAppID : baseUrl + '/api/public/v1.0'), _v)), _defineProperty(_stitchClient$rootURL, v2, (_v2 = {}, _defineProperty(_v2, API_TYPE_PUBLIC, baseUrl + '/api/public/v2.0'), _defineProperty(_v2, API_TYPE_CLIENT, baseUrl + '/api/client/v2.0'), _defineProperty(_v2, API_TYPE_PRIVATE, baseUrl + '/api/private/v2.0'), _defineProperty(_v2, API_TYPE_APP, clientAppID ? baseUrl + '/api/client/v2.0/app/' + clientAppID : baseUrl + '/api/public/v2.0'), _v2)), _defineProperty(_stitchClient$rootURL, v3, (_v3 = {}, _defineProperty(_v3, API_TYPE_PUBLIC, baseUrl + '/api/public/v3.0'), _defineProperty(_v3, API_TYPE_CLIENT, baseUrl + '/api/client/v3.0'), _defineProperty(_v3, API_TYPE_APP, clientAppID ? baseUrl + '/api/client/v3.0/app/' + clientAppID : baseUrl + '/api/admin/v3.0'), _v3)), _stitchClient$rootURL);
var authOptions = {
codec: _common.APP_CLIENT_CODEC,
storage: options.storage
};
if (options.storageType) {
authOptions.storageType = options.storageType;
}
if (options.platform) {
authOptions.platform = options.platform;
}
if (options.authCodec) {
authOptions.codec = options.authCodec;
}
if (options.requestOrigin) {
authOptions.requestOrigin = options.requestOrigin;
}
var authPromise = _auth.AuthFactory.create(stitchClient, stitchClient.authUrl, authOptions);
return authPromise.then(function (auth) {
stitchClient.auth = auth;
return Promise.all([stitchClient.auth.handleRedirect(), stitchClient.auth.handleCookie()]);
}).then(function () {
return stitchClient;
});
}
/**
* StitchClient is the fundamental way of communicating with MongoDB Stitch in your
* application. Use StitchClient to authenticate users and to access Stitch services.
* StitchClient is not meant to be instantiated directly. Use a
* {@link StitchClientFactory} to create one.
*/
var StitchClient = exports.StitchClient = function () {
/**
* @hideconstructor
*/
function StitchClient() {
_classCallCheck(this, StitchClient);
var classname = this.constructor.name;
throw new _errors.StitchError(classname + ' can only be made from the ' + classname + 'Factory.create function');
}
_createClass(StitchClient, [{
key: 'login',
/**
* Login to Stitch instance, optionally providing a username and password. In
* the event that these are omitted, anonymous authentication is used.
*
* @param {String} [email] the email address used for login
* @param {String} [password] the password for the provided email address
* @param {Object} [options = {}] additional authentication options
* @returns {Promise} which resolve to a String value: the authenticated user ID.
*/
value: function login(email, password) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (email === undefined || password === undefined) {
return this.authenticate(_providers.PROVIDER_TYPE_ANON, options);
}
return this.authenticate('userpass', Object.assign({ username: email, password: password }, options));
}
/**
* Send a request to the server indicating the provided email would like
* to sign up for an account. This will trigger a confirmation email containing
* a token which must be used with the `emailConfirm` method of the `userpass`
* auth provider in order to complete registration. The user will not be able
* to log in until that flow has been completed.
*
* @param {String} email the email used to sign up for the app
* @param {String} password the password used to sign up for the app
* @param {Object} [options = {}] additional authentication options
* @returns {Promise}
*/
}, {
key: 'register',
value: function register(email, password) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
return this.auth.provider('userpass').register(email, password, options);
}
/**
* Links the currently logged in user with another identity.
*
* @param {String} providerType the provider of the other identity (e.g. 'userpass', 'facebook', 'google')
* @param {Object} [options = {}] additional authentication options
* @returns {Promise} which resolves to a String value: the original user ID
*/
}, {
key: 'linkWithProvider',
value: function linkWithProvider(providerType) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!this.isAuthenticated()) {
throw new _errors.StitchError('Must be authenticated to link an account');
}
return this.auth.provider(providerType).authenticate(options, true).then(function () {
return _this.authedId();
});
}
/**
* Submits an authentication request to the specified provider providing any
* included options (read: user data). If auth data already exists and the
* existing auth data has an access token, then these credentials are returned.
*
* @param {String} providerType the provider used for authentication (The possible
* options are 'anon', 'userpass', 'custom', 'facebook', 'google',
* and 'apiKey')
* @param {Object} [options = {}] additional authentication options
* @returns {Promise} which resolves to a String value: the authenticated user ID
*/
}, {
key: 'authenticate',
value: function authenticate(providerType) {
var _this2 = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// reuse existing auth if present
var authenticateFn = function authenticateFn() {
return _this2.auth.provider(providerType).authenticate(options).then(function () {
return _this2.authedId();
});
};
if (this.isAuthenticated()) {
if (providerType === _providers.PROVIDER_TYPE_ANON && this.auth.getLoggedInProviderType() === _providers.PROVIDER_TYPE_ANON) {
return Promise.resolve(this.auth.authedId); // is authenticated, skip log in
}
return this.logout().then(function () {
return authenticateFn();
}); // will not be authenticated, continue log in
}
// is not authenticated, continue log in
return authenticateFn();
}
/**
* Ends the session for the current user, and clears auth information from storage.
*
* @returns {Promise}
*/
}, {
key: 'logout',
value: function logout() {
var _this3 = this;
return this._do('/auth/session', 'DELETE', {
refreshOnFailure: false,
useRefreshToken: true,
rootURL: this.rootURLsByAPIVersion[v2][API_TYPE_CLIENT]
}).then(function () {
return _this3.auth.clear();
}, function () {
return _this3.auth.clear();
});
}
/**
* @returns {*} Returns any error from the Stitch authentication system.
*/
}, {
key: 'authError',
value: function authError() {
return this.auth.error();
}
/**
* Returns profile information for the currently logged in user.
*
* @returns {Promise} which resolves to a a JSON object containing user profile information.
*/
}, {
key: 'userProfile',
value: function userProfile() {
return this._do('/auth/profile', 'GET', { rootURL: this.rootURLsByAPIVersion[v2][API_TYPE_CLIENT] }).then(function (response) {
return response.json();
});
}
/**
* @returns {Boolean} whether or not the current client is authenticated.
*/
}, {
key: 'isAuthenticated',
value: function isAuthenticated() {
return !!this.authedId();
}
/**
* @returns {String} a string of the currently authenticated user's ID.
*/
}, {
key: 'authedId',
value: function authedId() {
return this.auth.authedId;
}
/**
* Factory method for accessing Stitch services.
*
* @method
* @param {String} type the service type (e.g. "mongodb", "aws-s3", "aws-ses", "twilio", "http", etc.)
* @param {String} name the service name specified in the Stitch admin console.
* @returns {Object} returns an instance of the specified service type.
*/
}, {
key: 'service',
value: function service(type, name) {
if (this.constructor !== StitchClient) {
throw new _errors.StitchError('`service` is a factory method, do not use `new`');
}
if (!_services2.default.hasOwnProperty(type)) {
throw new _errors.StitchError('Invalid service type specified: ' + type);
}
var ServiceType = _services2.default[type];
return new ServiceType(this, name);
}
/**
* Executes a function.
*
* @param {String} name The name of the function.
* @param {...*} args Arguments to pass to the function.
*/
}, {
key: 'executeFunction',
value: function executeFunction(name) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return this._doFunctionCall({
name: name,
arguments: args
});
}
/**
* Executes a service function.
*
* @param {String} service The name of the service.
* @param {String} action The name of the service action.
* @param {...*} args Arguments to pass to the service action.
*/
}, {
key: 'executeServiceFunction',
value: function executeServiceFunction(service, action) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
return this._doFunctionCall({
service: service,
name: action,
arguments: args
});
}
}, {
key: '_doFunctionCall',
value: function _doFunctionCall(request) {
var responseDecoder = function responseDecoder(d) {
return _mongodbExtjson2.default.parse(d, { relaxed: true });
};
var responseEncoder = function responseEncoder(d) {
return _mongodbExtjson2.default.stringify(d, { strict: true });
};
return this._do('/functions/call', 'POST', { body: responseEncoder(request) }).then(function (response) {
return response.text();
}).then(function (body) {
return responseDecoder(body);
});
}
/**
* Returns an access token for the user
*
* @private
* @returns {Promise}
*/
}, {
key: 'doSessionPost',
value: function doSessionPost() {
return this._do('/auth/session', 'POST', {
refreshOnFailure: false,
useRefreshToken: true,
rootURL: this.rootURLsByAPIVersion[v2][API_TYPE_CLIENT]
}).then(function (response) {
return response.json();
});
}
/**
* Returns the user API keys associated with the current user.
*
* @returns {Promise} which resolves to an array of API key objects
*/
}, {
key: 'getApiKeys',
value: function getApiKeys() {
return this._do('/auth/api_keys', 'GET', {
rootURL: this.rootURLsByAPIVersion[v2][API_TYPE_CLIENT],
useRefreshToken: true
}).then(function (response) {
return response.json();
});
}
/**
* Creates a user API key that can be used to authenticate as the current user.
*
* @param {String} userApiKeyName a unique name for the user API key
* @returns {Promise} which resolves to an API key object containing the API key value
*/
}, {
key: 'createApiKey',
value: function createApiKey(userApiKeyName) {
return this._do('/auth/api_keys', 'POST', { rootURL: this.rootURLsByAPIVersion[v2][API_TYPE_CLIENT],
useRefreshToken: true,
body: JSON.stringify({ 'name': userApiKeyName })
}).then(function (response) {
return response.json();
});
}
/**
* Returns a user API key associated with the current user.
*
* @param {String} keyID the ID of the key to fetch
* @returns {Promise} which resolves to an API key object, although the API key value will be omitted
*/
}, {
key: 'getApiKeyByID',
value: function getApiKeyByID(keyID) {
return this._do('/auth/api_keys/' + keyID, 'GET', {
rootURL: this.rootURLsByAPIVersion[v2][API_TYPE_CLIENT],
useRefreshToken: true
}).then(function (response) {
return response.json();
});
}
/**
* Deletes a user API key associated with the current user.
*
* @param {String} keyID the ID of the key to delete
* @returns {Promise}
*/
}, {
key: 'deleteApiKeyByID',
value: function deleteApiKeyByID(keyID) {
return this._do('/auth/api_keys/' + keyID, 'DELETE', {
rootURL: this.rootURLsByAPIVersion[v2][API_TYPE_CLIENT],
useRefreshToken: true
});
}
/**
* Enables a user API key associated with the current user.
*
* @param {String} keyID the ID of the key to enable
* @returns {Promise}
*/
}, {
key: 'enableApiKeyByID',
value: function enableApiKeyByID(keyID) {
return this._do('/auth/api_keys/' + keyID + '/enable', 'PUT', {
rootURL: this.rootURLsByAPIVersion[v2][API_TYPE_CLIENT],
useRefreshToken: true
});
}
/**
* Disables a user API key associated with the current user.
*
* @param {String} keyID the ID of the key to disable
* @returns {Promise}
*/
}, {
key: 'disableApiKeyByID',
value: function disableApiKeyByID(keyID) {
return this._do('/auth/api_keys/' + keyID + '/disable', 'PUT', {
rootURL: this.rootURLsByAPIVersion[v2][API_TYPE_CLIENT],
useRefreshToken: true
});
}
}, {
key: '_fetch',
value: function _fetch(url, fetchArgs, resource, method, options) {
var _this4 = this;
return fetch(url, fetchArgs).then(function (response) {
// Okay: passthrough
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response);
}
if (response.headers.get('Content-Type') === common.JSONTYPE) {
return response.json().then(function (json) {
// Only want to try refreshing token when there's an invalid session
if ('error_code' in json && json.error_code === _errors.ErrInvalidSession) {
if (!options.refreshOnFailure) {
return _this4.auth.clear().then(function () {
var error = new _errors.StitchError(json.error, json.error_code);
error.response = response;
error.json = json;
throw error;
});
}
return _this4.auth.refreshToken().then(function () {
options.refreshOnFailure = false;
return _this4._do(resource, method, options);
});
}
var error = new _errors.StitchError(json.error, json.error_code);
error.response = response;
error.json = json;
return Promise.reject(error);
});
}
var error = new Error(response.statusText);
error.response = response;
return Promise.reject(error);
});
}
}, {
key: '_fetchArgs',
value: function _fetchArgs(resource, method, options) {
var appURL = this.rootURLsByAPIVersion[options.apiVersion][options.apiType];
var url = '' + appURL + resource;
if (options.rootURL) {
url = '' + options.rootURL + resource;
}
var fetchArgs = common.makeFetchArgs(method, options.body, options);
if (!!options.headers) {
Object.assign(fetchArgs.headers, options.headers);
}
if (options.queryParams) {
url = url + '?' + _queryString2.default.stringify(options.queryParams);
}
if (options.multipart) {
// fall-back on browser to generate Content-Type for us based on request body (FormData)
delete fetchArgs.headers['Content-Type'];
}
return { url: url, fetchArgs: fetchArgs };
}
}, {
key: '_do',
value: function _do(resource, method, options) {
options = Object.assign({}, {
refreshOnFailure: true,
useRefreshToken: false,
apiVersion: v2,
apiType: API_TYPE_APP,
rootURL: undefined
}, options);
var _fetchArgs2 = this._fetchArgs(resource, method, options),
url = _fetchArgs2.url,
fetchArgs = _fetchArgs2.fetchArgs;
if (options.noAuth) {
return this._fetch(url, fetchArgs, resource, method, options);
}
if (!this.isAuthenticated()) {
return Promise.reject(new _errors.StitchError('Must auth first', _errors.ErrUnauthorized));
}
if (this.auth.requestOrigin) {
fetchArgs.headers['X-STITCH-Request-Origin'] = this.auth.requestOrigin;
}
var token = options.useRefreshToken ? this.auth.getRefreshToken() : this.auth.getAccessToken();
fetchArgs.headers.Authorization = 'Bearer ' + token;
return this._fetch(url, fetchArgs, resource, method, options);
}
}, {
key: 'type',
get: function get() {
return common.APP_CLIENT_TYPE;
}
}]);
return StitchClient;
}();
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
(function (global, factory) {
( false ? 'undefined' : _typeof2(exports)) === 'object' && typeof module !== 'undefined' ? module.exports = factory(__webpack_require__(6)) : true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(6)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : global['mongodb-extjson'] = factory(global.bson);
})(undefined, function (bson) {
'use strict';
bson = bson && bson.hasOwnProperty('default') ? bson['default'] : bson;
/**
* Module dependencies.
* @ignore
*/
function convert(integer) {
var str = Number(integer).toString(16);
return str.length === 1 ? '0' + str : str;
}
function toExtendedJSON(obj) {
var base64String = Buffer.isBuffer(obj.buffer) ? obj.buffer.toString('base64') : Buffer.from(obj.buffer).toString('base64');
return {
$binary: {
base64: base64String,
subType: convert(obj.sub_type)
}
};
}
function fromExtendedJSON(BSON, doc) {
var type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
var data = new Buffer(doc.$binary.base64, 'base64');
return new BSON.Binary(data, type);
}
var binary = {
toExtendedJSON: toExtendedJSON,
fromExtendedJSON: fromExtendedJSON
};
function toExtendedJSON$1(obj) {
if (obj.scope) {
return { $code: obj.code, $scope: obj.scope };
}
return { $code: obj.code };
}
function fromExtendedJSON$1(BSON, doc) {
return new BSON.Code(doc.$code, doc.$scope);
}
var code = {
toExtendedJSON: toExtendedJSON$1,
fromExtendedJSON: fromExtendedJSON$1
};
function toExtendedJSON$2(obj) {
var o = {
$ref: obj.collection,
$id: obj.oid
};
if (obj.db) o.$db = obj.db;
o = Object.assign(o, obj.fields);
return o;
}
function fromExtendedJSON$2(BSON, doc) {
var copy = Object.assign({}, doc);
['$ref', '$id', '$db'].forEach(function (k) {
return delete copy[k];
});
return new BSON.DBRef(doc.$ref, doc.$id, doc.$db, copy);
}
var db_ref = {
toExtendedJSON: toExtendedJSON$2,
fromExtendedJSON: fromExtendedJSON$2
};
function toExtendedJSON$3(obj) {
return { $numberDecimal: obj.toString() };
}
function fromExtendedJSON$3(BSON, doc) {
return new BSON.Decimal128.fromString(doc.$numberDecimal);
}
var decimal128 = {
toExtendedJSON: toExtendedJSON$3,
fromExtendedJSON: fromExtendedJSON$3
};
function toExtendedJSON$4(obj, options) {
if (options && options.relaxed && isFinite(obj.value)) return obj.value;
return { $numberDouble: obj.value.toString() };
}
function fromExtendedJSON$4(BSON, doc, options) {
return options && options.relaxed ? parseFloat(doc.$numberDouble) : new BSON.Double(parseFloat(doc.$numberDouble));
}
var double_1 = {
toExtendedJSON: toExtendedJSON$4,
fromExtendedJSON: fromExtendedJSON$4
};
function toExtendedJSON$5(obj, options) {
if (options && options.relaxed) return obj.value;
return { $numberInt: obj.value.toString() };
}
function fromExtendedJSON$5(BSON, doc, options) {
return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new BSON.Int32(doc.$numberInt);
}
var int_32 = {
toExtendedJSON: toExtendedJSON$5,
fromExtendedJSON: fromExtendedJSON$5
};
function toExtendedJSON$6(obj, options) {
if (options && options.relaxed) return obj.toNumber();
return { $numberLong: obj.toString() };
}
function fromExtendedJSON$6(BSON, doc, options) {
var result = BSON.Long.fromString(doc.$numberLong);
return options && options.relaxed ? result.toNumber() : result;
}
var long_1 = {
toExtendedJSON: toExtendedJSON$6,
fromExtendedJSON: fromExtendedJSON$6
};
function toExtendedJSON$7() {
return { $maxKey: 1 };
}
function fromExtendedJSON$7(BSON) {
return new BSON.MaxKey();
}
var max_key = {
toExtendedJSON: toExtendedJSON$7,
fromExtendedJSON: fromExtendedJSON$7
};
function toExtendedJSON$8() {
return { $minKey: 1 };
}
function fromExtendedJSON$8(BSON) {
return new BSON.MinKey();
}
var min_key = {
toExtendedJSON: toExtendedJSON$8,
fromExtendedJSON: fromExtendedJSON$8
};
function toExtendedJSON$9(obj) {
if (obj.toHexString) return { $oid: obj.toHexString() };
return { $oid: obj.toString('hex') };
}
function fromExtendedJSON$9(BSON, doc) {
return new BSON.ObjectID(doc.$oid);
}
var objectid = {
toExtendedJSON: toExtendedJSON$9,
fromExtendedJSON: fromExtendedJSON$9
};
function toExtendedJSON$10(obj) {
return { $regularExpression: { pattern: obj.pattern, options: obj.options } };
}
function fromExtendedJSON$10(BSON, doc) {
return new BSON.BSONRegExp(doc.$regularExpression.pattern, doc.$regularExpression.options.split('').sort().join(''));
}
var regexp = {
toExtendedJSON: toExtendedJSON$10,
fromExtendedJSON: fromExtendedJSON$10
};
function toExtendedJSON$11(obj) {
return { $symbol: obj.value };
}
function fromExtendedJSON$11(BSON, doc) {
return new BSON.Symbol(doc.$symbol);
}
var symbol = {
toExtendedJSON: toExtendedJSON$11,
fromExtendedJSON: fromExtendedJSON$11
};
function toExtendedJSON$12(obj) {
return {
$timestamp: {
t: obj.high_,
i: obj.low_
}
};
}
function fromExtendedJSON$12(BSON, doc) {
return new BSON.Timestamp(doc.$timestamp.i, doc.$timestamp.t);
}
var timestamp = {
toExtendedJSON: toExtendedJSON$12,
fromExtendedJSON: fromExtendedJSON$12
};
var bson$1 = {
Binary: binary,
Code: code,
DBRef: db_ref,
Decimal128: decimal128,
Double: double_1,
Int32: int_32,
Long: long_1,
MaxKey: max_key,
MinKey: min_key,
ObjectID: objectid,
BSONRegExp: regexp,
Symbol: symbol,
Timestamp: timestamp
};
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : _typeof2(obj);
};
var BSON = bson;
var BSONTypes = ['Binary', 'Code', 'DBRef', 'Decimal128', 'Double', 'Int32', 'Long', 'MaxKey', 'MinKey', 'ObjectID', 'BSONRegExp', 'Symbol', 'Timestamp'];
setBSONModule(BSON);
// all the types where we don't need to do any special processing and can just pass the EJSON
//straight to type.fromExtendedJSON
var keysToCodecs = {
$oid: bson$1.ObjectID,
$binary: bson$1.Binary,
$symbol: bson$1.Symbol,
$numberInt: bson$1.Int32,
$numberDecimal: bson$1.Decimal128,
$numberDouble: bson$1.Double,
$numberLong: bson$1.Long,
$minKey: bson$1.MinKey,
$maxKey: bson$1.MaxKey,
$regularExpression: bson$1.BSONRegExp,
$timestamp: bson$1.Timestamp
};
function setBSONModule(module) {
BSONTypes.forEach(function (t) {
if (!module[t]) throw new Error('passed in module does not contain all BSON types required');
});
BSON = module;
}
function deserializeValue(self, key, value, options) {
if (typeof value === 'number') {
// if it's an integer, should interpret as smallest BSON integer
// that can represent it exactly. (if out of range, interpret as double.)
if (Math.floor(value) === value) {
var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX,
int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX;
if (int32Range) return options.strict ? new BSON.Int32(value) : value;
if (int64Range) return options.strict ? new BSON.Long.fromNumber(value) : value;
}
// If the number is a non-integer or out of integer range, should interpret as BSON Double.
return new BSON.Double(value);
}
// from here on out we're looking for bson types, so bail if its not an object
if (value == null || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') return value;
// upgrade deprecated undefined to null
if (value.$undefined) return null;
var keys = Object.keys(value).filter(function (k) {
return k.startsWith('$') && value[k] != null;
});
for (var i = 0; i < keys.length; i++) {
var c = keysToCodecs[keys[i]];
if (c) return c.fromExtendedJSON(BSON, value, options);
}
if (value.$date != null) {
var d = value.$date,
date = new Date();
if (typeof d === 'string') date.setTime(Date.parse(d));else if (d instanceof BSON.Long) date.setTime(d.toNumber());else if (typeof d === 'number' && options.relaxed) date.setTime(d);
return date;
}
if (value.$code != null) {
if (value.$scope) var scope = deserializeValue(self, null, value.$scope);
var copy = Object.assign({}, value);
copy.$scope = scope;
return bson$1.Code.fromExtendedJSON(BSON, value);
}
if (value.$ref != null || value.$dbPointer != null) {
var v = value.$ref ? value : value.$dbPointer;
// we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
// because of the order JSON.parse goes through the document
if (v instanceof BSON.DBRef) return v;
var dollarKeys = Object.keys(v).filter(function (k) {
return k.startsWith('$');
}),
valid = true;
dollarKeys.forEach(function (k) {
if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
});
// only make DBRef if $ keys are all valid
if (valid) return bson$1.DBRef.fromExtendedJSON(BSON, v);
}
return value;
}
var parse = function parse(text, options) {
var self = this;
options = options || { relaxed: false };
// relaxed implies not strict
if (typeof options.relaxed === 'boolean') options.strict = !options.relaxed;
if (typeof options.strict === 'boolean') options.relaxed = !options.strict;
return JSON.parse(text, function (key, value) {
return deserializeValue(self, key, value, options);
});
};
//
// Serializer
//
// MAX INT32 boundaries
var BSON_INT32_MAX = 0x7fffffff,
BSON_INT32_MIN = -0x80000000,
BSON_INT64_MAX = 0x7fffffffffffffff,
BSON_INT64_MIN = -0x8000000000000000;
var stringify = function stringify(value, reducer, indents, options) {
var opts = {};
if (options != null && (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') opts = options;else if (indents != null && (typeof indents === 'undefined' ? 'undefined' : _typeof(indents)) === 'object') {
opts = indents;
indents = 0;
} else if (reducer != null && (typeof reducer === 'undefined' ? 'undefined' : _typeof(reducer)) === 'object') {
opts = reducer;
reducer = null;
}
var doc = Array.isArray(value) ? serializeArray(value, opts) : serializeDocument(value, opts);
return JSON.stringify(doc, reducer, indents);
};
function serializeArray(array, options) {
return array.map(function (v) {
return serializeValue(v, options);
});
}
function getISOString(date) {
var isoStr = date.toISOString();
// we should only show milliseconds in timestamp if they're non-zero
return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
}
function serializeValue(value, options) {
if (Array.isArray(value)) return serializeArray(value, options);
if (value === undefined) return null;
if (value instanceof Date) {
var dateNum = value.getTime(),
// is it in year range 1970-9999?
inRange = dateNum > -1 && dateNum < 253402318800000;
return options.relaxed && inRange ? { $date: getISOString(value) } : { $date: { $numberLong: value.getTime().toString() } };
}
if (typeof value === 'number' && !options.relaxed) {
// it's an integer
if (Math.floor(value) === value) {
var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX,
int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX;
// interpret as being of the smallest BSON integer type that can represent the number exactly
if (int32Range) return { $numberInt: value.toString() };
if (int64Range) return { $numberLong: value.toString() };
}
return { $numberDouble: value.toString() };
}
if (value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') return serializeDocument(value, options);
return value;
}
function serializeDocument(doc, options) {
if (doc == null || (typeof doc === 'undefined' ? 'undefined' : _typeof(doc)) !== 'object') throw new Error('not an object instance');
// the document itself is a BSON type
if (doc._bsontype && BSONTypes.indexOf(doc._bsontype) !== -1) {
// we need to separately serialize the embedded scope document
if (doc._bsontype === 'Code' && doc.scope) {
var tempScope = serializeDocument(doc.scope, options),
tempDoc = Object.assign({}, doc, { scope: tempScope });
return bson$1['Code'].toExtendedJSON(tempDoc, options);
// we need to separately serialize the embedded OID document
} else if (doc._bsontype === 'DBRef' && doc.oid) {
var tempId = serializeDocument(doc.oid, options),
_tempDoc = Object.assign({}, doc, { oid: tempId });
return bson$1['DBRef'].toExtendedJSON(_tempDoc, options);
}
return bson$1[doc._bsontype].toExtendedJSON(doc, options);
}
// the document is an object with nested BSON types
var _doc = {};
for (var name in doc) {
var val = doc[name];
if (Array.isArray(val)) {
_doc[name] = serializeArray(val, options);
} else if (val != null && val._bsontype && BSONTypes.indexOf(val._bsontype) !== -1) {
// we need to separately serialize the embedded scope document
if (val._bsontype === 'Code' && val.scope) {
var _tempScope = serializeDocument(val.scope, options),
tempVal = Object.assign({}, val, { scope: _tempScope });
_doc[name] = bson$1['Code'].toExtendedJSON(tempVal, options);
// we need to separately serialize the embedded OID document
} else if (val._bsontype === 'DBRef' && val.oid) {
var _tempId = serializeDocument(val.oid, options),
_tempVal = Object.assign({}, val, { oid: _tempId });
_doc[name] = bson$1['DBRef'].toExtendedJSON(_tempVal, options);
} else _doc[name] = bson$1[val._bsontype].toExtendedJSON(val, options);
} else if (val instanceof Date) {
_doc[name] = serializeValue(val, options);
} else if (val != null && (typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object') {
_doc[name] = serializeDocument(val, options);
}
_doc[name] = serializeValue(val, options);
if (val instanceof RegExp) {
var flags = val.flags;
if (flags === undefined) {
flags = val.toString().match(/[gimuy]*$/)[0];
}
_doc[name] = bson$1['BSONRegExp'].toExtendedJSON({ pattern: val.source, options: flags });
}
}
return _doc;
}
var ext_json = {
parse: parse,
stringify: stringify,
setBSONModule: setBSONModule,
BSON: BSON
};
var mongodbExtjson = ext_json;
return mongodbExtjson;
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8).Buffer))
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, Buffer, process) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
(function (global, factory) {
( false ? 'undefined' : _typeof2(exports)) === 'object' && typeof module !== 'undefined' ? module.exports = factory() : true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : global.bson = factory();
})(undefined, function () {
'use strict';
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var map = createCommonjsModule(function (module) {
// We have an ES6 Map available, return the native instance
if (typeof commonjsGlobal.Map !== 'undefined') {
module.exports = commonjsGlobal.Map;
module.exports.Map = commonjsGlobal.Map;
} else {
// We will return a polyfill
var Map = function Map(array) {
this._keys = [];
this._values = {};
for (var i = 0; i < arra