UNPKG

2.68 kBJavaScriptView Raw
1/**
2 * @fileoverview Restrict usage of specified node imports.
3 * @author Guy Ellis
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11const ignore = require("ignore");
12
13const arrayOfStrings = {
14 type: "array",
15 items: {
16 type: "string"
17 },
18 uniqueItems: true
19};
20
21module.exports = {
22 meta: {
23 docs: {
24 description: "disallow specified modules when loaded by `import`",
25 category: "ECMAScript 6",
26 recommended: false
27 },
28
29 schema: {
30 anyOf: [
31 arrayOfStrings,
32 {
33 type: "array",
34 items: [{
35 type: "object",
36 properties: {
37 paths: arrayOfStrings,
38 patterns: arrayOfStrings
39 },
40 additionalProperties: false
41 }],
42 additionalItems: false
43 }
44 ]
45 }
46 },
47
48 create(context) {
49 const options = Array.isArray(context.options) ? context.options : [];
50 const isStringArray = typeof options[0] !== "object";
51 const restrictedPaths = new Set(isStringArray ? context.options : options[0].paths || []);
52 const restrictedPatterns = isStringArray ? [] : options[0].patterns || [];
53
54 // if no imports are restricted we don"t need to check
55 if (restrictedPaths.size === 0 && restrictedPatterns.length === 0) {
56 return {};
57 }
58
59 const ig = ignore().add(restrictedPatterns);
60
61 return {
62 ImportDeclaration(node) {
63 if (node && node.source && node.source.value) {
64
65 const importName = node.source.value.trim();
66
67 if (restrictedPaths.has(importName)) {
68 context.report({
69 node,
70 message: "'{{importName}}' import is restricted from being used.",
71 data: { importName }
72 });
73 }
74 if (restrictedPatterns.length > 0 && ig.ignores(importName)) {
75 context.report({
76 node,
77 message: "'{{importName}}' import is restricted from being used by a pattern.",
78 data: { importName }
79 });
80 }
81 }
82 }
83 };
84 }
85};