@salesforce/core 3.7.5 → 3.7.8

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 (79) hide show
  1. package/CHANGELOG.md +219 -0
  2. package/README.md +4 -4
  3. package/lib/config/config.d.ts +7 -5
  4. package/lib/config/config.js +14 -9
  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 +22 -20
  9. package/lib/config/configStore.js +7 -6
  10. package/lib/config/keychainConfig.js +4 -3
  11. package/lib/crypto/keyChainImpl.js +12 -11
  12. package/lib/deviceOauthService.js +2 -2
  13. package/lib/exported.d.ts +6 -5
  14. package/lib/exported.js +11 -7
  15. package/lib/global.js +2 -2
  16. package/lib/globalInfo/accessors/aliasAccessor.js +2 -2
  17. package/lib/globalInfo/sfdxDataHandler.d.ts +1 -1
  18. package/lib/globalInfo/sfdxDataHandler.js +5 -4
  19. package/lib/lifecycleEvents.js +1 -1
  20. package/lib/logger.d.ts +3 -3
  21. package/lib/logger.js +20 -19
  22. package/lib/messages.d.ts +42 -3
  23. package/lib/messages.js +55 -12
  24. package/lib/org/authInfo.d.ts +1 -1
  25. package/lib/org/authInfo.js +8 -9
  26. package/lib/org/authRemover.d.ts +2 -2
  27. package/lib/org/authRemover.js +2 -2
  28. package/lib/org/connection.d.ts +7 -2
  29. package/lib/org/connection.js +17 -4
  30. package/lib/org/org.d.ts +16 -6
  31. package/lib/org/org.js +54 -51
  32. package/lib/org/permissionSetAssignment.js +2 -2
  33. package/lib/org/scratchOrgCreate.d.ts +43 -0
  34. package/lib/org/scratchOrgCreate.js +142 -0
  35. package/lib/org/scratchOrgErrorCodes.d.ts +4 -0
  36. package/lib/org/scratchOrgErrorCodes.js +62 -0
  37. package/lib/org/scratchOrgFeatureDeprecation.d.ts +26 -0
  38. package/lib/org/scratchOrgFeatureDeprecation.js +110 -0
  39. package/lib/org/scratchOrgInfoApi.d.ts +94 -0
  40. package/lib/org/scratchOrgInfoApi.js +350 -0
  41. package/lib/org/scratchOrgInfoGenerator.d.ts +63 -0
  42. package/lib/org/scratchOrgInfoGenerator.js +223 -0
  43. package/lib/org/scratchOrgSettingsGenerator.d.ts +56 -0
  44. package/lib/org/scratchOrgSettingsGenerator.js +210 -0
  45. package/lib/org/user.js +8 -7
  46. package/lib/schema/printer.js +2 -2
  47. package/lib/schema/validator.d.ts +4 -4
  48. package/lib/schema/validator.js +13 -13
  49. package/lib/{sfdxError.d.ts → sfError.d.ts} +14 -14
  50. package/lib/{sfdxError.js → sfError.js} +20 -21
  51. package/lib/{sfdxProject.d.ts → sfProject.d.ts} +37 -27
  52. package/lib/{sfdxProject.js → sfProject.js} +77 -65
  53. package/lib/status/pollingClient.d.ts +2 -2
  54. package/lib/status/pollingClient.js +10 -4
  55. package/lib/status/streamingClient.d.ts +1 -1
  56. package/lib/status/streamingClient.js +6 -6
  57. package/lib/testSetup.d.ts +4 -4
  58. package/lib/testSetup.js +8 -8
  59. package/lib/util/internal.d.ts +28 -2
  60. package/lib/util/internal.js +64 -6
  61. package/lib/util/jsonXmlTools.d.ts +14 -0
  62. package/lib/util/jsonXmlTools.js +41 -0
  63. package/lib/util/mapKeys.d.ts +14 -0
  64. package/lib/util/mapKeys.js +48 -0
  65. package/lib/util/sfdcUrl.d.ts +2 -2
  66. package/lib/util/sfdcUrl.js +2 -2
  67. package/lib/util/zipWriter.d.ts +14 -0
  68. package/lib/util/zipWriter.js +68 -0
  69. package/lib/webOAuthServer.js +11 -11
  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 +4 -1
  78. package/lib/util/fs.d.ts +0 -201
  79. package/lib/util/fs.js +0 -378
