@salesforce/core 4.0.0 → 4.1.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 (151) hide show
  1. package/LICENSE.txt +1 -1
  2. package/README.md +93 -44
  3. package/lib/config/authInfoConfig.d.ts +19 -0
  4. package/lib/config/authInfoConfig.js +35 -0
  5. package/lib/config/config.d.ts +87 -22
  6. package/lib/config/config.js +117 -65
  7. package/lib/config/configAggregator.d.ts +41 -35
  8. package/lib/config/configAggregator.js +102 -73
  9. package/lib/config/configFile.d.ts +2 -2
  10. package/lib/config/configFile.js +38 -29
  11. package/lib/config/configStore.d.ts +9 -9
  12. package/lib/config/configStore.js +17 -15
  13. package/lib/config/envVars.d.ts +15 -9
  14. package/lib/config/envVars.js +71 -47
  15. package/lib/config/orgUsersConfig.js +2 -0
  16. package/lib/config/sandboxOrgConfig.js +2 -0
  17. package/lib/config/sandboxProcessCache.d.ts +16 -0
  18. package/lib/config/sandboxProcessCache.js +38 -0
  19. package/lib/config/tokensConfig.d.ts +10 -0
  20. package/lib/config/tokensConfig.js +29 -0
  21. package/lib/config/ttlConfig.d.ts +34 -0
  22. package/lib/config/ttlConfig.js +50 -0
  23. package/lib/crypto/crypto.js +15 -22
  24. package/lib/crypto/keyChain.js +2 -3
  25. package/lib/crypto/keyChainImpl.d.ts +5 -3
  26. package/lib/crypto/keyChainImpl.js +58 -61
  27. package/lib/crypto/secureBuffer.d.ts +1 -1
  28. package/lib/deviceOauthService.d.ts +3 -3
  29. package/lib/deviceOauthService.js +27 -25
  30. package/lib/exported.d.ts +15 -12
  31. package/lib/exported.js +28 -16
  32. package/lib/global.d.ts +11 -3
  33. package/lib/global.js +39 -12
  34. package/lib/lifecycleEvents.d.ts +1 -1
  35. package/lib/lifecycleEvents.js +3 -0
  36. package/lib/logger.d.ts +19 -9
  37. package/lib/logger.js +112 -86
  38. package/lib/messages.d.ts +53 -36
  39. package/lib/messages.js +81 -91
  40. package/lib/org/authInfo.d.ts +56 -20
  41. package/lib/org/authInfo.js +232 -131
  42. package/lib/org/authRemover.d.ts +8 -7
  43. package/lib/org/authRemover.js +32 -28
  44. package/lib/org/connection.d.ts +13 -37
  45. package/lib/org/connection.js +78 -124
  46. package/lib/org/index.js +5 -1
  47. package/lib/org/org.d.ts +151 -48
  48. package/lib/org/org.js +468 -225
  49. package/lib/org/orgConfigProperties.d.ts +64 -3
  50. package/lib/org/orgConfigProperties.js +96 -4
  51. package/lib/org/permissionSetAssignment.js +4 -13
  52. package/lib/org/scratchOrgCache.d.ts +20 -0
  53. package/lib/org/scratchOrgCache.js +33 -0
  54. package/lib/org/scratchOrgCreate.d.ts +28 -17
  55. package/lib/org/scratchOrgCreate.js +125 -53
  56. package/lib/org/scratchOrgErrorCodes.d.ts +9 -3
  57. package/lib/org/scratchOrgErrorCodes.js +34 -17
  58. package/lib/org/scratchOrgFeatureDeprecation.js +1 -6
  59. package/lib/org/scratchOrgInfoApi.d.ts +21 -47
  60. package/lib/org/scratchOrgInfoApi.js +129 -63
  61. package/lib/org/scratchOrgInfoGenerator.d.ts +6 -5
  62. package/lib/org/scratchOrgInfoGenerator.js +76 -62
  63. package/lib/org/scratchOrgLifecycleEvents.d.ts +10 -0
  64. package/lib/org/scratchOrgLifecycleEvents.js +41 -0
  65. package/lib/org/scratchOrgSettingsGenerator.d.ts +44 -21
  66. package/lib/org/scratchOrgSettingsGenerator.js +165 -98
  67. package/lib/org/scratchOrgTypes.d.ts +43 -0
  68. package/lib/org/scratchOrgTypes.js +9 -0
  69. package/lib/org/user.d.ts +1 -1
  70. package/lib/org/user.js +25 -34
  71. package/lib/schema/printer.d.ts +6 -0
  72. package/lib/schema/printer.js +34 -31
  73. package/lib/schema/validator.d.ts +12 -10
  74. package/lib/schema/validator.js +56 -76
  75. package/lib/{sfdxError.d.ts → sfError.d.ts} +12 -20
  76. package/lib/{sfdxError.js → sfError.js} +40 -30
  77. package/lib/{sfdxProject.d.ts → sfProject.d.ts} +75 -35
  78. package/lib/sfProject.js +651 -0
  79. package/lib/stateAggregator/accessors/aliasAccessor.d.ts +129 -0
  80. package/lib/stateAggregator/accessors/aliasAccessor.js +263 -0
  81. package/lib/stateAggregator/accessors/orgAccessor.d.ts +101 -0
  82. package/lib/stateAggregator/accessors/orgAccessor.js +240 -0
  83. package/lib/stateAggregator/accessors/sandboxAccessor.d.ts +8 -0
  84. package/lib/stateAggregator/accessors/sandboxAccessor.js +28 -0
  85. package/lib/stateAggregator/accessors/tokenAccessor.d.ts +63 -0
  86. package/lib/stateAggregator/accessors/tokenAccessor.js +80 -0
  87. package/lib/stateAggregator/index.d.ts +4 -0
  88. package/lib/stateAggregator/index.js +27 -0
  89. package/lib/stateAggregator/stateAggregator.d.ts +25 -0
  90. package/lib/stateAggregator/stateAggregator.js +46 -0
  91. package/lib/status/myDomainResolver.d.ts +1 -1
  92. package/lib/status/myDomainResolver.js +4 -4
  93. package/lib/status/pollingClient.js +4 -4
  94. package/lib/status/streamingClient.d.ts +2 -2
  95. package/lib/status/streamingClient.js +58 -63
  96. package/lib/status/types.d.ts +2 -2
  97. package/lib/testSetup.d.ts +204 -75
  98. package/lib/testSetup.js +468 -164
  99. package/lib/util/cache.d.ts +2 -2
  100. package/lib/util/cache.js +6 -6
  101. package/lib/util/checkLightningDomain.js +3 -4
  102. package/lib/util/directoryWriter.d.ts +12 -0
  103. package/lib/util/directoryWriter.js +54 -0
  104. package/lib/util/getJwtAudienceUrl.js +1 -1
  105. package/lib/util/internal.d.ts +28 -2
  106. package/lib/util/internal.js +65 -8
  107. package/lib/util/jsonXmlTools.js +2 -4
  108. package/lib/util/mapKeys.d.ts +9 -9
  109. package/lib/util/mapKeys.js +13 -9
  110. package/lib/util/sfdc.d.ts +51 -51
  111. package/lib/util/sfdc.js +74 -79
  112. package/lib/util/sfdcUrl.d.ts +5 -19
  113. package/lib/util/sfdcUrl.js +40 -49
  114. package/lib/util/structuredWriter.d.ts +9 -0
  115. package/lib/util/structuredWriter.js +3 -0
  116. package/lib/util/zipWriter.d.ts +8 -6
  117. package/lib/util/zipWriter.js +13 -13
  118. package/lib/webOAuthServer.d.ts +20 -6
  119. package/lib/webOAuthServer.js +102 -56
  120. package/messageTransformer/messageTransformer.ts +93 -0
  121. package/messages/auth.md +9 -1
  122. package/messages/config.md +42 -6
  123. package/messages/connection.md +8 -0
  124. package/messages/core.md +10 -0
  125. package/messages/envVars.md +37 -3
  126. package/messages/org.md +21 -1
  127. package/messages/scratchOrgCreate.md +2 -6
  128. package/messages/scratchOrgErrorCodes.md +17 -1
  129. package/messages/scratchOrgInfoApi.md +9 -0
  130. package/messages/scratchOrgInfoGenerator.md +9 -1
  131. package/package.json +123 -46
  132. package/CHANGELOG.md +0 -1244
  133. package/lib/config/keychainConfig.d.ts +0 -19
  134. package/lib/config/keychainConfig.js +0 -43
  135. package/lib/globalInfo/accessors/aliasAccessor.d.ts +0 -83
  136. package/lib/globalInfo/accessors/aliasAccessor.js +0 -130
  137. package/lib/globalInfo/accessors/orgAccessor.d.ts +0 -13
  138. package/lib/globalInfo/accessors/orgAccessor.js +0 -45
  139. package/lib/globalInfo/accessors/tokenAccessor.d.ts +0 -13
  140. package/lib/globalInfo/accessors/tokenAccessor.js +0 -35
  141. package/lib/globalInfo/globalInfoConfig.d.ts +0 -36
  142. package/lib/globalInfo/globalInfoConfig.js +0 -105
  143. package/lib/globalInfo/index.d.ts +0 -6
  144. package/lib/globalInfo/index.js +0 -29
  145. package/lib/globalInfo/sfdxDataHandler.d.ts +0 -43
  146. package/lib/globalInfo/sfdxDataHandler.js +0 -217
  147. package/lib/globalInfo/types.d.ts +0 -39
  148. package/lib/globalInfo/types.js +0 -10
  149. package/lib/sfdxProject.js +0 -557
  150. package/lib/util/fs.d.ts +0 -201
  151. package/lib/util/fs.js +0 -378
