@salesforce/core 3.7.4 → 3.7.7

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 (77) hide show
  1. package/CHANGELOG.md +219 -0
  2. package/README.md +4 -4
  3. package/lib/config/config.d.ts +5 -5
  4. package/lib/config/config.js +5 -5
  5. package/lib/config/configAggregator.d.ts +2 -2
  6. package/lib/config/configAggregator.js +2 -2
  7. package/lib/config/configFile.d.ts +2 -2
  8. package/lib/config/configFile.js +7 -7
  9. package/lib/config/configStore.js +7 -6
  10. package/lib/config/envVars.d.ts +20 -5
  11. package/lib/config/envVars.js +70 -5
  12. package/lib/crypto/keyChainImpl.js +2 -3
  13. package/lib/deviceOauthService.js +2 -2
  14. package/lib/exported.d.ts +6 -4
  15. package/lib/exported.js +13 -6
  16. package/lib/globalInfo/accessors/aliasAccessor.js +2 -2
  17. package/lib/lifecycleEvents.js +1 -1
  18. package/lib/logger.d.ts +3 -3
  19. package/lib/logger.js +9 -10
  20. package/lib/messages.d.ts +2 -2
  21. package/lib/messages.js +4 -4
  22. package/lib/org/authInfo.d.ts +1 -1
  23. package/lib/org/authInfo.js +6 -7
  24. package/lib/org/authRemover.d.ts +2 -2
  25. package/lib/org/authRemover.js +2 -2
  26. package/lib/org/connection.d.ts +7 -2
  27. package/lib/org/connection.js +17 -4
  28. package/lib/org/org.d.ts +16 -6
  29. package/lib/org/org.js +52 -49
  30. package/lib/org/permissionSetAssignment.js +2 -2
  31. package/lib/org/scratchOrgCreate.d.ts +43 -0
  32. package/lib/org/scratchOrgCreate.js +142 -0
  33. package/lib/org/scratchOrgErrorCodes.d.ts +4 -0
  34. package/lib/org/scratchOrgErrorCodes.js +62 -0
  35. package/lib/org/scratchOrgFeatureDeprecation.d.ts +26 -0
  36. package/lib/org/scratchOrgFeatureDeprecation.js +110 -0
  37. package/lib/org/scratchOrgInfoApi.d.ts +94 -0
  38. package/lib/org/scratchOrgInfoApi.js +350 -0
  39. package/lib/org/scratchOrgInfoGenerator.d.ts +63 -0
  40. package/lib/org/scratchOrgInfoGenerator.js +223 -0
  41. package/lib/org/scratchOrgSettingsGenerator.d.ts +56 -0
  42. package/lib/org/scratchOrgSettingsGenerator.js +210 -0
  43. package/lib/org/user.js +8 -7
  44. package/lib/schema/printer.js +2 -2
  45. package/lib/schema/validator.d.ts +4 -4
  46. package/lib/schema/validator.js +9 -9
  47. package/lib/{sfdxError.d.ts → sfError.d.ts} +14 -9
  48. package/lib/{sfdxError.js → sfError.js} +20 -14
  49. package/lib/{sfdxProject.d.ts → sfProject.d.ts} +37 -27
  50. package/lib/{sfdxProject.js → sfProject.js} +75 -63
  51. package/lib/status/pollingClient.d.ts +2 -2
  52. package/lib/status/pollingClient.js +10 -4
  53. package/lib/status/streamingClient.d.ts +1 -1
  54. package/lib/status/streamingClient.js +6 -6
  55. package/lib/testSetup.d.ts +4 -4
  56. package/lib/testSetup.js +8 -8
  57. package/lib/util/fs.js +7 -7
  58. package/lib/util/internal.d.ts +2 -2
  59. package/lib/util/internal.js +2 -2
  60. package/lib/util/jsonXmlTools.d.ts +14 -0
  61. package/lib/util/jsonXmlTools.js +41 -0
  62. package/lib/util/mapKeys.d.ts +14 -0
  63. package/lib/util/mapKeys.js +48 -0
  64. package/lib/util/sfdcUrl.d.ts +2 -2
  65. package/lib/util/sfdcUrl.js +2 -2
  66. package/lib/util/zipWriter.d.ts +14 -0
  67. package/lib/util/zipWriter.js +68 -0
  68. package/lib/webOAuthServer.js +11 -11
  69. package/messages/envVars.md +53 -13
  70. package/messages/org.md +4 -0
  71. package/messages/scratchOrgCreate.md +27 -0
  72. package/messages/scratchOrgErrorCodes.md +99 -0
  73. package/messages/scratchOrgFeatureDeprecation.md +11 -0
  74. package/messages/scratchOrgInfoApi.md +11 -0
  75. package/messages/scratchOrgInfoGenerator.md +19 -0
  76. package/messages/user.md +4 -0
  77. package/package.json +5 -1
