-
-
Notifications
You must be signed in to change notification settings - Fork 354
/
require-post-message-target-origin.js
74 lines (66 loc) · 1.81 KB
/
require-post-message-target-origin.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
'use strict';
const {isMethodCall} = require('./ast/index.js');
const {appendArgument} = require('./fix/index.js');
const ERROR = 'error';
const SUGGESTION = 'suggestion';
const messages = {
[ERROR]: 'Missing the `targetOrigin` argument.',
[SUGGESTION]: 'Use `{{code}}`.',
};
/** @param {import('eslint').Rule.RuleContext} context */
function create(context) {
const {sourceCode} = context;
return {
CallExpression(node) {
if (!isMethodCall(node, {
method: 'postMessage',
argumentsLength: 1,
optionalCall: false,
optionalMember: false,
})) {
return;
}
const [penultimateToken, lastToken] = sourceCode.getLastTokens(node, 2);
const replacements = [];
const target = node.callee.object;
if (target.type === 'Identifier') {
const {name} = target;
replacements.push(`${name}.location.origin`);
if (name !== 'self' && name !== 'window' && name !== 'globalThis') {
replacements.push('self.location.origin');
}
} else {
replacements.push('self.location.origin');
}
replacements.push('\'*\'');
return {
loc: {
start: penultimateToken.loc.end,
end: lastToken.loc.end,
},
messageId: ERROR,
suggest: replacements.map(code => ({
messageId: SUGGESTION,
data: {code},
/** @param {import('eslint').Rule.RuleFixer} fixer */
fix: fixer => appendArgument(fixer, node, code, sourceCode),
})),
};
},
};
}
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
create,
meta: {
type: 'problem',
docs: {
description: 'Enforce using the `targetOrigin` argument with `window.postMessage()`.',
// Turned off because we can't distinguish `window.postMessage` and `{Worker,MessagePort,Client,BroadcastChannel}#postMessage()`
// See #1396
recommended: false,
},
hasSuggestions: true,
messages,
},
};