Skip to content

Commit

Permalink
Remove * import warnings (duckduckgo#2113)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathanKingston authored Jul 24, 2023
1 parent 3b2322a commit 4426bea
Show file tree
Hide file tree
Showing 11 changed files with 62 additions and 53 deletions.
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"indent": ["error", 4],
"no-shadow": ["error"],
"no-restricted-syntax": [
"warn",
"error",
{
"selector": ":matches(ImportNamespaceSpecifier, ExportAllDeclaration, ExportNamespaceSpecifier)",
"message": "Prefer explicit named imports over wildcard (import * as x)"
Expand Down
15 changes: 7 additions & 8 deletions shared/js/background/devbuild-reloader.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
*/

import browser from 'webextension-polyfill'
// TODO: Only import `createAlarm`, `getFromSessionStorage` and `setToSessionStorage` here
import * as browserWrapper from './wrapper'
import { createAlarm, getFromSessionStorage, setToSessionStorage } from './wrapper'

export default function initReloader () {
function createAlarm () {
browserWrapper.createAlarm('checkBuildTime', { when: Date.now() + 5000 })
function createAlarmTimer () {
createAlarm('checkBuildTime', { when: Date.now() + 5000 })
}

browser.alarms.onAlarm.addListener(async alarmEvent => {
Expand All @@ -25,16 +24,16 @@ export default function initReloader () {
} catch (e) { }

if (buildTime) {
const previousBuildTime = await browserWrapper.getFromSessionStorage('buildTime')
const previousBuildTime = await getFromSessionStorage('buildTime')
if (!previousBuildTime) {
await browserWrapper.setToSessionStorage('buildTime', buildTime)
await setToSessionStorage('buildTime', buildTime)
} else if (buildTime !== previousBuildTime) {
browser.runtime.reload()
}
}

createAlarm()
createAlarmTimer()
})

createAlarm()
createAlarmTimer()
}
7 changes: 5 additions & 2 deletions shared/js/background/devbuild.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* This exposes some modules we use for testing via the background page console.
* NOTE this is not added to the release version of the extension
*/
import * as startup from './startup'
import { onStartup, ready } from './startup'
import Companies from './companies'
import atb from './atb'
import tds from './storage/tds'
Expand All @@ -21,7 +21,10 @@ export default function initDebugBuild () {
// @ts-ignore - dbg is not a standard property of self.
self.dbg = {
settings,
startup,
startup: {
ready,
onStartup
},
tabManager,
Tab,
TabState,
Expand Down
16 changes: 8 additions & 8 deletions shared/js/background/dnr-config-rulesets.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as browserWrapper from './wrapper'
import { getExtensionVersion, getManifestVersion } from './wrapper'
import settings from './settings'
import tdsStorage from './storage/tds'
import trackers from './trackers'
import * as startup from './startup'
import { ready as startupReady } from './startup'
import { isFeatureEnabled } from './utils'
import {
ensureServiceWorkerInitiatedRequestExceptions
Expand Down Expand Up @@ -181,7 +181,7 @@ async function updateConfigRules (
* @returns {Promise<>}
*/
export async function updateExtensionConfigRules (etag = null, configValue = null) {
const extensionVersion = browserWrapper.getExtensionVersion()
const extensionVersion = getExtensionVersion()
const denylistedDomains = await getDenylistedDomains()

const latestState = {
Expand Down Expand Up @@ -228,7 +228,7 @@ export async function updateExtensionConfigRules (etag = null, configValue = nul
}

export async function updateCombinedConfigBlocklistRules () {
const extensionVersion = browserWrapper.getExtensionVersion()
const extensionVersion = getExtensionVersion()
const denylistedDomains = await getDenylistedDomains()
const tdsEtag = settings.getSetting('tds-etag')
const combinedState = {
Expand Down Expand Up @@ -261,7 +261,7 @@ let ruleUpdateLock = Promise.resolve()
* @returns {Promise}
*/
export async function onConfigUpdate (configName, etag, configValue) {
const extensionVersion = browserWrapper.getExtensionVersion()
const extensionVersion = getExtensionVersion()
// Run an async lock on all blocklist updates so the latest update is always processed last
ruleUpdateLock = ruleUpdateLock.then(async () => {
// TDS (aka the block list).
Expand All @@ -272,8 +272,8 @@ export async function onConfigUpdate (configName, etag, configValue) {
return
}

await startup.ready()
// @ts-ignore: Once startup.ready() has finished, surrogateList will be
await startupReady()
// @ts-ignore: Once startupReady() has finished, surrogateList will be
// assigned.
const supportedSurrogates = new Set(Object.keys(trackers.surrogateList))

Expand All @@ -299,7 +299,7 @@ export async function onConfigUpdate (configName, etag, configValue) {
await ruleUpdateLock
}

if (browserWrapper.getManifestVersion() === 3) {
if (getManifestVersion() === 3) {
tdsStorage.onUpdate('config', onConfigUpdate)
tdsStorage.onUpdate('tds', onConfigUpdate)
}
6 changes: 3 additions & 3 deletions shared/js/background/dnr-session-rule-id.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
* For managing dynamically created MV3 session rules
* getNextSessionRuleId will return the next unique session rule id to use when creating new session rules
**/
import * as browserWrapper from './wrapper'
import { getFromSessionStorage, setToSessionStorage } from './wrapper'
const SESSION_RULE_ID_START = 100000
const SESSION_RULE_STORAGE_KEY = 'sessionRuleOffset'
let sessionRuleOffset = 0
let ready = false

export async function setSessionRuleOffsetFromStorage () {
const offset = await browserWrapper.getFromSessionStorage(SESSION_RULE_STORAGE_KEY)
const offset = await getFromSessionStorage(SESSION_RULE_STORAGE_KEY)
if (offset) {
sessionRuleOffset = offset
}
Expand All @@ -28,7 +28,7 @@ export function getNextSessionRuleId () {

const nextRuleId = SESSION_RULE_ID_START + sessionRuleOffset
sessionRuleOffset += 1
browserWrapper.setToSessionStorage(SESSION_RULE_STORAGE_KEY, sessionRuleOffset)
setToSessionStorage(SESSION_RULE_STORAGE_KEY, sessionRuleOffset)
return nextRuleId
}

Expand Down
6 changes: 3 additions & 3 deletions shared/js/background/events/privacy-icon-indicator.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as constants from '../../../data/constants'
import { iconPaths } from '../../../data/constants'
import { setActionIcon } from '../wrapper'

/**
Expand All @@ -20,8 +20,8 @@ export function updateActionIcon (site, tabId) {
// Enabled: regular icon
// Disabled: special state, greyed-out Dax
const nextIcon = protectionsEnabled
? constants.iconPaths.regular
: constants.iconPaths.withSpecialState
? iconPaths.regular
: iconPaths.withSpecialState

// now call out to the browser wrapper to actually change the icon
return setActionIcon(nextIcon, tabId)
Expand Down
10 changes: 5 additions & 5 deletions shared/js/background/newtab-tracker-stats.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import browser from 'webextension-polyfill'
import constants from '../../data/constants'
import * as browserWrapper from './wrapper.js'
import { getManifestVersion, createAlarm, syncToStorage, getFromStorage } from './wrapper.js'
import tdsStorage from './storage/tds'
import { emitter, TrackerBlockedEvent } from './before-request.js'
import { generateDNRRule } from '@duckduckgo/ddg2dnr/lib/utils'
Expand Down Expand Up @@ -74,7 +74,7 @@ export class NewTabTrackerStats {
* place for this module.
*/
register () {
const manifestVersion = browserWrapper.getManifestVersion()
const manifestVersion = getManifestVersion()
if (manifestVersion === 3) {
mv3Redirect()
} else {
Expand Down Expand Up @@ -111,7 +111,7 @@ export class NewTabTrackerStats {
* For now, we're pruning data every 10 min
*/
const pruneAlarmName = 'pruneNewTabData'
browserWrapper.createAlarm(pruneAlarmName, { periodInMinutes: 10 })
createAlarm(pruneAlarmName, { periodInMinutes: 10 })
browser.alarms.onAlarm.addListener(async alarmEvent => {
if (alarmEvent.name === pruneAlarmName) {
this._handlePruneAlarm()
Expand Down Expand Up @@ -206,7 +206,7 @@ export class NewTabTrackerStats {
stats: serializedData
}
}
browserWrapper.syncToStorage(toSync)
syncToStorage(toSync)
}

/**
Expand All @@ -215,7 +215,7 @@ export class NewTabTrackerStats {
*/
async restoreFromStorage () {
try {
const prev = await browserWrapper.getFromStorage(NewTabTrackerStats.storageKey)
const prev = await getFromStorage(NewTabTrackerStats.storageKey)
if (prev) {
this.stats.deserialize(prev.stats)
}
Expand Down
26 changes: 13 additions & 13 deletions shared/js/background/tracker-utils.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Utility functions for dealing with tracker information
import * as utils from './utils'
import { extractHostFromURL, isSafeListed, extractLimitedDomainFromURL, brokenListIndex, isSameTopLevelDomain } from './utils'
import trackers from './trackers'
import * as tldts from 'tldts'
import { parse as tldtsParse } from 'tldts'
import tdsStorage from './storage/tds'

export function hasTrackerListLoaded () {
Expand All @@ -11,12 +11,12 @@ export function hasTrackerListLoaded () {
// Determine if two URL's belong to the same entity.
export function isSameEntity (url1, url2) {
try {
const domain1 = tldts.parse(url1).domain
const domain2 = tldts.parse(url2).domain
const domain1 = tldtsParse(url1).domain
const domain2 = tldtsParse(url2).domain
if (domain1 === domain2) return true

const entity1 = trackers.findWebsiteOwner({ siteUrlSplit: utils.extractHostFromURL(url1).split('.') })
const entity2 = trackers.findWebsiteOwner({ siteUrlSplit: utils.extractHostFromURL(url2).split('.') })
const entity1 = trackers.findWebsiteOwner({ siteUrlSplit: extractHostFromURL(url1).split('.') })
const entity2 = trackers.findWebsiteOwner({ siteUrlSplit: extractHostFromURL(url2).split('.') })
if (entity1 === undefined && entity2 === undefined) return false
return entity1 === entity2
} catch (e) {
Expand All @@ -28,7 +28,7 @@ export function isSameEntity (url1, url2) {
// return true if URL is in our tracker list
export function isTracker (url) {
const data = {
urlToCheckSplit: utils.extractHostFromURL(url).split('.')
urlToCheckSplit: extractHostFromURL(url).split('.')
}
const tracker = trackers.findTracker(data)
return !!tracker
Expand All @@ -51,7 +51,7 @@ export function truncateReferrer (referrer, target) {
return undefined
}

if (utils.isSafeListed(referrer) || utils.isSafeListed(target)) {
if (isSafeListed(referrer) || isSafeListed(target)) {
return undefined
}

Expand All @@ -63,13 +63,13 @@ export function truncateReferrer (referrer, target) {
}

const exceptionList = tdsStorage.config.features.referrer.exceptions
if (utils.brokenListIndex(referrer, exceptionList) !== -1 || utils.brokenListIndex(target, exceptionList) !== -1) {
if (brokenListIndex(referrer, exceptionList) !== -1 || brokenListIndex(target, exceptionList) !== -1) {
return undefined
}

// If extractLimitedDomainFromURL fails (for instance, invalid referrer URL), it
// returns undefined, (in practice, don't modify the referrer), so sometimes this value could be undefined.
return utils.extractLimitedDomainFromURL(referrer, { keepSubdomains: true })
return extractLimitedDomainFromURL(referrer, { keepSubdomains: true })
}

/**
Expand All @@ -82,14 +82,14 @@ export function isFirstPartyByEntity (trackerUrl, siteUrl) {
const cnameResolution = trackers.resolveCname(trackerUrl)
trackerUrl = cnameResolution.finalURL

if (utils.isSameTopLevelDomain(trackerUrl, siteUrl)) {
if (isSameTopLevelDomain(trackerUrl, siteUrl)) {
return true
}

const trackerDomain = tldts.parse(trackerUrl).domain
const trackerDomain = tldtsParse(trackerUrl).domain
if (!trackerDomain) return false
const trackerOwner = trackers.findTrackerOwner(trackerDomain)
const websiteOwner = trackers.findWebsiteOwner({ siteUrlSplit: utils.extractHostFromURL(siteUrl).split('.') })
const websiteOwner = trackers.findWebsiteOwner({ siteUrlSplit: extractHostFromURL(siteUrl).split('.') })

return (trackerOwner && websiteOwner) ? trackerOwner === websiteOwner : false
}
10 changes: 5 additions & 5 deletions shared/js/background/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import browser from 'webextension-polyfill'
import { getExtensionVersion, getFromSessionStorage, setToSessionStorage } from './wrapper'
import tdsStorage from './storage/tds'
import settings from './settings'
import * as tldts from 'tldts'
import { parse as tldtsParse } from 'tldts'
import parseUserAgentString from '../shared-utils/parse-user-agent-string'
import sha1 from '../shared-utils/sha1'
const browserInfo = parseUserAgentString()
Expand Down Expand Up @@ -52,7 +52,7 @@ export async function sendAllTabsMessage (message, details) {
* @returns {string | null} etld plus one of the URL
*/
export function getBaseDomain (urlString) {
const parsedUrl = tldts.parse(urlString, { allowPrivateDomains: true })
const parsedUrl = tldtsParse(urlString, { allowPrivateDomains: true })
if (parsedUrl.hostname === 'localhost' || parsedUrl.hostname?.endsWith('.localhost') || parsedUrl.isIp) {
return parsedUrl.hostname
}
Expand All @@ -68,7 +68,7 @@ export function extractHostFromURL (url, shouldKeepWWW) {
url = 'about://' + url.substr(6)
}

const urlObj = tldts.parse(url)
const urlObj = tldtsParse(url)
let hostname = urlObj.hostname || ''

if (!shouldKeepWWW) {
Expand All @@ -84,7 +84,7 @@ export function extractLimitedDomainFromURL (url, { keepSubdomains } = {}) {
if (!url) return undefined
try {
const parsedURL = new URL(url)
const tld = tldts.parse(url)
const tld = tldtsParse(url)
if (!parsedURL || !tld) return ''
// tld.domain is null if this is an IP or the domain does not use a known TLD (e.g. localhost)
// in that case use the hostname (no truncation)
Expand Down Expand Up @@ -256,7 +256,7 @@ export function getEnabledFeatures (url) {
}

export function brokenListIndex (url, list) {
const parsedDomain = tldts.parse(url)
const parsedDomain = tldtsParse(url)
const hostname = parsedDomain.hostname || url

// If root domain in temp unprotected list, return true
Expand Down
10 changes: 5 additions & 5 deletions shared/js/newtab/newtab.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import constants from '../../data/constants'
import * as schema from './schema'
import { incoming, outgoing } from './schema'
const { events, allowedOrigin, clientPortName } = constants.trackerStats

/**
Expand Down Expand Up @@ -74,11 +74,11 @@ window.addEventListener('message', (e) => {
* This allows developers to come here and read the schemas to figure out what data
* will be sent.
*
* @param {import("zod").infer<schema.outgoing>} msg
* @param {import("zod").infer<outgoing>} msg
*/
function sendToNewTabPage (msg) {
// try to validate the message
const parsed = schema.outgoing.safeParse(msg)
const parsed = outgoing.safeParse(msg)
if (!parsed.success) {
console.warn('not forwarding as validation failed on', msg)
return console.error(parsed.error)
Expand All @@ -100,7 +100,7 @@ function sendToNewTabPage (msg) {
* so we take a straight-forward approach to errors. Any communication error found here
* will result in the NTP receiving a 'disconnect' message so that it can remove its UI
*
* @param {import("zod").infer<schema.incoming>} msg
* @param {import("zod").infer<incoming>} msg
*/
let port = null
function sendToChromeRuntime (msg) {
Expand All @@ -113,7 +113,7 @@ function sendToChromeRuntime (msg) {
}

// now ensure the event is valid
const parsed = schema.incoming.safeParse(msg)
const parsed = incoming.safeParse(msg)
if (!parsed.success) {
console.warn('not forwarding to the chrome runtime because validation failed for:', msg)
return console.error(parsed.error)
Expand Down
7 changes: 7 additions & 0 deletions unit-test/legacy/declarative-net-request.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import '../helpers/mock-browser-api'
// TODO remove the * imports
// eslint-disable-next-line no-restricted-syntax
import * as allowlistedTrackers from '@duckduckgo/privacy-reference-tests/tracker-radar-tests/TR-domain-matching/tracker_allowlist_reference.json'
// eslint-disable-next-line no-restricted-syntax
import * as tds from '../data/tds.json'
// eslint-disable-next-line no-restricted-syntax
import * as browserWrapper from '../../shared/js/background/wrapper'
// eslint-disable-next-line no-restricted-syntax
import * as testConfig from '../data/extension-config.json'
// eslint-disable-next-line no-restricted-syntax
import * as tdsStorageStub from '../helpers/tds'
// eslint-disable-next-line no-restricted-syntax
import * as startup from '../../shared/js/background/startup'
import settings from '../../shared/js/background/settings'
import tabManager from '../../shared/js/background/tab-manager'
Expand Down

0 comments on commit 4426bea

Please sign in to comment.