-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfield_rules.ts
More file actions
690 lines (595 loc) · 28.8 KB
/
field_rules.ts
File metadata and controls
690 lines (595 loc) · 28.8 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
import map from 'lodash/map';
import { join, resolve } from 'path';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { FsUtility, Locale, sanitizePath, cliux, log } from '@contentstack/cli-utilities';
import {
ModularBlockType,
ContentTypeStruct,
GroupFieldDataType,
CtConstructorParam,
GlobalFieldDataType,
ModularBlocksDataType,
ModuleConstructorParam,
EntryStruct,
FieldRuleStruct,
} from '../types';
import auditConfig from '../config';
import { $t, auditFixMsg, auditMsg, commonMsg } from '../messages';
import { MarketplaceAppsInstallationData } from '../types/extension';
import { values } from 'lodash';
import BaseClass from './base-class';
/* The `FieldRule` class is responsible for scanning field rules, looking for references, and
generating a report in JSON and CSV formats. */
export default class FieldRule extends BaseClass {
protected fix: boolean;
public fileName: string;
public folderPath: string;
public currentUid!: string;
public currentTitle!: string;
public extensions: string[] = [];
public inMemoryFix: boolean = false;
public gfSchema: ContentTypeStruct[];
public ctSchema: ContentTypeStruct[];
protected schema: ContentTypeStruct[] = [];
protected missingRefs: Record<string, any> = {};
public moduleName: keyof typeof auditConfig.moduleConfig;
public schemaMap: any = [];
public locales!: Locale[];
protected entries!: Record<string, EntryStruct>;
protected missingSelectFeild: Record<string, any> = {};
protected missingMandatoryFields: Record<string, any> = {};
protected missingEnvLocale: Record<string, any> = {};
public entryMetaData: Record<string, any>[] = [];
public action: string[] = ['show', 'hide'];
constructor({ fix, config, moduleName, ctSchema, gfSchema }: ModuleConstructorParam & CtConstructorParam) {
super({ config });
this.fix = fix ?? false;
this.ctSchema = ctSchema;
this.gfSchema = gfSchema;
log.debug(`Initializing FieldRule module`, this.config.auditContext);
log.debug(`Fix mode: ${this.fix}`, this.config.auditContext);
log.debug(`Content types count: ${ctSchema?.length || 0}`, this.config.auditContext);
log.debug(`Global fields count: ${gfSchema?.length || 0}`, this.config.auditContext);
log.debug(`Module name: ${moduleName}`, this.config.auditContext);
this.moduleName = this.validateModules(moduleName!, this.config.moduleConfig);
this.fileName = config.moduleConfig[this.moduleName].fileName;
log.debug(`File name: ${this.fileName}`, this.config.auditContext);
this.folderPath = resolve(
sanitizePath(config.basePath),
sanitizePath(config.moduleConfig[this.moduleName].dirName),
);
log.debug(`Folder path: ${this.folderPath}`, this.config.auditContext);
log.debug(`FieldRule module initialization completed`, this.config.auditContext);
}
validateModules(
moduleName: keyof typeof auditConfig.moduleConfig,
moduleConfig: Record<string, unknown>,
): keyof typeof auditConfig.moduleConfig {
log.debug(`Validating module: ${moduleName}`, this.config.auditContext);
log.debug(`Available modules: ${Object.keys(moduleConfig).join(', ')}`, this.config.auditContext);
if (Object.keys(moduleConfig).includes(moduleName)) {
log.debug(`Module ${moduleName} is valid`, this.config.auditContext);
return moduleName;
}
log.debug(`Module ${moduleName} not found, defaulting to 'content-types'`, this.config.auditContext);
return 'content-types';
}
/**
* 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(totalCount?: number) {
try {
log.debug(`Starting ${this.moduleName} field rules audit process`, this.config.auditContext);
log.debug(`Field rules folder path: ${this.folderPath}`, this.config.auditContext);
log.debug(`Fix mode: ${this.fix}`, this.config.auditContext);
if (!existsSync(this.folderPath)) {
log.debug(`Skipping ${this.moduleName} audit - path does not exist`, this.config.auditContext);
log.warn(`Skipping ${this.moduleName} audit`, this.config.auditContext);
cliux.print($t(auditMsg.NOT_VALID_PATH, { path: this.folderPath }), { color: 'yellow' });
return {};
}
this.schema = this.moduleName === 'content-types' ? this.ctSchema : this.gfSchema;
log.debug(`Using ${this.moduleName} schema with ${this.schema?.length || 0} items`, this.config.auditContext);
// Load prerequisite data with loading spinner
await this.withLoadingSpinner('FIELD-RULES: Loading prerequisite data...', async () => {
await this.prerequisiteData();
});
log.debug(`Loaded ${this.extensions.length} extensions`, this.config.auditContext);
// Prepare entry metadata with loading spinner
await this.withLoadingSpinner('FIELD-RULES: Preparing entry metadata...', async () => {
await this.prepareEntryMetaData();
});
log.debug(`Prepared metadata for ${this.entryMetaData.length} entries`, this.config.auditContext);
// Create progress manager if we have a total count
if (totalCount && totalCount > 0) {
const progress = this.createSimpleProgress('field-rules', totalCount);
progress.updateStatus('Validating field rules...');
}
log.debug(`Processing ${this.schema?.length || 0} schemas for field rules`, this.config.auditContext);
for (const schema of this.schema ?? []) {
this.currentUid = schema.uid;
this.currentTitle = schema.title;
this.missingRefs[this.currentUid] = [];
const { uid, title } = schema;
log.debug(`Processing schema: ${title} (${uid})`, this.config.auditContext);
log.debug(
`Field rules count: ${Array.isArray(schema.field_rules) ? schema.field_rules.length : 0}`,
this.config.auditContext,
);
log.debug(`Looking for references in schema: ${title}`, this.config.auditContext);
await this.lookForReference([{ uid, name: title }], schema, null);
log.debug(`Schema map contains ${this.schemaMap.length} field references`, this.config.auditContext);
this.missingRefs[this.currentUid] = [];
if (this.fix) {
log.debug(`Fixing field rules for schema: ${title}`, this.config.auditContext);
this.fixFieldRules(schema);
} else {
log.debug(`Validating field rules for schema: ${title}`, this.config.auditContext);
this.validateFieldRules(schema);
}
this.schemaMap = [];
log.info(
$t(auditMsg.SCAN_CT_SUCCESS_MSG, { title, module: this.config.moduleConfig[this.moduleName].name }),
this.config.auditContext,
);
if (this.progressManager) {
this.progressManager.tick(true, `field-rules: ${title}`, null);
}
}
if (this.fix) {
log.debug(`Fix mode enabled, writing fix content`, this.config.auditContext);
await this.writeFixContent();
}
log.debug(`Cleaning up empty missing references`, this.config.auditContext);
for (let propName in this.missingRefs) {
if (!this.missingRefs[propName].length) {
log.debug(`Removing empty missing references for: ${propName}`, this.config.auditContext);
delete this.missingRefs[propName];
}
}
log.debug(
`Field rules audit completed. Found ${Object.keys(this.missingRefs).length} schemas with issues`,
this.config.auditContext,
);
this.completeProgress(true);
return this.missingRefs;
} catch (error: any) {
this.completeProgress(false, error?.message || 'Field rules audit failed');
throw error;
}
}
validateFieldRules(schema: Record<string, unknown>): void {
log.debug(`Validating field rules for schema: ${schema.uid}`, this.config.auditContext);
if (Array.isArray(schema.field_rules)) {
log.debug(`Found ${schema.field_rules.length} field rules to validate`, this.config.auditContext);
let count = 0;
schema.field_rules.forEach((fr, index) => {
log.debug(`Validating field rule ${index + 1}`, this.config.auditContext);
log.debug(`Field rule actions count: ${fr.actions?.length || 0}`, this.config.auditContext);
log.debug(`Field rule conditions count: ${fr.conditions?.length || 0}`, this.config.auditContext);
fr.actions.forEach((actions: { target_field: any }, actionIndex: number) => {
log.debug(
`Validating action ${actionIndex + 1}: target_field=${actions.target_field}`,
this.config.auditContext,
);
if (!this.schemaMap.includes(actions.target_field)) {
log.debug(`Missing target field: ${actions.target_field}`, this.config.auditContext);
log.error(
$t(auditMsg.FIELD_RULE_TARGET_ABSENT, {
target_field: actions.target_field,
ctUid: schema.uid as string,
}),
this.config.auditContext,
);
this.addMissingReferences(actions);
} else {
log.debug(`Target field ${actions.target_field} is valid`, this.config.auditContext);
}
log.info(
$t(auditMsg.FIELD_RULE_TARGET_SCAN_MESSAGE, { num: count.toString(), ctUid: schema.uid as string }),
this.config.auditContext,
);
});
fr.conditions.forEach((actions: { operand_field: any }, conditionIndex: number) => {
log.debug(
`Validating condition ${conditionIndex + 1}: operand_field=${actions.operand_field}`,
this.config.auditContext,
);
if (!this.schemaMap.includes(actions.operand_field)) {
log.debug(`Missing operand field: ${actions.operand_field}`, this.config.auditContext);
this.addMissingReferences(actions);
log.error(
$t(auditMsg.FIELD_RULE_CONDITION_ABSENT, { condition_field: actions.operand_field }),
this.config.auditContext,
);
} else {
log.debug(`Operand field ${actions.operand_field} is valid`, this.config.auditContext);
}
log.info(
$t(auditMsg.FIELD_RULE_CONDITION_SCAN_MESSAGE, { num: count.toString(), ctUid: schema.uid as string }),
this.config.auditContext,
);
});
count = count + 1;
});
} else {
log.debug(`No field rules found in schema: ${schema.uid}`, this.config.auditContext);
}
log.debug(`Field rules validation completed for schema: ${schema.uid}`, this.config.auditContext);
}
fixFieldRules(schema: Record<string, unknown>): void {
log.debug(`Fixing field rules for schema: ${schema.uid}`, this.config.auditContext);
if (!Array.isArray(schema.field_rules)) {
log.debug(`No field rules found in schema: ${schema.uid}`, this.config.auditContext);
return;
}
log.debug(`Found ${schema.field_rules.length} field rules to fix`, this.config.auditContext);
schema.field_rules = schema.field_rules
.map((fr: FieldRuleStruct, index: number) => {
log.debug(`Fixing field rule ${index + 1}`, this.config.auditContext);
log.debug(`Original actions count: ${fr.actions?.length || 0}`, this.config.auditContext);
log.debug(`Original conditions count: ${fr.conditions?.length || 0}`, this.config.auditContext);
const validActions =
fr.actions?.filter((action) => {
const isValid = this.schemaMap.includes(action.target_field);
log.debug(`Action target_field=${action.target_field}, valid=${isValid}`, this.config.auditContext);
const logMsg = isValid ? auditMsg.FIELD_RULE_TARGET_SCAN_MESSAGE : auditMsg.FIELD_RULE_TARGET_ABSENT;
if (isValid) {
log.info(
$t(logMsg, {
num: index.toString(),
ctUid: schema.uid as string,
...(action.target_field && { target_field: action.target_field }),
}),
this.config.auditContext,
);
} else {
log.error(
$t(logMsg, {
num: index.toString(),
ctUid: schema.uid as string,
...(action.target_field && { target_field: action.target_field }),
}),
this.config.auditContext,
);
}
if (!isValid) {
log.debug(`Fixing invalid action target_field: ${action.target_field}`, this.config.auditContext);
this.addMissingReferences(action, 'Fixed');
log.info(
$t(auditFixMsg.FIELD_RULE_FIX_MESSAGE, {
num: index.toString(),
ctUid: schema.uid as string,
}),
this.config.auditContext,
);
}
return isValid;
}) ?? [];
log.debug(`Valid actions after filtering: ${validActions.length}`, this.config.auditContext);
const validConditions =
fr.conditions?.filter((condition) => {
const isValid = this.schemaMap.includes(condition.operand_field);
log.debug(`Condition operand_field=${condition.operand_field}, valid=${isValid}`, this.config.auditContext);
const logMsg = isValid ? auditMsg.FIELD_RULE_CONDITION_SCAN_MESSAGE : auditMsg.FIELD_RULE_CONDITION_ABSENT;
if (isValid) {
log.info(
$t(logMsg, {
num: index.toString(),
ctUid: schema.uid as string,
...(condition.operand_field && { condition_field: condition.operand_field }),
}),
this.config.auditContext,
);
} else {
log.error(
$t(logMsg, {
num: index.toString(),
ctUid: schema.uid as string,
...(condition.operand_field && { condition_field: condition.operand_field }),
}),
this.config.auditContext,
);
}
if (!isValid) {
log.debug(`Fixing invalid condition operand_field: ${condition.operand_field}`, this.config.auditContext);
this.addMissingReferences(condition, 'Fixed');
log.info(
$t(auditFixMsg.FIELD_RULE_FIX_MESSAGE, {
num: index.toString(),
ctUid: schema.uid as string,
}),
this.config.auditContext,
);
}
return isValid;
}) ?? [];
log.debug(`Valid conditions after filtering: ${validConditions.length}`, this.config.auditContext);
const shouldKeepRule = validActions.length && validConditions.length;
log.debug(
`Field rule ${index + 1} ${shouldKeepRule ? 'kept' : 'removed'} (actions: ${validActions.length}, conditions: ${validConditions.length})`,
this.config.auditContext,
);
return shouldKeepRule
? {
...fr,
actions: validActions,
conditions: validConditions,
}
: null;
})
.filter(Boolean);
log.debug(
`Field rules fix completed for schema: ${schema.uid}. ${(schema.field_rules as any[]).length} rules remaining`,
this.config.auditContext,
);
}
addMissingReferences(actions: Record<string, unknown>, fixStatus?: string) {
log.debug(`Adding missing reference for schema: ${this.currentUid}`, this.config.auditContext);
log.debug(`Action data: ${JSON.stringify(actions)}`, this.config.auditContext);
log.debug(`Fix status: ${fixStatus || 'none'}`, this.config.auditContext);
if (fixStatus) {
log.debug(`Recording fixed missing reference`, this.config.auditContext);
this.missingRefs[this.currentUid].push({
ctUid: this.currentUid,
action: actions,
fixStatus: 'Fixed',
});
} else {
log.debug(`Recording missing reference for validation`, this.config.auditContext);
this.missingRefs[this.currentUid].push({ ctUid: this.currentUid, action: actions });
}
log.debug(
`Missing references count for ${this.currentUid}: ${this.missingRefs[this.currentUid].length}`,
this.config.auditContext,
);
}
/**
* @method prerequisiteData
* The `prerequisiteData` function reads and parses JSON files to retrieve extension and marketplace
* app data, and stores them in the `extensions` array.
*/
async prerequisiteData(): Promise<void> {
log.debug(`Loading prerequisite data`, this.config.auditContext);
const extensionPath = resolve(this.config.basePath, 'extensions', 'extensions.json');
const marketplacePath = resolve(this.config.basePath, 'marketplace_apps', 'marketplace_apps.json');
log.debug(`Extensions path: ${extensionPath}`, this.config.auditContext);
log.debug(`Marketplace apps path: ${marketplacePath}`, this.config.auditContext);
if (existsSync(extensionPath)) {
log.debug(`Loading extensions from file`, this.config.auditContext);
try {
this.extensions = Object.keys(JSON.parse(readFileSync(extensionPath, 'utf8')));
log.debug(`Loaded ${this.extensions.length} extensions`, this.config.auditContext);
} catch (error) {
log.debug(`Error loading extensions: ${error}`, this.config.auditContext);
}
} else {
log.debug(`Extensions file not found`, this.config.auditContext);
}
if (existsSync(marketplacePath)) {
log.debug(`Loading marketplace apps from file`, this.config.auditContext);
try {
const marketplaceApps: MarketplaceAppsInstallationData[] = JSON.parse(readFileSync(marketplacePath, 'utf8'));
log.debug(`Found ${marketplaceApps.length} marketplace apps`, this.config.auditContext);
for (const app of marketplaceApps) {
log.debug(`Processing marketplace app: ${app.uid}`, this.config.auditContext);
const metaData = map(map(app?.ui_location?.locations, 'meta').flat(), 'extension_uid').filter(
(val) => val,
) as string[];
log.debug(`Found ${metaData.length} extension UIDs in app`, this.config.auditContext);
this.extensions.push(...metaData);
}
} catch (error) {
log.debug(`Error loading marketplace apps: ${error}`, this.config.auditContext);
}
} else {
log.debug(`Marketplace apps file not found`, this.config.auditContext);
}
log.debug(
`Prerequisite data loading completed. Total extensions: ${this.extensions.length}`,
this.config.auditContext,
);
}
/**
* 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(): Promise<void> {
log.debug(`Writing fix content`, this.config.auditContext);
log.debug(`Fix mode: ${this.fix}`, this.config.auditContext);
log.debug(`Copy directory flag: ${this.config.flags['copy-dir']}`, this.config.auditContext);
log.debug(
`External config skip confirm: ${this.config.flags['external-config']?.skipConfirm}`,
this.config.auditContext,
);
log.debug(`Yes flag: ${this.config.flags.yes}`, this.config.auditContext);
let canWrite = true;
if (this.fix) {
if (!this.config.flags['copy-dir'] && !this.config.flags['external-config']?.skipConfirm) {
log.debug(`Asking user for confirmation to write fix content`, this.config.auditContext);
this.completeProgress(true);
canWrite = this.config.flags.yes ?? (await cliux.confirm(commonMsg.FIX_CONFIRMATION));
log.debug(`User confirmation: ${canWrite}`, this.config.auditContext);
} else {
log.debug(`Skipping confirmation due to flags`, this.config.auditContext);
}
if (canWrite) {
// const outputPath = join(this.folderPath, this.config.moduleConfig[this.moduleName].fileName);
// log.debug(`Writing fixed schema to: ${outputPath}`, this.config.auditContext);
// log.debug(`Schema items to write: ${this.schema?.length || 0}`, this.config.auditContext);
// writeFileSync(outputPath, JSON.stringify(this.schema));
// log.debug(`Successfully wrote fixed schema to file`, this.config.auditContext);
for (const schema of this.schema ?? []) {
if (!schema?.uid) {
log.warn(`Skipping schema with missing uid`, this.config.auditContext);
continue;
}
const filePath = join(this.folderPath, `${schema.uid}.json`);
writeFileSync(filePath, JSON.stringify(schema));
log.debug(`Wrote fixed schema: ${schema.uid} → ${filePath}`, this.config.auditContext);
}
} else {
log.debug(`Skipping file write - user declined confirmation`, this.config.auditContext);
}
} else {
log.debug(`Skipping file write - fix mode disabled`, this.config.auditContext);
}
}
async lookForReference(
tree: Record<string, unknown>[],
field: ContentTypeStruct | GlobalFieldDataType | ModularBlockType | GroupFieldDataType,
parent: string | null = null,
): Promise<void> {
log.debug(
`Looking for references in field: ${(field as any).uid || (field as any).title || 'unknown'}`,
this.config.auditContext,
);
log.debug(`Parent: ${parent || 'none'}`, this.config.auditContext);
log.debug(`Schema fields count: ${field.schema?.length || 0}`, this.config.auditContext);
const fixTypes = this.config.flags['fix-only'] ?? this.config['fix-fields'];
log.debug(`Fix types: ${fixTypes.join(', ')}`, this.config.auditContext);
for (let child of field.schema ?? []) {
const fieldPath = parent !== null ? `${parent}.${child?.uid}` : child.uid;
log.debug(`Processing field: ${child.uid} (${child.data_type}) at path: ${fieldPath}`, this.config.auditContext);
if (parent !== null) {
this.schemaMap.push(`${parent}.${child?.uid}`);
} else {
this.schemaMap.push(child.uid);
}
if (!fixTypes.includes(child.data_type) && child.data_type !== 'json') {
log.debug(
`Skipping field ${child.uid} - data type ${child.data_type} not in fix types`,
this.config.auditContext,
);
continue;
}
log.debug(`Validating field ${child.uid} of type ${child.data_type}`, this.config.auditContext);
switch (child.data_type) {
case 'global_field':
log.debug(`Validating global field: ${child.uid}`, this.config.auditContext);
await this.validateGlobalField(
[...tree, { uid: child.uid, name: child.display_name }],
child as GlobalFieldDataType,
parent ? `${parent}.${child?.uid}` : child?.uid,
);
break;
case 'blocks':
log.debug(`Validating modular blocks field: ${child.uid}`, this.config.auditContext);
await this.validateModularBlocksField(
[...tree, { uid: child.uid, name: child.display_name }],
child as ModularBlocksDataType,
parent ? `${parent}.${child?.uid}` : child?.uid,
);
break;
case 'group':
log.debug(`Validating group field: ${child.uid}`, this.config.auditContext);
await this.validateGroupField(
[...tree, { uid: child.uid, name: child.display_name }],
child as GroupFieldDataType,
parent ? `${parent}.${child?.uid}` : child?.uid,
);
break;
}
}
log.debug(
`Reference lookup completed for field: ${(field as any).uid || (field as any).title || 'unknown'}`,
this.config.auditContext,
);
}
async validateGlobalField(
tree: Record<string, unknown>[],
field: GlobalFieldDataType,
parent: string | null,
): Promise<void> {
log.debug(`Validating global field: ${field.uid} (${field.display_name})`, this.config.auditContext);
log.debug(`Tree depth: ${tree.length}`, this.config.auditContext);
log.debug(`Parent: ${parent || 'none'}`, this.config.auditContext);
await this.lookForReference(tree, field, parent);
log.debug(`Global field validation completed: ${field.uid}`, this.config.auditContext);
}
async validateModularBlocksField(
tree: Record<string, unknown>[],
field: ModularBlocksDataType,
parent: string | null,
): Promise<void> {
log.debug(`Validating modular blocks field: ${field.uid} (${field.display_name})`, this.config.auditContext);
log.debug(`Tree depth: ${tree.length}`, this.config.auditContext);
log.debug(`Parent: ${parent || 'none'}`, this.config.auditContext);
const { blocks } = field;
log.debug(`Found ${blocks.length} blocks to validate`, this.config.auditContext);
for (const block of blocks) {
const { uid, title } = block;
log.debug(`Validating block: ${uid} (${title})`, this.config.auditContext);
const updatedTree = [...tree, { uid, name: title }];
const blockParent = parent + '.' + block.uid;
log.debug(`Updated tree depth: ${updatedTree.length}, block parent: ${blockParent}`, this.config.auditContext);
await this.lookForReference(updatedTree, block, blockParent);
log.debug(`Block validation completed: ${uid}`, this.config.auditContext);
}
log.debug(`Modular blocks field validation completed: ${field.uid}`, this.config.auditContext);
}
async validateGroupField(
tree: Record<string, unknown>[],
field: GroupFieldDataType,
parent: string | null,
): Promise<void> {
log.debug(`Validating group field: ${field.uid} (${field.display_name})`, this.config.auditContext);
log.debug(`Tree depth: ${tree.length}`, this.config.auditContext);
log.debug(`Parent: ${parent || 'none'}`, this.config.auditContext);
// NOTE Any Group Field related logic can be added here (Ex data serialization or picking any metadata for report etc.,)
await this.lookForReference(tree, field, parent);
log.debug(`Group field validation completed: ${field.uid}`, this.config.auditContext);
}
async prepareEntryMetaData() {
log.debug(`Preparing entry metadata`, this.config.auditContext);
log.info(auditMsg.PREPARING_ENTRY_METADATA, this.config.auditContext);
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');
log.debug(`Locales folder path: ${localesFolderPath}`, this.config.auditContext);
log.debug(`Locales path: ${localesPath}`, this.config.auditContext);
log.debug(`Master locales path: ${masterLocalesPath}`, this.config.auditContext);
log.debug(`Loading master locales`, this.config.auditContext);
this.locales = existsSync(masterLocalesPath) ? values(JSON.parse(readFileSync(masterLocalesPath, 'utf8'))) : [];
log.debug(`Loaded ${this.locales.length} master locales`, this.config.auditContext);
if (existsSync(localesPath)) {
log.debug(`Loading additional locales from file`, this.config.auditContext);
this.locales.push(...values(JSON.parse(readFileSync(localesPath, 'utf8'))));
log.debug(`Total locales after loading: ${this.locales.length}`, this.config.auditContext);
} else {
log.debug(`Additional locales file not found`, this.config.auditContext);
}
const entriesFolderPath = resolve(sanitizePath(this.config.basePath), 'entries');
log.debug(`Entries folder path: ${entriesFolderPath}`, this.config.auditContext);
log.debug(
`Processing ${this.locales.length} locales and ${this.ctSchema?.length || 0} content types`,
this.config.auditContext,
);
for (const { code } of this.locales) {
log.debug(`Processing locale: ${code}`, this.config.auditContext);
for (const { uid } of this.ctSchema ?? []) {
log.debug(`Processing content type: ${uid}`, this.config.auditContext);
let basePath = join(entriesFolderPath, uid, code);
log.debug(`Base path: ${basePath}`, this.config.auditContext);
let fsUtility = new FsUtility({ basePath, indexFileName: 'index.json' });
let indexer = fsUtility.indexFileContent;
log.debug(`Found ${Object.keys(indexer).length} entry files`, this.config.auditContext);
for (const _ in indexer) {
log.debug(`Loading entries from file`, this.config.auditContext);
const entries = (await fsUtility.readChunkFiles.next()) as Record<string, EntryStruct>;
log.debug(`Loaded ${Object.keys(entries).length} entries`, this.config.auditContext);
for (const entryUid in entries) {
let { title } = entries[entryUid];
this.entryMetaData.push({ uid: entryUid, title, ctUid: uid });
}
}
}
}
log.debug(
`Entry metadata preparation completed. Total entries: ${this.entryMetaData.length}`,
this.config.auditContext,
);
}
}