@@ -0,0 +1,56 @@
1
+ import { JsonMap } from '@salesforce/ts-types';
2
+ import { ScratchOrgInfo } from './scratchOrgInfoApi';
3
+ import { Org } from './org';
4
+ export declare enum RequestStatus {
5
+ Pending = "Pending",
6
+ InProgress = "InProgress",
7
+ Succeeded = "Succeeded",
8
+ SucceededPartial = "SucceededPartial",
9
+ Failed = "Failed",
10
+ Canceling = "Canceling",
11
+ Canceled = "Canceled"
12
+ }
13
+ export interface ObjectSetting extends JsonMap {
14
+ sharingModel?: string;
15
+ defaultRecordType?: string;
16
+ }
17
+ export interface BusinessProcessFileContent extends JsonMap {
18
+ fullName: string;
19
+ isActive: boolean;
20
+ values: [
21
+ {
22
+ fullName: string;
23
+ default?: boolean;
24
+ }
25
+ ];
26
+ }
27
+ /**
28
+ * Helper class for dealing with the settings that are defined in a scratch definition file. This class knows how to extract the
29
+ * settings from the definition, how to expand them into a MD directory and how to generate a package.xml.
30
+ */
31
+ export default class SettingsGenerator {
32
+ private settingData?;
33
+ private objectSettingsData?;
34
+ private logger;
35
+ private writer;
36
+ private shapeDirName;
37
+ constructor();
38
+ /** extract the settings from the scratch def file, if they are present. */
39
+ extract(scratchDef: ScratchOrgInfo): Promise<void>;
40
+ /** True if we are currently tracking setting or object setting data. */
41
+ hasSettings(): boolean;
42
+ /** Create temporary deploy directory used to upload the scratch org shape.
43
+ * This will create the dir, all of the .setting files and minimal object files needed for objectSettings
44
+ */
45
+ createDeploy(): Promise<void>;
46
+ /**
47
+ * Deploys the settings to the org.
48
+ */
49
+ deploySettingsViaFolder(scratchOrg: Org, apiVersion: string): Promise<void>;
50
+ private writeObjectSettingsIfNeeded;
51
+ private writeSettingsIfNeeded;
52
+ private createPackageXml;
53
+ private createObjectFileContent;
54
+ private createRecordTypeFileContent;
55
+ private createBusinessProcessFileContent;
56
+ }
@@ -0,0 +1,210 @@
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.RequestStatus = void 0;
10
+ const path = require("path");
11
+ const kit_1 = require("@salesforce/kit");
12
+ const ts_types_1 = require("@salesforce/ts-types");
13
+ const js2xmlparser = require("js2xmlparser");
14
+ const logger_1 = require("../logger");
15
+ const sfError_1 = require("../sfError");
16
+ const jsonXmlTools_1 = require("../util/jsonXmlTools");
17
+ const zipWriter_1 = require("../util/zipWriter");
18
+ const pollingClient_1 = require("../status/pollingClient");
19
+ var RequestStatus;
20
+ (function (RequestStatus) {
21
+ RequestStatus["Pending"] = "Pending";
22
+ RequestStatus["InProgress"] = "InProgress";
23
+ RequestStatus["Succeeded"] = "Succeeded";
24
+ RequestStatus["SucceededPartial"] = "SucceededPartial";
25
+ RequestStatus["Failed"] = "Failed";
26
+ RequestStatus["Canceling"] = "Canceling";
27
+ RequestStatus["Canceled"] = "Canceled";
28
+ })(RequestStatus = exports.RequestStatus || (exports.RequestStatus = {}));
29
+ const breakPolling = ['Succeeded', 'SucceededPartial', 'Failed', 'Canceled'];
30
+ /**
31
+ * Helper class for dealing with the settings that are defined in a scratch definition file. This class knows how to extract the
32
+ * settings from the definition, how to expand them into a MD directory and how to generate a package.xml.
33
+ */
34
+ class SettingsGenerator {
35
+ constructor() {
36
+ this.shapeDirName = `shape_${Date.now()}`;
37
+ this.logger = logger_1.Logger.childFromRoot('SettingsGenerator');
38
+ // 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);
41
+ }
42
+ /** extract the settings from the scratch def file, if they are present. */
43
+ async extract(scratchDef) {
44
+ this.logger.debug('extracting settings from scratch definition file');
45
+ this.settingData = scratchDef.settings;
46
+ this.objectSettingsData = scratchDef.objectSettings;
47
+ this.logger.debug('settings are', this.settingData);
48
+ }
49
+ /** True if we are currently tracking setting or object setting data. */
50
+ hasSettings() {
51
+ return !(0, kit_1.isEmpty)(this.settingData) || !(0, kit_1.isEmpty)(this.objectSettingsData);
52
+ }
53
+ /** Create temporary deploy directory used to upload the scratch org shape.
54
+ * This will create the dir, all of the .setting files and minimal object files needed for objectSettings
55
+ */
56
+ async createDeploy() {
57
+ const settingsDir = path.join(this.shapeDirName, 'settings');
58
+ const objectsDir = path.join(this.shapeDirName, 'objects');
59
+ await Promise.all([this.writeSettingsIfNeeded(settingsDir), this.writeObjectSettingsIfNeeded(objectsDir)]);
60
+ }
61
+ /**
62
+ * Deploys the settings to the org.
63
+ */
64
+ async deploySettingsViaFolder(scratchOrg, apiVersion) {
65
+ const username = scratchOrg.getUsername();
66
+ const logger = await logger_1.Logger.child('deploySettingsViaFolder');
67
+ this.createPackageXml(apiVersion);
68
+ await this.writer.finalize();
69
+ const connection = scratchOrg.getConnection();
70
+ logger.debug(`deploying to apiVersion: ${apiVersion}`);
71
+ connection.setApiVersion(apiVersion);
72
+ const { id } = await connection.deploy(this.writer.buffer, {});
73
+ logger.debug(`deploying settings id ${id}`);
74
+ let result = await connection.metadata.checkDeployStatus(id);
75
+ const pollingOptions = {
76
+ async poll() {
77
+ try {
78
+ result = await connection.metadata.checkDeployStatus(id, true);
79
+ logger.debug(`Deploy id: ${id} status: ${result.status}`);
80
+ if (breakPolling.includes(result.status)) {
81
+ return {
82
+ completed: true,
83
+ payload: result.status,
84
+ };
85
+ }
86
+ return {
87
+ completed: false,
88
+ };
89
+ }
90
+ catch (error) {
91
+ logger.debug(`An error occurred trying to check deploy id: ${id}`);
92
+ logger.debug(`Error: ${error.message}`);
93
+ logger.debug('Re-trying deploy check again....');
94
+ return {
95
+ completed: false,
96
+ };
97
+ }
98
+ },
99
+ timeout: kit_1.Duration.minutes(10),
100
+ frequency: kit_1.Duration.seconds(1),
101
+ timeoutErrorName: 'DeployingSettingsTimeoutError',
102
+ };
103
+ const client = await pollingClient_1.PollingClient.create(pollingOptions);
104
+ const status = await client.subscribe();
105
+ if (status !== RequestStatus.Succeeded) {
106
+ const componentFailures = (0, ts_types_1.ensureObject)(result.details).componentFailures;
107
+ const failures = (Array.isArray(componentFailures) ? componentFailures : [componentFailures])
108
+ .map((failure) => failure.problem)
109
+ .join('\n');
110
+ 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
+ error.setData(result);
112
+ throw error;
113
+ }
114
+ }
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
+ }
147
+ }
148
+ }
149
+ async writeSettingsIfNeeded(settingsDir) {
150
+ if (this.settingData) {
151
+ for (const item of Object.keys(this.settingData)) {
152
+ const value = (0, ts_types_1.getObject)(this.settingData, item);
153
+ const typeName = (0, kit_1.upperFirst)(item);
154
+ const fname = typeName.replace('Settings', '');
155
+ const fileContent = js2xmlparser.parse(typeName, value);
156
+ this.writer.addToZip(fileContent, path.join(settingsDir, fname + '.settings'));
157
+ }
158
+ }
159
+ }
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
+ }
209
+ exports.default = SettingsGenerator;
210
+ //# sourceMappingURL=scratchOrgSettingsGenerator.js.map
package/lib/org/user.js CHANGED
@@ -11,12 +11,12 @@ const os_1 = require("os");
11
11
  const kit_1 = require("@salesforce/kit");
