UNPKG

jsforce

Version:

Salesforce API Library for JavaScript

1,294 lines (1,265 loc) 246 kB
import _Reflect$construct from "@babel/runtime-corejs3/core-js-stable/reflect/construct"; import _Object$keys from "@babel/runtime-corejs3/core-js-stable/object/keys"; import _Object$getOwnPropertySymbols from "@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols"; import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter"; import _Object$getOwnPropertyDescriptor from "@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor"; import _Object$getOwnPropertyDescriptors from "@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors"; import _Object$defineProperties from "@babel/runtime-corejs3/core-js-stable/object/define-properties"; import _Object$defineProperty from "@babel/runtime-corejs3/core-js-stable/object/define-property"; import _Array$from from "@babel/runtime-corejs3/core-js-stable/array/from"; import _Symbol from "@babel/runtime-corejs3/core-js-stable/symbol"; import _getIteratorMethod from "@babel/runtime-corejs3/core-js/get-iterator-method"; import _Symbol$toPrimitive from "@babel/runtime-corejs3/core-js-stable/symbol/to-primitive"; import _typeof from "@babel/runtime-corejs3/helpers/typeof"; import _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray"; import _objectWithoutProperties from "@babel/runtime-corejs3/helpers/objectWithoutProperties"; import _classCallCheck from "@babel/runtime-corejs3/helpers/classCallCheck"; import _createClass from "@babel/runtime-corejs3/helpers/createClass"; import _possibleConstructorReturn from "@babel/runtime-corejs3/helpers/possibleConstructorReturn"; import _getPrototypeOf from "@babel/runtime-corejs3/helpers/getPrototypeOf"; import _inherits from "@babel/runtime-corejs3/helpers/inherits"; import _defineProperty from "@babel/runtime-corejs3/helpers/defineProperty"; import _asyncToGenerator from "@babel/runtime-corejs3/helpers/asyncToGenerator"; import _slicedToArray from "@babel/runtime-corejs3/helpers/slicedToArray"; var _excluded = ["Id", "type", "attributes"], _excluded2 = ["Id", "type", "attributes"], _excluded3 = ["Id", "type", "attributes"], _excluded4 = ["Id", "type", "attributes"]; function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } 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); } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof _Symbol && _getIteratorMethod(r) || r["@@iterator"]; if (!t) { if (_Array$isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } function _unsupportedIterableToArray(r, a) { if (r) { var _context59; if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = _sliceInstanceProperty(_context59 = {}.toString.call(r)).call(_context59, 8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function ownKeys(e, r) { var t = _Object$keys(e); if (_Object$getOwnPropertySymbols) { var o = _Object$getOwnPropertySymbols(e); r && (o = _filterInstanceProperty(o).call(o, function (r) { return _Object$getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var _context57, _context58; var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? _forEachInstanceProperty(_context57 = ownKeys(Object(t), !0)).call(_context57, function (r) { _defineProperty(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(e, _Object$getOwnPropertyDescriptors(t)) : _forEachInstanceProperty(_context58 = ownKeys(Object(t))).call(_context58, function (r) { _Object$defineProperty(e, r, _Object$getOwnPropertyDescriptor(t, r)); }); } return e; } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? _Reflect$construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(_Reflect$construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } import _regeneratorRuntime from "@babel/runtime-corejs3/regenerator"; import _startsWithInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/starts-with"; import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice"; import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat"; import _Promise from "@babel/runtime-corejs3/core-js-stable/promise"; import _parseInt from "@babel/runtime-corejs3/core-js-stable/parse-int"; import _JSON$stringify from "@babel/runtime-corejs3/core-js-stable/json/stringify"; import _Array$isArray from "@babel/runtime-corejs3/core-js-stable/array/is-array"; import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map"; import _forEachInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/for-each"; import _Object$entries from "@babel/runtime-corejs3/core-js-stable/object/entries"; import _includesInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/includes"; import "core-js/modules/es.error.cause.js"; import "core-js/modules/es.array.join.js"; import "core-js/modules/es.function.name.js"; import "core-js/modules/es.array.push.js"; import "core-js/modules/es.number.constructor.js"; import "core-js/modules/es.object.keys.js"; import "core-js/modules/es.object.to-string.js"; import "core-js/modules/es.regexp.exec.js"; import "core-js/modules/es.regexp.test.js"; import "core-js/modules/es.regexp.to-string.js"; import "core-js/modules/es.string.match.js"; import "core-js/modules/es.string.replace.js"; /** * */ import { EventEmitter } from 'events'; import jsforce from './jsforce'; import Transport, { CanvasTransport, XdProxyTransport, HttpProxyTransport } from './transport'; import { getLogger } from './util/logger'; import OAuth2 from './oauth2'; import Cache from './cache'; import HttpApi from './http-api'; import SessionRefreshDelegate from './session-refresh-delegate'; import Query from './query'; import SObject from './sobject'; import QuickAction from './quick-action'; import Process from './process'; import { formatDate } from './util/formatter'; import FormData from 'form-data'; /** * type definitions */ /** * */ var defaultConnectionConfig = { loginUrl: 'https://login.salesforce.com', instanceUrl: '', version: '50.0', logLevel: 'NONE', maxRequest: 10 }; /** * */ function esc(str) { return String(str || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } /** * */ function parseSignedRequest(sr) { if (typeof sr === 'string') { if (_startsWithInstanceProperty(sr).call(sr, '{')) { // might be JSON return JSON.parse(sr); } // might be original base64-encoded signed request var msg = sr.split('.').pop(); // retrieve latter part if (!msg) { throw new Error('Invalid signed request'); } var json = Buffer.from(msg, 'base64').toString('utf-8'); return JSON.parse(json); } return sr; } /** @private **/ function parseIdUrl(url) { var _context; var _url$split$slice = _sliceInstanceProperty(_context = url.split('/')).call(_context, -2), _url$split$slice2 = _slicedToArray(_url$split$slice, 2), organizationId = _url$split$slice2[0], id = _url$split$slice2[1]; return { id: id, organizationId: organizationId, url: url }; } /** * Session Refresh delegate function for OAuth2 authz code flow * @private */ function oauthRefreshFn(_x, _x2) { return _oauthRefreshFn.apply(this, arguments); } /** * Session Refresh delegate function for username/password login * @private */ function _oauthRefreshFn() { _oauthRefreshFn = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee37(conn, callback) { var res, userInfo; return _regeneratorRuntime.wrap(function _callee37$(_context56) { while (1) switch (_context56.prev = _context56.next) { case 0: _context56.prev = 0; if (conn.refreshToken) { _context56.next = 3; break; } throw new Error('No refresh token found in the connection'); case 3: _context56.next = 5; return conn.oauth2.refreshToken(conn.refreshToken); case 5: res = _context56.sent; userInfo = parseIdUrl(res.id); conn._establish({ instanceUrl: res.instance_url, accessToken: res.access_token, userInfo: userInfo }); callback(undefined, res.access_token, res); _context56.next = 18; break; case 11: _context56.prev = 11; _context56.t0 = _context56["catch"](0); if (!(_context56.t0 instanceof Error)) { _context56.next = 17; break; } callback(_context56.t0); _context56.next = 18; break; case 17: throw _context56.t0; case 18: case "end": return _context56.stop(); } }, _callee37, null, [[0, 11]]); })); return _oauthRefreshFn.apply(this, arguments); } function createUsernamePasswordRefreshFn(username, password) { return /*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(conn, callback) { return _regeneratorRuntime.wrap(function _callee$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _context2.prev = 0; _context2.next = 3; return conn.login(username, password); case 3: if (conn.accessToken) { _context2.next = 5; break; } throw new Error('Access token not found after login'); case 5: callback(null, conn.accessToken); _context2.next = 15; break; case 8: _context2.prev = 8; _context2.t0 = _context2["catch"](0); if (!(_context2.t0 instanceof Error)) { _context2.next = 14; break; } callback(_context2.t0); _context2.next = 15; break; case 14: throw _context2.t0; case 15: case "end": return _context2.stop(); } }, _callee, null, [[0, 8]]); })); return function (_x3, _x4) { return _ref.apply(this, arguments); }; }(); } /** * @private */ function toSaveResult(err) { return { success: false, errors: [err] }; } /** * */ function raiseNoModuleError(name) { var _context3; throw new Error(_concatInstanceProperty(_context3 = "API module '".concat(name, "' is not loaded, load 'jsforce/api/")).call(_context3, name, "' explicitly")); } /* * Constant of maximum records num in DML operation (update/delete) */ var MAX_DML_COUNT = 200; /** * */ export var Connection = /*#__PURE__*/function (_EventEmitter) { /** * */ function Connection() { var _this; var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Connection); _this = _callSuper(this, Connection); _defineProperty(_this, "limitInfo", {}); _defineProperty(_this, "sobjects", {}); /** * Synonym of Connection#create() */ _defineProperty(_this, "insert", _this.create); /** * Synonym of Connection#destroy() */ _defineProperty(_this, "delete", _this.destroy); /** * Synonym of Connection#destroy() */ _defineProperty(_this, "del", _this.destroy); /** * Module which manages process rules and approval processes */ _defineProperty(_this, "process", new Process(_this)); var loginUrl = config.loginUrl, instanceUrl = config.instanceUrl, version = config.version, oauth2 = config.oauth2, maxRequest = config.maxRequest, logLevel = config.logLevel, proxyUrl = config.proxyUrl, httpProxy = config.httpProxy; _this.loginUrl = loginUrl || defaultConnectionConfig.loginUrl; _this.instanceUrl = instanceUrl || defaultConnectionConfig.instanceUrl; if (_this.isLightningInstance()) { throw new Error('lightning URLs are not valid as instance URLs'); } _this.version = version || defaultConnectionConfig.version; _this.oauth2 = oauth2 instanceof OAuth2 ? oauth2 : new OAuth2(_objectSpread({ loginUrl: _this.loginUrl, proxyUrl: proxyUrl, httpProxy: httpProxy }, oauth2)); var refreshFn = config.refreshFn; if (!refreshFn && _this.oauth2.clientId) { refreshFn = oauthRefreshFn; } if (refreshFn) { _this._refreshDelegate = new SessionRefreshDelegate(_this, refreshFn); } _this._maxRequest = maxRequest || defaultConnectionConfig.maxRequest; _this._logger = logLevel ? Connection._logger.createInstance(logLevel) : Connection._logger; _this._logLevel = logLevel; _this._transport = proxyUrl ? new XdProxyTransport(proxyUrl) : httpProxy ? new HttpProxyTransport(httpProxy) : new Transport(); _this._callOptions = config.callOptions; _this.cache = new Cache(); var describeCacheKey = function describeCacheKey(type) { return type ? "describe.".concat(type) : 'describe'; }; var describe = Connection.prototype.describe; _this.describe = _this.cache.createCachedFunction(describe, _this, { key: describeCacheKey, strategy: 'NOCACHE' }); _this.describe$ = _this.cache.createCachedFunction(describe, _this, { key: describeCacheKey, strategy: 'HIT' }); _this.describe$$ = _this.cache.createCachedFunction(describe, _this, { key: describeCacheKey, strategy: 'IMMEDIATE' }); _this.describeSObject = _this.describe; _this.describeSObject$ = _this.describe$; _this.describeSObject$$ = _this.describe$$; var describeGlobal = Connection.prototype.describeGlobal; _this.describeGlobal = _this.cache.createCachedFunction(describeGlobal, _this, { key: 'describeGlobal', strategy: 'NOCACHE' }); _this.describeGlobal$ = _this.cache.createCachedFunction(describeGlobal, _this, { key: 'describeGlobal', strategy: 'HIT' }); _this.describeGlobal$$ = _this.cache.createCachedFunction(describeGlobal, _this, { key: 'describeGlobal', strategy: 'IMMEDIATE' }); var accessToken = config.accessToken, refreshToken = config.refreshToken, sessionId = config.sessionId, serverUrl = config.serverUrl, signedRequest = config.signedRequest; _this._establish({ accessToken: accessToken, refreshToken: refreshToken, instanceUrl: instanceUrl, sessionId: sessionId, serverUrl: serverUrl, signedRequest: signedRequest }); jsforce.emit('connection:new', _this); return _this; } /* @private */ _inherits(Connection, _EventEmitter); return _createClass(Connection, [{ key: "analytics", get: // describe: (name: string) => Promise<DescribeSObjectResult>; // describeGlobal: () => Promise<DescribeGlobalResult>; // API libs are not instantiated here so that core module to remain without dependencies to them // It is responsible for developers to import api libs explicitly if they are using 'jsforce/core' instead of 'jsforce'. function get() { return raiseNoModuleError('analytics'); } }, { key: "apex", get: function get() { return raiseNoModuleError('apex'); } }, { key: "bulk", get: function get() { return raiseNoModuleError('bulk'); } }, { key: "bulk2", get: function get() { return raiseNoModuleError('bulk2'); } }, { key: "chatter", get: function get() { return raiseNoModuleError('chatter'); } }, { key: "metadata", get: function get() { return raiseNoModuleError('metadata'); } }, { key: "soap", get: function get() { return raiseNoModuleError('soap'); } }, { key: "streaming", get: function get() { return raiseNoModuleError('streaming'); } }, { key: "tooling", get: function get() { return raiseNoModuleError('tooling'); } }, { key: "_establish", value: function _establish(options) { var _context4; var accessToken = options.accessToken, refreshToken = options.refreshToken, instanceUrl = options.instanceUrl, sessionId = options.sessionId, serverUrl = options.serverUrl, signedRequest = options.signedRequest, userInfo = options.userInfo; this.instanceUrl = serverUrl ? _sliceInstanceProperty(_context4 = serverUrl.split('/')).call(_context4, 0, 3).join('/') : instanceUrl || this.instanceUrl; this.accessToken = sessionId || accessToken || this.accessToken; this.refreshToken = refreshToken || this.refreshToken; if (this.refreshToken && !this._refreshDelegate) { throw new Error('Refresh token is specified without oauth2 client information or refresh function'); } var signedRequestObject = signedRequest && parseSignedRequest(signedRequest); if (signedRequestObject) { this.accessToken = signedRequestObject.client.oauthToken; if (CanvasTransport.supported) { this._transport = new CanvasTransport(signedRequestObject); } } this.userInfo = userInfo || this.userInfo; this._sessionType = sessionId ? 'soap' : 'oauth2'; this._resetInstance(); } /* @priveate */ }, { key: "_clearSession", value: function _clearSession() { this.accessToken = null; this.refreshToken = null; this.instanceUrl = defaultConnectionConfig.instanceUrl; this.userInfo = null; this._sessionType = null; } /* @priveate */ }, { key: "_resetInstance", value: function _resetInstance() { var _this2 = this; this.limitInfo = {}; this.sobjects = {}; // TODO impl cache this.cache.clear(); this.cache.get('describeGlobal').removeAllListeners('value'); this.cache.get('describeGlobal').on('value', function (_ref2) { var result = _ref2.result; if (result) { var _iterator = _createForOfIteratorHelper(result.sobjects), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var so = _step.value; _this2.sobject(so.name); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } }); /* if (this.tooling) { this.tooling._resetInstance(); } */ } /** * Authorize the connection using OAuth2 flow. * Typically, just pass the code returned from authorization server in the first argument to complete authorization. * If you want to authorize with grant types other than `authorization_code`, you can also pass params object with the grant type. * * @returns {Promise<UserInfo>} An object that contains the user ID, org ID and identity URL. * */ }, { key: "authorize", value: (function () { var _authorize = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(codeOrParams) { var _context5; var params, res, userInfo, _args2 = arguments; return _regeneratorRuntime.wrap(function _callee2$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: params = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {}; _context6.next = 3; return this.oauth2.requestToken(codeOrParams, params); case 3: res = _context6.sent; userInfo = parseIdUrl(res.id); this._establish({ instanceUrl: res.instance_url, accessToken: res.access_token, refreshToken: res.refresh_token, userInfo: userInfo }); this._logger.debug(_concatInstanceProperty(_context5 = "<login> completed. user id = ".concat(userInfo.id, ", org id = ")).call(_context5, userInfo.organizationId)); return _context6.abrupt("return", userInfo); case 8: case "end": return _context6.stop(); } }, _callee2, this); })); function authorize(_x5) { return _authorize.apply(this, arguments); } return authorize; }() /** * */ ) }, { key: "login", value: (function () { var _login = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(username, password) { var _this$oauth; return _regeneratorRuntime.wrap(function _callee3$(_context7) { while (1) switch (_context7.prev = _context7.next) { case 0: this._refreshDelegate = new SessionRefreshDelegate(this, createUsernamePasswordRefreshFn(username, password)); if (!((_this$oauth = this.oauth2) !== null && _this$oauth !== void 0 && _this$oauth.clientId && this.oauth2.clientSecret)) { _context7.next = 3; break; } return _context7.abrupt("return", this.loginByOAuth2(username, password)); case 3: return _context7.abrupt("return", this.loginBySoap(username, password)); case 4: case "end": return _context7.stop(); } }, _callee3, this); })); function login(_x6, _x7) { return _login.apply(this, arguments); } return login; }() /** * Login by OAuth2 username & password flow */ ) }, { key: "loginByOAuth2", value: (function () { var _loginByOAuth = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(username, password) { var _context8; var res, userInfo; return _regeneratorRuntime.wrap(function _callee4$(_context9) { while (1) switch (_context9.prev = _context9.next) { case 0: _context9.next = 2; return this.oauth2.authenticate(username, password); case 2: res = _context9.sent; userInfo = parseIdUrl(res.id); this._establish({ instanceUrl: res.instance_url, accessToken: res.access_token, userInfo: userInfo }); this._logger.info(_concatInstanceProperty(_context8 = "<login> completed. user id = ".concat(userInfo.id, ", org id = ")).call(_context8, userInfo.organizationId)); return _context9.abrupt("return", userInfo); case 7: case "end": return _context9.stop(); } }, _callee4, this); })); function loginByOAuth2(_x8, _x9) { return _loginByOAuth.apply(this, arguments); } return loginByOAuth2; }() /** * */ ) }, { key: "loginBySoap", value: (function () { var _loginBySoap = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(username, password) { var _context10, _context11; var body, soapLoginEndpoint, response, m, faultstring, serverUrl, sessionId, userId, organizationId, idUrl, userInfo; return _regeneratorRuntime.wrap(function _callee5$(_context12) { while (1) switch (_context12.prev = _context12.next) { case 0: if (!(!username || !password)) { _context12.next = 2; break; } return _context12.abrupt("return", _Promise.reject(new Error('no username password given'))); case 2: body = ['<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/">', '<se:Header/>', '<se:Body>', '<login xmlns="urn:partner.soap.sforce.com">', "<username>".concat(esc(username), "</username>"), "<password>".concat(esc(password), "</password>"), '</login>', '</se:Body>', '</se:Envelope>'].join(''); soapLoginEndpoint = [this.loginUrl, 'services/Soap/u', this.version].join('/'); _context12.next = 6; return this._transport.httpRequest({ method: 'POST', url: soapLoginEndpoint, body: body, headers: { 'Content-Type': 'text/xml', SOAPAction: '""' } }); case 6: response = _context12.sent; if (!(response.statusCode >= 400)) { _context12.next = 11; break; } m = response.body.match(/<faultstring>([^<]+)<\/faultstring>/); faultstring = m && m[1]; throw new Error(faultstring || response.body); case 11: if (!response.body.match(/<passwordExpired>true<\/passwordExpired>/g)) { _context12.next = 13; break; } throw new Error('Unable to login because the used password has expired.'); case 13: this._logger.debug("SOAP response = ".concat(response.body)); m = response.body.match(/<serverUrl>([^<]+)<\/serverUrl>/); serverUrl = m && m[1]; m = response.body.match(/<sessionId>([^<]+)<\/sessionId>/); sessionId = m && m[1]; m = response.body.match(/<userId>([^<]+)<\/userId>/); userId = m && m[1]; m = response.body.match(/<organizationId>([^<]+)<\/organizationId>/); organizationId = m && m[1]; if (!(!serverUrl || !sessionId || !userId || !organizationId)) { _context12.next = 24; break; } throw new Error('could not extract session information from login response'); case 24: idUrl = [this.loginUrl, 'id', organizationId, userId].join('/'); userInfo = { id: userId, organizationId: organizationId, url: idUrl }; this._establish({ serverUrl: _sliceInstanceProperty(_context10 = serverUrl.split('/')).call(_context10, 0, 3).join('/'), sessionId: sessionId, userInfo: userInfo }); this._logger.info(_concatInstanceProperty(_context11 = "<login> completed. user id = ".concat(userId, ", org id = ")).call(_context11, organizationId)); return _context12.abrupt("return", userInfo); case 29: case "end": return _context12.stop(); } }, _callee5, this); })); function loginBySoap(_x10, _x11) { return _loginBySoap.apply(this, arguments); } return loginBySoap; }() /** * Logout the current session */ ) }, { key: "logout", value: (function () { var _logout = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(revoke) { return _regeneratorRuntime.wrap(function _callee6$(_context13) { while (1) switch (_context13.prev = _context13.next) { case 0: this._refreshDelegate = undefined; if (!(this._sessionType === 'oauth2')) { _context13.next = 3; break; } return _context13.abrupt("return", this.logoutByOAuth2(revoke)); case 3: return _context13.abrupt("return", this.logoutBySoap(revoke)); case 4: case "end": return _context13.stop(); } }, _callee6, this); })); function logout(_x12) { return _logout.apply(this, arguments); } return logout; }() /** * Logout the current session by revoking access token via OAuth2 session revoke */ ) }, { key: "logoutByOAuth2", value: (function () { var _logoutByOAuth = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(revoke) { var token; return _regeneratorRuntime.wrap(function _callee7$(_context14) { while (1) switch (_context14.prev = _context14.next) { case 0: token = revoke ? this.refreshToken : this.accessToken; if (!token) { _context14.next = 4; break; } _context14.next = 4; return this.oauth2.revokeToken(token); case 4: // Destroy the session bound to this connection this._clearSession(); this._resetInstance(); case 6: case "end": return _context14.stop(); } }, _callee7, this); })); function logoutByOAuth2(_x13) { return _logoutByOAuth.apply(this, arguments); } return logoutByOAuth2; }() /** * Logout the session by using SOAP web service API */ ) }, { key: "logoutBySoap", value: (function () { var _logoutBySoap = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(revoke) { var _context15; var body, response, m, faultstring; return _regeneratorRuntime.wrap(function _callee8$(_context16) { while (1) switch (_context16.prev = _context16.next) { case 0: body = ['<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/">', '<se:Header>', '<SessionHeader xmlns="urn:partner.soap.sforce.com">', "<sessionId>".concat(esc(revoke ? this.refreshToken : this.accessToken), "</sessionId>"), '</SessionHeader>', '</se:Header>', '<se:Body>', '<logout xmlns="urn:partner.soap.sforce.com"/>', '</se:Body>', '</se:Envelope>'].join(''); _context16.next = 3; return this._transport.httpRequest({ method: 'POST', url: [this.instanceUrl, 'services/Soap/u', this.version].join('/'), body: body, headers: { 'Content-Type': 'text/xml', SOAPAction: '""' } }); case 3: response = _context16.sent; this._logger.debug(_concatInstanceProperty(_context15 = "SOAP statusCode = ".concat(response.statusCode, ", response = ")).call(_context15, response.body)); if (!(response.statusCode >= 400)) { _context16.next = 9; break; } m = response.body.match(/<faultstring>([^<]+)<\/faultstring>/); faultstring = m && m[1]; throw new Error(faultstring || response.body); case 9: // Destroy the session bound to this connection this._clearSession(); this._resetInstance(); case 11: case "end": return _context16.stop(); } }, _callee8, this); })); function logoutBySoap(_x14) { return _logoutBySoap.apply(this, arguments); } return logoutBySoap; }() /** * Send REST API request with given HTTP request info, with connected session information. * * Endpoint URL can be absolute URL ('https://na1.salesforce.com/services/data/v32.0/sobjects/Account/describe') * , relative path from root ('/services/data/v32.0/sobjects/Account/describe') * , or relative path from version root ('/sobjects/Account/describe'). */ ) }, { key: "request", value: function request(_request) { var _this3 = this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // if request is simple string, regard it as url in GET method var request_ = typeof _request === 'string' ? { method: 'GET', url: _request } : _request; // if url is given in relative path, prepend base url or instance url before. request_ = _objectSpread(_objectSpread({}, request_), {}, { url: this._normalizeUrl(request_.url) }); var httpApi = new HttpApi(this, options); // log api usage and its quota httpApi.on('response', function (response) { if (response.headers && response.headers['sforce-limit-info']) { var apiUsage = response.headers['sforce-limit-info'].match(/api-usage=(\d+)\/(\d+)/); if (apiUsage) { _this3.limitInfo = { apiUsage: { used: _parseInt(apiUsage[1], 10), limit: _parseInt(apiUsage[2], 10) } }; } } }); return httpApi.request(request_); } /** * Send HTTP GET request * * Endpoint URL can be absolute URL ('https://na1.salesforce.com/services/data/v32.0/sobjects/Account/describe') * , relative path from root ('/services/data/v32.0/sobjects/Account/describe') * , or relative path from version root ('/sobjects/Account/describe'). */ }, { key: "requestGet", value: function requestGet(url, options) { var request = { method: 'GET', url: url }; return this.request(request, options); } /** * Send HTTP POST request with JSON body, with connected session information * * Endpoint URL can be absolute URL ('https://na1.salesforce.com/services/data/v32.0/sobjects/Account/describe') * , relative path from root ('/services/data/v32.0/sobjects/Account/describe') * , or relative path from version root ('/sobjects/Account/describe'). */ }, { key: "requestPost", value: function requestPost(url, body, options) { var request = { method: 'POST', url: url, body: _JSON$stringify(body), headers: { 'content-type': 'application/json' } }; return this.request(request, options); } /** * Send HTTP PUT request with JSON body, with connected session information * * Endpoint URL can be absolute URL ('https://na1.salesforce.com/services/data/v32.0/sobjects/Account/describe') * , relative path from root ('/services/data/v32.0/sobjects/Account/describe') * , or relative path from version root ('/sobjects/Account/describe'). */ }, { key: "requestPut", value: function requestPut(url, body, options) { var request = { method: 'PUT', url: url, body: _JSON$stringify(body), headers: { 'content-type': 'application/json' } }; return this.request(request, options); } /** * Send HTTP PATCH request with JSON body * * Endpoint URL can be absolute URL ('https://na1.salesforce.com/services/data/v32.0/sobjects/Account/describe') * , relative path from root ('/services/data/v32.0/sobjects/Account/describe') * , or relative path from version root ('/sobjects/Account/describe'). */ }, { key: "requestPatch", value: function requestPatch(url, body, options) { var request = { method: 'PATCH', url: url, body: _JSON$stringify(body), headers: { 'content-type': 'application/json' } }; return this.request(request, options); } /** * Send HTTP DELETE request * * Endpoint URL can be absolute URL ('https://na1.salesforce.com/services/data/v32.0/sobjects/Account/describe') * , relative path from root ('/services/data/v32.0/sobjects/Account/describe') * , or relative path from version root ('/sobjects/Account/describe'). */ }, { key: "requestDelete", value: function requestDelete(url, options) { var request = { method: 'DELETE', url: url }; return this.request(request, options); } /** @private **/ }, { key: "_baseUrl", value: function _baseUrl() { return [this.instanceUrl, 'services/data', "v".concat(this.version)].join('/'); } /** * Convert path to absolute url * @private */ }, { key: "_normalizeUrl", value: function _normalizeUrl(url) { if (_startsWithInstanceProperty(url).call(url, '/')) { if (_startsWithInstanceProperty(url).call(url, this.instanceUrl + '/services/')) { return url; } if (_startsWithInstanceProperty(url).call(url, '/services/')) { return this.instanceUrl + url; } return this._baseUrl() + url; } return url; } /** * */ }, { key: "query", value: function query(soql, options) { return new Query(this, soql, options); } /** * Execute search by SOSL * * @param {String} sosl - SOSL string * @param {Callback.<Array.<RecordResult>>} [callback] - Callback function * @returns {Promise.<Array.<RecordResult>>} */ }, { key: "search", value: function search(sosl) { var url = this._baseUrl() + '/search?q=' + encodeURIComponent(sosl); return this.request(url); } /** * */ }, { key: "queryMore", value: function queryMore(locator, options) { return new Query(this, { locator: locator }, options); } /* */ }, { key: "_ensureVersion", value: function _ensureVersion(majorVersion) { var versions = this.version.split('.'); return _parseInt(versions[0], 10) >= majorVersion; } /* */ }, { key: "_supports", value: function _supports(feature) { switch (feature) { case 'sobject-collection': // sobject collection is available only in API ver 42.0+ return this._ensureVersion(42); default: return false; } } /** * Retrieve specified records */ }, { key: "retrieve", value: function () { var _retrieve = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(type, ids) { var options, _args9 = arguments; return _regeneratorRuntime.wrap(function _callee9$(_context17) { while (1) switch (_context17.prev = _context17.next) { case 0: options = _args9.length > 2 && _args9[2] !== undefined ? _args9[2] : {}; return _context17.abrupt("return", _Array$isArray(ids) ? // check the version whether SObject collection API is supported (42.0) this._ensureVersion(42) ? this._retrieveMany(type, ids, options) : this._retrieveParallel(type, ids, options) : this._retrieveSingle(type, ids, options)); case 2: case "end": return _context17.stop(); } }, _callee9, this); })); function retrieve(_x15, _x16) { return _retrieve.apply(this, arguments); } return retrieve; }() /** @private */ }, { key: "_retrieveSingle", value: (function () { var _retrieveSingle2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee10(type, id, options) { var url, fields, headers; return _regeneratorRuntime.wrap(function _callee10$(_context18) { while (1) switch (_context18.prev = _context18.next) { case 0: if (id) { _context18.next = 2; break; } throw new Error('Invalid record ID. Specify valid record ID value'); case 2: url = [this._baseUrl(), 'sobjects', type, id].join('/'); fields = options.fields, headers = options.headers; if (fields) { url += "?fields=".concat(fields.join(',')); } return _context18.abrupt("return", this.request({ method: 'GET', url: url, headers: headers })); case 6: case "end": return _context18.stop(); } }, _callee10, this); })); function _retrieveSingle(_x17, _x18, _x19) { return _retrieveSingle2.apply(this, arguments); } return _retrieveSingle; }() /** @private */) }, { key: "_retrieveParallel", value: (function () { var _retrieveParallel2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee11(type, ids, options) { var _this4 = this; return _regeneratorRuntime.wrap(function _callee11$(_context19) { while (1) switch (_context19.prev = _context19.next) { case 0: if (!(ids.length > this._maxRequest)) { _context19.next = 2; break; } throw new Error('Exceeded max limit of concurrent call'); case 2: return _context19.abrupt("return", _Promise.all(_mapInstanceProperty(ids).call(ids, function (id) { return _this4._retrieveSingle(type, id, options).catch(function (err) { if (options.allOrNone || err.errorCode !== 'NOT_FOUND') { throw err; } return null; }); }))); case 3: case "end": return _context19.stop(); } }, _callee11, this); })); function _retrieveParallel(_x20, _x21, _x22) { return _retrieveParallel2.apply(this, arguments); } return _retrieveParallel; }() /** @private */) }, { key: "_retrieveMany", value: (function () { var _retrieveMany2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee12(type, ids, options) { var _context20; var url, fields; return _regeneratorRuntime.wrap(function _callee12$(_context21) { while (1) switch (_context21.prev = _context21.next) { case 0: if (!(ids.length === 0)) { _context21.next = 2; break; } return _context21.abrupt("return", []); case 2: url = [this._baseUrl(), 'composite', 'sobjects', type].join('/'); _context21.t0 = options.fields; if (_context21.t0) { _context21.next = 10; break; } _context21.t1 = _mapInstanceProperty; _context21.next = 8; return this.describe$(type); case 8: _context21.t2 = _context20 = _context21.sent.fields; _context21.t0 = (0, _context21.t1)(_context21.t2).call(_context20, function (field) { return field.name; }); case 10: fields = _context21.t0; return _context21.abrupt("return", this.request({ method: 'POST', url: url, body: _JSON$stringify({ ids: ids, fields: fields }), headers: _objectSpread(_objectSpread({}, options.headers || {}), {}, { 'content-type': 'application/json' }) })); case 12: case "end": return _context21.stop(); } }, _callee12, this); })); function _retrieveMany(_x23, _x24, _x25) { return _retrieveMany2.apply(this, arguments); } return _retrieveMany; }() /** * Create records */ ) }, { key: "create", value: ( /** * @param type * @param records * @param options */ function () { var _create = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee13(type, records) { var options, ret, _args13 = arguments; return _regeneratorRuntime.wrap(function _callee13$(_context22) { while (1) switch (_context22.prev = _context22.next) { case 0: options = _args13.length > 2 && _args13[2] !== undefined ? _args13[2] : {}; if (!_Array$isArray(records)) { _context22.next = 14; break; } if (!this._ensureVersion(42)) { _context22.next = 8; break; } _context22.next = 5; return this._createMany(type, records, options); case 5: _context22.t1 = _context22.sent; _context22.next = 11; break; case 8: _context22.next = 10; return this._createParallel(type, records, options); case 10: _context22.t1 = _context22.sent; case 11: _context22.t0 = _context22.t1; _context22.next = 17; break; case 14: _context22.next = 16; return this._createSingle(type, records, options); case 16: _context22.t0 = _context22.sent; case 17: ret = _context22.t0; return _context22.abrupt("return", ret); case 19: case "end": return _context22.stop(); } }, _callee13, this); })); function create(_x26, _x27) { return _create.apply(this, arguments); } return create; }() /** @private */) }, { key: "_createSingle", value: (function () { var _createSingle2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee14(type, record, options) { var Id, rtype, attributes, rec, sobjectType, url, contentType, body, _context23, form; return _regeneratorRuntime.wrap(function _callee14$(_context24) { while (1) switch (_context24.prev = _context24.next) { case 0: Id = record.Id, rtype = record.type, attributes = record.attributes, rec = _objectWithoutProperties(record, _excluded); sobjectType = type || (attributes === null || attributes === void 0 ? void 0 : attributes.type) || rtype; if (sobjectType) { _context24.next = 4; break; } throw new Error('No SObject Type defined in record'); case 4: url = [this._baseUrl(), 'sobjects', sobjectType].join('/'); if (options !== null && options !== void 0 && options.multipartFileFields) { // Send the record as a multipart/form-data request. Useful for fields containing large binary blobs. form = new FormData(); // Extract the fields requested to be sent separately from the JSON _forEachInstanceProperty(_context23 = _Object$entries(options.multipartFileFields)).call(_context23, function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), fieldName = _ref4[0], fileDetails = _ref4[1]; form.append(fieldName, Buffer.from(rec[fieldName], 'base64'), fileDetails); delete rec[fieldName]; }); // Serialize the remaining fields as JSON form.append(type, _JSON$stringify(rec), { contentType: 'application/json' }); contentType = form.getHeaders()['content-type']; // This is necessary to ensure the 'boundary' is present body = form; } else { // Default behavior: send the request as JSON contentType = 'application/json'; body = _JSON$stringify(rec); } return _context24.abrupt("return", this.request({ method: 'POST', url: url, body: body, headers: _objectSpread(_objectSpread({}, options.headers || {}), {}, { 'content-type': contentType }) })); case 7: case "end": return _context24.stop(); } }, _callee14, this); })); function _createSingle(_x28, _x29, _x30) { return _createSingle2.apply(this, arguments); } return _createSingle; }() /** @private */) }, { key: "_createParal