|
| 1 | +/** |
| 2 | + * @fileoverview disallow `window/document` in `created/beforeCreate` |
| 3 | + * @author Clark Du |
| 4 | + */ |
| 5 | +'use strict' |
| 6 | + |
| 7 | +const utils = require('../utils') |
| 8 | + |
| 9 | +// ------------------------------------------------------------------------------ |
| 10 | +// Rule Definition |
| 11 | +// ------------------------------------------------------------------------------ |
| 12 | + |
| 13 | +module.exports = { |
| 14 | + meta: { |
| 15 | + docs: { |
| 16 | + description: 'disallow `window/document` in `created/beforeCreate`', |
| 17 | + category: 'ssr' |
| 18 | + }, |
| 19 | + fixable: null, // or "code" or "whitespace" |
| 20 | + schema: [ |
| 21 | + // fill in your schema |
| 22 | + ], |
| 23 | + messages: { |
| 24 | + noGlobals: 'Unexpected {{name}} in {{funcName}}.' |
| 25 | + } |
| 26 | + }, |
| 27 | + |
| 28 | + create: function (context) { |
| 29 | + const forbiddenNodes = [] |
| 30 | + const options = context.options[0] || {} |
| 31 | + |
| 32 | + const HOOKS = new Set( |
| 33 | + ['created', 'beforeCreate'].concat(options.methods || []) |
| 34 | + ) |
| 35 | + const GLOBALS = ['window', 'document'] |
| 36 | + |
| 37 | + function isGlobals (name) { |
| 38 | + return GLOBALS.includes(name) |
| 39 | + } |
| 40 | + |
| 41 | + return { |
| 42 | + MemberExpression (node) { |
| 43 | + if (!node.object) return |
| 44 | + |
| 45 | + const name = node.object.name |
| 46 | + |
| 47 | + if (isGlobals(name)) { |
| 48 | + forbiddenNodes.push({ name, node }) |
| 49 | + } |
| 50 | + }, |
| 51 | + VariableDeclarator (node) { |
| 52 | + if (!node.init) return |
| 53 | + |
| 54 | + const name = node.init.name |
| 55 | + |
| 56 | + if (isGlobals(name)) { |
| 57 | + forbiddenNodes.push({ name, node }) |
| 58 | + } |
| 59 | + }, |
| 60 | + ...utils.executeOnVue(context, obj => { |
| 61 | + for (const { funcName, name, node } of utils.getParentFuncs(obj, HOOKS, forbiddenNodes)) { |
| 62 | + context.report({ |
| 63 | + node, |
| 64 | + messageId: 'noGlobals', |
| 65 | + data: { |
| 66 | + name, |
| 67 | + funcName |
| 68 | + } |
| 69 | + }) |
| 70 | + } |
| 71 | + }) |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments