forked from mysticatea/eslint-plugin-node
-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
exports-style.js
446 lines (404 loc) · 13.7 KB
/
exports-style.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
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { hasParentNode } = require("../util/has-parent-node.js")
const { getSourceCode, getScope } = require("../util/eslint-compat")
/*istanbul ignore next */
/**
* This function is copied from https://github.com/eslint/eslint/blob/2355f8d0de1d6732605420d15ddd4f1eee3c37b6/lib/ast-utils.js#L648-L684
*
* @param {import('estree').Node} node - The node to get.
* @returns {string | null | undefined} The property name if static. Otherwise, null.
* @private
*/
function getStaticPropertyName(node) {
/** @type {import('estree').Expression | import('estree').PrivateIdentifier | null} */
let prop = null
switch (node?.type) {
case "Property":
case "MethodDefinition":
prop = node.key
break
case "MemberExpression":
prop = node.property
break
// no default
}
switch (prop?.type) {
case "Literal":
return String(prop.value)
case "TemplateLiteral":
if (prop.expressions.length === 0 && prop.quasis.length === 1) {
return prop.quasis[0]?.value.cooked
}
break
case "Identifier":
if (node.type === "MemberExpression" && node.computed === false) {
return prop.name
}
break
// no default
}
return null
}
/**
* Checks whether the given node is assignee or not.
*
* @param {import('estree').Node} node - The node to check.
* @returns {boolean} `true` if the node is assignee.
*/
function isAssignee(node) {
return (
hasParentNode(node) &&
node.parent?.type === "AssignmentExpression" &&
node.parent.left === node
)
}
/**
* Gets the top assignment expression node if the given node is an assignee.
*
* This is used to distinguish 2 assignees belong to the same assignment.
* If the node is not an assignee, this returns null.
*
* @param {import('estree').Node} leafNode - The node to get.
* @returns {import('estree').Node | null} The top assignment expression node, or null.
*/
function getTopAssignment(leafNode) {
let node = leafNode
// Skip MemberExpressions.
while (
hasParentNode(node) &&
node.parent.type === "MemberExpression" &&
node.parent.object === node
) {
node = node.parent
}
// Check assignments.
if (!isAssignee(node)) {
return null
}
// Find the top.
while (hasParentNode(node) && node.parent.type === "AssignmentExpression") {
node = node.parent
}
return node
}
/**
* Gets top assignment nodes of the given node list.
*
* @param {import('estree').Node[]} nodes - The node list to get.
* @returns {import('estree').Node[]} Gotten top assignment nodes.
*/
function createAssignmentList(nodes) {
return nodes.map(getTopAssignment).filter(input => input != null)
}
/**
* Gets the reference of `module.exports` from the given scope.
*
* @param {import('eslint').Scope.Scope} scope - The scope to get.
* @returns {import('estree').Node[]} Gotten MemberExpression node list.
*/
function getModuleExportsNodes(scope) {
const variable = scope.set.get("module")
if (variable == null) {
return []
}
/** @type {import('estree').Node[]} */
const nodes = []
for (const reference of variable.references) {
if (hasParentNode(reference.identifier) === false) {
continue
}
const node = reference.identifier.parent
if (
node.type === "MemberExpression" &&
getStaticPropertyName(node) === "exports"
) {
nodes.push(node)
}
}
return nodes
}
/**
* Gets the reference of `exports` from the given scope.
*
* @param {import('eslint').Scope.Scope} scope - The scope to get.
* @returns {import('estree').Identifier[]} Gotten Identifier node list.
*/
function getExportsNodes(scope) {
const variable = scope.set.get("exports")
if (variable == null) {
return []
}
return variable.references.map(reference => reference.identifier)
}
/**
* @param {import('estree').Node} property
* @param {import('eslint').SourceCode} sourceCode
* @returns {string | null}
*/
function getReplacementForProperty(property, sourceCode) {
if (property.type !== "Property" || property.kind !== "init") {
// We don't have a nice syntax for adding these directly on the exports object. Give up on fixing the whole thing:
// property.kind === 'get':
// module.exports = { get foo() { ... } }
// property.kind === 'set':
// module.exports = { set foo() { ... } }
// property.type === 'SpreadElement':
// module.exports = { ...foo }
return null
}
let fixedValue = sourceCode.getText(property.value)
if (property.value.type === "FunctionExpression" && property.method) {
fixedValue = `function${
property.value.generator ? "*" : ""
} ${fixedValue}`
if (property.value.async) {
fixedValue = `async ${fixedValue}`
}
}
const lines = sourceCode
.getCommentsBefore(property)
// @ts-expect-error getText supports both BaseNode and BaseNodeWithoutComments
.map(comment => sourceCode.getText(comment))
if (property.key.type === "Literal" || property.computed) {
// String or dynamic key:
// module.exports = { [ ... ]: ... } or { "foo": ... }
lines.push(
`exports[${sourceCode.getText(property.key)}] = ${fixedValue};`
)
} else if (property.key.type === "Identifier") {
// Regular identifier:
// module.exports = { foo: ... }
lines.push(`exports.${property.key.name} = ${fixedValue};`)
} else {
// Some other unknown property type. Conservatively give up on fixing the whole thing.
return null
}
lines.push(
...sourceCode
.getCommentsAfter(property)
// @ts-expect-error getText supports both BaseNode and BaseNodeWithoutComments
.map(comment => sourceCode.getText(comment))
)
return lines.join("\n")
}
/**
* Check for a top level module.exports = { ... }
* @param {import('estree').Node} node
* @returns {node is {parent: import('estree').AssignmentExpression & {parent: import('estree').ExpressionStatement, right: import('estree').ObjectExpression}}}
*/
function isModuleExportsObjectAssignment(node) {
return (
hasParentNode(node) &&
node.parent?.type === "AssignmentExpression" &&
hasParentNode(node.parent) &&
node.parent?.parent?.type === "ExpressionStatement" &&
hasParentNode(node.parent.parent) &&
node.parent.parent.parent?.type === "Program" &&
node.parent.right.type === "ObjectExpression"
)
}
/**
* Check for module.exports.foo or module.exports.bar reference or assignment
* @param {import('estree').Node} node
* @returns {node is import('estree').MemberExpression}
*/
function isModuleExportsReference(node) {
return (
hasParentNode(node) &&
node.parent?.type === "MemberExpression" &&
node.parent.object === node
)
}
/**
* @param {import('estree').Node} node
* @param {import('eslint').SourceCode} sourceCode
* @param {import('eslint').Rule.RuleFixer} fixer
* @returns {import('eslint').Rule.Fix | null}
*/
function fixModuleExports(node, sourceCode, fixer) {
if (isModuleExportsReference(node)) {
return fixer.replaceText(node, "exports")
}
if (!isModuleExportsObjectAssignment(node)) {
return null
}
const statements = []
const properties = node.parent.right.properties
for (const property of properties) {
const statement = getReplacementForProperty(property, sourceCode)
if (statement) {
statements.push(statement)
} else {
// No replacement available, give up on the whole thing
return null
}
}
return fixer.replaceText(node.parent, statements.join("\n\n"))
}
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
docs: {
description: "enforce either `module.exports` or `exports`",
recommended: false,
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/exports-style.md",
},
type: "suggestion",
fixable: "code",
schema: [
{
//
enum: ["module.exports", "exports"],
},
{
type: "object",
properties: { allowBatchAssign: { type: "boolean" } },
additionalProperties: false,
},
],
messages: {
unexpectedExports:
"Unexpected access to 'exports'. Use 'module.exports' instead.",
unexpectedModuleExports:
"Unexpected access to 'module.exports'. Use 'exports' instead.",
unexpectedAssignment:
"Unexpected assignment to 'exports'. Don't modify 'exports' itself.",
},
},
create(context) {
const mode = context.options[0] || "module.exports"
const batchAssignAllowed = Boolean(
context.options[1] != null && context.options[1].allowBatchAssign
)
const sourceCode = getSourceCode(context)
/**
* Gets the location info of reports.
*
* exports = foo
* ^^^^^^^^^
*
* module.exports = foo
* ^^^^^^^^^^^^^^^^
*
* @param {import('estree').Node} node - The node of `exports`/`module.exports`.
* @returns {import('estree').SourceLocation | undefined} The location info of reports.
*/
function getLocation(node) {
const token = sourceCode.getTokenAfter(node)
if (node.loc?.start == null || token?.loc?.end == null) {
return
}
return {
start: node.loc?.start,
end: token?.loc?.end,
}
}
/**
* Enforces `module.exports`.
* This warns references of `exports`.
*
* @param {import('eslint').Scope.Scope} globalScope
* @returns {void}
*/
function enforceModuleExports(globalScope) {
const exportsNodes = getExportsNodes(globalScope)
const assignList = batchAssignAllowed
? createAssignmentList(getModuleExportsNodes(globalScope))
: []
for (const node of exportsNodes) {
// Skip if it's a batch assignment.
const topAssignment = getTopAssignment(node)
if (
topAssignment &&
assignList.length > 0 &&
assignList.indexOf(topAssignment) !== -1
) {
continue
}
// Report.
context.report({
node,
loc: getLocation(node),
messageId: "unexpectedExports",
})
}
}
/**
* Enforces `exports`.
* This warns references of `module.exports`.
*
* @param {import('eslint').Scope.Scope} globalScope
* @returns {void}
*/
function enforceExports(globalScope) {
const exportsNodes = getExportsNodes(globalScope)
const moduleExportsNodes = getModuleExportsNodes(globalScope)
const assignList = batchAssignAllowed
? createAssignmentList(exportsNodes)
: []
const batchAssignList = []
for (const node of moduleExportsNodes) {
// Skip if it's a batch assignment.
if (assignList.length > 0) {
const topAssignment = getTopAssignment(node)
const found = topAssignment
? assignList.indexOf(topAssignment)
: -1
if (found !== -1) {
batchAssignList.push(assignList[found])
assignList.splice(found, 1)
continue
}
}
// Report.
context.report({
node,
loc: getLocation(node),
messageId: "unexpectedModuleExports",
fix(fixer) {
return fixModuleExports(node, sourceCode, fixer)
},
})
}
// Disallow direct assignment to `exports`.
for (const node of exportsNodes) {
// Skip if it's not assignee.
if (!isAssignee(node)) {
continue
}
const topAssignment = getTopAssignment(node)
// Check if it's a batch assignment.
if (
topAssignment &&
batchAssignList.indexOf(topAssignment) !== -1
) {
continue
}
// Report.
context.report({
node,
loc: getLocation(node),
messageId: "unexpectedAssignment",
})
}
}
return {
"Program:exit"() {
const scope = getScope(context)
switch (mode) {
case "module.exports":
enforceModuleExports(scope)
break
case "exports":
enforceExports(scope)
break
// no default
}
},
}
},
}