@salesforce/core 3.7.3 → 3.7.6

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 (70) hide show
  1. package/CHANGELOG.md +223 -0
  2. package/LICENSE.txt +1 -1
  3. package/lib/config/config.js +15 -15
  4. package/lib/config/configAggregator.js +4 -4
  5. package/lib/config/configFile.js +9 -9
  6. package/lib/config/configStore.js +14 -13
  7. package/lib/config/envVars.d.ts +20 -5
  8. package/lib/config/envVars.js +75 -10
  9. package/lib/config/keychainConfig.js +1 -1
  10. package/lib/crypto/crypto.js +6 -6
  11. package/lib/crypto/keyChainImpl.js +6 -6
  12. package/lib/crypto/secureBuffer.js +1 -1
  13. package/lib/deviceOauthService.js +5 -4
  14. package/lib/exported.d.ts +4 -2
  15. package/lib/exported.js +5 -1
  16. package/lib/globalInfo/globalInfoConfig.js +1 -1
  17. package/lib/globalInfo/sfdxDataHandler.js +11 -11
  18. package/lib/lifecycleEvents.js +2 -2
  19. package/lib/logger.js +12 -13
  20. package/lib/messages.js +10 -9
  21. package/lib/org/authInfo.js +45 -43
  22. package/lib/org/connection.d.ts +6 -1
  23. package/lib/org/connection.js +22 -8
  24. package/lib/org/org.d.ts +12 -2
  25. package/lib/org/org.js +62 -56
  26. package/lib/org/orgConfigProperties.js +1 -1
  27. package/lib/org/permissionSetAssignment.js +3 -3
  28. package/lib/org/scratchOrgCreate.d.ts +43 -0
  29. package/lib/org/scratchOrgCreate.js +142 -0
  30. package/lib/org/scratchOrgErrorCodes.d.ts +4 -0
  31. package/lib/org/scratchOrgErrorCodes.js +62 -0
  32. package/lib/org/scratchOrgFeatureDeprecation.d.ts +26 -0
  33. package/lib/org/scratchOrgFeatureDeprecation.js +110 -0
  34. package/lib/org/scratchOrgInfoApi.d.ts +94 -0
  35. package/lib/org/scratchOrgInfoApi.js +350 -0
  36. package/lib/org/scratchOrgInfoGenerator.d.ts +63 -0
  37. package/lib/org/scratchOrgInfoGenerator.js +223 -0
  38. package/lib/org/scratchOrgSettingsGenerator.d.ts +56 -0
  39. package/lib/org/scratchOrgSettingsGenerator.js +210 -0
  40. package/lib/org/user.js +24 -23
  41. package/lib/schema/printer.js +18 -18
  42. package/lib/schema/validator.js +8 -8
  43. package/lib/sfdxError.js +2 -2
  44. package/lib/sfdxProject.js +15 -13
  45. package/lib/status/myDomainResolver.js +3 -3
  46. package/lib/status/pollingClient.d.ts +2 -2
  47. package/lib/status/pollingClient.js +10 -4
  48. package/lib/status/streamingClient.d.ts +1 -1
  49. package/lib/status/streamingClient.js +6 -6
  50. package/lib/testSetup.js +21 -21
  51. package/lib/util/cache.js +3 -3
  52. package/lib/util/fs.js +12 -12
  53. package/lib/util/jsonXmlTools.d.ts +14 -0
  54. package/lib/util/jsonXmlTools.js +41 -0
  55. package/lib/util/mapKeys.d.ts +14 -0
  56. package/lib/util/mapKeys.js +48 -0
  57. package/lib/util/sfdc.js +3 -3
  58. package/lib/util/sfdcUrl.js +3 -3
  59. package/lib/util/zipWriter.d.ts +14 -0
  60. package/lib/util/zipWriter.js +68 -0
  61. package/lib/webOAuthServer.js +8 -8
  62. package/messages/envVars.md +53 -13
  63. package/messages/org.md +4 -0
  64. package/messages/scratchOrgCreate.md +27 -0
  65. package/messages/scratchOrgErrorCodes.md +99 -0
  66. package/messages/scratchOrgFeatureDeprecation.md +11 -0
  67. package/messages/scratchOrgInfoApi.md +11 -0
  68. package/messages/scratchOrgInfoGenerator.md +19 -0
  69. package/messages/user.md +4 -0
  70. package/package.json +33 -30
@@ -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>>;
@@ -0,0 +1,350 @@
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.deploySettingsAndResolveUrl = exports.pollForScratchOrgInfo = exports.requestScratchOrgCreation = exports.authorizeScratchOrg = void 0;
10
+ const kit_1 = require("@salesforce/kit");
11
+ const ts_types_1 = require("@salesforce/ts-types");
12
+ const ts_retry_promise_1 = require("ts-retry-promise");
13
+ const logger_1 = require("../logger");
14
+ const mapKeys_1 = require("../util/mapKeys");
15
+ const messages_1 = require("../messages");
16
+ const sfdxError_1 = require("../sfdxError");
17
+ const sfdcUrl_1 = require("../util/sfdcUrl");
18
+ const pollingClient_1 = require("../status/pollingClient");
19
+ const myDomainResolver_1 = require("../status/myDomainResolver");
20
+ const authInfo_1 = require("./authInfo");
21
+ const org_1 = require("./org");
22
+ const scratchOrgErrorCodes_1 = require("./scratchOrgErrorCodes");
23
+ messages_1.Messages.importMessagesDirectory(__dirname);
24
+ const messages = messages_1.Messages.loadMessages('@salesforce/core', 'scratchOrgInfoApi');
25
+ const errorCodes = messages_1.Messages.load('@salesforce/core', 'scratchOrgErrorCodes', ['C-1007']);
26
+ /**
27
+ * Returns the url to be used to authorize into the new scratch org
28
+ *
29
+ * @param scratchOrgInfoComplete The completed ScratchOrgInfo
30
+ * @param hubOrgLoginUrl the hun org login url
31
+ * @param signupTargetLoginUrlConfig the login url
32
+ * @returns {string}
33
+ */
34
+ const getOrgInstanceAuthority = function (scratchOrgInfoComplete, hubOrgLoginUrl, signupTargetLoginUrlConfig) {
35
+ const createdOrgInstance = scratchOrgInfoComplete.SignupInstance;
36
+ if (createdOrgInstance === 'utf8') {
37
+ return hubOrgLoginUrl;
38
+ }
39
+ let altUrl;
40
+ // For non-Falcon (ie - instance names not ending in -s) sandboxes, use the instance URL
41
+ if (createdOrgInstance && !createdOrgInstance.toLowerCase().endsWith('s')) {
42
+ altUrl = `https://${createdOrgInstance}.salesforce.com`;
43
+ }
44
+ else {
45
+ // For Falcon sandboxes, try the LoginURL instead; createdOrgInstance will not yield a valid URL
46
+ altUrl = scratchOrgInfoComplete.LoginUrl;
47
+ }
48
+ return signupTargetLoginUrlConfig !== null && signupTargetLoginUrlConfig !== void 0 ? signupTargetLoginUrlConfig : altUrl;
49
+ };
50
+ /**
51
+ * Returns OAuth2Options object
52
+ *
53
+ * @returns {OAuth2Options, number, number, number} options, retries, timeout, delay
54
+ * @param options
55
+ */
56
+ const buildOAuth2Options = async (options) => {
57
+ const logger = await logger_1.Logger.child('buildOAuth2Options');
58
+ const isJwtFlow = !!options.hubOrg.getConnection().getAuthInfoFields().privateKey;
59
+ const oauth2Options = {
60
+ loginUrl: getOrgInstanceAuthority(options.scratchOrgInfoComplete, options.hubOrg.getField(org_1.Org.Fields.LOGIN_URL), options.signupTargetLoginUrlConfig),
61
+ };
62
+ logger.debug(`isJwtFlow: ${isJwtFlow}`);
63
+ if (isJwtFlow && !process.env.SFDX_CLIENT_SECRET) {
64
+ oauth2Options.privateKeyFile = options.hubOrg.getConnection().getAuthInfoFields().privateKey;
65
+ const retries = (options === null || options === void 0 ? void 0 : options.retry) || kit_1.env.getNumber('SFDX_JWT_AUTH_RETRY_ATTEMPTS') || 0;
66
+ const timeoutInSeconds = kit_1.env.getNumber('SFDX_JWT_AUTH_RETRY_TIMEOUT') || 300;
67
+ const timeout = kit_1.Duration.seconds(timeoutInSeconds).milliseconds;
68
+ const delay = retries ? timeout / retries : 1000;
69
+ return {
70
+ options: oauth2Options,
71
+ retries,
72
+ timeout,
73
+ delay,
74
+ };
75
+ }
76
+ else {
77
+ // Web Server OAuth "auth code exchange" flow
78
+ if (process.env.SFDX_CLIENT_SECRET) {
79
+ oauth2Options.clientSecret = process.env.SFDX_CLIENT_SECRET;
80
+ }
81
+ else if (options.clientSecret) {
82
+ oauth2Options.clientSecret = options.clientSecret;
83
+ }
84
+ oauth2Options.redirectUri = options.scratchOrgInfoComplete.ConnectedAppCallbackUrl;
85
+ oauth2Options.authCode = options.scratchOrgInfoComplete.AuthCode;
86
+ return {
87
+ options: oauth2Options,
88
+ retries: 0,
89
+ };
90
+ }
91
+ };
92
+ /**
93
+ * Returns OAuth2Options object
94
+ *
95
+ * hubOrg the environment hub org
96
+ * username The OAuth client secret. May be null for JWT OAuth flow.
97
+ * oauth2Options The completed ScratchOrgInfo which should contain an access token.
98
+ * retries auth retry a
99
+ * timeout the login url
100
+ * delay the login url
101
+ *
102
+ * @returns {OAuth2Options, number, number, number} options, retries, timeout, delay
103
+ */
104
+ const getAuthInfo = async (options) => {
105
+ const logger = await logger_1.Logger.child('getAuthInfo');
106
+ const retryAuthorize = (0, ts_retry_promise_1.retryDecorator)(async (opts) => authInfo_1.AuthInfo.create(opts), {
107
+ timeout: options.timeout,
108
+ delay: options.delay,
109
+ retries: options.retries,
110
+ });
111
+ if (options.retries) {
112
+ try {
113
+ return await retryAuthorize({
114
+ username: options.username,
115
+ parentUsername: options.hubOrg.getUsername(),
116
+ oauth2Options: options.oauth2Options,
117
+ });
118
+ }
119
+ catch (err) {
120
+ const error = err;
121
+ logger.error(error);
122
+ throw error.lastError || error;
123
+ }
124
+ }
125
+ else {
126
+ return authInfo_1.AuthInfo.create({
127
+ username: options.username,
128
+ parentUsername: options.hubOrg.getUsername(),
129
+ oauth2Options: options.oauth2Options,
130
+ });
131
+ }
132
+ };
133
+ /**
134
+ * after we successfully signup an org we need to trade the auth token for access and refresh token.
135
+ *
136
+ * scratchOrgInfoComplete - The completed ScratchOrgInfo which should contain an access token.
137
+ * hubOrg - the environment hub org
138
+ * clientSecret - The OAuth client secret. May be null for JWT OAuth flow.
139
+ * signupTargetLoginUrlConfig - Login url
140
+ * retry - auth retry attempts
141
+ *
142
+ * @returns {Promise<AuthInfo>}
143
+ */
144
+ const authorizeScratchOrg = async (options) => {
145
+ var _a;
146
+ const { scratchOrgInfoComplete, hubOrg, clientSecret, signupTargetLoginUrlConfig, retry: maxRetries } = options;
147
+ const logger = await logger_1.Logger.child('authorizeScratchOrg');
148
+ logger.debug(`scratchOrgInfoComplete: ${JSON.stringify(scratchOrgInfoComplete, null, 4)}`);
149
+ // if we didn't have it marked as a devhub but just successfully used it as one, this will update the authFile, fix cache, etc
150
+ if (!hubOrg.isDevHubOrg()) {
151
+ await hubOrg.determineIfDevHubOrg(true);
152
+ }
153
+ const oAuth2Options = await buildOAuth2Options({
154
+ hubOrg,
155
+ clientSecret,
156
+ scratchOrgInfoComplete,
157
+ retry: maxRetries,
158
+ signupTargetLoginUrlConfig,
159
+ });
160
+ const authInfo = await getAuthInfo({
161
+ hubOrg,
162
+ username: scratchOrgInfoComplete.SignupUsername,
163
+ oauth2Options: oAuth2Options.options,
164
+ retries: oAuth2Options.retries,
165
+ timeout: oAuth2Options.timeout,
166
+ delay: oAuth2Options.delay,
167
+ });
168
+ await authInfo.save({
169
+ devHubUsername: hubOrg.getUsername(),
170
+ created: new Date((_a = scratchOrgInfoComplete.CreatedDate) !== null && _a !== void 0 ? _a : new Date()).valueOf().toString(),
171
+ expirationDate: scratchOrgInfoComplete.ExpirationDate,
172
+ clientId: scratchOrgInfoComplete.ConnectedAppConsumerKey,
173
+ createdOrgInstance: scratchOrgInfoComplete.SignupInstance,
174
+ isDevHub: false,
175
+ snapshot: scratchOrgInfoComplete.Snapshot,
176
+ });
177
+ return authInfo;
178
+ };
179
+ exports.authorizeScratchOrg = authorizeScratchOrg;
180
+ const checkOrgDoesntExist = async (scratchOrgInfo) => {
181
+ const usernameKey = Object.keys(scratchOrgInfo).find((key) => key.toUpperCase() === 'USERNAME');
182
+ if (!usernameKey) {
183
+ return;
184
+ }
185
+ const username = (0, ts_types_1.getString)(scratchOrgInfo, usernameKey);
186
+ if (username && username.length > 0) {
187
+ try {
188
+ await authInfo_1.AuthInfo.create({ username: username.toLowerCase() });
189
+ }
190
+ catch (error) {
191
+ const sfdxError = sfdxError_1.SfdxError.wrap(error);
192
+ // if an AuthInfo couldn't be created that means no AuthFile exists.
193
+ if (sfdxError.name === 'NamedOrgNotFound') {
194
+ return;
195
+ }
196
+ // Something unexpected
197
+ throw sfdxError;
198
+ }
199
+ // An org file already exists
200
+ throw errorCodes.createError('C-1007');
201
+ }
202
+ };
203
+ /**
204
+ * This extracts orgPrefs/settings from the user input and performs a basic scratchOrgInfo request.
205
+ *
206
+ * @param hubOrg - the environment hub org
207
+ * @param scratchOrgRequest - An object containing the fields of the ScratchOrgInfo
208
+ * @param settings - An object containing org settings
209
+ * @returns {Promise<SaveResult>}
210
+ */
211
+ const requestScratchOrgCreation = async (hubOrg, scratchOrgRequest, settings) => {
212
+ // If these were present, they were already used to initialize the scratchOrgSettingsGenerator.
213
+ // They shouldn't be submitted as part of the scratchOrgInfo.
214
+ delete scratchOrgRequest.settings;
215
+ delete scratchOrgRequest.objectSettings;
216
+ // We do not allow you to specify the old and the new way of doing post create settings
217
+ if (scratchOrgRequest.orgPreferences && settings.hasSettings()) {
218
+ // This is not allowed
219
+ throw new sfdxError_1.SfdxError('SignupDuplicateSettingsSpecifiedError');
220
+ }
221
+ // deprecated old style orgPreferences
222
+ if (scratchOrgRequest.orgPreferences) {
223
+ throw new sfdxError_1.SfdxError(messages.getMessage('DeprecatedPrefFormat'));
224
+ }
225
+ const scratchOrgInfo = (0, mapKeys_1.default)(scratchOrgRequest, kit_1.upperFirst, true);
226
+ await checkOrgDoesntExist(scratchOrgInfo); // throw if it does exist.
227
+ try {
228
+ return await hubOrg.getConnection().sobject('ScratchOrgInfo').create(scratchOrgInfo);
229
+ }
230
+ catch (error) {
231
+ // this is a jsforce error which contains the property "fields" which regular error don't
232
+ const jsForceError = error;
233
+ if (jsForceError.errorCode === 'REQUIRED_FIELD_MISSING') {
234
+ throw new sfdxError_1.SfdxError(messages.getMessage('SignupFieldsMissingError', [jsForceError.fields.toString()]));
235
+ }
236
+ throw sfdxError_1.SfdxError.wrap(jsForceError);
237
+ }
238
+ };
239
+ exports.requestScratchOrgCreation = requestScratchOrgCreation;
240
+ /**
241
+ * This retrieves the ScratchOrgInfo, polling until the status is Active or Error
242
+ *
243
+ * @param hubOrg
244
+ * @param scratchOrgInfoId - the id of the scratchOrgInfo that we are retrieving
245
+ * @param timeout - A Duration object
246
+ * @returns {Promise<ScratchOrgInfo>}
247
+ */
248
+ const pollForScratchOrgInfo = async (hubOrg, scratchOrgInfoId,
249
+ // org:create specifies a default timeout of 6. This longer default is for other consumers
250
+ timeout = kit_1.Duration.minutes(15)) => {
251
+ const logger = await logger_1.Logger.child('scratchOrgInfoApi-pollForScratchOrgInfo');
252
+ logger.debug(`PollingTimeout in minutes: ${timeout.minutes}`);
253
+ const pollingOptions = {
254
+ async poll() {
255
+ try {
256
+ const resultInProgress = await hubOrg.getConnection().sobject('ScratchOrgInfo').retrieve(scratchOrgInfoId);
257
+ logger.debug(`polling client result: ${JSON.stringify(resultInProgress, null, 4)}`);
258
+ // Once it's "done" we can return it
259
+ if (resultInProgress.Status === 'Active' || resultInProgress.Status === 'Error') {
260
+ return {
261
+ completed: true,
262
+ payload: resultInProgress,
263
+ };
264
+ }
265
+ logger.debug(`Scratch org status is ${resultInProgress.Status}`);
266
+ return {
267
+ completed: false,
268
+ };
269
+ }
270
+ catch (error) {
271
+ logger.debug(`An error occurred trying to retrieve scratchOrgInfo for ${scratchOrgInfoId}`);
272
+ logger.debug(`Error: ${error.message}`);
273
+ logger.debug('Re-trying deploy check again....');
274
+ return {
275
+ completed: false,
276
+ };
277
+ }
278
+ },
279
+ timeout,
280
+ frequency: kit_1.Duration.seconds(1),
281
+ timeoutErrorName: 'ScratchOrgInfoTimeoutError',
282
+ };
283
+ const client = await pollingClient_1.PollingClient.create(pollingOptions);
284
+ try {
285
+ const resultInProgress = await client.subscribe();
286
+ return (0, scratchOrgErrorCodes_1.checkScratchOrgInfoForErrors)(resultInProgress, hubOrg.getUsername(), logger);
287
+ }
288
+ catch (error) {
289
+ const err = error;
290
+ if (err.message) {
291
+ throw sfdxError_1.SfdxError.wrap(err);
292
+ }
293
+ throw new sfdxError_1.SfdxError(`The scratch org did not complete within ${timeout.minutes} minutes`, 'orgCreationTimeout', [
294
+ 'Try your force:org:create command again with a longer --wait value',
295
+ ]);
296
+ }
297
+ };
298
+ exports.pollForScratchOrgInfo = pollForScratchOrgInfo;
299
+ /**
300
+ * This authenticates into the newly created org and sets org preferences
301
+ *
302
+ * @param scratchOrgAuthInfo - an object containing the AuthInfo of the ScratchOrg
303
+ * @param apiVersion - the target api version
304
+ * @param orgSettings - The ScratchOrg settings
305
+ * @param scratchOrg - The scratchOrg Org info
306
+ * @returns {Promise<Optional<AuthInfo>>}
307
+ */
308
+ const deploySettingsAndResolveUrl = async (scratchOrgAuthInfo, apiVersion, orgSettings, scratchOrg) => {
309
+ const logger = await logger_1.Logger.child('scratchOrgInfoApi-deploySettingsAndResolveUrl');
310
+ if (orgSettings.hasSettings()) {
311
+ // deploy the settings to the newly created scratch org
312
+ logger.debug(`deploying scratch org settings with apiVersion ${apiVersion}`);
313
+ try {
314
+ await orgSettings.createDeploy();
315
+ await orgSettings.deploySettingsViaFolder(scratchOrg, apiVersion);
316
+ }
317
+ catch (error) {
318
+ throw sfdxError_1.SfdxError.wrap(error);
319
+ }
320
+ }
321
+ const { instanceUrl } = scratchOrgAuthInfo.getFields();
322
+ if (instanceUrl) {
323
+ logger.debug(`processScratchOrgInfoResult - resultData.instanceUrl: ${instanceUrl}`);
324
+ const options = {
325
+ timeout: kit_1.Duration.minutes(3),
326
+ frequency: kit_1.Duration.seconds(10),
327
+ url: new sfdcUrl_1.SfdcUrl(instanceUrl),
328
+ };
329
+ try {
330
+ const resolver = await myDomainResolver_1.MyDomainResolver.create(options);
331
+ await resolver.resolve();
332
+ }
333
+ catch (error) {
334
+ const sfdxError = sfdxError_1.SfdxError.wrap(error);
335
+ logger.debug('processScratchOrgInfoResult - err: %s', error);
336
+ if (sfdxError.name === 'MyDomainResolverTimeoutError') {
337
+ sfdxError.setData({
338
+ orgId: scratchOrgAuthInfo.getFields().orgId,
339
+ username: scratchOrgAuthInfo.getFields().username,
340
+ instanceUrl,
341
+ });
342
+ logger.debug('processScratchOrgInfoResult - err data: %s', sfdxError.data);
343
+ }
344
+ throw sfdxError;
345
+ }
346
+ return scratchOrgAuthInfo;
347
+ }
348
+ };
349
+ exports.deploySettingsAndResolveUrl = deploySettingsAndResolveUrl;
350
+ //# sourceMappingURL=scratchOrgInfoApi.js.map
@@ -0,0 +1,63 @@
1
+ import { SfdxProjectJson } from '../sfdxProject';
2
+ import { Org } from './org';
3
+ import { ScratchOrgInfo } from './scratchOrgInfoApi';
4
+ declare type PartialScratchOrgInfo = Pick<ScratchOrgInfo, 'ConnectedAppConsumerKey' | 'AuthCode' | 'Snapshot' | 'Status' | 'LoginUrl' | 'SignupEmail' | 'SignupUsername' | 'SignupInstance' | 'Username'>;
5
+ export interface ScratchOrgInfoPayload extends PartialScratchOrgInfo {
6
+ orgName: string;
7
+ package2AncestorIds: string;
8
+ features: string | string[];
9
+ connectedAppConsumerKey: string;
10
+ namespace: string;
11
+ connectedAppCallbackUrl: string;
12
+ }
13
+ /**
14
+ * Generates the package2AncestorIds scratch org property
15
+ *
16
+ * @param scratchOrgInfo - the scratchOrgInfo passed in by the user
17
+ * @param projectJson - sfdxProjectJson
18
+ * @param hubOrg - the hub org, in case we need to do queries
19
+ */
20
+ export declare const getAncestorIds: (scratchOrgInfo: ScratchOrgInfoPayload, projectJson: SfdxProjectJson, hubOrg: Org) => Promise<string>;
21
+ /**
22
+ * Takes in a scratchOrgInfo and fills in the missing fields
23
+ *
24
+ * @param hubOrg the environment hub org
25
+ * @param scratchOrgInfoPayload - the scratchOrgInfo passed in by the user
26
+ * @param nonamespace create the scratch org with no namespace
27
+ * @param ignoreAncestorIds true if the sfdx-project.json ancestorId keys should be ignored
28
+ */
29
+ export declare const generateScratchOrgInfo: ({ hubOrg, scratchOrgInfoPayload, nonamespace, ignoreAncestorIds, }: {
30
+ hubOrg: Org;
31
+ scratchOrgInfoPayload: ScratchOrgInfoPayload;
32
+ nonamespace?: boolean | undefined;
33
+ ignoreAncestorIds?: boolean | undefined;
34
+ }) => Promise<ScratchOrgInfoPayload>;
35
+ /**
36
+ * Returns a valid signup json
37
+ *
38
+ * definitionjson org definition in JSON format
39
+ * definitionfile path to an org definition file
40
+ * connectedAppConsumerKey The connected app consumer key. May be null for JWT OAuth flow.
41
+ * durationdays duration of the scratch org (in days) (default:1, min:1, max:30)
42
+ * nonamespace create the scratch org with no namespace
43
+ * noancestors do not include second-generation package ancestors in the scratch org
44
+ * orgConfig overrides definitionjson
45
+ *
46
+ * @returns scratchOrgInfoPayload: ScratchOrgInfoPayload;
47
+ ignoreAncestorIds: boolean;
48
+ warnings: string[];
49
+ */
50
+ export declare const getScratchOrgInfoPayload: (options: {
51
+ durationDays: number;
52
+ definitionjson?: string;
53
+ definitionfile?: string;
54
+ connectedAppConsumerKey?: string;
55
+ nonamespace?: boolean;
56
+ noancestors?: boolean;
57
+ orgConfig?: Record<string, unknown>;
58
+ }) => Promise<{
59
+ scratchOrgInfoPayload: ScratchOrgInfoPayload;
60
+ ignoreAncestorIds: boolean;
61
+ warnings: string[];
62
+ }>;
63
+ export {};