package/lib/org/org.d.ts CHANGED
@@ -5,6 +5,7 @@ import { OrgUsersConfig } from '../config/orgUsersConfig';
5
5
  import { SandboxOrgConfig } from '../config/sandboxOrgConfig';
6
6
  import { Connection } from './connection';
7
7
  import { AuthFields, AuthInfo } from './authInfo';
8
+ import { ScratchOrgCreateOptions, ScratchOrgCreateResult } from './scratchOrgCreate';
8
9
  export declare type OrganizationInformation = {
9
10
  Name: string;
10
11
  InstanceName: string;
@@ -63,6 +64,7 @@ export declare type SandboxRequest = {
63
64
  SourceId?: string;
64
65
  Description?: string;
65
66
  };
67
+ export declare type ScratchOrgRequest = Pick<ScratchOrgCreateOptions, 'connectedAppConsumerKey' | 'durationDays' | 'nonamespace' | 'noancestors' | 'wait' | 'retry' | 'apiversion' | 'definitionjson' | 'definitionfile' | 'orgConfig' | 'clientSecret'>;
66
68
  /**
67
69
  * Provides a way to manage a locally authenticated Org.
68
70
  *
@@ -111,6 +113,14 @@ export declare class Org extends AsyncOptionalCreatable<Org.Options> {
111
113
  wait?: Duration;
112
114
  interval?: Duration;
113
115
  }): Promise<SandboxProcessObject>;
116
+ /**
117
+ * Creates a scratchOrg
118
+ * 'this' needs to be a valid dev-hub
119
+ *
120
+ * @param {options} ScratchOrgCreateOptions
121
+ * @returns {ScratchOrgCreateResult}
122
+ */
123
+ scratchOrgCreate(options: ScratchOrgRequest): Promise<ScratchOrgCreateResult>;
114
124
  /**
115
125
  * Clean all data files in the org's data path. Usually <workspace>/.sfdx/orgs/<username>.
116
126
  *
@@ -138,9 +148,9 @@ export declare class Org extends AsyncOptionalCreatable<Org.Options> {
138
148
  /**
139
149
  * Check that this org is a scratch org by asking the dev hub if it knows about it.
140
150
  *
141
- * **Throws** *{@link SfdxError}{ name: 'NotADevHubError' }* Not a Dev Hub.
151
+ * **Throws** *{@link SfError}{ name: 'NotADevHubError' }* Not a Dev Hub.
142
152
  *
143
- * **Throws** *{@link SfdxError}{ name: 'NoResultsError' }* No results.
153
+ * **Throws** *{@link SfError}{ name: 'NoResultsError' }* No results.
144
154
  *
145
155
  * @param devHubUsernameOrAlias The username or alias of the dev hub org.
146
156
  */
@@ -243,7 +253,7 @@ export declare class Org extends AsyncOptionalCreatable<Org.Options> {
243
253
  /**
244
254
  * Removes a username from the user config for this object. For convenience `this` object is returned.
245
255
  *
246
- * **Throws** *{@link SfdxError}{ name: 'MissingAuthInfoError' }* Auth info is missing.
256
+ * **Throws** *{@link SfError}{ name: 'MissingAuthInfoError' }* Auth info is missing.
247
257
  *
248
258
  * @param {AuthInfo | string} auth The AuthInfo containing the username to remove.
249
259
  */
@@ -295,12 +305,12 @@ export declare class Org extends AsyncOptionalCreatable<Org.Options> {
295
305
  */
296
306
  protected init(): Promise<void>;
297
307
  /**
298
- * **Throws** *{@link SfdxError}{ name: 'NotSupportedError' }* Throws an unsupported error.
308
+ * **Throws** *{@link SfError}{ name: 'NotSupportedError' }* Throws an unsupported error.
299
309
  */
300
310
  protected getDefaultOptions(): Org.Options;
301
311
  private queryProduction;
302
- private destorySandbox;
303
- private destoryScratchOrg;
312
+ private destroySandbox;
313
+ private destroyScratchOrg;
304
314
  /**
305
315
  * this method will delete the sandbox org from the production org and clean up any local files
306
316
  *
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
- const sfdxError_1 = require("../sfdxError");
20
+ const sfError_1 = require("../sfError");
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
  *
@@ -176,9 +187,9 @@ class Org extends kit_1.AsyncOptionalCreatable {
176
187
  /**
177
188
  * Check that this org is a scratch org by asking the dev hub if it knows about it.
178
189
  *
179
- * **Throws** *{@link SfdxError}{ name: 'NotADevHubError' }* Not a Dev Hub.
190
+ * **Throws** *{@link SfError}{ name: 'NotADevHubError' }* Not a Dev Hub.
180
191
  *
181
- * **Throws** *{@link SfdxError}{ name: 'NoResultsError' }* No results.
192
+ * **Throws** *{@link SfError}{ name: 'NoResultsError' }* No results.
182
193
  *
183
194
  * @param devHubUsernameOrAlias The username or alias of the dev hub org.
184
195
  */
@@ -194,7 +205,7 @@ class Org extends kit_1.AsyncOptionalCreatable {
194
205
  try {
195
206
  const results = await devHubConnection.query(DEV_HUB_SOQL);
196
207
  if ((0, ts_types_1.getNumber)(results, 'records.length') !== 1) {
197
- throw new sfdxError_1.SfdxError('No results', 'NoResultsError');
208
+ throw new sfError_1.SfError('No results', 'NoResultsError');
198
209
  }
199
210
  }
200
211
  catch (err) {
@@ -429,7 +440,7 @@ class Org extends kit_1.AsyncOptionalCreatable {
429
440
  */
430
441
  async addUsername(auth) {
431
442
  if (!auth) {
432
- throw new sfdxError_1.SfdxError('Missing auth info', 'MissingAuthInfo');
443
+ throw new sfError_1.SfError('Missing auth info', 'MissingAuthInfo');
433
444
  }
434
445
  const authInfo = (0, ts_types_1.isString)(auth) ? await authInfo_1.AuthInfo.create({ username: auth }) : auth;
435
446
  this.logger.debug(`adding username ${authInfo.getFields().username}`);
@@ -439,7 +450,7 @@ class Org extends kit_1.AsyncOptionalCreatable {
439
450
  // needs config refactoring to improve
440
451
  const usernames = contents.usernames || [];
441
452
  if (!(0, ts_types_1.isArray)(usernames)) {
442
- throw new sfdxError_1.SfdxError('Usernames is not an array', 'UnexpectedDataFormat');
453
+ throw new sfError_1.SfError('Usernames is not an array', 'UnexpectedDataFormat');
443
454
  }
444
455
  let shouldUpdate = false;
445
456
  const thisUsername = (0, ts_types_1.ensure)(this.getUsername());
@@ -461,13 +472,13 @@ class Org extends kit_1.AsyncOptionalCreatable {
461
472
  /**
462
473
  * Removes a username from the user config for this object. For convenience `this` object is returned.
463
474
  *
464
- * **Throws** *{@link SfdxError}{ name: 'MissingAuthInfoError' }* Auth info is missing.
475
+ * **Throws** *{@link SfError}{ name: 'MissingAuthInfoError' }* Auth info is missing.
465
476
  *
466
477
  * @param {AuthInfo | string} auth The AuthInfo containing the username to remove.
467
478
  */
468
479
  async removeUsername(auth) {
469
480
  if (!auth) {
470
- throw new sfdxError_1.SfdxError('Missing auth info', 'MissingAuthInfoError');
481
+ throw new sfError_1.SfError('Missing auth info', 'MissingAuthInfoError');
471
482
  }
472
483
  const authInfo = (0, ts_types_1.isString)(auth) ? await authInfo_1.AuthInfo.create({ username: auth }) : auth;
473
484
  this.logger.debug(`removing username ${authInfo.getFields().username}`);
@@ -575,7 +586,7 @@ class Org extends kit_1.AsyncOptionalCreatable {
575
586
  throw messages.createError('noUsernameFound');
576
587
  }
577
588
  this.connection = await connection_1.Connection.create({
578
- // If no username is provided or resolvable from an alias, AuthInfo will throw an SfdxError.
589
+ // If no username is provided or resolvable from an alias, AuthInfo will throw an SfError.
579
590
  authInfo: await authInfo_1.AuthInfo.create({ username, isDevHub: this.options.isDevHub }),
580
591
  });
581
592
  }
@@ -585,18 +596,18 @@ class Org extends kit_1.AsyncOptionalCreatable {
585
596
  this.orgId = this.getField(Org.Fields.ORG_ID);
586
597
  }
587
598
  /**
588
- * **Throws** *{@link SfdxError}{ name: 'NotSupportedError' }* Throws an unsupported error.
599
+ * **Throws** *{@link SfError}{ name: 'NotSupportedError' }* Throws an unsupported error.
589
600
  */
590
601
  getDefaultOptions() {
591
- throw new sfdxError_1.SfdxError('Not Supported', 'NotSupportedError');
602
+ throw new sfError_1.SfError('Not Supported', 'NotSupportedError');
592
603
  }
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.
@@ -851,7 +854,7 @@ class Org extends kit_1.AsyncOptionalCreatable {
851
854
  waitingOnAuth = true;
852
855
  }
853
856
  else {
854
- throw sfdxError_1.SfdxError.wrap(error);
857
+ throw sfError_1.SfError.wrap(error);
855
858
  }
856
859
  }
857
860
  }
@@ -943,7 +946,7 @@ class Org extends kit_1.AsyncOptionalCreatable {
943
946
  }
944
947
  else {
945
948
  // If it fails for any unexpected reason, just pass that through
946
- throw sfdxError_1.SfdxError.wrap(error);
949
+ throw sfError_1.SfError.wrap(error);
947
950
  }
948
951
  }
949
952
  }
@@ -12,7 +12,7 @@ const kit_1 = require("@salesforce/kit");
12
12
  const ts_types_1 = require("@salesforce/ts-types");
13
13
  const logger_1 = require("../logger");
14
14
  const messages_1 = require("../messages");
15
- const sfdxError_1 = require("../sfdxError");
15
+ const sfError_1 = require("../sfError");
16
16
  messages_1.Messages.importMessagesDirectory(__dirname);
17
17
  const messages = messages_1.Messages.load('@salesforce/core', 'permissionSetAssignment', [
18
18
  'errorsEncounteredCreatingAssignment',
@@ -86,7 +86,7 @@ class PermissionSetAssignment {
86
86
  errors.forEach((_message) => {
87
87
  message = `${message}${_message}${os_1.EOL}`;
88
88
  });
89
- throw new sfdxError_1.SfdxError(message, 'errorsEncounteredCreatingAssignment');
89
+ throw new sfError_1.SfError(message, 'errorsEncounteredCreatingAssignment');
90
90
  }
91
91
  else {
92
92
  throw messages.createError('notSuccessfulButNoErrorsReported');
@@ -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 sfProject_1 = require("../sfProject");
16
+ const sfError_1 = require("../sfError");
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 sfProject_1.SfProject.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 sfError_1.SfError(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 sfError_1 = require("../sfError");
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 sfError_1.SfError('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 sfError_1.SfError(message, 'RemoteOrgSignupFailed', [
48
+ namedMessages.getMessage('SignupFailedActionError', [orgInfo.ErrorCode]),
49
+ ]);
50
+ }
51
+ throw new sfError_1.SfError(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 sfError_1.SfError(namedMessages.getMessage('SignupFailedUnknownError', [orgInfo.Id, hubUsername]), 'signupFailedUnknown');
58
+ }
59
+ throw new sfError_1.SfError(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 {};