@salesforce/core 2.32.0 → 2.34.2

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.
@@ -0,0 +1,226 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getScratchOrgInfoPayload = exports.generateScratchOrgInfo = exports.getAncestorIds = void 0;
4
+ /*
5
+ * Copyright (c) 2021, 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
+ // Node
11
+ const fs_1 = require("fs");
12
+ // @salesforce
13
+ const kit_1 = require("@salesforce/kit");
14
+ const ts_types_1 = require("@salesforce/ts-types");
15
+ const sfdc_1 = require("./util/sfdc");
16
+ const sfdxProject_1 = require("./sfdxProject");
17
+ const webOAuthServer_1 = require("./webOAuthServer");
18
+ const messages_1 = require("./messages");
19
+ const sfdxError_1 = require("./sfdxError");
20
+ const scratchOrgFeatureDeprecation_1 = require("./scratchOrgFeatureDeprecation");
21
+ const defaultConnectedAppInfo = {
22
+ clientId: 'PlatformCLI',
23
+ legacyClientId: 'SalesforceDevelopmentExperience',
24
+ legacyClientSecret: '1384510088588713504',
25
+ };
26
+ messages_1.Messages.importMessagesDirectory(__dirname);
27
+ const messages = messages_1.Messages.loadMessages('@salesforce/core', 'scratchOrgInfoGenerator');
28
+ const SNAPSHOT_UNSUPPORTED_OPTIONS = [
29
+ 'features',
30
+ 'orgPreferences',
31
+ 'edition',
32
+ 'sourceOrg',
33
+ 'settingsPath',
34
+ 'releaseVersion',
35
+ 'language',
36
+ ];
37
+ // A validator function to ensure any options parameters entered by the user adhere
38
+ // to a allowlist of valid option settings. Because org:create allows options to be
39
+ // input either key=value pairs or within the definition file, this validator is
40
+ // executed within the ctor and also after parsing/normalization of the definition file.
41
+ const optionsValidator = (key, scratchOrgInfoPayload) => {
42
+ if (key.toLowerCase() === 'durationdays') {
43
+ throw new sfdxError_1.SfdxError('unrecognizedScratchOrgOption', 'durationDays');
44
+ }
45
+ if (key.toLowerCase() === 'snapshot') {
46
+ const foundInvalidFields = SNAPSHOT_UNSUPPORTED_OPTIONS.filter((invalidField) => invalidField in scratchOrgInfoPayload);
47
+ if (foundInvalidFields.length > 0) {
48
+ throw new sfdxError_1.SfdxError(messages.getMessage('unsupportedSnapshotOrgCreateOptions', [foundInvalidFields.join(', ')]), 'orgSnapshot');
49
+ }
50
+ }
51
+ };
52
+ /**
53
+ * Generates the package2AncestorIds scratch org property
54
+ *
55
+ * @param scratchOrgInfo - the scratchOrgInfo passed in by the user
56
+ * @param projectJson - sfdxProjectJson
57
+ * @param hubOrg - the hub org, in case we need to do queries
58
+ */
59
+ const getAncestorIds = async (scratchOrgInfo, projectJson, hubOrg) => {
60
+ if (Reflect.has(scratchOrgInfo, 'package2AncestorIds')) {
61
+ throw new sfdxError_1.SfdxError(messages.getMessage('errorpackage2AncestorIdsKeyNotSupported'), 'DeprecationError');
62
+ }
63
+ const packagesWithAncestors = (await projectJson.getPackageDirectories())
64
+ // check that the package has any ancestor types (id or version)
65
+ .filter((packageDir) => packageDir.ancestorId || packageDir.ancestorVersion);
66
+ if (packagesWithAncestors.length === 0) {
67
+ return '';
68
+ }
69
+ const ancestorIds = await Promise.all(packagesWithAncestors.map(async (packageDir) => {
70
+ var _a, _b, _c;
71
+ // ancestorID can be 05i, or 04t, alias; OR "ancestorVersion": "4.6.0.1"
72
+ // according to docs, 05i is not ok: https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev2gp_config_file.htm
73
+ if (packageDir.ancestorVersion) {
74
+ if (!/^[0-9]+.[0-9]+.[0-9]+(.[0-9]+)?$/.test(packageDir.ancestorVersion)) {
75
+ throw sfdxError_1.SfdxError.create('@salesforce/core', 'scratchOrgInfoGenerator', 'errorInvalidAncestorVersionFormat', [
76
+ packageDir.ancestorVersion,
77
+ ]);
78
+ }
79
+ // package can be an ID, but not according to docs
80
+ const packageAliases = projectJson.get('packageAliases');
81
+ const packageId = (_a = packageAliases[ts_types_1.ensureString(packageDir.package)]) !== null && _a !== void 0 ? _a : packageDir.package;
82
+ const [major, minor, patch] = packageDir.ancestorVersion.split('.');
83
+ let releasedAncestor;
84
+ try {
85
+ releasedAncestor = await hubOrg
86
+ .getConnection()
87
+ .singleRecordQuery(`SELECT Id, IsReleased FROM Package2Version WHERE Package2Id = '${packageId}' AND MajorVersion = ${major} AND MinorVersion = ${minor} AND PatchVersion = ${patch} and IsReleased = true`, { tooling: true });
88
+ }
89
+ catch (err) {
90
+ throw new sfdxError_1.SfdxError(messages.getMessage('errorNoMatchingAncestor', [packageDir.ancestorVersion, packageDir.package]), 'ErrorNoMatchingAncestor', [messages.getMessage('errorAncestorNotReleased', [packageDir.ancestorVersion])]);
91
+ }
92
+ if (packageDir.ancestorId && packageDir.ancestorId !== releasedAncestor.Id) {
93
+ throw sfdxError_1.SfdxError.create('@salesforce/core', 'scratchOrgInfogenerator', 'ErrorAncestorIdVersionMismatch', [
94
+ packageDir.ancestorVersion,
95
+ packageDir.ancestorId,
96
+ ]);
97
+ }
98
+ return releasedAncestor.Id;
99
+ }
100
+ if ((_b = packageDir === null || packageDir === void 0 ? void 0 : packageDir.ancestorId) === null || _b === void 0 ? void 0 : _b.startsWith('05i')) {
101
+ // if it's already a 05i return it, otherwise query for it
102
+ return packageDir.ancestorId;
103
+ }
104
+ if ((_c = packageDir === null || packageDir === void 0 ? void 0 : packageDir.ancestorId) === null || _c === void 0 ? void 0 : _c.startsWith('04t')) {
105
+ // query for the Id
106
+ return (await hubOrg
107
+ .getConnection()
108
+ .singleRecordQuery(`SELECT Id FROM Package2Version WHERE SubscriberPackageVersionId = '${packageDir.ancestorId}'`, { tooling: true })).Id;
109
+ }
110
+ // ancestorID can be an alias get it from projectJson
111
+ const packageAliases = projectJson.get('packageAliases');
112
+ if (packageDir.ancestorId && (packageAliases === null || packageAliases === void 0 ? void 0 : packageAliases[packageDir.ancestorId])) {
113
+ return packageAliases[packageDir.ancestorId];
114
+ }
115
+ throw new sfdxError_1.SfdxError(`Invalid ancestorId ${packageDir.ancestorId}`, 'InvalidAncestorId');
116
+ }));
117
+ return Array.from(new Set(ancestorIds)).join(';');
118
+ };
119
+ exports.getAncestorIds = getAncestorIds;
120
+ /**
121
+ * Takes in a scratchOrgInfo and fills in the missing fields
122
+ *
123
+ * @param hubOrg the environment hub org
124
+ * @param scratchOrgInfoPayload - the scratchOrgInfo passed in by the user
125
+ * @param nonamespace create the scratch org with no namespace
126
+ * @param ignoreAncestorIds true if the sfdx-project.json ancestorId keys should be ignored
127
+ */
128
+ const generateScratchOrgInfo = async ({ hubOrg, scratchOrgInfoPayload, nonamespace, ignoreAncestorIds, }) => {
129
+ var _a, _b;
130
+ let sfdxProject;
131
+ try {
132
+ sfdxProject = await sfdxProject_1.SfdxProjectJson.create({});
133
+ }
134
+ catch (e) {
135
+ // project is not required
136
+ }
137
+ scratchOrgInfoPayload.orgName = (_a = scratchOrgInfoPayload.orgName) !== null && _a !== void 0 ? _a : 'Company';
138
+ scratchOrgInfoPayload.package2AncestorIds =
139
+ !ignoreAncestorIds && (sfdxProject === null || sfdxProject === void 0 ? void 0 : sfdxProject.hasPackages())
140
+ ? await exports.getAncestorIds(scratchOrgInfoPayload, sfdxProject, hubOrg)
141
+ : '';
142
+ // Use the Hub org's client ID value, if one wasn't provided to us, or the default
143
+ if (!scratchOrgInfoPayload.connectedAppConsumerKey) {
144
+ scratchOrgInfoPayload.connectedAppConsumerKey =
145
+ (_b = hubOrg.getConnection().getAuthInfoFields().clientId) !== null && _b !== void 0 ? _b : defaultConnectedAppInfo.clientId;
146
+ }
147
+ if (!nonamespace && (sfdxProject === null || sfdxProject === void 0 ? void 0 : sfdxProject.get('namespace'))) {
148
+ scratchOrgInfoPayload.namespace = sfdxProject.get('namespace');
149
+ }
150
+ // we already have the info, and want to get rid of configApi, so this doesn't use that
151
+ scratchOrgInfoPayload.connectedAppCallbackUrl = `http://localhost:${await webOAuthServer_1.WebOAuthServer.determineOauthPort()}/OauthRedirect`;
152
+ return scratchOrgInfoPayload;
153
+ };
154
+ exports.generateScratchOrgInfo = generateScratchOrgInfo;
155
+ /**
156
+ * Returns a valid signup json
157
+ *
158
+ * @param definitionjson org definition in JSON format
159
+ * @param definitionfile path to an org definition file
160
+ * @param connectedAppConsumerKey The connected app consumer key. May be null for JWT OAuth flow.
161
+ * @param durationdays duration of the scratch org (in days) (default:1, min:1, max:30)
162
+ * @param nonamespace create the scratch org with no namespace
163
+ * @param noancestors do not include second-generation package ancestors in the scratch org
164
+ * @param orgConfig overrides definitionjson
165
+ * @returns scratchOrgInfoPayload: ScratchOrgInfoPayload;
166
+ ignoreAncestorIds: boolean;
167
+ warnings: string[];
168
+ */
169
+ const getScratchOrgInfoPayload = async (options) => {
170
+ var _a;
171
+ let warnings = [];
172
+ // orgConfig input overrides definitionjson (-j option; hidden/deprecated)
173
+ const definitionJson = options.definitionjson ? JSON.parse(options.definitionjson) : {};
174
+ const orgConfigInput = { ...definitionJson, ...((_a = options.orgConfig) !== null && _a !== void 0 ? _a : {}) };
175
+ let scratchOrgInfoPayload = orgConfigInput;
176
+ // the -f option
177
+ if (options.definitionfile) {
178
+ try {
179
+ const fileData = await fs_1.promises.readFile(options.definitionfile, 'utf8');
180
+ const defFileContents = kit_1.parseJson(fileData);
181
+ // definitionjson and orgConfig override file input
182
+ scratchOrgInfoPayload = { ...defFileContents, ...orgConfigInput };
183
+ }
184
+ catch (err) {
185
+ const error = err;
186
+ if (error.name === 'JsonParseError') {
187
+ throw new sfdxError_1.SfdxError(`An error occurred parsing ${options.definitionfile}`);
188
+ }
189
+ throw sfdxError_1.SfdxError.wrap(error);
190
+ }
191
+ }
192
+ // scratchOrgInfoPayload must be heads down camelcase.
193
+ const upperCaseKey = sfdc_1.sfdc.findUpperCaseKeys(scratchOrgInfoPayload);
194
+ if (upperCaseKey) {
195
+ throw new sfdxError_1.SfdxError('InvalidJsonCasing', upperCaseKey);
196
+ }
197
+ // Now run the fully resolved user input against the validator
198
+ Object.keys(scratchOrgInfoPayload).forEach((key) => {
199
+ optionsValidator(key, scratchOrgInfoPayload);
200
+ });
201
+ if (options.connectedAppConsumerKey) {
202
+ scratchOrgInfoPayload.connectedAppConsumerKey = options.connectedAppConsumerKey;
203
+ }
204
+ scratchOrgInfoPayload.durationDays = options.durationDays;
205
+ // Throw warnings for deprecated scratch org features.
206
+ const scratchOrgFeatureDeprecation = new scratchOrgFeatureDeprecation_1.ScratchOrgFeatureDeprecation();
207
+ // convert various supported array and string formats to a semi-colon-delimited string
208
+ if (scratchOrgInfoPayload.features) {
209
+ if (typeof scratchOrgInfoPayload.features === 'string') {
210
+ scratchOrgInfoPayload.features = scratchOrgInfoPayload.features.split(/[;,]/);
211
+ }
212
+ warnings = scratchOrgFeatureDeprecation.getFeatureWarnings(scratchOrgInfoPayload.features);
213
+ scratchOrgInfoPayload.features = scratchOrgInfoPayload.features.map((feature) => feature.trim());
214
+ scratchOrgInfoPayload.features = scratchOrgFeatureDeprecation
215
+ .filterDeprecatedFeatures(scratchOrgInfoPayload.features)
216
+ .join(';');
217
+ }
218
+ return {
219
+ scratchOrgInfoPayload,
220
+ // Ignore ancestor ids only when 'nonamespace' or 'noancestors' options are specified
221
+ ignoreAncestorIds: options.nonamespace || options.noancestors || false,
222
+ warnings,
223
+ };
224
+ };
225
+ exports.getScratchOrgInfoPayload = getScratchOrgInfoPayload;
226
+ //# sourceMappingURL=scratchOrgInfoGenerator.js.map
@@ -0,0 +1,56 @@
1
+ import { JsonMap } from '@salesforce/ts-types';
2
+ import { Org } from './org';
3
+ import { ScratchOrgInfo } from './scratchOrgInfoApi';
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,208 @@
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
+ // Node
11
+ const path = require("path");
12
+ // @salesforce
13
+ const kit_1 = require("@salesforce/kit");
14
+ const ts_types_1 = require("@salesforce/ts-types");
15
+ const js2xmlparser = require("js2xmlparser");
16
+ const logger_1 = require("./logger");
17
+ const sfdxError_1 = require("./sfdxError");
18
+ const jsonXmlTools_1 = require("./util/jsonXmlTools");
19
+ const zipWriter_1 = require("./util/zipWriter");
20
+ const pollingClient_1 = require("./status/pollingClient");
21
+ var RequestStatus;
22
+ (function (RequestStatus) {
23
+ RequestStatus["Pending"] = "Pending";
24
+ RequestStatus["InProgress"] = "InProgress";
25
+ RequestStatus["Succeeded"] = "Succeeded";
26
+ RequestStatus["SucceededPartial"] = "SucceededPartial";
27
+ RequestStatus["Failed"] = "Failed";
28
+ RequestStatus["Canceling"] = "Canceling";
29
+ RequestStatus["Canceled"] = "Canceled";
30
+ })(RequestStatus = exports.RequestStatus || (exports.RequestStatus = {}));
31
+ const breakPolling = ['Succeeded', 'SucceededPartial', 'Failed', 'Canceled'];
32
+ /**
33
+ * Helper class for dealing with the settings that are defined in a scratch definition file. This class knows how to extract the
34
+ * settings from the definition, how to expand them into a MD directory and how to generate a package.xml.
35
+ */
36
+ class SettingsGenerator {
37
+ constructor() {
38
+ this.shapeDirName = `shape_${Date.now()}`;
39
+ this.logger = logger_1.Logger.childFromRoot('SettingsGenerator');
40
+ // If SFDX_MDAPI_TEMP_DIR is set, copy settings to that dir for people to inspect.
41
+ const mdapiTmpDir = kit_1.env.getString('SFDX_MDAPI_TEMP_DIR');
42
+ this.writer = new zipWriter_1.ZipWriter(mdapiTmpDir);
43
+ }
44
+ /** extract the settings from the scratch def file, if they are present. */
45
+ async extract(scratchDef) {
46
+ this.logger.debug('extracting settings from scratch definition file');
47
+ this.settingData = scratchDef.settings;
48
+ this.objectSettingsData = scratchDef.objectSettings;
49
+ this.logger.debug('settings are', this.settingData);
50
+ }
51
+ /** True if we are currently tracking setting or object setting data. */
52
+ hasSettings() {
53
+ return !kit_1.isEmpty(this.settingData) || !kit_1.isEmpty(this.objectSettingsData);
54
+ }
55
+ /** Create temporary deploy directory used to upload the scratch org shape.
56
+ * This will create the dir, all of the .setting files and minimal object files needed for objectSettings
57
+ */
58
+ async createDeploy() {
59
+ const settingsDir = path.join(this.shapeDirName, 'settings');
60
+ const objectsDir = path.join(this.shapeDirName, 'objects');
61
+ await Promise.all([this.writeSettingsIfNeeded(settingsDir), this.writeObjectSettingsIfNeeded(objectsDir)]);
62
+ }
63
+ /**
64
+ * Deploys the settings to the org.
65
+ */
66
+ async deploySettingsViaFolder(scratchOrg, apiVersion) {
67
+ const username = scratchOrg.getUsername();
68
+ const logger = await logger_1.Logger.child('deploySettingsViaFolder');
69
+ this.createPackageXml(apiVersion);
70
+ await this.writer.finalize();
71
+ const connection = scratchOrg.getConnection();
72
+ logger.debug(`deploying to apiVersion: ${apiVersion}`);
73
+ connection.setApiVersion(apiVersion);
74
+ const { id } = await connection.deploy(this.writer.buffer, {});
75
+ logger.debug(`deploying settings id ${id}`);
76
+ let result = await connection.metadata.checkDeployStatus(id);
77
+ const pollingOptions = {
78
+ async poll() {
79
+ try {
80
+ result = await connection.metadata.checkDeployStatus(id);
81
+ logger.debug(`Deploy id: ${id} status: ${result.status}`);
82
+ if (breakPolling.includes(result.status)) {
83
+ return {
84
+ completed: true,
85
+ payload: result.status,
86
+ };
87
+ }
88
+ return {
89
+ completed: false,
90
+ };
91
+ }
92
+ catch (error) {
93
+ logger.debug(`An error occurred trying to check deploy id: ${id}`);
94
+ logger.debug(`Error: ${error.message}`);
95
+ logger.debug('Re-trying deploy check again....');
96
+ return {
97
+ completed: false,
98
+ };
99
+ }
100
+ },
101
+ timeout: kit_1.Duration.minutes(10),
102
+ frequency: kit_1.Duration.seconds(1),
103
+ timeoutErrorName: 'DeployingSettingsTimeoutError',
104
+ };
105
+ const client = await pollingClient_1.PollingClient.create(pollingOptions);
106
+ const status = (await client.subscribe());
107
+ if (status !== RequestStatus.Succeeded) {
108
+ const error = new sfdxError_1.SfdxError(`A scratch org was created with username ${username}, but the settings failed to deploy`, 'ProblemDeployingSettings');
109
+ error.setData(result);
110
+ throw error;
111
+ }
112
+ }
113
+ async writeObjectSettingsIfNeeded(objectsDir) {
114
+ if (!this.objectSettingsData || !Object.keys(this.objectSettingsData).length) {
115
+ return;
116
+ }
117
+ for (const objectName of Object.keys(this.objectSettingsData)) {
118
+ const value = this.objectSettingsData[objectName];
119
+ // writes the object file in source format
120
+ const objectDir = path.join(objectsDir, kit_1.upperFirst(objectName));
121
+ const customObjectDir = path.join(objectDir, `${kit_1.upperFirst(objectName)}.object`);
122
+ const customObjectXml = jsonXmlTools_1.JsonAsXml({
123
+ json: this.createObjectFileContent(value),
124
+ type: 'RecordType',
125
+ });
126
+ this.writer.addToZip(customObjectXml, customObjectDir);
127
+ if (value.defaultRecordType) {
128
+ const recordTypesDir = path.join(objectDir, 'recordTypes', `${kit_1.upperFirst(value.defaultRecordType)}.recordType`);
129
+ const recordTypesFileContent = this.createRecordTypeFileContent(objectName, value);
130
+ const recordTypesXml = jsonXmlTools_1.JsonAsXml({
131
+ json: recordTypesFileContent,
132
+ type: 'RecordType',
133
+ });
134
+ this.writer.addToZip(recordTypesXml, recordTypesDir);
135
+ // for things that required a businessProcess
136
+ if (recordTypesFileContent.businessProcess) {
137
+ const businessProcessesDir = path.join(objectDir, 'businessProcesses', `${recordTypesFileContent.businessProcess}.businessProcess`);
138
+ const businessProcessesXml = jsonXmlTools_1.JsonAsXml({
139
+ json: this.createBusinessProcessFileContent(objectName, recordTypesFileContent.businessProcess),
140
+ type: 'BusinessProcess',
141
+ });
142
+ this.writer.addToZip(businessProcessesXml, businessProcessesDir);
143
+ }
144
+ }
145
+ }
146
+ }
147
+ async writeSettingsIfNeeded(settingsDir) {
148
+ if (this.settingData) {
149
+ for (const item of Object.keys(this.settingData)) {
150
+ const value = ts_types_1.getObject(this.settingData, item);
151
+ const typeName = kit_1.upperFirst(item);
152
+ const fname = typeName.replace('Settings', '');
153
+ const fileContent = js2xmlparser.parse(typeName, value);
154
+ this.writer.addToZip(fileContent, path.join(settingsDir, fname + '.settings'));
155
+ }
156
+ }
157
+ }
158
+ createPackageXml(apiVersion) {
159
+ const pkg = `<?xml version="1.0" encoding="UTF-8"?>
160
+ <Package xmlns="http://soap.sforce.com/2006/04/metadata">
161
+ <types>
162
+ <members>*</members>
163
+ <name>Settings</name>
164
+ </types>
165
+ <types>
166
+ <members>*</members>
167
+ <name>CustomObject</name>
168
+ </types>
169
+ <version>${apiVersion}</version>
170
+ </Package>`;
171
+ this.writer.addToZip(pkg, path.join(this.shapeDirName, 'package.xml'));
172
+ }
173
+ createObjectFileContent(json) {
174
+ const output = {};
175
+ if (json.sharingModel) {
176
+ output.sharingModel = kit_1.upperFirst(json.sharingModel);
177
+ }
178
+ return output;
179
+ }
180
+ createRecordTypeFileContent(objectName, setting) {
181
+ const defaultRecordType = kit_1.upperFirst(setting.defaultRecordType);
182
+ const output = {
183
+ fullName: defaultRecordType,
184
+ label: defaultRecordType,
185
+ active: true,
186
+ };
187
+ // all the edge cases
188
+ if (['Case', 'Lead', 'Opportunity', 'Solution'].includes(kit_1.upperFirst(objectName))) {
189
+ return { ...output, businessProcess: `${defaultRecordType}Process` };
190
+ }
191
+ return output;
192
+ }
193
+ createBusinessProcessFileContent(objectName, businessProcessName) {
194
+ const objectToBusinessProcessPicklist = {
195
+ Opportunity: { fullName: 'Prospecting' },
196
+ Case: { fullName: 'New', default: true },
197
+ Lead: { fullName: 'New - Not Contacted', default: true },
198
+ Solution: { fullName: 'Draft', default: true },
199
+ };
200
+ return {
201
+ fullName: businessProcessName,
202
+ isActive: true,
203
+ values: [objectToBusinessProcessPicklist[kit_1.upperFirst(objectName)]],
204
+ };
205
+ }
206
+ }
207
+ exports.default = SettingsGenerator;
208
+ //# sourceMappingURL=scratchOrgSettingsGenerator.js.map
@@ -261,7 +261,6 @@ export declare namespace StreamingClient {
261
261
  handshakeTimeout: Duration;
262
262
  channel: string;
263
263
  streamingImpl: StreamingClientIfc;
264
- private envDep;
265
264
  /**
266
265
  * Constructor for DefaultStreamingOptions
267
266
  *
@@ -335,6 +335,10 @@ exports.StreamingClient = StreamingClient;
335
335
  * @see {@link StatusResult}
336
336
  */
337
337
  constructor(org, channel, streamProcessor, envDep = lib_1.env) {
338
+ if (envDep) {
339
+ const logger = logger_1.Logger.childFromRoot('StreamingClient');
340
+ logger.warn('envDep is deprecated');
341
+ }
338
342
  if (!streamProcessor) {
339
343
  throw new sfdxError_1.SfdxError('Missing stream processor', 'MissingArg');
340
344
  }
@@ -344,7 +348,6 @@ exports.StreamingClient = StreamingClient;
344
348
  if (!channel) {
345
349
  throw new sfdxError_1.SfdxError('Missing streaming channel', 'MissingArg');
346
350
  }
347
- this.envDep = envDep;
348
351
  this.org = org;
349
352
  this.apiVersion = org.getConnection().getApiVersion();
350
353
  if (channel.startsWith('/system')) {
@@ -359,18 +362,7 @@ exports.StreamingClient = StreamingClient;
359
362
  this.handshakeTimeout = StreamingClient.DefaultOptions.DEFAULT_HANDSHAKE_TIMEOUT;
360
363
  this.streamingImpl = {
361
364
  getCometClient: (url) => {
362
- const x = this.envDep.getString(StreamingClient.DefaultOptions.SFDX_ENABLE_FAYE_COOKIES_ALLOW_ALL_PATHS);
363
- return new Faye.Client(url, {
364
- // This parameter ensures all cookies regardless of path are included in subsequent requests. Otherwise
365
- // only cookies with the path "/" and "/cometd" are known to be included.
366
- // if SFDX_ENABLE_FAYE_COOKIES_ALLOW_ALL_PATHS is *not* set the default to true.
367
- cookiesAllowAllPaths: x === undefined
368
- ? true
369
- : this.envDep.getBoolean(StreamingClient.DefaultOptions.SFDX_ENABLE_FAYE_COOKIES_ALLOW_ALL_PATHS),
370
- // WARNING - The allows request/response exchanges to be written to the log instance which includes
371
- // header and cookie information.
372
- enableRequestResponseLogging: this.envDep.getBoolean(StreamingClient.DefaultOptions.SFDX_ENABLE_FAYE_REQUEST_RESPONSE_LOGGING),
373
- });
365
+ return new Faye.Client(url);
374
366
  },
375
367
  setLogger: (logLine) => {
376
368
  Faye.logger = {};
@@ -0,0 +1,14 @@
1
+ import { JsonMap } from '@salesforce/ts-types';
2
+ import { IOptions } from 'js2xmlparser/lib/options';
3
+ export interface JSONasXML {
4
+ json: JsonMap;
5
+ type: string;
6
+ options?: IOptions;
7
+ }
8
+ export interface WriteJSONasXMLInputs extends JSONasXML {
9
+ path: string;
10
+ }
11
+ export declare const standardOptions: IOptions;
12
+ export declare const writeJSONasXML: ({ path, json, type, options, }: WriteJSONasXMLInputs) => Promise<void>;
13
+ export declare const JsonAsXml: ({ json, type, options }: JSONasXML) => string;
14
+ export declare const fixExistingDollarSign: (existing: WriteJSONasXMLInputs['json']) => Record<string, unknown>;
@@ -0,0 +1,41 @@
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.fixExistingDollarSign = exports.JsonAsXml = exports.writeJSONasXML = exports.standardOptions = void 0;
10
+ const fs_1 = require("fs");
11
+ const jsToXml = require("js2xmlparser");
12
+ exports.standardOptions = {
13
+ declaration: {
14
+ include: true,
15
+ encoding: 'UTF-8',
16
+ version: '1.0',
17
+ },
18
+ format: {
19
+ doubleQuotes: true,
20
+ },
21
+ };
22
+ const writeJSONasXML = async ({ path, json, type, options = exports.standardOptions, }) => {
23
+ const xml = jsToXml.parse(type, exports.fixExistingDollarSign(json), options);
24
+ return await fs_1.promises.writeFile(path, xml);
25
+ };
26
+ exports.writeJSONasXML = writeJSONasXML;
27
+ const JsonAsXml = ({ json, type, options = exports.standardOptions }) => {
28
+ return jsToXml.parse(type, exports.fixExistingDollarSign(json), options);
29
+ };
30
+ exports.JsonAsXml = JsonAsXml;
31
+ const fixExistingDollarSign = (existing) => {
32
+ const existingCopy = { ...existing };
33
+ if (existingCopy.$) {
34
+ const temp = existingCopy.$;
35
+ delete existingCopy.$;
36
+ existingCopy['@'] = temp;
37
+ }
38
+ return existingCopy;
39
+ };
40
+ exports.fixExistingDollarSign = fixExistingDollarSign;
41
+ //# sourceMappingURL=jsonXmlTools.js.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Use mapKeys to convert object keys to another format using the specified conversion function.
3
+ *
4
+ * E.g., to deep convert all object keys to camelCase: mapKeys(myObj, _.camelCase, true)
5
+ * to shallow convert object keys to lower case: mapKeys(myObj, _.toLower)
6
+ *
7
+ * NOTE: This mutates the object passed in for conversion.
8
+ *
9
+ * @param target - {Object} The object to convert the keys
10
+ * @param converter - {Function} The function that converts the object key
11
+ * @param deep - {boolean} Whether to do a deep object key conversion
12
+ * @return {Object} - the object with the converted keys
13
+ */
14
+ export default function mapKeys(obj: any, converter: (key: string) => string, deep?: boolean): Record<string, unknown>;
@@ -0,0 +1,48 @@
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
+ const ts_types_1 = require("@salesforce/ts-types");
10
+ /**
11
+ * Use mapKeys to convert object keys to another format using the specified conversion function.
12
+ *
13
+ * E.g., to deep convert all object keys to camelCase: mapKeys(myObj, _.camelCase, true)
14
+ * to shallow convert object keys to lower case: mapKeys(myObj, _.toLower)
15
+ *
16
+ * NOTE: This mutates the object passed in for conversion.
17
+ *
18
+ * @param target - {Object} The object to convert the keys
19
+ * @param converter - {Function} The function that converts the object key
20
+ * @param deep - {boolean} Whether to do a deep object key conversion
21
+ * @return {Object} - the object with the converted keys
22
+ */
23
+ function mapKeys(
24
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
25
+ obj, converter, deep) {
26
+ const target = Object.assign({}, obj);
27
+ return Object.fromEntries(Object.entries(target).map(([key, value]) => {
28
+ const k = converter.call(null, key);
29
+ if (deep) {
30
+ let v = value;
31
+ if (Array.isArray(value)) {
32
+ v = value.map((v1) => {
33
+ if (ts_types_1.isPlainObject(v1)) {
34
+ return mapKeys(v1, converter, deep);
35
+ }
36
+ return v1;
37
+ });
38
+ }
39
+ else if (ts_types_1.isPlainObject(value)) {
40
+ v = mapKeys(value, converter, deep);
41
+ }
42
+ return [k, v];
43
+ }
44
+ return [k, value];
45
+ }));
46
+ }
47
+ exports.default = mapKeys;
48
+ //# sourceMappingURL=mapKeys.js.map