-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathentries.ts
More file actions
1000 lines (910 loc) · 39 KB
/
entries.ts
File metadata and controls
1000 lines (910 loc) · 39 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
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
import map from 'lodash/map';
import find from 'lodash/find';
import values from 'lodash/values';
import isEmpty from 'lodash/isEmpty';
import { join, resolve } from 'path';
import { ux, FsUtility } from '@contentstack/cli-utilities';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import auditConfig from '../config';
import ContentType from './content-types';
import { $t, auditMsg, commonMsg } from '../messages';
import {
LogFn,
Locale,
ConfigType,
EntryStruct,
EntryFieldType,
ModularBlockType,
ContentTypeStruct,
CtConstructorParam,
GroupFieldDataType,
GlobalFieldDataType,
JsonRTEFieldDataType,
ContentTypeSchemaType,
EntryModularBlockType,
ModularBlocksDataType,
ModuleConstructorParam,
ReferenceFieldDataType,
EntryRefErrorReturnType,
EntryGroupFieldDataType,
EntryGlobalFieldDataType,
EntryJsonRTEFieldDataType,
EntryModularBlocksDataType,
EntryReferenceFieldDataType,
ExtensionOrAppFieldDataType,
EntryExtensionOrAppFieldDataType,
} from '../types';
import { print } from '../util';
import GlobalField from './global-fields';
import { MarketplaceAppsInstallationData } from '../types/extension';
export default class Entries {
public log: LogFn;
protected fix: boolean;
public fileName: string;
public locales!: Locale[];
public config: ConfigType;
public folderPath: string;
public currentUid!: string;
public currentTitle!: string;
public extensions: string[] = [];
public gfSchema: ContentTypeStruct[];
public ctSchema: ContentTypeStruct[];
protected entries!: Record<string, EntryStruct>;
protected missingRefs: Record<string, any> = {};
public entryMetaData: Record<string, any>[] = [];
public moduleName: keyof typeof auditConfig.moduleConfig = 'entries';
public isEntryWithoutTitleField: boolean = false;
constructor({ log, fix, config, moduleName, ctSchema, gfSchema }: ModuleConstructorParam & CtConstructorParam) {
this.log = log;
this.config = config;
this.fix = fix ?? false;
this.ctSchema = ctSchema;
this.gfSchema = gfSchema;
this.moduleName = moduleName ?? 'entries';
this.fileName = config.moduleConfig[this.moduleName].fileName;
this.folderPath = resolve(config.basePath, config.moduleConfig.entries.dirName);
}
/**
* The `run` function checks if a folder path exists, sets the schema based on the module name,
* iterates over the schema and looks for references, and returns a list of missing references.
* @returns the `missingRefs` object.
*/
async run() {
if (!existsSync(this.folderPath)) {
this.log(`Skipping ${this.moduleName} audit`, 'warn');
this.log($t(auditMsg.NOT_VALID_PATH, { path: this.folderPath }), { color: 'yellow' });
return {};
}
await this.prepareEntryMetaData();
await this.fixPrerequisiteData();
for (const { code } of this.locales) {
for (const ctSchema of this.ctSchema) {
const basePath = join(this.folderPath, ctSchema.uid, code);
const fsUtility = new FsUtility({ basePath, indexFileName: 'index.json', createDirIfNotExist: false });
const indexer = fsUtility.indexFileContent;
for (const fileIndex in indexer) {
const entries = (await fsUtility.readChunkFiles.next()) as Record<string, EntryStruct>;
this.entries = entries;
for (const entryUid in this.entries) {
const entry = this.entries[entryUid];
const { uid, title } = entry;
this.currentUid = uid;
this.currentTitle = title;
if (!this.missingRefs[this.currentUid]) {
this.missingRefs[this.currentUid] = [];
}
if (this.fix) {
this.removeMissingKeysOnEntry(ctSchema.schema as ContentTypeSchemaType[], this.entries[entryUid]);
}
this.lookForReference([{ locale: code, uid, name: title }], ctSchema, this.entries[entryUid]);
const message = $t(auditMsg.SCAN_ENTRY_SUCCESS_MSG, {
title,
local: code,
module: this.config.moduleConfig.entries.name,
});
this.log(message, 'hidden');
print([{ message: `info: ${message}`, color: 'green' }]);
}
if (this.fix) {
await this.writeFixContent(`${basePath}/${indexer[fileIndex]}`, this.entries);
}
}
}
}
// this.log('', 'info'); // Adding empty line
this.removeEmptyVal();
return this.missingRefs;
}
/**
* The function removes any properties from the `missingRefs` object that have an empty array value.
*/
removeEmptyVal() {
for (let propName in this.missingRefs) {
if (!this.missingRefs[propName].length) {
delete this.missingRefs[propName];
}
}
}
/**
* The function `fixPrerequisiteData` fixes the prerequisite data by updating the `ctSchema` and
* `gfSchema` properties using the `ContentType` class.
*/
async fixPrerequisiteData() {
this.ctSchema = (await new ContentType({
fix: true,
log: () => {},
config: this.config,
moduleName: 'content-types',
ctSchema: this.ctSchema,
gfSchema: this.gfSchema,
}).run(true)) as ContentTypeStruct[];
this.gfSchema = (await new GlobalField({
fix: true,
log: () => {},
config: this.config,
moduleName: 'global-fields',
ctSchema: this.ctSchema,
gfSchema: this.gfSchema,
}).run(true)) as ContentTypeStruct[];
const extensionPath = resolve(this.config.basePath, 'extensions', 'extensions.json');
const marketplacePath = resolve(this.config.basePath, 'marketplace_apps', 'marketplace_apps.json');
if (existsSync(extensionPath)) {
try {
this.extensions = Object.keys(JSON.parse(readFileSync(extensionPath, 'utf8')));
} catch (error) {}
}
if (existsSync(marketplacePath)) {
try {
const marketplaceApps: MarketplaceAppsInstallationData[] = JSON.parse(readFileSync(marketplacePath, 'utf8'));
for (const app of marketplaceApps) {
const metaData = map(map(app?.ui_location?.locations, 'meta').flat(), 'extension_uid').filter(
(val) => val,
) as string[];
this.extensions.push(...metaData);
}
} catch (error) {}
}
}
/**
* The function checks if it can write the fix content to a file and if so, it writes the content as
* JSON to the specified file path.
*/
async writeFixContent(filePath: string, schema: Record<string, EntryStruct>) {
let canWrite = true;
if (this.fix) {
if (!this.config.flags['copy-dir'] && !this.config.flags['external-config']?.skipConfirm) {
canWrite = this.config.flags.yes || (await ux.confirm(commonMsg.FIX_CONFIRMATION));
}
if (canWrite) {
writeFileSync(filePath, JSON.stringify(schema));
}
}
}
/**
* The function `lookForReference` iterates over a given schema and validates different field types
* such as reference, global field, JSON, modular blocks, and group fields.
* @param {Record<string, unknown>[]} tree - An array of objects representing the tree structure of
* the content type or field being validated. Each object in the array has the following properties:
* @param {ContentTypeStruct | GlobalFieldDataType | ModularBlockType | GroupFieldDataType} - -
* `tree`: An array of objects representing the tree structure of the content type or field being
* validated.
* @param {EntryStruct | EntryGlobalFieldDataType | EntryModularBlocksDataType |
* EntryGroupFieldDataType} entry - The `entry` parameter is an object that represents the data of an
* entry. It can have different types depending on the `schema` parameter.
*/
lookForReference(
tree: Record<string, unknown>[],
field: ContentTypeStruct | GlobalFieldDataType | ModularBlockType | GroupFieldDataType,
entry: EntryFieldType,
) {
if (this.fix) {
entry = this.runFixOnSchema(tree, field.schema as ContentTypeSchemaType[], entry);
}
for (const child of field.schema ?? []) {
const { uid } = child;
if (!entry?.[uid]) continue;
switch (child.data_type) {
case 'reference':
this.missingRefs[this.currentUid].push(
...this.validateReferenceField(
[...tree, { uid: child.uid, name: child.display_name, field: uid }],
child as ReferenceFieldDataType,
entry[uid] as EntryReferenceFieldDataType[],
),
);
break;
case 'global_field':
this.validateGlobalField(
[...tree, { uid: child.uid, name: child.display_name, field: uid }],
child as GlobalFieldDataType,
entry[uid] as EntryGlobalFieldDataType,
);
break;
case 'json':
if ('extension' in child.field_metadata && child.field_metadata.extension) {
this.missingRefs[this.currentUid].push(
...this.validateExtensionAndAppField(
[...tree, { uid: child.uid, name: child.display_name, field: uid }],
child as ExtensionOrAppFieldDataType,
entry as EntryExtensionOrAppFieldDataType,
),
);
// NOTE Custom field type
} else if ('allow_json_rte' in child.field_metadata && child.field_metadata.allow_json_rte) {
// NOTE JSON RTE field type
this.validateJsonRTEFields(
[...tree, { uid: child.uid, name: child.display_name, field: uid }],
child as JsonRTEFieldDataType,
entry[uid] as EntryJsonRTEFieldDataType,
);
}
break;
case 'blocks':
this.validateModularBlocksField(
[...tree, { uid: child.uid, name: child.display_name, field: uid }],
child as ModularBlocksDataType,
entry[uid] as EntryModularBlocksDataType[],
);
break;
case 'group':
this.validateGroupField(
[...tree, { uid: field.uid, name: child.display_name, field: uid }],
child as GroupFieldDataType,
entry[uid] as EntryGroupFieldDataType[],
);
break;
}
}
}
/**
* The function `validateReferenceField` validates the reference values of a given field in a tree
* structure.
* @param {Record<string, unknown>[]} tree - An array of objects representing a tree structure. Each
* object in the array should have a unique identifier field.
* @param {ReferenceFieldDataType} fieldStructure - The `fieldStructure` parameter is of type
* `ReferenceFieldDataType`. It represents the structure of the reference field that needs to be
* validated.
* @param {EntryReferenceFieldDataType[]} field - The `field` parameter is an array of
* `EntryReferenceFieldDataType` objects.
* @returns the result of calling the `validateReferenceValues` function with the provided arguments
* `tree`, `fieldStructure`, and `field`.
*/
validateReferenceField(
tree: Record<string, unknown>[],
fieldStructure: ReferenceFieldDataType,
field: EntryReferenceFieldDataType[],
) {
if (typeof field === 'string') {
let stringReference = field as string;
stringReference = stringReference.replace(/'/g, '"');
field = JSON.parse(stringReference);
}
return this.validateReferenceValues(tree, fieldStructure, field);
}
/**
* The function `validateExtensionAndAppField` checks if a given field has a valid extension
* reference and returns any missing references.
* @param {Record<string, unknown>[]} tree - An array of objects representing a tree structure.
* @param {ExtensionOrAppFieldDataType} fieldStructure - The `fieldStructure` parameter is of type
* `ExtensionOrAppFieldDataType` and represents the structure of a field in an extension or app. It
* contains properties such as `uid`, `display_name`, and `data_type`.
* @param {EntryExtensionOrAppFieldDataType} field - The `field` parameter is of type
* `EntryExtensionOrAppFieldDataType`, which is an object containing information about a specific
* field in an entry. It has the following properties:
* @returns an array containing an object if there are missing references. If there are no missing
* references, an empty array is returned.
*/
validateExtensionAndAppField(
tree: Record<string, unknown>[],
fieldStructure: ExtensionOrAppFieldDataType,
field: EntryExtensionOrAppFieldDataType,
) {
if (this.fix) return [];
const missingRefs = [];
let { uid, display_name, data_type } = fieldStructure || {};
if (field[uid]) {
let { metadata: { extension_uid } = { extension_uid: '' } } = field[uid] || {};
if (extension_uid && !this.extensions.includes(extension_uid)) {
missingRefs.push({ uid, extension_uid, type: 'Extension or Apps' } as any);
}
}
return missingRefs.length
? [
{
tree,
data_type,
missingRefs,
display_name,
ct_uid: this.currentUid,
name: this.currentTitle,
treeStr: tree
.map(({ name }) => name)
.filter((val) => val)
.join(' ➜ '),
},
]
: [];
}
/**
* The function "validateGlobalField" is an asynchronous function that takes in a tree,
* fieldStructure, and field as parameters and looks for references in the tree.
* @param {Record<string, unknown>[]} tree - The `tree` parameter is an array of objects. Each object
* represents a node in a tree structure. The tree structure can be represented as a hierarchical
* structure where each object can have child objects.
* @param {GlobalFieldDataType} fieldStructure - The `fieldStructure` parameter is of type
* `GlobalFieldDataType` and represents the structure of the global field. It defines the expected
* properties and their types for the global field.
* @param {EntryGlobalFieldDataType} field - The `field` parameter is of type
* `EntryGlobalFieldDataType`. It represents a single global field entry.
*/
validateGlobalField(
tree: Record<string, unknown>[],
fieldStructure: GlobalFieldDataType,
field: EntryGlobalFieldDataType,
) {
// NOTE Any GlobalField related logic can be added here
this.lookForReference(tree, fieldStructure, field);
}
/**
* The function `validateJsonRTEFields` is used to validate the JSON RTE fields by checking if the
* referenced entries exist and adding missing references to a tree structure.
* @param {Record<string, unknown>[]} tree - An array of objects representing the tree structure of
* the JSON RTE fields.
* @param {JsonRTEFieldDataType} fieldStructure - The `fieldStructure` parameter is of type
* `JsonRTEFieldDataType` and represents the structure of a JSON RTE field. It contains properties
* such as `uid`, `data_type`, and `display_name`.
* @param {EntryJsonRTEFieldDataType} field - The `field` parameter is of type
* `EntryJsonRTEFieldDataType`, which represents a JSON RTE field in an entry. It contains properties
* such as `uid`, `attrs`, and `children`.
*/
validateJsonRTEFields(
tree: Record<string, unknown>[],
fieldStructure: JsonRTEFieldDataType,
field: EntryJsonRTEFieldDataType,
) {
// NOTE Other possible reference logic will be added related to JSON RTE (Ex missing assets, extensions etc.,)
for (const index in field?.children ?? []) {
const child = field.children[index];
const { children } = child;
if (!this.fix) {
this.jsonRefCheck(tree, fieldStructure, child);
}
if (!isEmpty(children)) {
this.validateJsonRTEFields(tree, fieldStructure, field.children[index]);
}
}
}
/**
* The function validates the modular blocks field by traversing each module and looking for
* references.
* @param {Record<string, unknown>[]} tree - The `tree` parameter is an array of objects that
* represent the structure of the modular blocks field. Each object in the array represents a level
* in the tree structure, and it contains a `field` property that represents the unique identifier of
* the modular block at that level.
* @param {ModularBlocksDataType} fieldStructure - The `fieldStructure` parameter is of type
* `ModularBlocksDataType` and represents the structure of the modular blocks field. It contains
* information about the blocks and their properties.
* @param {EntryModularBlocksDataType[]} field - The `field` parameter is an array of objects of type
* `EntryModularBlocksDataType`.
*/
validateModularBlocksField(
tree: Record<string, unknown>[],
fieldStructure: ModularBlocksDataType,
field: EntryModularBlocksDataType[],
) {
if (!this.fix) {
for (const index in field) {
this.modularBlockRefCheck(tree, fieldStructure.blocks, field[index], +index);
}
}
for (const block of fieldStructure.blocks) {
const { uid, title } = block;
for (const eBlock of field) {
if (eBlock[uid]) {
this.lookForReference([...tree, { uid, name: title }], block, eBlock[uid] as EntryModularBlocksDataType);
}
}
}
}
/**
* The function validates a group field by looking for a reference in a tree structure.
* @param {Record<string, unknown>[]} tree - An array of objects representing the tree structure.
* @param {GroupFieldDataType} fieldStructure - The `fieldStructure` parameter is of type
* `GroupFieldDataType` and represents the structure of the group field. It contains information
* about the fields and their types within the group.
* @param {EntryGroupFieldDataType} field - The `field` parameter is of type
* `EntryGroupFieldDataType` and represents a single group field entry.
*/
validateGroupField(
tree: Record<string, unknown>[],
fieldStructure: GroupFieldDataType,
field: EntryGroupFieldDataType | EntryGroupFieldDataType[],
) {
// NOTE Any Group Field related logic can be added here (Ex data serialization or picking any metadata for report etc.,)
if (Array.isArray(field)) {
field.forEach((eGroup) => {
this.lookForReference(
[...tree, { uid: fieldStructure.uid, display_name: fieldStructure.display_name }],
fieldStructure,
eGroup,
);
});
} else {
this.lookForReference(tree, fieldStructure, field);
}
}
/**
* The function `validateReferenceValues` checks if the references in a given field exist in the
* provided tree and returns any missing references.
* @param {Record<string, unknown>[]} tree - An array of objects representing the tree structure of
* the data. Each object in the array represents a node in the tree.
* @param {ReferenceFieldDataType} fieldStructure - The `fieldStructure` parameter is of type
* `ReferenceFieldDataType` and represents the structure of a reference field. It contains properties
* such as `data_type` (the data type of the reference field) and `display_name` (the display name of
* the reference field).
* @param {EntryReferenceFieldDataType[]} field - The `field` parameter is an array of objects
* representing entry reference fields. Each object in the array has properties such as `uid` which
* represents the unique identifier of the referenced entry.
* @returns The function `validateReferenceValues` returns an array of `EntryRefErrorReturnType`
* objects.
*/
validateReferenceValues(
tree: Record<string, unknown>[],
fieldStructure: ReferenceFieldDataType,
field: EntryReferenceFieldDataType[],
): EntryRefErrorReturnType[] {
if (this.fix) return [];
const missingRefs: Record<string, any>[] = [];
const { uid: data_type, display_name } = fieldStructure;
for (const index in field ?? []) {
const reference = field[index];
const { uid } = reference;
// NOTE Can skip specific references keys (Ex, system defined keys can be skipped)
// if (this.config.skipRefs.includes(reference)) continue;
const refExist = find(this.entryMetaData, { uid });
if (!refExist) {
missingRefs.push(reference);
}
}
return missingRefs.length
? [
{
tree,
data_type,
missingRefs,
display_name,
uid: this.currentUid,
name: this.currentTitle,
treeStr: tree
.map(({ name }) => name)
.filter((val) => val)
.join(' ➜ '),
},
]
: [];
}
removeMissingKeysOnEntry(schema: ContentTypeSchemaType[], entry: EntryFieldType) {
// NOTE remove invalid entry keys
const ctFields = map(schema, 'uid');
const entryFields = Object.keys(entry ?? {});
entryFields.forEach((eKey) => {
// NOTE Key should not be system key and not exist in schema means it's invalid entry key
if (!this.config.entries.systemKeys.includes(eKey) && !ctFields.includes(eKey)) {
delete entry[eKey];
}
});
}
/**
* The function `runFixOnSchema` takes in a tree, schema, and entry, and applies fixes to the entry
* based on the schema.
* @param {Record<string, unknown>[]} tree - An array of objects representing the tree structure of
* the schema. Each object has the following properties:
* @param {ContentTypeSchemaType[]} schema - The `schema` parameter is an array of objects
* representing the content type schema. Each object in the array contains information about a
* specific field in the schema, such as its unique identifier (`uid`) and data type (`data_type`).
* @param {EntryFieldType} entry - The `entry` parameter is of type `EntryFieldType`, which
* represents the data of an entry. It is an object that contains fields as key-value pairs, where
* the key is the field UID (unique identifier) and the value is the field data.
* @returns the updated `entry` object after applying fixes to the fields based on the provided
* `schema`.
*/
runFixOnSchema(tree: Record<string, unknown>[], schema: ContentTypeSchemaType[], entry: EntryFieldType) {
// NOTE Global field Fix
schema.forEach((field) => {
const { uid, data_type } = field;
if (!Object(entry).hasOwnProperty(uid)) {
return;
}
switch (data_type) {
case 'global_field':
entry[uid] = this.fixGlobalFieldReferences(
[...tree, { uid: field.uid, name: field.display_name, data_type: field.data_type }],
field as GlobalFieldDataType,
entry[uid] as EntryGlobalFieldDataType,
) as EntryGlobalFieldDataType;
break;
case 'json':
case 'reference':
if (data_type === 'json') {
if ('extension' in field.field_metadata && field.field_metadata.extension) {
// NOTE Custom field type
this.fixMissingExtensionOrApp(
[...tree, { uid: field.uid, name: field.display_name, data_type: field.data_type }],
field as ExtensionOrAppFieldDataType,
entry as EntryExtensionOrAppFieldDataType,
);
break;
} else if ('allow_json_rte' in field.field_metadata && field.field_metadata.allow_json_rte) {
this.fixJsonRteMissingReferences(
[...tree, { uid: field.uid, name: field.display_name, data_type: field.data_type }],
field as JsonRTEFieldDataType,
entry[uid] as EntryJsonRTEFieldDataType,
);
break;
}
}
// NOTE Reference field
entry[uid] = this.fixMissingReferences(
[...tree, { uid: field.uid, name: field.display_name, data_type: field.data_type }],
field as ReferenceFieldDataType,
entry[uid] as EntryReferenceFieldDataType[],
);
if (!entry[uid]) {
delete entry[uid];
}
break;
case 'blocks':
entry[uid] = this.fixModularBlocksReferences(
[...tree, { uid: field.uid, name: field.display_name, data_type: field.data_type }],
(field as ModularBlocksDataType).blocks,
entry[uid] as EntryModularBlocksDataType[],
);
break;
case 'group':
entry[uid] = this.fixGroupField(
[...tree, { uid: field.uid, name: field.display_name, data_type: field.data_type }],
field as GroupFieldDataType,
entry[uid] as EntryGroupFieldDataType[],
) as EntryGroupFieldDataType;
break;
}
});
return entry;
}
/**
* The function `fixGlobalFieldReferences` adds a new entry to a tree data structure and runs a fix
* on the schema.
* @param {Record<string, unknown>[]} tree - An array of objects representing the tree structure.
* @param {GlobalFieldDataType} field - The `field` parameter is of type `GlobalFieldDataType` and
* represents a global field object. It contains properties such as `uid` and `display_name`.
* @param {EntryGlobalFieldDataType} entry - The `entry` parameter is of type
* `EntryGlobalFieldDataType` and represents the global field entry that needs to be fixed.
* @returns the result of calling the `runFixOnSchema` method with the updated `tree` array,
* `field.schema`, and `entry` as arguments.
*/
fixGlobalFieldReferences(
tree: Record<string, unknown>[],
field: GlobalFieldDataType,
entry: EntryGlobalFieldDataType,
) {
return this.runFixOnSchema([...tree, { uid: field.uid, display_name: field.display_name }], field.schema, entry);
}
/**
* The function `fixModularBlocksReferences` takes in a tree, a list of blocks, and an entry, and
* performs various operations to fix references within the entry.
* @param {Record<string, unknown>[]} tree - An array of objects representing the tree structure of
* the modular blocks.
* @param {ModularBlockType[]} blocks - An array of objects representing modular blocks. Each object
* has properties like `uid` (unique identifier) and `title` (display name).
* @param {EntryModularBlocksDataType[]} entry - An array of objects representing the modular blocks
* data in an entry. Each object in the array represents a modular block and contains its unique
* identifier (uid) and other properties.
* @returns the updated `entry` array after performing some modifications.
*/
fixModularBlocksReferences(
tree: Record<string, unknown>[],
blocks: ModularBlockType[],
entry: EntryModularBlocksDataType[],
) {
entry = entry
?.map((block, index) => this.modularBlockRefCheck(tree, blocks, block, index))
.filter((val) => !isEmpty(val));
blocks.forEach((block) => {
entry = entry
?.map((eBlock) => {
if (!isEmpty(block.schema)) {
if (eBlock[block.uid]) {
eBlock[block.uid] = this.runFixOnSchema(
[...tree, { uid: block.uid, display_name: block.title }],
block.schema as ContentTypeSchemaType[],
eBlock[block.uid] as EntryFieldType,
) as EntryModularBlockType;
}
}
return eBlock;
})
.filter((val) => !isEmpty(val));
});
return entry;
}
/**
* The function `fixMissingExtensionOrApp` checks if a field in an entry has a valid extension or app
* reference, and fixes it if necessary.
* @param {Record<string, unknown>[]} tree - An array of objects representing a tree structure.
* @param {ExtensionOrAppFieldDataType} field - The `field` parameter is of type
* `ExtensionOrAppFieldDataType`, which is an object with properties `uid`, `display_name`, and
* `data_type`.
* @param {EntryExtensionOrAppFieldDataType} entry - The `entry` parameter is of type
* `EntryExtensionOrAppFieldDataType`, which is an object containing the data for a specific entry.
* It may have a property with the key specified by the `uid` variable, which represents the field
* that contains the extension or app data.
* @returns the `field` parameter.
*/
fixMissingExtensionOrApp(
tree: Record<string, unknown>[],
field: ExtensionOrAppFieldDataType,
entry: EntryExtensionOrAppFieldDataType,
) {
const missingRefs = [];
let { uid, display_name, data_type } = field || {};
if (entry[uid]) {
let { metadata: { extension_uid } = { extension_uid: '' } } = entry[uid] || {};
if (extension_uid && !this.extensions.includes(extension_uid)) {
missingRefs.push({ uid, extension_uid, type: 'Extension or Apps' } as any);
}
}
if (this.fix && !isEmpty(missingRefs)) {
this.missingRefs[this.currentUid].push({
tree,
data_type,
missingRefs,
display_name,
fixStatus: 'Fixed',
ct_uid: this.currentUid,
name: this.currentTitle,
treeStr: tree.map(({ name }) => name).join(' ➜ '),
});
delete entry[uid];
}
return field;
}
/**
* The function `fixGroupField` takes in a tree, a field, and an entry, and if the field has a
* schema, it runs a fix on the schema and returns the updated entry, otherwise it returns the
* original entry.
* @param {Record<string, unknown>[]} tree - An array of objects representing the tree structure.
* @param {GroupFieldDataType} field - The `field` parameter is of type `GroupFieldDataType` and
* represents a group field object. It contains properties such as `uid` (unique identifier) and
* `display_name` (name of the field).
* @param {EntryGroupFieldDataType} entry - The `entry` parameter is of type
* `EntryGroupFieldDataType`.
* @returns If the `field.schema` is not empty, the function will return the result of calling
* `this.runFixOnSchema` with the updated `tree`, `field.schema`, and `entry` as arguments.
* Otherwise, it will return the `entry` as is.
*/
fixGroupField(
tree: Record<string, unknown>[],
field: GroupFieldDataType,
entry: EntryGroupFieldDataType | EntryGroupFieldDataType[],
) {
if (!isEmpty(field.schema)) {
if (Array.isArray(entry)) {
entry = entry.map((eGroup) => {
return this.runFixOnSchema(
[...tree, { uid: field.uid, display_name: field.display_name }],
field.schema as ContentTypeSchemaType[],
eGroup,
);
}) as EntryGroupFieldDataType[];
} else {
entry = this.runFixOnSchema(
[...tree, { uid: field.uid, display_name: field.display_name }],
field.schema as ContentTypeSchemaType[],
entry,
) as EntryGroupFieldDataType;
}
}
return entry;
}
/**
* The function fixes missing references in a JSON tree structure.
* @param {Record<string, unknown>[]} tree - An array of objects representing a tree structure. Each
* object in the array has a string key and an unknown value.
* @param {ReferenceFieldDataType | JsonRTEFieldDataType} field - The `field` parameter can be of
* type `ReferenceFieldDataType` or `JsonRTEFieldDataType`.
* @param {EntryJsonRTEFieldDataType} entry - The `entry` parameter is of type
* `EntryJsonRTEFieldDataType`, which represents an entry in a JSON Rich Text Editor (JsonRTE) field.
* @returns the updated `entry` object with fixed missing references in the `children` property.
*/
fixJsonRteMissingReferences(
tree: Record<string, unknown>[],
field: ReferenceFieldDataType | JsonRTEFieldDataType,
entry: EntryJsonRTEFieldDataType | EntryJsonRTEFieldDataType[],
) {
if (Array.isArray(entry)) {
entry = entry.map((child: any, index) => {
return this.fixJsonRteMissingReferences([...tree, { index, type: child?.type, uid: child?.uid }], field, child);
}) as EntryJsonRTEFieldDataType[];
} else {
if (entry?.children) {
entry.children = entry.children
.map((child) => {
const refExist = this.jsonRefCheck(tree, field, child);
if (!refExist) return null;
if (!isEmpty(child.children)) {
child = this.fixJsonRteMissingReferences(tree, field, child) as EntryJsonRTEFieldDataType;
}
return child;
})
.filter((val) => val) as EntryJsonRTEFieldDataType[];
}
}
return entry;
}
/**
* The `fixMissingReferences` function checks for missing references in an entry and adds them to a
* list if they are not found.
* @param {Record<string, unknown>[]} tree - An array of objects representing a tree structure. Each
* object in the array should have a "name" property and an optional "index" property.
* @param {ReferenceFieldDataType | JsonRTEFieldDataType} field - The `field` parameter is of type
* `ReferenceFieldDataType` or `JsonRTEFieldDataType`.
* @param {EntryReferenceFieldDataType[]} entry - The `entry` parameter is an array of objects that
* represent references to other entries. Each object in the array has the following properties:
* @returns the `entry` variable.
*/
fixMissingReferences(
tree: Record<string, unknown>[],
field: ReferenceFieldDataType | JsonRTEFieldDataType,
entry: EntryReferenceFieldDataType[],
) {
const missingRefs: Record<string, any>[] = [];
if (typeof entry === 'string') {
let stringReference = entry as string;
stringReference = stringReference.replace(/'/g, '"');
entry = JSON.parse(stringReference);
}
entry = entry
?.map((reference) => {
const { uid } = reference;
const refExist = find(this.entryMetaData, { uid });
if (!refExist) {
missingRefs.push(reference);
return null;
}
return reference;
})
.filter((val) => val) as EntryReferenceFieldDataType[];
if (!isEmpty(missingRefs)) {
this.missingRefs[this.currentUid].push({
tree,
fixStatus: 'Fixed',
uid: this.currentUid,
name: this.currentTitle,
data_type: field.data_type,
display_name: field.display_name,
treeStr: tree
.map(({ name, index }) => (index || index === 0 ? `[${+index}].${name}` : name))
.filter((val) => val)
.join(' ➜ '),
missingRefs,
});
}
return entry;
}
/**
* The function `modularBlockRefCheck` checks for invalid keys in an entry block and returns the
* updated entry block.
* @param {Record<string, unknown>[]} tree - An array of objects representing the tree structure of
* the blocks.
* @param {ModularBlockType[]} blocks - The `blocks` parameter is an array of `ModularBlockType`
* objects.
* @param {EntryModularBlocksDataType} entryBlock - The `entryBlock` parameter is an object that
* represents a modular block entry. It contains key-value pairs where the keys are the UIDs of the
* modular blocks and the values are the data associated with each modular block.
* @param {Number} index - The `index` parameter is a number that represents the index of the current
* block in the `tree` array.
* @returns the `entryBlock` object.
*/
modularBlockRefCheck(
tree: Record<string, unknown>[],
blocks: ModularBlockType[],
entryBlock: EntryModularBlocksDataType,
index: number,
) {
const validBlockUid = blocks.map((block) => block.uid);
const invalidKeys = Object.keys(entryBlock).filter((key) => !validBlockUid.includes(key));
invalidKeys.forEach((key) => {
if (this.fix) {
delete entryBlock[key];
}
this.missingRefs[this.currentUid].push({
uid: this.currentUid,
name: this.currentTitle,
data_type: key,
display_name: key,
fixStatus: this.fix ? 'Fixed' : undefined,
tree: [...tree, { index, uid: key, name: key }],
treeStr: [...tree, { index, uid: key, name: key }]
.map(({ name, index }) => (index || index === 0 ? `[${+index}].${name}` : name))
.filter((val) => val)
.join(' ➜ '),
missingRefs: [key],
});
});
return entryBlock;
}
/**
* The `jsonRefCheck` function checks if a reference exists in a JSON tree and adds missing
* references to a list if they are not found.
* @param {Record<string, unknown>[]} tree - An array of objects representing the tree structure.
* @param {JsonRTEFieldDataType} schema - The `schema` parameter is of type `JsonRTEFieldDataType`
* and represents the schema of a JSON field. It contains properties such as `uid`, `data_type`, and
* `display_name`.
* @param {EntryJsonRTEFieldDataType} child - The `child` parameter is an object that represents a
* child entry in a JSON tree. It has the following properties:
* @returns The function `jsonRefCheck` returns either `null` or `true`.
*/
jsonRefCheck(tree: Record<string, unknown>[], schema: JsonRTEFieldDataType, child: EntryJsonRTEFieldDataType) {
const { uid: childrenUid } = child;
const { 'entry-uid': entryUid, 'content-type-uid': contentTypeUid } = child.attrs || {};
if (entryUid) {
const refExist = find(this.entryMetaData, { uid: entryUid });
if (!refExist) {
tree.push({ field: 'children' }, { field: childrenUid, uid: schema.uid });
this.missingRefs[this.currentUid].push({
tree,
uid: this.currentUid,
name: this.currentTitle,
data_type: schema.data_type,
display_name: schema.display_name,
fixStatus: this.fix ? 'Fixed' : undefined,
treeStr: tree
.map(({ name }) => name)
.filter((val) => val)
.join(' ➜ '),
missingRefs: [{ uid: entryUid, 'content-type-uid': contentTypeUid }],
});
return null;
}
}
return true;
}
/**
* The function prepares entry metadata by reading and processing files from different locales and
* schemas.
*/
async prepareEntryMetaData() {
this.log(auditMsg.PREPARING_ENTRY_METADATA, 'info');
const localesFolderPath = resolve(this.config.basePath, this.config.moduleConfig.locales.dirName);
const localesPath = join(localesFolderPath, this.config.moduleConfig.locales.fileName);
const masterLocalesPath = join(localesFolderPath, 'master-locale.json');
this.locales = existsSync(masterLocalesPath) ? values(JSON.parse(readFileSync(masterLocalesPath, 'utf8'))) : [];
if (existsSync(localesPath)) {
this.locales.push(...values(JSON.parse(readFileSync(localesPath, 'utf8'))));
}
for (const { code } of this.locales) {
for (const { uid } of this.ctSchema) {
let basePath = join(this.folderPath, uid, code);
let fsUtility = new FsUtility({ basePath, indexFileName: 'index.json' });
let indexer = fsUtility.indexFileContent;
for (const _ in indexer) {
const entries = (await fsUtility.readChunkFiles.next()) as Record<string, EntryStruct>;
for (const entryUid in entries) {
let { title } = entries[entryUid];
if (!title) {
this.isEntryWithoutTitleField = true;
this.log(
`Entry with UID '${entryUid}' of Content Type '${uid}' in Locale '${code}' does not have a 'title' field.`,
`error`,
);
}
this.entryMetaData.push({ uid: entryUid, title });
}
}
}
}
if (this.isEntryWithoutTitleField) {
throw Error(`Entries found with missing 'title' field! Please make the data corrections and re-run the audit.`);
}
}
}