1 | 'use strict';
|
2 | const getDocumentationUrl = require('./utils/get-documentation-url');
|
3 |
|
4 | const regexp = /^(?<package>@.*?\/.*?|[./]+?.*?)\/(?:\.|(?:index(?:\.js)?))?$/;
|
5 | const isImportingIndex = value => regexp.test(value);
|
6 | const normalize = value => value.replace(regexp, '$<package>');
|
7 |
|
8 | const importIndex = (context, node, argument) => {
|
9 | if (argument && isImportingIndex(argument.value)) {
|
10 | context.report({
|
11 | node,
|
12 | message: 'Do not reference the index file directly.',
|
13 | fix: fixer => fixer.replaceText(argument, `'${normalize(argument.value)}'`)
|
14 | });
|
15 | }
|
16 | };
|
17 |
|
18 | const create = context => {
|
19 | const options = context.options[0] || {};
|
20 |
|
21 | const rules = {
|
22 | 'CallExpression[callee.name="require"]': node => importIndex(context, node, node.arguments[0])
|
23 | };
|
24 |
|
25 | if (!options.ignoreImports) {
|
26 | rules.ImportDeclaration = node => importIndex(context, node, node.source);
|
27 | }
|
28 |
|
29 | return rules;
|
30 | };
|
31 |
|
32 | const schema = [
|
33 | {
|
34 | type: 'object',
|
35 | properties: {
|
36 | ignoreImports: {
|
37 | type: 'boolean',
|
38 | default: false
|
39 | }
|
40 | },
|
41 | additionalProperties: false
|
42 | }
|
43 | ];
|
44 |
|
45 | module.exports = {
|
46 | create,
|
47 | meta: {
|
48 | type: 'suggestion',
|
49 | docs: {
|
50 | url: getDocumentationUrl(__filename)
|
51 | },
|
52 | schema,
|
53 | fixable: 'code'
|
54 | }
|
55 | };
|