|
| 1 | +'use strict'; |
| 2 | +const getDocumentationUrl = require('./utils/get-documentation-url'); |
| 3 | +const {methodCallSelector} = require('./selectors'); |
| 4 | +const {appendArgument} = require('./fix'); |
| 5 | + |
| 6 | +const ERROR = 'error'; |
| 7 | +const SUGGESTION_TARGET_LOCATION_ORIGIN = 'target-location-origin'; |
| 8 | +const SUGGESTION_SELF_LOCATION_ORIGIN = 'self-location-origin'; |
| 9 | +const SUGGESTION_STAR = 'star'; |
| 10 | +const messages = { |
| 11 | + [ERROR]: 'Missing the `targetOrigin` argument.', |
| 12 | + [SUGGESTION_TARGET_LOCATION_ORIGIN]: 'Use `{{target}}.location.origin`.', |
| 13 | + [SUGGESTION_SELF_LOCATION_ORIGIN]: 'Use `self.location.origin`.', |
| 14 | + [SUGGESTION_STAR]: 'Use `"*"`.' |
| 15 | +}; |
| 16 | + |
| 17 | +/** @param {import('eslint').Rule.RuleContext} context */ |
| 18 | +function create(context) { |
| 19 | + const sourceCode = context.getSourceCode(); |
| 20 | + return { |
| 21 | + [methodCallSelector({name: 'postMessage', length: 1})](node) { |
| 22 | + const [penultimateToken, lastToken] = sourceCode.getLastTokens(node, 2); |
| 23 | + const suggestions = []; |
| 24 | + const target = node.callee.object; |
| 25 | + if (target.type === 'Identifier') { |
| 26 | + const {name} = target; |
| 27 | + |
| 28 | + suggestions.push({ |
| 29 | + messageId: SUGGESTION_TARGET_LOCATION_ORIGIN, |
| 30 | + data: {target: name}, |
| 31 | + code: `${target.name}.location.origin` |
| 32 | + }); |
| 33 | + |
| 34 | + if (name !== 'self' && name !== 'window' && name !== 'globalThis') { |
| 35 | + suggestions.push({messageId: SUGGESTION_SELF_LOCATION_ORIGIN, code: 'self.location.origin'}); |
| 36 | + } |
| 37 | + } else { |
| 38 | + suggestions.push({messageId: SUGGESTION_SELF_LOCATION_ORIGIN, code: 'self.location.origin'}); |
| 39 | + } |
| 40 | + |
| 41 | + suggestions.push({messageId: SUGGESTION_STAR, code: '\'*\''}); |
| 42 | + |
| 43 | + context.report({ |
| 44 | + loc: { |
| 45 | + start: penultimateToken.loc.end, |
| 46 | + end: lastToken.loc.end |
| 47 | + }, |
| 48 | + messageId: ERROR, |
| 49 | + suggest: suggestions.map(({messageId, data, code}) => ({ |
| 50 | + messageId, |
| 51 | + data, |
| 52 | + /** @param {import('eslint').Rule.RuleFixer} fixer */ |
| 53 | + fix: fixer => appendArgument(fixer, node, code, sourceCode) |
| 54 | + })) |
| 55 | + }); |
| 56 | + } |
| 57 | + }; |
| 58 | +} |
| 59 | + |
| 60 | +module.exports = { |
| 61 | + create, |
| 62 | + meta: { |
| 63 | + type: 'problem', |
| 64 | + docs: { |
| 65 | + description: 'Enforce using the `targetOrigin` argument with `window.postMessage()`.', |
| 66 | + url: getDocumentationUrl(__filename), |
| 67 | + suggestion: true |
| 68 | + }, |
| 69 | + schema: [], |
| 70 | + messages |
| 71 | + } |
| 72 | +}; |
0 commit comments