UNPKG

@aurahelper/connector

Version:

Powerfull Libraries to connect with Salesforce to list, describe, deploy or retrieve metadata types. Also can describe SObjects, Create Projects, Authorize Orgs, Execute Queries, Export or Import Data... To the correct work of this library, you need to ha

918 lines 156 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SFConnector = void 0; var events_1 = __importDefault(require("events")); var core_1 = require("@salesforce/core"); var metadata_factory_1 = require("@aurahelper/metadata-factory"); var package_generator_1 = require("@aurahelper/package-generator"); var xml_compressor_1 = require("@aurahelper/xml-compressor"); var languages_1 = require("@aurahelper/languages"); var core_2 = require("@aurahelper/core"); var XMLParser = languages_1.XML.XMLParser; var XMLUtils = languages_1.XML.XMLUtils; var Validator = core_2.CoreUtils.Validator; var StrUtils = core_2.CoreUtils.StrUtils; var OSUtils = core_2.CoreUtils.OSUtils; var Utils = core_2.CoreUtils.Utils; var MathUtils = core_2.CoreUtils.MathUtils; var MetadataUtils = core_2.CoreUtils.MetadataUtils; var ProjectUtils = core_2.CoreUtils.ProjectUtils; var xmlChars = { '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;' }; var PROJECT_NAME = 'TempProject'; var METADATA_QUERIES = { Report: 'Select Id, DeveloperName, NamespacePrefix, FolderName from Report', Dashboard: 'Select Id, DeveloperName, NamespacePrefix, FolderId from Dashboard', Document: 'Select Id, DeveloperName, NamespacePrefix, FolderId from Document', EmailTemplate: 'Select Id, DeveloperName, NamespacePrefix, FolderId FROM EmailTemplate' }; var SUBFOLDER_BY_METADATA_TYPE = { RecordType: 'recordTypes' }; var EVENT = { PREPARE: 'preapre', CREATE_PROJECT: 'createProject', RETRIEVE: 'retrieve', PROCESS: 'process', LOADING_LOCAL: 'loadingLocal', LOADING_ORG: 'loadingOrg', COPY_DATA: 'copyData', COPY_FILE: 'copyFile', COMPRESS_FILE: 'compressFile', BEFORE_DOWNLOAD_TYPE: 'beforeDownloadType', AFTER_DOWNLOAD_TYPE: 'afterDownloadType', BEFORE_DOWNLOAD_OBJECT: 'beforeDownloadSObj', AFTER_DOWNLOAD_OBJECT: 'afterDownloadSObj', DOWNLOAD_ERROR: 'onDownloadError', ABORT: 'abort', }; /** * Class to connect with Salesforce to list or describe metadata types, list or describe all SObjects, make queries, create SFDX Project, validate, * deploy or retrieve in SFDX and Metadata API Formats, export and import data and much more. * Is used to Aura Helper and Aura Helper CLI to support salesfore conections. * * The setters methods are defined like a builder pattern to make it more usefull * * All connection methods return a Promise with the associated data to the processes. */ var SFConnector = /** @class */ (function () { /** * Constructor to create a new connection object * @param {string} [usernameOrAlias] Org Username or Alias to connect. (Must be authorized in the system) * @param {string | number} [apiVersion] API Version number to connect with salesforce * @param {string} [projectFolder] Path to the project root folder * @param {string} [namespacePrefix] Namespace prefix from the Org to connect */ function SFConnector(usernameOrAlias, apiVersion, projectFolder, namespacePrefix) { this.usernameOrAlias = usernameOrAlias; this.apiVersion = apiVersion; this.projectFolder = (projectFolder !== undefined) ? core_2.PathUtils.getAbsolutePath(projectFolder) : projectFolder; this.namespacePrefix = (namespacePrefix !== undefined) ? namespacePrefix : ''; this.multiThread = false; if (!Utils.isNull(this.projectFolder)) { this.packageFolder = this.projectFolder + '/manifest'; this.packageFile = this.projectFolder + '/manifest/package.xml'; } this._processes = {}; this._inProgress = false; this._percentage = 0; this._increment = 0; this._abort = false; this._allowConcurrence = false; this._event = new events_1.default(); this._useAuraHelperSFDX = false; } SFConnector.prototype.useAuraHelperSFDX = function (useAuraHelperSFDX) { this._useAuraHelperSFDX = useAuraHelperSFDX === undefined ? true : useAuraHelperSFDX; }; /** * Method to set the Username or Alias to connect with org * @param {string} usernameOrAlias Org Username or Alias to connect. (Must be authorized in the system) * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.setUsernameOrAlias = function (usernameOrAlias) { this.usernameOrAlias = usernameOrAlias; return this; }; /** * Method to set the API Version to connect * @param {string | number} apiVersion API Version number to connect with salesforce * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.setApiVersion = function (apiVersion) { this.apiVersion = apiVersion; return this; }; /** * Method to set the project root folder path. When set the project root, automatically set the packageFolder and packageFile to their respective paths * @param {string} projectFolder Path to the project root folder * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.setProjectFolder = function (projectFolder) { this.projectFolder = (projectFolder !== undefined) ? core_2.PathUtils.getAbsolutePath(projectFolder) : projectFolder; this.packageFolder = this.projectFolder + '/manifest'; this.packageFile = this.projectFolder + '/manifest/package.xml'; return this; }; /** * Method to set the package folder path. When set the package folder, automatically set packageFile to the respective path * @param {string} packageFile Path to the package folder * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.setPackageFolder = function (packageFolder) { this.packageFolder = (packageFolder !== undefined) ? core_2.PathUtils.getAbsolutePath(packageFolder) : packageFolder; this.packageFile = this.projectFolder + '/manifest/package.xml'; return this; }; /** * Method to set the package xml file path * @param {string} packageFile Path to the package file * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.setPackageFile = function (packageFile) { this.packageFile = (packageFile !== undefined) ? core_2.PathUtils.getAbsolutePath(packageFile) : packageFile; return this; }; /** * Method to set the Org namespace prefix * @param {string} namespacePrefix Namespace prefix from the Org to connect * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.setNamespacePrefix = function (namespacePrefix) { this.namespacePrefix = (namespacePrefix !== undefined) ? namespacePrefix : ''; return this; }; /** * Method to able to the connection object to use several threads and processor cores to run some processes and run faster * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.setMultiThread = function () { this.multiThread = true; return this; }; /** * Method to set the connection object to use only one thread and processo core to all processes * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.setSingleThread = function () { this.multiThread = false; return this; }; /** * Method to handle the event when preparing execution of some processes * @param {Function} callback Callback function to call when connection is on prepare * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onPrepare = function (callback) { this._event.on(EVENT.PREPARE, callback); return this; }; /** * Method to handle the event before the create a project on some processes * @param {Function} callback Callback function to handle progress when connection will create a project * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onCreateProject = function (callback) { this._event.on(EVENT.CREATE_PROJECT, callback); return this; }; /** * Method to handle the event before start retrieve data on some processes * @param {Function} callback Callback function to handle progress when connection retrieve data * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onRetrieve = function (callback) { this._event.on(EVENT.RETRIEVE, callback); return this; }; /** * Method to handle the event before start processing results on some processes * @param {Function} callback Callback function to handle progress when connection is processing results * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onProcess = function (callback) { this._event.on(EVENT.PROCESS, callback); return this; }; /** * Method to handle the event before start loading local metadata types on some processes * @param {Function} callback Callback function to handle progress when connection load metadata types from local project * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onLoadingLocal = function (callback) { this._event.on(EVENT.LOADING_LOCAL, callback); return this; }; /** * Method to handle the event before start loading metadata types from org on some processes * @param {Function} callback Callback function to handle progress when connection load metadata types from connected org * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onLoadingOrg = function (callback) { this._event.on(EVENT.LOADING_ORG, callback); return this; }; /** * Method to handle the event before start copying files on some processes * @param {Function} callback Callback function to handle progress when connection start to copying files * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onCopyData = function (callback) { this._event.on(EVENT.COPY_DATA, callback); return this; }; /** * Method to handle the event before start copying file content on some processes * @param {Function} callback Callback function to handle progress when connection star to copy a single file * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onCopyFile = function (callback) { this._event.on(EVENT.COPY_FILE, callback); return this; }; /** * Method to handle the event before start compress XML File on some processes * @param {Function} callback Callback function to handle progress when start compress * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onCompressFile = function (callback) { this._event.on(EVENT.COMPRESS_FILE, callback); return this; }; /** * Method to handle the event before download a Metadata Type from Org on some processes * @param {Function} callback Callback function to handle progress when start download metadata type * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onBeforeDownloadType = function (callback) { this._event.on(EVENT.BEFORE_DOWNLOAD_TYPE, callback); return this; }; /** * Method to handle the event after download a Metadata Type from Org on some processes * @param {Function} callback Callback function to handle progress when metadata type is downloaded * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onAfterDownloadType = function (callback) { this._event.on(EVENT.AFTER_DOWNLOAD_TYPE, callback); return this; }; /** * Method to handle the event before download a SObject when describe SObejcts * @param {Function} callback Callback function to handle progress when start download sobject * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onBeforeDownloadSObject = function (callback) { this._event.on(EVENT.BEFORE_DOWNLOAD_OBJECT, callback); return this; }; /** * Method to handle the event after download a SObject when describe SObejcts * @param {Function} callback Callback function to handle progress when sobject is downloaded * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onAfterDownloadSObject = function (callback) { this._event.on(EVENT.AFTER_DOWNLOAD_OBJECT, callback); return this; }; /** * Method to handle the event when error ocurred when download metadata * @param {Function} callback Callback function to handle error * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onErrorDownload = function (callback) { this._event.on(EVENT.DOWNLOAD_ERROR, callback); return this; }; /** * Method to handle the event when connection is aborted * @param {Function} callback Callback function to call when connection is aborted * * @returns {SFConnector} Returns the connection object */ SFConnector.prototype.onAbort = function (callback) { this._event.on(EVENT.ABORT, callback); return this; }; /** * Method to abort all connection running processes. When finishes call onAbort() callback */ SFConnector.prototype.abortConnection = function () { this._abort = true; killProcesses(this); this._event.emit(EVENT.ABORT); }; /** * Method to get the username from an authorized org using a username or alias, or using connection username or alias, or using project auth org username or alias * @param {string} [usernameOrAlias] Username or alias to get auth username * * @returns {Promise<string | undefined>} Return a String promise with the Username or Alias data * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error */ SFConnector.prototype.getAuthUsername = function (usernameOrAlias) { return __awaiter(this, void 0, void 0, function () { var authOrg; return __generator(this, function (_a) { switch (_a.label) { case 0: usernameOrAlias = usernameOrAlias !== null && usernameOrAlias !== void 0 ? usernameOrAlias : this.usernameOrAlias; return [4 /*yield*/, this.getAuthOrg(usernameOrAlias)]; case 1: authOrg = _a.sent(); return [2 /*return*/, authOrg ? authOrg.username : undefined]; } }); }); }; /** * Method to get the server instance using a username or alias, or using connection username or alias, or using project auth org username or alias * @param {string} [usernameOrAlias] Username or alias to get the server instance * * @returns {Promise<string | undefined>} Return a String promise with the instance URL * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error */ SFConnector.prototype.getServerInstance = function (usernameOrAlias) { return __awaiter(this, void 0, void 0, function () { var authOrg; return __generator(this, function (_a) { switch (_a.label) { case 0: usernameOrAlias = usernameOrAlias !== null && usernameOrAlias !== void 0 ? usernameOrAlias : this.usernameOrAlias; return [4 /*yield*/, this.getAuthOrg(usernameOrAlias)]; case 1: authOrg = _a.sent(); return [2 /*return*/, authOrg ? authOrg.instanceUrl : undefined]; } }); }); }; /** * Method to get the auth org data using a username or alias, or using connection username or alias, or using project auth org username or alias * @param {string} [usernameOrAlias] Username or alias to get the auth org data * * @returns {Promise<AuthOrg | undefined>} Return a promise with Auth Org data or undefined if not exists * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error */ SFConnector.prototype.getAuthOrg = function (usernameOrAlias) { var _a, _b; return __awaiter(this, void 0, void 0, function () { var authOrgs, resultOrg, defaultUsername_1, _i, authOrgs_1, authOrg, orgAlias_1, orgAlias; return __generator(this, function (_c) { switch (_c.label) { case 0: usernameOrAlias = usernameOrAlias !== null && usernameOrAlias !== void 0 ? usernameOrAlias : this.usernameOrAlias; return [4 /*yield*/, core_1.AuthInfo.listAllAuthorizations()]; case 1: authOrgs = _c.sent(); if (authOrgs && authOrgs.length > 0) { defaultUsername_1 = usernameOrAlias || this.usernameOrAlias || ProjectUtils.getOrgAlias(Validator.validateFolderPath(this.projectFolder)); if (defaultUsername_1) { for (_i = 0, authOrgs_1 = authOrgs; _i < authOrgs_1.length; _i++) { authOrg = authOrgs_1[_i]; if (defaultUsername_1.indexOf('@') !== -1) { if (authOrg.username && authOrg.username.toLowerCase().trim() === defaultUsername_1.toLowerCase().trim()) { resultOrg = new core_2.AuthOrg(authOrg); } } else { orgAlias_1 = (_a = authOrg.aliases) === null || _a === void 0 ? void 0 : _a.find(function (alias) { return (alias === null || alias === void 0 ? void 0 : alias.toLowerCase().trim()) === defaultUsername_1.toLowerCase().trim(); }); if (orgAlias_1) { resultOrg = new core_2.AuthOrg(authOrg); } } orgAlias = (_b = authOrg.aliases) === null || _b === void 0 ? void 0 : _b.find(function (alias) { return (alias === null || alias === void 0 ? void 0 : alias.toLowerCase().trim()) === defaultUsername_1.toLowerCase().trim(); }); if (!resultOrg && ((authOrg.username && authOrg.username.toLowerCase().trim() === defaultUsername_1.toLowerCase().trim()) || orgAlias)) { resultOrg = new core_2.AuthOrg(authOrg); } } } return [2 /*return*/, resultOrg]; } else { return [2 /*return*/, undefined]; } return [2 /*return*/]; } }); }); }; /** * Method to list all auth org on the system * * @returns {Promise<AuthOrg[]>} Return a promise with all authorized org in the system * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error */ SFConnector.prototype.listAuthOrgs = function () { return __awaiter(this, void 0, void 0, function () { var orgs, authOrgs, _i, orgs_1, org; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, core_1.AuthInfo.listAllAuthorizations()]; case 1: orgs = _a.sent(); authOrgs = []; if (orgs) { for (_i = 0, orgs_1 = orgs; _i < orgs_1.length; _i++) { org = orgs_1[_i]; authOrgs.push(new core_2.AuthOrg(org)); } } return [2 /*return*/, authOrgs]; } }); }); }; /** * Method to execute a query to the connected org. Can return a Typed data (or use any to return any json) * @param {string} query Query to execute (Required) * @param {boolean} [useToolingApi] true to use Tooling API to execute the query * * @returns {Promise<any[]>} Return a promise with the record list * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error * @throws {DataRequiredException} If required data is not provided * @throws {OSNotSupportedException} When run this processes with not supported operative system */ SFConnector.prototype.query = function (query, useToolingApi) { return __awaiter(this, void 0, void 0, function () { var username, connection, _a, _b, _c, result, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: if (!this.usernameOrAlias) { throw new core_2.DataRequiredException('usernameOrAlias'); } return [4 /*yield*/, this.getAuthUsername()]; case 1: username = _e.sent(); if (!username) return [3 /*break*/, 8]; _b = (_a = core_1.Connection).create; _c = {}; return [4 /*yield*/, core_1.AuthInfo.create({ username: username })]; case 2: return [4 /*yield*/, _b.apply(_a, [(_c.authInfo = _e.sent(), _c)])]; case 3: connection = _e.sent(); if (!(useToolingApi)) return [3 /*break*/, 5]; return [4 /*yield*/, connection.tooling.query(query)]; case 4: _d = _e.sent(); return [3 /*break*/, 7]; case 5: return [4 /*yield*/, connection.query(query)]; case 6: _d = _e.sent(); _e.label = 7; case 7: result = _d; if (!result.records || result.records.length <= 0) { return [2 /*return*/, []]; } else { return [2 /*return*/, result.records]; } return [3 /*break*/, 9]; case 8: throw new core_2.ConnectionException('Not authorized org found with Username or Alias ' + this.usernameOrAlias); case 9: return [2 /*return*/]; } }); }); }; /** * Method to list all Metadata Types available in the connected org (according selected API Version) * * @returns {Promise<MetadataDetail[]>} Return a promise with the MetadataDetail objects from all available Metadata Types * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error * @throws {DataRequiredException} If required data is not provided * @throws {OSNotSupportedException} When run this processes with not supported operative system * @throws {WrongDatatypeException} If the api version is not a Number or String. Can be undefined */ SFConnector.prototype.listMetadataTypes = function () { return __awaiter(this, void 0, void 0, function () { var username, connection, _a, _b, _c, apiVersion, describeMetadata, metadataDetails; return __generator(this, function (_d) { switch (_d.label) { case 0: if (!this.usernameOrAlias) { throw new core_2.DataRequiredException('usernameOrAlias'); } return [4 /*yield*/, this.getAuthUsername()]; case 1: username = _d.sent(); if (!username) return [3 /*break*/, 5]; _b = (_a = core_1.Connection).create; _c = {}; return [4 /*yield*/, core_1.AuthInfo.create({ username: username })]; case 2: return [4 /*yield*/, _b.apply(_a, [(_c.authInfo = _d.sent(), _c)])]; case 3: connection = _d.sent(); apiVersion = this.apiVersion ? ProjectUtils.getApiAsString(this.apiVersion) : undefined; return [4 /*yield*/, connection.metadata.describe(apiVersion)]; case 4: describeMetadata = _d.sent(); metadataDetails = metadata_factory_1.MetadataFactory.createMetadataDetails(describeMetadata.metadataObjects); return [2 /*return*/, metadataDetails]; case 5: throw new core_2.ConnectionException('Not authorized org found with Username or Alias ' + this.usernameOrAlias); } }); }); }; /** * Method to describe all or selected Metadata Types from the connected org * @param {string[] | MetadataDetail[]} [typesOrDetails] List of Metadata Type API Names or Metadata Details to describe (undefined to describe all metadata types) * @param {boolean} [downloadAll] true to download all Metadata Types from the connected org, false to download only the org namespace Metadata Types * @param {boolean} [groupGlobalActions] True to group global quick actions on "GlobalActions" group, false to include as object and item. * * @returns {Promise<{ [key: string]: MetadataType }>} Return a promise with Metadata JSON Object with the selected Metadata Types to describe * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error * @throws {DataRequiredException} If required data is not provided * @throws {OSNotSupportedException} When run this processes with not supported operative system */ SFConnector.prototype.describeMetadataTypes = function (typesOrDetails, downloadAll, groupGlobalActions) { return __awaiter(this, void 0, void 0, function () { var username, connection, _a, _b, _c, metadataToProcess, foldersByType, metadata, promises, _i, metadataToProcess_1, metadataType, result, _d, result_1, metadataType; return __generator(this, function (_e) { switch (_e.label) { case 0: resetProgress(this); if (!this.usernameOrAlias) { throw new core_2.DataRequiredException('usernameOrAlias'); } return [4 /*yield*/, this.getAuthUsername()]; case 1: username = _e.sent(); if (!username) return [3 /*break*/, 7]; _b = (_a = core_1.Connection).create; _c = {}; return [4 /*yield*/, core_1.AuthInfo.create({ username: username })]; case 2: return [4 /*yield*/, _b.apply(_a, [(_c.authInfo = _e.sent(), _c)])]; case 3: connection = _e.sent(); metadataToProcess = getMetadataTypeNames(typesOrDetails); this._increment = calculateIncrement(metadataToProcess); callEvent(this, EVENT.PREPARE); foldersByType = void 0; if (!(metadataToProcess.includes(core_2.MetadataTypes.REPORT) || metadataToProcess.includes(core_2.MetadataTypes.DASHBOARD) || metadataToProcess.includes(core_2.MetadataTypes.EMAIL_TEMPLATE) || metadataToProcess.includes(core_2.MetadataTypes.DOCUMENT))) return [3 /*break*/, 5]; return [4 /*yield*/, getFoldersByType(this)]; case 4: foldersByType = _e.sent(); _e.label = 5; case 5: metadata = {}; promises = []; for (_i = 0, metadataToProcess_1 = metadataToProcess; _i < metadataToProcess_1.length; _i++) { metadataType = metadataToProcess_1[_i]; promises.push(downloadMetadataType(this, connection, metadataType, downloadAll, foldersByType, groupGlobalActions)); } return [4 /*yield*/, Promise.all(promises)]; case 6: result = _e.sent(); for (_d = 0, result_1 = result; _d < result_1.length; _d++) { metadataType = result_1[_d]; if (metadataType) { metadata[metadataType.name] = metadataType; } } return [2 /*return*/, metadata]; case 7: throw new core_2.ConnectionException('Not authorized org found with Username or Alias ' + this.usernameOrAlias); } }); }); }; /** * Method to list all SObjects API Name by category * @param {string} [category] Object Category. Values are: Standard, Custom, All. (All by default) * * @returns {Promise<string[]>} Return a promise with a list with the sObject names * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error * @throws {DataRequiredException} If required data is not provided * @throws {OSNotSupportedException} When run this processes with not supported operative system * @throws {WrongDatatypeException} If the api version is not a Number or String. Can be undefined */ SFConnector.prototype.listSObjects = function (category) { return __awaiter(this, void 0, void 0, function () { var username, sObjects, connection, _a, _b, _c, result, _i, _d, obj; return __generator(this, function (_e) { switch (_e.label) { case 0: if (!this.usernameOrAlias) { throw new core_2.DataRequiredException('usernameOrAlias'); } return [4 /*yield*/, this.getAuthUsername()]; case 1: username = _e.sent(); if (!username) return [3 /*break*/, 5]; sObjects = []; _b = (_a = core_1.Connection).create; _c = {}; return [4 /*yield*/, core_1.AuthInfo.create({ username: username })]; case 2: return [4 /*yield*/, _b.apply(_a, [(_c.authInfo = _e.sent(), _c)])]; case 3: connection = _e.sent(); return [4 /*yield*/, connection.describeGlobal()]; case 4: result = _e.sent(); if (result.sobjects) { for (_i = 0, _d = result.sobjects; _i < _d.length; _i++) { obj = _d[_i]; if (obj.queryable) { if (!category || category.toLowerCase() === 'all') { sObjects.push(obj.name); } else if (!obj.custom && category.toLowerCase() === 'standard') { sObjects.push(obj.name); } else if (obj.custom && category.toLowerCase() === 'custom') { sObjects.push(obj.name); } } } } return [2 /*return*/, sObjects]; case 5: throw new core_2.ConnectionException('Not authorized org found with Username or Alias ' + this.usernameOrAlias); } }); }); }; /** * Method to describe SObject data to the specified objects * @param {string | string[]} sObjects List with the object API Names to describe * * @returns {Promise<{ [key: string]: SObject }>} Return a promise with a SObjects data * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error * @throws {DataRequiredException} If required data is not provided * @throws {OSNotSupportedException} When run this processes with not supported operative system */ SFConnector.prototype.describeSObjects = function (sObjects) { return __awaiter(this, void 0, void 0, function () { var username, connection, _a, _b, _c, resultObjects, promises, _i, sObjects_1, sObject, result, _d, result_2, sObject; return __generator(this, function (_e) { switch (_e.label) { case 0: resetProgress(this); if (!this.usernameOrAlias) { throw new core_2.DataRequiredException('usernameOrAlias'); } return [4 /*yield*/, this.getAuthUsername()]; case 1: username = _e.sent(); _b = (_a = core_1.Connection).create; _c = {}; return [4 /*yield*/, core_1.AuthInfo.create({ username: username })]; case 2: return [4 /*yield*/, _b.apply(_a, [(_c.authInfo = _e.sent(), _c)])]; case 3: connection = _e.sent(); if (!username) return [3 /*break*/, 5]; sObjects = Utils.forceArray(sObjects); this._increment = calculateIncrement(sObjects); callEvent(this, EVENT.PREPARE); resultObjects = {}; promises = []; for (_i = 0, sObjects_1 = sObjects; _i < sObjects_1.length; _i++) { sObject = sObjects_1[_i]; promises.push(downloadSObject(this, connection, sObject)); } return [4 /*yield*/, Promise.all(promises)]; case 4: result = _e.sent(); for (_d = 0, result_2 = result; _d < result_2.length; _d++) { sObject = result_2[_d]; if (sObject) { resultObjects[sObject.name] = sObject; } } return [2 /*return*/, resultObjects]; case 5: throw new core_2.ConnectionException('Not authorized org found with Username or Alias ' + this.usernameOrAlias); } }); }); }; /** * Method to retrieve data using the connection package file. You can choose to retrieve as Metadata API format or Source Format * @param {boolean} useMetadataAPI True to use Metadata API format, false to use source format * @param {string} [targetDir] Path to the target dir when retrieve with Metadata API Format * @param {string | number} [waitMinutes] Number of minutes to wait for the command to complete and display results * * @returns {Promise<RetrieveResult>} Return a promise with the RetrieveResult object with the retrieve result * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error * @throws {DataRequiredException} If required data is not provided * @throws {OSNotSupportedException} When run this processes with not supported operative system * @throws {WrongDirectoryPathException} If the project folder or target dir is not a String or can't convert to absolute path * @throws {DirectoryNotFoundException} If the project folder or target dir not exists or not have access to it * @throws {InvalidDirectoryPathException} If the project folder or target dir is not a directory * @throws {WrongDatatypeException} If the api version is not a Number or String. Can be undefined */ SFConnector.prototype.retrieve = function (useMetadataAPI, targetDir, waitMinutes) { return __awaiter(this, void 0, void 0, function () { var process_1, projectFolder, packageFolder, packageFile, response, _a, status_1, error_1; return __generator(this, function (_b) { switch (_b.label) { case 0: startOperation(this); resetProgress(this); _b.label = 1; case 1: _b.trys.push([1, 3, , 4]); if (!this.usernameOrAlias) { throw new core_2.DataRequiredException('usernameOrAlias'); } projectFolder = Validator.validateFolderPath(this.projectFolder); if (useMetadataAPI) { targetDir = Validator.validateFolderPath(targetDir); packageFolder = Validator.validateFolderPath(this.packageFolder); if (this._useAuraHelperSFDX) { process_1 = core_2.ProcessFactory.mdapiRetrievePackageSFDX(this.usernameOrAlias, packageFolder, projectFolder, targetDir, this.apiVersion, waitMinutes); } else { process_1 = core_2.ProcessFactory.mdapiRetrievePackageSF(this.usernameOrAlias, packageFolder, projectFolder, targetDir, this.apiVersion, waitMinutes); } } else { packageFile = Validator.validateFilePath(this.packageFile); if (this._useAuraHelperSFDX) { process_1 = core_2.ProcessFactory.sourceRetrievePackageSFDX(this.usernameOrAlias, packageFile, projectFolder, this.apiVersion, waitMinutes); } else { process_1 = core_2.ProcessFactory.sourceRetrievePackageSF(this.usernameOrAlias, packageFile, projectFolder, this.apiVersion, waitMinutes); } } addProcess(this, process_1); _a = this.handleResponse; return [4 /*yield*/, core_2.ProcessHandler.runProcess(process_1)]; case 2: response = _a.apply(this, [_b.sent()]); status_1 = new core_2.RetrieveResult(response.result); endOperation(this); return [2 /*return*/, status_1]; case 3: error_1 = _b.sent(); endOperation(this); throw error_1; case 4: return [2 /*return*/]; } }); }); }; /** * Retrieve report when use Metadata API to retrieve data * @param {string} retrieveId Retrieve Id to get the report (Required) * @param {string} targetDir Path to the target dir (Required) * * @returns {Promise<RetrieveStatus>} Return a promise with the RetrieveStatus object with the retrieve status result * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error * @throws {DataRequiredException} If required data is not provided * @throws {OSNotSupportedException} When run this processes with not supported operative system * @throws {WrongDirectoryPathException} If the target dir is not a String or can't convert to absolute path * @throws {DirectoryNotFoundException} If the target dir not exists or not have access to it * @throws {InvalidDirectoryPathException} If the target dir is not a directory */ SFConnector.prototype.retrieveReport = function (retrieveId, targetDir) { var _a; return __awaiter(this, void 0, void 0, function () { var process_2, response, _b, status_2, error_2, err, error_3; return __generator(this, function (_c) { switch (_c.label) { case 0: startOperation(this); resetProgress(this); _c.label = 1; case 1: _c.trys.push([1, 6, , 7]); if (!this.usernameOrAlias) { throw new core_2.DataRequiredException('usernameOrAlias'); } this._allowConcurrence = true; targetDir = Validator.validateFolderPath(targetDir); process_2 = this._useAuraHelperSFDX ? core_2.ProcessFactory.mdapiRetrieveReportSFDX(this.usernameOrAlias, retrieveId, targetDir) : core_2.ProcessFactory.mdapiRetrieveReportSF(this.usernameOrAlias, retrieveId, targetDir); addProcess(this, process_2); _c.label = 2; case 2: _c.trys.push([2, 4, , 5]); _b = this.handleResponse; return [4 /*yield*/, core_2.ProcessHandler.runProcess(process_2)]; case 3: response = _b.apply(this, [_c.sent()]); status_2 = new core_2.RetrieveStatus(response.result); this._allowConcurrence = false; endOperation(this); return [2 /*return*/, status_2]; case 4: error_2 = _c.sent(); err = error_2; this._allowConcurrence = false; if (((_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.indexOf('Retrieve result has been deleted')) !== -1) { return [2 /*return*/, new core_2.RetrieveStatus(retrieveId, 'Succeeded', true, true)]; } endOperation(this); throw error_2; case 5: return [3 /*break*/, 7]; case 6: error_3 = _c.sent(); this._allowConcurrence = false; endOperation(this); throw error_3; case 7: return [2 /*return*/]; } }); }); }; /** * Method to validate a deploy against the org using the connection package file * @param {string} [testLevel] Level of deployment tests to run. Values are 'NoTestRun', 'RunSpecifiedTests', 'RunLocalTests', 'RunAllTestsInOrg' * @param {string | string[]} [runTests] String with comma separated test names to execute or list with the test names to execute * @param {boolean} [useMetadataAPI] True to validate deploy using Metadata API Format, false to use Source Format * @param {string | number} [waitMinutes] Number of minutes to wait for the command to complete and display results * * @returns {Promise<DeployStatus>} Return a promise with the DeployStatus object with the deploy status result * * @throws {ConnectionException} If run other connection process when has one process running or Connection Return an error * @throws {DataRequiredException} If required data is not provided * @throws {OSNotSupportedException} When run this processes with not supported operative system * @throws {WrongDirectoryPathException} If the project folder or package folder is not a String or can't convert to absolute path * @throws {DirectoryNotFoundException} If the project folder or package folder not exists or not have access to it * @throws {InvalidDirectoryPathException} If the project folder or package folder is not a directory * @throws {WrongFilePathException} If the package file is not a String or can't convert to absolute path * @throws {FileNotFoundException} If the package file not exists or not have access to it * @throws {InvalidFilePathException} If the package file is not a file * @throws {WrongDatatypeException} If the api version is not a Number or String. Can be undefined */ SFConnector.prototype.vali