@@ -6,16 +6,16 @@
6
6
  * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.RequestStatus = void 0;
9
+ exports.createRecordTypeAndBusinessProcessFileContent = exports.createObjectFileContent = exports.RequestStatus = void 0;
10
10
  const path = require("path");
11
11
  const kit_1 = require("@salesforce/kit");
12
12
  const ts_types_1 = require("@salesforce/ts-types");
13
13
  const js2xmlparser = require("js2xmlparser");
14
14
  const logger_1 = require("../logger");
15
- const sfdxError_1 = require("../sfdxError");
16
- const jsonXmlTools_1 = require("../util/jsonXmlTools");
17
- const zipWriter_1 = require("../util/zipWriter");
15
+ const sfError_1 = require("../sfError");
18
16
  const pollingClient_1 = require("../status/pollingClient");
17
+ const zipWriter_1 = require("../util/zipWriter");
18
+ const directoryWriter_1 = require("../util/directoryWriter");
19
19
  var RequestStatus;
20
20
  (function (RequestStatus) {
21
21
  RequestStatus["Pending"] = "Pending";
@@ -27,24 +27,141 @@ var RequestStatus;
27
27
  RequestStatus["Canceled"] = "Canceled";
28
28
  })(RequestStatus = exports.RequestStatus || (exports.RequestStatus = {}));
