-
Notifications
You must be signed in to change notification settings - Fork 1
/
validate.js
2006 lines (1839 loc) · 72 KB
/
validate.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
import Ajv from 'ajv';
import chalk from 'chalk';
import cp from 'child_process';
import {
combineTextAndLanguageSettings,
finalizeSettings,
getDefaultSettings,
mergeSettings,
readSettings,
validateText
} from 'cspell-lib';
import {
differenceInHours,
endOfMonth,
endOfQuarter,
endOfYear,
fromUnixTime,
getUnixTime,
startOfMonth,
startOfQuarter,
startOfYear,
subDays,
subHours,
subMonths,
subQuarters,
subYears
} from 'date-fns';
import fs from 'fs';
import inquirer from 'inquirer';
import os from 'os';
import path, { dirname } from 'path';
import { exit } from 'process';
import requestPromise from 'request-promise';
import slugify from 'slugify';
import { titleCase } from 'title-case';
import { fileURLToPath, pathToFileURL } from 'url';
import util from 'util';
import {
codsSchema,
customTypesSchema,
dashboardsSchema,
dataStreamsSchema,
metadataSchema,
payloadSchema,
scopesSchema,
uiSchema
} from './schema.js';
import open from 'open';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const ajv = new Ajv({ allowUnionTypes: true, strict: false });
const exec = util.promisify(cp.exec);
const readDir = util.promisify(fs.readdir);
const directoryPath = path.join(__dirname, 'plugins');
const maxImportPayloadSize = 2 * 1024 * 1024;
const prodEnvPluginsRefUrl = 'https://squaredup.com/cloud/pluginexport';
// build up an array of any errors as the integration tests run
export const automationErrors = [];
let pluginPath;
let warningCount = 0;
let errorCount = 0;
let handler;
let metadata;
let pluginConfig;
let globalNodeId = 0;
let pluginName;
let intTestRun = false;
export let testResult;
const importedGraph = {
vertices: [],
edges: []
};
const handlerFileName = 'handler.js';
const packageFileName = 'package.json';
// Files required for plugin to work
const requiredFiles = ['metadata.json', 'ui.json', 'data_streams.json'];
// Optional configuration files
const optionalFiles = [handlerFileName, 'custom_types.json', 'default_content.json'];
const jsonSchemas = {
'metadata.json': metadataSchema,
'custom_types.json': customTypesSchema,
'ui.json': uiSchema,
'data_streams.json': dataStreamsSchema
};
// Return path for file
const getPluginFilePath = (file) => path.join(pluginPath, file);
// Return JSON from loaded file
export const loadJsonFromFile = (filePath) => {
const rawdata = fs.readFileSync(filePath);
return JSON.parse(rawdata);
};
// Log any warnings passed
const logWarnings = (warnings) => {
if (!intTestRun) {
warnings.forEach((warning) => console.warn(warning));
}
warningCount += warnings.length;
};
// Log any errors passed
const logErrors = (errors) => {
let errorsArr = [];
errorCount += errors.length;
// if integration test run, push errors to automationErrors array
if (intTestRun) {
errors.forEach((error) => errorsArr.push(error));
const foundIndex = automationErrors.findIndex((entry) => entry.pluginName === pluginName);
if (foundIndex !== -1) {
automationErrors[foundIndex].errors = automationErrors[foundIndex].errors.concat(errorsArr);
} else {
automationErrors.push({
pluginName: pluginName,
errors: errorsArr
});
}
} else {
errors.forEach((error) => console.log(error));
}
};
// Log any errors passed and exit validation process
const logErrorsAndExit = (errors) => {
logErrors(errors);
exit();
};
const spellCheckerFactory = async () => {
let settings = {
...getDefaultSettings(),
enabledLanguageIds: []
};
// Get global allowed words
const cspellConfigFileName = 'cspell.json';
const globalCspellConfigPath = path.join(__dirname, cspellConfigFileName);
settings = mergeSettings(settings, readSettings(globalCspellConfigPath));
// Get plugin-specific allowed words (if any)
const cspellConfigPath = getPluginFilePath(cspellConfigFileName);
if (fs.existsSync(cspellConfigPath)) {
settings = mergeSettings(settings, readSettings(cspellConfigPath));
}
const fileSettings = combineTextAndLanguageSettings(settings, '', ['plaintext']);
const finalSettings = finalizeSettings(fileSettings);
return async (phrase) => {
return await validateText(phrase, finalSettings, { generateSuggestions: true });
};
};
async function spellCheck(pluginName, textName, text, file = 'metadata.json') {
if (text) {
const spellChecker = await spellCheckerFactory();
const typos = await spellChecker(text);
for (const typo of typos) {
logErrors([
chalk.bgRed(`The ${file} file for plugin name "${pluginName}" has typo in ${textName}: "${typo.text}"`)
]);
}
} else {
logErrors([chalk.bgRed(`The ${file} file for plugin name "${pluginName}" has missing ${textName}`)]);
}
}
// Produce Mermaid source for import JSON
const mermaidForImportObjects = (importJson) => {
const lines = ['graph LR'];
const nodeIdsBySourceId = new Map();
for (const vertex of importJson.vertices) {
if (nodeIdsBySourceId.has(vertex.sourceId)) {
console.warn(chalk.yellow(`duplicate sourceId "${vertex.sourceId}"`));
} else {
const nodeId = `node_${nodeIdsBySourceId.size + 1}`;
nodeIdsBySourceId.set(vertex.sourceId, nodeId);
let type = '';
if (vertex.type) {
if (typeof vertex.type === 'string') {
type = vertex.type.replace('"', '#quot;');
}
if (Array.isArray(vertex.type)) {
type = vertex.type.reduce((prev, current) => {
return `${prev.replace('"', '#quot;')}, ${current.replace('"', '#quot;')}`;
});
}
}
lines.push(
` ${nodeId}["${type} (${vertex.sourceType.replace('"', '#quot;')})<br>${vertex.name.replace(
'"',
'#quot;'
)}"]`
);
}
}
for (const edge of importJson.edges) {
const inNodeId = nodeIdsBySourceId.get(edge.inV);
if (!inNodeId) {
console.warn(chalk.yellow(`Edge '${JSON.stringify(edge)}' - inV not found`));
}
const outNodeId = nodeIdsBySourceId.get(edge.outV);
if (!outNodeId) {
console.warn(chalk.yellow(`Edge '${JSON.stringify(edge)}' - outV not found`));
}
if (inNodeId && outNodeId) {
lines.push(` ${outNodeId} --"${edge.label.replace('"', '#quot;')}"--> ${inNodeId}`);
}
}
return lines;
};
// Validate JSON for a specific file
const validateJson = (file, jsonSchema = null) => {
let filePath, json;
if (!jsonSchema) {
jsonSchema = jsonSchemas[file];
}
if (!path.isAbsolute(file)) {
filePath = getPluginFilePath(file);
json = loadJsonFromFile(filePath);
} else {
json = loadJsonFromFile(file);
}
const validate = ajv.compile(jsonSchema);
switch (intTestRun) {
case intTestRun === true:
!validate(json)
? logErrors([
chalk.bgRed(`${file} is invalid`),
...validate.errors.map((error) => chalk.red(`path ${error.instancePath}: ${error.message}`))
])
: console.log(chalk.green(`${file} matches schema`));
break;
case intTestRun === false:
!validate(json)
? logErrorsAndExit([
chalk.bgRed(`${file} is invalid`),
...validate.errors.map((error) => chalk.red(`path ${error.instancePath}: ${error.message}`))
])
: console.log(chalk.green(`${file} matches schema`));
break;
default:
break;
}
};
// Returns loaded import handler
const loadHandler = async () => {
const packagePath = getPluginFilePath(packageFileName);
if (fs.existsSync(packagePath)) {
// Ensure npm packages are installed and return importer
console.log('Installing node packages...');
const prevWd = process.cwd();
process.chdir(pluginPath);
await exec('npm i');
process.chdir(prevWd);
const { testConfig, importObjects, readDataSource } = await import(
pathToFileURL(getPluginFilePath(handlerFileName))
);
return { testConfig, importObjects, readDataSource };
} else {
return false;
}
};
// Returns correct inquirer question type based on field type
const getInquirerQuestion = (field) => {
let questionType;
switch (field.type) {
case 'checkbox':
questionType = 'confirm';
break;
case 'checkboxes':
questionType = 'checkbox';
break;
case 'radio':
questionType = 'list';
break;
case 'autocomplete':
questionType = 'input';
break;
default:
questionType = 'input';
}
return {
type: questionType,
name: field.name,
message: `${field.title} ${field.help ? `- ${field.help}` : ''}`,
...(field.options && { choices: field.options }),
...(field.validation && {
validate: (answer) => {
if (field.validation?.required && !answer) {
return `${field.label} is required`;
}
return true;
}
}),
filter: (val) => {
// Hack for allowing arrays to be generated by ending answer with a ','
if (val.endsWith(',')) {
return val
.split(',')
.filter((item) => item)
.map((val) => ({ value: val })); // (Mimics autocomplete UI component output)
}
return val;
}
};
};
// Returns array of config fields for user input
const buildHandlerQuestions = async () => {
const uiPath = getPluginFilePath('ui.json');
const handlerFields = loadJsonFromFile(uiPath);
return [
...handlerFields.map((field) => getInquirerQuestion(field)),
{
type: 'confirm',
name: 'logHandlerOutput',
message: 'Do you want to log the handler output?'
}
];
};
async function validateMetadata() {
const helpLink = 'Help adding this plugin';
metadata = loadJsonFromFile(getPluginFilePath('metadata.json'));
if (!Array.isArray(metadata.links) || !metadata.links.some((l) => l.label === helpLink)) {
if (metadata.author === 'SquaredUp') {
logErrors([
chalk.bgRed(
`The metadata.json file for plugin name "${metadata.name}" is missing the required "${helpLink}" link.`
)
]);
}
} else {
if (metadata.author === 'SquaredUp') {
const link = metadata.links.find((l) => l.label === helpLink);
const name = metadata.name.toLowerCase().replace(/ /g, '');
const baseName = name.replace(/onpremise$/, '');
const expectUrl1 = `https://squaredup.com/cloud/pluginsetup-${name}`;
const expectUrl2 = `https://squaredup.com/cloud/pluginsetup-${baseName}`;
if (link.url !== expectUrl1 && link.url !== expectUrl2) {
const expectUrl = expectUrl1 === expectUrl2 ? expectUrl1 : `${expectUrl1} or ${expectUrl2}`;
logErrors([
chalk.bgRed(
`The metadata.json file for plugin name "${metadata.name}" has the wrong URL for "${helpLink}" link - "${link.url}" should be "${expectUrl}"`
)
]);
}
}
for (const link of metadata.links) {
await spellCheck(metadata.name, `link label for "${link.url}"`, link.label);
}
}
await spellCheck(metadata.name, 'description', metadata.description);
// Additional checks for on-prem
if (['onprem', 'hybrid', 'declarative'].includes(metadata.type)) {
if (typeof metadata.actions !== 'object' || metadata.actions === null) {
logErrors([
chalk.bgRed(
`The metadata.json file for plugin name "${metadata.name}" is missing the required "actions" object.`
)
]);
} else {
const actionNames = new Set(Object.keys(metadata.actions));
const dataStreams = loadJsonFromFile(getPluginFilePath('data_streams.json'));
for (const dataSource of dataStreams.dataSources) {
if (!actionNames.has(dataSource.name)) {
logErrors([
chalk.bgRed(
`The metadata.json file for plugin name "${metadata.name}" is missing the required action "${dataSource.name}"`
)
]);
}
}
}
}
return metadata;
}
async function validateUi(pluginName) {
const ui = loadJsonFromFile(getPluginFilePath('ui.json'));
async function spellCheckItem(pluginName, item) {
if (item.type === 'fieldGroup') {
for (const subItem of item.fields) {
await spellCheckItem(pluginName, subItem);
}
} else {
await spellCheck(pluginName, `label for UI item "${item.name}"`, item.label, 'ui.json');
if (item.title) {
await spellCheck(pluginName, `title for UI item "${item.name}"`, item.title, 'ui.json');
}
if (item.help) {
await spellCheck(pluginName, `help for UI item "${item.name}"`, item.help, 'ui.json');
}
}
}
for (const item of ui) {
await spellCheckItem(pluginName, item);
}
return ui;
}
//TODO: see if latest set of valid shapes can be provided by the SAAS build rather than hard-coding here
const validShapes = new Set([
'boolean',
'date',
'number',
'string',
'currency',
'eur',
'gbp',
'usd',
'bytes',
'kilobytes',
'megabytes',
'gigabytes',
'terabytes',
'petabytes',
'exabytes',
'zettabytes',
'yottabytes',
'awsJsonLogEvent',
'azureVmId',
'state',
'milliseconds',
'seconds',
'minutes',
'timespan',
'customUnit',
'guid',
'json',
'percent',
'url'
]);
const validRoles = new Set(['id', 'label', 'link', 'timestamp', 'unitLabel', 'value']);
async function validateDataStreamMetadata(pluginName, name, metadata) {
let stateColNum;
let expectedLabelColsStart = 0;
const labelColNumbers = [];
for (let colNum = 0; colNum < metadata.length; colNum++) {
const col = metadata[colNum];
let shapeName;
if (Array.isArray(col.shape)) {
if (col.shape.length != 2) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has metadata for column "${
col.name
}" with invalid 'shape': "${col.shape.join(', ')}"`
)
]);
} else {
if (
typeof col.shape[0] !== 'string' ||
!validShapes.has(col.shape[0]) ||
typeof col.shape[1] !== 'object' ||
Array.isArray(col.shape[1])
) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has metadata for column "${
col.name
}" with invalid 'shape': "${col.shape.join(', ')}"`
)
]);
}
}
shapeName = col.shape[0];
} else {
if (typeof col.name !== 'string' || col.name.match(/^\s*$/)) {
// The absence of 'name' is acceptable if a pattern is provided. Pattern doesn't require displayName or shape
if (typeof col.pattern !== 'string' || col.pattern.match(/^\s*$/)) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has metadata for column with no 'name' or 'pattern'`
)
]);
}
} else {
if (Object.prototype.hasOwnProperty.call(col, 'visible') && typeof col.visible !== 'boolean') {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has metadata for column "${col.name}" with invalid 'visible' - must be boolean`
)
]);
}
if (typeof col.visible !== 'boolean' || col.visible !== false) {
if (typeof col.displayName !== 'string' || col.displayName.match(/^\s*$/)) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has metadata for column "${col.name}" with missing 'displayName'`
)
]);
} else {
const tc = titleCase(col.displayName.replace('_', ' '));
if (col.displayName !== tc) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has metadata for column "${col.name}" with bad 'displayName' = "${col.displayName}" should be "${tc}"`
)
]);
}
await spellCheck(pluginName, `displayName column "${col.name}" in "${name}"`, col.displayName);
}
}
if (typeof col.shape !== 'string' || col.shape.match(/^\s*$/)) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has metadata for column "${col.name}" with missing 'shape'`
)
]);
} else {
if (!validShapes.has(col.shape)) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has metadata for column "${col.name}" with invalid 'shape': "${col.shape}"`
)
]);
}
}
}
shapeName = col.shape;
}
if (shapeName === 'state') {
if (typeof stateColNum === 'number') {
logWarnings([
chalk.yellow(
`Warning: The data_streams.json file for plugin name "${pluginName}" "${name}" has metadata for column "${col.name}" with multiple state columns`
)
]);
} else {
stateColNum = colNum;
expectedLabelColsStart = 1;
}
}
if (col.role) {
if (typeof col.role !== 'string' || !validRoles.has(col.role)) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has metadata for column "${col.name}" with invalid 'role': "${col.role}"`
)
]);
}
}
if (col.role === 'label') {
labelColNumbers.push(colNum);
}
}
if (typeof stateColNum === 'number' && stateColNum !== 0) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has state column at index ${stateColNum} - should be 0`
)
]);
}
if (labelColNumbers.length > 0) {
if (labelColNumbers[0] !== expectedLabelColsStart) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has label column at index ${labelColNumbers[0]} - should be ${expectedLabelColsStart}`
)
]);
}
if (labelColNumbers[labelColNumbers.length - 1] - labelColNumbers[0] !== labelColNumbers.length - 1) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" "${name}" has non-contiguous label columns ${labelColNumbers.join(
', '
)}`
)
]);
}
}
}
async function validateDataStreams(pluginName) {
const dataStreams = loadJsonFromFile(getPluginFilePath('data_streams.json'));
if (Array.isArray(dataStreams.rowTypes)) {
for (const rowType of dataStreams.rowTypes) {
await validateDataStreamMetadata(pluginName, `ROW:${rowType.name}`, rowType.metadata);
}
}
for (const dataSource of dataStreams.dataSources) {
await spellCheck(pluginName, `display name for data source "${dataSource.name}"`, dataSource.displayName);
if (dataSource.description) {
await spellCheck(pluginName, `description for data source "${dataSource.name}"`, dataSource.description);
}
}
const dataSourceNames = dataStreams.dataSources.reduce((acc, val) => {
if (acc.has(val.name)) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" has duplicate data source name: "${val.name}"`
)
]);
}
acc.add(val.name);
return acc;
}, new Set());
for (const dataStream of dataStreams.dataStreams) {
if (!dataSourceNames.has(dataStream.dataSourceName)) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" has data stream "${dataStream.definition.name}" referencing non-existent data source: "${dataStream.dataSourceName}"`
)
]);
}
if (Array.isArray(dataStream.definition.metadata)) {
await validateDataStreamMetadata(
pluginName,
`STREAM:${dataStream.definition.name}`,
dataStream.definition.metadata
);
} else {
if (!dataStream.definition.rowType) {
logErrors([
chalk.bgRed(
`The data_streams.json file for plugin name "${pluginName}" has no metadata for data stream "${dataStream.definition.name}"`
)
]);
}
}
await spellCheck(
pluginName,
`display name for data stream "${dataStream.definition.name}"`,
dataStream.displayName
);
if (dataStream.description) {
await spellCheck(
pluginName,
`description for data stream "${dataStream.definition.name}"`,
dataStream.description
);
}
}
return dataStreams;
}
async function validateCustomTypes(pluginName) {
const customTypesPath = getPluginFilePath('custom_types.json');
if (!fs.existsSync(customTypesPath)) {
return null;
}
const customTypes = loadJsonFromFile(customTypesPath);
for (const item of customTypes) {
await spellCheck(pluginName, `display name for custom type "${item.type}"`, item.name);
await spellCheck(pluginName, `singular for custom type "${item.type}"`, item.singular);
await spellCheck(pluginName, `plural for custom type "${item.type}"`, item.plural);
}
return customTypes;
}
const validTypes = new Set([
'app',
'api',
'apidomain',
'apigateway',
'dnszone',
'dnsrecord',
'db',
'host',
'monitor',
'kpi',
'function',
'table',
'storage',
'cdn',
'directory',
'relay',
'tag',
'space',
'scope',
'dash',
'cluster',
'service',
'loadbalancer',
'container',
'workflow',
'pipeline',
'organization',
'unknown'
]);
async function validateDefaultContent(pluginName, dataStreams, customTypes) {
const defaultContentPath = path.join(path.resolve(__dirname, pluginPath), 'DefaultContent');
if (!fs.existsSync(defaultContentPath)) {
return null;
}
let defaultScopes = [];
let defaultCods = [];
let defaultDashboards = [];
const allDefaultContentFiles = await readDir(defaultContentPath);
allDefaultContentFiles.forEach((file) => {
const filePath = path.join(defaultContentPath, file);
const defaultContentFile = loadJsonFromFile(filePath);
if (file.toLowerCase() === 'scopes.json') {
validateJson(filePath, scopesSchema);
defaultScopes = defaultContentFile;
} else if (file.toLowerCase() === 'cods.json') {
validateJson(filePath, codsSchema);
defaultCods = defaultContentFile;
} else if (file.toLowerCase().endsWith('.dash.json')) {
validateJson(filePath, dashboardsSchema);
defaultContentFile['filePath'] = file;
defaultDashboards.push(defaultContentFile);
}
});
const allScopes = defaultScopes.map((s) => s.name);
const allDataStreams = dataStreams.dataStreams.map((ds) => ds.definition.name);
defaultCods.forEach((cods) => {
allDataStreams.push(`${cods.tplName}___${cods.index}`);
});
const allTypes = Array.from(validTypes).concat(customTypes.map((t) => t.type));
for (const scope of defaultScopes) {
await spellCheck(pluginName, 'Scope name in default content', scope.name, 'scopes.json');
if (typeof scope.matches === 'object') {
if (scope.matches.type.type === 'equals') {
if (!allTypes.includes(scope.matches.type.value)) {
logErrors([
chalk.yellow(
`The default_content.json file for plugin name "${pluginName}" has scope "${scope.name}" with invalid type: "${scope.matches.type.value}"`
)
]);
}
} else {
const nonMatchingTypes = [];
for (const value of scope.matches.type.values) {
if (!allTypes.includes(value)) {
nonMatchingTypes.push(value);
}
}
if (nonMatchingTypes.length > 0) {
logErrors([
chalk.yellow(
`The default_content.json file for plugin name "${pluginName}" has scope "${
scope.name
}" with invalid type${nonMatchingTypes.length == 1 ? '' : 's'}: "${nonMatchingTypes.join(
'", "'
)}"`
)
]);
}
}
}
}
for (const dashboard of defaultDashboards) {
await spellCheck(pluginName, 'Dashboard name in default content', dashboard.name, dashboard.filePath);
for (const tile of dashboard.dashboard.contents) {
await spellCheck(pluginName, 'Tile title in default content', tile.config.title, dashboard.filePath);
if (tile.config.description) {
await spellCheck(
pluginName,
'Tile description in default content',
tile.config.description,
dashboard.filePath
);
}
checkTileValue(pluginName, dashboard.name, tile.config.title, tile.config, allScopes, allDataStreams);
checkTileVizConfig(pluginName, dashboard, tile.config.title, tile.config);
}
checkTileTimeframes(pluginName, dashboard);
}
}
const checkTileVizConfig = (pluginName, dashboard, tileName, config) => {
if (
config?.visualisation?.config &&
Object.keys(config.visualisation?.config).filter((k) => k !== config?.visualisation.type).length > 0
) {
logWarnings([
chalk.yellow(
`The tile "${tileName}" on dashboard "${dashboard.filePath}" in plugin "${pluginName}" contains redundant visualization configuration.`
)
]);
}
};
const checkTileTimeframes = (pluginName, dashboard) => {
const tiles = dashboard.dashboard.contents;
if (tiles.every((t) => Boolean(t.config.timeframe) && t.config.timeframe === tiles[0].config.timeframe)) {
logErrors([
chalk.bgRed(
`The ${dashboard.filePath} file for plugin "${pluginName}" uses the same timeframe for all tiles, use a dashboard timeframe instead.`
)
]);
}
};
const checkTileValue = (pluginName, dashboardName, tileName, value, allScopes, allDataStreams) => {
if (value == null) {
return; // null or undefined values don't require further checking
}
if (typeof value === 'object' && !Array.isArray(value)) {
for (const key of Object.keys(value)) {
checkTileValue(pluginName, dashboardName, tileName, value[key], allScopes, allDataStreams);
}
} else if (Array.isArray(value)) {
for (const item of value) {
checkTileValue(pluginName, dashboardName, tileName, item, allScopes, allDataStreams);
}
} else if (typeof value === 'string') {
if (value.startsWith('config-') && value !== 'config-00000000000000000000') {
logErrors([
chalk.bgRed(
`The default_content.json file for plugin name ${pluginName} has dashboard "${dashboardName}" with tile "${tileName}" with raw config ID: ${value}`
)
]);
}
if (value.startsWith('space-')) {
logErrors([
chalk.bgRed(
`The default_content.json file for plugin name ${pluginName} has dashboard "${dashboardName}" with tile "${tileName}" with raw workspace ID: "${value}"`
)
]);
}
if (value.startsWith('scope-')) {
logErrors([
chalk.bgRed(
`The default_content.json file for plugin name ${pluginName} has dashboard "${dashboardName}" with tile "${tileName}" with raw scope ID: "${value}"`
)
]);
}
if (
value.startsWith('datastream-') &&
value !== 'datastream-health' &&
value !== 'datastream-properties' &&
value !== 'datastream-sql'
) {
logErrors([
chalk.bgRed(
`The default_content.json file for plugin name ${pluginName} has dashboard "${dashboardName}" with tile "${tileName}" with raw data stream ID: "${value}"`
)
]);
}
if (value.startsWith('{{{{raw}}}}') && value.endsWith('{{{{/raw}}}}')) {
return; // handlebar raw values don't require further checking
}
if (value.startsWith('{{') && value.endsWith('}}')) {
const originalValue = value;
value = value.replace('{{', '');
value = value.replace('}}', '');
if (value.startsWith('scopes.')) {
value = value.replace('scopes.', '');
let hasSquareBrackets = value.startsWith('[') && value.endsWith(']');
if (hasSquareBrackets) {
value = value.replace('[', '');
value = value.replace(']', '');
}
if (!allScopes.includes(value)) {
logErrors([
chalk.bgRed(
`The default_content.json file for plugin name ${pluginName} has dashboard "${dashboardName}" with tile "${tileName}" with non-existent scope name: "${value}"`
)
]);
}
if (value.includes(' ') && !hasSquareBrackets) {
logErrors([
chalk.bgRed(
`The default_content.json file for plugin name ${pluginName} has dashboard "${dashboardName}" with tile "${tileName}" with scope name containing spaces without square brackets: "${originalValue}"`
)
]);
}
} else if (value.startsWith('dataStreams.')) {
value = value.replace('dataStreams.', '');
if (value.startsWith('[') && value.endsWith(']')) {
value = value.substring(1, value.length - 1);
}
if (!allDataStreams.includes(value)) {
logErrors([
chalk.bgRed(
`The default_content.json file for plugin name ${pluginName} has dashboard "${dashboardName}" with tile "${tileName}" with non-existent data stream name: "${value}"`
)
]);
}
} else {
if (!['configId', 'workspaceId'].includes(value)) {
logErrors([
chalk.bgRed(
`The default_content.json file for plugin name ${pluginName} has dashboard "${dashboardName}" with tile "${tileName}" with invalid handlebar value: "${originalValue}"`
)
]);
}
}
}
}
};
// Validate plugin configuration/JSON files
const checkPluginFiles = async () => {
const allPluginFiles = await readDir(pluginPath);
const missingFiles = requiredFiles.filter((file) => !allPluginFiles.includes(file));
if (missingFiles.length) {
// Failure here ends validation process if intTestRun is false
intTestRun === true
? logErrors([
chalk.bgRed('Your plugin is missing the following required files:'),
chalk.red(missingFiles.join(', '))
])
: logErrorsAndExit([
chalk.bgRed('Your plugin is missing the following required files:'),
chalk.red(missingFiles.join(', '))
]);
}
const filesToCheck = [...requiredFiles, ...optionalFiles.filter((file) => allPluginFiles.includes(file))];
const jsonFilesToCheck = filesToCheck.filter((file) => file.endsWith('.json'));
// Validate JSON files against respective schema
jsonFilesToCheck.forEach((file) => validateJson(file));
// Check the metadata file
const metadata = await validateMetadata();
if (['cloud', 'hybrid'].includes(metadata.type)) {
if (!allPluginFiles.includes(handlerFileName)) {
logErrorsAndExit([
chalk.bgRed('Your plugin is missing the following required files:'),
chalk.red(handlerFileName)
]);
}
}
// Check the UI file
await validateUi(metadata.name);
// Check the data_streams file
const dataStreams = await validateDataStreams(metadata.name);
// Check the custom types
const customTypes = await validateCustomTypes(metadata.name);
// Check the default content
await validateDefaultContent(metadata.name, dataStreams, customTypes);
};
// log functions (part of the api object passed to plugin entry points).
const log = {
error: function (msg) {
console.log(`Plugin ERROR: ${msg}`);
},
warn: function (msg) {
console.log(`Plugin WARN: ${msg}`);
},
info: function (msg) {
console.log(`Plugin INFO: ${msg}`);
},
debug: function (msg) {
console.log(`Plugin DEBUG: ${msg}`);
}
};
const report = {
warning: function (text) {
console.log(`plugin reports warning: ${text}`);