-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathcomponentSet.ts
More file actions
784 lines (704 loc) · 29.9 KB
/
componentSet.ts
File metadata and controls
784 lines (704 loc) · 29.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
/* eslint @typescript-eslint/unified-signatures:0 */
import { XMLBuilder } from 'fast-xml-parser';
import {
AuthInfo,
ConfigAggregator,
Connection,
Logger,
Messages,
OrgConfigProperties,
SfError,
SfProject,
} from '@salesforce/core';
import { isString } from '@salesforce/ts-types';
import { objectHasSomeRealValues } from '../utils/decomposed';
import { MetadataApiDeploy, MetadataApiDeployOptions } from '../client/metadataApiDeploy';
import { MetadataApiRetrieve } from '../client/metadataApiRetrieve';
import type { MetadataApiRetrieveOptions } from '../client/types';
import { XML_DECL, XML_NS_KEY, XML_NS_URL } from '../common/constants';
import { SourceComponent } from '../resolve/sourceComponent';
import { MetadataResolver } from '../resolve/metadataResolver';
import { ConnectionResolver } from '../resolve/connectionResolver';
import { ManifestResolver } from '../resolve/manifestResolver';
import { ComponentLike, MetadataComponent, MetadataMember } from '../resolve/types';
import { RegistryAccess } from '../registry/registryAccess';
import { getCurrentApiVersion } from '../registry/coverage';
import { MetadataType } from '../registry/types';
import {
DestructiveChangesType,
FromConnectionOptions,
FromManifestOptions,
FromSourceOptions,
PackageManifestObject,
} from './types';
import { LazyCollection } from './lazyCollection';
import { DecodeableMap } from './decodeableMap';
Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/source-deploy-retrieve', 'sdr');
export type DeploySetOptions = Omit<MetadataApiDeployOptions, 'components'>;
export type RetrieveSetOptions = Omit<MetadataApiRetrieveOptions, 'components'>;
const KEY_DELIMITER = '#';
/**
* A collection containing no duplicate metadata members (`fullName` and `type` pairs). `ComponentSets`
* are a convenient way of constructing a unique collection of components to perform operations such as
* deploying and retrieving.
*
* Multiple {@link SourceComponent}s can be present in the set and correspond to the same member.
* This is typically the case when a component's source files are split across locations. For an example, see
* the [multiple package directories](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_ws_mpd.htm)
* scenario.
*/
export class ComponentSet extends LazyCollection<MetadataComponent> {
public static readonly WILDCARD = '*';
/**
* The metadata API version to use. E.g., 52.0
*/
public apiVersion?: string;
/**
* The metadata API version of the deployed/retrieved source.
* This is used as the value for the `version` field in the manifest.
*/
public sourceApiVersion?: string;
/**
* Used to explicitly set the project directory for the component set.
* When not present, sfdx-core's SfProject will use the current working directory.
*/
public projectDirectory?: string;
public fullName?: string;
public forceIgnoredPaths?: Set<string>;
private logger: Logger;
private readonly registry: RegistryAccess;
// all components stored here, regardless of what manifest they belong to
private components = new DecodeableMap<string, DecodeableMap<string, SourceComponent>>();
// internal component maps used by this.getObject() when building manifests.
private destructiveComponents = {
[DestructiveChangesType.PRE]: new DecodeableMap<string, DecodeableMap<string, SourceComponent>>(),
[DestructiveChangesType.POST]: new DecodeableMap<string, DecodeableMap<string, SourceComponent>>(),
};
// used to store components meant for a "constructive" (not destructive) manifest
private manifestComponents = new DecodeableMap<string, DecodeableMap<string, SourceComponent>>();
private destructiveChangesType = DestructiveChangesType.POST;
public constructor(components: Iterable<ComponentLike> = [], registry = new RegistryAccess()) {
super();
this.registry = registry;
this.logger = Logger.childFromRoot(this.constructor.name);
for (const component of components) {
const destructiveType =
component instanceof SourceComponent ? component.getDestructiveChangesType() : this.destructiveChangesType;
this.add(component, destructiveType);
}
}
/**
* Each {@link SourceComponent} counts as an element in the set, even if multiple
* ones map to the same `fullName` and `type` pair.
*
* @returns number of metadata components in the set
*/
public get size(): number {
let size = 0;
for (const collection of this.components.values()) {
// just having an entry in the parent map counts as 1
size += collection.size === 0 ? 1 : collection.size;
}
return size;
}
public get destructiveChangesPre(): DecodeableMap<string, DecodeableMap<string, SourceComponent>> {
return this.destructiveComponents[DestructiveChangesType.PRE];
}
public get destructiveChangesPost(): DecodeableMap<string, DecodeableMap<string, SourceComponent>> {
return this.destructiveComponents[DestructiveChangesType.POST];
}
/**
* Resolve metadata components from a file or directory path in a file system.
*
* @param fsPath File or directory path to resolve against
* @returns ComponentSet of source resolved components
*/
public static fromSource(fsPath: string): ComponentSet;
/**
* Resolve metadata components from multiple file paths or directory paths in a file system.
*
* @param fsPaths File or directory paths to resolve against
* @returns ComponentSet of source resolved components
*/
public static fromSource(fsPaths: string[]): ComponentSet;
/**
* Resolve metadata components from file or directory paths in a file system.
* Customize the resolution process using an options object, such as specifying filters
* and resolving against a different file system abstraction (see {@link TreeContainer}).
*
* @param options
* @returns ComponentSet of source resolved components
*/
public static fromSource(options: FromSourceOptions): ComponentSet;
public static fromSource(input: string | string[] | FromSourceOptions): ComponentSet {
const parseFromSourceInputs = (given: string | string[] | FromSourceOptions): FromSourceOptions => {
if (Array.isArray(given)) {
return { fsPaths: given };
} else if (typeof given === 'object') {
return given;
} else {
return { fsPaths: [given] };
}
};
const { fsPaths, registry, tree, include, fsDeletePaths = [] } = parseFromSourceInputs(input);
const resolver = new MetadataResolver(registry, tree);
const set = new ComponentSet([], registry);
const buildComponents = (paths: string[], destructiveType?: DestructiveChangesType): void => {
for (const path of paths) {
for (const component of resolver.getComponentsFromPath(path, include)) {
set.add(component, destructiveType);
}
}
};
buildComponents(fsPaths);
buildComponents(fsDeletePaths, DestructiveChangesType.POST);
set.forceIgnoredPaths = resolver.forceIgnoredPaths;
return set;
}
/**
* Resolve components from a manifest file in XML format.
*
* see [Sample package.xml Manifest Files](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/manifest_samples.htm)
*
* @param manifestPath Path to XML file
* @returns Promise of a ComponentSet containing manifest components
*/
public static async fromManifest(manifestPath: string): Promise<ComponentSet>;
/**
* Resolve components from a manifest file in XML format.
* Customize the resolution process using an options object. For example, resolve source-backed components
* while using the manifest file as a filter.
* process using an options object, such as resolving source-backed components
* and using the manifest file as a filter.
*
* see [Sample package.xml Manifest Files](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/manifest_samples.htm)
*
* @param options
* @returns Promise of a ComponentSet containing manifest components
*/
public static async fromManifest(options: FromManifestOptions): Promise<ComponentSet>;
public static async fromManifest(input: string | FromManifestOptions): Promise<ComponentSet> {
const manifestPath = typeof input === 'string' ? input : input.manifestPath;
const options = (typeof input === 'object' ? input : {}) as Partial<FromManifestOptions>;
const manifestResolver = new ManifestResolver(options.tree, options.registry);
const manifest = await manifestResolver.resolve(manifestPath);
const resolveIncludeSet = options.resolveSourcePaths ? new ComponentSet([], options.registry) : undefined;
const resolvePostSet = options.resolveSourcePaths ? new ComponentSet([], options.registry) : undefined;
const resolvePreSet = options.resolveSourcePaths ? new ComponentSet([], options.registry) : undefined;
const result = new ComponentSet([], options.registry);
result.logger.debug(`Setting sourceApiVersion of ${manifest.apiVersion} on ComponentSet from manifest`);
result.sourceApiVersion = manifest.apiVersion;
result.fullName = manifest.fullName;
const addComponent = (component: MetadataComponent, deletionType?: DestructiveChangesType): void => {
if (resolveIncludeSet && !deletionType) {
resolveIncludeSet.add(component);
}
if (resolvePreSet && deletionType) {
resolvePreSet.add(component, deletionType);
}
const memberIsWildcard = component.fullName === ComponentSet.WILDCARD;
if (options.resolveSourcePaths === undefined || !memberIsWildcard || options.forceAddWildcards) {
result.add(component, deletionType);
}
};
const resolveDestructiveChanges = async (
path: string,
destructiveChangeType: DestructiveChangesType
): Promise<void> => {
const destructiveManifest = await manifestResolver.resolve(path);
for (const comp of destructiveManifest.components) {
addComponent(new SourceComponent({ type: comp.type, name: comp.fullName }), destructiveChangeType);
}
};
if (options.destructivePre) {
await resolveDestructiveChanges(options.destructivePre, DestructiveChangesType.PRE);
}
if (options.destructivePost) {
await resolveDestructiveChanges(options.destructivePost, DestructiveChangesType.POST);
}
for (const component of manifest.components) {
addComponent(component);
}
if (options.resolveSourcePaths) {
const components = ComponentSet.fromSource({
fsPaths: options.resolveSourcePaths,
tree: options.tree,
include: resolveIncludeSet,
registry: options.registry,
});
result.forceIgnoredPaths = components.forceIgnoredPaths;
for (const component of components) {
result.add(component);
}
// if there was nothing in the resolveIncludeSet, then we can be missing information that we display to the user for deletes
if (resolveIncludeSet?.size === 0) {
const preCS = ComponentSet.fromSource({
fsPaths: options.resolveSourcePaths,
tree: options.tree,
include: resolvePreSet,
registry: options.registry,
});
for (const component of preCS) {
result.add(component, DestructiveChangesType.PRE);
}
const postCS = ComponentSet.fromSource({
fsPaths: options.resolveSourcePaths,
tree: options.tree,
include: resolvePostSet,
registry: options.registry,
});
for (const component of postCS) {
result.add(component, DestructiveChangesType.POST);
}
}
}
return result;
}
/**
* Resolve components from an org connection.
*
* @param username org connection username
* @returns ComponentSet of source resolved components
*/
public static async fromConnection(username: string): Promise<ComponentSet>;
/**
* Resolve components from an org connection.
*
* @param options
* @returns ComponentSet of source resolved components
*/
public static async fromConnection(options: FromConnectionOptions): Promise<ComponentSet>;
public static async fromConnection(input: string | FromConnectionOptions): Promise<ComponentSet> {
let usernameOrConnection = typeof input === 'string' ? input : input.usernameOrConnection;
const options = (typeof input === 'object' ? input : {}) as Partial<FromConnectionOptions>;
if (typeof usernameOrConnection === 'string') {
usernameOrConnection = await Connection.create({
authInfo: await AuthInfo.create({ username: usernameOrConnection }),
});
if (options.apiVersion && options.apiVersion !== usernameOrConnection.version) {
usernameOrConnection.setApiVersion(options.apiVersion);
}
}
const connectionResolver = new ConnectionResolver(usernameOrConnection, options.registry, options.metadataTypes);
const manifest = await connectionResolver.resolve(options.componentFilter);
const result = new ComponentSet([], options.registry);
result.apiVersion = manifest.apiVersion;
for (const component of manifest.components) {
result.add(component);
}
return result;
}
/**
* Constructs a deploy operation using the components in the set and starts
* the deployment. There must be at least one source-backed component in
* the set to create an operation.
*
* @param options
* @returns Metadata API deploy operation
*/
public async deploy(options: DeploySetOptions): Promise<MetadataApiDeploy> {
const toDeploy = Array.from(this.getSourceComponents());
if (toDeploy.length === 0) {
throw new SfError(messages.getMessage('error_no_source_to_deploy'), 'ComponentSetError');
}
if (
typeof options.usernameOrConnection !== 'string' &&
this.apiVersion &&
this.apiVersion !== options.usernameOrConnection.version
) {
options.usernameOrConnection.setApiVersion(this.apiVersion);
this.logger.debug(
`Received conflicting apiVersion values for deploy. Using option=${this.apiVersion}, Ignoring apiVersion on connection=${options.usernameOrConnection.version}.`
);
}
const operationOptions = Object.assign({}, options, {
components: this,
registry: this.registry,
apiVersion: this.apiVersion,
});
const mdapiDeploy = new MetadataApiDeploy(operationOptions);
await mdapiDeploy.start();
return mdapiDeploy;
}
/**
* Constructs a retrieve operation using the components in the set and
* starts the retrieval.
*
* @param options
* @returns Metadata API retrieve operation
*/
public async retrieve(options: RetrieveSetOptions): Promise<MetadataApiRetrieve> {
const operationOptions = Object.assign({}, options, {
components: this,
registry: this.registry,
apiVersion: this.apiVersion,
});
if (
typeof options.usernameOrConnection !== 'string' &&
this.apiVersion &&
this.apiVersion !== options.usernameOrConnection.version
) {
options.usernameOrConnection.setApiVersion(this.apiVersion);
this.logger.debug(
`Received conflicting apiVersion values for retrieve. Using option=${this.apiVersion}, Ignoring apiVersion on connection=${options.usernameOrConnection.version}.`
);
}
const mdapiRetrieve = new MetadataApiRetrieve(operationOptions);
await mdapiRetrieve.start();
return mdapiRetrieve;
}
/**
* Get an object representation of a package manifest based on the set components.
*
* @param destructiveType Optional value for generating objects representing destructive change manifests
* @returns Object representation of a package manifest
*/
public async getObject(destructiveType?: DestructiveChangesType): Promise<PackageManifestObject> {
// If this ComponentSet has components marked for delete, we need to
// only include those components in a destructiveChanges.xml and
// all other components in the regular manifest.
const components = this.getTypesOfDestructiveChanges().length
? destructiveType
? this.destructiveComponents[destructiveType]
: this.manifestComponents
: this.components;
const typeMap = new Map<string, Set<string>>();
[...components.entries()].map(([key, cmpMap]) => {
const [typeId, fullName] = splitOnFirstDelimiter(key);
const type = this.registry.getTypeByName(typeId);
// Add children
[...(cmpMap?.values() ?? [])]
.flatMap((c) => c.getChildren())
.map((child) => addToTypeMap({ typeMap, type: child.type, fullName: child.fullName, destructiveType }));
// logic: if this is a decomposed type, skip its inclusion in the manifest if the parent is "empty"
if (
type.strategies?.transformer === 'decomposed' &&
// exclude (ex: CustomObjectTranslation) where there are no addressable children
Object.values(type.children?.types ?? {}).some((t) => t.unaddressableWithoutParent !== true) &&
Object.values(type.children?.types ?? {}).some((t) => t.isAddressable !== false)
) {
const parentComp = [...(cmpMap?.values() ?? [])].find((c) => c.fullName === fullName);
if (parentComp?.xml && !objectHasSomeRealValues(type)(parentComp.parseXmlSync())) {
return;
}
}
addToTypeMap({
typeMap,
type: type.folderContentType ? this.registry.getTypeByName(type.folderContentType) : type,
fullName: constructFullName(this.registry, type, fullName),
destructiveType,
});
});
const typeMembers = Array.from(typeMap.entries())
.map(([typeName, members]) => ({ members: [...members].sort(), name: typeName }))
.sort((a, b) => (a.name > b.name ? 1 : -1));
return {
Package: {
...{
types: typeMembers,
version: await this.getApiVersion(),
},
...(this.fullName ? { fullName: this.fullName } : {}),
},
};
}
/**
* Create a manifest in xml format based on the set components and the
* type of manifest to create.
*
* E.g. package.xml or destructiveChanges.xml
*
* @param indentation Number of spaces to indent lines by.
* @param destructiveType What type of destructive manifest to build.
*/
public async getPackageXml(indentation = 4, destructiveType?: DestructiveChangesType): Promise<string> {
const builder = new XMLBuilder({
format: true,
indentBy: ''.padEnd(indentation, ' '),
ignoreAttributes: false,
});
const toParse = await this.getObject(destructiveType);
toParse.Package[XML_NS_KEY] = XML_NS_URL;
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return XML_DECL.concat(builder.build(toParse));
}
/**
* Get only the source-backed metadata components in the set.
*
* @param member Member to retrieve source-backed components for.
* @returns Collection of source-backed components
*/
public getSourceComponents(member?: ComponentLike): LazyCollection<SourceComponent> {
let iter: Iterable<MetadataComponent>;
if (member) {
// filter optimization
const memberCollection = this.components.get(simpleKey(member));
iter = memberCollection && memberCollection.size > 0 ? memberCollection.values() : [];
} else {
// eslint-disable-next-line @typescript-eslint/no-this-alias
iter = this;
}
return new LazyCollection(iter).filter((c) => c instanceof SourceComponent) as LazyCollection<SourceComponent>;
}
public add(component: ComponentLike, deletionType?: DestructiveChangesType): void {
const key = simpleKey(component);
if (!this.components.has(key)) {
this.components.set(key, new DecodeableMap<string, SourceComponent>());
}
if (!deletionType && typeof component.type !== 'string') {
// this component is meant to be added to manifestComponents, even if it's not a fully validated source component,
// this ensures when getObject is called, we created consistent manifests whether using this.components, or this.manifestComponents
// when no destructive changes are present, we use this.components (not fully validated as source components, so typos end up in the generated manifest)
// when destructive changes are used, we use this.manifestComponents (fully validated, would not match this.components)
// this ensures this.components manifest === this.manifestComponents manifest
const sc = new SourceComponent({ type: component.type, name: component.fullName });
const srcKey = sourceKey(sc);
if (!this.manifestComponents.has(key)) {
this.manifestComponents.set(key, new DecodeableMap<string, SourceComponent>());
}
this.manifestComponents.get(key)?.set(srcKey, sc);
}
if (!(component instanceof SourceComponent)) {
return;
}
const srcKey = sourceKey(component);
// we're working with SourceComponents now
this.components.get(key)?.set(srcKey, component);
// Build maps of destructive components and regular components as they are added
// as an optimization when building manifests.
if (deletionType) {
component.setMarkedForDelete(deletionType);
this.logger.debug(`Marking component for delete: ${component.fullName}`);
if (!this.destructiveComponents[deletionType].has(key)) {
this.destructiveComponents[deletionType].set(key, new DecodeableMap<string, SourceComponent>());
}
this.destructiveComponents[deletionType].get(key)?.set(srcKey, component);
// updated with deletion information
this.components.get(key)?.set(srcKey, component);
} else {
if (!this.manifestComponents.has(key)) {
this.manifestComponents.set(key, new DecodeableMap<string, SourceComponent>());
}
this.manifestComponents.get(key)?.set(srcKey, component);
}
}
/**
* Tests whether or not a `fullName` and `type` pair is present in the set.
*
* A pair is considered present in the set if one of the following criteria is met:
*
* - The pair is directly in the set, matching the component key "as is" or decoded.
* - A wildcard component with the same `type` as the pair
* - If a parent is attached to the pair and the parent is directly in the set
* - If a parent is attached to the pair, and a wildcard component's `type` matches the parent's `type`
*
* @param component Component to test for membership in the set
* @returns `true` if the component is in the set
*/
public has(component: ComponentLike): boolean {
const key = simpleKey(component);
if (this.components.has(key)) {
return true;
}
const wildcardMember: ComponentLike = {
fullName: ComponentSet.WILDCARD,
type: typeof component.type === 'object' ? component.type.name : component.type,
};
const isIncludedInWildcard = this.components.has(simpleKey(wildcardMember));
if (isIncludedInWildcard) {
return true;
}
if (typeof component.type === 'object') {
const { parent } = component as MetadataComponent;
if (parent) {
const parentDirectlyInSet = this.components.has(simpleKey(parent));
if (parentDirectlyInSet) {
return true;
}
const wildcardKey = simpleKey({
fullName: ComponentSet.WILDCARD,
type: parent.type,
});
const parentInWildcard = this.components.has(wildcardKey);
if (parentInWildcard) {
return true;
}
const partialWildcardKey = simpleKey({
fullName: `${parent.fullName}.${ComponentSet.WILDCARD}`,
type: component.type,
});
const parentInPartialWildcard = this.components.has(partialWildcardKey);
if (parentInPartialWildcard) {
return true;
}
}
}
return false;
}
/**
* For a fullName and type, this returns the filenames the matching component, or an empty array if the component is not present
*
* @param param Object with fullName and type properties
* @returns string[]
*/
public getComponentFilenamesByNameAndType({ fullName, type }: MetadataMember): string[] {
const key = simpleKey({ fullName, type });
const componentMap = this.components.get(key);
if (!componentMap) {
return [];
}
const output = new Set<string>();
componentMap.forEach((component) => {
[...component.walkContent(), component.content, component.xml]
.filter(isString)
.map((filename) => output.add(filename));
});
return Array.from(output);
}
public *[Symbol.iterator](): Iterator<MetadataComponent> {
for (const [key, sourceComponents] of this.components.entries()) {
if (sourceComponents.size === 0) {
const [typeName, fullName] = splitOnFirstDelimiter(key);
yield {
fullName,
type: this.registry.getTypeByName(typeName),
};
} else {
for (const component of sourceComponents.values()) {
yield component;
}
}
}
}
/**
* If this `ComponentSet` has components marked for delete, this sets
* whether those components are deleted before any other changes are
* deployed (`destructiveChangesPre.xml`) or after changes are deployed
* (`destructiveChangesPost.xml`).
*
* @param type The type of destructive changes to make; i.e., pre or post deploy.
*/
public setDestructiveChangesType(type: DestructiveChangesType): void {
this.destructiveChangesType = type;
}
/**
* If this `ComponentSet` has components marked for delete it will use this
* type to build the appropriate destructive changes manifest.
*
* @returns The type of destructive changes to make; i.e., pre or post deploy.
*/
public getDestructiveChangesType(): DestructiveChangesType {
return this.destructiveChangesType;
}
/**
* Will return the types of destructive changes in the component set
* or an empty array if there aren't destructive components present
*
* @return DestructiveChangesType[]
*/
public getTypesOfDestructiveChanges(): DestructiveChangesType[] {
const destructiveChangesTypes: DestructiveChangesType[] = [];
if (this.destructiveChangesPre.size) {
destructiveChangesTypes.push(DestructiveChangesType.PRE);
}
if (this.destructiveChangesPost.size) {
destructiveChangesTypes.push(DestructiveChangesType.POST);
}
return destructiveChangesTypes;
}
/**
* Returns an API version to use as the value of the `version` field
* in a manifest (package.xml) for MDAPI calls in the following order
* of preference:
*
* 1. this.sourceApiVersion
* 2. this.apiVersion
* 3. sourceApiVersion set in sfdx-project.json
* 4. apiVersion from ConfigAggregator (config files and Env Vars)
* 5. http call to apexrest endpoint for highest apiVersion
* 6. hardcoded value of "58.0" as a last resort
*
* @returns string The resolved API version to use in a manifest
*/
private async getApiVersion(): Promise<string> {
let version = this.sourceApiVersion ?? this.apiVersion;
if (!version) {
try {
const project = await SfProject.resolve(this.projectDirectory);
const projectConfig = await project.resolveProjectConfig();
version = projectConfig?.sourceApiVersion as string;
} catch (e) {
// If there's any problem just move on to ConfigAggregator
}
}
if (!version) {
try {
version = ConfigAggregator.getValue(OrgConfigProperties.ORG_API_VERSION).value as string;
} catch (e) {
// If there's any problem just move on to the REST endpoint
}
}
if (!version) {
try {
version = `${await getCurrentApiVersion()}.0`;
} catch (e) {
version = '58.0';
this.logger.warn(messages.getMessage('missingApiVersion'));
}
}
return version;
}
}
const sourceKey = (component: SourceComponent): string => {
const { fullName, type, xml, content } = component;
return `${type.name}${fullName}${xml ?? ''}${content ?? ''}`;
};
const simpleKey = (component: ComponentLike): string => {
const typeName = typeof component.type === 'string' ? component.type.toLowerCase().trim() : component.type.id;
return `${typeName}${KEY_DELIMITER}${component.fullName}`;
};
const splitOnFirstDelimiter = (input: string): [string, string] => {
const indexOfSplitChar = input.indexOf(KEY_DELIMITER);
return [input.substring(0, indexOfSplitChar), input.substring(indexOfSplitChar + 1)];
};
const constructFullName = (registry: RegistryAccess, type: MetadataType, fullName: string): string =>
// Some InFolder types are different. e.g., Report/ReportFolder & Dashboard/DashboardFolder.
// ReportFolders are deployed/retrieved as Reports. If a ReportFolder is being added append
// a "/" so the metadata API can identify it as a folder.
['DashboardFolder', 'ReportFolder', 'EmailTemplateFolder'].includes(type.name) && !fullName.endsWith('/')
? `${fullName}/`
: registry.getParentType(type.name)?.strategies?.recomposition === 'startEmpty' && fullName.includes('.')
? // they're reassembled like CustomLabels.MyLabel
fullName.split('.')[1]
: fullName;
/** side effect: mutates the typeMap property */
const addToTypeMap = ({
typeMap,
type,
fullName,
destructiveType,
}: {
typeMap: Map<string, Set<string>>;
type: MetadataType;
fullName: string;
destructiveType?: DestructiveChangesType;
}): void => {
if (type.isAddressable === false) return;
if (fullName === ComponentSet.WILDCARD && !type.supportsWildcardAndName && !destructiveType) {
// if the type doesn't support mixed wildcards and specific names, overwrite the names to be a wildcard
typeMap.set(type.name, new Set([fullName]));
return;
}
const existing = typeMap.get(type.name) ?? new Set<string>();
if (!existing.has(ComponentSet.WILDCARD) || type.supportsWildcardAndName) {
// if the type supports both wildcards and names, add them regardless
typeMap.set(type.name, existing.add(fullName));
}
};