-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
no-invalid.ts
586 lines (545 loc) · 17.3 KB
/
no-invalid.ts
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
import type { AST as JSONAST } from "jsonc-eslint-parser";
import { getStaticJSONValue } from "jsonc-eslint-parser";
import type { AST as YAML } from "yaml-eslint-parser";
import { getStaticYAMLValue } from "yaml-eslint-parser";
import type { AST as TOML } from "toml-eslint-parser";
import { getStaticTOMLValue } from "toml-eslint-parser";
import { createRule } from "../utils";
import minimatch from "minimatch";
import path from "path";
import type { PathData } from "../utils/ast";
import {
getJSONNodeFromPath,
getYAMLNodeFromPath,
getTOMLNodeFromPath,
analyzeJsAST,
} from "../utils/ast";
import { loadJson, loadSchema } from "../utils/schema";
import type { RuleContext } from "../types";
import type { NodeData } from "../utils/ast/common";
import type {
ESLintAssignmentExpression,
ESLintExportDefaultDeclaration,
ESLintExpression,
} from "vue-eslint-parser/ast";
import type { ValidateError, Validator } from "../utils/validator-factory";
import { compile } from "../utils/validator-factory";
import type { SchemaObject } from "../utils/types";
import fs from "fs";
import { getCwd, getFilename, getSourceCode } from "../utils/compat";
const CATALOG_URL = "https://www.schemastore.org/api/json/catalog.json";
/**
* Checks if match file
*/
function matchFile(filename: string, fileMatch: string[]) {
return (
fileMatch.includes(path.basename(filename)) ||
fileMatch.some((fm) => minimatch(filename, fm, { dot: true }))
);
}
/**
* Generate validator from schema path
*/
function schemaPathToValidator(
schemaPath: string,
context: RuleContext,
): Validator | null {
const schema = loadSchema(schemaPath, context);
if (!schema) {
return null;
}
return compile(schema, schemaPath, context);
}
/**
* Generate validator from schema object
*/
function schemaObjectToValidator(
schema: SchemaObject | null,
context: RuleContext,
): Validator | null {
if (!schema) {
return null;
}
const schemaPath = getCwd(context);
return compile(schema, schemaPath, context);
}
/**
* Report for cannot resolved schema path
*/
function reportCannotResolvedPath(schemaPath: string, context: RuleContext) {
context.report({
loc: { line: 1, column: 0 },
message: `Specified schema could not be resolved. Path: "${schemaPath}"`,
});
}
/**
* Report for cannot resolved schema object
*/
function reportCannotResolvedObject(context: RuleContext) {
context.report({
loc: { line: 1, column: 0 },
message: `Specified schema could not be resolved.`,
});
}
type SchemaKind = "$schema" | "catalog" | "options";
const SCHEMA_KINDS: SchemaKind[] = ["$schema", "options", "catalog"];
/** Get mergeSchemas option */
function parseMergeSchemasOption(
option: boolean | string[] | undefined,
): SchemaKind[] | null {
return option === true
? SCHEMA_KINDS
: Array.isArray(option)
? [...(option as SchemaKind[])].sort(
(a, b) => SCHEMA_KINDS.indexOf(a) - SCHEMA_KINDS.indexOf(b),
)
: null;
}
export default createRule("no-invalid", {
meta: {
docs: {
description: "validate object with JSON Schema.",
categories: ["recommended"],
default: "warn",
},
fixable: undefined,
schema: [
{
oneOf: [
{ type: "string" },
{
type: "object",
properties: {
schemas: {
type: "array",
items: {
type: "object",
properties: {
name: { type: "string" },
description: { type: "string" },
fileMatch: {
type: "array",
items: { type: "string" },
minItems: 1,
},
schema: { type: ["object", "string"] },
},
additionalProperties: true, // It also accepts unrelated properties.
required: ["fileMatch", "schema"],
},
},
useSchemastoreCatalog: { type: "boolean" },
mergeSchemas: {
oneOf: [
{ type: "boolean" },
{
type: "array",
items: {
type: "string",
enum: ["$schema", "catalog", "options"],
},
minItems: 2,
uniqueItems: true,
},
],
},
},
additionalProperties: false,
},
],
},
],
messages: {},
type: "suggestion",
},
create(context, { filename }) {
const sourceCode = getSourceCode(context);
const cwd = getCwd(context);
const relativeFilename = filename.startsWith(cwd)
? path.relative(cwd, filename)
: filename;
const validator = createValidator(context, relativeFilename);
if (!validator) {
return {};
}
let existsExports = false;
/**
* Validate JSON Schema
*/
function validateData(
data: unknown,
resolveLoc: (error: ValidateError) => JSONAST.SourceLocation | null,
) {
const errors = validator!(data);
for (const error of errors) {
const loc = resolveLoc(error);
if (!loc) {
// Ignore
continue;
}
context.report({
loc,
message: error.message,
});
}
}
/**
* Validate JS Object
*/
function validateJSExport(
node: ESLintExpression,
rootRange: [number, number],
) {
if (existsExports) {
return;
}
existsExports = true;
const data = analyzeJsAST(node, rootRange, context);
if (data == null) {
return;
}
validateData(data.object, (error) => {
let target: PathData | undefined = data.pathData;
for (const p of error.path) {
const next = target?.children.get(p);
target = typeof next === "symbol" ? undefined : next;
}
const key = target?.key;
const range = typeof key === "function" ? key(sourceCode) : key;
if (!range) {
return null;
}
return {
start: sourceCode.getLocFromIndex(range[0]),
end: sourceCode.getLocFromIndex(range[1]),
};
});
}
/** Find schema path from program */
function findSchemaPathFromJSON(node: JSONAST.JSONProgram) {
const rootExpr = node.body[0].expression;
if (rootExpr.type !== "JSONObjectExpression") {
return null;
}
for (const prop of rootExpr.properties) {
if (
prop.computed ||
(prop.key.type === "JSONIdentifier"
? prop.key.name
: prop.key.value) !== "$schema"
) {
continue;
}
return getStaticJSONValue(prop.value);
}
return null;
}
return {
Program(node) {
if (sourceCode.parserServices.isJSON) {
const program = node as JSONAST.JSONProgram;
validateData(getStaticJSONValue(program), (error) => {
return errorDataToLoc(getJSONNodeFromPath(program, error.path));
});
} else if (sourceCode.parserServices.isYAML) {
const program = node as YAML.YAMLProgram;
validateData(getStaticYAMLValue(program), (error) => {
return errorDataToLoc(getYAMLNodeFromPath(program, error.path));
});
} else if (sourceCode.parserServices.isTOML) {
const program = node as TOML.TOMLProgram;
validateData(getStaticTOMLValue(program), (error) => {
return errorDataToLoc(getTOMLNodeFromPath(program, error.path));
});
}
},
ExportDefaultDeclaration(node: ESLintExportDefaultDeclaration) {
if (
node.declaration.type === "FunctionDeclaration" ||
node.declaration.type === "ClassDeclaration" ||
node.declaration.type === "VariableDeclaration"
) {
return;
}
const defaultToken = sourceCode.getTokenBefore(node.declaration)!;
validateJSExport(node.declaration, [
node.range[0],
defaultToken.range![1],
]);
},
AssignmentExpression(node: ESLintAssignmentExpression) {
if (
// exports = {}
(node.left.type === "Identifier" && node.left.name === "exports") ||
// module.exports = {}
(node.left.type === "MemberExpression" &&
node.left.object.type === "Identifier" &&
node.left.object.name === "module" &&
node.left.computed === false &&
node.left.property.type === "Identifier" &&
node.left.property.name === "exports")
) {
validateJSExport(node.right, node.left.range);
}
},
};
/**
* ErrorData to report location.
*/
function errorDataToLoc(
errorData: NodeData<JSONAST.JSONNode | YAML.YAMLNode | TOML.TOMLNode>,
) {
if (errorData.key) {
const range = errorData.key(sourceCode);
return {
start: sourceCode.getLocFromIndex(range[0]),
end: sourceCode.getLocFromIndex(range[1]),
};
}
return errorData.value.loc;
}
/** Find schema path from program */
function findSchemaPathFromYAML(node: YAML.YAMLProgram) {
const rootExpr = node.body[0]?.content;
if (!rootExpr || rootExpr.type !== "YAMLMapping") {
return null;
}
for (const pair of rootExpr.pairs) {
if (
!pair.key ||
!pair.value ||
pair.key.type !== "YAMLScalar" ||
pair.key.value !== "$schema"
) {
continue;
}
return getStaticYAMLValue(pair.value);
}
return null;
}
/** Find schema path from program */
function findSchemaPathFromTOML(node: TOML.TOMLProgram) {
const rootExpr = node.body[0];
for (const body of rootExpr.body) {
if (body.type !== "TOMLKeyValue" || body.key.keys.length !== 1) {
continue;
}
const keyNode = body.key.keys[0];
const key = keyNode.type === "TOMLBare" ? keyNode.name : keyNode.value;
if (key !== "$schema") {
continue;
}
return getStaticTOMLValue(body.value);
}
return null;
}
/** Find schema path from program */
function findSchemaPath(node: unknown) {
let $schema = null;
if (sourceCode.parserServices.isJSON) {
const program = node as JSONAST.JSONProgram;
$schema = findSchemaPathFromJSON(program);
} else if (sourceCode.parserServices.isYAML) {
const program = node as YAML.YAMLProgram;
$schema = findSchemaPathFromYAML(program);
} else if (sourceCode.parserServices.isTOML) {
const program = node as TOML.TOMLProgram;
$schema = findSchemaPathFromTOML(program);
}
return typeof $schema === "string"
? $schema.startsWith(".")
? path.resolve(
path.dirname(
typeof context.getPhysicalFilename === "function"
? context.getPhysicalFilename()
: getPhysicalFilename(getFilename(context)),
),
$schema,
)
: $schema
: null;
}
/** Validator from $schema */
function get$SchemaValidators(context: RuleContext): Validator[] | null {
const $schemaPath = findSchemaPath(sourceCode.ast);
if (!$schemaPath) return null;
const validator = schemaPathToValidator($schemaPath, context);
if (!validator) {
reportCannotResolvedPath($schemaPath, context);
return null;
}
return [validator];
}
/** Validator from catalog.json */
function getCatalogValidators(
context: RuleContext,
relativeFilename: string,
): Validator[] | null {
const option = context.options[0] || {};
const useSchemastoreCatalog = option.useSchemastoreCatalog !== false;
if (!useSchemastoreCatalog) {
return null;
}
interface ISchema {
name?: string;
description?: string;
fileMatch: string[];
url: string;
}
const catalog = loadJson<{ schemas: ISchema[] }>(CATALOG_URL, context);
if (!catalog) {
return null;
}
const validators: Validator[] = [];
for (const schemaData of catalog.schemas) {
if (!schemaData.fileMatch) {
continue;
}
// Exclude schemas with patterns that match all json files.
// https://github.com/SchemaStore/schemastore/pull/3291
if (schemaData.fileMatch.some((s) => /^\*\.json$/u.test(s))) {
continue;
}
if (!matchFile(relativeFilename, schemaData.fileMatch)) {
continue;
}
const validator = schemaPathToValidator(schemaData.url, context);
if (validator) validators.push(validator);
}
return validators.length ? validators : null;
}
/** Validator from options.schemas */
function getOptionsValidators(
context: RuleContext,
filename: string,
): Validator[] | null {
const option = context.options[0];
if (typeof option === "string") {
const validator = schemaPathToValidator(option, context);
return validator ? [validator] : null;
}
if (typeof option !== "object" || !Array.isArray(option.schemas)) {
return null;
}
const validators: Validator[] = [];
for (const schemaData of option.schemas) {
if (!matchFile(filename, schemaData.fileMatch)) {
continue;
}
if (typeof schemaData.schema === "string") {
const validator = schemaPathToValidator(schemaData.schema, context);
if (validator) {
validators.push(validator);
} else {
reportCannotResolvedPath(schemaData.schema, context);
}
} else {
const validator = schemaObjectToValidator(schemaData.schema, context);
if (validator) {
validators.push(validator);
} else {
reportCannotResolvedObject(context);
}
}
}
return validators.length ? validators : null;
}
/** Create combined validator */
function createValidator(context: RuleContext, filename: string) {
const mergeSchemas = parseMergeSchemasOption(
context.options[0]?.mergeSchemas,
);
const validatorsCtx = createValidatorsContext(context, filename);
if (mergeSchemas && mergeSchemas.some((kind) => validatorsCtx[kind])) {
const validators: Validator[] = [];
for (const kind of mergeSchemas) {
const v = validatorsCtx[kind];
if (v) validators.push(...v);
}
return margeValidators(validators);
}
const validators =
validatorsCtx.$schema || validatorsCtx.options || validatorsCtx.catalog;
if (!validators) {
return null;
}
return margeValidators(validators);
/** Marge validators */
function margeValidators(validators: Validator[]) {
return (data: unknown) =>
validators.reduce(
(errors, validator) => [...errors, ...validator(data)],
[] as ValidateError[],
);
}
}
/** Creates validators context */
function createValidatorsContext(context: RuleContext, filename: string) {
type Cache = { validators: Validator[] | null };
let $schema: Cache | null = null;
let options: Cache | null = null;
let catalog: Cache | null = null;
/**
* Get a validator. Returns the value of the cache if there is one.
* If there is no cache, cache and return the value obtained from the supplier function
*/
function get(
cache: Cache | null,
setCache: (c: Cache) => void,
supplier: () => Validator[] | null,
) {
if (cache) {
return cache.validators;
}
const v = supplier();
setCache({ validators: v });
return v;
}
return {
get $schema() {
return get(
$schema,
(c) => ($schema = c),
() => get$SchemaValidators(context),
);
},
get options() {
return get(
options,
(c) => (options = c),
() => getOptionsValidators(context, filename),
);
},
get catalog() {
return get(
catalog,
(c) => (catalog = c),
() => getCatalogValidators(context, filename),
);
},
};
}
},
});
/**
* ! copied from https://github.com/mdx-js/eslint-mdx/blob/b97db2e912a416d5d40ddb78ab6c9fa1ab150c17/packages/eslint-mdx/src/helpers.ts#L28-L50
*
* Given a filepath, get the nearest path that is a regular file.
* The filepath provided by eslint may be a virtual filepath rather than a file
* on disk. This attempts to transform a virtual path into an on-disk path
*/
function getPhysicalFilename(filename: string, child?: string): string {
try {
if (fs.statSync(filename).isDirectory()) {
return child || filename;
}
} catch (err) {
const { code } = err as { code: string };
// https://github.com/eslint/eslint/issues/11989
// Additionally, it seems there is no `ENOTDIR` code on Windows...
if (code === "ENOTDIR" || code === "ENOENT") {
return getPhysicalFilename(path.dirname(filename), filename);
}
}
return filename;
}