12
12
  const ts_types_1 = require("@salesforce/ts-types");
13
13
  const http_api_1 = require("jsforce/lib/http-api");
14
- const connection_1 = require("../org/connection");
15
14
  const logger_1 = require("../logger");
16
15
  const messages_1 = require("../messages");
17
16
  const secureBuffer_1 = require("../crypto/secureBuffer");
18
- const sfdxError_1 = require("../sfdxError");
17
+ const sfError_1 = require("../sfError");
19
18
  const sfdc_1 = require("../util/sfdc");
19
+ const connection_1 = require("./connection");
20
20
  const permissionSetAssignment_1 = require("./permissionSetAssignment");
21
21
  const authInfo_1 = require("./authInfo");
22
22
  const rand = (len) => Math.floor(Math.random() * len.length);
@@ -185,11 +185,11 @@ class User extends kit_1.AsyncCreatable {
185
185
  static generatePasswordUtf8(passwordCondition = { length: 13, complexity: 5 }) {
186
186
  if (!PASSWORD_COMPLEXITY[passwordCondition.complexity]) {
187
187
  const msg = messages.getMessage('complexityOutOfBound');
188
- throw new sfdxError_1.SfdxError(msg, 'complexityOutOfBound');
188
+ throw new sfError_1.SfError(msg, 'complexityOutOfBound');
189
189
  }
190
190
  if (passwordCondition.length < 8 || passwordCondition.length > 1000) {
191
191
  const msg = messages.getMessage('lengthOutOfBound');
192
- throw new sfdxError_1.SfdxError(msg, 'lengthOutOfBound');
192
+ throw new sfError_1.SfError(msg, 'lengthOutOfBound');
193
193
  }
194
194
  let password = [];
195
195
  ['SYMBOLS', 'NUMBERS', 'UPPER', 'LOWER'].forEach((charSet) => {
@@ -228,7 +228,6 @@ class User extends kit_1.AsyncCreatable {
228
228
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
229
229
  password.value(async (buffer) => {
230
230
  try {
231
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
232
231
  // @ts-ignore TODO: expose `soap` on Connection however appropriate
233
232
  const soap = userConnection.soap;
234
233
  await soap.setPassword((0, ts_types_1.ensureString)(info.getFields().userId), buffer.toString('utf8'));
@@ -294,6 +293,7 @@ class User extends kit_1.AsyncCreatable {
294
293
  * ```
295
294
  */
296
295
  async createUser(fields) {
296
+ var _a;
297
297
  // Create a user and get a refresh token
298
298
  const refreshTokenSecret = await this.createUserInternal(fields);
299
299
  // Create the initial auth info
@@ -301,7 +301,8 @@ class User extends kit_1.AsyncCreatable {
301
301
  const adminUserAuthFields = authInfo.getFields(true);
302
302
  // Setup oauth options for the new user
303
303
  const oauthOptions = {
304
- loginUrl: adminUserAuthFields.loginUrl,
304
+ // Communities users require the instance for auth
305
+ loginUrl: (_a = adminUserAuthFields.instanceUrl) !== null && _a !== void 0 ? _a : adminUserAuthFields.loginUrl,
305
306
  refreshToken: refreshTokenSecret.buffer.value((buffer) => buffer.toString('utf8')),
306
307
  clientId: adminUserAuthFields.clientId,
307
308
  clientSecret: adminUserAuthFields.clientSecret,
@@ -406,7 +407,7 @@ class User extends kit_1.AsyncCreatable {
406
407
  }
407
408
  }
408
409
  this.logger.debug(message);
409
- throw new sfdxError_1.SfdxError(message, 'UserCreateHttpError');
410
+ throw new sfError_1.SfError(message, 'UserCreateHttpError');
410
411
  }
411
412
  fields.id = (0, ts_types_1.ensureString)(responseBody.id);
412
413
  await this.updateRequiredUserFields(fields);
@@ -8,7 +8,7 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.SchemaPrinter = exports.SchemaPropertyRenderer = void 0;
10
10
  const ts_types_1 = require("@salesforce/ts-types");
11
- const sfdxError_1 = require("../sfdxError");
11
+ const sfError_1 = require("../sfError");
12
12
  /**
13
13
  * Renders schema properties. By default, this is simply an identity transform. Subclasses may provide more
14
14
  * interesting decorations of each values, such as ANSI coloring.
@@ -78,7 +78,7 @@ class SchemaPrinter {
78
78
  // No need to add to messages, since this should never happen. In fact,
79
79
  // this will cause a test failure if there is a command that uses a schema
80
80
  // with no properties defined.
81
- throw new sfdxError_1.SfdxError('There is no purpose to print a schema with no properties or items');
81
+ throw new sfError_1.SfError('There is no purpose to print a schema with no properties or items');
82
82
  }
83
83
  const startLevel = 0;
84
84
  const add = this.addFn(startLevel);
@@ -27,8 +27,8 @@ export declare class SchemaValidator {
27
27
  * Performs validation of JSON data against the schema located at the `schemaPath` value provided
28
28
  * at instantiation.
29
29
  *
30
- * **Throws** *{@link SfdxError}{ name: 'ValidationSchemaFieldError' }* If there are known validations errors.
31
- * **Throws** *{@link SfdxError}{ name: 'ValidationSchemaUnknownError' }* If there are unknown validations errors.
30
+ * **Throws** *{@link SfError}{ name: 'ValidationSchemaFieldError' }* If there are known validations errors.
31
+ * **Throws** *{@link SfError}{ name: 'ValidationSchemaUnknownError' }* If there are unknown validations errors.
32
32
  *
33
33
  * @param json A JSON value to validate against this instance's target schema.
34
34
  * @returns The validated JSON data.
@@ -38,8 +38,8 @@ export declare class SchemaValidator {
38
38
  * Performs validation of JSON data against the schema located at the `schemaPath` value provided
39
39
  * at instantiation.
40
40
  *
41
- * **Throws** *{@link SfdxError}{ name: 'ValidationSchemaFieldError' }* If there are known validations errors.
42
- * **Throws** *{@link SfdxError}{ name: 'ValidationSchemaUnknownError' }* If there are unknown validations errors.
41
+ * **Throws** *{@link SfError}{ name: 'ValidationSchemaFieldError' }* If there are known validations errors.
42
+ * **Throws** *{@link SfError}{ name: 'ValidationSchemaUnknownError' }* If there are unknown validations errors.
43
43
  *
44
44
  * @param json A JSON value to validate against this instance's target schema.
45
45
  * @returns The validated JSON data.
@@ -8,11 +8,11 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.SchemaValidator = void 0;
10
10
  const path = require("path");
11
+ const fs = require("fs");
11
12
  const kit_1 = require("@salesforce/kit");
12
13
  const ts_types_1 = require("@salesforce/ts-types");
13
14
  const validator = require("jsen");
14
- const sfdxError_1 = require("../sfdxError");
15
- const fs_1 = require("../util/fs");
15
+ const sfError_1 = require("../sfError");
16
16
  /**
17
17
  * Loads a JSON schema and performs validations against JSON objects.
18
18
  */
@@ -33,7 +33,7 @@ class SchemaValidator {
33
33
  */
34
34
  async load() {
35
35
  if (!this.schema) {
36
- this.schema = await fs_1.fs.readJsonMap(this.schemaPath);
36
+ this.schema = (0, kit_1.parseJsonMap)(await fs.promises.readFile(this.schemaPath, 'utf8'));
37
37
  this.logger.debug(`Schema loaded for ${this.schemaPath}`);
38
38
  }
39
39
  return this.schema;
@@ -43,7 +43,7 @@ class SchemaValidator {
43
43
  */
44
44
  loadSync() {
45
45
  if (!this.schema) {
46
- this.schema = fs_1.fs.readJsonMapSync(this.schemaPath);
46
+ this.schema = (0, kit_1.parseJsonMap)(fs.readFileSync(this.schemaPath, 'utf8'));
47
47
  this.logger.debug(`Schema loaded for ${this.schemaPath}`);
48
48
  }
49
49
  return this.schema;
@@ -52,8 +52,8 @@ class SchemaValidator {
52
52
  * Performs validation of JSON data against the schema located at the `schemaPath` value provided
53
53
  * at instantiation.
54
54
  *
55
- * **Throws** *{@link SfdxError}{ name: 'ValidationSchemaFieldError' }* If there are known validations errors.
56
- * **Throws** *{@link SfdxError}{ name: 'ValidationSchemaUnknownError' }* If there are unknown validations errors.
55
+ * **Throws** *{@link SfError}{ name: 'ValidationSchemaFieldError' }* If there are known validations errors.
56
+ * **Throws** *{@link SfError}{ name: 'ValidationSchemaUnknownError' }* If there are unknown validations errors.
57
57
  *
58
58
  * @param json A JSON value to validate against this instance's target schema.
59
59
  * @returns The validated JSON data.
@@ -66,8 +66,8 @@ class SchemaValidator {
66
66
  * Performs validation of JSON data against the schema located at the `schemaPath` value provided
67
67
  * at instantiation.
68
68
  *
69
- * **Throws** *{@link SfdxError}{ name: 'ValidationSchemaFieldError' }* If there are known validations errors.
70
- * **Throws** *{@link SfdxError}{ name: 'ValidationSchemaUnknownError' }* If there are unknown validations errors.
69
+ * **Throws** *{@link SfError}{ name: 'ValidationSchemaFieldError' }* If there are known validations errors.
70
+ * **Throws** *{@link SfError}{ name: 'ValidationSchemaUnknownError' }* If there are unknown validations errors.
71
71
  *
72
72
  * @param json A JSON value to validate against this instance's target schema.
73
73
  * @returns The validated JSON data.
@@ -85,10 +85,10 @@ class SchemaValidator {
85
85
  if (!validate(json)) {
86
86
  if (validate.errors) {
87
87
  const errors = this.getErrorsText(validate.errors, schema);
88
- throw new sfdxError_1.SfdxError(`Validation errors:\n${errors}`, 'ValidationSchemaFieldError');
88
+ throw new sfError_1.SfError(`Validation errors:\n${errors}`, 'ValidationSchemaFieldError');
89
89
  }
90
90
  else {
91
- throw new sfdxError_1.SfdxError('Unknown schema validation error', 'ValidationSchemaUnknownError');
91
+ throw new sfError_1.SfError('Unknown schema validation error', 'ValidationSchemaUnknownError');
92
92
  }
93
93
  }
94
94
  return validate.build(json);
@@ -112,7 +112,7 @@ class SchemaValidator {
112
112
  externalSchemas[externalSchema.id] = externalSchema;
113
113
  }
114
114
  else {
115
- throw new sfdxError_1.SfdxError(`Unexpected external schema id type: ${typeof externalSchema.id}`, 'ValidationSchemaTypeError');
115
+ throw new sfError_1.SfError(`Unexpected external schema id type: ${typeof externalSchema.id}`, 'ValidationSchemaTypeError');
116
116
  }
117
117
  });
118
118
  return externalSchemas;
@@ -125,11 +125,11 @@ class SchemaValidator {
125
125
  loadExternalSchema(uri) {
126
126
  const schemaPath = path.join(this.schemasDir, `${uri}.json`);
127
127
  try {
128
- return fs_1.fs.readJsonMapSync(schemaPath);
128
+ return (0, kit_1.parseJsonMap)(fs.readFileSync(schemaPath, 'utf8'));
129
129
  }
130
130
  catch (err) {
131
131
  if (err.code === 'ENOENT') {
132
- throw new sfdxError_1.SfdxError(`Schema not found: ${schemaPath}`, 'ValidationSchemaNotFound');
132
+ throw new sfError_1.SfError(`Schema not found: ${schemaPath}`, 'ValidationSchemaNotFound');
133
133
  }
134
134
  throw err;
135
135
  }
@@ -13,10 +13,10 @@ import { JsonMap } from '@salesforce/ts-types';
13
13
  * const messages = Messages.load('myPackageName', 'myBundleName');
14
14
  *
15
15
  * // To throw a non-bundle based error:
16
- * throw new SfdxError(message.getMessage('myError'), 'MyErrorName');
16
+ * throw new SfError(message.getMessage('myError'), 'MyErrorName');
17
17
  * ```
18
18
  */
19
- export declare class SfdxError extends NamedError {
19
+ export declare class SfError extends NamedError {
20
20
  /**
21
21
  * Action messages. Hints to the users regarding what can be done to fix related issues.
22
22
  */
@@ -35,21 +35,21 @@ export declare class SfdxError extends NamedError {
35
35
  */
36
36
  private _code?;
37
37
  /**
38
- * Create an SfdxError.
38
+ * Create an SfError.
39
39
  *
40
40
  * @param message The error message.
41
- * @param name The error name. Defaults to 'SfdxError'.
41
+ * @param name The error name. Defaults to 'SfError'.
42
42
  * @param actions The action message(s).
43
43
  * @param exitCodeOrCause The exit code which will be used by SfdxCommand or he underlying error that caused this error to be raised.
44
44
  * @param cause The underlying error that caused this error to be raised.
45
45
  */
46
46
  constructor(message: string, name?: string, actions?: string[], exitCodeOrCause?: number | Error, cause?: Error);
47
47
  /**
48
- * Convert an Error to an SfdxError.
48
+ * Convert an Error to an SfError.
49
49
  *
50
50
  * @param err The error to convert.
51
51
  */
52
- static wrap(err: Error | string): SfdxError;
52
+ static wrap(err: Error | string): SfError;
53
53
  get code(): string | undefined | any;
54
54
  set code(code: string);
55
55
  /**
@@ -57,20 +57,20 @@ export declare class SfdxError extends NamedError {
57
57
  *
58
58
  * @param context The command name.
59
59
  */
60
- setContext(context: string): SfdxError;
60
+ setContext(context: string): SfError;
61
61
  /**
62
62
  * An additional payload for the error. For convenience `this` object is returned.
63
63
  *
64
64
  * @param data The payload data.
65
65
  */
66
- setData(data: unknown): SfdxError;
66
+ setData(data: unknown): SfError;
67
67
  /**
68
- * Convert an {@link SfdxError} state to an object. Returns a plain object representing the state of this error.
68
+ * Convert an {@link SfError} state to an object. Returns a plain object representing the state of this error.
69
69
  */
70
70
  toObject(): JsonMap;
71
- /**
72
- * @deprecated Does nothing. Do not use. This is kept around to support older versions of SfdxCommand.
73
- * @param commandName
74
- */
75
- setCommandName(): void;
71
+ }
72
+ /**
73
+ * @deprecated use SfError instead
74
+ */
75
+ export declare class SfdxError extends SfError {
76
76
  }
@@ -6,7 +6,7 @@
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.SfdxError = void 0;
9
+ exports.SfdxError = exports.SfError = void 0;
10
10
  const kit_1 = require("@salesforce/kit");
11
11
  const ts_types_1 = require("@salesforce/ts-types");
12
12
  /**
@@ -22,22 +22,22 @@ const ts_types_1 = require("@salesforce/ts-types");
22
22
  * const messages = Messages.load('myPackageName', 'myBundleName');
23
23
  *
24
24
  * // To throw a non-bundle based error:
25
- * throw new SfdxError(message.getMessage('myError'), 'MyErrorName');
25
+ * throw new SfError(message.getMessage('myError'), 'MyErrorName');
26
26
  * ```
27
27
  */
28
- class SfdxError extends kit_1.NamedError {
28
+ class SfError extends kit_1.NamedError {
29
29
  /**
30
- * Create an SfdxError.
30
+ * Create an SfError.
31
31
  *
32
32
  * @param message The error message.
33
- * @param name The error name. Defaults to 'SfdxError'.
33
+ * @param name The error name. Defaults to 'SfError'.
34
34
  * @param actions The action message(s).
35
35
  * @param exitCodeOrCause The exit code which will be used by SfdxCommand or he underlying error that caused this error to be raised.
36
36
  * @param cause The underlying error that caused this error to be raised.
37
37
  */
38
38
  constructor(message, name, actions, exitCodeOrCause, cause) {
39
39
  cause = exitCodeOrCause instanceof Error ? exitCodeOrCause : cause;
40
- super(name || 'SfdxError', message || name, cause);
40
+ super(name || 'SfError', message || name, cause);
41
41
  this.actions = actions;
42
42
  if (typeof exitCodeOrCause === 'number') {
43
43
  this.exitCode = exitCodeOrCause;
@@ -47,23 +47,23 @@ class SfdxError extends kit_1.NamedError {
47
47
  }
48
48
  }
49
49
  /**
50
- * Convert an Error to an SfdxError.
50
+ * Convert an Error to an SfError.
51
51
  *
52
52
  * @param err The error to convert.
53
53
  */
54
54
  static wrap(err) {
55
55
  if ((0, ts_types_1.isString)(err)) {
56
- return new SfdxError(err);
56
+ return new SfError(err);
57
57
  }
58
- if (err instanceof SfdxError) {
58
+ if (err instanceof SfError) {
59
59
  return err;
60
60
  }
61
- const sfdxError = new SfdxError(err.message, err.name, undefined, err);
61
+ const sfError = new SfError(err.message, err.name, undefined, err);
62
62
  // If the original error has a code, use that instead of name.
63
63
  if ((0, ts_types_1.hasString)(err, 'code')) {
64
- sfdxError.code = err.code;
64
+ sfError.code = err.code;
65
65
  }
66
- return sfdxError;
66
+ return sfError;
67
67
  }
68
68
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
69
  get code() {
@@ -91,7 +91,7 @@ class SfdxError extends kit_1.NamedError {
91
91
  return this;
92
92
  }
93
93
  /**
94
- * Convert an {@link SfdxError} state to an object. Returns a plain object representing the state of this error.
94
+ * Convert an {@link SfError} state to an object. Returns a plain object representing the state of this error.
95
95
  */
96
96
  toObject() {
97
97
  const obj = {
@@ -109,13 +109,12 @@ class SfdxError extends kit_1.NamedError {
109
109
  }
110
110
  return obj;
111
111
  }
112
- /**
113
- * @deprecated Does nothing. Do not use. This is kept around to support older versions of SfdxCommand.
114
- * @param commandName
115
- */
116
- setCommandName() {
117
- /** Do nothing. */
118
- }
112
+ }
113
+ exports.SfError = SfError;
114
+ /**
115
+ * @deprecated use SfError instead
116
+ */
117
+ class SfdxError extends SfError {
119
118
  }
120
119
  exports.SfdxError = SfdxError;
121
- //# sourceMappingURL=sfdxError.js.map
120
+ //# sourceMappingURL=sfError.js.map