@salesforce/core 3.7.4 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +215 -0
  2. package/lib/config/configStore.js +2 -1
  3. package/lib/config/envVars.d.ts +20 -5
  4. package/lib/config/envVars.js +70 -5
  5. package/lib/crypto/keyChainImpl.js +0 -1
  6. package/lib/exported.d.ts +4 -2
  7. package/lib/exported.js +5 -1
  8. package/lib/lifecycleEvents.js +1 -1
  9. package/lib/logger.js +0 -1
  10. package/lib/org/authInfo.js +2 -3
  11. package/lib/org/connection.d.ts +6 -1
  12. package/lib/org/connection.js +13 -0
  13. package/lib/org/org.d.ts +12 -2
  14. package/lib/org/org.js +39 -36
  15. package/lib/org/scratchOrgCreate.d.ts +43 -0
  16. package/lib/org/scratchOrgCreate.js +142 -0
  17. package/lib/org/scratchOrgErrorCodes.d.ts +4 -0
  18. package/lib/org/scratchOrgErrorCodes.js +62 -0
  19. package/lib/org/scratchOrgFeatureDeprecation.d.ts +26 -0
  20. package/lib/org/scratchOrgFeatureDeprecation.js +110 -0
  21. package/lib/org/scratchOrgInfoApi.d.ts +94 -0
  22. package/lib/org/scratchOrgInfoApi.js +350 -0
  23. package/lib/org/scratchOrgInfoGenerator.d.ts +63 -0
  24. package/lib/org/scratchOrgInfoGenerator.js +223 -0
  25. package/lib/org/scratchOrgSettingsGenerator.d.ts +56 -0
  26. package/lib/org/scratchOrgSettingsGenerator.js +210 -0
  27. package/lib/org/user.js +4 -3
  28. package/lib/status/pollingClient.d.ts +2 -2
  29. package/lib/status/pollingClient.js +8 -2
  30. package/lib/status/streamingClient.d.ts +1 -1
  31. package/lib/util/jsonXmlTools.d.ts +14 -0
  32. package/lib/util/jsonXmlTools.js +41 -0
  33. package/lib/util/mapKeys.d.ts +14 -0
  34. package/lib/util/mapKeys.js +48 -0
  35. package/lib/util/zipWriter.d.ts +14 -0
  36. package/lib/util/zipWriter.js +68 -0
  37. package/lib/webOAuthServer.js +1 -1
  38. package/messages/envVars.md +53 -13
  39. package/messages/org.md +4 -0
  40. package/messages/scratchOrgCreate.md +27 -0
  41. package/messages/scratchOrgErrorCodes.md +99 -0
  42. package/messages/scratchOrgFeatureDeprecation.md +11 -0
  43. package/messages/scratchOrgInfoApi.md +11 -0
  44. package/messages/scratchOrgInfoGenerator.md +19 -0
  45. package/messages/user.md +4 -0
  46. package/package.json +5 -1
package/lib/org/org.js CHANGED
@@ -15,16 +15,17 @@ const configAggregator_1 = require("../config/configAggregator");
15
15
  const orgUsersConfig_1 = require("../config/orgUsersConfig");
16
16
  const sandboxOrgConfig_1 = require("../config/sandboxOrgConfig");
17
17
  const global_1 = require("../global");
18
+ const lifecycleEvents_1 = require("../lifecycleEvents");
18
19
  const logger_1 = require("../logger");
19
20
  const sfdxError_1 = require("../sfdxError");
20
21
  const fs_1 = require("../util/fs");
21
22
  const sfdc_1 = require("../util/sfdc");
22
- const globalInfo_1 = require("../globalInfo");
23
- const messages_1 = require("../messages");
24
- const lifecycleEvents_1 = require("../lifecycleEvents");
25
23
  const webOAuthServer_1 = require("../webOAuthServer");
24
+ const messages_1 = require("../messages");
25
+ const globalInfo_1 = require("../globalInfo");
26
26
  const connection_1 = require("./connection");
27
27
  const authInfo_1 = require("./authInfo");
28
+ const scratchOrgCreate_1 = require("./scratchOrgCreate");
28
29
  const orgConfigProperties_1 = require("./orgConfigProperties");
29
30
  messages_1.Messages.importMessagesDirectory(__dirname);
30
31
  const messages = messages_1.Messages.load('@salesforce/core', 'org', [
@@ -114,6 +115,16 @@ class Org extends kit_1.AsyncOptionalCreatable {
114
115
  pollInterval,
115
116
  });
116
117
  }
