-
Notifications
You must be signed in to change notification settings - Fork 36
/
MetadataType.js
2922 lines (2756 loc) · 124 KB
/
MetadataType.js
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/* eslint no-unused-vars:off */
/*
* README no-unused-vars is reduced to WARNING here as this file is a template
* for all metadata types and methods often define params that are not used
* in the generic version of the method
*/
import { Util } from '../util/util.js';
import File from '../util/file.js';
import cache from '../util/cache.js';
import deepEqual from 'deep-equal';
import pLimit from 'p-limit';
import Mustache from 'mustache';
import MetadataTypeInfo from '../MetadataTypeInfo.js';
import validationsRules from '../util/validations.js';
/**
* @typedef {import('../../types/mcdev.d.js').BuObject} BuObject
* @typedef {import('../../types/mcdev.d.js').CodeExtract} CodeExtract
* @typedef {import('../../types/mcdev.d.js').CodeExtractItem} CodeExtractItem
* @typedef {import('../../types/mcdev.d.js').Mcdevrc} Mcdevrc
* @typedef {import('../../types/mcdev.d.js').MetadataTypeItem} MetadataTypeItem
* @typedef {import('../../types/mcdev.d.js').MetadataTypeItemDiff} MetadataTypeItemDiff
* @typedef {import('../../types/mcdev.d.js').MetadataTypeItemObj} MetadataTypeItemObj
* @typedef {import('../../types/mcdev.d.js').MetadataTypeMap} MetadataTypeMap
* @typedef {import('../../types/mcdev.d.js').MetadataTypeMapObj} MetadataTypeMapObj
* @typedef {import('../../types/mcdev.d.js').MultiMetadataTypeList} MultiMetadataTypeList
* @typedef {import('../../types/mcdev.d.js').SoapRequestParams} SoapRequestParams
* @typedef {import('../../types/mcdev.d.js').TemplateMap} TemplateMap
* @typedef {import('../../types/mcdev.d.js').TypeKeyCombo} TypeKeyCombo
* @typedef {import('sfmc-sdk').default} SDK
* @typedef {import('../../types/mcdev.d.js').SDKError} SDKError
* @typedef {import('../../types/mcdev.d.js').SOAPError} SOAPError
* @typedef {import('../../types/mcdev.d.js').RestError} RestError
* @typedef {import('../../types/mcdev.d.js').ContentBlockConversionTypes} ContentBlockConversionTypes
*/
/**
* ensure that Mustache does not escape any characters
*
* @param {string} text -
* @returns {string} text
*/
Mustache.escape = function (text) {
return text;
};
/**
* MetadataType class that gets extended by their specific metadata type class.
* Provides default functionality that can be overwritten by child metadata type classes
*
*/
class MetadataType {
/**
* Returns file contents mapped to their filename without '.json' ending
*
* @param {string} dir directory with json files, e.g. /retrieve/cred/bu/event, /deploy/cred/bu/event, /template/event
* @param {boolean} [listBadKeys] do not print errors, used for badKeys()
* @param {string[]} [selectedSubType] asset, message, ...
* @returns {Promise.<MetadataTypeMap>} fileName => fileContent map
*/
static async getJsonFromFS(dir, listBadKeys, selectedSubType) {
const fileName2FileContent = {};
try {
const files = await File.readdir(dir);
for (const fileName of files) {
try {
if (fileName.endsWith('.json')) {
const fileContent = await File.readJSONFile(dir, fileName, false);
const fileNameWithoutEnding = File.reverseFilterIllegalFilenames(
fileName.split(/\.(\w|-)+-meta.json/)[0]
);
// We always store the filename using the External Key (CustomerKey or key) to avoid duplicate names.
// to ensure any changes are done to both the filename and external key do a check here
// ! convert numbers to string to allow numeric keys to be checked properly
const key = Number.isInteger(fileContent[this.definition.keyField])
? fileContent[this.definition.keyField].toString()
: fileContent[this.definition.keyField];
if (key === fileNameWithoutEnding || listBadKeys) {
fileName2FileContent[fileNameWithoutEnding] = fileContent;
} else {
Util.logger.error(
` ${this.definition.type} ${key}: Name of the metadata file and the JSON-key (${this.definition.keyField}) must match` +
Util.getGrayMsg(` - ${dir}/${fileName}`)
);
}
}
} catch (ex) {
// by catching this in the loop we gracefully handle the issue and move on to the next file
Util.metadataLogger('debug', this.definition.type, 'getJsonFromFS', ex);
}
}
} catch (ex) {
// this will catch issues with readdirSync
Util.metadataLogger('debug', this.definition.type, 'getJsonFromFS', ex);
throw new Error(ex);
}
return fileName2FileContent;
}
/**
* Returns fieldnames of Metadata Type. 'this.definition.fields' variable only set in child classes.
*
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {boolean} [isCaching] if true, then check if field should be skipped for caching
* @returns {string[]} Fieldnames
*/
static getFieldNamesToRetrieve(additionalFields, isCaching) {
const fieldNames = [];
for (const fieldName in this.definition.fields) {
if (
additionalFields?.includes(fieldName) ||
(this.definition.fields[fieldName].retrieving &&
!(isCaching && this.definition.fields[fieldName].skipCache))
) {
fieldNames.push(fieldName);
}
}
if (!fieldNames.includes(this.definition.idField)) {
// Always retrieve the ID because it may be used in references
fieldNames.push(this.definition.idField);
}
return fieldNames;
}
/**
* Deploys metadata
*
* @param {MetadataTypeMap} metadataMap metadata mapped by their keyField
* @param {string} deployDir directory where deploy metadata are saved
* @param {string} retrieveDir directory where metadata after deploy should be saved
* @returns {Promise.<MetadataTypeMap>} Promise of keyField => metadata map
*/
static async deploy(metadataMap, deployDir, retrieveDir) {
const upsertedMetadataMap = await this.upsert(metadataMap, deployDir);
if (retrieveDir) {
// deploy can be run with retrieveDir set to null for deploying auto-created foldes - these should not be saved to the retrieve-folder while everything else should
const savedMetadataMap = await this.saveResults(upsertedMetadataMap, retrieveDir, null);
if (
this.properties.metaDataTypes.documentOnRetrieve.includes(this.definition.type) &&
!this.definition.documentInOneFile
) {
// * do not await here as this might take a while and has no impact on the deploy
// * this should only be run if documentation is on a per metadata record level. Types that document an overview into a single file will need a full retrieve to work instead
this.document(savedMetadataMap, true);
}
}
return upsertedMetadataMap;
}
/**
* Gets executed after deployment of metadata type
*
* @param {MetadataTypeMap} upsertResults metadata mapped by their keyField as returned by update/create
* @param {MetadataTypeMap} originalMetadata metadata to be updated (contains additioanl fields)
* @param {{created: number, updated: number}} createdUpdated counter representing successful creates/updates
* @returns {Promise.<void>} -
*/
static async postDeployTasks(upsertResults, originalMetadata, createdUpdated) {}
/**
* helper for {@link MetadataType.createREST}
*
* @param {MetadataTypeItem} metadataEntry a single metadata Entry
* @param {object} apiResponse varies depending on the API call
* @param {MetadataTypeItem} metadataEntryWithAllFields like metadataEntry but before non-creatable fields were stripped
* @returns {void}
*/
static postCreateTasks(metadataEntry, apiResponse, metadataEntryWithAllFields) {}
/**
* helper for {@link MetadataType.updateREST}
*
* @param {MetadataTypeItem} metadataEntry a single metadata Entry
* @param {object} apiResponse varies depending on the API call
* @returns {void}
*/
static postUpdateTasks(metadataEntry, apiResponse) {}
/**
* helper for {@link MetadataType.createREST} when legacy API endpoints as these do not return the created item but only their new id
*
* @param {MetadataTypeItem} metadataEntry a single metadata Entry
* @param {object} apiResponse varies depending on the API call
* @returns {Promise.<void>} -
*/
static async postDeployTasks_legacyApi(metadataEntry, apiResponse) {
if (!apiResponse?.[this.definition.idField] && !metadataEntry?.[this.definition.idField]) {
return;
}
const id =
apiResponse?.[this.definition.idField] || metadataEntry?.[this.definition.idField];
// re-retrieve created items because the API does not return any info for them except the new id (api key)
try {
const { metadata } = await this.retrieveForCache(null, null, 'id:' + id);
const item = Object.values(metadata)[0];
// ensure the "created item" cli log entry has the new auto-generated value
metadataEntry[this.definition.keyField] = item[this.definition.keyField];
// ensure postRetrieveTasks has the complete object in "apiResponse"
Object.assign(apiResponse, item);
// postRetrieveTasks will be run automatically on this via super.saveResult
} catch (ex) {
throw new Error(
`Could not get details for new ${this.definition.type} ${id} from server (${ex.message})`
);
}
}
/**
* Gets executed after retreive of metadata type
*
* @param {MetadataTypeItem} metadata a single item
* @param {string} targetDir folder where retrieves should be saved
* @param {boolean} [isTemplating] signals that we are retrieving templates
* @returns {MetadataTypeItem} cloned metadata
*/
static postRetrieveTasks(metadata, targetDir, isTemplating) {
return structuredClone(metadata);
}
/**
* generic script that retrieves the folder path from cache and updates the given metadata with it after retrieve
*
* @param {MetadataTypeItem} metadata a single item
*/
static setFolderPath(metadata) {
if (!this.definition.folderIdField) {
return;
}
try {
metadata.r__folder_Path = cache.searchForField(
'folder',
metadata[this.definition.folderIdField],
'ID',
'Path'
);
delete metadata[this.definition.folderIdField];
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}): Could not find folder (${ex.message})`
);
}
}
/**
* generic script that retrieves the folder ID from cache and updates the given metadata with it before deploy
*
* @param {MetadataTypeItem} metadata a single item
*/
static setFolderId(metadata) {
if (!this.definition.folderIdField) {
return;
}
if (!metadata.r__folder_Path) {
throw new Error(
`Dependent folder could not be found because r__folder_Path is not set`
);
}
metadata[this.definition.folderIdField] = cache.getFolderId(metadata.r__folder_Path);
delete metadata.r__folder_Path;
}
/**
* Gets metadata from Marketing Cloud
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {string[]} [subTypeArr] optionally limit to a single subtype
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<MetadataTypeMapObj>} metadata
*/
static async retrieve(retrieveDir, additionalFields, subTypeArr, key) {
Util.metadataLogger('error', this.definition.type, 'retrieve', `Not Supported`);
const metadata = {};
return { metadata: {}, type: this.definition.type };
}
/**
* Gets metadata from Marketing Cloud
*
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {string[]} [subTypeArr] optionally limit to a single subtype
* @returns {Promise.<MetadataTypeMapObj>} metadata
*/
static retrieveChangelog(additionalFields, subTypeArr) {
return this.retrieveForCache(additionalFields, subTypeArr);
}
/**
* Gets metadata cache with limited fields and does not store value to disk
*
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {string[]} [subTypeArr] optionally limit to a single subtype
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<MetadataTypeMapObj>} metadata
*/
static async retrieveForCache(additionalFields, subTypeArr, key) {
return this.retrieve(null, additionalFields, subTypeArr, key);
}
/**
* Gets metadata cache with limited fields and does not store value to disk
*
* @param {string} templateDir Directory where retrieved metadata directory will be saved
* @param {string} name name of the metadata file
* @param {TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} [subType] optionally limit to a single subtype
* @returns {Promise.<MetadataTypeItemObj>} metadata
*/
static async retrieveAsTemplate(templateDir, name, templateVariables, subType) {
Util.logger.error('retrieveAsTemplate is not supported yet for ' + this.definition.type);
Util.metadataLogger(
'debug',
this.definition.type,
'retrieveAsTemplate',
`(${templateDir}, ${name}, ${templateVariables}) no templating function`
);
return { metadata: null, type: this.definition.type };
}
/**
* Retrieve a specific Script by Name
*
* @param {string} templateDir Directory where retrieved metadata directory will be saved
* @param {string} uri rest endpoint for GET
* @param {TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} name name (not key) of the metadata item
* @returns {Promise.<{metadata: MetadataTypeItem, type: string}>} Promise
*/
static async retrieveTemplateREST(templateDir, uri, templateVariables, name) {
return this.retrieveREST(templateDir, uri, templateVariables, name);
}
/**
* Gets metadata cache with limited fields and does not store value to disk
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {string} templateDir (List of) Directory where built definitions will be saved
* @param {string} key name of the metadata file
* @param {TemplateMap} templateVariables variables to be replaced in the metadata
* @returns {Promise.<MetadataTypeItemObj>} single metadata
*/
static async buildTemplate(retrieveDir, templateDir, key, templateVariables) {
// retrieve metadata template
let metadataStr;
const typeDirArr = [this.definition.type];
const subType = await this.findSubType(retrieveDir, key);
if (subType) {
typeDirArr.push(subType);
}
const suffix = subType ? `-${subType}-meta` : '-meta';
const fileName = key + '.' + this.definition.type + suffix;
try {
// ! do not load via readJSONFile to ensure we get a string, not parsed JSON
// templated files might contain illegal json before the conversion back to the file that shall be saved
metadataStr = await File.readFilteredFilename(
[retrieveDir, ...typeDirArr],
fileName,
'json'
);
if (!metadataStr) {
throw new Error('File not found');
}
} catch (ex) {
try {
metadataStr = await this.readSecondaryFolder(
retrieveDir,
typeDirArr,
key,
fileName,
ex
);
} catch {
// only happening for types that use readSecondaryFolder (e.g. asset)
// if we still have no metadataStr then we have to skip this metadata for all types and hence handle it outside of this catch
}
if (!metadataStr) {
Util.logger.warn(
Util.getGrayMsg(` ☇ skipped ${this.definition.type} ${key}: not found`)
);
return;
}
}
if (this.definition.stringifyFieldsBeforeTemplate) {
// numeric fields are returned as numbers by the SDK/API. If we try to replace them in buildTemplate it would break the JSON format - but not if we stringify them first because then the {{{var}}} is in quotes
const metadataTemp = JSON.parse(metadataStr);
for (const field of this.definition.stringifyFieldsBeforeTemplate) {
if (metadataTemp[field]) {
if (Array.isArray(metadataTemp[field])) {
for (let i = 0; i < metadataTemp[field].length; i++) {
metadataTemp[field][i] = metadataTemp[field][i].toString();
}
} else if ('object' === typeof metadataTemp[field]) {
for (const subField in metadataTemp[field]) {
metadataTemp[field][subField] =
metadataTemp[field][subField].toString();
}
} else {
metadataTemp[field] = metadataTemp[field].toString();
}
}
}
metadataStr = JSON.stringify(metadataTemp);
}
// handle extracted code
// templating to extracted content is applied inside of buildTemplateForNested()
await this.buildTemplateForNested(
retrieveDir,
templateDir,
JSON.parse(metadataStr),
templateVariables,
key
);
const metadata = JSON.parse(Util.replaceByObject(metadataStr, templateVariables));
this.keepTemplateFields(metadata);
try {
// write to file
await File.writeJSONToFile([templateDir, ...typeDirArr], fileName, metadata);
Util.logger.info(
`- templated ${this.definition.type}: ${key} (${
metadata[this.definition.nameField]
})`
);
return { metadata: metadata, type: this.definition.type };
} catch (ex) {
throw new Error(`${this.definition.type}:: ${ex.message}`);
}
}
/**
* Gets executed before deploying metadata
*
* @param {MetadataTypeItem} metadata a single metadata item
* @param {string} deployDir folder where files for deployment are stored
* @returns {Promise.<MetadataTypeItem>} Promise of a single metadata item
*/
static async preDeployTasks(metadata, deployDir) {
return metadata;
}
/**
* helper to find a new unique name during item creation
*
* @param {string} key key of the item
* @param {string} name name of the item
* @param {{ type: string; key: string; name: any; }[]} namesInFolder names of the items in the same folder
* @param {string} [subtype] itemType-name
* @returns {string} new name
*/
static findUniqueName(key, name, namesInFolder, subtype) {
let newName = name;
let suffix;
let i = 1;
while (
namesInFolder.find(
(item) =>
item.name === newName && item.key !== key && (!subtype || item.type === subtype)
)
) {
suffix = ' (' + i + ')';
// for customer key max is 100 chars
newName = name.slice(0, Math.max(0, 100 - suffix.length)) + suffix;
i++;
}
return newName;
}
/**
* Abstract create method that needs to be implemented in child metadata type
*
* @param {MetadataTypeItem} metadata single metadata entry
* @param {string} deployDir directory where deploy metadata are saved
* @returns {Promise.<object> | null} Promise of API response or null in case of an error
*/
static async create(metadata, deployDir) {
Util.logger.error(
` ☇ skipping ${this.definition.type} ${metadata[this.definition.keyField]} / ${
metadata[this.definition.nameField]
}: create is not supported yet for ${this.definition.type}`
);
return;
}
/**
* Abstract update method that needs to be implemented in child metadata type
*
* @param {MetadataTypeItem} metadata single metadata entry
* @param {MetadataTypeItem} [metadataBefore] metadata mapped by their keyField
* @returns {Promise.<object> | null} Promise of API response or null in case of an error
*/
static async update(metadata, metadataBefore) {
Util.logger.error(
` ☇ skipping ${this.definition.type} ${metadata[this.definition.keyField]} / ${
metadata[this.definition.nameField]
}: update is not supported yet for ${this.definition.type}`
);
return;
}
/**
* Abstract refresh method that needs to be implemented in child metadata type
*
* @param {string[]} [keyArr] metadata keys
* @param {boolean} [checkKey] whether to check if the key is valid
* @returns {Promise.<string[]>} Returns list of keys that were refreshed
*/
static async refresh(keyArr, checkKey = true) {
Util.logger.error(
` ☇ skipping ${this.definition.type}: refresh is not supported yet for ${this.definition.type}`
);
return [];
}
/**
*
* @param {string[]} keyArr limit retrieval to given metadata type
* @param {string} retrieveDir retrieve dir including cred and bu
* @param {Set.<string>} [findAssetKeys] list of keys that were found referenced via ContentBlockByX; if set, method only gets keys and runs no updates
* @returns {Promise.<Set.<string>>} found asset keys
*/
static async getCbReferenceKeys(keyArr, retrieveDir, findAssetKeys) {
if (!Object.prototype.hasOwnProperty.call(this, 'replaceCbReference')) {
// only types that have a replaceCbReference method actually have ampscript/ssjs
return;
}
// get all metadata of the current type; then filter by keys in selectedTypes
const metadataMap = Util.filterObjByKeys(
await this.getJsonFromFS(File.normalizePath([retrieveDir, this.definition.type])),
keyArr
);
await this.replaceCbReferenceLoop(metadataMap, retrieveDir, findAssetKeys);
return findAssetKeys;
}
/**
* this iterates over all items found in the retrieve folder and executes the type-specific method for replacing references
*
* @param {MetadataTypeMap} metadataMap list of metadata (keyField => metadata)
* @param {string} retrieveDir retrieve dir including cred and bu
* @param {Set.<string>} [findAssetKeys] list of keys that were found referenced via ContentBlockByX; if set, method only gets keys and runs no updates
* @returns {Promise.<string[]>} Returns list of keys for which references were replaced
*/
static async replaceCbReferenceLoop(metadataMap, retrieveDir, findAssetKeys) {
const keysForDeploy = [];
if (!metadataMap) {
// if a type was skipped e.g. because it shall only be looked at on the parent then we would expect metadataMap to be undefined
return keysForDeploy;
}
const fromDescription = Util.OPTIONS.referenceFrom
.map((from) => 'ContentBlockBy' + Util.capitalizeFirstLetter(from))
.join(' and ');
if (Object.keys(metadataMap).length) {
Util.logger.debug(` - Searching in ${this.definition.type} `);
const baseDir = [retrieveDir, ...this.definition.type.split('-')];
const deployMap = {};
for (const key in metadataMap) {
const item = metadataMap[key];
if (this.isFiltered(item, true) || this.isFiltered(item, false)) {
// we would not have saved these items to disk but they exist in the cache and hence need to be skipped here
continue;
}
try {
// add key but make sure to turn it into string or else numeric keys will be filtered later
deployMap[key] = await this.replaceCbReference(
item,
retrieveDir,
findAssetKeys
);
keysForDeploy.push(key + '');
if (!findAssetKeys) {
await this.saveToDisk(deployMap, key, baseDir);
Util.logger.info(
` - added ${this.definition.type} to update queue: ${key}`
);
}
} catch (ex) {
if (ex.code !== 200) {
// dont print error if we simply did not find relevant content blocks
Util.logger.errorStack(
ex,
'issue with ' + this.definition.type + ' ' + key
);
}
if (!findAssetKeys) {
Util.logger.info(
Util.getGrayMsg(
` ☇ skipping ${this.definition.type} ${
item[this.definition.keyField]
}: no ${fromDescription} found`
)
);
}
}
}
if (!findAssetKeys) {
Util.logger.info(
`Found ${keysForDeploy.length} ${this.definition.type}${keysForDeploy.length === 1 ? '' : 's'} to update`
);
}
}
return keysForDeploy;
}
/**
* Abstract execute method that needs to be implemented in child metadata type
*
* @param {MetadataTypeItem} item single metadata item
* @param {string} [retrieveDir] directory where metadata is saved
* @param {Set.<string>} [findAssetKeys] list of keys that were found referenced via ContentBlockByX; if set, method only gets keys and runs no updates
* @returns {Promise.<MetadataTypeItem | CodeExtractItem>} key of the item that was updated
*/
static async replaceCbReference(item, retrieveDir, findAssetKeys) {
Util.logger.error(
` ☇ skipping ${this.definition.type}: replaceCbReference is not supported yet for ${this.definition.type}`
);
return [];
}
/**
* Abstract execute method that needs to be implemented in child metadata type
*
* @param {string[]} keyArr customerkey of the metadata
* @returns {Promise.<string[]>} Returns list of keys that were executed
*/
static async execute(keyArr) {
Util.logger.error(
` ☇ skipping ${this.definition.type}: execute is not supported yet for ${this.definition.type}`
);
return [];
}
/**
* Abstract pause method that needs to be implemented in child metadata type
*
* @param {string[]} keyArr customerkey of the metadata
* @returns {Promise.<string[]>} Returns list of keys that were paused
*/
static async pause(keyArr) {
Util.logger.error(
` ☇ skipping ${this.definition.type}: pause is not supported yet for ${this.definition.type}`
);
return [];
}
/**
* Abstract stop method that needs to be implemented in child metadata type
*
* @param {string[]} keyArr customerkey of the metadata
* @returns {Promise.<string[]>} Returns list of keys that were stopped
*/
static async stop(keyArr) {
Util.logger.error(
` ☇ skipping ${this.definition.type}: stop is not supported yet for ${this.definition.type}`
);
return [];
}
/**
* test if metadata was actually changed or not to potentially skip it during deployment
*
* @param {MetadataTypeItem} cachedVersion cached version from the server
* @param {MetadataTypeItem} metadata item to upload
* @param {string} [fieldName] optional field name to use for identifying the record in logs
* @returns {boolean} true if metadata was changed
*/
static hasChanged(cachedVersion, metadata, fieldName) {
// should be set up type by type but the *_generic version is likely a good start for many types
return true;
}
/**
* test if metadata was actually changed or not to potentially skip it during deployment
*
* @param {MetadataTypeItem} cachedVersion cached version from the server
* @param {MetadataTypeItem} metadataItem item to upload
* @param {string} [fieldName] optional field name to use for identifying the record in logs
* @param {boolean} [silent] optionally suppress logging
* @returns {boolean} true on first identified deviation or false if none are found
*/
static hasChangedGeneric(cachedVersion, metadataItem, fieldName, silent) {
if (!cachedVersion) {
return true;
}
// we do need the full set in other places and hence need to work with a clone here
const clonedMetada = structuredClone(metadataItem);
// keep copy of identifier in case it is among the non-updateable fields
const identifier = clonedMetada[fieldName || this.definition.keyField];
this.removeNotUpdateableFields(clonedMetada);
// iterate over what we want to upload rather than what we cached to avoid false positives
for (const prop in clonedMetada) {
if (this.definition.ignoreFieldsForUpdateCheck?.includes(prop)) {
continue;
}
if (
clonedMetada[prop] === null ||
['string', 'number', 'boolean'].includes(typeof clonedMetada[prop])
) {
// check simple variables directly
// check should ignore types to bypass string/number auto-conversions caused by SFMC-SDK
if (clonedMetada[prop] != cachedVersion[prop]) {
Util.logger.debug(
`${this.definition.type}:: ${
identifier
}.${prop} changed: '${cachedVersion[prop]}' to '${clonedMetada[prop]}'`
);
return true;
}
} else if (deepEqual(clonedMetada[prop], cachedVersion[prop])) {
// test complex objects here
Util.logger.debug(
`${this.definition.type}:: ${
identifier
}.${prop} changed: '${cachedVersion[prop]}' to '${clonedMetada[prop]}'`
);
return true;
}
}
if (!silent) {
Util.logger.verbose(
` ☇ skipping ${this.definition.type} ${identifier} / ${
clonedMetada[this.definition.nameField] || ''
}: no change detected`
);
}
return false;
}
/**
* MetadataType upsert, after retrieving from target and comparing to check if create or update operation is needed.
*
* @param {MetadataTypeMap} metadataMap metadata mapped by their keyField
* @param {string} deployDir directory where deploy metadata are saved
* @param {boolean} [runUpsertSequentially] when a type has self-dependencies creates need to run one at a time and created/changed keys need to be cached to ensure following creates/updates have thoses keys available
* @returns {Promise.<MetadataTypeMap>} keyField => metadata map
*/
static async upsert(metadataMap, deployDir, runUpsertSequentially = false) {
const orignalMetadataMap = structuredClone(metadataMap);
const metadataToUpdate = [];
const metadataToCreate = [];
let createResults = [];
let updateResults = [];
let filteredByPreDeploy = 0;
for (const metadataKey in metadataMap) {
let hasError = false;
try {
// preDeployTasks parsing
let deployableMetadata;
try {
await this.validation('deploy', metadataMap[metadataKey], deployDir);
deployableMetadata = await this.preDeployTasks(
metadataMap[metadataKey],
deployDir
);
} catch (ex) {
// do this in case something went wrong during pre-deploy steps to ensure the total counter is correct
hasError = true;
deployableMetadata = metadataMap[metadataKey];
// * include ": ${ex.message}" in the error if this is ever turned back into Util.logger.error()
Util.logger.errorStack(
ex,
` ☇ skipping ${this.definition.type} ${
deployableMetadata[this.definition.keyField]
} / ${deployableMetadata[this.definition.nameField]}`
);
}
// if preDeploy returns nothing then it cannot be deployed so skip deployment
if (deployableMetadata) {
metadataMap[metadataKey] = deployableMetadata;
// create normalizedKey off of whats in the json rather than from "metadataKey" because preDeployTasks might have altered something (type asset)
const action = await this.createOrUpdate(
metadataMap,
metadataKey,
hasError,
metadataToUpdate,
metadataToCreate
);
if (runUpsertSequentially) {
if (action === 'create') {
// handle creates sequentially here becasue we might have interdepencies
const result = await this.create(metadataMap[metadataKey], deployDir);
if (result) {
createResults.push(result);
// make this newly created item available in cache for other itmes that might reference it
const newObject = {};
newObject[metadataKey] = metadataMap[metadataKey];
cache.mergeMetadata(this.definition.type, newObject);
}
} else if (action === 'update' && !Util.OPTIONS.noUpdate) {
const metadataEntry = metadataToUpdate.find(
(el) =>
el !== null &&
el.after[this.definition.keyField] ===
metadataMap[metadataKey][this.definition.keyField]
);
if (!metadataEntry) {
Util.logger.error(
` - ${this.definition.type} ${metadataKey} / ${metadataMap[metadataKey][this.definition.keyField]} not found in update list`
);
continue;
}
// handle updates sequentially here becasue we might have interdepencies
// this is especially important when we use features like --matchName which are updates but change the key
const result = await this.update(
metadataEntry.after,
metadataEntry.before
);
if (result) {
updateResults.push(result);
// make this newly created item available in cache for other itmes that might reference it
const newObject = {};
newObject[metadataKey] = structuredClone(metadataMap[metadataKey]);
if (result.objectID) {
// required for assets
newObject[metadataKey].objectID = result.objectID;
}
cache.mergeMetadata(this.definition.type, newObject);
}
}
}
} else {
filteredByPreDeploy++;
}
} catch (ex) {
if (
metadataMap[metadataKey] &&
metadataMap[metadataKey][this.definition.nameField]
) {
Util.logger.error(
` ☇ skipping ${this.definition.type} ${metadataKey} / ${metadataMap[metadataKey][this.definition.nameField]}: ${ex.message}`
);
} else {
Util.logger.errorStack(ex, `Upserting ${this.definition.type} failed`);
}
}
}
if (!runUpsertSequentially) {
// create
const createLimit = pLimit(10);
createResults = (
await Promise.all(
metadataToCreate
.filter((r) => r !== undefined && r !== null)
.map((metadataEntry) =>
createLimit(() => this.create(metadataEntry, deployDir))
)
)
).filter((r) => r !== undefined && r !== null);
// update
if (Util.OPTIONS.noUpdate && metadataToUpdate.length) {
Util.logger.info(
` ☇ skipping update of ${metadataToUpdate.length} ${this.definition.type}${metadataToUpdate.length == 1 ? '' : 's'}: --noUpdate flag is set`
);
} else if (metadataToUpdate.length) {
const updateLimit = pLimit(10);
updateResults = (
await Promise.all(
metadataToUpdate
.filter((r) => r !== undefined && r !== null)
.map((metadataEntry) =>
updateLimit(() =>
this.update(metadataEntry.after, metadataEntry.before)
)
)
)
).filter((r) => r !== undefined && r !== null);
}
}
// Logging
Util.logger.info(
`${this.definition.type} upsert: ${createResults.length} of ${metadataToCreate.length} created / ${updateResults.length} of ${metadataToUpdate.length} updated` +
(filteredByPreDeploy > 0 ? ` / ${filteredByPreDeploy} filtered` : '')
);
let upsertResults;
if (this.definition.bodyIteratorField === 'Results') {
// if Results then parse as SOAP
// put in Retrieve Format for parsing
// todo add handling when response does not contain items.
const metadataResults = createResults
.concat(updateResults)
// TODO remove Object.keys check after create/update SOAP methods stop returning empty objects instead of null
.filter((r) => r !== undefined && r !== null && Object.keys(r).length !== 0)
.flatMap((r) => r.Results)
.map((r) => r.Object);
upsertResults = this.parseResponseBody({ Results: metadataResults });
} else {
// likely comming from one of the many REST APIs
// put in Retrieve Format for parsing
// todo add handling when response does not contain items.
const metadataResults = createResults.concat(updateResults).filter(Boolean);
upsertResults = this.parseResponseBody(metadataResults);
}
await this.postDeployTasks(upsertResults, orignalMetadataMap, {
created: createResults.length,
updated: updateResults.length,
});
return upsertResults;
}
/**
* helper for {@link MetadataType.upsert}
*
* @param {MetadataTypeMap} metadataMap list of metadata
* @param {string} metadataKey key of item we are looking at
* @param {boolean} hasError error flag from previous code
* @param {MetadataTypeItemDiff[]} metadataToUpdate list of items to update
* @param {MetadataTypeItem[]} metadataToCreate list of items to create
* @returns {Promise.<'create' | 'update' | 'skip'>} action to take
*/
static async createOrUpdate(
metadataMap,
metadataKey,
hasError,
metadataToUpdate,
metadataToCreate
) {
let normalizedKey = File.reverseFilterIllegalFilenames(
metadataMap[metadataKey][this.definition.keyField]
);
// Update if it already exists; Create it if not
const maxKeyLength = this.definition.maxKeyLength || 36;
// make sure keySuffix always has a string value
Util.OPTIONS.keySuffix = Util.OPTIONS.keySuffix ? Util.OPTIONS.keySuffix.trim() : '';
if (Util.OPTIONS.keySuffix && !cache.getByKey(this.definition.type, normalizedKey)) {
// to ensure we go into update mode like we would with appending the MID to asset-keys, recreated the normalized key here
const newKey = this.getNewKey(
this.definition.keyField,
metadataMap[metadataKey],
maxKeyLength
);
normalizedKey = File.reverseFilterIllegalFilenames(newKey);
}
const cacheMatchedByKey = cache.getByKey(this.definition.type, normalizedKey);
const cacheMatchedByName = cacheMatchedByKey
? null
: this.getCacheMatchedByName(metadataMap[metadataKey]);
if (
Util.logger.level === 'debug' &&
metadataMap[metadataKey][this.definition.idField] &&
this.definition.idField !== this.definition.keyField
) {
// TODO: re-evaluate in future releases if & when we managed to solve folder dependencies once and for all
// only used if resource is excluded from cache and we still want to update it
// needed e.g. to rewire lost folders
Util.logger.warn(
' - Hotfix for non-cachable resource found in deploy folder. Trying update:'
);
Util.logger.warn(JSON.stringify(metadataMap[metadataKey]));
if (hasError) {
metadataToUpdate.push(null);
return 'skip';
} else {
metadataToUpdate.push({
before: {},
after: metadataMap[metadataKey],
});
return 'update';
}
} else if (cacheMatchedByKey || cacheMatchedByName) {
// normal way of processing update files
const cachedVersion = cacheMatchedByKey || cacheMatchedByName;
if (!cacheMatchedByKey && cacheMatchedByName) {
Util.matchedByName[this.definition.type] ||= {};
Util.matchedByName[this.definition.type][metadataKey] =
cacheMatchedByName[this.definition.keyField];
}
if (!this.hasChanged(cachedVersion, metadataMap[metadataKey])) {
hasError = true;
}
if (Util.OPTIONS.changeKeyField) {
if (this.definition.keyField == this.definition.idField) {
Util.logger.error(
` - --changeKeyField cannot be used for types that use their ID as key. Skipping change.`
);
hasError = true;
} else if (this.definition.keyIsFixed) {
Util.logger.error(
` - type ${this.definition.type} does not support --changeKeyField and --changeKeyValue. Skipping change.`