require-post-message-target-origin.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const {methodCallSelector} = require('./selectors/index.js');
  3. const {appendArgument} = require('./fix/index.js');
  4. const ERROR = 'error';
  5. const SUGGESTION = 'suggestion';
  6. const messages = {
  7. [ERROR]: 'Missing the `targetOrigin` argument.',
  8. [SUGGESTION]: 'Use `{{code}}`.',
  9. };
  10. /** @param {import('eslint').Rule.RuleContext} context */
  11. function create(context) {
  12. const sourceCode = context.getSourceCode();
  13. return {
  14. [methodCallSelector({method: 'postMessage', argumentsLength: 1})](node) {
  15. const [penultimateToken, lastToken] = sourceCode.getLastTokens(node, 2);
  16. const replacements = [];
  17. const target = node.callee.object;
  18. if (target.type === 'Identifier') {
  19. const {name} = target;
  20. replacements.push(`${name}.location.origin`);
  21. if (name !== 'self' && name !== 'window' && name !== 'globalThis') {
  22. replacements.push('self.location.origin');
  23. }
  24. } else {
  25. replacements.push('self.location.origin');
  26. }
  27. replacements.push('\'*\'');
  28. return {
  29. loc: {
  30. start: penultimateToken.loc.end,
  31. end: lastToken.loc.end,
  32. },
  33. messageId: ERROR,
  34. suggest: replacements.map(code => ({
  35. messageId: SUGGESTION,
  36. data: {code},
  37. /** @param {import('eslint').Rule.RuleFixer} fixer */
  38. fix: fixer => appendArgument(fixer, node, code, sourceCode),
  39. })),
  40. };
  41. },
  42. };
  43. }
  44. /** @type {import('eslint').Rule.RuleModule} */
  45. module.exports = {
  46. create,
  47. meta: {
  48. type: 'problem',
  49. docs: {
  50. description: 'Enforce using the `targetOrigin` argument with `window.postMessage()`.',
  51. },
  52. hasSuggestions: true,
  53. messages,
  54. },
  55. };