29
29
  const breakPolling = ['Succeeded', 'SucceededPartial', 'Failed', 'Canceled'];
30
+ const createObjectFileContent = ({ allRecordTypes = [], allBusinessProcesses = [], apiVersion, settingData, objectSettingsData, }) => {
31
+ const output = {
32
+ '@': {
33
+ xmlns: 'http://soap.sforce.com/2006/04/metadata',
34
+ },
35
+ types: [],
36
+ };
37
+ if (settingData) {
38
+ const strings = Object.keys(settingData).map((item) => (0, kit_1.upperFirst)(item).replace('Settings', ''));
39
+ output.types.push({ members: strings, name: 'Settings' });
40
+ }
41
+ if (objectSettingsData) {
42
+ const strings = Object.keys(objectSettingsData).map((item) => (0, kit_1.upperFirst)(item));
43
+ output.types.push({ members: strings, name: 'CustomObject' });
44
+ if (allRecordTypes.length > 0) {
45
+ output.types.push({ members: allRecordTypes, name: 'RecordType' });
46
+ }
47
+ if (allBusinessProcesses.length > 0) {
48
+ output.types.push({ members: allBusinessProcesses, name: 'BusinessProcess' });
49
+ }
50
+ }
51
+ return { ...output, ...{ version: apiVersion } };
52
+ };
53
+ exports.createObjectFileContent = createObjectFileContent;
54
+ const calculateBusinessProcess = (objectName, defaultRecordType) => {
55
+ let businessProcessName = null;
56
+ let businessProcessPicklistVal = null;
57
+ // These four objects require any record type to specify a "business process"--
58
+ // a restricted set of items from a standard picklist on the object.
59
+ if (['Case', 'Lead', 'Opportunity', 'Solution'].includes(objectName)) {
60
+ businessProcessName = (0, kit_1.upperFirst)(defaultRecordType) + 'Process';
61
+ switch (objectName) {
62
+ case 'Case':
63
+ businessProcessPicklistVal = 'New';
64
+ break;
65
+ case 'Lead':
66
+ businessProcessPicklistVal = 'New - Not Contacted';
67
+ break;
68
+ case 'Opportunity':
69
+ businessProcessPicklistVal = 'Prospecting';
70
+ break;
71
+ case 'Solution':
72
+ businessProcessPicklistVal = 'Draft';
73
+ }
74
+ }
75
+ return [businessProcessName, businessProcessPicklistVal];
76
+ };
77
+ const createRecordTypeAndBusinessProcessFileContent = (objectName, json, allRecordTypes, allBusinessProcesses) => {
78
+ let output = {
79
+ '@': {
80
+ xmlns: 'http://soap.sforce.com/2006/04/metadata',
81
+ },
82
+ };
83
+ const name = (0, kit_1.upperFirst)(objectName);
84
+ const sharingModel = json.sharingModel;
85
+ if (sharingModel) {
86
+ output = {
87
+ ...output,
88
+ sharingModel: (0, kit_1.upperFirst)(sharingModel),
89
+ };
90
+ }
91
+ const defaultRecordType = json.defaultRecordType;
92
+ if (typeof defaultRecordType === 'string') {
93
+ // We need to keep track of these globally for when we generate the package XML.
94
+ allRecordTypes.push(`${name}.${(0, kit_1.upperFirst)(defaultRecordType)}`);
95
+ const [businessProcessName, businessProcessPicklistVal] = calculateBusinessProcess(name, defaultRecordType);
96
+ // Create the record type
97
+ const recordTypes = {
98
+ fullName: (0, kit_1.upperFirst)(defaultRecordType),
99
+ label: (0, kit_1.upperFirst)(defaultRecordType),
100
+ active: true,
101
+ };
102
+ output = {
103
+ ...output,
104
+ recordTypes: {
105
+ ...recordTypes,
106
+ },
107
+ };
108
+ if (businessProcessName) {
109
+ // We need to keep track of these globally for the package.xml
110
+ const values = {
111
+ fullName: businessProcessPicklistVal,
112
+ };
113
+ if (name !== 'Opportunity') {
114
+ values.default = true;
115
+ }
116
+ allBusinessProcesses.push(`${name}.${businessProcessName}`);
117
+ output = {
118
+ ...output,
119
+ recordTypes: {
120
+ ...recordTypes,
121
+ businessProcess: businessProcessName,
122
+ },
123
+ businessProcesses: {
124
+ fullName: businessProcessName,
125
+ isActive: true,
126
+ values,
127
+ },
128
+ };
129
+ }
130
+ }
131
+ return output;
132
+ };
133
+ exports.createRecordTypeAndBusinessProcessFileContent = createRecordTypeAndBusinessProcessFileContent;
30
134
  /**
31
135
  * Helper class for dealing with the settings that are defined in a scratch definition file. This class knows how to extract the
32
136
  * settings from the definition, how to expand them into a MD directory and how to generate a package.xml.
33
137
  */
