File size: 2,484 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { defineRule } from '../utils/define-rule'
import NodeAttributes from '../utils/node-attributes'

const SUPPORTED_SRCS = [
  'www.google-analytics.com/analytics.js',
  'www.googletagmanager.com/gtag/js',
]
const SUPPORTED_HTML_CONTENT_URLS = [
  'www.google-analytics.com/analytics.js',
  'www.googletagmanager.com/gtm.js',
]
const description =
  'Prefer `next/script` component when using the inline script for Google Analytics.'
const url = 'https://nextjs.org/docs/messages/next-script-for-ga'
const ERROR_MSG = `${description} See: ${url}`

// Check if one of the items in the list is a substring of the passed string
const containsStr = (str, strList) => {
  return strList.some((s) => str.includes(s))
}

export = defineRule({
  meta: {
    docs: {
      description,
      recommended: true,
      url,
    },
    type: 'problem',
    schema: [],
  },
  create(context) {
    return {
      JSXOpeningElement(node) {
        if (node.name.name !== 'script') {
          return
        }
        if (node.attributes.length === 0) {
          return
        }
        const attributes = new NodeAttributes(node)

        // Check if the Alternative async tag is being used to add GA.
        // https://developers.google.com/analytics/devguides/collection/analyticsjs#alternative_async_tag
        // https://developers.google.com/analytics/devguides/collection/gtagjs
        if (
          typeof attributes.value('src') === 'string' &&
          containsStr(attributes.value('src'), SUPPORTED_SRCS)
        ) {
          return context.report({
            node,
            message: ERROR_MSG,
          })
        }

        // Check if inline script is being used to add GA.
        // https://developers.google.com/analytics/devguides/collection/analyticsjs#the_google_analytics_tag
        // https://developers.google.com/tag-manager/quickstart
        if (
          attributes.value('dangerouslySetInnerHTML') &&
          attributes.value('dangerouslySetInnerHTML').length > 0
        ) {
          const htmlContent =
            attributes.value('dangerouslySetInnerHTML')[0].value.quasis &&
            attributes.value('dangerouslySetInnerHTML')[0].value.quasis[0].value
              .raw
          if (
            htmlContent &&
            containsStr(htmlContent, SUPPORTED_HTML_CONTENT_URLS)
          ) {
            context.report({
              node,
              message: ERROR_MSG,
            })
          }
        }
      },
    }
  },
})