| 1 |
module.exports = { |
| 2 |
meta: { |
| 3 |
type: "suggestion", |
| 4 |
docs: { |
| 5 |
description: "", |
| 6 |
}, |
| 7 |
fixable: "code", |
| 8 |
}, |
| 9 |
create(ctx) { |
| 10 |
return { |
| 11 |
ImportDeclaration(node) { |
| 12 |
const filename = ctx.getFilename(); |
| 13 |
const src = node.source.value; |
| 14 |
if ( |
| 15 |
|
| 16 |
(!src.includes("/lib/") && !src.startsWith("@babel/")) || |
| 17 |
|
| 18 |
src === "@babel/helper-plugin-test-runner" || |
| 19 |
|
| 20 |
src.startsWith("@babel/compat-data") || |
| 21 |
|
| 22 |
src.endsWith(".cjs") || |
| 23 |
|
| 24 |
/^@babel\/(plugin|preset)-/.test(src) || |
| 25 |
(src.endsWith("./lib/index.js") && |
| 26 |
/babel-(plugin|preset)-/.test(filename)) |
| 27 |
) { |
| 28 |
return; |
| 29 |
} |
| 30 |
|
| 31 |
const defaultSpecifier = node.specifiers.find( |
| 32 |
spec => spec.type === "ImportDefaultSpecifier", |
| 33 |
); |
| 34 |
if (!defaultSpecifier) return; |
| 35 |
|
| 36 |
const scope = ctx.getScope(); |
| 37 |
|
| 38 |
const { name: local } = defaultSpecifier.local; |
| 39 |
const { references } = scope.variables.find(v => v.name === local); |
| 40 |
|
| 41 |
const isRef = node => node.type === "Identifier" && node.name === local; |
| 42 |
const isRefDefault = node => |
| 43 |
node.type === "MemberExpression" && |
| 44 |
!node.computed && |
| 45 |
node.property.name === "default" && |
| 46 |
isRef(node.object); |
| 47 |
|
| 48 |
for (const { identifier } of references) { |
| 49 |
const base = |
| 50 |
identifier.parent.type === "MemberExpression" |
| 51 |
? identifier.parent.parent |
| 52 |
: identifier.parent; |
| 53 |
|
| 54 |
if ( |
| 55 |
base.type !== "LogicalExpression" || |
| 56 |
base.operator !== "||" || |
| 57 |
!isRefDefault(base.left) || |
| 58 |
!isRef(base.right) |
| 59 |
) { |
| 60 |
const expected = `${local}.default || ${local}`; |
| 61 |
ctx.report({ |
| 62 |
node: identifier, |
| 63 |
message: `Default imports of source files must be used with an explicit fallback: \`${expected}\``, |
| 64 |
fix(fixer) { |
| 65 |
const base = isRefDefault(identifier.parent) |
| 66 |
? identifier.parent |
| 67 |
: identifier; |
| 68 |
return fixer.replaceText(base, `(${expected})`); |
| 69 |
}, |
| 70 |
}); |
| 71 |
} |
| 72 |
} |
| 73 |
}, |
| 74 |
}; |
| 75 |
}, |
| 76 |
}; |