From 0ba7676e973d8d411bc6f7e69a36afc100cb21b7 Mon Sep 17 00:00:00 2001
From: Mike Cao <mike@mikecao.com>
Date: Sun, 23 Aug 2020 13:34:00 -0700
Subject: [PATCH] Refactor do not track code.

---
 lib/web.js               | 35 +++++++++++++----------------------
 rollup.tracker.config.js |  8 +++++++-
 tracker/index.js         |  2 +-
 3 files changed, 21 insertions(+), 24 deletions(-)

diff --git a/lib/web.js b/lib/web.js
index 04e4466c..4a8578f1 100644
--- a/lib/web.js
+++ b/lib/web.js
@@ -48,26 +48,17 @@ export const hook = (_this, method, callback) => {
 };
 
 export const doNotTrack = () => {
-  if (
-    window.doNotTrack ||
-    navigator.doNotTrack ||
-    navigator.msDoNotTrack ||
-    (window.external && 'msTrackingProtectionEnabled' in window.external)
-  ) {
-    if (
-      window.doNotTrack == '1' ||
-      navigator.doNotTrack == 'yes' ||
-      navigator.doNotTrack == '1' ||
-      navigator.msDoNotTrack == '1' ||
-      (window.external &&
-        window.external.msTrackingProtectionEnabled &&
-        window.external.msTrackingProtectionEnabled())
-    ) {
-      return true;
-    } else {
-      return false;
-    }
-  } else {
-    return false;
-  }
+  const { doNotTrack, navigator, external } = window;
+
+  const msTracking = () => {
+    return (
+      external &&
+      typeof external.msTrackingProtectionEnabled === 'function' &&
+      external.msTrackingProtectionEnabled()
+    );
+  };
+
+  const dnt = doNotTrack || navigator.doNotTrack || navigator.msDoNotTrack || msTracking();
+
+  return dnt === true || dnt === 1 || dnt === 'yes' || dnt === '1';
 };
diff --git a/rollup.tracker.config.js b/rollup.tracker.config.js
index e836955f..ea5f709f 100644
--- a/rollup.tracker.config.js
+++ b/rollup.tracker.config.js
@@ -1,5 +1,6 @@
 import 'dotenv/config';
 import buble from '@rollup/plugin-buble';
+import replace from '@rollup/plugin-replace';
 import resolve from '@rollup/plugin-node-resolve';
 import { terser } from 'rollup-plugin-terser';
 
@@ -9,5 +10,10 @@ export default {
     file: 'public/umami.js',
     format: 'iife',
   },
-  plugins: [resolve(), buble(), terser({ compress: { evaluate: false } })],
+  plugins: [
+    replace({ __DNT__: !!process.env.ENABLE_DNT }),
+    resolve(),
+    buble(),
+    terser({ compress: { evaluate: false } }),
+  ],
 };
diff --git a/tracker/index.js b/tracker/index.js
index a62696dc..8c27c8e2 100644
--- a/tracker/index.js
+++ b/tracker/index.js
@@ -13,7 +13,7 @@ import { post, hook, doNotTrack } from '../lib/web';
 
   const script = document.querySelector('script[data-website-id]');
 
-  if (!script || doNotTrack()) return;
+  if (!script || (__DNT__ && doNotTrack())) return;
 
   const website = script.getAttribute('data-website-id');
   const hostUrl = new URL(script.src).origin;