forked from SchemaStore/schemastore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gruntfile.cjs
2163 lines (1979 loc) · 69.6 KB
/
Gruntfile.cjs
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
/// <binding AfterBuild='build' />
const path = require('node:path')
const fs = require('node:fs')
const readline = require('node:readline/promises')
const addFormats = require('ajv-formats')
const ajvFormatsDraft2019 = require('ajv-formats-draft2019')
const AjvDraft04 = require('ajv-draft-04')
const AjvDraft06And07 = require('ajv')
const Ajv2019 = require('ajv/dist/2019')
const Ajv2020 = require('ajv/dist/2020')
const AjvDraft06SchemaJson = require('ajv/dist/refs/json-schema-draft-06.json')
const AjvStandalone = require('ajv/dist/standalone').default
const TOML = require('@ltd/j-toml')
const YAML = require('yaml')
const schemasafe = require('@exodus/schemasafe')
const prettier = require('prettier')
const axios = require('axios').default
const jsonlint = require('@prantlf/jsonlint')
const jsoncParser = require('jsonc-parser')
const temporaryCoverageDir = './temp'
const schemaDir = './src/schemas/json'
const testPositiveDir = './src/test'
const testNegativeDir = './src/negative_test'
const urlSchemaStore = 'https://json.schemastore.org/'
const catalog = require('./src/api/json/catalog.json')
const schemaValidation = jsoncParser.parse(
fs.readFileSync('./src/schema-validation.json', 'utf-8'),
)
const schemasToBeTested = fs.readdirSync(schemaDir)
const foldersPositiveTest = fs.readdirSync(testPositiveDir)
const foldersNegativeTest = fs.readdirSync(testNegativeDir)
// prettier-ignore
const SCHEMA_DIALECTS = [
{ schemaName: '2020-12', url: 'https://json-schema.org/draft/2020-12/schema', isActive: true, isTooHigh: true },
{ schemaName: '2019-09', url: 'https://json-schema.org/draft/2019-09/schema', isActive: true, isTooHigh: true },
{ schemaName: 'draft-07', url: 'http://json-schema.org/draft-07/schema#', isActive: true, isTooHigh: false },
{ schemaName: 'draft-06', url: 'http://json-schema.org/draft-06/schema#', isActive: false, isTooHigh: false },
{ schemaName: 'draft-04', url: 'http://json-schema.org/draft-04/schema#', isActive: false, isTooHigh: false },
{ schemaName: 'draft-03', url: 'http://json-schema.org/draft-03/schema#', isActive: false, isTooHigh: false },
]
module.exports = function (/** @type {import('grunt')} */ grunt) {
'use strict'
function skipThisFileName(/** @type {string} */ name) {
// This macOS file must always be ignored.
return name === '.DS_Store'
}
function getUrlFromCatalog(catalogUrl) {
for (const schema of catalog.schemas) {
catalogUrl(schema.url)
const versions = schema.versions
if (versions) {
Object.values(versions).forEach((url) => catalogUrl(url))
}
}
}
/**
* @summary Create an exception with error text
* Make sure that the user see this error message.
* And not only the error message generated by npm after this message.
* @param {string[]} errorText
*/
function throwWithErrorText(errorText) {
grunt.log.writeln()
grunt.log.writeln()
grunt.log.writeln('################ Error message')
for (const text of errorText) {
grunt.log.error(text)
}
grunt.log.writeln('##############################')
throw new Error('See error message above this line.')
}
/**
* @param {CbParamFn} schemaOnlyScan
*/
async function remoteSchemaFile(schemaOnlyScan, showLog = true) {
const responseType = 'arraybuffer'
for (const { url } of catalog.schemas) {
if (url.startsWith(urlSchemaStore)) {
// Skip local schema
continue
}
try {
const response = await axios.get(url, { responseType })
if (response.status === 200) {
const parsed = new URL(url)
const schema = {
jsonName: path.basename(parsed.pathname),
jsonObj: JSON.parse(response.data.toString()),
rawFile: response.data,
urlOrFilePath: url,
schemaScan: true,
}
schemaOnlyScan(schema)
if (showLog) {
grunt.log.ok(url)
}
} else {
if (showLog) {
grunt.log.error(url, response.status)
}
}
} catch (error) {
if (showLog) {
grunt.log.writeln('')
grunt.log.error(url, error.name, error.message)
grunt.log.writeln('')
}
}
}
}
/**
* @typedef {Object} JsonSchema
* @property {string} $schema
* @property {string} $id
*/
/**
* @typedef {Object} Schema
* @prop {Buffer | undefined} rawFile
* @prop {Record<string, unknown> & JsonSchema} jsonObj
* @prop {string} jsonName
* @prop {string} urlOrFilePath
* @prop {boolean} schemaScan
*/
/**
* @callback CbParamFn
* @param {Schema}
*/
/**
* @typedef {Object} localSchemaFileAndTestFileParameter1
* @prop {CbParamFn} schemaOnlyScan
* @prop {CbParamFn} schemaOnlyScanDone
* @prop {CbParamFn} schemaForTestScan
* @prop {CbParamFn} schemaForTestScanDone
* @prop {CbParamFn} positiveTestScan
* @prop {CbParamFn} positiveTestScanDone
* @prop {CbParamFn} negativeTestScan
* @prop {CbParamFn} negativeTestScanDone
*/
/**
* @typedef {Object} localSchemaFileAndTestFileParameter2
* @prop {boolean} fullScanAllFiles
* @prop {boolean} skipReadFile
* @prop {boolean} ignoreSkiptest
* @prop {string} processOnlyThisOneSchemaFile
*/
/**
* @param {localSchemaFileAndTestFileParameter1}
* @param {localSchemaFileAndTestFileParameter2}
*/
function localSchemaFileAndTestFile(
{
schemaOnlyScan = undefined,
schemaOnlyScanDone = undefined,
schemaForTestScan = undefined,
schemaForTestScanDone = undefined,
positiveTestScan = undefined,
positiveTestScanDone = undefined,
negativeTestScan = undefined,
negativeTestScanDone = undefined,
},
{
fullScanAllFiles = false,
skipReadFile = true,
ignoreSkiptest = false,
processOnlyThisOneSchemaFile = undefined,
} = {},
) {
const schemaNameOption = grunt.option('SchemaName')
if (processOnlyThisOneSchemaFile === undefined && schemaNameOption) {
processOnlyThisOneSchemaFile = schemaNameOption
const file = path.join(schemaDir, processOnlyThisOneSchemaFile)
if (!fs.existsSync(file)) {
throwWithErrorText([
`Schema file ${processOnlyThisOneSchemaFile} does not exist`,
])
}
}
/**
* @summary Check if the present json schema file must be tested or not
* @param {string} jsonFilename
* @returns {boolean}
*/
const canThisTestBeRun = (jsonFilename) => {
if (!ignoreSkiptest && schemaValidation.skiptest.includes(jsonFilename)) {
return false // This test can be never process
}
if (fullScanAllFiles) {
return true // All tests are always performed.
} else {
return true
}
}
/**
* @summary Get all the schema files via callback
* @param callback The callback function(schema)
* @param {boolean} onlySchemaScan True = a scan without test files.
*/
const scanAllSchemaFiles = (callback, onlySchemaScan) => {
if (!callback) {
return
}
// Process all the schema files one by one via callback.
schemasToBeTested.forEach((schemaFileName) => {
if (processOnlyThisOneSchemaFile) {
if (schemaFileName !== processOnlyThisOneSchemaFile) return
}
const schemaFullPathName = path.join(schemaDir, schemaFileName)
// Some schema files must be ignored.
if (
canThisTestBeRun(schemaFileName) &&
!skipThisFileName(schemaFileName)
) {
const buffer = skipReadFile
? undefined
: fs.readFileSync(schemaFullPathName)
let jsonObj_
try {
jsonObj_ = buffer ? JSON.parse(buffer.toString()) : undefined
} catch (err) {
throwWithErrorText([
`JSON file ${schemaFullPathName} did not parse correctly.`,
err,
])
}
const schema = {
// Return the real Raw file for BOM file test rejection
rawFile: buffer,
jsonObj: jsonObj_,
jsonName: path.basename(schemaFullPathName),
urlOrFilePath: schemaFullPathName,
schemaScan: onlySchemaScan,
}
callback(schema)
}
})
}
// Scan one test folder for all the files inside it
const scanOneTestFolder = (
schemaName,
testDir,
testPassScan,
testPassScanDone,
) => {
const loadTestFile = (testFileNameWithPath, buffer) => {
// Test files have extension '.json' or else it must be a YAML file
const fileExtension = testFileNameWithPath.split('.').pop()
switch (fileExtension) {
case 'json':
try {
return JSON.parse(buffer.toString())
} catch (err) {
throwWithErrorText([
`JSON file ${testFileNameWithPath} did not parse correctly.`,
err,
])
}
break
case 'yaml':
case 'yml':
try {
return YAML.parse(buffer.toString())
} catch (err) {
throwWithErrorText([
`Can't read/decode yaml file: ${testFileNameWithPath}`,
err,
])
}
break
case 'toml':
try {
// { bigint: false } or else toml variable like 'a = 3' will return as 'a = 3n'
// This creates an error because the schema expect an integer 3 and not 3n
return TOML.parse(buffer.toString(), {
bigint: false,
joiner: '\n',
})
} catch (err) {
throwWithErrorText([
`Can't read/decode toml file: ${testFileNameWithPath}`,
err,
])
}
break
default:
throwWithErrorText([`Unknown file extension: ${fileExtension}`])
}
}
if (!testPassScan) {
return
}
// remove filename '.json' extension and to create the folder name
const folderNameAndPath = path.join(
testDir,
path.basename(schemaName, '.json'),
)
// if test folder doesn't exist then exit. Some schemas do not have a test folder.
if (!fs.existsSync(folderNameAndPath)) {
return
}
// Read all files name inside one test folder
const filesInsideOneTestFolder = fs.readdirSync(folderNameAndPath).map(
// Must create a list with full path name
(fileName) => path.join(folderNameAndPath, fileName),
)
if (!filesInsideOneTestFolder.length) {
throwWithErrorText([
`Found folder with no test files: ${folderNameAndPath}`,
])
}
// Test file may have BOM. This must be removed.
grunt.file.preserveBOM = false // Strip BOM from file
filesInsideOneTestFolder.forEach(function (testFileFullPathName) {
// forbidden to add extra folder inside the specific test folder
if (!fs.lstatSync(testFileFullPathName).isFile()) {
throwWithErrorText([
`Found non test file inside test folder: ${testFileFullPathName}`,
])
}
if (!skipThisFileName(path.basename(testFileFullPathName))) {
const buffer = skipReadFile
? undefined
: fs.readFileSync(testFileFullPathName)
const schema = {
rawFile: buffer,
jsonObj: skipReadFile
? undefined
: loadTestFile(testFileFullPathName, buffer),
jsonName: path.basename(testFileFullPathName),
urlOrFilePath: testFileFullPathName,
// This is a test folder scan process, not schema scan process
schemaScan: false,
}
testPassScan(schema)
}
})
testPassScanDone?.()
}
// Callback only for schema file scan. No test files are process here.
scanAllSchemaFiles(schemaOnlyScan, true)
schemaOnlyScanDone?.()
// process one by one all schema + positive test folders + negative test folders
scanAllSchemaFiles((callbackParameterFromSchema) => {
// process one schema
schemaForTestScan?.(callbackParameterFromSchema)
// process positive and negative test folder belonging to the one schema
const schemaName = callbackParameterFromSchema.jsonName
scanOneTestFolder(
schemaName,
testPositiveDir,
positiveTestScan,
positiveTestScanDone,
)
scanOneTestFolder(
schemaName,
testNegativeDir,
negativeTestScan,
negativeTestScanDone,
)
}, false)
schemaForTestScanDone?.()
}
/**
* @param {Schema} schema
*/
function testSchemaFileForBOM(schema) {
// JSON schema file must not have any BOM type
const buffer = schema.rawFile
const bomTypes = [
{ name: 'UTF-8', signature: [0xef, 0xbb, 0xbf] },
{ name: 'UTF-16 (BE)', signature: [0xfe, 0xff] },
{ name: 'UTF-16 (LE)', signature: [0xff, 0xfe] },
{ name: 'UTF-32 (BE)', signature: [0x00, 0x00, 0xff, 0xfe] },
{ name: 'UTF-32 (LE)', signature: [0xff, 0xfe, 0x00, 0x00] },
]
for (const bom of bomTypes) {
if (buffer.length >= bom.signature.length) {
const bomFound = bom.signature.every(
(value, index) => buffer[index] === value,
)
if (bomFound) {
throwWithErrorText([
`Schema file must not have ${bom.name} BOM: ${schema.urlOrFilePath}`,
])
}
}
}
}
/**
* @typedef {Object} FactoryAJVParameter
* @prop {string} schemaName
* @prop {string[]} unknownFormatsList
* @prop {boolean} fullStrictMode
* @prop {boolean} standAloneCode
* @prop {string[]} standAloneCodeWithMultipleSchema
*/
/**
* There are multiple AJV version for each $schema version.
* return the correct AJV instance
* @param {FactoryAJVParameter} schemaName
* @returns {Object}
*/
function factoryAJV({
schemaName,
unknownFormatsList = [],
fullStrictMode = true,
standAloneCode = false,
standAloneCodeWithMultipleSchema = [],
} = {}) {
// some AJV default setting are [true, false or log]
// Some options are default: 'log'
// 'log' will generate a lot of noise in the build log. So make it true or false.
// Hiding the issue log also does not solve anything.
// These option items that are not strict must be reduces in the future.
const ajvOptionsNotStrictMode = {
strictTypes: false, // recommended : true
strictTuples: false, // recommended : true
allowMatchingProperties: true, // recommended : false
}
const ajvOptionsStrictMode = {
strict: true,
}
const ajvOptions = fullStrictMode
? ajvOptionsStrictMode
: ajvOptionsNotStrictMode
// Stand-alone code need some special options parameters
if (standAloneCode) {
ajvOptions.code = { source: true }
if (standAloneCodeWithMultipleSchema.length) {
ajvOptions.schemas = standAloneCodeWithMultipleSchema
}
}
let ajvSelected
// There are multiple AJV version for each $schema version.
// Create the correct one.
switch (schemaName) {
case 'draft-04':
ajvSelected = new AjvDraft04(ajvOptions)
break
case 'draft-06':
case 'draft-07':
ajvSelected = new AjvDraft06And07(ajvOptions)
if (schemaName === 'draft-06') {
ajvSelected.addMetaSchema(AjvDraft06SchemaJson)
} else {
// 'draft-07' have additional format
ajvFormatsDraft2019(ajvSelected)
}
break
case '2019-09':
ajvSelected = new Ajv2019(ajvOptions)
ajvFormatsDraft2019(ajvSelected)
break
case '2020-12':
ajvSelected = new Ajv2020(ajvOptions)
ajvFormatsDraft2019(ajvSelected)
break
default:
ajvSelected = new AjvDraft04(ajvOptions)
}
// addFormats() and addFormat() to the latest AJV version
addFormats(ajvSelected)
unknownFormatsList.forEach((x) => {
ajvSelected.addFormat(x, true)
})
return ajvSelected
}
/**
* @typedef {Object} getOptionReturn
* @prop {string[]} unknownFormatsList
* @prop {string[]} externalSchemaWithPathList
* @prop {string[]} unknownKeywordsList
*/
/**
* Get the option items for this specific jsonName
* @param {string} jsonName
* @returns {getOptionReturn}
*/
function getOption(jsonName) {
const options = schemaValidation.options[jsonName]
// collect the unknownFormat list
const unknownFormatsList = options?.unknownFormat ?? []
// collect the unknownKeywords list
const unknownKeywordsList = options?.unknownKeywords ?? []
// collect the externalSchema list
const externalSchemaList = options?.externalSchema ?? []
const externalSchemaWithPathList = externalSchemaList?.map(
(schemaFileName) => {
return path.resolve('.', schemaDir, schemaFileName)
},
)
// return all the collected values
return {
unknownFormatsList,
unknownKeywordsList,
externalSchemaWithPathList,
}
}
function ajv() {
const schemaVersion = showSchemaVersions()
const textCompile = 'compile | '
const textPassSchema = 'pass schema | '
const textPositivePassTest = 'pass positive test | '
const textPositiveFailedTest = 'failed positive test | '
const textNegativePassTest = 'pass negative test | '
const textNegativeFailedTest = 'failed negative test | '
let validate
let countSchema = 0
const processSchemaFile = (/** @type {Schema} */ schema) => {
let ajvSelected
// Get possible options define in schema-validation.json
const {
unknownFormatsList,
unknownKeywordsList,
externalSchemaWithPathList,
} = getOption(schema.jsonName)
// Start validate the JSON schema
let schemaJson
let versionObj
let schemaVersionStr = 'unknown'
// const fullStrictMode = schemaValidation.ajvFullStrictMode.includes(schema.jsonName)
// The SchemaStore default mode is full Strict Mode. Not in the list => full strict mode
const fullStrictMode = !schemaValidation.ajvNotStrictMode.includes(
schema.jsonName,
)
const fullStrictModeStr = fullStrictMode
? '(FullStrictMode)'
: '(NotStrictMode)'
try {
// select the correct AJV object for this schema
schemaJson = schema.jsonObj
versionObj = schemaVersion.getObj(schemaJson)
// Get the correct AJV version
ajvSelected = factoryAJV({
schemaName: versionObj?.schemaName,
unknownFormatsList,
fullStrictMode,
})
// AJV must ignore these keywords
unknownKeywordsList?.forEach((x) => {
ajvSelected.addKeyword(x)
})
// Add external schema to AJV
externalSchemaWithPathList.forEach((x) => {
ajvSelected.addSchema(require(x.toString()))
})
// What schema draft version is it?
schemaVersionStr = versionObj ? versionObj.schemaName : 'unknown'
// compile the schema
validate = ajvSelected.compile(schemaJson)
} catch (err) {
throwWithErrorText([
`${textCompile}${schema.urlOrFilePath} (${schemaVersionStr})${fullStrictModeStr}`,
err,
])
}
countSchema++
grunt.log.writeln()
grunt.log.ok(
`${textPassSchema}${schema.urlOrFilePath} (${schemaVersionStr})${fullStrictModeStr}`,
)
}
const processTestFile = (schema, success, failure) => {
validate(schema.jsonObj) ? success() : failure()
}
const processPositiveTestFile = (/** @type {Schema} */ schema) => {
processTestFile(
schema,
() => {
grunt.log.ok(`${textPositivePassTest}${schema.urlOrFilePath}`)
},
() => {
throwWithErrorText([
`${textPositiveFailedTest}${schema.urlOrFilePath}`,
`(Schema file) keywordLocation: ${validate.errors[0].schemaPath}`,
`(Test file) instanceLocation: ${validate.errors[0].instancePath}`,
`(Message) ${validate.errors[0].message}`,
'Error in positive test.',
])
},
)
}
const processNegativeTestFile = (/** @type {Schema} */ schema) => {
processTestFile(
schema,
() => {
throwWithErrorText([
`${textNegativeFailedTest}${schema.urlOrFilePath}`,
'Negative test must always fail.',
])
},
() => {
// must show log as single line
// const path = validate.errors[0].instancePath
let text = ''
text = text.concat(`${textNegativePassTest}${schema.urlOrFilePath}`)
text = text.concat(` (Schema: ${validate.errors[0].schemaPath})`)
text = text.concat(` (Test: ${validate.errors[0].instancePath})`)
text = text.concat(` (Message): ${validate.errors[0].message})`)
grunt.log.ok(text)
},
)
}
const processSchemaFileDone = () => {
grunt.log.writeln()
grunt.log.writeln(`Total schemas validated with AJV: ${countSchema}`)
countSchema = 0
}
return {
testSchemaFile: processSchemaFile,
testSchemaFileDone: processSchemaFileDone,
positiveTestFile: processPositiveTestFile,
negativeTestFile: processNegativeTestFile,
}
}
grunt.registerTask(
'new_schema',
'Create a new schemas and associated files',
async function () {
const done = this.async()
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
console.log('Enter the name of the schema (without .json extension)')
/** @type {string} */
let schemaName
do {
schemaName = await rl.question('input: ')
} while (schemaName.endsWith('.json'))
const schemaFile = path.join(schemaDir, schemaName + '.json')
const testDir = path.join(testPositiveDir, schemaName)
const testFile = path.join(testDir, `${schemaName}.json`)
if (fs.existsSync(schemaFile)) {
throw new Error(`Schema file already exists: ${schemaFile}`)
}
console.info(`Creating schema file at 'src/${schemaFile}'...`)
console.info(`Creating positive test file at 'src/${testFile}'...`)
await fs.promises.mkdir(path.dirname(schemaFile), { recursive: true })
await fs.promises.writeFile(
schemaFile,
`{
"$id": "https://json.schemastore.org/${schemaName}.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": true,
"properties": {
},
"type": "object"
}\n`,
)
await fs.promises.mkdir(testDir, { recursive: true })
await fs.promises.writeFile(
testFile,
`"Replace this file with an example/test that passes schema validation. Supported formats are JSON, YAML, and TOML. We recommend adding as many files as possible to make your schema most robust."\n`,
)
console.info(`Please add the following to 'src/api/json/catalog.json':
{
"name": "",
"description": "",
"fileMatch": ["${schemaName}.yml", "${schemaName}.yaml"],
"url": "https://json.schemastore.org/${schemaName}.json"
}`)
done()
},
)
grunt.registerTask(
'local_lint_schema_has_correct_metadata',
'Check that metadata fields like "$id" are correct.',
function () {
let countScan = 0
let totalMismatchIds = 0
let totalIncorrectIds = 0
localSchemaFileAndTestFile(
{
schemaOnlyScan(schema) {
countScan++
/**
* Old JSON Schema specification versions use the "id" key for unique
* identifiers, rather than "$id". See for details:
* https://json-schema.org/understanding-json-schema/basics.html#declaring-a-unique-identifier
*/
const schemasWithDollarlessId = [
'http://json-schema.org/draft-03/schema#',
'http://json-schema.org/draft-04/schema#',
]
if (schemasWithDollarlessId.includes(schema.jsonObj.$schema)) {
if (schema.jsonObj.$id) {
grunt.log.warn(
`Bad property of '$id'; expected 'id' for this schema version`,
)
++totalMismatchIds
return
}
if (
schema.jsonObj.id !==
`https://json.schemastore.org/${schema.jsonName}`
) {
grunt.log.warn(
`Incorrect property 'id' for schema 'src/schemas/json/${schema.jsonName}'`,
)
console.warn(
` expected value: https://json.schemastore.org/${schema.jsonName}`,
)
console.warn(` found value : ${schema.jsonObj.id}`)
++totalIncorrectIds
}
} else {
if (schema.jsonObj.id) {
grunt.log.warn(
`Bad property of 'id'; expected '$id' for this schema version`,
)
++totalMismatchIds
return
}
if (
schema.jsonObj.$id !==
`https://json.schemastore.org/${schema.jsonName}`
) {
grunt.log.warn(
`Incorrect property '$id' for schema 'src/schemas/json/${schema.jsonName}'`,
)
console.warn(
` expected value: https://json.schemastore.org/${schema.jsonName}`,
)
console.warn(` found value : ${schema.jsonObj.$id}`)
++totalIncorrectIds
}
}
},
},
{
fullScanAllFiles: true,
skipReadFile: false,
},
)
grunt.log.ok(`Total mismatched ids: ${totalMismatchIds}`)
grunt.log.ok(`Total incorrect ids: ${totalIncorrectIds}`)
grunt.log.ok(`Total files scan: ${countScan}`)
},
)
grunt.registerTask(
'lint_schema_no_smart_quotes',
'Check that local schemas have no smart quotes',
function () {
let countScan = 0
localSchemaFileAndTestFile(
{
schemaOnlyScan(schema) {
countScan++
const buffer = schema.rawFile
const bufferArr = buffer.toString().split('\n')
for (let i = 0; i < bufferArr.length; ++i) {
const line = bufferArr[i]
const smartQuotes = ['‘', '’', '“', '”']
for (const quote of smartQuotes) {
if (line.includes(quote)) {
grunt.log.error(
`Schema file should not have a smart quote: ${
schema.urlOrFilePath
}:${++i}`,
)
}
}
}
},
},
{ fullScanAllFiles: true, skipReadFile: false },
)
grunt.log.writeln(`Total files scan: ${countScan}`)
},
)
grunt.registerTask(
'local_assert_catalog.json_no_poorly_worded_fields',
'Check that catalog.json entries do not contain the word "schema" or "json"',
function () {
let countScan = 0
for (const entry of catalog.schemas) {
if (
schemaValidation.catalogEntryNoLintNameOrDescription.includes(
entry.url,
)
) {
continue
}
const schemaName = new URL(entry.url).pathname.slice(1)
for (const property of ['name', 'description']) {
if (
/$[,. \t-]/u.test(entry?.[property]) ||
/[,. \t-]$/u.test(entry?.[property])
) {
++countScan
throwWithErrorText([
`Catalog entry .${property}: Should not start or end with punctuation or whitespace (${schemaName})`,
])
}
}
for (const property of ['name', 'description']) {
if (entry?.[property]?.toLowerCase()?.includes('schema')) {
++countScan
throwWithErrorText([
`Catalog entry .${property}: Should not contain the string 'schema'. In most cases, this word is extraneous and the meaning is implied (${schemaName})`,
])
}
}
for (const property of ['name', 'description']) {
if (entry?.[property]?.toLowerCase()?.includes('\n')) {
++countScan
throwWithErrorText([
`Catalog entry .${property}: Should not contain a newline character. In editors like VSCode, the newline is not rendered. (${schemaName})`,
])
}
}
}
grunt.log.writeln(`Total found files: ${countScan}`)
},
)
grunt.registerTask(
'local_test_ajv',
'Use AJV to validate local schemas in ./test/',
function () {
const x = ajv()
localSchemaFileAndTestFile(
{
schemaForTestScan: x.testSchemaFile,
positiveTestScan: x.positiveTestFile,
negativeTestScan: x.negativeTestFile,
schemaForTestScanDone: x.testSchemaFileDone,
},
{ skipReadFile: false },
)
grunt.log.ok('local AJV schema passed')
},
)
grunt.registerTask(
'remote_test_ajv',
'Use AJV to validate remote schemas',
async function () {
const done = this.async()
const x = ajv()
let countScan = 0
await remoteSchemaFile((testSchemaFile) => {
x.testSchemaFile(testSchemaFile)
countScan++
})
grunt.log.writeln()
grunt.log.writeln(`Total schemas validated with AJV: ${countScan}`)
done()
},
)
grunt.registerTask(
'local_assert_schema_no_bom',
'Check that local schema files do not have a BOM (Byte Order Mark)',
function () {
let countScan = 0
localSchemaFileAndTestFile(
{
schemaOnlyScan(schema) {
countScan++
testSchemaFileForBOM(schema)
},
},
{ fullScanAllFiles: true, skipReadFile: false },
)
grunt.log.ok(
`no BOM file found in all schema files. Total files scan: ${countScan}`,
)
},
)
grunt.registerTask(
'remote_assert_schema_no_bom',
'Check that remote schema files do not have a BOM (Byte Order Mark)',
async function () {
const done = this.async()
await remoteSchemaFile(testSchemaFileForBOM, false)
done()
},
)
grunt.registerTask(
'local_assert_catalog.json_passes_jsonlint',
'Check that catalog.json passes jsonlint',
function () {
jsonlint.parse(fs.readFileSync('./src/api/json/catalog.json', 'utf-8'), {
ignoreBOM: false,
ignoreComments: false,
ignoreTrailingCommas: false,
allowSingleQuotedStrings: false,
allowDuplicateObjectKeys: false,
})
},
)
grunt.registerTask(
'local_assert_catalog.json_validates_against_json_schema',
'Check that the catalog.json file passes schema validation',
function () {
const catalogSchema = require(
path.resolve('.', schemaDir, 'schema-catalog.json'),
)
const ajvInstance = factoryAJV({ schemaName: 'draft-04' })
if (ajvInstance.validate(catalogSchema, catalog)) {
grunt.log.ok('catalog.json OK')
} else {
throwWithErrorText([
`(Schema file) keywordLocation: ${ajvInstance.errors[0].schemaPath}`,
`(Catalog file) instanceLocation: ${ajvInstance.errors[0].instancePath}`,
`(message) instanceLocation: ${ajvInstance.errors[0].message}`,
'"Catalog ERROR"',
])
}
},
)
grunt.registerTask(