-
Notifications
You must be signed in to change notification settings - Fork 743
/
validate.js
468 lines (433 loc) · 11 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
/*eslint-env node */
'use strict';
var revalidator = require('revalidator').validate,
fs = require('fs'),
path = require('path');
function fileExists(v, o) {
if (!v.endsWith('.js')) {
return true;
}
var file = path.resolve(path.dirname(o._path), v);
var exists;
try {
exists = fs.existsSync(file);
} catch (e) {
return false;
}
return exists;
}
function hasUniqueId() {
var seen = {};
return function (v, o) {
if (!seen[v]) {
seen[v] = o;
return true;
}
return false;
};
}
function hasMultipleOutcomes(messages) {
const keys = Object.keys(messages);
if (keys.length < 2) {
return false;
}
return keys.every(key => {
switch (key) {
case 'pass':
case 'fail':
case 'incomplete':
return ['string', 'object'].includes(typeof messages[key]);
default:
return false;
}
});
}
function createSchemas() {
var schemas = {};
schemas.tool = {
properties: {
id: {
required: true,
type: 'string',
conform: hasUniqueId()
},
options: {
type: 'object'
},
source: {
type: 'string',
required: true,
conform: fileExists,
messages: {
conform: 'File does not exist'
}
}
}
};
schemas.check = {
properties: {
id: {
required: true,
type: 'string',
conform: hasUniqueId()
},
excludeHidden: {
type: 'boolean'
},
evaluate: {
type: 'string',
required: true,
conform: fileExists,
messages: {
conform: 'File does not exist'
}
},
matches: {
type: 'string',
required: false,
conform: fileExists,
messages: {
conform: 'File does not exist'
}
},
metadata: {
type: 'object',
required: true,
properties: {
messages: {
required: true,
type: 'object',
conform: hasMultipleOutcomes,
messages: {
conform: 'Must have at least two valid messages'
}
},
impact: {
required: true,
type: 'string',
enum: ['minor', 'moderate', 'serious', 'critical']
}
}
}
}
};
schemas.rule = {
seen: {},
properties: {
id: {
required: true,
type: 'string',
conform: hasUniqueId()
},
selector: {
type: 'string'
},
impact: {
type: 'string',
enum: ['minor', 'moderate', 'serious', 'critical']
},
excludeHidden: {
type: 'boolean'
},
enabled: {
type: 'boolean'
},
pageLevel: {
type: 'boolean'
},
any: {
type: 'array',
items: {
type: ['string', 'object'],
conform: function (v) {
if (typeof v === 'string') {
return true;
}
if (typeof v === 'object' && typeof v.id === 'string') {
return true;
}
return false;
},
message: 'must be a string or an object with a key of id'
}
},
all: {
type: 'array',
items: {
type: ['string', 'object'],
conform: function (v) {
if (typeof v === 'string') {
return true;
}
if (typeof v === 'object' && typeof v.id === 'string') {
return true;
}
return false;
},
message: 'must be a string or an object with a key of id'
}
},
none: {
type: 'array',
items: {
type: ['string', 'object'],
conform: function (v) {
if (typeof v === 'string') {
return true;
}
if (typeof v === 'object' && typeof v.id === 'string') {
return true;
}
return false;
},
message: 'must be a string or an object with a key of id'
}
},
tags: {
type: 'array',
items: {
type: 'string'
}
},
actIds: {
type: 'array',
items: {
type: 'string'
}
},
matches: {
type: 'string',
required: false,
conform: fileExists,
messages: {
conform: 'File does not exist'
}
},
metadata: {
type: 'object',
required: true,
additionalProperties: false,
properties: {
help: {
required: true,
type: 'string'
},
description: {
required: true,
type: 'string'
}
}
}
}
};
return schemas;
}
function validateFiles(grunt, files, schema, type) {
var valid = true;
files.forEach(function (f) {
f.src.forEach(function (pathArg) {
var file = grunt.file.readJSON(pathArg);
file._path = pathArg;
var result = revalidator(file, schema);
if (!result.valid) {
result.errors.forEach(function (err) {
grunt.log.error(pathArg, err.property + ' ' + err.message);
});
valid = false;
}
const ruleIssues = type === 'rule' ? validateRule(file) : [];
if (ruleIssues.length > 0) {
ruleIssues.forEach(issue => grunt.log.error(pathArg, issue));
valid = false;
}
if (valid) {
grunt.verbose.ok();
}
});
});
return valid;
}
module.exports = function (grunt) {
grunt.registerMultiTask(
'validate',
'Task for validating API schema for checks and rules',
function () {
const { type } = this.options();
const schemas = createSchemas();
const schema = schemas[type];
if (!schema) {
grunt.log.error(
'Please specify a valid type to validate: ' + Object.keys(schemas)
);
return false;
}
const valid = validateFiles(grunt, this.files, schema, type);
schema.seen = {};
return valid;
}
);
};
function validateRule({ tags, metadata }) {
if (!Array.isArray(tags) || typeof metadata !== 'object') {
return [];
}
const issues = [];
const prohibitedWord = tags.includes('best-practice') ? 'must' : 'should';
const { description, help } = metadata;
if (description.toLowerCase().includes(prohibitedWord)) {
issues.push(
`metadata.description can not contain the word '${prohibitedWord}'.`
);
}
if (help.toLowerCase().includes(prohibitedWord)) {
issues.push(`metadata.help can not contain the word '${prohibitedWord}'.`);
}
issues.push(...findTagIssues(tags));
return issues;
}
const miscTags = ['ACT', 'experimental', 'review-item', 'deprecated'];
const categories = [
'aria',
'color',
'forms',
'keyboard',
'language',
'name-role-value',
'parsing',
'semantics',
'sensory-and-visual-cues',
'structure',
'tables',
'text-alternatives',
'time-and-media'
];
const standardsTags = [
{
// Has to be first, as others rely on the WCAG level getting picked up first
name: 'WCAG',
standardRegex: /^wcag2(1|2)?a{1,3}(-obsolete)?$/,
criterionRegex: /^wcag\d{3,4}$/
},
{
name: 'Section 508',
standardRegex: /^section508$/,
criterionRegex: /^section508\.\d{1,2}\.[a-z]$/,
wcagLevelRegex: /^wcag2aa?$/
},
{
name: 'Trusted Tester',
standardRegex: /^TTv5$/,
criterionRegex: /^TT\d{1,3}\.[a-z]$/,
wcagLevelRegex: /^wcag2aa?$/
},
{
name: 'EN 301 549',
standardRegex: /^EN-301-549$/,
criterionRegex: /^EN-9\.[1-4]\.[1-9]\.\d{1,2}$/,
wcagLevelRegex: /^wcag21?aa?$/
}
];
function findTagIssues(tags) {
const issues = [];
const catTags = tags.filter(tag => tag.startsWith('cat.'));
const bestPracticeTags = tags.filter(tag => tag === 'best-practice');
// Category
if (catTags.length !== 1) {
issues.push(`Must have exactly one cat. tag, got ${catTags.length}`);
}
if (catTags.length && !categories.includes(catTags[0].slice(4))) {
issues.push(`Invalid category tag: ${catTags[0]}`);
}
if (!startsWith(tags, catTags)) {
issues.push(`Tag ${catTags[0]} must be before ${tags[0]}`);
}
tags = removeTags(tags, catTags);
// Best practice
if (bestPracticeTags.length > 1) {
issues.push(
`Only one best-practice tag is allowed, got ${bestPracticeTags.length}`
);
}
if (!startsWith(tags, bestPracticeTags)) {
issues.push(`Tag ${bestPracticeTags[0]} must be before ${tags[0]}`);
}
tags = removeTags(tags, bestPracticeTags);
const standards = {};
// WCAG, Section 508, Trusted Tester, EN 301 549
for (const {
name,
standardRegex,
criterionRegex,
wcagLevelRegex
} of standardsTags) {
const standardTags = tags.filter(tag => tag.match(standardRegex));
const criterionTags = tags.filter(tag => tag.match(criterionRegex));
if (!standardTags.length && !criterionTags.length) {
continue;
}
standards[name] = {
name,
standardTag: standardTags[0] ?? null,
criterionTags
};
if (bestPracticeTags.length !== 0) {
issues.push(`${name} tags cannot be used along side best-practice tag`);
}
if (standardTags.length === 0) {
issues.push(`Expected one ${name} tag, got 0`);
} else if (standardTags.length > 1) {
issues.push(`Expected one ${name} tag, got: ${standardTags.join(', ')}`);
}
if (criterionTags.length === 0) {
issues.push(`Expected at least one ${name} criterion tag, got 0`);
}
if (wcagLevelRegex) {
const wcagLevel = standards.WCAG.standardTag;
if (!wcagLevel.match(wcagLevelRegex)) {
issues.push(`${name} rules not allowed on ${wcagLevel}`);
}
}
// Must have the same criteria listed
if (name === 'EN 301 549') {
const wcagCriteria = standards.WCAG.criterionTags.map(tag =>
tag.slice(4)
);
const enCriteria = criterionTags.map(tag =>
tag.slice(5).replaceAll('.', '')
);
if (
wcagCriteria.length !== enCriteria.length ||
!startsWith(wcagCriteria, enCriteria)
) {
issues.push(
`Expect WCAG and EN criteria numbers to match: ${wcagCriteria.join(
', '
)} vs ${enCriteria.join(', ')}}`
);
}
}
tags = removeTags(tags, [...standardTags, ...criterionTags]);
}
// Other tags
const usedMiscTags = miscTags.filter(tag => tags.includes(tag));
const unknownTags = removeTags(tags, usedMiscTags);
if (unknownTags.length) {
issues.push(`Invalid tags: ${unknownTags.join(', ')}`);
}
// At this point only misc tags are left:
tags = removeTags(tags, unknownTags);
if (!startsWith(tags, usedMiscTags)) {
issues.push(
`Tags [${tags.join(', ')}] should be sorted like [${usedMiscTags.join(
', '
)}]`
);
}
return issues;
}
function startsWith(arr1, arr2) {
return arr2.every((item, i) => item === arr1[i]);
}
function removeTags(tags, tagsToRemove) {
return tags.filter(tag => !tagsToRemove.includes(tag));
}