diff --git a/build.js b/build.js index e5fd3d76b..bb4e706f3 100755 --- a/build.js +++ b/build.js @@ -1,10 +1,9 @@ #!/usr/bin/env node -'use strict' -require('dotenv').config() +import 'dotenv/config' -const config = require('./src/utils/config') -const customTracker = require('./src/utils/customTracker') -const { index, styles, scripts, tracker, build } = require('./src/ui/index') +import config from './src/utils/config.js' +import * as customTracker from './src/utils/customTracker.js' +import { index, styles, scripts, tracker, build } from './src/ui/index.js' // Build files that are identical on every installation if (config.isPreBuildMode === true) { diff --git a/functions/api.js b/functions/api.js index ea43d588f..aead1ccbb 100644 --- a/functions/api.js +++ b/functions/api.js @@ -1,9 +1,7 @@ -'use strict' - /** * A serverless function handler for the '/api' route, for use with Netlify. * * See: * - https://docs.netlify.com/functions/overview/ */ -exports.handler = require('../src/serverless').handler \ No newline at end of file +export { handler } from '../src/serverless.js' \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 3f3617547..a6eca52c8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -74,7 +74,6 @@ "integrity": "sha512-0YQKKRIxiMlIou+SekQqdCo0ZTHxOcES+K8vKB53cIDpwABNR0P0yRzPgsbgcj3zRJniD93S/ontsnZsCLZrxQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@graphql-typed-document-node/core": "^3.1.1", "@wry/caches": "^1.0.0", @@ -307,7 +306,6 @@ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.5", @@ -2803,7 +2801,6 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -3515,7 +3512,6 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -4411,7 +4407,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.8.25", "caniuse-lite": "^1.0.30001754", @@ -5323,7 +5318,6 @@ "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz", "integrity": "sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==", "license": "MIT", - "peer": true, "dependencies": { "@babel/runtime": "^7.21.0" }, @@ -5880,7 +5874,6 @@ "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", @@ -6467,7 +6460,6 @@ "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", "license": "MIT", - "peer": true, "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", @@ -7162,7 +7154,6 @@ "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.12.0.tgz", "integrity": "sha512-DKKrynuQRne0PNpEbzuEdHlYOMksHSUI8Zc9Unei5gTsMNA2/vMpoMz/yKba50pejK56qj98qM0SjYxAKi13gQ==", "license": "MIT", - "peer": true, "engines": { "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } @@ -8559,7 +8550,6 @@ "resolved": "https://registry.npmjs.org/micro/-/micro-9.4.1.tgz", "integrity": "sha512-Lpjcbp6Y9GJIfewxDfTmu9eW0rt0MGo+Gs1d3yJLFa7mhErtKkCngGhDbA/O1gqUjEwsHh+jWPg8BJ0Bx4AgFA==", "license": "MIT", - "peer": true, "dependencies": { "arg": "4.1.0", "content-type": "1.0.4", @@ -9886,7 +9876,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -10512,7 +10501,6 @@ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -10538,7 +10526,6 @@ "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -10976,7 +10963,6 @@ "integrity": "sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@types/estree": "1.0.8" }, @@ -12656,8 +12642,7 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD", - "peer": true + "license": "0BSD" }, "node_modules/type-check": { "version": "0.4.0", diff --git a/package.json b/package.json index 7f9afe7ff..59ed7133d 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "Tobias Reich " ], "description": "Self-hosted, Node.js based analytics tool for those who care about privacy", + "type": "module", "main": "src/index.js", "keywords": [ "server", diff --git a/src/aggregations/aggregateActions.js b/src/aggregations/aggregateActions.js index 8b4780e41..456ba0878 100644 --- a/src/aggregations/aggregateActions.js +++ b/src/aggregations/aggregateActions.js @@ -1,9 +1,7 @@ -'use strict' +import { INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY } from '../constants/intervals.js' +import matchEvents from '../stages/matchEvents.js' -const intervals = require('../constants/intervals') -const matchEvents = require('../stages/matchEvents') - -module.exports = (ids, average, interval, limit, dateDetails) => { +export default (ids, average, interval, limit, dateDetails) => { const aggregation = [ matchEvents(ids), { @@ -17,9 +15,9 @@ module.exports = (ids, average, interval, limit, dateDetails) => { aggregation[1].$group.count = average === true ? { $avg: '$value' } : { $sum: '$value' } const dateExpression = { date: '$created', timezone: dateDetails.userTimeZone } - const matchDay = [ intervals.INTERVALS_DAILY ].includes(interval) - const matchMonth = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY ].includes(interval) - const matchYear = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY, intervals.INTERVALS_YEARLY ].includes(interval) + const matchDay = [ INTERVALS_DAILY ].includes(interval) + const matchMonth = [ INTERVALS_DAILY, INTERVALS_MONTHLY ].includes(interval) + const matchYear = [ INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY ].includes(interval) if (matchDay === true) aggregation[1].$group._id.day = { $dayOfMonth: dateExpression } if (matchMonth === true) aggregation[1].$group._id.month = { $month: dateExpression } diff --git a/src/aggregations/aggregateActiveVisitors.js b/src/aggregations/aggregateActiveVisitors.js index d59f17d30..610c9b45e 100644 --- a/src/aggregations/aggregateActiveVisitors.js +++ b/src/aggregations/aggregateActiveVisitors.js @@ -1,9 +1,7 @@ -'use strict' +import { DURATIONS_LIMIT, DURATIONS_INTERVAL } from '../constants/durations.js' +import matchDomains from '../stages/matchDomains.js' -const { DURATIONS_LIMIT, DURATIONS_INTERVAL } = require('../constants/durations') -const matchDomains = require('../stages/matchDomains') - -module.exports = (ids, dateDetails) => { +export default (ids, dateDetails) => { const aggregation = [ matchDomains(ids), { diff --git a/src/aggregations/aggregateDurations.js b/src/aggregations/aggregateDurations.js index de56a97cd..83eded94c 100644 --- a/src/aggregations/aggregateDurations.js +++ b/src/aggregations/aggregateDurations.js @@ -1,12 +1,10 @@ -'use strict' +import { INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY } from '../constants/intervals.js' +import matchDomains from '../stages/matchDomains.js' +import projectDuration from '../stages/projectDuration.js' +import projectMinInterval from '../stages/projectMinInterval.js' +import matchLimit from '../stages/matchLimit.js' -const intervals = require('../constants/intervals') -const matchDomains = require('../stages/matchDomains') -const projectDuration = require('../stages/projectDuration') -const projectMinInterval = require('../stages/projectMinInterval') -const matchLimit = require('../stages/matchLimit') - -module.exports = (ids, interval, limit, dateDetails) => { +export default (ids, interval, limit, dateDetails) => { const aggregation = [ matchDomains(ids), projectDuration(), @@ -25,9 +23,9 @@ module.exports = (ids, interval, limit, dateDetails) => { aggregation[0].$match.created = { $gte: dateDetails.includeFnByInterval(interval)(limit) } const dateExpression = { date: '$created', timezone: dateDetails.userTimeZone } - const matchDay = [ intervals.INTERVALS_DAILY ].includes(interval) - const matchMonth = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY ].includes(interval) - const matchYear = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY, intervals.INTERVALS_YEARLY ].includes(interval) + const matchDay = [ INTERVALS_DAILY ].includes(interval) + const matchMonth = [ INTERVALS_DAILY, INTERVALS_MONTHLY ].includes(interval) + const matchYear = [ INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY ].includes(interval) if (matchDay === true) aggregation[4].$group._id.day = { $dayOfMonth: dateExpression } if (matchMonth === true) aggregation[4].$group._id.month = { $month: dateExpression } diff --git a/src/aggregations/aggregateNewActions.js b/src/aggregations/aggregateNewActions.js index 6b612f93c..5d29e6a17 100644 --- a/src/aggregations/aggregateNewActions.js +++ b/src/aggregations/aggregateNewActions.js @@ -1,8 +1,6 @@ -'use strict' +import matchEvents from '../stages/matchEvents.js' -const matchEvents = require('../stages/matchEvents') - -module.exports = (ids, limit) => { +export default (ids, limit) => { const aggregation = [ matchEvents(ids), { diff --git a/src/aggregations/aggregateNewRecords.js b/src/aggregations/aggregateNewRecords.js index 5f60ff970..35d646be2 100644 --- a/src/aggregations/aggregateNewRecords.js +++ b/src/aggregations/aggregateNewRecords.js @@ -1,8 +1,6 @@ -'use strict' +import matchDomains from '../stages/matchDomains.js' -const matchDomains = require('../stages/matchDomains') - -module.exports = (ids, properties, limit, or) => { +export default (ids, properties, limit, or) => { const aggregation = [ matchDomains(ids), { diff --git a/src/aggregations/aggregateRecentActions.js b/src/aggregations/aggregateRecentActions.js index 01b1a874c..50281a9ad 100644 --- a/src/aggregations/aggregateRecentActions.js +++ b/src/aggregations/aggregateRecentActions.js @@ -1,8 +1,6 @@ -'use strict' +import matchEvents from '../stages/matchEvents.js' -const matchEvents = require('../stages/matchEvents') - -module.exports = (ids, limit) => { +export default (ids, limit) => { const aggregation = [ matchEvents(ids), { diff --git a/src/aggregations/aggregateRecentRecords.js b/src/aggregations/aggregateRecentRecords.js index f20bf6c5b..c17c1dc68 100644 --- a/src/aggregations/aggregateRecentRecords.js +++ b/src/aggregations/aggregateRecentRecords.js @@ -1,8 +1,6 @@ -'use strict' +import matchDomains from '../stages/matchDomains.js' -const matchDomains = require('../stages/matchDomains') - -module.exports = (ids, properties, limit, or) => { +export default (ids, properties, limit, or) => { const aggregation = [ matchDomains(ids), { diff --git a/src/aggregations/aggregateTopActions.js b/src/aggregations/aggregateTopActions.js index 30b93da46..9d3932dcf 100644 --- a/src/aggregations/aggregateTopActions.js +++ b/src/aggregations/aggregateTopActions.js @@ -1,9 +1,7 @@ -'use strict' +import { RANGES_LAST_24_HOURS, RANGES_LAST_7_DAYS, RANGES_LAST_30_DAYS, RANGES_LAST_6_MONTHS } from '../constants/ranges.js' +import matchEvents from '../stages/matchEvents.js' -const ranges = require('../constants/ranges') -const matchEvents = require('../stages/matchEvents') - -module.exports = (ids, average, range, limit, dateDetails) => { +export default (ids, average, range, limit, dateDetails) => { const aggregation = [ matchEvents(ids), { @@ -26,19 +24,19 @@ module.exports = (ids, average, range, limit, dateDetails) => { aggregation[0].$match.key = { $ne: null } aggregation[1].$group.count = average === true ? { $avg: '$value' } : { $sum: '$value' } - if (range === ranges.RANGES_LAST_24_HOURS) { + if (range === RANGES_LAST_24_HOURS) { aggregation[0].$match.created = { $gte: dateDetails.lastHours(24) } } - if (range === ranges.RANGES_LAST_7_DAYS) { + if (range === RANGES_LAST_7_DAYS) { aggregation[0].$match.created = { $gte: dateDetails.lastDays(7) } } - if (range === ranges.RANGES_LAST_30_DAYS) { + if (range === RANGES_LAST_30_DAYS) { aggregation[0].$match.created = { $gte: dateDetails.lastDays(30) } } - if (range === ranges.RANGES_LAST_6_MONTHS) { + if (range === RANGES_LAST_6_MONTHS) { aggregation[0].$match.created = { $gte: dateDetails.lastMonths(6) } } diff --git a/src/aggregations/aggregateTopRecords.js b/src/aggregations/aggregateTopRecords.js index 8c1f6eff0..3034ed710 100644 --- a/src/aggregations/aggregateTopRecords.js +++ b/src/aggregations/aggregateTopRecords.js @@ -1,9 +1,7 @@ -'use strict' +import { RANGES_LAST_24_HOURS, RANGES_LAST_7_DAYS, RANGES_LAST_30_DAYS, RANGES_LAST_6_MONTHS } from '../constants/ranges.js' +import matchDomains from '../stages/matchDomains.js' -const ranges = require('../constants/ranges') -const matchDomains = require('../stages/matchDomains') - -module.exports = (ids, properties, range, limit, dateDetails, or) => { +export default (ids, properties, range, limit, dateDetails, or) => { const aggregation = [ matchDomains(ids), { @@ -36,19 +34,19 @@ module.exports = (ids, properties, range, limit, dateDetails, or) => { aggregation[1].$group._id[property] = `$${ property }` }) - if (range === ranges.RANGES_LAST_24_HOURS) { + if (range === RANGES_LAST_24_HOURS) { aggregation[0].$match.created = { $gte: dateDetails.lastHours(24) } } - if (range === ranges.RANGES_LAST_7_DAYS) { + if (range === RANGES_LAST_7_DAYS) { aggregation[0].$match.created = { $gte: dateDetails.lastDays(7) } } - if (range === ranges.RANGES_LAST_30_DAYS) { + if (range === RANGES_LAST_30_DAYS) { aggregation[0].$match.created = { $gte: dateDetails.lastDays(30) } } - if (range === ranges.RANGES_LAST_6_MONTHS) { + if (range === RANGES_LAST_6_MONTHS) { aggregation[0].$match.created = { $gte: dateDetails.lastMonths(6) } } diff --git a/src/aggregations/aggregateViews.js b/src/aggregations/aggregateViews.js index 04643984a..1af276eef 100644 --- a/src/aggregations/aggregateViews.js +++ b/src/aggregations/aggregateViews.js @@ -1,9 +1,7 @@ -'use strict' +import { INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY } from '../constants/intervals.js' +import matchDomains from '../stages/matchDomains.js' -const intervals = require('../constants/intervals') -const matchDomains = require('../stages/matchDomains') - -module.exports = (ids, unique, interval, limit, dateDetails) => { +export default (ids, unique, interval, limit, dateDetails) => { const aggregation = [ matchDomains(ids), { @@ -24,9 +22,9 @@ module.exports = (ids, unique, interval, limit, dateDetails) => { aggregation[0].$match.created = { $gte: dateDetails.includeFnByInterval(interval)(limit) } const dateExpression = { date: '$created', timezone: dateDetails.userTimeZone } - const matchDay = [ intervals.INTERVALS_DAILY ].includes(interval) - const matchMonth = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY ].includes(interval) - const matchYear = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY, intervals.INTERVALS_YEARLY ].includes(interval) + const matchDay = [ INTERVALS_DAILY ].includes(interval) + const matchMonth = [ INTERVALS_DAILY, INTERVALS_MONTHLY ].includes(interval) + const matchYear = [ INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY ].includes(interval) if (matchDay === true) aggregation[1].$group._id.day = { $dayOfMonth: dateExpression } if (matchMonth === true) aggregation[1].$group._id.month = { $month: dateExpression } diff --git a/src/constants/browsers.js b/src/constants/browsers.js index f34543e75..3c8ab3a63 100644 --- a/src/constants/browsers.js +++ b/src/constants/browsers.js @@ -1,9 +1,2 @@ -'use strict' - -const BROWSERS_TYPE_WITH_VERSION = 'WITH_VERSION' -const BROWSERS_TYPE_NO_VERSION = 'NO_VERSION' - -module.exports = { - BROWSERS_TYPE_WITH_VERSION, - BROWSERS_TYPE_NO_VERSION, -} \ No newline at end of file +export const BROWSERS_TYPE_WITH_VERSION = 'WITH_VERSION' +export const BROWSERS_TYPE_NO_VERSION = 'NO_VERSION' \ No newline at end of file diff --git a/src/constants/devices.js b/src/constants/devices.js index e3f7a5aab..8edf75c61 100644 --- a/src/constants/devices.js +++ b/src/constants/devices.js @@ -1,9 +1,2 @@ -'use strict' - -const DEVICES_TYPE_WITH_MODEL = 'WITH_MODEL' -const DEVICES_TYPE_NO_MODEL = 'NO_MODEL' - -module.exports = { - DEVICES_TYPE_WITH_MODEL, - DEVICES_TYPE_NO_MODEL, -} \ No newline at end of file +export const DEVICES_TYPE_WITH_MODEL = 'WITH_MODEL' +export const DEVICES_TYPE_NO_MODEL = 'NO_MODEL' \ No newline at end of file diff --git a/src/constants/durations.js b/src/constants/durations.js index f1ad75d47..f01858c8f 100644 --- a/src/constants/durations.js +++ b/src/constants/durations.js @@ -1,11 +1,4 @@ -'use strict' +import { hour } from '../utils/times.js' -const { hour } = require('../utils/times') - -const DURATIONS_INTERVAL = 15000 -const DURATIONS_LIMIT = hour / 2 - -module.exports = { - DURATIONS_INTERVAL, - DURATIONS_LIMIT, -} \ No newline at end of file +export const DURATIONS_INTERVAL = 15000 +export const DURATIONS_LIMIT = hour / 2 \ No newline at end of file diff --git a/src/constants/events.js b/src/constants/events.js index 91cd45691..fc8c3ca5f 100644 --- a/src/constants/events.js +++ b/src/constants/events.js @@ -1,13 +1,4 @@ -'use strict' - -const EVENTS_TYPE_TOTAL_CHART = 'TOTAL_CHART' -const EVENTS_TYPE_AVERAGE_CHART = 'AVERAGE_CHART' -const EVENTS_TYPE_TOTAL_LIST = 'TOTAL_LIST' -const EVENTS_TYPE_AVERAGE_LIST = 'AVERAGE_LIST' - -module.exports = { - EVENTS_TYPE_TOTAL_CHART, - EVENTS_TYPE_AVERAGE_CHART, - EVENTS_TYPE_TOTAL_LIST, - EVENTS_TYPE_AVERAGE_LIST, -} \ No newline at end of file +export const EVENTS_TYPE_TOTAL_CHART = 'TOTAL_CHART' +export const EVENTS_TYPE_AVERAGE_CHART = 'AVERAGE_CHART' +export const EVENTS_TYPE_TOTAL_LIST = 'TOTAL_LIST' +export const EVENTS_TYPE_AVERAGE_LIST = 'AVERAGE_LIST' \ No newline at end of file diff --git a/src/constants/intervals.js b/src/constants/intervals.js index 8b54438cb..c83204014 100644 --- a/src/constants/intervals.js +++ b/src/constants/intervals.js @@ -1,11 +1,3 @@ -'use strict' - -const INTERVALS_DAILY = 'DAILY' -const INTERVALS_MONTHLY = 'MONTHLY' -const INTERVALS_YEARLY = 'YEARLY' - -module.exports = { - INTERVALS_DAILY, - INTERVALS_MONTHLY, - INTERVALS_YEARLY, -} \ No newline at end of file +export const INTERVALS_DAILY = 'DAILY' +export const INTERVALS_MONTHLY = 'MONTHLY' +export const INTERVALS_YEARLY = 'YEARLY' \ No newline at end of file diff --git a/src/constants/ranges.js b/src/constants/ranges.js index 50f2fbf22..c0309e4b8 100644 --- a/src/constants/ranges.js +++ b/src/constants/ranges.js @@ -1,13 +1,4 @@ -'use strict' - -const RANGES_LAST_24_HOURS = 'LAST_24_HOURS' -const RANGES_LAST_7_DAYS = 'LAST_7_DAYS' -const RANGES_LAST_30_DAYS = 'LAST_30_DAYS' -const RANGES_LAST_6_MONTHS = 'LAST_6_MONTHS' - -module.exports = { - RANGES_LAST_24_HOURS, - RANGES_LAST_7_DAYS, - RANGES_LAST_30_DAYS, - RANGES_LAST_6_MONTHS, -} \ No newline at end of file +export const RANGES_LAST_24_HOURS = 'LAST_24_HOURS' +export const RANGES_LAST_7_DAYS = 'LAST_7_DAYS' +export const RANGES_LAST_30_DAYS = 'LAST_30_DAYS' +export const RANGES_LAST_6_MONTHS = 'LAST_6_MONTHS' \ No newline at end of file diff --git a/src/constants/referrers.js b/src/constants/referrers.js index 4ef272be0..25cee780a 100644 --- a/src/constants/referrers.js +++ b/src/constants/referrers.js @@ -1,11 +1,3 @@ -'use strict' - -const REFERRERS_TYPE_WITH_SOURCE = 'WITH_SOURCE' -const REFERRERS_TYPE_NO_SOURCE = 'NO_SOURCE' -const REFERRERS_TYPE_ONLY_SOURCE = 'ONLY_SOURCE' - -module.exports = { - REFERRERS_TYPE_WITH_SOURCE, - REFERRERS_TYPE_NO_SOURCE, - REFERRERS_TYPE_ONLY_SOURCE, -} \ No newline at end of file +export const REFERRERS_TYPE_WITH_SOURCE = 'WITH_SOURCE' +export const REFERRERS_TYPE_NO_SOURCE = 'NO_SOURCE' +export const REFERRERS_TYPE_ONLY_SOURCE = 'ONLY_SOURCE' \ No newline at end of file diff --git a/src/constants/sizes.js b/src/constants/sizes.js index bd1524a35..9d2ee701c 100644 --- a/src/constants/sizes.js +++ b/src/constants/sizes.js @@ -1,17 +1,6 @@ -'use strict' - -const SIZES_TYPE_BROWSER_HEIGHT = 'BROWSER_HEIGHT' -const SIZES_TYPE_BROWSER_RESOLUTION = 'BROWSER_RESOLUTION' -const SIZES_TYPE_BROWSER_WIDTH = 'BROWSER_WIDTH' -const SIZES_TYPE_SCREEN_HEIGHT = 'SCREEN_HEIGHT' -const SIZES_TYPE_SCREEN_RESOLUTION = 'SCREEN_RESOLUTION' -const SIZES_TYPE_SCREEN_WIDTH = 'SCREEN_WIDTH' - -module.exports = { - SIZES_TYPE_BROWSER_HEIGHT, - SIZES_TYPE_BROWSER_RESOLUTION, - SIZES_TYPE_BROWSER_WIDTH, - SIZES_TYPE_SCREEN_HEIGHT, - SIZES_TYPE_SCREEN_RESOLUTION, - SIZES_TYPE_SCREEN_WIDTH, -} \ No newline at end of file +export const SIZES_TYPE_BROWSER_HEIGHT = 'BROWSER_HEIGHT' +export const SIZES_TYPE_BROWSER_RESOLUTION = 'BROWSER_RESOLUTION' +export const SIZES_TYPE_BROWSER_WIDTH = 'BROWSER_WIDTH' +export const SIZES_TYPE_SCREEN_HEIGHT = 'SCREEN_HEIGHT' +export const SIZES_TYPE_SCREEN_RESOLUTION = 'SCREEN_RESOLUTION' +export const SIZES_TYPE_SCREEN_WIDTH = 'SCREEN_WIDTH' \ No newline at end of file diff --git a/src/constants/sortings.js b/src/constants/sortings.js index dd3ada468..bd350e58e 100644 --- a/src/constants/sortings.js +++ b/src/constants/sortings.js @@ -1,11 +1,3 @@ -'use strict' - -const SORTINGS_TOP = 'TOP' -const SORTINGS_NEW = 'NEW' -const SORTINGS_RECENT = 'RECENT' - -module.exports = { - SORTINGS_TOP, - SORTINGS_NEW, - SORTINGS_RECENT, -} \ No newline at end of file +export const SORTINGS_TOP = 'TOP' +export const SORTINGS_NEW = 'NEW' +export const SORTINGS_RECENT = 'RECENT' \ No newline at end of file diff --git a/src/constants/systems.js b/src/constants/systems.js index 9e59f8ef1..642d4fe63 100644 --- a/src/constants/systems.js +++ b/src/constants/systems.js @@ -1,9 +1,2 @@ -'use strict' - -const SYSTEMS_TYPE_WITH_VERSION = 'WITH_VERSION' -const SYSTEMS_TYPE_NO_VERSION = 'NO_VERSION' - -module.exports = { - SYSTEMS_TYPE_WITH_VERSION, - SYSTEMS_TYPE_NO_VERSION, -} \ No newline at end of file +export const SYSTEMS_TYPE_WITH_VERSION = 'WITH_VERSION' +export const SYSTEMS_TYPE_NO_VERSION = 'NO_VERSION' \ No newline at end of file diff --git a/src/constants/views.js b/src/constants/views.js index 1e6178d76..56078597b 100644 --- a/src/constants/views.js +++ b/src/constants/views.js @@ -1,9 +1,2 @@ -'use strict' - -const VIEWS_TYPE_UNIQUE = 'UNIQUE' -const VIEWS_TYPE_TOTAL = 'TOTAL' - -module.exports = { - VIEWS_TYPE_UNIQUE, - VIEWS_TYPE_TOTAL, -} \ No newline at end of file +export const VIEWS_TYPE_UNIQUE = 'UNIQUE' +export const VIEWS_TYPE_TOTAL = 'TOTAL' \ No newline at end of file diff --git a/src/database/actions.js b/src/database/actions.js index 90890b398..1b455fd14 100644 --- a/src/database/actions.js +++ b/src/database/actions.js @@ -1,17 +1,15 @@ -'use strict' - -const { utcToZonedTime } = require('date-fns-tz') - -const Action = require('../models/Action') -const aggregateTopActions = require('../aggregations/aggregateTopActions') -const aggregateNewActions = require('../aggregations/aggregateNewActions') -const aggregateRecentActions = require('../aggregations/aggregateRecentActions') -const aggregateActions = require('../aggregations/aggregateActions') -const sortings = require('../constants/sortings') -const intervals = require('../constants/intervals') -const createArray = require('../utils/createArray') -const matchesDate = require('../utils/matchesDate') -const recursiveId = require('../utils/recursiveId') +import { utcToZonedTime } from 'date-fns-tz/esm' + +import Action from '../models/Action.js' +import aggregateTopActions from '../aggregations/aggregateTopActions.js' +import aggregateNewActions from '../aggregations/aggregateNewActions.js' +import aggregateRecentActions from '../aggregations/aggregateRecentActions.js' +import aggregateActions from '../aggregations/aggregateActions.js' +import { SORTINGS_TOP, SORTINGS_NEW, SORTINGS_RECENT } from '../constants/sortings.js' +import { INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY } from '../constants/intervals.js' +import createArray from '../utils/createArray.js' +import matchesDate from '../utils/matchesDate.js' +import recursiveId from '../utils/recursiveId.js' const response = (entry) => ({ id: entry.id, @@ -22,7 +20,7 @@ const response = (entry) => ({ updated: entry.updated, }) -const add = async (data) => { +export const add = async (data) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } @@ -32,7 +30,7 @@ const add = async (data) => { ) } -const update = async (id, data) => { +export const update = async (id, data) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } @@ -53,16 +51,16 @@ const update = async (id, data) => { ) } -const getChart = async (ids, type, interval, limit, dateDetails) => { +export const getChart = async (ids, type, interval, limit, dateDetails) => { const aggregation = (() => { if (type === 'TOTAL') return aggregateActions(ids, false, interval, limit, dateDetails) if (type === 'AVERAGE') return aggregateActions(ids, true, interval, limit, dateDetails) })() const enhance = (entries) => { - const matchDay = [ intervals.INTERVALS_DAILY ].includes(interval) - const matchMonth = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY ].includes(interval) - const matchYear = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY, intervals.INTERVALS_YEARLY ].includes(interval) + const matchDay = [ INTERVALS_DAILY ].includes(interval) + const matchMonth = [ INTERVALS_DAILY, INTERVALS_MONTHLY ].includes(interval) + const matchYear = [ INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY ].includes(interval) return createArray(limit).map((_, index) => { const date = dateDetails.lastFnByInterval(interval)(index) @@ -101,17 +99,17 @@ const getChart = async (ids, type, interval, limit, dateDetails) => { ) } -const getList = async (ids, sorting, type, range, limit, dateDetails) => { +export const getList = async (ids, sorting, type, range, limit, dateDetails) => { const aggregation = (() => { if (type === 'TOTAL') { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopActions(ids, false, range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewActions(ids, limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentActions(ids, limit) + if (sorting === SORTINGS_TOP) return aggregateTopActions(ids, false, range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewActions(ids, limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentActions(ids, limit) } if (type === 'AVERAGE') { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopActions(ids, true, range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewActions(ids, limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentActions(ids, limit) + if (sorting === SORTINGS_TOP) return aggregateTopActions(ids, true, range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewActions(ids, limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentActions(ids, limit) } })() @@ -137,16 +135,8 @@ const getList = async (ids, sorting, type, range, limit, dateDetails) => { ) } -const del = (eventId) => { +export const del = (eventId) => { return Action.deleteMany({ eventId, }) -} - -module.exports = { - add, - update, - getChart, - getList, - del, } \ No newline at end of file diff --git a/src/database/browsers.js b/src/database/browsers.js index 22ff5600a..6dd912f78 100644 --- a/src/database/browsers.js +++ b/src/database/browsers.js @@ -1,30 +1,28 @@ -'use strict' - -const Record = require('../models/Record') -const aggregateTopRecords = require('../aggregations/aggregateTopRecords') -const aggregateNewRecords = require('../aggregations/aggregateNewRecords') -const aggregateRecentRecords = require('../aggregations/aggregateRecentRecords') -const sortings = require('../constants/sortings') -const constants = require('../constants/browsers') -const recursiveId = require('../utils/recursiveId') +import Record from '../models/Record.js' +import aggregateTopRecords from '../aggregations/aggregateTopRecords.js' +import aggregateNewRecords from '../aggregations/aggregateNewRecords.js' +import aggregateRecentRecords from '../aggregations/aggregateRecentRecords.js' +import { SORTINGS_TOP, SORTINGS_NEW, SORTINGS_RECENT } from '../constants/sortings.js' +import { BROWSERS_TYPE_NO_VERSION, BROWSERS_TYPE_WITH_VERSION } from '../constants/browsers.js' +import recursiveId from '../utils/recursiveId.js' const get = async (ids, sorting, type, range, limit, dateDetails) => { const aggregation = (() => { - if (type === constants.BROWSERS_TYPE_NO_VERSION) { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'browserName' ], range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'browserName' ], limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'browserName' ], limit) + if (type === BROWSERS_TYPE_NO_VERSION) { + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'browserName' ], range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'browserName' ], limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'browserName' ], limit) } - if (type === constants.BROWSERS_TYPE_WITH_VERSION) { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'browserName', 'browserVersion' ], range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'browserName', 'browserVersion' ], limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'browserName', 'browserVersion' ], limit) + if (type === BROWSERS_TYPE_WITH_VERSION) { + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'browserName', 'browserVersion' ], range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'browserName', 'browserVersion' ], limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'browserName', 'browserVersion' ], limit) } })() const enhanceId = (id) => { - if (type === constants.BROWSERS_TYPE_NO_VERSION) return `${ id.browserName }` - if (type === constants.BROWSERS_TYPE_WITH_VERSION) return `${ id.browserName } ${ id.browserVersion }` + if (type === BROWSERS_TYPE_NO_VERSION) return `${ id.browserName }` + if (type === BROWSERS_TYPE_WITH_VERSION) return `${ id.browserName } ${ id.browserVersion }` } const enhance = (entries) => { @@ -45,6 +43,4 @@ const get = async (ids, sorting, type, range, limit, dateDetails) => { ) } -module.exports = { - get, -} \ No newline at end of file +export default get \ No newline at end of file diff --git a/src/database/devices.js b/src/database/devices.js index b1c2f349b..1061c529d 100644 --- a/src/database/devices.js +++ b/src/database/devices.js @@ -1,30 +1,28 @@ -'use strict' - -const Record = require('../models/Record') -const aggregateTopRecords = require('../aggregations/aggregateTopRecords') -const aggregateNewRecords = require('../aggregations/aggregateNewRecords') -const aggregateRecentRecords = require('../aggregations/aggregateRecentRecords') -const sortings = require('../constants/sortings') -const constants = require('../constants/devices') -const recursiveId = require('../utils/recursiveId') +import Record from '../models/Record.js' +import aggregateTopRecords from '../aggregations/aggregateTopRecords.js' +import aggregateNewRecords from '../aggregations/aggregateNewRecords.js' +import aggregateRecentRecords from '../aggregations/aggregateRecentRecords.js' +import { SORTINGS_TOP, SORTINGS_NEW, SORTINGS_RECENT } from '../constants/sortings.js' +import { DEVICES_TYPE_NO_MODEL, DEVICES_TYPE_WITH_MODEL } from '../constants/devices.js' +import recursiveId from '../utils/recursiveId.js' const get = async (ids, sorting, type, range, limit, dateDetails) => { const aggregation = (() => { - if (type === constants.DEVICES_TYPE_NO_MODEL) { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'deviceManufacturer' ], range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'deviceManufacturer' ], limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'deviceManufacturer' ], limit) + if (type === DEVICES_TYPE_NO_MODEL) { + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'deviceManufacturer' ], range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'deviceManufacturer' ], limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'deviceManufacturer' ], limit) } - if (type === constants.DEVICES_TYPE_WITH_MODEL) { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'deviceManufacturer', 'deviceName' ], range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'deviceManufacturer', 'deviceName' ], limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'deviceManufacturer', 'deviceName' ], limit) + if (type === DEVICES_TYPE_WITH_MODEL) { + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'deviceManufacturer', 'deviceName' ], range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'deviceManufacturer', 'deviceName' ], limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'deviceManufacturer', 'deviceName' ], limit) } })() const enhanceId = (id) => { - if (type === constants.DEVICES_TYPE_NO_MODEL) return `${ id.deviceManufacturer }` - if (type === constants.DEVICES_TYPE_WITH_MODEL) return `${ id.deviceManufacturer } ${ id.deviceName }` + if (type === DEVICES_TYPE_NO_MODEL) return `${ id.deviceManufacturer }` + if (type === DEVICES_TYPE_WITH_MODEL) return `${ id.deviceManufacturer } ${ id.deviceName }` } const enhance = (entries) => { @@ -41,10 +39,8 @@ const get = async (ids, sorting, type, range, limit, dateDetails) => { } return enhance( - await Record.aggregate(aggregation), +await Record.aggregate(aggregation), ) } -module.exports = { - get, -} \ No newline at end of file +export default get \ No newline at end of file diff --git a/src/database/domains.js b/src/database/domains.js index 2a4eddae4..01161476e 100644 --- a/src/database/domains.js +++ b/src/database/domains.js @@ -1,7 +1,5 @@ -'use strict' - -const Domain = require('../models/Domain') -const sortByProp = require('../utils/sortByProp') +import Domain from '../models/Domain.js' +import sortByProp from '../utils/sortByProp.js' const response = (entry) => ({ id: entry.id, @@ -10,19 +8,19 @@ const response = (entry) => ({ updated: entry.updated, }) -const add = async (data) => { +export const add = async (data) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Domain.create({ - title: data.title, - }), +await Domain.create({ + title: data.title, +}), ) } -const all = async () => { +export const all = async () => { const enhance = (entries) => { return entries .map(response) @@ -30,49 +28,41 @@ const all = async () => { } return enhance( - await Domain.find({}), +await Domain.find({}), ) } -const get = async (id) => { +export const get = async (id) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Domain.findOne({ id }), +await Domain.findOne({ id }), ) } -const update = async (id, data) => { +export const update = async (id, data) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Domain.findOneAndUpdate({ - id, - }, { - $set: { - title: data.title, - updated: Date.now(), - }, - }, { - new: true, - }), +await Domain.findOneAndUpdate({ + id, +}, { + $set: { + title: data.title, + updated: Date.now(), + }, +}, { + new: true, +}), ) } -const del = (id) => { +export const del = (id) => { return Domain.findOneAndDelete({ id, }) -} - -module.exports = { - add, - all, - get, - update, - del, } \ No newline at end of file diff --git a/src/database/durations.js b/src/database/durations.js index ca260ef3c..fe9e2221b 100644 --- a/src/database/durations.js +++ b/src/database/durations.js @@ -1,13 +1,11 @@ -'use strict' +import { utcToZonedTime } from 'date-fns-tz/esm' -const { utcToZonedTime } = require('date-fns-tz') - -const Record = require('../models/Record') -const aggregateDurations = require('../aggregations/aggregateDurations') -const intervals = require('../constants/intervals') -const createArray = require('../utils/createArray') -const matchesDate = require('../utils/matchesDate') -const recursiveId = require('../utils/recursiveId') +import Record from '../models/Record.js' +import aggregateDurations from '../aggregations/aggregateDurations.js' +import { INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY } from '../constants/intervals.js' +import createArray from '../utils/createArray.js' +import matchesDate from '../utils/matchesDate.js' +import recursiveId from '../utils/recursiveId.js' const get = async (ids, interval, limit, dateDetails) => { const aggregation = (() => { @@ -15,9 +13,9 @@ const get = async (ids, interval, limit, dateDetails) => { })() const enhance = (entries) => { - const matchDay = [ intervals.INTERVALS_DAILY ].includes(interval) - const matchMonth = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY ].includes(interval) - const matchYear = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY, intervals.INTERVALS_YEARLY ].includes(interval) + const matchDay = [ INTERVALS_DAILY ].includes(interval) + const matchMonth = [ INTERVALS_DAILY, INTERVALS_MONTHLY ].includes(interval) + const matchYear = [ INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY ].includes(interval) return createArray(limit).map((_, index) => { const date = dateDetails.lastFnByInterval(interval)(index) @@ -30,10 +28,10 @@ const get = async (ids, interval, limit, dateDetails) => { // Find a entry that matches the date const entry = entries.find((entry) => { return matchesDate( - matchDay === true ? entry._id.day : undefined, - matchMonth === true ? entry._id.month : undefined, - matchYear === true ? entry._id.year : undefined, - userZonedDate, +matchDay === true ? entry._id.day : undefined, +matchMonth === true ? entry._id.month : undefined, +matchYear === true ? entry._id.year : undefined, +userZonedDate, ) }) @@ -52,10 +50,8 @@ const get = async (ids, interval, limit, dateDetails) => { } return enhance( - await Record.aggregate(aggregation), +await Record.aggregate(aggregation), ) } -module.exports = { - get, -} \ No newline at end of file +export default get \ No newline at end of file diff --git a/src/database/events.js b/src/database/events.js index bc0cb7f2e..6741fbe22 100644 --- a/src/database/events.js +++ b/src/database/events.js @@ -1,7 +1,5 @@ -'use strict' - -const Event = require('../models/Event') -const sortByProp = require('../utils/sortByProp') +import Event from '../models/Event.js' +import sortByProp from '../utils/sortByProp.js' const response = (entry) => ({ id: entry.id, @@ -11,17 +9,17 @@ const response = (entry) => ({ updated: entry.updated, }) -const add = async (data) => { +export const add = async (data) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Event.create(data), +await Event.create(data), ) } -const all = async () => { +export const all = async () => { const enhance = (entries) => { return entries .map(response) @@ -29,50 +27,42 @@ const all = async () => { } return enhance( - await Event.find({}), +await Event.find({}), ) } -const get = async (id) => { +export const get = async (id) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Event.findOne({ id }), +await Event.findOne({ id }), ) } -const update = async (id, data) => { +export const update = async (id, data) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Event.findOneAndUpdate({ - id, - }, { - $set: { - title: data.title, - type: data.type, - updated: Date.now(), - }, - }, { - new: true, - }), +await Event.findOneAndUpdate({ + id, +}, { + $set: { + title: data.title, + type: data.type, + updated: Date.now(), + }, +}, { + new: true, +}), ) } -const del = (id) => { +export const del = (id) => { return Event.findOneAndDelete({ id, }) -} - -module.exports = { - add, - all, - get, - update, - del, } \ No newline at end of file diff --git a/src/database/facts.js b/src/database/facts.js index 0afcc35ca..70872b58a 100644 --- a/src/database/facts.js +++ b/src/database/facts.js @@ -1,7 +1,5 @@ -'use strict' - -const Record = require('../models/Record') -const aggregateActiveVisitors = require('../aggregations/aggregateActiveVisitors') +import Record from '../models/Record.js' +import aggregateActiveVisitors from '../aggregations/aggregateActiveVisitors.js' const getActiveVisitors = async (ids, dateDetails) => { const enhance = (entries) => { @@ -10,12 +8,10 @@ const getActiveVisitors = async (ids, dateDetails) => { } return enhance( - await Record.aggregate( - aggregateActiveVisitors(ids, dateDetails), - ), +await Record.aggregate( +aggregateActiveVisitors(ids, dateDetails), +), ) } -module.exports = { - getActiveVisitors, -} \ No newline at end of file +export default getActiveVisitors \ No newline at end of file diff --git a/src/database/languages.js b/src/database/languages.js index 885dc9909..3289864a6 100644 --- a/src/database/languages.js +++ b/src/database/languages.js @@ -1,18 +1,16 @@ -'use strict' - -const Record = require('../models/Record') -const aggregateTopRecords = require('../aggregations/aggregateTopRecords') -const aggregateNewRecords = require('../aggregations/aggregateNewRecords') -const aggregateRecentRecords = require('../aggregations/aggregateRecentRecords') -const sortings = require('../constants/sortings') -const languageCodes = require('../utils/languageCodes') -const recursiveId = require('../utils/recursiveId') +import Record from '../models/Record.js' +import aggregateTopRecords from '../aggregations/aggregateTopRecords.js' +import aggregateNewRecords from '../aggregations/aggregateNewRecords.js' +import aggregateRecentRecords from '../aggregations/aggregateRecentRecords.js' +import { SORTINGS_TOP, SORTINGS_NEW, SORTINGS_RECENT } from '../constants/sortings.js' +import languageCodes from '../utils/languageCodes.js' +import recursiveId from '../utils/recursiveId.js' const get = async (ids, sorting, range, limit, dateDetails) => { const aggregation = (() => { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'siteLanguage' ], range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'siteLanguage' ], limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'siteLanguage' ], limit) + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'siteLanguage' ], range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'siteLanguage' ], limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'siteLanguage' ], limit) })() const enhanceId = (id) => { @@ -33,10 +31,8 @@ const get = async (ids, sorting, range, limit, dateDetails) => { } return enhance( - await Record.aggregate(aggregation), +await Record.aggregate(aggregation), ) } -module.exports = { - get, -} \ No newline at end of file +export default get \ No newline at end of file diff --git a/src/database/pages.js b/src/database/pages.js index 60053fe8a..da111b87a 100644 --- a/src/database/pages.js +++ b/src/database/pages.js @@ -1,17 +1,15 @@ -'use strict' - -const Record = require('../models/Record') -const aggregateTopRecords = require('../aggregations/aggregateTopRecords') -const aggregateNewRecords = require('../aggregations/aggregateNewRecords') -const aggregateRecentRecords = require('../aggregations/aggregateRecentRecords') -const sortings = require('../constants/sortings') -const recursiveId = require('../utils/recursiveId') +import Record from '../models/Record.js' +import aggregateTopRecords from '../aggregations/aggregateTopRecords.js' +import aggregateNewRecords from '../aggregations/aggregateNewRecords.js' +import aggregateRecentRecords from '../aggregations/aggregateRecentRecords.js' +import { SORTINGS_TOP, SORTINGS_NEW, SORTINGS_RECENT } from '../constants/sortings.js' +import recursiveId from '../utils/recursiveId.js' const get = async (ids, sorting, range, limit, dateDetails) => { const aggregation = (() => { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'siteLocation' ], range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'siteLocation' ], limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'siteLocation' ], limit) + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'siteLocation' ], range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'siteLocation' ], limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'siteLocation' ], limit) })() const enhanceId = (id) => { @@ -32,10 +30,8 @@ const get = async (ids, sorting, range, limit, dateDetails) => { } return enhance( - await Record.aggregate(aggregation), +await Record.aggregate(aggregation), ) } -module.exports = { - get, -} \ No newline at end of file +export default get \ No newline at end of file diff --git a/src/database/permanentTokens.js b/src/database/permanentTokens.js index 8fef60a2e..b87cfee7d 100644 --- a/src/database/permanentTokens.js +++ b/src/database/permanentTokens.js @@ -1,7 +1,5 @@ -'use strict' - -const PermanentToken = require('../models/PermanentToken') -const sortByProp = require('../utils/sortByProp') +import PermanentToken from '../models/PermanentToken.js' +import sortByProp from '../utils/sortByProp.js' const response = (entry) => ({ id: entry.id, @@ -10,19 +8,19 @@ const response = (entry) => ({ updated: entry.updated, }) -const add = async (data) => { +export const add = async (data) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await PermanentToken.create({ - title: data.title, - }), +await PermanentToken.create({ + title: data.title, +}), ) } -const all = async () => { +export const all = async () => { const enhance = (entries) => { return entries .map(response) @@ -30,49 +28,41 @@ const all = async () => { } return enhance( - await PermanentToken.find({}), +await PermanentToken.find({}), ) } -const get = async (id) => { +export const get = async (id) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await PermanentToken.findOne({ id }), +await PermanentToken.findOne({ id }), ) } -const update = async (id, data) => { +export const update = async (id, data) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await PermanentToken.findOneAndUpdate({ - id, - }, { - $set: { - title: data.title, - updated: Date.now(), - }, - }, { - new: true, - }), +await PermanentToken.findOneAndUpdate({ + id, +}, { + $set: { + title: data.title, + updated: Date.now(), + }, +}, { + new: true, +}), ) } -const del = (id) => { +export const del = (id) => { return PermanentToken.findOneAndDelete({ id, }) -} - -module.exports = { - add, - all, - get, - update, - del, } \ No newline at end of file diff --git a/src/database/records.js b/src/database/records.js index e2413e124..da2a9ed89 100644 --- a/src/database/records.js +++ b/src/database/records.js @@ -1,6 +1,4 @@ -'use strict' - -const Record = require('../models/Record') +import Record from '../models/Record.js' const response = (entry) => ({ id: entry.id, @@ -23,54 +21,54 @@ const response = (entry) => ({ updated: entry.updated, }) -const add = async (data) => { +export const add = async (data) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Record.create({ - clientId: data.clientId, - domainId: data.domainId, - siteLocation: data.siteLocation, - siteReferrer: data.siteReferrer, - siteLanguage: data.siteLanguage, - source: data.source, - screenWidth: data.screenWidth, - screenHeight: data.screenHeight, - screenColorDepth: data.screenColorDepth, - deviceName: data.deviceName, - deviceManufacturer: data.deviceManufacturer, - osName: data.osName, - osVersion: data.osVersion, - browserName: data.browserName, - browserVersion: data.browserVersion, - browserWidth: data.browserWidth, - browserHeight: data.browserHeight, - }), +await Record.create({ + clientId: data.clientId, + domainId: data.domainId, + siteLocation: data.siteLocation, + siteReferrer: data.siteReferrer, + siteLanguage: data.siteLanguage, + source: data.source, + screenWidth: data.screenWidth, + screenHeight: data.screenHeight, + screenColorDepth: data.screenColorDepth, + deviceName: data.deviceName, + deviceManufacturer: data.deviceManufacturer, + osName: data.osName, + osVersion: data.osVersion, + browserName: data.browserName, + browserVersion: data.browserVersion, + browserWidth: data.browserWidth, + browserHeight: data.browserHeight, +}), ) } -const update = async (id) => { +export const update = async (id) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Record.findOneAndUpdate({ - id, - }, { - $set: { - updated: Date.now(), - }, - }, { - new: true, - }), +await Record.findOneAndUpdate({ + id, +}, { + $set: { + updated: Date.now(), + }, +}, { + new: true, +}), ) } -const anonymize = (clientId, ignoreId) => { - // Don't return anything about the update +export const anonymize = (clientId, ignoreId) => { +// Don't return anything about the update return Record.updateMany({ $and: [ { clientId }, @@ -97,15 +95,8 @@ const anonymize = (clientId, ignoreId) => { }) } -const del = (domainId) => { +export const del = (domainId) => { return Record.deleteMany({ domainId, }) -} - -module.exports = { - add, - update, - anonymize, - del, } \ No newline at end of file diff --git a/src/database/referrers.js b/src/database/referrers.js index 97335fcec..6680db8ab 100644 --- a/src/database/referrers.js +++ b/src/database/referrers.js @@ -1,29 +1,27 @@ -'use strict' - -const Record = require('../models/Record') -const aggregateTopRecords = require('../aggregations/aggregateTopRecords') -const aggregateRecentRecords = require('../aggregations/aggregateRecentRecords') -const aggregateNewRecords = require('../aggregations/aggregateNewRecords') -const sortings = require('../constants/sortings') -const constants = require('../constants/referrers') -const recursiveId = require('../utils/recursiveId') +import Record from '../models/Record.js' +import aggregateTopRecords from '../aggregations/aggregateTopRecords.js' +import aggregateRecentRecords from '../aggregations/aggregateRecentRecords.js' +import aggregateNewRecords from '../aggregations/aggregateNewRecords.js' +import { SORTINGS_TOP, SORTINGS_NEW, SORTINGS_RECENT } from '../constants/sortings.js' +import { REFERRERS_TYPE_WITH_SOURCE, REFERRERS_TYPE_NO_SOURCE, REFERRERS_TYPE_ONLY_SOURCE } from '../constants/referrers.js' +import recursiveId from '../utils/recursiveId.js' const get = async (ids, sorting, type, range, limit, dateDetails) => { const aggregation = (() => { - if (type === constants.REFERRERS_TYPE_WITH_SOURCE) { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'source', 'siteReferrer' ], range, limit, dateDetails, true) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'source', 'siteReferrer' ], limit, true) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'source', 'siteReferrer' ], limit, true) + if (type === REFERRERS_TYPE_WITH_SOURCE) { + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'source', 'siteReferrer' ], range, limit, dateDetails, true) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'source', 'siteReferrer' ], limit, true) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'source', 'siteReferrer' ], limit, true) } - if (type === constants.REFERRERS_TYPE_NO_SOURCE) { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'siteReferrer' ], range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'siteReferrer' ], limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'siteReferrer' ], limit) + if (type === REFERRERS_TYPE_NO_SOURCE) { + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'siteReferrer' ], range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'siteReferrer' ], limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'siteReferrer' ], limit) } - if (type === constants.REFERRERS_TYPE_ONLY_SOURCE) { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'source' ], range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'source' ], limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'source' ], limit) + if (type === REFERRERS_TYPE_ONLY_SOURCE) { + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'source' ], range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'source' ], limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'source' ], limit) } })() @@ -45,10 +43,8 @@ const get = async (ids, sorting, type, range, limit, dateDetails) => { } return enhance( - await Record.aggregate(aggregation), +await Record.aggregate(aggregation), ) } -module.exports = { - get, -} \ No newline at end of file +export default get \ No newline at end of file diff --git a/src/database/sizes.js b/src/database/sizes.js index e0f5fe089..358080848 100644 --- a/src/database/sizes.js +++ b/src/database/sizes.js @@ -1,48 +1,53 @@ -'use strict' - -const Record = require('../models/Record') -const aggregateTopRecords = require('../aggregations/aggregateTopRecords') -const aggregateNewRecords = require('../aggregations/aggregateNewRecords') -const aggregateRecentRecords = require('../aggregations/aggregateRecentRecords') -const sortings = require('../constants/sortings') -const constants = require('../constants/sizes') -const recursiveId = require('../utils/recursiveId') +import Record from '../models/Record.js' +import aggregateTopRecords from '../aggregations/aggregateTopRecords.js' +import aggregateNewRecords from '../aggregations/aggregateNewRecords.js' +import aggregateRecentRecords from '../aggregations/aggregateRecentRecords.js' +import { SORTINGS_TOP, SORTINGS_NEW, SORTINGS_RECENT } from '../constants/sortings.js' +import { + SIZES_TYPE_BROWSER_HEIGHT, + SIZES_TYPE_BROWSER_RESOLUTION, + SIZES_TYPE_BROWSER_WIDTH, + SIZES_TYPE_SCREEN_HEIGHT, + SIZES_TYPE_SCREEN_RESOLUTION, + SIZES_TYPE_SCREEN_WIDTH, +} from '../constants/sizes.js' +import recursiveId from '../utils/recursiveId.js' const get = async (ids, sorting, type, range, limit, dateDetails) => { const aggregation = (() => { - if (sorting === sortings.SORTINGS_TOP) { - if (type === constants.SIZES_TYPE_BROWSER_WIDTH) return aggregateTopRecords(ids, [ 'browserWidth' ], range, limit, dateDetails) - if (type === constants.SIZES_TYPE_BROWSER_HEIGHT) return aggregateTopRecords(ids, [ 'browserHeight' ], range, limit, dateDetails) - if (type === constants.SIZES_TYPE_BROWSER_RESOLUTION) return aggregateTopRecords(ids, [ 'browserWidth', 'browserHeight' ], range, limit, dateDetails) - if (type === constants.SIZES_TYPE_SCREEN_WIDTH) return aggregateTopRecords(ids, [ 'screenWidth' ], range, limit, dateDetails) - if (type === constants.SIZES_TYPE_SCREEN_HEIGHT) return aggregateTopRecords(ids, [ 'screenHeight' ], range, limit, dateDetails) - if (type === constants.SIZES_TYPE_SCREEN_RESOLUTION) return aggregateTopRecords(ids, [ 'screenWidth', 'screenHeight' ], range, limit, dateDetails) + if (sorting === SORTINGS_TOP) { + if (type === SIZES_TYPE_BROWSER_WIDTH) return aggregateTopRecords(ids, [ 'browserWidth' ], range, limit, dateDetails) + if (type === SIZES_TYPE_BROWSER_HEIGHT) return aggregateTopRecords(ids, [ 'browserHeight' ], range, limit, dateDetails) + if (type === SIZES_TYPE_BROWSER_RESOLUTION) return aggregateTopRecords(ids, [ 'browserWidth', 'browserHeight' ], range, limit, dateDetails) + if (type === SIZES_TYPE_SCREEN_WIDTH) return aggregateTopRecords(ids, [ 'screenWidth' ], range, limit, dateDetails) + if (type === SIZES_TYPE_SCREEN_HEIGHT) return aggregateTopRecords(ids, [ 'screenHeight' ], range, limit, dateDetails) + if (type === SIZES_TYPE_SCREEN_RESOLUTION) return aggregateTopRecords(ids, [ 'screenWidth', 'screenHeight' ], range, limit, dateDetails) } - if (sorting === sortings.SORTINGS_NEW) { - if (type === constants.SIZES_TYPE_BROWSER_WIDTH) return aggregateNewRecords(ids, [ 'browserWidth' ], limit) - if (type === constants.SIZES_TYPE_BROWSER_HEIGHT) return aggregateNewRecords(ids, [ 'browserHeight' ], limit) - if (type === constants.SIZES_TYPE_BROWSER_RESOLUTION) return aggregateNewRecords(ids, [ 'browserWidth', 'browserHeight' ], limit) - if (type === constants.SIZES_TYPE_SCREEN_WIDTH) return aggregateNewRecords(ids, [ 'screenWidth' ], limit) - if (type === constants.SIZES_TYPE_SCREEN_HEIGHT) return aggregateNewRecords(ids, [ 'screenHeight' ], limit) - if (type === constants.SIZES_TYPE_SCREEN_RESOLUTION) return aggregateNewRecords(ids, [ 'screenWidth', 'screenHeight' ], limit) + if (sorting === SORTINGS_NEW) { + if (type === SIZES_TYPE_BROWSER_WIDTH) return aggregateNewRecords(ids, [ 'browserWidth' ], limit) + if (type === SIZES_TYPE_BROWSER_HEIGHT) return aggregateNewRecords(ids, [ 'browserHeight' ], limit) + if (type === SIZES_TYPE_BROWSER_RESOLUTION) return aggregateNewRecords(ids, [ 'browserWidth', 'browserHeight' ], limit) + if (type === SIZES_TYPE_SCREEN_WIDTH) return aggregateNewRecords(ids, [ 'screenWidth' ], limit) + if (type === SIZES_TYPE_SCREEN_HEIGHT) return aggregateNewRecords(ids, [ 'screenHeight' ], limit) + if (type === SIZES_TYPE_SCREEN_RESOLUTION) return aggregateNewRecords(ids, [ 'screenWidth', 'screenHeight' ], limit) } - if (sorting === sortings.SORTINGS_RECENT) { - if (type === constants.SIZES_TYPE_BROWSER_WIDTH) return aggregateRecentRecords(ids, [ 'browserWidth' ], limit) - if (type === constants.SIZES_TYPE_BROWSER_HEIGHT) return aggregateRecentRecords(ids, [ 'browserHeight' ], limit) - if (type === constants.SIZES_TYPE_BROWSER_RESOLUTION) return aggregateRecentRecords(ids, [ 'browserWidth', 'browserHeight' ], limit) - if (type === constants.SIZES_TYPE_SCREEN_WIDTH) return aggregateRecentRecords(ids, [ 'screenWidth' ], limit) - if (type === constants.SIZES_TYPE_SCREEN_HEIGHT) return aggregateRecentRecords(ids, [ 'screenHeight' ], limit) - if (type === constants.SIZES_TYPE_SCREEN_RESOLUTION) return aggregateRecentRecords(ids, [ 'screenWidth', 'screenHeight' ], limit) + if (sorting === SORTINGS_RECENT) { + if (type === SIZES_TYPE_BROWSER_WIDTH) return aggregateRecentRecords(ids, [ 'browserWidth' ], limit) + if (type === SIZES_TYPE_BROWSER_HEIGHT) return aggregateRecentRecords(ids, [ 'browserHeight' ], limit) + if (type === SIZES_TYPE_BROWSER_RESOLUTION) return aggregateRecentRecords(ids, [ 'browserWidth', 'browserHeight' ], limit) + if (type === SIZES_TYPE_SCREEN_WIDTH) return aggregateRecentRecords(ids, [ 'screenWidth' ], limit) + if (type === SIZES_TYPE_SCREEN_HEIGHT) return aggregateRecentRecords(ids, [ 'screenHeight' ], limit) + if (type === SIZES_TYPE_SCREEN_RESOLUTION) return aggregateRecentRecords(ids, [ 'screenWidth', 'screenHeight' ], limit) } })() const enhanceId = (id) => { - if (type === constants.SIZES_TYPE_BROWSER_WIDTH) return `${ id.browserWidth }px` - if (type === constants.SIZES_TYPE_BROWSER_HEIGHT) return `${ id.browserHeight }px` - if (type === constants.SIZES_TYPE_BROWSER_RESOLUTION) return `${ id.browserWidth }px x ${ id.browserHeight }px` - if (type === constants.SIZES_TYPE_SCREEN_WIDTH) return `${ id.screenWidth }px` - if (type === constants.SIZES_TYPE_SCREEN_HEIGHT) return `${ id.screenHeight }px` - if (type === constants.SIZES_TYPE_SCREEN_RESOLUTION) return `${ id.screenWidth }px x ${ id.screenHeight }px` + if (type === SIZES_TYPE_BROWSER_WIDTH) return `${ id.browserWidth }px` + if (type === SIZES_TYPE_BROWSER_HEIGHT) return `${ id.browserHeight }px` + if (type === SIZES_TYPE_BROWSER_RESOLUTION) return `${ id.browserWidth }px x ${ id.browserHeight }px` + if (type === SIZES_TYPE_SCREEN_WIDTH) return `${ id.screenWidth }px` + if (type === SIZES_TYPE_SCREEN_HEIGHT) return `${ id.screenHeight }px` + if (type === SIZES_TYPE_SCREEN_RESOLUTION) return `${ id.screenWidth }px x ${ id.screenHeight }px` } const enhance = (entries) => { @@ -59,10 +64,8 @@ const get = async (ids, sorting, type, range, limit, dateDetails) => { } return enhance( - await Record.aggregate(aggregation), +await Record.aggregate(aggregation), ) } -module.exports = { - get, -} \ No newline at end of file +export default get \ No newline at end of file diff --git a/src/database/systems.js b/src/database/systems.js index 6b1be4b24..73a86f64d 100644 --- a/src/database/systems.js +++ b/src/database/systems.js @@ -1,30 +1,28 @@ -'use strict' - -const Record = require('../models/Record') -const aggregateTopRecords = require('../aggregations/aggregateTopRecords') -const aggregateNewRecords = require('../aggregations/aggregateNewRecords') -const aggregateRecentRecords = require('../aggregations/aggregateRecentRecords') -const sortings = require('../constants/sortings') -const constants = require('../constants/systems') -const recursiveId = require('../utils/recursiveId') +import Record from '../models/Record.js' +import aggregateTopRecords from '../aggregations/aggregateTopRecords.js' +import aggregateNewRecords from '../aggregations/aggregateNewRecords.js' +import aggregateRecentRecords from '../aggregations/aggregateRecentRecords.js' +import { SORTINGS_TOP, SORTINGS_NEW, SORTINGS_RECENT } from '../constants/sortings.js' +import { SYSTEMS_TYPE_NO_VERSION, SYSTEMS_TYPE_WITH_VERSION } from '../constants/systems.js' +import recursiveId from '../utils/recursiveId.js' const get = async (ids, sorting, type, range, limit, dateDetails) => { const aggregation = (() => { - if (type === constants.SYSTEMS_TYPE_NO_VERSION) { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'osName' ], range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'osName' ], limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'osName' ], limit) + if (type === SYSTEMS_TYPE_NO_VERSION) { + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'osName' ], range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'osName' ], limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'osName' ], limit) } - if (type === constants.SYSTEMS_TYPE_WITH_VERSION) { - if (sorting === sortings.SORTINGS_TOP) return aggregateTopRecords(ids, [ 'osName', 'osVersion' ], range, limit, dateDetails) - if (sorting === sortings.SORTINGS_NEW) return aggregateNewRecords(ids, [ 'osName', 'osVersion' ], limit) - if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'osName', 'osVersion' ], limit) + if (type === SYSTEMS_TYPE_WITH_VERSION) { + if (sorting === SORTINGS_TOP) return aggregateTopRecords(ids, [ 'osName', 'osVersion' ], range, limit, dateDetails) + if (sorting === SORTINGS_NEW) return aggregateNewRecords(ids, [ 'osName', 'osVersion' ], limit) + if (sorting === SORTINGS_RECENT) return aggregateRecentRecords(ids, [ 'osName', 'osVersion' ], limit) } })() const enhanceId = (id) => { - if (type === constants.SYSTEMS_TYPE_NO_VERSION) return `${ id.osName }` - if (type === constants.SYSTEMS_TYPE_WITH_VERSION) return `${ id.osName } ${ id.osVersion }` + if (type === SYSTEMS_TYPE_NO_VERSION) return `${ id.osName }` + if (type === SYSTEMS_TYPE_WITH_VERSION) return `${ id.osName } ${ id.osVersion }` } const enhance = (entries) => { @@ -41,10 +39,8 @@ const get = async (ids, sorting, type, range, limit, dateDetails) => { } return enhance( - await Record.aggregate(aggregation), +await Record.aggregate(aggregation), ) } -module.exports = { - get, -} \ No newline at end of file +export default get \ No newline at end of file diff --git a/src/database/tokens.js b/src/database/tokens.js index b6b2e8dea..87d46665d 100644 --- a/src/database/tokens.js +++ b/src/database/tokens.js @@ -1,6 +1,4 @@ -'use strict' - -const Token = require('../models/Token') +import Token from '../models/Token.js' const response = (entry) => ({ id: entry.id, @@ -8,53 +6,46 @@ const response = (entry) => ({ updated: entry.updated, }) -const add = async () => { +export const add = async () => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Token.create({}), +await Token.create({}), ) } -const get = async (id) => { +export const get = async (id) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Token.findOne({ id }), +await Token.findOne({ id }), ) } -const update = async (id) => { +export const update = async (id) => { const enhance = (entry) => { return entry == null ? entry : response(entry) } return enhance( - await Token.findOneAndUpdate({ - id, - }, { - $set: { - updated: Date.now(), - }, - }, { - new: true, - }), +await Token.findOneAndUpdate({ + id, +}, { + $set: { + updated: Date.now(), + }, +}, { + new: true, +}), ) } -const del = (id) => { +export const del = (id) => { return Token.findOneAndDelete({ id, }) -} - -module.exports = { - add, - get, - update, - del, } \ No newline at end of file diff --git a/src/database/views.js b/src/database/views.js index bd6292c81..897a2a887 100644 --- a/src/database/views.js +++ b/src/database/views.js @@ -1,25 +1,23 @@ -'use strict' +import { utcToZonedTime } from 'date-fns-tz/esm' -const { utcToZonedTime } = require('date-fns-tz') - -const Record = require('../models/Record') -const aggregateViews = require('../aggregations/aggregateViews') -const constants = require('../constants/views') -const intervals = require('../constants/intervals') -const createArray = require('../utils/createArray') -const matchesDate = require('../utils/matchesDate') -const recursiveId = require('../utils/recursiveId') +import Record from '../models/Record.js' +import aggregateViews from '../aggregations/aggregateViews.js' +import { VIEWS_TYPE_UNIQUE, VIEWS_TYPE_TOTAL } from '../constants/views.js' +import { INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY } from '../constants/intervals.js' +import createArray from '../utils/createArray.js' +import matchesDate from '../utils/matchesDate.js' +import recursiveId from '../utils/recursiveId.js' const get = async (ids, type, interval, limit, dateDetails) => { const aggregation = (() => { - if (type === constants.VIEWS_TYPE_UNIQUE) return aggregateViews(ids, true, interval, limit, dateDetails) - if (type === constants.VIEWS_TYPE_TOTAL) return aggregateViews(ids, false, interval, limit, dateDetails) + if (type === VIEWS_TYPE_UNIQUE) return aggregateViews(ids, true, interval, limit, dateDetails) + if (type === VIEWS_TYPE_TOTAL) return aggregateViews(ids, false, interval, limit, dateDetails) })() const enhance = (entries) => { - const matchDay = [ intervals.INTERVALS_DAILY ].includes(interval) - const matchMonth = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY ].includes(interval) - const matchYear = [ intervals.INTERVALS_DAILY, intervals.INTERVALS_MONTHLY, intervals.INTERVALS_YEARLY ].includes(interval) + const matchDay = [ INTERVALS_DAILY ].includes(interval) + const matchMonth = [ INTERVALS_DAILY, INTERVALS_MONTHLY ].includes(interval) + const matchYear = [ INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY ].includes(interval) return createArray(limit).map((_, index) => { const date = dateDetails.lastFnByInterval(interval)(index) @@ -32,10 +30,10 @@ const get = async (ids, type, interval, limit, dateDetails) => { // Find a entry that matches the date const entry = entries.find((entry) => { return matchesDate( - matchDay === true ? entry._id.day : undefined, - matchMonth === true ? entry._id.month : undefined, - matchYear === true ? entry._id.year : undefined, - userZonedDate, +matchDay === true ? entry._id.day : undefined, +matchMonth === true ? entry._id.month : undefined, +matchYear === true ? entry._id.year : undefined, +userZonedDate, ) }) @@ -54,10 +52,8 @@ const get = async (ids, type, interval, limit, dateDetails) => { } return enhance( - await Record.aggregate(aggregation), +await Record.aggregate(aggregation), ) } -module.exports = { - get, -} \ No newline at end of file +export default get \ No newline at end of file diff --git a/src/healthcheck.js b/src/healthcheck.js index 8b74e713f..933cabc9b 100755 --- a/src/healthcheck.js +++ b/src/healthcheck.js @@ -1,10 +1,9 @@ #!/usr/bin/env node -'use strict' -require('dotenv').config() +import 'dotenv/config' -const signale = require('./utils/signale') -const config = require('./utils/config') -const checkMongoDB = require('./utils/connect') +import signale from './utils/signale.js' +import config from './utils/config.js' +import connect from './utils/connect.js' if (config.dbUrl == null) { signale.fatal('MongoDB connection URI missing in environment') @@ -30,7 +29,7 @@ const checkApi = async (url) => { const exit = (healthy) => process.exit(healthy === true ? 0 : 1) const check = () => Promise.all([ - checkMongoDB(config.dbUrl), + connect(config.dbUrl), checkServer(`http://localhost:${ config.port }`), checkApi(`http://localhost:${ config.port }/.well-known/apollo/server-health`), ]) diff --git a/src/index.js b/src/index.js index 46ccd08a1..4a45c58cd 100644 --- a/src/index.js +++ b/src/index.js @@ -1,12 +1,11 @@ #!/usr/bin/env node -'use strict' -require('dotenv').config() - -const server = require('./server') -const signale = require('./utils/signale') -const config = require('./utils/config') -const connect = require('./utils/connect') -const stripUrlAuth = require('./utils/stripUrlAuth') +import 'dotenv/config' + +import server from './server.js' +import signale from './utils/signale.js' +import config from './utils/config.js' +import connect from './utils/connect.js' +import stripUrlAuth from './utils/stripUrlAuth.js' if (config.dbUrl == null) { signale.fatal('MongoDB connection URI missing in environment') diff --git a/src/middlewares/blockDemoMode.js b/src/middlewares/blockDemoMode.js index 747ac8dc7..327dda0fa 100644 --- a/src/middlewares/blockDemoMode.js +++ b/src/middlewares/blockDemoMode.js @@ -1,8 +1,6 @@ -'use strict' +import KnownError from '../utils/KnownError.js' -const KnownError = require('../utils/KnownError') - -module.exports = (parent, args, { isDemoMode }) => { +export default (parent, args, { isDemoMode }) => { if (isDemoMode === true) { throw new KnownError('Forbidden in demo mode') } diff --git a/src/middlewares/requireAuth.js b/src/middlewares/requireAuth.js index 8bf1939a8..33ff01c04 100644 --- a/src/middlewares/requireAuth.js +++ b/src/middlewares/requireAuth.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = (parent, args, { isAuthenticated }) => { +export default (parent, args, { isAuthenticated }) => { if (isAuthenticated !== true) { throw isAuthenticated } diff --git a/src/models/Action.js b/src/models/Action.js index 72b7c5478..9dc696768 100644 --- a/src/models/Action.js +++ b/src/models/Action.js @@ -1,7 +1,5 @@ -'use strict' - -const mongoose = require('mongoose') -const uuid = require('crypto').randomUUID +import mongoose from 'mongoose' +import { randomUUID as uuid } from 'crypto' const schema = new mongoose.Schema({ id: { @@ -39,4 +37,4 @@ const schema = new mongoose.Schema({ }, }) -module.exports = mongoose.model('Action', schema) \ No newline at end of file +export default mongoose.model('Action', schema) \ No newline at end of file diff --git a/src/models/Domain.js b/src/models/Domain.js index 1d53ccf33..796023da4 100644 --- a/src/models/Domain.js +++ b/src/models/Domain.js @@ -1,7 +1,5 @@ -'use strict' - -const mongoose = require('mongoose') -const uuid = require('crypto').randomUUID +import mongoose from 'mongoose' +import { randomUUID as uuid } from 'crypto' const schema = new mongoose.Schema({ id: { @@ -26,4 +24,4 @@ const schema = new mongoose.Schema({ }, }) -module.exports = mongoose.model('Domain', schema) \ No newline at end of file +export default mongoose.model('Domain', schema) \ No newline at end of file diff --git a/src/models/Event.js b/src/models/Event.js index 9406e749d..1245fcf9e 100644 --- a/src/models/Event.js +++ b/src/models/Event.js @@ -1,15 +1,13 @@ -'use strict' +import mongoose from 'mongoose' +import { randomUUID as uuid } from 'crypto' -const mongoose = require('mongoose') -const uuid = require('crypto').randomUUID - -const events = require('../constants/events') +import { EVENTS_TYPE_TOTAL_CHART, EVENTS_TYPE_AVERAGE_CHART, EVENTS_TYPE_TOTAL_LIST, EVENTS_TYPE_AVERAGE_LIST } from '../constants/events.js' const isKnownType = (value) => [ - events.EVENTS_TYPE_TOTAL_CHART, - events.EVENTS_TYPE_AVERAGE_CHART, - events.EVENTS_TYPE_TOTAL_LIST, - events.EVENTS_TYPE_AVERAGE_LIST, + EVENTS_TYPE_TOTAL_CHART, + EVENTS_TYPE_AVERAGE_CHART, + EVENTS_TYPE_TOTAL_LIST, + EVENTS_TYPE_AVERAGE_LIST, ].includes(value) const schema = new mongoose.Schema({ @@ -40,4 +38,4 @@ const schema = new mongoose.Schema({ }, }) -module.exports = mongoose.model('Event', schema) \ No newline at end of file +export default mongoose.model('Event', schema) \ No newline at end of file diff --git a/src/models/PermanentToken.js b/src/models/PermanentToken.js index 619bc9789..5d00e06f3 100644 --- a/src/models/PermanentToken.js +++ b/src/models/PermanentToken.js @@ -1,7 +1,5 @@ -'use strict' - -const mongoose = require('mongoose') -const uuid = require('crypto').randomUUID +import mongoose from 'mongoose' +import { randomUUID as uuid } from 'crypto' const schema = new mongoose.Schema({ id: { @@ -26,4 +24,4 @@ const schema = new mongoose.Schema({ }, }) -module.exports = mongoose.model('PermanentToken', schema) \ No newline at end of file +export default mongoose.model('PermanentToken', schema) \ No newline at end of file diff --git a/src/models/Record.js b/src/models/Record.js index 2c6a32633..488135219 100644 --- a/src/models/Record.js +++ b/src/models/Record.js @@ -1,8 +1,6 @@ -'use strict' - -const mongoose = require('mongoose') -const uuid = require('crypto').randomUUID -const isUrl = require('is-url') +import mongoose from 'mongoose' +import { randomUUID as uuid } from 'crypto' +import isUrl from 'is-url' const isNullOrUrl = (value) => value == null || isUrl(value) @@ -96,4 +94,4 @@ const schema = new mongoose.Schema({ }, }) -module.exports = mongoose.model('Record', schema) \ No newline at end of file +export default mongoose.model('Record', schema) \ No newline at end of file diff --git a/src/models/Token.js b/src/models/Token.js index d64198560..c44727b9e 100644 --- a/src/models/Token.js +++ b/src/models/Token.js @@ -1,7 +1,5 @@ -'use strict' - -const mongoose = require('mongoose') -const uuid = require('crypto').randomUUID +import mongoose from 'mongoose' +import { randomUUID as uuid } from 'crypto' const schema = new mongoose.Schema({ id: { @@ -22,4 +20,4 @@ const schema = new mongoose.Schema({ }, }) -module.exports = mongoose.model('Token', schema) \ No newline at end of file +export default mongoose.model('Token', schema) \ No newline at end of file diff --git a/src/resolvers/actions.js b/src/resolvers/actions.js index a88f2ed83..117212694 100644 --- a/src/resolvers/actions.js +++ b/src/resolvers/actions.js @@ -1,9 +1,7 @@ -'use strict' - -const KnownError = require('../utils/KnownError') -const messages = require('../utils/messages') -const events = require('../database/events') -const actions = require('../database/actions') +import KnownError from '../utils/KnownError.js' +import messages from '../utils/messages.js' +import * as events from '../database/events.js' +import * as actions from '../database/actions.js' const polish = (obj) => { return Object.entries(obj).reduce((acc, [ key, value ]) => { @@ -16,7 +14,7 @@ const polish = (obj) => { }, {}) } -module.exports = { +export default { Mutation: { createAction: async (parent, { eventId, input }, { isIgnored }) => { // Ignore your own actions when logged in diff --git a/src/resolvers/domainStatistics.js b/src/resolvers/domainStatistics.js index 260a0fd21..338700242 100644 --- a/src/resolvers/domainStatistics.js +++ b/src/resolvers/domainStatistics.js @@ -1,20 +1,18 @@ -'use strict' +import getViews from '../database/views.js' +import getPages from '../database/pages.js' +import getReferrers from '../database/referrers.js' +import getDurations from '../database/durations.js' +import getSystems from '../database/systems.js' +import getDevices from '../database/devices.js' +import getBrowsers from '../database/browsers.js' +import getSizes from '../database/sizes.js' +import getLanguages from '../database/languages.js' +import pipe from '../utils/pipe.js' +import domainIds from '../utils/domainIds.js' +import recursiveId from '../utils/recursiveId.js' +import requireAuth from '../middlewares/requireAuth.js' -const views = require('../database/views') -const pages = require('../database/pages') -const referrers = require('../database/referrers') -const durations = require('../database/durations') -const systems = require('../database/systems') -const devices = require('../database/devices') -const browsers = require('../database/browsers') -const sizes = require('../database/sizes') -const languages = require('../database/languages') -const pipe = require('../utils/pipe') -const domainIds = require('../utils/domainIds') -const recursiveId = require('../utils/recursiveId') -const requireAuth = require('../middlewares/requireAuth') - -module.exports = { +export default { DomainStatistics: { id: pipe(requireAuth, async (domain) => { const ids = await domainIds(domain) @@ -26,39 +24,39 @@ module.exports = { }), views: pipe(requireAuth, async (domain, { type, interval, limit }, { dateDetails }) => { const ids = await domainIds(domain) - return views.get(ids, type, interval, limit, dateDetails) + return getViews(ids, type, interval, limit, dateDetails) }), pages: pipe(requireAuth, async (domain, { sorting, range, limit }, { dateDetails }) => { const ids = await domainIds(domain) - return pages.get(ids, sorting, range, limit, dateDetails) + return getPages(ids, sorting, range, limit, dateDetails) }), referrers: pipe(requireAuth, async (domain, { sorting, type, range, limit }, { dateDetails }) => { const ids = await domainIds(domain) - return referrers.get(ids, sorting, type, range, limit, dateDetails) + return getReferrers(ids, sorting, type, range, limit, dateDetails) }), durations: pipe(requireAuth, async (domain, { interval, limit }, { dateDetails }) => { const ids = await domainIds(domain) - return durations.get(ids, interval, limit, dateDetails) + return getDurations(ids, interval, limit, dateDetails) }), systems: pipe(requireAuth, async (domain, { sorting, type, range, limit }, { dateDetails }) => { const ids = await domainIds(domain) - return systems.get(ids, sorting, type, range, limit, dateDetails) + return getSystems(ids, sorting, type, range, limit, dateDetails) }), devices: pipe(requireAuth, async (domain, { sorting, type, range, limit }, { dateDetails }) => { const ids = await domainIds(domain) - return devices.get(ids, sorting, type, range, limit, dateDetails) + return getDevices(ids, sorting, type, range, limit, dateDetails) }), browsers: pipe(requireAuth, async (domain, { sorting, type, range, limit }, { dateDetails }) => { const ids = await domainIds(domain) - return browsers.get(ids, sorting, type, range, limit, dateDetails) + return getBrowsers(ids, sorting, type, range, limit, dateDetails) }), sizes: pipe(requireAuth, async (domain, { sorting, type, range, limit }, { dateDetails }) => { const ids = await domainIds(domain) - return sizes.get(ids, sorting, type, range, limit, dateDetails) + return getSizes(ids, sorting, type, range, limit, dateDetails) }), languages: pipe(requireAuth, async (domain, { sorting, range, limit }, { dateDetails }) => { const ids = await domainIds(domain) - return languages.get(ids, sorting, range, limit, dateDetails) + return getLanguages(ids, sorting, range, limit, dateDetails) }), }, Query: { diff --git a/src/resolvers/domains.js b/src/resolvers/domains.js index 9eea9e9f6..54d7694e3 100644 --- a/src/resolvers/domains.js +++ b/src/resolvers/domains.js @@ -1,14 +1,12 @@ -'use strict' +import * as records from '../database/records.js' +import * as domains from '../database/domains.js' +import KnownError from '../utils/KnownError.js' +import messages from '../utils/messages.js' +import pipe from '../utils/pipe.js' +import requireAuth from '../middlewares/requireAuth.js' +import blockDemoMode from '../middlewares/blockDemoMode.js' -const records = require('../database/records') -const domains = require('../database/domains') -const KnownError = require('../utils/KnownError') -const messages = require('../utils/messages') -const pipe = require('../utils/pipe') -const requireAuth = require('../middlewares/requireAuth') -const blockDemoMode = require('../middlewares/blockDemoMode') - -module.exports = { +export default { Domain: { facts: (parent) => parent, statistics: (parent) => parent, diff --git a/src/resolvers/eventStatistics.js b/src/resolvers/eventStatistics.js index 313a71b01..25ec8a710 100644 --- a/src/resolvers/eventStatistics.js +++ b/src/resolvers/eventStatistics.js @@ -1,10 +1,8 @@ -'use strict' +import * as actions from '../database/actions.js' +import pipe from '../utils/pipe.js' +import requireAuth from '../middlewares/requireAuth.js' -const actions = require('../database/actions') -const pipe = require('../utils/pipe') -const requireAuth = require('../middlewares/requireAuth') - -module.exports = { +export default { EventStatistics: { id: pipe(requireAuth, (event) => { return event.id diff --git a/src/resolvers/events.js b/src/resolvers/events.js index a4fffaf0d..d959ffe72 100644 --- a/src/resolvers/events.js +++ b/src/resolvers/events.js @@ -1,14 +1,12 @@ -'use strict' +import * as actions from '../database/actions.js' +import * as events from '../database/events.js' +import KnownError from '../utils/KnownError.js' +import messages from '../utils/messages.js' +import pipe from '../utils/pipe.js' +import requireAuth from '../middlewares/requireAuth.js' +import blockDemoMode from '../middlewares/blockDemoMode.js' -const actions = require('../database/actions') -const events = require('../database/events') -const KnownError = require('../utils/KnownError') -const messages = require('../utils/messages') -const pipe = require('../utils/pipe') -const requireAuth = require('../middlewares/requireAuth') -const blockDemoMode = require('../middlewares/blockDemoMode') - -module.exports = { +export default { Event: { statistics: (parent) => parent, }, diff --git a/src/resolvers/facts.js b/src/resolvers/facts.js index 8d6ddcda9..fc84e8978 100644 --- a/src/resolvers/facts.js +++ b/src/resolvers/facts.js @@ -1,16 +1,14 @@ -'use strict' - -const views = require('../database/views') -const facts = require('../database/facts') -const durations = require('../database/durations') -const viewsType = require('../constants/views') -const intervals = require('../constants/intervals') -const pipe = require('../utils/pipe') -const domainIds = require('../utils/domainIds') -const recursiveId = require('../utils/recursiveId') -const requireAuth = require('../middlewares/requireAuth') - -module.exports = { +import getViews from '../database/views.js' +import getActiveVisitors from '../database/facts.js' +import getDurations from '../database/durations.js' +import { VIEWS_TYPE_UNIQUE } from '../constants/views.js' +import { INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY } from '../constants/intervals.js' +import pipe from '../utils/pipe.js' +import domainIds from '../utils/domainIds.js' +import recursiveId from '../utils/recursiveId.js' +import requireAuth from '../middlewares/requireAuth.js' + +export default { AverageViews: { count: pipe(requireAuth, (entries) => { const totalCount = entries.slice(1, 15).reduce((acc, entry) => acc + entry.count, 0) @@ -54,37 +52,37 @@ module.exports = { }), activeVisitors: pipe(requireAuth, async (domain, _, { dateDetails }) => { const ids = await domainIds(domain) - const activeVisitors = await facts.getActiveVisitors(ids, dateDetails) + const activeVisitors = await getActiveVisitors(ids, dateDetails) return activeVisitors }), averageViews: pipe(requireAuth, async (domain, _, { dateDetails }) => { const ids = await domainIds(domain) - const entries = views.get(ids, viewsType.VIEWS_TYPE_UNIQUE, intervals.INTERVALS_DAILY, 15, dateDetails) + const entries = getViews(ids, VIEWS_TYPE_UNIQUE, INTERVALS_DAILY, 15, dateDetails) return entries }), averageDuration: pipe(requireAuth, async (domain, _, { dateDetails }) => { const ids = await domainIds(domain) - const entries = durations.get(ids, intervals.INTERVALS_DAILY, 15, dateDetails) + const entries = getDurations(ids, INTERVALS_DAILY, 15, dateDetails) return entries }), viewsToday: pipe(requireAuth, async (domain, _, { dateDetails }) => { const ids = await domainIds(domain) - const entries = await views.get(ids, viewsType.VIEWS_TYPE_UNIQUE, intervals.INTERVALS_DAILY, 1, dateDetails) + const entries = await getViews(ids, VIEWS_TYPE_UNIQUE, INTERVALS_DAILY, 1, dateDetails) return entries[0].count }), viewsMonth: pipe(requireAuth, async (domain, _, { dateDetails }) => { const ids = await domainIds(domain) - const entries = await views.get(ids, viewsType.VIEWS_TYPE_UNIQUE, intervals.INTERVALS_MONTHLY, 1, dateDetails) + const entries = await getViews(ids, VIEWS_TYPE_UNIQUE, INTERVALS_MONTHLY, 1, dateDetails) return entries[0].count }), viewsYear: pipe(requireAuth, async (domain, _, { dateDetails }) => { const ids = await domainIds(domain) - const entries = await views.get(ids, viewsType.VIEWS_TYPE_UNIQUE, intervals.INTERVALS_YEARLY, 1, dateDetails) + const entries = await getViews(ids, VIEWS_TYPE_UNIQUE, INTERVALS_YEARLY, 1, dateDetails) return entries[0].count }), diff --git a/src/resolvers/index.js b/src/resolvers/index.js index 7a4deef5a..430aa1095 100644 --- a/src/resolvers/index.js +++ b/src/resolvers/index.js @@ -1,15 +1,23 @@ -'use strict' +import { mergeResolvers } from '@graphql-tools/merge' -const { mergeResolvers } = require('@graphql-tools/merge') +import tokens from './tokens.js' +import permanentTokens from './permanentTokens.js' +import records from './records.js' +import domains from './domains.js' +import events from './events.js' +import actions from './actions.js' +import facts from './facts.js' +import domainStatistics from './domainStatistics.js' +import eventStatistics from './eventStatistics.js' -module.exports = mergeResolvers([ - require('./tokens'), - require('./permanentTokens'), - require('./records'), - require('./domains'), - require('./events'), - require('./actions'), - require('./facts'), - require('./domainStatistics'), - require('./eventStatistics'), +export default mergeResolvers([ + tokens, + permanentTokens, + records, + domains, + events, + actions, + facts, + domainStatistics, + eventStatistics, ]) \ No newline at end of file diff --git a/src/resolvers/permanentTokens.js b/src/resolvers/permanentTokens.js index 60daf3c7f..3972c1294 100644 --- a/src/resolvers/permanentTokens.js +++ b/src/resolvers/permanentTokens.js @@ -1,13 +1,11 @@ -'use strict' +import * as permanentTokens from '../database/permanentTokens.js' +import KnownError from '../utils/KnownError.js' +import messages from '../utils/messages.js' +import pipe from '../utils/pipe.js' +import requireAuth from '../middlewares/requireAuth.js' +import blockDemoMode from '../middlewares/blockDemoMode.js' -const permanentTokens = require('../database/permanentTokens') -const KnownError = require('../utils/KnownError') -const messages = require('../utils/messages') -const pipe = require('../utils/pipe') -const requireAuth = require('../middlewares/requireAuth') -const blockDemoMode = require('../middlewares/blockDemoMode') - -module.exports = { +export default { Query: { permanentToken: pipe(requireAuth, (parent, { id }) => { return permanentTokens.get(id) diff --git a/src/resolvers/records.js b/src/resolvers/records.js index 092e5f1c7..3d37c572c 100644 --- a/src/resolvers/records.js +++ b/src/resolvers/records.js @@ -1,11 +1,9 @@ -'use strict' - -const KnownError = require('../utils/KnownError') -const normalizeUrl = require('../utils/normalizeUrl') -const identifier = require('../utils/identifier') -const messages = require('../utils/messages') -const domains = require('../database/domains') -const records = require('../database/records') +import KnownError from '../utils/KnownError.js' +import normalizeUrl from '../utils/normalizeUrl.js' +import identifier from '../utils/identifier.js' +import messages from '../utils/messages.js' +import * as domains from '../database/domains.js' +import * as records from '../database/records.js' const normalizeSiteLocation = (siteLocation) => { if (siteLocation == null) { @@ -21,7 +19,7 @@ const normalizeSiteLocation = (siteLocation) => { } const normalizeSiteReferrer = (siteReferrer) => { - // The siteReferrer is optional +// The siteReferrer is optional if (siteReferrer == null) return siteReferrer try { @@ -45,7 +43,7 @@ const polish = (obj) => { }, {}) } -module.exports = { +export default { Mutation: { createRecord: async (parent, { domainId, input }, { ip, userAgent, isIgnored }) => { // Ignore your own records when logged in diff --git a/src/resolvers/tokens.js b/src/resolvers/tokens.js index 89015891e..3cdc2b036 100644 --- a/src/resolvers/tokens.js +++ b/src/resolvers/tokens.js @@ -1,9 +1,7 @@ -'use strict' - -const tokens = require('../database/tokens') -const config = require('../utils/config') -const KnownError = require('../utils/KnownError') -const ignoreCookie = require('../utils/ignoreCookie') +import * as tokens from '../database/tokens.js' +import config from '../utils/config.js' +import KnownError from '../utils/KnownError.js' +import { on as ignoreCookieOn, off as ignoreCookieOff } from '../utils/ignoreCookie.js' const response = (entry) => ({ id: entry.id, @@ -11,7 +9,7 @@ const response = (entry) => ({ updated: entry.updated, }) -module.exports = { +export default { Mutation: { createToken: async (parent, { input }, { setCookies }) => { const { username, password } = input @@ -25,7 +23,7 @@ module.exports = { const entry = await tokens.add() // Set cookie to avoid reporting your own visits - setCookies.push(ignoreCookie.on) + setCookies.push(ignoreCookieOn) return { success: true, @@ -36,7 +34,7 @@ module.exports = { await tokens.del(id) // Remove cookie to report your own visits, again - setCookies.push(ignoreCookie.off) + setCookies.push(ignoreCookieOff) return { success: true, diff --git a/src/server.js b/src/server.js index b8bffa8c4..df1101796 100644 --- a/src/server.js +++ b/src/server.js @@ -1,19 +1,23 @@ -'use strict' - -const micro = require('micro') -const { resolve } = require('path') -const { readFile } = require('fs').promises -const { send, createError } = require('micro') -const { router, get, post, put, patch, del } = require('microrouter') -const { ApolloServer } = require('apollo-server-micro') - -const KnownError = require('./utils/KnownError') -const signale = require('./utils/signale') -const config = require('./utils/config') -const findMatchingOrigin = require('./utils/findMatchingOrigin') -const customTracker = require('./utils/customTracker') -const createApolloServer = require('./utils/createApolloServer') -const { createMicroContext } = require('./utils/createContext') +import micro from 'micro' +import { resolve, dirname } from 'path' +import { readFile } from 'fs/promises' +import microrouter from 'microrouter' +import { ApolloServer } from 'apollo-server-micro' +import { fileURLToPath } from 'url' + +const { send, createError } = micro +const { router, get, post, put, patch, del } = microrouter + +import KnownError from './utils/KnownError.js' +import signale from './utils/signale.js' +import config from './utils/config.js' +import findMatchingOrigin from './utils/findMatchingOrigin.js' +import * as customTracker from './utils/customTracker.js' +import createApolloServer from './utils/createApolloServer.js' +import { createMicroContext } from './utils/createContext.js' + +const __filename = fileURLToPath(import.meta.url) +const __dirname = dirname(__filename) const index = readFile(resolve(__dirname, '../dist/index.html')).catch(signale.fatal) const favicon = readFile(resolve(__dirname, '../dist/favicon.ico')).catch(signale.fatal) @@ -22,12 +26,12 @@ const scripts = readFile(resolve(__dirname, '../dist/index.js')).catch(signale.f const tracker = readFile(resolve(__dirname, '../dist/tracker.js')).catch(signale.fatal) const handleMicroError = (error, response) => { - // This part is for micro errors and errors outside of GraphQL. - // Most errors won't be caught here, but some error can still - // happen outside of GraphQL. In this case we distinguish - // between unknown errors and known errors. Known errors are - // created with the createError function while unknown errors - // are simply errors thrown somewhere in the application. +// This part is for micro errors and errors outside of GraphQL. +// Most errors won't be caught here, but some error can still +// happen outside of GraphQL. In this case we distinguish +// between unknown errors and known errors. Known errors are +// created with the createError function while unknown errors +// are simply errors thrown somewhere in the application. const isUnknownError = error.statusCode == null const hasOriginalError = error.originalError != null @@ -43,10 +47,10 @@ const handleMicroError = (error, response) => { } const handleGraphError = (error) => { - // This part is for error that happen inside GraphQL resolvers. - // All known errors should be thrown as a KnownError as those - // errors will only show up in the response and as a warning - // in the console output. +// This part is for error that happen inside GraphQL resolvers. +// All known errors should be thrown as a KnownError as those +// errors will only show up in the response and as a warning +// in the console output. const suitableError = error.originalError || error const isKnownError = suitableError instanceof KnownError @@ -146,10 +150,10 @@ const routes = [ ].filter(Boolean) -module.exports = micro( - attachCorsHeaders( - catchError( - router(...routes), - ), - ), +export default micro( +attachCorsHeaders( +catchError( +router(...routes), +), +), ) \ No newline at end of file diff --git a/src/serverless.js b/src/serverless.js index 6a36a32c4..bf7c66696 100644 --- a/src/serverless.js +++ b/src/serverless.js @@ -1,12 +1,10 @@ -'use strict' +import { ApolloServer } from 'apollo-server-lambda' -const { ApolloServer } = require('apollo-server-lambda') - -const config = require('./utils/config') -const connect = require('./utils/connect') -const fullyQualifiedDomainNames = require('./utils/fullyQualifiedDomainNames') -const createApolloServer = require('./utils/createApolloServer') -const { createServerlessContext } = require('./utils/createContext') +import config from './utils/config.js' +import connect from './utils/connect.js' +import fullyQualifiedDomainNames from './utils/fullyQualifiedDomainNames.js' +import createApolloServer from './utils/createApolloServer.js' +import { createServerlessContext } from './utils/createContext.js' if (config.dbUrl == null) { throw new Error('MongoDB connection URI missing in environment') @@ -22,8 +20,8 @@ const origin = (origin, callback) => { if (config.autoOrigin === true) { fullyQualifiedDomainNames() .then((names) => callback( - null, - names.flatMap((name) => [ `http://${ name }`, `https://${ name }`, name ]), +null, +names.flatMap((name) => [ `http://${ name }`, `https://${ name }`, name ]), )) .catch((error) => callback(error, false)) return @@ -43,9 +41,9 @@ const origin = (origin, callback) => { return } -exports.handler = (event, context) => { - // Set request context which is missing on Vercel: - // https://stackoverflow.com/questions/71360059/apollo-server-lambda-unable-to-determine-event-source-based-on-event +export const handler = (event, context) => { +// Set request context which is missing on Vercel: +// https://stackoverflow.com/questions/71360059/apollo-server-lambda-unable-to-determine-event-source-based-on-event if (event.requestContext == null) event.requestContext = context const handler = apolloServer.createHandler({ diff --git a/src/stages/matchDomains.js b/src/stages/matchDomains.js index 8e55a52b4..614d05d92 100644 --- a/src/stages/matchDomains.js +++ b/src/stages/matchDomains.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = (ids) => { +export default (ids) => { const stage = { $match: {}, } diff --git a/src/stages/matchEvents.js b/src/stages/matchEvents.js index 3c21af026..a39315792 100644 --- a/src/stages/matchEvents.js +++ b/src/stages/matchEvents.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = (ids) => { +export default (ids) => { const stage = { $match: {}, } diff --git a/src/stages/matchLimit.js b/src/stages/matchLimit.js index 0c3eff637..a0191f3f2 100644 --- a/src/stages/matchLimit.js +++ b/src/stages/matchLimit.js @@ -1,8 +1,6 @@ -'use strict' +import { DURATIONS_LIMIT } from '../constants/durations.js' -const { DURATIONS_LIMIT } = require('../constants/durations') - -module.exports = () => { +export default () => { // Some visitors keep sites open in the background. Their duration is often // way above the limit. This distorts the average and should be omitted. return { diff --git a/src/stages/projectDuration.js b/src/stages/projectDuration.js index 59ed6851a..14bc2aec8 100644 --- a/src/stages/projectDuration.js +++ b/src/stages/projectDuration.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = () => { +export default () => { // The time that elapsed between the creation and updating of records. return { $project: { diff --git a/src/stages/projectMinInterval.js b/src/stages/projectMinInterval.js index 6922758b1..7ac53e05d 100644 --- a/src/stages/projectMinInterval.js +++ b/src/stages/projectMinInterval.js @@ -1,8 +1,6 @@ -'use strict' +import { DURATIONS_INTERVAL } from '../constants/durations.js' -const { DURATIONS_INTERVAL } = require('../constants/durations') - -module.exports = () => { +export default () => { // Visits below the tracking interval will have a duration of zero. That's // incorrect as visitors spent time on the site, but just not enough. This // step sets the minimum duration to the half of the tracking interval. diff --git a/src/types/actions.js b/src/types/actions.js index d3249dd80..53b23984e 100644 --- a/src/types/actions.js +++ b/src/types/actions.js @@ -1,8 +1,7 @@ -'use strict' -const { gql } = require('apollo-server-micro') +import { gql } from 'apollo-server-micro' -module.exports = gql` +export default gql` """ Event entries will be stored as actions. """ diff --git a/src/types/domainStatistics.js b/src/types/domainStatistics.js index 07d1ba209..09e3ad486 100644 --- a/src/types/domainStatistics.js +++ b/src/types/domainStatistics.js @@ -1,8 +1,7 @@ -'use strict' -const { gql } = require('apollo-server-micro') +import { gql } from 'apollo-server-micro' -module.exports = gql` +export default gql` enum ViewType { """ Unique site views. diff --git a/src/types/domains.js b/src/types/domains.js index a8b7ec81f..df542c366 100644 --- a/src/types/domains.js +++ b/src/types/domains.js @@ -1,8 +1,7 @@ -'use strict' -const { gql } = require('apollo-server-micro') +import { gql } from 'apollo-server-micro' -module.exports = gql` +export default gql` """ Domains are required to track views. You can create as many domains as you want, but it's recommended to create on domain per project/site. This allows you to view facts and statistics separately. """ diff --git a/src/types/eventStatistics.js b/src/types/eventStatistics.js index 97d2bece6..6d9f18741 100644 --- a/src/types/eventStatistics.js +++ b/src/types/eventStatistics.js @@ -1,8 +1,7 @@ -'use strict' -const { gql } = require('apollo-server-micro') +import { gql } from 'apollo-server-micro' -module.exports = gql` +export default gql` enum EventChartType { """ Total sum of values. diff --git a/src/types/events.js b/src/types/events.js index 3ee6f058b..0f50340c2 100644 --- a/src/types/events.js +++ b/src/types/events.js @@ -1,8 +1,7 @@ -'use strict' -const { gql } = require('apollo-server-micro') +import { gql } from 'apollo-server-micro' -module.exports = gql` +export default gql` enum EventType { """ The UI will display the data of this event as a bar chart with totalized values. diff --git a/src/types/facts.js b/src/types/facts.js index 704a6e913..0d89429d6 100644 --- a/src/types/facts.js +++ b/src/types/facts.js @@ -1,8 +1,7 @@ -'use strict' -const { gql } = require('apollo-server-micro') +import { gql } from 'apollo-server-micro' -module.exports = gql` +export default gql` type AverageViews { """ Average number of views per day during the last 14 days, excluding the current day. diff --git a/src/types/index.js b/src/types/index.js index 9ec0013f4..6f3584ce1 100644 --- a/src/types/index.js +++ b/src/types/index.js @@ -1,16 +1,25 @@ -'use strict' +import { mergeTypeDefs } from '@graphql-tools/merge' -const { mergeTypeDefs } = require('@graphql-tools/merge') +import tokens from './tokens.js' +import permanentTokens from './permanentTokens.js' +import records from './records.js' +import domains from './domains.js' +import events from './events.js' +import actions from './actions.js' +import facts from './facts.js' +import miscellaneous from './miscellaneous.js' +import domainStatistics from './domainStatistics.js' +import eventStatistics from './eventStatistics.js' -module.exports = mergeTypeDefs([ - require('./tokens'), - require('./permanentTokens'), - require('./records'), - require('./domains'), - require('./events'), - require('./actions'), - require('./facts'), - require('./miscellaneous'), - require('./domainStatistics'), - require('./eventStatistics'), +export default mergeTypeDefs([ + tokens, + permanentTokens, + records, + domains, + events, + actions, + facts, + miscellaneous, + domainStatistics, + eventStatistics, ], { all: true }) \ No newline at end of file diff --git a/src/types/miscellaneous.js b/src/types/miscellaneous.js index 75d68b17c..578407304 100644 --- a/src/types/miscellaneous.js +++ b/src/types/miscellaneous.js @@ -1,8 +1,7 @@ -'use strict' -const { gql } = require('apollo-server-micro') +import { gql } from 'apollo-server-micro' -module.exports = gql` +export default gql` enum Interval { """ Group by day. diff --git a/src/types/permanentTokens.js b/src/types/permanentTokens.js index 66af00a58..4735ab3f0 100644 --- a/src/types/permanentTokens.js +++ b/src/types/permanentTokens.js @@ -1,8 +1,7 @@ -'use strict' -const { gql } = require('apollo-server-micro') +import { gql } from 'apollo-server-micro' -module.exports = gql` +export default gql` type PermanentToken { """ Permanent token identifier. Use this value for authentication. diff --git a/src/types/records.js b/src/types/records.js index ae738bbc1..1c9de6247 100644 --- a/src/types/records.js +++ b/src/types/records.js @@ -1,8 +1,7 @@ -'use strict' -const { gql } = require('apollo-server-micro') +import { gql } from 'apollo-server-micro' -module.exports = gql` +export default gql` """ Page views will be stored in records. They contain data about the visit and user. Ackee tries its best to keep tracked data anonymized. Several steps are used to avoid that users are identifiable, while still providing helpful analytics. """ diff --git a/src/types/tokens.js b/src/types/tokens.js index ae9ad6cd0..44ff979aa 100644 --- a/src/types/tokens.js +++ b/src/types/tokens.js @@ -1,8 +1,7 @@ -'use strict' -const { gql } = require('apollo-server-micro') +import { gql } from 'apollo-server-micro' -module.exports = gql` +export default gql` type Token { """ Token identifier. Use this value for authentication. diff --git a/src/ui/index.js b/src/ui/index.js index 06ceed729..e858dc195 100644 --- a/src/ui/index.js +++ b/src/ui/index.js @@ -1,29 +1,34 @@ -'use strict' +import { resolve, dirname } from 'path' +import { writeFile, readFile } from 'fs/promises' +import { createRequire } from 'module' +import { fileURLToPath } from 'url' -const { resolve } = require('path') -const { writeFile, readFile } = require('fs').promises +import layout from '../utils/layout.js' +import config from '../utils/config.js' +import { exists, url, path } from '../utils/customTracker.js' +import signale from '../utils/signale.js' -const layout = require('../utils/layout') -const config = require('../utils/config') -const customTracker = require('../utils/customTracker') -const signale = require('../utils/signale') +const __filename = fileURLToPath(import.meta.url) +const __dirname = dirname(__filename) -const index = () => { +const customTracker = { exists, url, path } + +export const index = () => { return layout('
', 'favicon.ico', [ 'index.css' ], [ 'index.js' ], { isDemoMode: config.isDemoMode, customTracker, }) } -const styles = () => { - const sass = require('rosid-handler-sass') +export const styles = async () => { + const { default: sass } = await import('rosid-handler-sass') const filePath = resolve(__dirname, './styles/index.scss') return sass(filePath, { optimize: config.isDevelopmentMode === false }) } -const scripts = () => { - const js = require('rosid-handler-js-next') +export const scripts = async () => { + const { default: js } = await import('rosid-handler-js-next') const filePath = resolve(__dirname, './scripts/index.js') return js(filePath, { @@ -34,13 +39,14 @@ const scripts = () => { }) } -const tracker = () => { +export const tracker = () => { + const require = createRequire(import.meta.url) const filePath = require.resolve('ackee-tracker') return readFile(filePath, 'utf8') } -const build = async (path, fn) => { +export const build = async (path, fn) => { try { signale.await(`Building and writing '${ path }'`) const data = await fn() @@ -50,12 +56,4 @@ const build = async (path, fn) => { signale.fatal(error) process.exit(1) } -} - -module.exports = { - index, - styles, - scripts, - tracker, - build, } \ No newline at end of file diff --git a/src/ui/scripts/utils/rangeLabel.js b/src/ui/scripts/utils/rangeLabel.js index 921ab76ac..130561bbb 100644 --- a/src/ui/scripts/utils/rangeLabel.js +++ b/src/ui/scripts/utils/rangeLabel.js @@ -1,10 +1,10 @@ -import ranges from '../../../constants/ranges' +import { RANGES_LAST_24_HOURS, RANGES_LAST_7_DAYS, RANGES_LAST_30_DAYS, RANGES_LAST_6_MONTHS } from '../../../constants/ranges' export default (range) => { return ({ - [ranges.RANGES_LAST_24_HOURS]: 'Last 24 hours', - [ranges.RANGES_LAST_7_DAYS]: 'Last 7 days', - [ranges.RANGES_LAST_30_DAYS]: 'Last 30 days', - [ranges.RANGES_LAST_6_MONTHS]: 'Last 6 months', + [RANGES_LAST_24_HOURS]: 'Last 24 hours', + [RANGES_LAST_7_DAYS]: 'Last 7 days', + [RANGES_LAST_30_DAYS]: 'Last 30 days', + [RANGES_LAST_6_MONTHS]: 'Last 6 months', })[range] } \ No newline at end of file diff --git a/src/utils/KnownError.js b/src/utils/KnownError.js index 1921ab3a3..33b92e2be 100644 --- a/src/utils/KnownError.js +++ b/src/utils/KnownError.js @@ -1,4 +1,4 @@ -module.exports = class KnownError extends Error { +export default class KnownError extends Error { constructor(message) { super(message) this.name = 'KnownError' diff --git a/src/utils/config.js b/src/utils/config.js index 3ff3eeb61..3fdc728c7 100644 --- a/src/utils/config.js +++ b/src/utils/config.js @@ -1,10 +1,8 @@ -'use static' - -const { day } = require('./times') +import { day } from './times.js' // Must be a function or object that loads and returns the env variables at runtime. // Otherwise it wouldn't be possible to mock the env variables with mockedEnv. -module.exports = new Proxy({}, { +export default new Proxy({}, { get: function(target, prop) { const data = { ttl: process.env.ACKEE_TTL || day, diff --git a/src/utils/connect.js b/src/utils/connect.js index ac2103abe..538d7627b 100644 --- a/src/utils/connect.js +++ b/src/utils/connect.js @@ -1,7 +1,5 @@ -'use strict' +import mongoose from 'mongoose' -const mongoose = require('mongoose') - -module.exports = (dbUrl) => mongoose.connect(dbUrl, { +export default (dbUrl) => mongoose.connect(dbUrl, { connectTimeoutMS: 60000, }) \ No newline at end of file diff --git a/src/utils/createApolloServer.js b/src/utils/createApolloServer.js index e9869ba2c..4b20d8bfc 100644 --- a/src/utils/createApolloServer.js +++ b/src/utils/createApolloServer.js @@ -1,11 +1,9 @@ -'use strict' - -const { - ApolloServerPluginLandingPageGraphQLPlayground: apolloServerPluginLandingPageGraphQLPlayground, - ApolloServerPluginLandingPageDisabled: apolloServerPluginLandingPageDisabled, -} = require('apollo-server-core') -const httpHeadersPlugin = require('apollo-server-plugin-http-headers') -const { +import { + ApolloServerPluginLandingPageGraphQLPlayground as apolloServerPluginLandingPageGraphQLPlayground, + ApolloServerPluginLandingPageDisabled as apolloServerPluginLandingPageDisabled, +} from 'apollo-server-core' +import httpHeadersPlugin from 'apollo-server-plugin-http-headers' +import { UnsignedIntResolver, UnsignedIntTypeDefinition, DateTimeResolver, @@ -14,11 +12,13 @@ const { PositiveFloatTypeDefinition, URLResolver, URLTypeDefinition, -} = require('graphql-scalars') +} from 'graphql-scalars' -const config = require('./config') +import config from './config.js' +import typeDefs from '../types/index.js' +import resolvers from '../resolvers/index.js' -module.exports = (ApolloServer, options) => new ApolloServer({ +export default (ApolloServer, options) => new ApolloServer({ cache: 'bounded', introspection: config.isDemoMode === true || config.isDevelopmentMode === true, playground: config.isDemoMode === true || config.isDevelopmentMode === true, @@ -34,14 +34,14 @@ module.exports = (ApolloServer, options) => new ApolloServer({ DateTimeTypeDefinition, PositiveFloatTypeDefinition, URLTypeDefinition, - require('../types'), + typeDefs, ], resolvers: { UnsignedInt: UnsignedIntResolver, DateTime: DateTimeResolver, PositiveFloat: PositiveFloatResolver, URL: URLResolver, - ...require('../resolvers'), + ...resolvers, }, ...options, }) \ No newline at end of file diff --git a/src/utils/createArray.js b/src/utils/createArray.js index c9a47cc91..51267d3e2 100644 --- a/src/utils/createArray.js +++ b/src/utils/createArray.js @@ -1,3 +1 @@ -'use strict' - -module.exports = (length) => new Array(length).fill() \ No newline at end of file +export default (length) => new Array(length).fill() \ No newline at end of file diff --git a/src/utils/createContext.js b/src/utils/createContext.js index f05e9a138..d5872341f 100644 --- a/src/utils/createContext.js +++ b/src/utils/createContext.js @@ -1,17 +1,15 @@ -'use strict' +import { getClientIp } from 'request-ip' -const { getClientIp } = require('request-ip') +import config from './config.js' +import isAuthenticated from './isAuthenticated.js' +import createDate from './createDate.js' +import { isSet } from './ignoreCookie.js' -const config = require('./config') -const isAuthenticated = require('./isAuthenticated') -const createDate = require('./createDate') -const ignoreCookie = require('./ignoreCookie') - -const createServerlessContext = (integrationContext) => { +export const createServerlessContext = (integrationContext) => { return createContext(integrationContext.event.headers['client-ip'], integrationContext.event.headers) } -const createMicroContext = (integrationContext) => { +export const createMicroContext = (integrationContext) => { return createContext(getClientIp(integrationContext.req), integrationContext.req.headers) } @@ -19,7 +17,7 @@ const createContext = async (ip, headers) => { return { isDemoMode: config.isDemoMode, isAuthenticated: await isAuthenticated(headers['authorization'], config.ttl), - isIgnored: ignoreCookie.isSet(headers['cookie']), + isIgnored: isSet(headers['cookie']), dateDetails: createDate(headers['time-zone']), userAgent: headers['user-agent'], ip, @@ -28,9 +26,4 @@ const createContext = async (ip, headers) => { setCookies: [], setHeaders: [], } -} - -module.exports = { - createServerlessContext, - createMicroContext, } \ No newline at end of file diff --git a/src/utils/createDate.js b/src/utils/createDate.js index 171bc95e1..11ef8b1b7 100644 --- a/src/utils/createDate.js +++ b/src/utils/createDate.js @@ -1,10 +1,8 @@ -'use strict' +import { subMilliseconds, subHours, subDays, subMonths, subYears, startOfDay, startOfMonth, startOfYear } from 'date-fns' +import serverTimeZone from './timeZone.js' +import { INTERVALS_DAILY, INTERVALS_MONTHLY, INTERVALS_YEARLY } from '../constants/intervals.js' -const { subMilliseconds, subHours, subDays, subMonths, subYears, startOfDay, startOfMonth, startOfYear } = require('date-fns') -const serverTimeZone = require('./timeZone') -const intervals = require('../constants/intervals') - -module.exports = (userTimeZone = serverTimeZone) => { +export default (userTimeZone = serverTimeZone) => { const currentDate = new Date() // This is the biggest, positive timezone offset possible (starting from UTC). @@ -35,18 +33,18 @@ module.exports = (userTimeZone = serverTimeZone) => { // Get the last-function that matches the interval const lastFnByInterval = (interval) => { switch (interval) { - case intervals.INTERVALS_DAILY: return instance.lastDays - case intervals.INTERVALS_MONTHLY: return instance.lastMonths - case intervals.INTERVALS_YEARLY: return instance.lastYears + case INTERVALS_DAILY: return instance.lastDays + case INTERVALS_MONTHLY: return instance.lastMonths + case INTERVALS_YEARLY: return instance.lastYears } } // Get the include-function that matches the interval const includeFnByInterval = (interval) => { switch (interval) { - case intervals.INTERVALS_DAILY: return instance.includeDays - case intervals.INTERVALS_MONTHLY: return instance.includeMonths - case intervals.INTERVALS_YEARLY: return instance.includeYears + case INTERVALS_DAILY: return instance.includeDays + case INTERVALS_MONTHLY: return instance.includeMonths + case INTERVALS_YEARLY: return instance.includeYears } } diff --git a/src/utils/customTracker.js b/src/utils/customTracker.js index bfe33e282..5eda2ae00 100644 --- a/src/utils/customTracker.js +++ b/src/utils/customTracker.js @@ -1,12 +1,6 @@ -'use strict' - -const sanitizeFilename = require('sanitize-filename') +import sanitizeFilename from 'sanitize-filename' const name = process.env.ACKEE_TRACKER -const exists = name != null && name !== '' - -module.exports = { - exists, - url: exists === true ? `/${ encodeURIComponent(name) }.js` : undefined, - path: exists === true ? `${ sanitizeFilename(name) }.js` : undefined, -} \ No newline at end of file +export const exists = name != null && name !== '' +export const url = exists === true ? `/${ encodeURIComponent(name) }.js` : undefined +export const path = exists === true ? `${ sanitizeFilename(name) }.js` : undefined \ No newline at end of file diff --git a/src/utils/domainIds.js b/src/utils/domainIds.js index 7db013bbd..78b864dcb 100644 --- a/src/utils/domainIds.js +++ b/src/utils/domainIds.js @@ -1,15 +1,13 @@ -'use strict' +import debouncePromise from 'debounce-promise' -const debouncePromise = require('debounce-promise') - -const domains = require('../database/domains') +import * as domains from '../database/domains.js' // A zero timeout is enough to ensure that this task // runs only once on every API call. It's a task that would // otherwise execute multiple times. const loadDomains = debouncePromise(domains.all, 0) -module.exports = async (domain) => { +export default async (domain) => { if (domain.id == null) { const allDomains = await loadDomains() return allDomains.map((domain) => domain.id) diff --git a/src/utils/findMatchingOrigin.js b/src/utils/findMatchingOrigin.js index 8c560426f..3ebbfffbe 100644 --- a/src/utils/findMatchingOrigin.js +++ b/src/utils/findMatchingOrigin.js @@ -1,12 +1,10 @@ -'use strict' - -const fullyQualifiedDomainNames = require('./fullyQualifiedDomainNames') +import fullyQualifiedDomainNames from './fullyQualifiedDomainNames.js' const findOrigin = (request, origins) => { return origins.find((origin) => origin.includes(request.headers.origin) || origin.includes(request.headers.host)) } -module.exports = async (request, allowedOrigins, autoOrigin) => { +export default async (request, allowedOrigins, autoOrigin) => { if (autoOrigin === true) { const origins = await fullyQualifiedDomainNames() return findOrigin(request, origins) diff --git a/src/utils/fullyQualifiedDomainNames.js b/src/utils/fullyQualifiedDomainNames.js index 8f2cb7325..f32165ac0 100644 --- a/src/utils/fullyQualifiedDomainNames.js +++ b/src/utils/fullyQualifiedDomainNames.js @@ -1,10 +1,8 @@ -'use strict' +import isValidDomain from 'is-valid-domain' -const isValidDomain = require('is-valid-domain') +import * as domains from '../database/domains.js' -const domains = require('../database/domains') - -module.exports = async () => { +export default async () => { const allDomains = await domains.all() const allTitles = allDomains.map((domain) => domain.title) const fullyQualifiedDomainNames = allTitles.filter((title) => isValidDomain(title, { subdomain: true, wildcard: false, allowUnicode: true })) diff --git a/src/utils/identifier.js b/src/utils/identifier.js index 4c0100d74..271eda719 100644 --- a/src/utils/identifier.js +++ b/src/utils/identifier.js @@ -1,10 +1,8 @@ -'use strict' +import crypto from 'crypto' -const crypto = require('crypto') +import salt from './salt.js' -const salt = require('./salt') - -module.exports = (ip, userAgent, domainId) => { +export default (ip, userAgent, domainId) => { return crypto.createHash('sha256').update(`${ salt() }${ ip }${ userAgent }${ domainId }`) .digest('hex') } \ No newline at end of file diff --git a/src/utils/ignoreCookie.js b/src/utils/ignoreCookie.js index 017d81280..400654214 100644 --- a/src/utils/ignoreCookie.js +++ b/src/utils/ignoreCookie.js @@ -1,25 +1,23 @@ -'use static' - const COOKIE_NAME = 'ackee_ignore' -module.exports = { - isSet: (cookie = '') => cookie.includes(`${ COOKIE_NAME }=1`), - on: { - name: COOKIE_NAME, - value: '1', - options: { - maxAge: 365 * 24 * 60 * 60, - sameSite: 'none', - secure: true, - }, +export const isSet = (cookie = '') => cookie.includes(`${ COOKIE_NAME }=1`) + +export const on = { + name: COOKIE_NAME, + value: '1', + options: { + maxAge: 365 * 24 * 60 * 60, + sameSite: 'none', + secure: true, }, - off: { - name: COOKIE_NAME, - value: '0', - options: { - maxAge: -1, - sameSite: 'none', - secure: true, - }, +} + +export const off = { + name: COOKIE_NAME, + value: '0', + options: { + maxAge: -1, + sameSite: 'none', + secure: true, }, } \ No newline at end of file diff --git a/src/utils/isAuthenticated.js b/src/utils/isAuthenticated.js index edb069c17..a2127275d 100644 --- a/src/utils/isAuthenticated.js +++ b/src/utils/isAuthenticated.js @@ -1,11 +1,9 @@ -'use strict' +import KnownError from './KnownError.js' +import isExpired from './isExpired.js' +import * as tokens from '../database/tokens.js' +import * as permanentTokens from '../database/permanentTokens.js' -const KnownError = require('../utils/KnownError') -const isExpired = require('../utils/isExpired') -const tokens = require('../database/tokens') -const permanentTokens = require('../database/permanentTokens') - -module.exports = async (authorization, ttl) => { +export default async (authorization, ttl) => { // Token not in request if (authorization == null) { return new KnownError('Token missing') diff --git a/src/utils/isDefined.js b/src/utils/isDefined.js index 0065e9de6..4438892a2 100644 --- a/src/utils/isDefined.js +++ b/src/utils/isDefined.js @@ -1,3 +1 @@ -'use strict' - -module.exports = (_) => _ != null \ No newline at end of file +export default (_) => _ != null \ No newline at end of file diff --git a/src/utils/isExpired.js b/src/utils/isExpired.js index 15e176559..198c7099d 100644 --- a/src/utils/isExpired.js +++ b/src/utils/isExpired.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = (timestamp, ttl) => { +export default (timestamp, ttl) => { const current = Date.now() const passed = current - timestamp diff --git a/src/utils/languageCodes.js b/src/utils/languageCodes.js index 67e3c255b..855c03750 100644 --- a/src/utils/languageCodes.js +++ b/src/utils/languageCodes.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = { +export default { aa: 'Afar', ab: 'Abkhazian', ae: 'Avestan', diff --git a/src/utils/layout.js b/src/utils/layout.js index f10037d6a..b91bc9a45 100644 --- a/src/utils/layout.js +++ b/src/utils/layout.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = (body, favicon, styles, scripts, variables) => ` +export default (body, favicon, styles, scripts, variables) => ` diff --git a/src/utils/matchesDate.js b/src/utils/matchesDate.js index d08d23f91..dfd1a0b92 100644 --- a/src/utils/matchesDate.js +++ b/src/utils/matchesDate.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = (day, month, year, date) => { +export default (day, month, year, date) => { const isDay = day === date.getDate() || day == null const isMonth = month === date.getMonth() + 1 || month == null const isYear = year === date.getFullYear() || year == null diff --git a/src/utils/messages.js b/src/utils/messages.js index 87ed4621d..38887405c 100644 --- a/src/utils/messages.js +++ b/src/utils/messages.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = (errors) => { +export default (errors) => { // Extract message from an error const message = (key) => errors[key].message diff --git a/src/utils/normalizeUrl.js b/src/utils/normalizeUrl.js index 00b239963..2b50aa2e6 100644 --- a/src/utils/normalizeUrl.js +++ b/src/utils/normalizeUrl.js @@ -1,8 +1,6 @@ -'use strict' +import normalizeUrl from 'normalize-url' -const normalizeUrl = require('normalize-url') - -module.exports = (url) => normalizeUrl(url, { +export default (url) => normalizeUrl(url, { removeDirectoryIndex: true, removeQueryParameters: [ /^utm_\w+/i, diff --git a/src/utils/pipe.js b/src/utils/pipe.js index 55f1eb453..4865c171c 100644 --- a/src/utils/pipe.js +++ b/src/utils/pipe.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = (...args) => { +export default (...args) => { return Array.prototype.slice.call(args, 1).reduce((a, b) => { return (...args) => Promise.resolve(a(...args)).then((result) => { if (result == null) return b(...args) diff --git a/src/utils/recursiveId.js b/src/utils/recursiveId.js index 7581fc5af..c6dc1514d 100644 --- a/src/utils/recursiveId.js +++ b/src/utils/recursiveId.js @@ -1,6 +1,4 @@ -'use strict' - -const uuid = require('uuid').v5 +import { v5 as uuid } from 'uuid' // Randomly generated UUID that should never change const DEFAULT_NAMESPACE = 'faea8d75-e9c5-45fe-a436-4a906d44b88e' @@ -10,4 +8,4 @@ const recursiveId = (ids) => { return uuid(current, rest.length === 0 ? DEFAULT_NAMESPACE : recursiveId(rest)) } -module.exports = recursiveId \ No newline at end of file +export default recursiveId \ No newline at end of file diff --git a/src/utils/salt.js b/src/utils/salt.js index f88ea60b1..634e6c88f 100644 --- a/src/utils/salt.js +++ b/src/utils/salt.js @@ -1,7 +1,5 @@ -'use strict' - -const crypto = require('crypto') -const schedule = require('node-schedule') +import crypto from 'crypto' +import schedule from 'node-schedule' const generate = () => crypto.randomBytes(16).toString('hex') let salt = generate() @@ -12,4 +10,4 @@ rule.hour = 0 schedule.scheduleJob(rule, () => salt = generate()) -module.exports = () => salt \ No newline at end of file +export default () => salt \ No newline at end of file diff --git a/src/utils/signale.js b/src/utils/signale.js index 1f9385000..f17912be8 100644 --- a/src/utils/signale.js +++ b/src/utils/signale.js @@ -1,7 +1,7 @@ -'use strict' +import signaleModule from 'signale' -const { Signale } = require('signale') +const { Signale } = signaleModule -module.exports = new Signale({ +export default new Signale({ scope: 'Ackee', }) \ No newline at end of file diff --git a/src/utils/sortByProp.js b/src/utils/sortByProp.js index 904095cd8..58a1185db 100644 --- a/src/utils/sortByProp.js +++ b/src/utils/sortByProp.js @@ -1,6 +1,4 @@ -'use strict' - -module.exports = (prop) => (a, b) => { +export default (prop) => (a, b) => { const _a = String(a[prop]) const _b = String(b[prop]) diff --git a/src/utils/stripUrlAuth.js b/src/utils/stripUrlAuth.js index 4406da81e..5ae837ef6 100644 --- a/src/utils/stripUrlAuth.js +++ b/src/utils/stripUrlAuth.js @@ -1,8 +1,6 @@ -'use strict' +import normalizeUrl from 'normalize-url' -const normalizeUrl = require('normalize-url') - -module.exports = (url) => normalizeUrl(url, { +export default (url) => normalizeUrl(url, { normalizeProtocol: false, stripWWW: false, removeTrailingSlash: false, diff --git a/src/utils/timeZone.js b/src/utils/timeZone.js index 6e9d094e0..7223a5564 100644 --- a/src/utils/timeZone.js +++ b/src/utils/timeZone.js @@ -1,3 +1 @@ -'use strict' - -module.exports = (new Intl.DateTimeFormat()).resolvedOptions().timeZone \ No newline at end of file +export default (new Intl.DateTimeFormat()).resolvedOptions().timeZone \ No newline at end of file diff --git a/src/utils/times.js b/src/utils/times.js index 76b94def4..70bdb17dd 100644 --- a/src/utils/times.js +++ b/src/utils/times.js @@ -1,13 +1,4 @@ -'use strict' - -const second = 1000 -const minute = second * 60 -const hour = minute * 60 -const day = hour * 24 - -module.exports = { - second, - minute, - hour, - day, -} \ No newline at end of file +export const second = 1000 +export const minute = second * 60 +export const hour = minute * 60 +export const day = hour * 24 \ No newline at end of file diff --git a/test/aggregations/aggregateActiveVisitors.js b/test/aggregations/aggregateActiveVisitors.js index 161574690..1c28cd9d2 100644 --- a/test/aggregations/aggregateActiveVisitors.js +++ b/test/aggregations/aggregateActiveVisitors.js @@ -1,10 +1,8 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const aggregateActiveVisitors = require('../../src/aggregations/aggregateActiveVisitors') -const createDate = require('../../src/utils/createDate') +import aggregateActiveVisitors from '../../src/aggregations/aggregateActiveVisitors.js' +import createDate from '../../src/utils/createDate.js' test('return aggregation', (t) => { const result = aggregateActiveVisitors(uuid(), createDate()) diff --git a/test/aggregations/aggregateDurations.js b/test/aggregations/aggregateDurations.js index db845487a..35c702a5b 100644 --- a/test/aggregations/aggregateDurations.js +++ b/test/aggregations/aggregateDurations.js @@ -1,14 +1,12 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const aggregateDurations = require('../../src/aggregations/aggregateDurations') -const intervals = require('../../src/constants/intervals') -const createDate = require('../../src/utils/createDate') +import aggregateDurations from '../../src/aggregations/aggregateDurations.js' +import { INTERVALS_DAILY } from '../../src/constants/intervals.js' +import createDate from '../../src/utils/createDate.js' test('return aggregation', (t) => { - const result = aggregateDurations(uuid(), intervals.INTERVALS_DAILY, 14, createDate()) + const result = aggregateDurations(uuid(), INTERVALS_DAILY, 14, createDate()) t.true(Array.isArray(result)) }) \ No newline at end of file diff --git a/test/aggregations/aggregateNewFields.js b/test/aggregations/aggregateNewFields.js index 58972edf8..2ea3bd175 100644 --- a/test/aggregations/aggregateNewFields.js +++ b/test/aggregations/aggregateNewFields.js @@ -1,9 +1,7 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const aggregateNewRecords = require('../../src/aggregations/aggregateNewRecords') +import aggregateNewRecords from '../../src/aggregations/aggregateNewRecords.js' test('return aggregation', (t) => { const result = aggregateNewRecords(uuid(), [ 'siteReferrer' ]) diff --git a/test/aggregations/aggregateRecentFields.js b/test/aggregations/aggregateRecentFields.js index 5e946028a..8f0568b02 100644 --- a/test/aggregations/aggregateRecentFields.js +++ b/test/aggregations/aggregateRecentFields.js @@ -1,9 +1,7 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const aggregateRecentRecords = require('../../src/aggregations/aggregateRecentRecords') +import aggregateRecentRecords from '../../src/aggregations/aggregateRecentRecords.js' test('return aggregation', (t) => { const result = aggregateRecentRecords(uuid(), [ 'osName', 'osVersion' ]) diff --git a/test/aggregations/aggregateTopFields.js b/test/aggregations/aggregateTopFields.js index 87da2caf1..82e9a46a7 100644 --- a/test/aggregations/aggregateTopFields.js +++ b/test/aggregations/aggregateTopFields.js @@ -1,10 +1,8 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const aggregateTopRecords = require('../../src/aggregations/aggregateTopRecords') -const createDate = require('../../src/utils/createDate') +import aggregateTopRecords from '../../src/aggregations/aggregateTopRecords.js' +import createDate from '../../src/utils/createDate.js' test('return aggregation', (t) => { const result = aggregateTopRecords(uuid(), [ 'osName', 'osVersion' ], createDate()) diff --git a/test/aggregations/aggregateViews.js b/test/aggregations/aggregateViews.js index 56b89b344..d46a7cd66 100644 --- a/test/aggregations/aggregateViews.js +++ b/test/aggregations/aggregateViews.js @@ -1,20 +1,18 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const aggregateViews = require('../../src/aggregations/aggregateViews') -const intervals = require('../../src/constants/intervals') -const createDate = require('../../src/utils/createDate') +import aggregateViews from '../../src/aggregations/aggregateViews.js' +import { INTERVALS_DAILY } from '../../src/constants/intervals.js' +import createDate from '../../src/utils/createDate.js' test('return unique aggregation', (t) => { - const result = aggregateViews(uuid(), true, intervals.INTERVALS_DAILY, 14, createDate()) + const result = aggregateViews(uuid(), true, INTERVALS_DAILY, 14, createDate()) t.true(Array.isArray(result)) }) test('return non-unique aggregation', (t) => { - const result = aggregateViews(uuid(), false, intervals.INTERVALS_DAILY, 14, createDate()) + const result = aggregateViews(uuid(), false, INTERVALS_DAILY, 14, createDate()) t.true(Array.isArray(result)) }) \ No newline at end of file diff --git a/test/constants/browsers.js b/test/constants/browsers.js index 6f9cd7b51..dd873169d 100644 --- a/test/constants/browsers.js +++ b/test/constants/browsers.js @@ -1,8 +1,8 @@ -'use strict' -const test = require('ava') -const browsers = require('../../src/constants/browsers') +import test from 'ava' + +import * as browsers from '../../src/constants/browsers.js' test('is an object', (t) => { t.is(typeof browsers, 'object') diff --git a/test/constants/devices.js b/test/constants/devices.js index a61dad0b9..ddd039fec 100644 --- a/test/constants/devices.js +++ b/test/constants/devices.js @@ -1,8 +1,8 @@ -'use strict' -const test = require('ava') -const devices = require('../../src/constants/devices') +import test from 'ava' + +import * as devices from '../../src/constants/devices.js' test('is an object', (t) => { t.is(typeof devices, 'object') diff --git a/test/constants/durations.js b/test/constants/durations.js index 4020cbbbf..d3167cb68 100644 --- a/test/constants/durations.js +++ b/test/constants/durations.js @@ -1,8 +1,8 @@ -'use strict' -const test = require('ava') -const durations = require('../../src/constants/durations') +import test from 'ava' + +import * as durations from '../../src/constants/durations.js' test('is an object', (t) => { t.is(typeof durations, 'object') diff --git a/test/constants/intervals.js b/test/constants/intervals.js index 58d1e9d23..a9166d46c 100644 --- a/test/constants/intervals.js +++ b/test/constants/intervals.js @@ -1,8 +1,8 @@ -'use strict' -const test = require('ava') -const intervals = require('../../src/constants/intervals') +import test from 'ava' + +import * as intervals from '../../src/constants/intervals.js' test('is an object', (t) => { t.is(typeof intervals, 'object') diff --git a/test/constants/ranges.js b/test/constants/ranges.js index 64f63be88..09307e351 100644 --- a/test/constants/ranges.js +++ b/test/constants/ranges.js @@ -1,8 +1,8 @@ -'use strict' -const test = require('ava') -const ranges = require('../../src/constants/ranges') +import test from 'ava' + +import * as ranges from '../../src/constants/ranges.js' test('is an object', (t) => { t.true(typeof ranges === 'object') diff --git a/test/constants/referrers.js b/test/constants/referrers.js index 341945c1f..76bde3666 100644 --- a/test/constants/referrers.js +++ b/test/constants/referrers.js @@ -1,8 +1,8 @@ -'use strict' -const test = require('ava') -const referrers = require('../../src/constants/referrers') +import test from 'ava' + +import * as referrers from '../../src/constants/referrers.js' test('is an object', (t) => { t.is(typeof referrers, 'object') diff --git a/test/constants/sizes.js b/test/constants/sizes.js index 8f7412eb1..1dd83a95d 100644 --- a/test/constants/sizes.js +++ b/test/constants/sizes.js @@ -1,8 +1,8 @@ -'use strict' -const test = require('ava') -const sizes = require('../../src/constants/sizes') +import test from 'ava' + +import * as sizes from '../../src/constants/sizes.js' test('is an object', (t) => { t.is(typeof sizes, 'object') diff --git a/test/constants/sortings.js b/test/constants/sortings.js index beec35d8d..85fc5e7b5 100644 --- a/test/constants/sortings.js +++ b/test/constants/sortings.js @@ -1,8 +1,8 @@ -'use strict' -const test = require('ava') -const sortings = require('../../src/constants/sortings') +import test from 'ava' + +import * as sortings from '../../src/constants/sortings.js' test('is an object', (t) => { t.is(typeof sortings, 'object') diff --git a/test/constants/systems.js b/test/constants/systems.js index dd0628f85..58230a840 100644 --- a/test/constants/systems.js +++ b/test/constants/systems.js @@ -1,8 +1,8 @@ -'use strict' -const test = require('ava') -const systems = require('../../src/constants/systems') +import test from 'ava' + +import * as systems from '../../src/constants/systems.js' test('is an object', (t) => { t.is(typeof systems, 'object') diff --git a/test/constants/views.js b/test/constants/views.js index 347568f3d..16ffe113f 100644 --- a/test/constants/views.js +++ b/test/constants/views.js @@ -1,8 +1,8 @@ -'use strict' -const test = require('ava') -const views = require('../../src/constants/views') +import test from 'ava' + +import * as views from '../../src/constants/views.js' test('is an object', (t) => { t.is(typeof views, 'object') diff --git a/test/resolvers/_utils.js b/test/resolvers/_utils.js index cba91bf36..4bf093928 100644 --- a/test/resolvers/_utils.js +++ b/test/resolvers/_utils.js @@ -1,27 +1,25 @@ -'use strict' - -const { MongoMemoryServer } = require('mongodb-memory-server') -const mongoose = require('mongoose') - -const Token = require('../../src/models/Token') -const PermanentToken = require('../../src/models/PermanentToken') -const Domain = require('../../src/models/Domain') -const Event = require('../../src/models/Event') -const Record = require('../../src/models/Record') -const Action = require('../../src/models/Action') -const connect = require('../../src/utils/connect') -const createArray = require('../../src/utils/createArray') -const { day, minute } = require('../../src/utils/times') +import { MongoMemoryServer } from 'mongodb-memory-server' +import mongoose from 'mongoose' + +import Token from '../../src/models/Token.js' +import PermanentToken from '../../src/models/PermanentToken.js' +import Domain from '../../src/models/Domain.js' +import Event from '../../src/models/Event.js' +import Record from '../../src/models/Record.js' +import Action from '../../src/models/Action.js' +import connect from '../../src/utils/connect.js' +import createArray from '../../src/utils/createArray.js' +import { day, minute } from '../../src/utils/times.js' const mongoDb = MongoMemoryServer.create() -const connectToDatabase = async () => { +export const connectToDatabase = async () => { const dbUrl = (await mongoDb).getUri() return connect(dbUrl) } -const fillDatabase = async (t) => { - // Saves to context so tests can access ids +export const fillDatabase = async (t) => { +// Saves to context so tests can access ids t.context.token = await Token.create({}) t.context.permanentToken = await PermanentToken.create({ title: 'Example' }) t.context.domain = await Domain.create({ title: 'Example' }) @@ -64,7 +62,7 @@ const fillDatabase = async (t) => { await Action.insertMany(actions) } -const cleanupDatabase = async (t) => { +export const cleanupDatabase = async (t) => { await Token.findOneAndDelete({ id: t.context.token.id, }) @@ -73,12 +71,12 @@ const cleanupDatabase = async (t) => { }) } -const disconnectFromDatabase = async () => { +export const disconnectFromDatabase = async () => { mongoose.disconnect() ;(await mongoDb).stop() } -const api = async (base, body, token, headers = {}) => { +export const api = async (base, body, token, headers = {}) => { const url = new URL('/api', await base) const defaultHeaders = {} @@ -98,12 +96,4 @@ const api = async (base, body, token, headers = {}) => { headers: result.headers, json: await result.json(), } -} - -module.exports = { - connectToDatabase, - fillDatabase, - cleanupDatabase, - disconnectFromDatabase, - api, } \ No newline at end of file diff --git a/test/resolvers/actions.js b/test/resolvers/actions.js index 4b3efe8f1..14c3a9acb 100644 --- a/test/resolvers/actions.js +++ b/test/resolvers/actions.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const listen = require('test-listen') -const uuid = require('crypto').randomUUID - -const server = require('../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } = require('./_utils') +import server from '../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/domainStatistics/_utils.js b/test/resolvers/domainStatistics/_utils.js index c17fed59a..f1776e72a 100644 --- a/test/resolvers/domainStatistics/_utils.js +++ b/test/resolvers/domainStatistics/_utils.js @@ -1,8 +1,6 @@ -'use strict' +import { api } from '../_utils.js' -const { api } = require('../_utils') - -const getStats = async ({ base, token, domainId, fragment }) => { +export const getStats = async ({ base, token, domainId, fragment }) => { const body = { query: ` query fetchStatistics($id: ID!) { @@ -26,8 +24,4 @@ const getStats = async ({ base, token, domainId, fragment }) => { } return json.data.domain.statistics -} - -module.exports = { - getStats, } \ No newline at end of file diff --git a/test/resolvers/domainStatistics/browsers.js b/test/resolvers/domainStatistics/browsers.js index ee97593cc..8494cae3f 100644 --- a/test/resolvers/domainStatistics/browsers.js +++ b/test/resolvers/domainStatistics/browsers.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/domainStatistics/devices.js b/test/resolvers/domainStatistics/devices.js index b40019297..043e18592 100644 --- a/test/resolvers/domainStatistics/devices.js +++ b/test/resolvers/domainStatistics/devices.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/domainStatistics/durations.js b/test/resolvers/domainStatistics/durations.js index 2e48480e0..59e6d7c19 100644 --- a/test/resolvers/domainStatistics/durations.js +++ b/test/resolvers/domainStatistics/durations.js @@ -1,12 +1,10 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { minute } = require('../../../src/utils/times') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { minute } from '../../../src/utils/times.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/domainStatistics/languages.js b/test/resolvers/domainStatistics/languages.js index ddc4acb44..818c7192b 100644 --- a/test/resolvers/domainStatistics/languages.js +++ b/test/resolvers/domainStatistics/languages.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/domainStatistics/pages.js b/test/resolvers/domainStatistics/pages.js index 9af770da5..390573852 100644 --- a/test/resolvers/domainStatistics/pages.js +++ b/test/resolvers/domainStatistics/pages.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/domainStatistics/referrers.js b/test/resolvers/domainStatistics/referrers.js index 7a9497c9e..aeb2ed56c 100644 --- a/test/resolvers/domainStatistics/referrers.js +++ b/test/resolvers/domainStatistics/referrers.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/domainStatistics/sizes.js b/test/resolvers/domainStatistics/sizes.js index f784e7693..d92b9685f 100644 --- a/test/resolvers/domainStatistics/sizes.js +++ b/test/resolvers/domainStatistics/sizes.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/domainStatistics/systems.js b/test/resolvers/domainStatistics/systems.js index cc29af97f..d65b3df80 100644 --- a/test/resolvers/domainStatistics/systems.js +++ b/test/resolvers/domainStatistics/systems.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/domainStatistics/views.js b/test/resolvers/domainStatistics/views.js index bc2acbd0d..8b4c12fab 100644 --- a/test/resolvers/domainStatistics/views.js +++ b/test/resolvers/domainStatistics/views.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/domains.js b/test/resolvers/domains.js index f4d736c89..c96bf489a 100644 --- a/test/resolvers/domains.js +++ b/test/resolvers/domains.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const listen = require('test-listen') -const uuid = require('crypto').randomUUID - -const server = require('../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } = require('./_utils') +import server from '../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/eventStatistics/_utils.js b/test/resolvers/eventStatistics/_utils.js index cb5f0e0f8..0b5c27160 100644 --- a/test/resolvers/eventStatistics/_utils.js +++ b/test/resolvers/eventStatistics/_utils.js @@ -1,8 +1,6 @@ -'use strict' +import { api } from '../_utils.js' -const { api } = require('../_utils') - -const getStats = async ({ base, token, eventId, fragment }) => { +export const getStats = async ({ base, token, eventId, fragment }) => { const body = { query: ` query fetchStatistics($id: ID!) { @@ -26,8 +24,4 @@ const getStats = async ({ base, token, eventId, fragment }) => { } return json.data.event.statistics -} - -module.exports = { - getStats, } \ No newline at end of file diff --git a/test/resolvers/eventStatistics/chart.js b/test/resolvers/eventStatistics/chart.js index a92eeee28..46670eae4 100644 --- a/test/resolvers/eventStatistics/chart.js +++ b/test/resolvers/eventStatistics/chart.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/eventStatistics/list.js b/test/resolvers/eventStatistics/list.js index 6d5a2df0f..d99e66b85 100644 --- a/test/resolvers/eventStatistics/list.js +++ b/test/resolvers/eventStatistics/list.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } = require('../_utils') -const { getStats } = require('./_utils') +import server from '../../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase } from '../_utils.js' +import { getStats } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/events.js b/test/resolvers/events.js index f6701107d..08dd4ec97 100644 --- a/test/resolvers/events.js +++ b/test/resolvers/events.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const listen = require('test-listen') -const uuid = require('crypto').randomUUID - -const server = require('../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } = require('./_utils') +import server from '../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/facts.js b/test/resolvers/facts.js index 082f273e1..1f230c7a2 100644 --- a/test/resolvers/facts.js +++ b/test/resolvers/facts.js @@ -1,10 +1,8 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } = require('./_utils') +import server from '../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/permanentTokens.js b/test/resolvers/permanentTokens.js index d3abbd4ec..a16aa2fbb 100644 --- a/test/resolvers/permanentTokens.js +++ b/test/resolvers/permanentTokens.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const listen = require('test-listen') -const uuid = require('crypto').randomUUID - -const server = require('../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } = require('./_utils') +import server from '../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/records.js b/test/resolvers/records.js index 115d0aa5f..534bae40c 100644 --- a/test/resolvers/records.js +++ b/test/resolvers/records.js @@ -1,10 +1,8 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' -const test = require('ava') -const listen = require('test-listen') - -const server = require('../../src/server') -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } = require('./_utils') +import server from '../../src/server.js' +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } from './_utils.js' const base = listen(server) diff --git a/test/resolvers/tokens.js b/test/resolvers/tokens.js index 7ec26e836..d930b51c9 100644 --- a/test/resolvers/tokens.js +++ b/test/resolvers/tokens.js @@ -1,11 +1,9 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import mockedEnv from 'mocked-env' -const test = require('ava') -const listen = require('test-listen') -const mockedEnv = require('mocked-env') - -const { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } = require('./_utils') -const server = require('../../src/server') +import { connectToDatabase, fillDatabase, cleanupDatabase, disconnectFromDatabase, api } from './_utils.js' +import server from '../../src/server.js' const base = listen(server) diff --git a/test/server.js b/test/server.js index 52372be54..a17505851 100644 --- a/test/server.js +++ b/test/server.js @@ -1,10 +1,8 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' +import listen from 'test-listen' -const test = require('ava') -const uuid = require('crypto').randomUUID -const listen = require('test-listen') - -const server = require('../src/server') +import server from '../src/server.js' const base = listen(server) diff --git a/test/serverWithAutoCors.js b/test/serverWithAutoCors.js index 532ff4f07..08e5981da 100644 --- a/test/serverWithAutoCors.js +++ b/test/serverWithAutoCors.js @@ -1,14 +1,11 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import mockedEnv from 'mocked-env' +import fetch from 'node-fetch' -const test = require('ava') -const listen = require('test-listen') -const fetch = require('node-fetch') -const mockedEnv = require('mocked-env') - -const server = require('../src/server') - -const Domain = require('../src/models/Domain') -const { connectToDatabase, disconnectFromDatabase } = require('./resolvers/_utils') +import server from '../src/server.js' +import Domain from '../src/models/Domain.js' +import { connectToDatabase, disconnectFromDatabase } from './resolvers/_utils.js' const base = listen(server) @@ -30,6 +27,7 @@ test('return cors headers based on fully qualifed domain names', async (t) => { ACKEE_AUTO_ORIGIN: 'true', }) + // Use node-fetch to make requests with different Host headers as the built-in fetch does not support modifying the Host header const { headers: fqdnHeaders } = await fetch(url.href, { headers: { Host: 'fqdn.example.com' } }) t.is(fqdnHeaders.get('Access-Control-Allow-Origin'), 'fqdn.example.com') @@ -37,6 +35,7 @@ test('return cors headers based on fully qualifed domain names', async (t) => { t.is(fqdnHeaders.get('Access-Control-Allow-Headers'), 'Content-Type, Authorization, Time-Zone') t.is(fqdnHeaders.get('Access-Control-Allow-Credentials'), 'true') + // Use node-fetch to make requests with different Host headers as the built-in fetch does not support modifying the Host header const { headers: noFqdnHeaders } = await fetch(url.href, { headers: { Host: 'No fqdn' } }) t.is(noFqdnHeaders.get('Access-Control-Allow-Origin'), null) diff --git a/test/serverWithCors.js b/test/serverWithCors.js index 5a751572a..40e9cee01 100644 --- a/test/serverWithCors.js +++ b/test/serverWithCors.js @@ -1,10 +1,8 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import mockedEnv from 'mocked-env' -const test = require('ava') -const listen = require('test-listen') -const mockedEnv = require('mocked-env') - -const server = require('../src/server') +import server from '../src/server.js' const base = listen(server) diff --git a/test/serverWithMultipleCors.js b/test/serverWithMultipleCors.js index c6e6cb9d5..df8ca716f 100644 --- a/test/serverWithMultipleCors.js +++ b/test/serverWithMultipleCors.js @@ -1,10 +1,8 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import mockedEnv from 'mocked-env' -const test = require('ava') -const listen = require('test-listen') -const mockedEnv = require('mocked-env') - -const server = require('../src/server') +import server from '../src/server.js' const base = listen(server) diff --git a/test/serverWithUnlistedCors.js b/test/serverWithUnlistedCors.js index f8e814ad4..8d8a80e99 100644 --- a/test/serverWithUnlistedCors.js +++ b/test/serverWithUnlistedCors.js @@ -1,10 +1,8 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import mockedEnv from 'mocked-env' -const test = require('ava') -const listen = require('test-listen') -const mockedEnv = require('mocked-env') - -const server = require('../src/server') +import server from '../src/server.js' const base = listen(server) diff --git a/test/serverWithWildcardCors.js b/test/serverWithWildcardCors.js index c59364ba0..a7b5e183b 100644 --- a/test/serverWithWildcardCors.js +++ b/test/serverWithWildcardCors.js @@ -1,10 +1,8 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import mockedEnv from 'mocked-env' -const test = require('ava') -const listen = require('test-listen') -const mockedEnv = require('mocked-env') - -const server = require('../src/server') +import server from '../src/server.js' const base = listen(server) diff --git a/test/serverWithoutCors.js b/test/serverWithoutCors.js index 360ac600a..0fbce47fa 100644 --- a/test/serverWithoutCors.js +++ b/test/serverWithoutCors.js @@ -1,10 +1,8 @@ -'use strict' +import test from 'ava' +import listen from 'test-listen' +import mockedEnv from 'mocked-env' -const test = require('ava') -const listen = require('test-listen') -const mockedEnv = require('mocked-env') - -const server = require('../src/server') +import server from '../src/server.js' const base = listen(server) diff --git a/test/utils/createArray.js b/test/utils/createArray.js index e38af13b0..5bd7805be 100644 --- a/test/utils/createArray.js +++ b/test/utils/createArray.js @@ -1,8 +1,6 @@ -'use strict' +import test from 'ava' -const test = require('ava') - -const createArray = require('../../src/utils/createArray') +import createArray from '../../src/utils/createArray.js' test('return boolean', (t) => { const length = 4 diff --git a/test/utils/customTrackerUrl.js b/test/utils/customTrackerUrl.js index cd4323524..11fd7bf33 100644 --- a/test/utils/customTrackerUrl.js +++ b/test/utils/customTrackerUrl.js @@ -1,8 +1,6 @@ -'use strict' +import test from 'ava' -const test = require('ava') - -const customTracker = require('../../src/utils/customTracker') +import * as customTracker from '../../src/utils/customTracker.js' test('return that a custom tracker exists', (t) => { const result = customTracker.exists diff --git a/test/utils/identifier.js b/test/utils/identifier.js index b5ebcf80a..0b790df51 100644 --- a/test/utils/identifier.js +++ b/test/utils/identifier.js @@ -1,9 +1,7 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const identifier = require('../../src/utils/identifier') +import identifier from '../../src/utils/identifier.js' test('return different identifiers', (t) => { const domainId = uuid() diff --git a/test/utils/isExpired.js b/test/utils/isExpired.js index 73bae24fa..c1c4f2f77 100644 --- a/test/utils/isExpired.js +++ b/test/utils/isExpired.js @@ -1,9 +1,7 @@ -'use strict' +import test from 'ava' -const test = require('ava') - -const { day } = require('../../src/utils/times') -const isExpired = require('../../src/utils/isExpired') +import { day } from '../../src/utils/times.js' +import isExpired from '../../src/utils/isExpired.js' test('return true when `timestamp` has expired', (t) => { const date = new Date() diff --git a/test/utils/layout.js b/test/utils/layout.js index 8dd29e3b7..b4c671bfd 100644 --- a/test/utils/layout.js +++ b/test/utils/layout.js @@ -1,9 +1,7 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const layout = require('../../src/utils/layout') +import layout from '../../src/utils/layout.js' test('return HTML with body', (t) => { const body = uuid() diff --git a/test/utils/messages.js b/test/utils/messages.js index 21bd1a1fb..5f55d0bca 100644 --- a/test/utils/messages.js +++ b/test/utils/messages.js @@ -1,9 +1,7 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const messages = require('../../src/utils/messages') +import messages from '../../src/utils/messages.js' test('extract messages from an object with errors', (t) => { const message = uuid() diff --git a/test/utils/normalizeUrl.js b/test/utils/normalizeUrl.js index 8cc9bde40..143e956d0 100644 --- a/test/utils/normalizeUrl.js +++ b/test/utils/normalizeUrl.js @@ -1,9 +1,7 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const normalizeUrl = require('../../src/utils/normalizeUrl') +import normalizeUrl from '../../src/utils/normalizeUrl.js' test('remove directory index', (t) => { const url = 'https://example.com/index.html' diff --git a/test/utils/pipe.js b/test/utils/pipe.js index 6d908891e..7542f5bcc 100644 --- a/test/utils/pipe.js +++ b/test/utils/pipe.js @@ -1,9 +1,7 @@ -'use strict' +import test from 'ava' +import { randomUUID as uuid } from 'crypto' -const test = require('ava') -const uuid = require('crypto').randomUUID - -const pipe = require('../../src/utils/pipe') +import pipe from '../../src/utils/pipe.js' test('return response of first function with a return value', async (t) => { const _b = uuid() diff --git a/test/utils/salt.js b/test/utils/salt.js index a27313d32..6af631055 100644 --- a/test/utils/salt.js +++ b/test/utils/salt.js @@ -1,8 +1,6 @@ -'use strict' +import test from 'ava' -const test = require('ava') - -const salt = require('../../src/utils/salt') +import salt from '../../src/utils/salt.js' test('return same result as long as it is the same day', (t) => { const a = salt() diff --git a/test/utils/signale.js b/test/utils/signale.js index 3f2d798d9..7a4767136 100644 --- a/test/utils/signale.js +++ b/test/utils/signale.js @@ -1,9 +1,9 @@ -'use strict' +import test from 'ava' +import signaleModule from 'signale' -const test = require('ava') -const { Signale } = require('signale') +import signale from '../../src/utils/signale.js' -const signale = require('../../src/utils/signale') +const { Signale } = signaleModule test('is a Signale instance', (t) => { t.true(signale instanceof Signale) diff --git a/test/utils/stripUrlAuth.js b/test/utils/stripUrlAuth.js index 571ef9f96..6605810f0 100644 --- a/test/utils/stripUrlAuth.js +++ b/test/utils/stripUrlAuth.js @@ -1,8 +1,6 @@ -'use strict' +import test from 'ava' -const test = require('ava') - -const stripUrlAuth = require('../../src/utils/stripUrlAuth') +import stripUrlAuth from '../../src/utils/stripUrlAuth.js' test('remove user and password', (t) => { const url = 'mongodb://username:password@host:3000/database' diff --git a/test/utils/timeZone.js b/test/utils/timeZone.js index 62aaf66fc..f1fdc9714 100644 --- a/test/utils/timeZone.js +++ b/test/utils/timeZone.js @@ -1,8 +1,6 @@ -'use strict' +import test from 'ava' -const test = require('ava') - -const timeZone = require('../../src/utils/timeZone') +import timeZone from '../../src/utils/timeZone.js' test('returns timeZone', (t) => { new Intl.DateTimeFormat(undefined, { timeZone }) diff --git a/test/utils/times.js b/test/utils/times.js index 8f0e9ecbe..af51e0d5d 100644 --- a/test/utils/times.js +++ b/test/utils/times.js @@ -1,8 +1,6 @@ -'use strict' +import test from 'ava' -const test = require('ava') - -const times = require('../../src/utils/times') +import * as times from '../../src/utils/times.js' test('return one second in milliseconds', (t) => { t.is(times.second, 1000)