34
138
  class SettingsGenerator {
35
- constructor() {
36
- this.shapeDirName = `shape_${Date.now()}`;
139
+ constructor(options) {
140
+ this.allRecordTypes = [];
141
+ this.allBusinessProcesses = [];
37
142
  this.logger = logger_1.Logger.childFromRoot('SettingsGenerator');
38
143
  // If SFDX_MDAPI_TEMP_DIR is set, copy settings to that dir for people to inspect.
39
- const mdapiTmpDir = kit_1.env.getString('SFDX_MDAPI_TEMP_DIR');
40
- this.writer = new zipWriter_1.ZipWriter(mdapiTmpDir);
144
+ const mdApiTmpDir = options?.mdApiTmpDir ?? kit_1.env.getString('SFDX_MDAPI_TEMP_DIR');
145
+ this.shapeDirName = options?.shapeDirName ?? `shape_${Date.now()}`;
146
+ this.packageFilePath = path.join(this.shapeDirName, 'package.xml');
147
+ let storePath;
148
+ if (!options?.asDirectory) {
149
+ storePath = mdApiTmpDir ? path.join(mdApiTmpDir, `${this.shapeDirName}.zip`) : undefined;
150
+ this.writer = new zipWriter_1.ZipWriter(storePath);
151
+ }
152
+ else {
153
+ storePath = mdApiTmpDir ? path.join(mdApiTmpDir, this.shapeDirName) : undefined;
154
+ this.writer = new directoryWriter_1.DirectoryWriter(storePath);
155
+ }
41
156
  }
42
157
  /** extract the settings from the scratch def file, if they are present. */
158
+ // eslint-disable-next-line @typescript-eslint/require-await
43
159
  async extract(scratchDef) {
44
160
  this.logger.debug('extracting settings from scratch definition file');
45
161
  this.settingData = scratchDef.settings;
46
162
  this.objectSettingsData = scratchDef.objectSettings;
47
163
  this.logger.debug('settings are', this.settingData);
164
+ return { settings: this.settingData, objectSettings: this.objectSettingsData };
48
165
  }
49
166
  /** True if we are currently tracking setting or object setting data. */
50
167
  hasSettings() {
@@ -56,16 +173,18 @@ class SettingsGenerator {
56
173
  async createDeploy() {
57
174
  const settingsDir = path.join(this.shapeDirName, 'settings');
58
175
  const objectsDir = path.join(this.shapeDirName, 'objects');
59
- await Promise.all([this.writeSettingsIfNeeded(settingsDir), this.writeObjectSettingsIfNeeded(objectsDir)]);
176
+ await Promise.all([
177
+ this.writeSettingsIfNeeded(settingsDir),
178
+ this.writeObjectSettingsIfNeeded(objectsDir, this.allRecordTypes, this.allBusinessProcesses),
179
+ ]);
60
180
  }
61
181
  /**
62
182
  * Deploys the settings to the org.
63
183
  */
64
- async deploySettingsViaFolder(scratchOrg, apiVersion) {
184
+ async deploySettingsViaFolder(scratchOrg, apiVersion, timeout = kit_1.Duration.minutes(10)) {
65
185
  const username = scratchOrg.getUsername();
66
186
  const logger = await logger_1.Logger.child('deploySettingsViaFolder');
67
- this.createPackageXml(apiVersion);
68
- await this.writer.finalize();
187
+ await this.createDeployPackageContents(apiVersion);
69
188
  const connection = scratchOrg.getConnection();
70
189
  logger.debug(`deploying to apiVersion: ${apiVersion}`);
71
190
  connection.setApiVersion(apiVersion);
@@ -96,7 +215,7 @@ class SettingsGenerator {
96
215
  };
97
216
  }
98
217
  },
99
- timeout: kit_1.Duration.minutes(10),
218
+ timeout,
100
219
  frequency: kit_1.Duration.seconds(1),
101
220
  timeoutErrorName: 'DeployingSettingsTimeoutError',
102
221
  };
@@ -107,104 +226,52 @@ class SettingsGenerator {
107
226
  const failures = (Array.isArray(componentFailures) ? componentFailures : [componentFailures])
108
227
  .map((failure) => failure.problem)
109
228
  .join('\n');
110
- const error = new sfdxError_1.SfdxError(`A scratch org was created with username ${username}, but the settings failed to deploy due to: \n${failures}`, 'ProblemDeployingSettings');
229
+ const error = new sfError_1.SfError(`A scratch org was created with username ${username}, but the settings failed to deploy due to: \n${failures}`, 'ProblemDeployingSettings');
111
230
  error.setData(result);
112
231
  throw error;
113
232
  }
114
233
  }
115
- async writeObjectSettingsIfNeeded(objectsDir) {
116
- if (!this.objectSettingsData || !Object.keys(this.objectSettingsData).length) {
117
- return;
118
- }
119
- for (const objectName of Object.keys(this.objectSettingsData)) {
120
- const value = this.objectSettingsData[objectName];
121
- // writes the object file in source format
122
- const objectDir = path.join(objectsDir, (0, kit_1.upperFirst)(objectName));
123
- const customObjectDir = path.join(objectDir, `${(0, kit_1.upperFirst)(objectName)}.object`);
124
- const customObjectXml = (0, jsonXmlTools_1.JsonAsXml)({
125
- json: this.createObjectFileContent(value),
126
- type: 'RecordType',
127
- });
128
- this.writer.addToZip(customObjectXml, customObjectDir);
129
- if (value.defaultRecordType) {
130
- const recordTypesDir = path.join(objectDir, 'recordTypes', `${(0, kit_1.upperFirst)(value.defaultRecordType)}.recordType`);
131
- const recordTypesFileContent = this.createRecordTypeFileContent(objectName, value);
132
- const recordTypesXml = (0, jsonXmlTools_1.JsonAsXml)({
133
- json: recordTypesFileContent,
134
- type: 'RecordType',
135
- });
136
- this.writer.addToZip(recordTypesXml, recordTypesDir);
137
- // for things that required a businessProcess
138
- if (recordTypesFileContent.businessProcess) {
139
- const businessProcessesDir = path.join(objectDir, 'businessProcesses', `${recordTypesFileContent.businessProcess}.businessProcess`);
140
- const businessProcessesXml = (0, jsonXmlTools_1.JsonAsXml)({
141
- json: this.createBusinessProcessFileContent(objectName, recordTypesFileContent.businessProcess),
142
- type: 'BusinessProcess',
143
- });
144
- this.writer.addToZip(businessProcessesXml, businessProcessesDir);
145
- }
146
- }
234
+ async createDeployPackageContents(apiVersion) {
235
+ const packageObjectProps = (0, exports.createObjectFileContent)({
236
+ allRecordTypes: this.allRecordTypes,
237
+ allBusinessProcesses: this.allBusinessProcesses,
238
+ apiVersion,
239
+ settingData: this.settingData,
240
+ objectSettingsData: this.objectSettingsData,
241
+ });
242
+ const xml = js2xmlparser.parse('Package', packageObjectProps);
243
+ await this.writer.addToStore(xml, this.packageFilePath);
244
+ await this.writer.finalize();
245
+ }
246
+ getShapeDirName() {
247
+ return this.shapeDirName;
248
+ }
249
+ /**
250
+ * Returns the destination where the writer placed the settings content.
251
+ *
252
+ */
253
+ getDestinationPath() {
254
+ return this.writer.getDestinationPath();
255
+ }
256
+ async writeObjectSettingsIfNeeded(objectsDir, allRecordTypes, allbusinessProcesses) {
257
+ if (this.objectSettingsData) {
258
+ await Promise.all(Object.entries(this.objectSettingsData).map(([item, value]) => {
259
+ const fileContent = (0, exports.createRecordTypeAndBusinessProcessFileContent)(item, value, allRecordTypes, allbusinessProcesses);
260
+ const xml = js2xmlparser.parse('CustomObject', fileContent);
261
+ return this.writer.addToStore(xml, path.join(objectsDir, (0, kit_1.upperFirst)(item) + '.object'));
262
+ }));
147
263
  }
148
264
  }
149
265
  async writeSettingsIfNeeded(settingsDir) {
150
266
  if (this.settingData) {
151
- for (const item of Object.keys(this.settingData)) {
152
- const value = (0, ts_types_1.getObject)(this.settingData, item);
267
+ await Promise.all(Object.entries(this.settingData).map(([item, value]) => {
153
268
  const typeName = (0, kit_1.upperFirst)(item);
154
269
  const fname = typeName.replace('Settings', '');
155
270
  const fileContent = js2xmlparser.parse(typeName, value);
156
- this.writer.addToZip(fileContent, path.join(settingsDir, fname + '.settings'));
157
- }
271
+ return this.writer.addToStore(fileContent, path.join(settingsDir, fname + '.settings'));
272
+ }));
158
273
  }
159
274
  }
160
- createPackageXml(apiVersion) {
161
- const pkg = `<?xml version="1.0" encoding="UTF-8"?>
162
- <Package xmlns="http://soap.sforce.com/2006/04/metadata">
163
- <types>
164
- <members>*</members>
165
- <name>Settings</name>
166
- </types>
167
- <types>
168
- <members>*</members>
169
- <name>CustomObject</name>
170
- </types>
171
- <version>${apiVersion}</version>
172
- </Package>`;
173
- this.writer.addToZip(pkg, path.join(this.shapeDirName, 'package.xml'));
174
- }
175
- createObjectFileContent(json) {
176
- const output = {};
177
- if (json.sharingModel) {
178
- output.sharingModel = (0, kit_1.upperFirst)(json.sharingModel);
179
- }
180
- return output;
181
- }
182
- createRecordTypeFileContent(objectName, setting) {
183
- const defaultRecordType = (0, kit_1.upperFirst)(setting.defaultRecordType);
184
- const output = {
185
- fullName: defaultRecordType,
186
- label: defaultRecordType,
187
- active: true,
188
- };
189
- // all the edge cases
190
- if (['Case', 'Lead', 'Opportunity', 'Solution'].includes((0, kit_1.upperFirst)(objectName))) {
191
- return { ...output, businessProcess: `${defaultRecordType}Process` };
192
- }
193
- return output;
194
- }
195
- createBusinessProcessFileContent(objectName, businessProcessName) {
196
- const objectToBusinessProcessPicklist = {
197
- Opportunity: { fullName: 'Prospecting' },
198
- Case: { fullName: 'New', default: true },
199
- Lead: { fullName: 'New - Not Contacted', default: true },
200
- Solution: { fullName: 'Draft', default: true },
201
- };
202
- return {
203
- fullName: businessProcessName,
204
- isActive: true,
205
- values: [objectToBusinessProcessPicklist[(0, kit_1.upperFirst)(objectName)]],
206
- };
207
- }
208
275
  }
209
276
  exports.default = SettingsGenerator;
210
277
  //# sourceMappingURL=scratchOrgSettingsGenerator.js.map
@@ -0,0 +1,43 @@
1
+ import { JsonMap } from '@salesforce/ts-types';
2
+ export interface ScratchOrgInfo {
3
+ AdminEmail?: string;
4
+ readonly CreatedDate?: string;
5
+ ConnectedAppCallbackUrl?: string;
6
+ ConnectedAppConsumerKey?: string;
7
+ Country?: string;
8
+ Description?: string;
9
+ DurationDays?: number;
10
+ Edition?: string;
11
+ readonly ErrorCode?: string;
12
+ readonly ExpirationDate?: string;
13
+ Features?: string;
14
+ HasSampleData?: boolean;
15
+ readonly Id?: string;
16
+ Language?: string;
17
+ LoginUrl: string;
18
+ readonly Name?: string;
19
+ Namespace?: string;
20
+ OrgName?: string;
21
+ Release?: 'Current' | 'Previous' | 'Preview';
22
+ readonly ScratchOrg?: string;
23
+ SourceOrg?: string;
24
+ readonly AuthCode: string;
25
+ Snapshot?: string;
26
+ readonly Status: 'New' | 'Creating' | 'Active' | 'Error' | 'Deleted';
27
+ readonly SignupEmail: string;
28
+ readonly SignupUsername: string;
29
+ readonly SignupInstance: string;
30
+ Username: string;
31
+ settings?: Record<string, unknown>;
32
+ objectSettings?: {
33
+ [objectName: string]: ObjectSetting;
34
+ };
35
+ orgPreferences?: {
36
+ enabled: string[];
37
+ disabled: string[];
38
+ };
39
+ }
40
+ export interface ObjectSetting extends JsonMap {
41
+ sharingModel?: string;
42
+ defaultRecordType?: string;
43
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2020, 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
+ //# sourceMappingURL=scratchOrgTypes.js.map
package/lib/org/user.d.ts CHANGED
@@ -22,7 +22,7 @@ export declare const REQUIRED_FIELDS: {
22
22
  *
23
23
  * **See** https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_user.htm
24
24
  */
25
- export declare type UserFields = {
25
+ export type UserFields = {
26
26
  -readonly [K in keyof typeof REQUIRED_FIELDS]: string;
27
27
  };
28
28
  /**
package/lib/org/user.js CHANGED
@@ -14,7 +14,7 @@ const http_api_1 = require("jsforce/lib/http-api");
14
14
  const logger_1 = require("../logger");
15
15
  const messages_1 = require("../messages");
16
16
  const secureBuffer_1 = require("../crypto/secureBuffer");
17
- const sfdxError_1 = require("../sfdxError");
17
+ const sfError_1 = require("../sfError");
18
18
  const sfdc_1 = require("../util/sfdc");
19
19
  const connection_1 = require("./connection");
20
20
  const permissionSetAssignment_1 = require("./permissionSetAssignment");
@@ -36,16 +36,7 @@ const PASSWORD_COMPLEXITY = {
36
36
  };
37
37
  const scimEndpoint = '/services/scim/v1/Users';
38
38
  const scimHeaders = { 'auto-approve-user': 'true' };
39
- messages_1.Messages.importMessagesDirectory(__dirname);
40
- const messages = messages_1.Messages.load('@salesforce/core', 'user', [
41
- 'invalidHttpResponseCreatingUser',
42
- 'userQueryFailed',
43
- 'missingId',
44
- 'permsetNamesAreRequired',
45
- 'missingFields',
46
- 'lengthOutOfBound',
47
- 'complexityOutOfBound',
48
- ]);
39
+ const messages = new messages_1.Messages('@salesforce/core', 'user', new Map([["orgRequired", "An org instance is required."], ["userQueryFailed", "Failed to query for the user %s."], ["invalidHttpResponseCreatingUser", "An invalid http response code (%s) was received while trying to create a user."], ["missingFields", "The fields parameters is undefined."], ["missingId", "The Salesforce id for the user is required."], ["permsetNamesAreRequired", "The permission set names are missing but required."], ["complexityOutOfBound", "Invalid complexity value. Specify a value between 0 and 5, inclusive."], ["lengthOutOfBound", "Invalid length value. Specify a value between 8 and 1000, inclusive."], ["problemsDescribingTheUserObject", "Problems occurred while attempting to describe the user object."]]));
49
40
  /**
50
41
  * A Map of Required Salesforce User fields.
51
42
  */
@@ -71,7 +62,7 @@ async function retrieveUserFields(logger, username) {
71
62
  const connection = await connection_1.Connection.create({
72
63
  authInfo: await authInfo_1.AuthInfo.create({ username }),
73
64
  });
74
- if (sfdc_1.sfdc.matchesAccessToken(username)) {
65
+ if ((0, sfdc_1.matchesAccessToken)(username)) {
75
66
  logger.debug('received an accessToken for the username. Converting...');
76
67
  username = (await connection.identity()).username;
77
68
  logger.debug(`accessToken converted to ${username}`);
@@ -80,22 +71,23 @@ async function retrieveUserFields(logger, username) {
80
71
  logger.debug('not a accessToken');
81
72
  }
82
73
  const fromFields = Object.keys(exports.REQUIRED_FIELDS).map(kit_1.upperFirst);
74
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
83
75
  const requiredFieldsFromAdminQuery = `SELECT ${fromFields} FROM User WHERE Username='${username}'`;
84
76
  const result = await connection.query(requiredFieldsFromAdminQuery);
85
77
  logger.debug('Successfully retrieved the admin user for this org.');
86
78
  if (result.totalSize === 1) {
87
79
  const results = (0, kit_1.mapKeys)(result.records[0], (value, key) => (0, kit_1.lowerFirst)(key));
88
80
  const fields = {
89
- id: (0, ts_types_1.ensure)((0, ts_types_1.getString)(results, exports.REQUIRED_FIELDS.id)),
81
+ id: (0, ts_types_1.ensureString)(results[exports.REQUIRED_FIELDS.id]),
90
82
  username,
91
- alias: (0, ts_types_1.ensure)((0, ts_types_1.getString)(results, exports.REQUIRED_FIELDS.alias)),
92
- email: (0, ts_types_1.ensure)((0, ts_types_1.getString)(results, exports.REQUIRED_FIELDS.email)),
93
- emailEncodingKey: (0, ts_types_1.ensure)((0, ts_types_1.getString)(results, exports.REQUIRED_FIELDS.emailEncodingKey)),
94
- languageLocaleKey: (0, ts_types_1.ensure)((0, ts_types_1.getString)(results, exports.REQUIRED_FIELDS.languageLocaleKey)),
95
- localeSidKey: (0, ts_types_1.ensure)((0, ts_types_1.getString)(results, exports.REQUIRED_FIELDS.localeSidKey)),
96
- profileId: (0, ts_types_1.ensure)((0, ts_types_1.getString)(results, exports.REQUIRED_FIELDS.profileId)),
97
- lastName: (0, ts_types_1.ensure)((0, ts_types_1.getString)(results, exports.REQUIRED_FIELDS.lastName)),
98
- timeZoneSidKey: (0, ts_types_1.ensure)((0, ts_types_1.getString)(results, exports.REQUIRED_FIELDS.timeZoneSidKey)),
83
+ alias: (0, ts_types_1.ensureString)(results[exports.REQUIRED_FIELDS.alias]),
84
+ email: (0, ts_types_1.ensureString)(results[exports.REQUIRED_FIELDS.email]),
85
+ emailEncodingKey: (0, ts_types_1.ensureString)(results[exports.REQUIRED_FIELDS.emailEncodingKey]),
86
+ languageLocaleKey: (0, ts_types_1.ensureString)(results[exports.REQUIRED_FIELDS.languageLocaleKey]),
87
+ localeSidKey: (0, ts_types_1.ensureString)(results[exports.REQUIRED_FIELDS.localeSidKey]),
88
+ profileId: (0, ts_types_1.ensureString)(results[exports.REQUIRED_FIELDS.profileId]),
89
+ lastName: (0, ts_types_1.ensureString)(results[exports.REQUIRED_FIELDS.lastName]),
90
+ timeZoneSidKey: (0, ts_types_1.ensureString)(results[exports.REQUIRED_FIELDS.timeZoneSidKey]),
99
91
  };
100
92
  return fields;
101
93
  }
@@ -110,7 +102,7 @@ async function retrieveUserFields(logger, username) {
110
102
  * @param connection The connection for the query.
111
103
  */
112
104
  async function retrieveProfileId(name, connection) {
113
- if (!sfdc_1.sfdc.validateSalesforceId(name)) {
105
+ if (!(0, sfdc_1.validateSalesforceId)(name)) {
114
106
  const profileQuery = `SELECT Id FROM Profile WHERE name='${name}'`;
115
107
  const result = await connection.query(profileQuery);
116
108
  if (result.records.length > 0) {
@@ -185,11 +177,11 @@ class User extends kit_1.AsyncCreatable {
185
177
  static generatePasswordUtf8(passwordCondition = { length: 13, complexity: 5 }) {
186
178
  if (!PASSWORD_COMPLEXITY[passwordCondition.complexity]) {
187
179
  const msg = messages.getMessage('complexityOutOfBound');
188
- throw new sfdxError_1.SfdxError(msg, 'complexityOutOfBound');
180
+ throw new sfError_1.SfError(msg, 'complexityOutOfBound');
189
181
  }
190
182
  if (passwordCondition.length < 8 || passwordCondition.length > 1000) {
191
183
  const msg = messages.getMessage('lengthOutOfBound');
192
- throw new sfdxError_1.SfdxError(msg, 'lengthOutOfBound');
184
+ throw new sfError_1.SfError(msg, 'lengthOutOfBound');
193
185
  }
194
186
  let password = [];
195
187
  ['SYMBOLS', 'NUMBERS', 'UPPER', 'LOWER'].forEach((charSet) => {
@@ -225,10 +217,10 @@ class User extends kit_1.AsyncCreatable {
225
217
  this.logger.debug(`Attempting to set password for userId: ${info.getFields().userId} username: ${info.getFields().username}`);
226
218
  const userConnection = await connection_1.Connection.create({ authInfo: info });
227
219
  return new Promise((resolve, reject) => {
220
+ // no promises in async method
228
221
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
229
222
  password.value(async (buffer) => {
230
223
  try {
231
- // @ts-ignore TODO: expose `soap` on Connection however appropriate
232
224
  const soap = userConnection.soap;
233
225
  await soap.setPassword((0, ts_types_1.ensureString)(info.getFields().userId), buffer.toString('utf8'));
234
226
  this.logger.debug(`Set password for userId: ${info.getFields().userId}`);
@@ -265,9 +257,7 @@ class User extends kit_1.AsyncCreatable {
265
257
  throw messages.createError('permsetNamesAreRequired');
266
258
  }
267
259
  const assignments = await permissionSetAssignment_1.PermissionSetAssignment.init(this.org);
268
- for (const permsetName of permsetNames) {
269
- await assignments.create(id, permsetName);
270
- }
260
+ await Promise.all(permsetNames.map((permsetName) => assignments.create(id, permsetName)));
271
261
  }
272
262
  /**
273
263
  * Method for creating a new User.
@@ -293,7 +283,6 @@ class User extends kit_1.AsyncCreatable {
293
283
  * ```
294
284
  */
295
285
  async createUser(fields) {
296
- var _a;
297
286
  // Create a user and get a refresh token
298
287
  const refreshTokenSecret = await this.createUserInternal(fields);
299
288
  // Create the initial auth info
@@ -302,7 +291,7 @@ class User extends kit_1.AsyncCreatable {
302
291
  // Setup oauth options for the new user
303
292
  const oauthOptions = {
304
293
  // Communities users require the instance for auth
305
- loginUrl: (_a = adminUserAuthFields.instanceUrl) !== null && _a !== void 0 ? _a : adminUserAuthFields.loginUrl,
294
+ loginUrl: adminUserAuthFields.instanceUrl ?? adminUserAuthFields.loginUrl,
306
295
  refreshToken: refreshTokenSecret.buffer.value((buffer) => buffer.toString('utf8')),
307
296
  clientId: adminUserAuthFields.clientId,
308
297
  clientSecret: adminUserAuthFields.clientSecret,
@@ -338,7 +327,7 @@ class User extends kit_1.AsyncCreatable {
338
327
  * ```
339
328
  */
340
329
  async retrieve(username) {
341
- return await retrieveUserFields(this.logger, username);
330
+ return retrieveUserFields(this.logger, username);
342
331
  }
343
332
  /**
344
333
  * Helper method that verifies the server's User object is available and if so allows persisting the Auth information.
@@ -349,7 +338,7 @@ class User extends kit_1.AsyncCreatable {
349
338
  const connection = await connection_1.Connection.create({ authInfo: newUserAuthInfo });
350
339
  this.logger.debug(`Created connection for user: ${newUserAuthInfo.getUsername()}`);
351
340
  const userDescribe = await connection.describe('User');
352
- if (userDescribe && userDescribe.fields) {
341
+ if (userDescribe?.fields) {
353
342
  await newUserAuthInfo.save();
354
343
  return newUserAuthInfo;
355
344
  }
@@ -402,12 +391,13 @@ class User extends kit_1.AsyncCreatable {
402
391
  errors.forEach((singleMessage) => {
403
392
  if (!(0, ts_types_1.isJsonMap)(singleMessage))
404
393
  return;
394
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
405
395
  message = `${message}${os_1.EOL}${singleMessage.description}`;
406
396
  });
407
397
  }
408
398
  }
409
399
  this.logger.debug(message);
410
- throw new sfdxError_1.SfdxError(message, 'UserCreateHttpError');
400
+ throw new sfError_1.SfError(message, 'UserCreateHttpError');
411
401
  }
412
402
  fields.id = (0, ts_types_1.ensureString)(responseBody.id);
413
403
  await this.updateRequiredUserFields(fields);
@@ -420,9 +410,10 @@ class User extends kit_1.AsyncCreatable {
420
410
  userId: fields.id,
421
411
  };
422
412
  }
413
+ // eslint-disable-next-line class-methods-use-this
423
414
  async rawRequest(conn, options) {
424
415
  return new Promise((resolve, reject) => {
425
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
416
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
426
417
  const httpApi = new http_api_1.HttpApi(conn, options);
427
418
  httpApi.on('response', (response) => resolve(response));
428
419
  httpApi.request(options).catch(reject);
@@ -3,6 +3,9 @@ import { Logger } from '../logger';
3
3
  /**
4
4
  * Renders schema properties. By default, this is simply an identity transform. Subclasses may provide more
5
5
  * interesting decorations of each values, such as ANSI coloring.
6
+ *
7
+ * @deprecated
8
+ *
6
9
  */
7
10
  export declare class SchemaPropertyRenderer {
8
11
  /**
@@ -33,6 +36,9 @@ export declare class SchemaPropertyRenderer {
33
36
  /**
34
37
  * Prints a JSON schema in a human-friendly format.
35
38
  *
39
+ * @deprecated
40
+ * remaining reference: https://github.com/salesforcecli/plugin-data/blob/cc1bdfa2c707f93a6da96beea8117b25f9612d4a/src/commands/data/import/tree.ts#L75
41
+ *
36
42
  * ```
37
43
  * import chalk from 'chalk';
38
44
  * class MyPropertyRenderer extends SchemaPropertyRenderer {