118
+ /**
119
+ * Creates a scratchOrg
120
+ * 'this' needs to be a valid dev-hub
121
+ *
122
+ * @param {options} ScratchOrgCreateOptions
123
+ * @returns {ScratchOrgCreateResult}
124
+ */
125
+ async scratchOrgCreate(options) {
126
+ return (0, scratchOrgCreate_1.scratchOrgCreate)({ ...options, hubOrg: this });
127
+ }
117
128
  /**
118
129
  * Clean all data files in the org's data path. Usually <workspace>/.sfdx/orgs/<username>.
119
130
  *
@@ -593,10 +604,10 @@ class Org extends kit_1.AsyncOptionalCreatable {
593
604
  async queryProduction(org, field, value) {
594
605
  return org.connection.singleRecordQuery(`SELECT SandboxInfoId FROM SandboxProcess WHERE ${field} ='${value}' AND Status NOT IN ('D', 'E')`, { tooling: true });
595
606
  }
596
- async destorySandbox(org, id) {
607
+ async destroySandbox(org, id) {
597
608
  return org.getConnection().tooling.delete('SandboxInfo', id);
598
609
  }
599
- async destoryScratchOrg(org, id) {
610
+ async destroyScratchOrg(org, id) {
600
611
  return org.getConnection().delete('ActiveScratchOrg', id);
601
612
  }
602
613
  /**
@@ -641,7 +652,7 @@ class Org extends kit_1.AsyncOptionalCreatable {
641
652
  }
642
653
  }
643
654
  // const deleteResult = await prodOrg.connection.tooling.delete('SandboxInfo', result.SandboxInfoId);
644
- const deleteResult = await this.destorySandbox(prodOrg, result.SandboxInfoId);
655
+ const deleteResult = await this.destroySandbox(prodOrg, result.SandboxInfoId);
645
656
  this.logger.debug('Return from calling tooling.delete: %o ', deleteResult);
646
657
  await this.remove();
647
658
  if (Array.isArray(deleteResult) || !deleteResult.success) {
@@ -669,7 +680,7 @@ class Org extends kit_1.AsyncOptionalCreatable {
669
680
  const username = this.getUsername();
670
681
  const activeScratchOrgRecordId = (await devHubConn.singleRecordQuery(`SELECT Id FROM ActiveScratchOrg WHERE SignupUsername='${username}'`)).Id;
671
682
  this.logger.trace(`found matching ActiveScratchOrg with SignupUsername: ${username}. Deleting...`);
672
- await this.destoryScratchOrg(devHub, activeScratchOrgRecordId);
683
+ await this.destroyScratchOrg(devHub, activeScratchOrgRecordId);
673
684
  await this.remove();
674
685
  }
675
686
  catch (err) {
@@ -703,7 +714,6 @@ class Org extends kit_1.AsyncOptionalCreatable {
703
714
  this.logger.debug(`Clearing auth cache for user: ${username}`);
704
715
  config.orgs.unset(username);
705
716
  }
706
- await config.write();
707
717
  }
708
718
  /**
709
719
  * Deletes the users config file
@@ -743,34 +753,27 @@ class Org extends kit_1.AsyncOptionalCreatable {
743
753
  this.logger.debug(`Removing users associate with org: ${this.getOrgId()}`);
744
754
  const config = await this.retrieveOrgUsersConfig();
745
755
  this.logger.debug(`using path for org users: ${config.getPath()}`);
746
- if (await config.exists()) {
747
- const authInfos = await this.readUserAuthFiles();
748
- this.logger.info(`Cleaning up usernames in org: ${this.getOrgId()}`);
749
- for (const auth of authInfos) {
750
- const username = auth.getFields().username;
751
- const aliases = (username && globalInfo.aliases.getAll(username)) || [];
752
- globalInfo.aliases.unsetAll(username);
753
- let orgForUser;
754
- if (username === this.getUsername()) {
755
- orgForUser = this;
756
- }
757
- else {
758
- const info = await authInfo_1.AuthInfo.create({ username });
759
- const connection = await connection_1.Connection.create({ authInfo: info });
760
- orgForUser = await Org.create({ connection });
761
- }
762
- const removeConfig = async (configInfo) => {
763
- if ((configInfo.value === username || aliases.includes(configInfo.value)) &&
764
- (configInfo.isGlobal() || configInfo.isLocal())) {
765
- await config_1.Config.update(configInfo.isGlobal(), configInfo.key, undefined);
766
- }
767
- };
768
- await removeConfig(this.configAggregator.getInfo(orgConfigProperties_1.OrgConfigProperties.TARGET_DEV_HUB));
769
- await removeConfig(this.configAggregator.getInfo(orgConfigProperties_1.OrgConfigProperties.TARGET_ORG));
770
- await orgForUser.removeAuth();
771
- }
772
- await globalInfo.write();
773
- }
756
+ const authInfos = await this.readUserAuthFiles();
757
+ await Promise.all(authInfos
758
+ .map((auth) => auth.getFields().username)
759
+ .map(async (username) => {
760
+ const aliasKeys = (username && globalInfo.aliases.getAll(username)) || [];
761
+ globalInfo.aliases.unsetAll(username);
762
+ const orgForUser = username === this.getUsername()
763
+ ? this
764
+ : await Org.create({
765
+ connection: await connection_1.Connection.create({ authInfo: await authInfo_1.AuthInfo.create({ username }) }),
766
+ });
767
+ const orgType = this.isDevHubOrg() ? orgConfigProperties_1.OrgConfigProperties.TARGET_DEV_HUB : orgConfigProperties_1.OrgConfigProperties.TARGET_ORG;
768
+ const configInfo = orgForUser.configAggregator.getInfo(orgType);
769
+ const needsConfigUpdate = (configInfo.isGlobal() || configInfo.isLocal()) &&
770
+ (configInfo.value === username || aliasKeys.includes(configInfo.value));
771
+ return [
772
+ orgForUser.removeAuth(),
773
+ needsConfigUpdate ? config_1.Config.update(configInfo.isGlobal(), orgType, undefined) : undefined,
774
+ ].filter(Boolean);
775
+ }));
776
+ await globalInfo.write();
774
777
  }
775
778
  /**
776
779
  * Remove an associate sandbox config.
@@ -0,0 +1,43 @@
1
+ import { Duration } from '@salesforce/kit';
2
+ import { Org } from './org';
3
+ import { ScratchOrgInfo } from './scratchOrgInfoApi';
4
+ import { AuthFields, AuthInfo } from './authInfo';
5
+ export declare const DEFAULT_STREAM_TIMEOUT_MINUTES = 6;
6
+ export interface ScratchOrgCreateResult {
7
+ username?: string;
8
+ scratchOrgInfo?: ScratchOrgInfo;
9
+ authInfo?: AuthInfo;
10
+ authFields?: AuthFields;
11
+ warnings: string[];
12
+ }
13
+ /**
14
+ * interface ScratchOrgCreateOptions
15
+ *
16
+ * @param hubOrg the environment hub org
17
+ * @param connectedAppConsumerKey The connected app consumer key.
18
+ * @param durationDays duration of the scratch org (in days) (default:1, min:1, max:30)
19
+ * @param nonamespace create the scratch org with no namespace
20
+ * @param noancestors do not include second-generation package ancestors in the scratch org
21
+ * @param wait the streaming client socket timeout (in minutes) must be an instance of the Duration utility class (default:6, min:2)
22
+ * @param retry number of scratch org auth retries after scratch org is successfully signed up (default:0, min:0, max:10)
23
+ * @param apiversion target server instance API version
24
+ * @param definitionjson org definition in JSON format
25
+ * @param definitionfile path to an org definition file
26
+ * @param orgConfig overrides definitionjson
27
+ * @param clientSecret OAuth client secret of personal connected app
28
+ */
29
+ export interface ScratchOrgCreateOptions {
30
+ hubOrg: Org;
31
+ connectedAppConsumerKey?: string;
32
+ durationDays?: number;
33
+ nonamespace?: boolean;
34
+ noancestors?: boolean;
35
+ wait?: Duration;
36
+ retry?: number;
37
+ apiversion?: string;
38
+ definitionjson?: string;
39
+ definitionfile?: string;
40
+ orgConfig?: Record<string, unknown>;
41
+ clientSecret?: string;
42
+ }
43
+ export declare const scratchOrgCreate: (options: ScratchOrgCreateOptions) => Promise<ScratchOrgCreateResult>;
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scratchOrgCreate = exports.DEFAULT_STREAM_TIMEOUT_MINUTES = void 0;
4
+ /*
5
+ * Copyright (c) 2020, salesforce.com, inc.
6
+ * All rights reserved.
7
+ * Licensed under the BSD 3-Clause license.
8
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
9
+ */
10
+ const kit_1 = require("@salesforce/kit");
11
+ const ts_types_1 = require("@salesforce/ts-types");
12
+ const messages_1 = require("../messages");
13
+ const logger_1 = require("../logger");
14
+ const configAggregator_1 = require("../config/configAggregator");
15
+ const sfdxProject_1 = require("../sfdxProject");
16
+ const sfdxError_1 = require("../sfdxError");
17
+ const org_1 = require("./org");
18
+ const scratchOrgInfoApi_1 = require("./scratchOrgInfoApi");
19
+ const scratchOrgSettingsGenerator_1 = require("./scratchOrgSettingsGenerator");
20
+ const scratchOrgInfoGenerator_1 = require("./scratchOrgInfoGenerator");
21
+ const connection_1 = require("./connection");
22
+ messages_1.Messages.importMessagesDirectory(__dirname);
23
+ const messages = messages_1.Messages.load('@salesforce/core', 'scratchOrgCreate', [
24
+ 'SourceStatusResetFailureError',
25
+ 'DurationDaysValidationMaxError',
26
+ 'DurationDaysValidationMinError',
27
+ 'RetryNotIntError',
28
+ 'WaitValidationMaxError',
29
+ 'DurationDaysNotIntError',
30
+ ]);
31
+ exports.DEFAULT_STREAM_TIMEOUT_MINUTES = 6;
32
+ const validateDuration = (durationDays) => {
33
+ const min = 1;
34
+ const max = 30;
35
+ if (Number.isInteger(durationDays)) {
36
+ if (durationDays < min) {
37
+ throw messages.createError('DurationDaysValidationMinError', [min, durationDays]);
38
+ }
39
+ if (durationDays > max) {
40
+ throw messages.createError('DurationDaysValidationMaxError', [max, durationDays]);
41
+ }
42
+ return;
43
+ }
44
+ throw messages.createError('DurationDaysNotIntError');
45
+ };
46
+ const validateRetry = (retry) => {
47
+ if (!Number.isInteger(retry)) {
48
+ throw messages.createError('RetryNotIntError');
49
+ }
50
+ };
51
+ const validateWait = (wait) => {
52
+ const min = 2;
53
+ if (wait.minutes < min) {
54
+ throw messages.createError('WaitValidationMaxError', [min, wait.minutes]);
55
+ }
56
+ };
57
+ const scratchOrgCreate = async (options) => {
58
+ var _a;
59
+ const logger = await logger_1.Logger.child('scratchOrgCreate');
60
+ logger.debug('scratchOrgCreate');
61
+ const { hubOrg, connectedAppConsumerKey, durationDays = 1, nonamespace, noancestors, wait = kit_1.Duration.minutes(exports.DEFAULT_STREAM_TIMEOUT_MINUTES), retry = 0, apiversion, definitionjson, definitionfile, orgConfig, clientSecret = undefined, } = options;
62
+ validateDuration(durationDays);
63
+ validateRetry(retry);
64
+ validateWait(wait);
65
+ const { scratchOrgInfoPayload, ignoreAncestorIds, warnings } = await (0, scratchOrgInfoGenerator_1.getScratchOrgInfoPayload)({
66
+ definitionjson,
67
+ definitionfile,
68
+ connectedAppConsumerKey,
69
+ durationDays,
70
+ nonamespace,
71
+ noancestors,
72
+ orgConfig,
73
+ });
74
+ const scratchOrgInfo = await (0, scratchOrgInfoGenerator_1.generateScratchOrgInfo)({
75
+ hubOrg,
76
+ scratchOrgInfoPayload,
77
+ nonamespace,
78
+ ignoreAncestorIds,
79
+ });
80
+ // gets the scratch org settings (will use in both signup paths AND to deploy the settings)
81
+ const settingsGenerator = new scratchOrgSettingsGenerator_1.default();
82
+ await settingsGenerator.extract(scratchOrgInfo);
83
+ logger.debug(`the scratch org def file has settings: ${settingsGenerator.hasSettings()}`);
84
+ // creates the scratch org info in the devhub
85
+ const scratchOrgInfoRequestResult = await (0, scratchOrgInfoApi_1.requestScratchOrgCreation)(hubOrg, scratchOrgInfo, settingsGenerator);
86
+ const scratchOrgInfoId = (0, ts_types_1.ensureString)((0, ts_types_1.getString)(scratchOrgInfoRequestResult, 'id'));
87
+ logger.debug(`scratch org has recordId ${scratchOrgInfoId}`);
88
+ const scratchOrgInfoResult = await (0, scratchOrgInfoApi_1.pollForScratchOrgInfo)(hubOrg, scratchOrgInfoId, wait);
89
+ const signupTargetLoginUrlConfig = await getSignupTargetLoginUrl();
90
+ const scratchOrgAuthInfo = await (0, scratchOrgInfoApi_1.authorizeScratchOrg)({
91
+ scratchOrgInfoComplete: scratchOrgInfoResult,
92
+ hubOrg,
93
+ clientSecret,
94
+ signupTargetLoginUrlConfig,
95
+ retry: retry || 0,
96
+ });
97
+ // we'll need this scratch org connection later;
98
+ const connection = await connection_1.Connection.create({ authInfo: scratchOrgAuthInfo });
99
+ const scratchOrg = await org_1.Org.create({ connection }); // scartchOrg should come from command
100
+ const username = scratchOrg.getUsername();
101
+ logger.debug(`scratch org username ${username}`);
102
+ const configAggregator = new configAggregator_1.ConfigAggregator();
103
+ const authInfo = await (0, scratchOrgInfoApi_1.deploySettingsAndResolveUrl)(scratchOrgAuthInfo, (_a = apiversion !== null && apiversion !== void 0 ? apiversion : configAggregator.getPropertyValue('apiVersion')) !== null && _a !== void 0 ? _a : (await scratchOrg.retrieveMaxApiVersion()), settingsGenerator, scratchOrg);
104
+ logger.trace('Settings deployed to org');
105
+ /** updating the revision num to zero during org:creation if source members are created during org:create.This only happens for some specific scratch org definition file.*/
106
+ await updateRevisionCounterToZero(scratchOrg);
107
+ return {
108
+ username,
109
+ scratchOrgInfo: scratchOrgInfoResult,
110
+ authInfo,
111
+ authFields: authInfo === null || authInfo === void 0 ? void 0 : authInfo.getFields(),
112
+ warnings,
113
+ };
114
+ };
115
+ exports.scratchOrgCreate = scratchOrgCreate;
116
+ const getSignupTargetLoginUrl = async () => {
117
+ try {
118
+ const project = await sfdxProject_1.SfdxProject.resolve();
119
+ const projectJson = await project.resolveProjectConfig();
120
+ return projectJson.signupTargetLoginUrl;
121
+ }
122
+ catch {
123
+ // a project isn't required for org:create
124
+ }
125
+ };
126
+ const updateRevisionCounterToZero = async (scratchOrg) => {
127
+ const conn = scratchOrg.getConnection();
128
+ const queryResult = await conn.tooling.sobject('SourceMember').find({ RevisionCounter: { $gt: 0 } }, ['Id']);
129
+ try {
130
+ await conn.tooling
131
+ .sobject('SourceMember')
132
+ .update(queryResult.map((record) => ({ Id: record.Id, RevisionCounter: 0 })));
133
+ }
134
+ catch (err) {
135
+ const message = messages.getMessage('SourceStatusResetFailureError', [
136
+ scratchOrg.getOrgId(),
137
+ scratchOrg.getUsername(),
138
+ ]);
139
+ throw new sfdxError_1.SfdxError(message, 'SourceStatusResetFailure');
140
+ }
141
+ };
142
+ //# sourceMappingURL=scratchOrgCreate.js.map
@@ -0,0 +1,4 @@
1
+ import { Optional } from '@salesforce/ts-types';
2
+ import { Logger } from '../logger';
3
+ import { ScratchOrgInfo } from './scratchOrgInfoApi';
4
+ export declare const checkScratchOrgInfoForErrors: (orgInfo: Optional<ScratchOrgInfo>, hubUsername: Optional<string>, logger: Logger) => ScratchOrgInfo;
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2021, salesforce.com, inc.
4
+ * All rights reserved.
5
+ * Licensed under the BSD 3-Clause license.
6
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.checkScratchOrgInfoForErrors = void 0;
10
+ const messages_1 = require("../messages");
11
+ const sfdxError_1 = require("../sfdxError");
12
+ const WORKSPACE_CONFIG_FILENAME = 'sfdx-project.json';
13
+ messages_1.Messages.importMessagesDirectory(__dirname);
14
+ const messages = messages_1.Messages.loadMessages('@salesforce/core', 'scratchOrgErrorCodes');
15
+ const namedMessages = messages_1.Messages.load('@salesforce/core', 'scratchOrgErrorCodes', [
16
+ 'SignupFailedActionError',
17
+ 'SignupFailedUnknownError',
18
+ 'SignupFailedError',
19
+ 'SignupUnexpectedError',
20
+ ]);
21
+ // getMessage will throw when the code isn't found
22
+ // and we don't know whether a given code takes arguments or not
23
+ const optionalErrorCodeMessage = (errorCode, args) => {
24
+ try {
25
+ // only apply args if message requires them
26
+ let message = messages.getMessage(errorCode);
27
+ if (message.includes('%s')) {
28
+ message = messages.getMessage(errorCode, args);
29
+ }
30
+ return message;
31
+ }
32
+ catch {
33
+ // generic error message
34
+ return undefined;
35
+ }
36
+ };
37
+ const checkScratchOrgInfoForErrors = (orgInfo, hubUsername, logger) => {
38
+ if (!orgInfo) {
39
+ throw new sfdxError_1.SfdxError('No scratch org info found.', 'ScratchOrgInfoNotFound');
40
+ }
41
+ if (orgInfo.Status === 'Active') {
42
+ return orgInfo;
43
+ }
44
+ if (orgInfo.Status === 'Error' && orgInfo.ErrorCode) {
45
+ const message = optionalErrorCodeMessage(orgInfo.ErrorCode, [WORKSPACE_CONFIG_FILENAME]);
46
+ if (message) {
47
+ throw new sfdxError_1.SfdxError(message, 'RemoteOrgSignupFailed', [
48
+ namedMessages.getMessage('SignupFailedActionError', [orgInfo.ErrorCode]),
49
+ ]);
50
+ }
51
+ throw new sfdxError_1.SfdxError(namedMessages.getMessage('SignupFailedError', [orgInfo.ErrorCode]));
52
+ }
53
+ if (orgInfo.Status === 'Error') {
54
+ // Maybe the request object can help the user somehow
55
+ logger.error('No error code on signup error! Logging request.');
56
+ logger.error(orgInfo);
57
+ throw new sfdxError_1.SfdxError(namedMessages.getMessage('SignupFailedUnknownError', [orgInfo.Id, hubUsername]), 'signupFailedUnknown');
58
+ }
59
+ throw new sfdxError_1.SfdxError(namedMessages.getMessage('SignupUnexpectedError'), 'UnexpectedSignupStatus');
60
+ };
61
+ exports.checkScratchOrgInfoForErrors = checkScratchOrgInfoForErrors;
62
+ //# sourceMappingURL=scratchOrgErrorCodes.js.map
@@ -0,0 +1,26 @@
1
+ interface FeatureTypes {
2
+ simpleFeatureMapping: {
3
+ [key: string]: string[];
4
+ };
5
+ quantifiedFeatureMapping: Record<string, string | number | boolean | null | undefined>;
6
+ deprecatedFeatures: string[];
7
+ }
8
+ export declare class ScratchOrgFeatureDeprecation {
9
+ private featureTypes;
10
+ constructor(options?: FeatureTypes);
11
+ /**
12
+ * Gets list of feature warnings that should be logged
13
+ *
14
+ * @param features The requested features.
15
+ * @returns List of string feature warnings.
16
+ */
17
+ getFeatureWarnings(features: string | string[]): string[];
18
+ /**
19
+ * Removes all deprecated features for the organization.
20
+ *
21
+ * @param features List of features to filter
22
+ * @returns feature array with proper mapping.
23
+ */
24
+ filterDeprecatedFeatures(features: string[]): string[];
25
+ }
26
+ export {};
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2021, salesforce.com, inc.
4
+ * All rights reserved.
5
+ * Licensed under the BSD 3-Clause license.
6
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.ScratchOrgFeatureDeprecation = void 0;
10
+ /**
11
+ * Certain Org Features require a translation or should be deprecated.
12
+ * Encapsulates feature mappings and deprecated features.
13
+ */
14
+ const ts_types_1 = require("@salesforce/ts-types");
15
+ // Local
16
+ const messages_1 = require("../messages");
17
+ messages_1.Messages.importMessagesDirectory(__dirname);
18
+ const messages = messages_1.Messages.load('@salesforce/core', 'scratchOrgFeatureDeprecation', [
19
+ 'quantifiedFeatureWithoutQuantityWarning',
20
+ 'mappedFeatureWarning',
21
+ 'deprecatedFeatureWarning',
22
+ ]);
23
+ const FEATURE_TYPES = {
24
+ // simpleFeatureMapping holds a set of direct replacement values for features.
25
+ simpleFeatureMapping: {
26
+ SALESWAVE: ['DEVELOPMENTWAVE'],
27
+ SERVICEWAVE: ['DEVELOPMENTWAVE'],
28
+ },
29
+ quantifiedFeatureMapping: {},
30
+ deprecatedFeatures: [
31
+ 'EXPANDEDSOURCETRACKING',
32
+ 'LISTCUSTOMSETTINGCREATION',
33
+ 'AppNavCapabilities',
34
+ 'EditInSubtab',
35
+ 'OldNewRecordFlowConsole',
36
+ 'OldNewRecordFlowStd',
37
+ 'DesktopLayoutStandardOff',
38
+ 'SplitViewOnStandardOff',
39
+ 'PopOutUtilities',
40
+ ],
41
+ };
42
+ class ScratchOrgFeatureDeprecation {
43
+ // Allow override for testing.
44
+ constructor(options = FEATURE_TYPES) {
45
+ this.featureTypes = options;
46
+ this.featureTypes.deprecatedFeatures = this.featureTypes.deprecatedFeatures.map((deprecatedFeature) => deprecatedFeature.toUpperCase());
47
+ // Make all of the keys in simpleFeatureMapping upper case.
48
+ const sfm = {};
49
+ Object.keys(this.featureTypes.simpleFeatureMapping).forEach((key) => {
50
+ sfm[key.toUpperCase()] = this.featureTypes.simpleFeatureMapping[key];
51
+ });
52
+ this.featureTypes.simpleFeatureMapping = sfm;
53
+ }
54
+ /**
55
+ * Gets list of feature warnings that should be logged
56
+ *
57
+ * @param features The requested features.
58
+ * @returns List of string feature warnings.
59
+ */
60
+ getFeatureWarnings(features) {
61
+ /* Get warning messages for deprecated features and feature mappings.*/
62
+ const featureWarningMessages = [];
63
+ const requestedFeatures = ((0, ts_types_1.isString)(features) ? features : features.join(';')).toUpperCase();
64
+ /* If a public quantified feature is defined without a quantity, throw a warning.*/
65
+ Object.keys(this.featureTypes.quantifiedFeatureMapping).forEach((key) => {
66
+ if (new RegExp(`${key};|${key},|${key}$`, 'i').test(requestedFeatures)) {
67
+ featureWarningMessages.push(messages.getMessage('quantifiedFeatureWithoutQuantityWarning', [
68
+ key,
69
+ this.featureTypes.quantifiedFeatureMapping[key],
70
+ ]));
71
+ }
72
+ });
73
+ /* If a simply mapped feature is defined, log a warning.*/
74
+ Object.keys(this.featureTypes.simpleFeatureMapping).forEach((key) => {
75
+ if (new RegExp(`${key};|${key},|${key}$`, 'i').test(requestedFeatures)) {
76
+ const tokens = '[' + this.featureTypes.simpleFeatureMapping[key].map((v) => "'" + v + "'").join(',') + ']';
77
+ featureWarningMessages.push(messages.getMessage('mappedFeatureWarning', [key, tokens]));
78
+ }
79
+ });
80
+ /* If a deprecated feature is identified as deprecated, throw a warning.*/
81
+ this.featureTypes.deprecatedFeatures.forEach((deprecatedFeature) => {
82
+ if (requestedFeatures.includes(deprecatedFeature)) {
83
+ featureWarningMessages.push(messages.getMessage('deprecatedFeatureWarning', [deprecatedFeature]));
84
+ }
85
+ });
86
+ return featureWarningMessages;
87
+ }
88
+ /**
89
+ * Removes all deprecated features for the organization.
90
+ *
91
+ * @param features List of features to filter
92
+ * @returns feature array with proper mapping.
93
+ */
94
+ filterDeprecatedFeatures(features) {
95
+ return features.reduce((previousValue, currentValue) => {
96
+ const feature = currentValue.toUpperCase();
97
+ if (this.featureTypes.deprecatedFeatures.includes(feature)) {
98
+ return previousValue;
99
+ }
100
+ else if (this.featureTypes.simpleFeatureMapping[feature]) {
101
+ /* If a simply mapped feature is specified, then perform the mapping. */
102
+ const simpleFeatureMapping = this.featureTypes.simpleFeatureMapping[feature];
103
+ return [...previousValue, ...simpleFeatureMapping];
104
+ }
105
+ return [...previousValue, currentValue];
106
+ }, []);
107
+ }
108
+ }
109
+ exports.ScratchOrgFeatureDeprecation = ScratchOrgFeatureDeprecation;
110
+ //# sourceMappingURL=scratchOrgFeatureDeprecation.js.map
@@ -0,0 +1,94 @@
1
+ import { Optional } from '@salesforce/ts-types';
2
+ import { Duration } from '@salesforce/kit';
3
+ import { SaveResult } from 'jsforce';
4
+ import { AuthInfo } from './authInfo';
5
+ import { Org } from './org';
6
+ import SettingsGenerator, { ObjectSetting } from './scratchOrgSettingsGenerator';
7
+ export interface ScratchOrgInfo {
8
+ AdminEmail?: string;
9
+ readonly CreatedDate?: string;
10
+ ConnectedAppCallbackUrl?: string;
11
+ ConnectedAppConsumerKey?: string;
12
+ Country?: string;
13
+ Description?: string;
14
+ DurationDays?: string;
15
+ Edition?: string;
16
+ readonly ErrorCode?: string;
17
+ readonly ExpirationDate?: string;
18
+ Features?: string;
19
+ HasSampleData?: boolean;
20
+ readonly Id?: string;
21
+ Language?: string;
22
+ LoginUrl: string;
23
+ readonly Name?: string;
24
+ Namespace?: string;
25
+ OrgName?: string;
26
+ Release?: 'Current' | 'Previous' | 'Preview';
27
+ readonly ScratchOrg?: string;
28
+ SourceOrg?: string;
29
+ readonly AuthCode: string;
30
+ Snapshot: string;
31
+ readonly Status: 'New' | 'Creating' | 'Active' | 'Error' | 'Deleted';
32
+ readonly SignupEmail: string;
33
+ readonly SignupUsername: string;
34
+ readonly SignupInstance: string;
35
+ Username: string;
36
+ settings?: Record<string, unknown>;
37
+ objectSettings?: {
38
+ [objectName: string]: ObjectSetting;
39
+ };
40
+ orgPreferences?: {
41
+ enabled: string[];
42
+ disabled: string[];
43
+ };
44
+ }
45
+ export interface JsForceError extends Error {
46
+ errorCode: string;
47
+ fields: string[];
48
+ }
49
+ /**
50
+ * after we successfully signup an org we need to trade the auth token for access and refresh token.
51
+ *
52
+ * scratchOrgInfoComplete - The completed ScratchOrgInfo which should contain an access token.
53
+ * hubOrg - the environment hub org
54
+ * clientSecret - The OAuth client secret. May be null for JWT OAuth flow.
55
+ * signupTargetLoginUrlConfig - Login url
56
+ * retry - auth retry attempts
57
+ *
58
+ * @returns {Promise<AuthInfo>}
59
+ */
60
+ export declare const authorizeScratchOrg: (options: {
61
+ scratchOrgInfoComplete: ScratchOrgInfo;
62
+ hubOrg: Org;
63
+ clientSecret?: string;
64
+ signupTargetLoginUrlConfig?: string;
65
+ retry?: number;
66
+ }) => Promise<AuthInfo>;
67
+ /**
68
+ * This extracts orgPrefs/settings from the user input and performs a basic scratchOrgInfo request.
69
+ *
70
+ * @param hubOrg - the environment hub org
71
+ * @param scratchOrgRequest - An object containing the fields of the ScratchOrgInfo
72
+ * @param settings - An object containing org settings
73
+ * @returns {Promise<SaveResult>}
74
+ */
75
+ export declare const requestScratchOrgCreation: (hubOrg: Org, scratchOrgRequest: ScratchOrgInfo, settings: SettingsGenerator) => Promise<SaveResult>;
76
+ /**
77
+ * This retrieves the ScratchOrgInfo, polling until the status is Active or Error
78
+ *
79
+ * @param hubOrg
80
+ * @param scratchOrgInfoId - the id of the scratchOrgInfo that we are retrieving
81
+ * @param timeout - A Duration object
82
+ * @returns {Promise<ScratchOrgInfo>}
83
+ */
84
+ export declare const pollForScratchOrgInfo: (hubOrg: Org, scratchOrgInfoId: string, timeout?: Duration) => Promise<ScratchOrgInfo>;
85
+ /**
86
+ * This authenticates into the newly created org and sets org preferences
87
+ *
88
+ * @param scratchOrgAuthInfo - an object containing the AuthInfo of the ScratchOrg
89
+ * @param apiVersion - the target api version
90
+ * @param orgSettings - The ScratchOrg settings
91
+ * @param scratchOrg - The scratchOrg Org info
92
+ * @returns {Promise<Optional<AuthInfo>>}
93
+ */
94
+ export declare const deploySettingsAndResolveUrl: (scratchOrgAuthInfo: AuthInfo, apiVersion: string, orgSettings: SettingsGenerator, scratchOrg: Org) => Promise<Optional<AuthInfo>>;