From 96e65b4b4ec899268f9a685bc54ed3fcd4fe88eb Mon Sep 17 00:00:00 2001 From: Stanislav Atroschenko Date: Tue, 10 Jan 2023 14:36:30 +0300 Subject: [PATCH] AG-17246 fix code style to conform to guidelines Merge in ADGUARD-FILTERS/scriptlets from fix/AG-17246 to release/v1.8 Squashed commit of the following: commit 62ebabae021badccfa3bedfdf13ad8cda84a675a Author: Stanislav A Date: Mon Jan 9 21:20:40 2023 +0300 remove dashes after param docs commit 3e1ea2d02c0c2e75d3f6e618563f338928e9bc78 Author: Stanislav A Date: Mon Jan 9 21:18:22 2023 +0300 swap wildcard to 'any' for param types commit 9edacb068d328039ac5d0f67f215a43c0d69f7ae Author: Stanislav A Date: Fri Dec 30 14:52:40 2022 +0300 config and apply check-types commit 8a17e2d657e572d746c28ad19c021b023d890617 Author: Stanislav A Date: Fri Dec 30 14:10:50 2022 +0300 remove unsupported import syntax commit c49ebf47b79996efed88ea05c88ef455c838df40 Author: Stanislav A Date: Thu Dec 29 20:51:12 2022 +0300 enable rules for helpers p2 commit 279c58904a11c16473729bd382bc4fe9868925d7 Author: Stanislav A Date: Thu Dec 29 20:18:20 2022 +0300 enable rules for helpers p1 commit 6e3f5de3968035acff369747a8cd119913ebd1be Author: Stanislav A Date: Thu Dec 29 17:04:06 2022 +0300 split overrides into separate eslint configs commit bbffe492aa6f9f33385b4b20f8be1f4b0edc019a Merge: 8717f33b 0aeb1d5c Author: Stanislav A Date: Thu Dec 29 16:34:42 2022 +0300 merge master commit 8717f33bd9d4affd6f1aeeb4d43b97354e933b8c Author: Stanislav A Date: Wed Dec 28 20:39:28 2022 +0300 use rules for helpers commit 026785f4ce6b2dbb83e9e80f63a969b075790981 Author: Stanislav A Date: Wed Dec 28 20:03:59 2022 +0300 fix tag-lines p2 commit 9a4aa4d0e3e9cee4c812d98a8460a269388dc04e Merge: 048e32c8 89185d3e Author: Stanislav A Date: Wed Dec 28 18:48:44 2022 +0300 merge release/v1.8 commit 048e32c886cced586fe5f6b32cb95814072c0ef2 Author: Stanislav A Date: Wed Dec 28 15:09:30 2022 +0300 enable jsdoc/require-property-description commit c3d3d5d10dc48259be416e78d675ecce2c0f6501 Author: Stanislav A Date: Wed Dec 28 14:39:00 2022 +0300 enable jsdoc/tag-lines commit fe47c15f0fe1f537d860df1e05e84637d082ae6e Author: Stanislav A Date: Wed Dec 28 14:14:21 2022 +0300 enable jsdoc/require-returns commit f5d898e43ba49800707e16f97d7f5f29bf5d1dea Author: Stanislav A Date: Wed Dec 28 13:33:58 2022 +0300 enable jsdoc/newline-after-description commit 034db74d130feaad63622b9f78774b6e22cc89a1 Author: Stanislav A Date: Wed Dec 28 12:59:12 2022 +0300 enable jsdoc/check-tag-names commit 286558e0d6aeaf42f5941ef0c36d7a731d01a0b5 Author: Stanislav A Date: Tue Dec 27 21:11:37 2022 +0300 enable jsdoc/require-param-type commit b34878a2ca29ade2235927207c3584e46726da50 Author: Stanislav A Date: Tue Dec 27 20:59:30 2022 +0300 enable jsdoc/check-alignment commit fe206576731c70958e9c92724e8cad6d902bb347 Author: Stanislav A Date: Tue Dec 27 20:56:32 2022 +0300 enable jsdoc/check-types commit 4908c90f48e8a552f0600bfb50c30f3e0aa16b0c Author: Stanislav A Date: Tue Dec 27 20:48:19 2022 +0300 enable jsdoc/check-param-names ... and 4 more commits --- .eslintrc | 30 -- .eslintrc.js | 48 +++ package.json | 1 + scripts/build-compatibility-table.js | 13 +- scripts/build-corelibs.js | 3 +- scripts/build-docs.js | 6 +- scripts/build-funcs.js | 5 +- scripts/build-redirects.js | 6 +- scripts/build-tests.js | 2 + scripts/check-sources-updates.js | 19 +- scripts/helpers.js | 6 +- scripts/rollup-runners.js | 6 +- src/helpers/.eslintrc.js | 14 + src/helpers/add-event-listener-utils.js | 17 +- src/helpers/adjust-set-utils.js | 13 +- src/helpers/array-utils.js | 9 +- src/helpers/converter.js | 69 +++-- src/helpers/cookie-utils.js | 30 +- src/helpers/create-on-error-handler.js | 3 +- src/helpers/get-descriptor-addon.js | 8 +- src/helpers/get-property-in-chain.js | 14 +- src/helpers/get-wildcard-property-in-chain.js | 14 +- src/helpers/hit.js | 4 +- src/helpers/injector.js | 20 +- src/helpers/log-message.js | 7 +- src/helpers/match-request-props.js | 11 +- src/helpers/match-stack.js | 3 +- src/helpers/noop-utils.js | 40 ++- src/helpers/number-utils.js | 22 +- src/helpers/object-utils.js | 23 +- src/helpers/observer.js | 11 +- src/helpers/open-shadow-dom-utils.js | 10 +- src/helpers/parse-flags.js | 12 +- src/helpers/parse-keyword-value.js | 4 +- src/helpers/parse-rule.js | 37 ++- src/helpers/prevent-utils.js | 17 +- src/helpers/random-id.js | 2 + src/helpers/request-utils.js | 35 ++- src/helpers/script-source-utils.js | 3 +- src/helpers/storage-utils.js | 13 +- src/helpers/string-utils.js | 80 +++-- src/helpers/throttle.js | 6 +- src/helpers/validator.js | 67 ++-- src/redirects/amazon-apstag.js | 1 - src/redirects/ati-smarttag.js | 1 - .../blocking-redirects/click2load.js | 5 + src/redirects/didomi-loader.js | 1 - src/redirects/fingerprintjs2.js | 1 - src/redirects/fingerprintjs3.js | 1 - src/redirects/gemius.js | 1 - src/redirects/google-analytics-ga.js | 1 - src/redirects/google-analytics.js | 8 +- src/redirects/google-ima3.js | 1 - .../googlesyndication-adsbygoogle.js | 1 - src/redirects/googletagservices-gpt.js | 1 - src/redirects/index.js | 3 + src/redirects/matomo.js | 1 - src/redirects/metrika-yandex-tag.js | 5 +- src/redirects/metrika-yandex-watch.js | 2 +- src/redirects/naver-wcslog.js | 1 - src/redirects/noeval.js | 1 - src/redirects/pardot-1.0.js | 1 - src/redirects/prebid-ads.js | 1 - src/redirects/prebid.js | 1 - src/redirects/prevent-bab.js | 1 - src/redirects/prevent-bab2.js | 1 - src/redirects/prevent-fab-3.2.0.js | 1 - src/redirects/prevent-popads-net.js | 1 - src/redirects/redirects.js | 23 +- src/redirects/scorecardresearch-beacon.js | 1 - src/redirects/set-popads-dummy.js | 1 - src/scriptlets/abort-current-inline-script.js | 1 - src/scriptlets/abort-on-property-read.js | 1 - src/scriptlets/abort-on-property-write.js | 1 - src/scriptlets/abort-on-stack-trace.js | 1 - src/scriptlets/adjust-setInterval.js | 1 - src/scriptlets/adjust-setTimeout.js | 1 - src/scriptlets/close-window.js | 1 - src/scriptlets/debug-current-inline-script.js | 1 - src/scriptlets/debug-on-property-read.js | 1 - src/scriptlets/debug-on-property-write.js | 1 - src/scriptlets/dir-string.js | 1 - src/scriptlets/disable-newtab-links.js | 1 - src/scriptlets/hide-in-shadow-dom.js | 1 - src/scriptlets/index.js | 5 +- src/scriptlets/json-prune.js | 3 +- src/scriptlets/log-addEventListener.js | 1 - src/scriptlets/log-eval.js | 1 - src/scriptlets/log-on-stack-trace.js | 1 - src/scriptlets/log.js | 1 - src/scriptlets/no-topics.js | 1 - src/scriptlets/noeval.js | 1 - src/scriptlets/nowebrtc.js | 1 - src/scriptlets/prevent-addEventListener.js | 3 +- src/scriptlets/prevent-adfly.js | 1 - src/scriptlets/prevent-bab.js | 1 - src/scriptlets/prevent-element-src-loading.js | 1 - src/scriptlets/prevent-eval-if.js | 1 - src/scriptlets/prevent-fab-3.2.0.js | 1 - src/scriptlets/prevent-fetch.js | 1 - src/scriptlets/prevent-popads-net.js | 1 - src/scriptlets/prevent-refresh.js | 1 - .../prevent-requestAnimationFrame.js | 1 - src/scriptlets/prevent-setInterval.js | 1 - src/scriptlets/prevent-setTimeout.js | 1 - src/scriptlets/prevent-window-open.js | 1 - src/scriptlets/prevent-xhr.js | 1 - src/scriptlets/remove-attr.js | 1 - src/scriptlets/remove-class.js | 1 - src/scriptlets/remove-cookie.js | 1 - src/scriptlets/remove-in-shadow-dom.js | 1 - src/scriptlets/set-attr.js | 1 - src/scriptlets/set-constant.js | 1 - src/scriptlets/set-cookie-reload.js | 1 - src/scriptlets/set-cookie.js | 1 - src/scriptlets/set-local-storage-item.js | 1 - src/scriptlets/set-popads-dummy.js | 1 - src/scriptlets/set-session-storage-item.js | 1 - src/scriptlets/trusted-click-element.js | 1 - .../trusted-replace-fetch-response.js | 2 +- .../trusted-replace-xhr-response.js | 1 - src/scriptlets/trusted-set-cookie-reload.js | 1 - src/scriptlets/trusted-set-cookie.js | 1 - .../trusted-set-local-storage-item.js | 1 - src/scriptlets/xml-prune.js | 2 - tests/.eslintrc.js | 8 + tests/helpers.js | 4 + tests/helpers/fetch-utils.test.js | 18 +- tests/helpers/number-utils.test.js | 4 - ...prevent-utils.js => prevent-utils.test.js} | 0 tests/index.js | 3 +- tests/redirects/ati-smarttag.test.js | 77 +++-- tests/scriptlets/hide-in-shadow-dom.test.js | 16 +- tests/scriptlets/json-prune.test.js | 290 +++++++++++++++--- tests/scriptlets/prevent-refresh.test.js | 2 +- tests/scriptlets/remove-in-shadow-dom.test.js | 16 +- tests/scriptlets/set-cookie.test.js | 12 +- yarn.lock | 48 ++- 138 files changed, 906 insertions(+), 487 deletions(-) delete mode 100644 .eslintrc create mode 100644 .eslintrc.js create mode 100644 src/helpers/.eslintrc.js create mode 100644 tests/.eslintrc.js rename tests/helpers/{prevent-utils.js => prevent-utils.test.js} (100%) diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index bc7d5b7bc..000000000 --- a/.eslintrc +++ /dev/null @@ -1,30 +0,0 @@ -{ - "extends": ["airbnb-base"], - "parser": "@babel/eslint-parser", - "parserOptions": { - "babelOptions": { - "rootMode": "upward" - } - }, - "env": { - "browser": true, - "qunit": true - }, - "rules": { - "max-len": [ - "error", - { - "code": 120, - "ignoreUrls": true - } - ], - "indent": ["error", 4, { "SwitchCase": 1}], - "no-param-reassign": 0, - "no-shadow": 0, - "import/prefer-default-export": 0, - "arrow-body-style": 0, - "import/no-extraneous-dependencies": 0, - "no-await-in-loop": 0, - "no-restricted-syntax": 0 - } -} diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 000000000..de4697c84 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,48 @@ +module.exports = { + extends: [ + 'airbnb-base', + 'plugin:jsdoc/recommended', + ], + parser: '@babel/eslint-parser', + parserOptions: { + babelOptions: { + rootMode: 'upward', + }, + }, + env: { + browser: true, + qunit: true, + }, + rules: { + 'max-len': [ + 'error', + { + code: 120, + ignoreUrls: true, + }, + ], + indent: ['error', 4, { SwitchCase: 1 }], + 'no-param-reassign': 0, + 'no-shadow': 0, + 'import/prefer-default-export': 0, + 'arrow-body-style': 0, + 'import/no-extraneous-dependencies': 0, + 'no-await-in-loop': 0, + 'no-restricted-syntax': 0, + // jsdoc rules + 'jsdoc/check-tag-names': ['error', { definedTags: ['scriptlet', 'trustedScriptlet', 'redirect'] }], + 'jsdoc/require-jsdoc': 0, + 'jsdoc/require-param': 0, + 'jsdoc/valid-types': 0, + 'jsdoc/no-undefined-types': 0, + 'jsdoc/require-param-description': 0, + 'jsdoc/require-returns-description': 0, + }, + settings: { + jsdoc: { + preferredTypes: { + object: 'Object', + }, + }, + }, +}; diff --git a/package.json b/package.json index de2a235aa..72b8347fc 100644 --- a/package.json +++ b/package.json @@ -69,6 +69,7 @@ "eslint-config-airbnb-base": "^14.2.1", "eslint-plugin-compat": "^3.9.0", "eslint-plugin-import": "^2.22.1", + "eslint-plugin-jsdoc": "^39.6.4", "fs-extra": "^10.0.1", "husky": "~8.0.2", "js-reporters": "^2.1.0", diff --git a/scripts/build-compatibility-table.js b/scripts/build-compatibility-table.js index f1ab4179c..9fb988253 100644 --- a/scripts/build-compatibility-table.js +++ b/scripts/build-compatibility-table.js @@ -21,15 +21,15 @@ const WIKI_COMPATIBILITY_TABLE_PATH = path.resolve( /** * @typedef {Object} CompatibilityItem - * @property {string} adg - * @property {string} abp - * @property {string} ubo + * @property {string} adg AdGuard name + * @property {string} abp Adblock Plus name + * @property {string} ubo uBlock name */ /** * @typedef {Object} CompatibilityData - * @property {CompatibilityItem[]} scriptlets - * @property {CompatibilityItem[]} redirects + * @property {CompatibilityItem[]} scriptlets list of scriptlets compatibility items + * @property {CompatibilityItem[]} redirects list of redirects compatibility items */ /** @@ -50,7 +50,6 @@ const getTableData = () => { * @param {string} item.adg AdGuard name * @param {string} item.abp Adblock Plus name * @param {string} item.ubo uBlock name - * * @returns {string} markdown table row */ const getRow = (id, { adg, abp, ubo }) => { @@ -77,10 +76,10 @@ const getTableHeader = () => { /** * Builds markdown string of scriptlets/redirect compatibility table + * * @param {string} title title for scriptlets or redirects * @param {CompatibilityItem[]} data array of scriptlets or redirects compatibility data items * @param {'scriptlets'|'redirects'} id - * * @returns {string} scriptlets or redirects compatibility table */ const buildTable = (title, data = [], id = '') => { diff --git a/scripts/build-corelibs.js b/scripts/build-corelibs.js index d335ef0f8..2338d65bc 100644 --- a/scripts/build-corelibs.js +++ b/scripts/build-corelibs.js @@ -7,7 +7,8 @@ import { version } from '../package.json'; import { writeFile } from './helpers'; const buildCorelibsJson = async () => { - const { getScriptletFunction } = require('../tmp/scriptlets-func'); // eslint-disable-line import/no-unresolved,global-require + // eslint-disable-next-line import/no-unresolved,global-require + const { getScriptletFunction } = require('../tmp/scriptlets-func'); const scriptlets = await Promise.all(Object .values(scriptletList) diff --git a/scripts/build-docs.js b/scripts/build-docs.js index 6ce574322..c785c8589 100644 --- a/scripts/build-docs.js +++ b/scripts/build-docs.js @@ -46,8 +46,9 @@ const aboutTrustedScriptletsPath = path.resolve( ); /** - * Collects required comments from files and - * returns describing object for scriptlets and redirects + * Collects required comments from files + * + * @returns {Object} describing object for scriptlets and redirects */ const manageDataFromFiles = () => { const dataFromScriptletsFiles = getDataFromFiles( @@ -95,7 +96,6 @@ const manageDataFromFiles = () => { * Generates markdown list and describing text. * * @param {DescribingCommentData[]} dataItems array of comment data objects - * * @returns {MarkdownData} */ const getMarkdownData = (dataItems) => { diff --git a/scripts/build-funcs.js b/scripts/build-funcs.js index 57683c13b..0219e1d32 100644 --- a/scripts/build-funcs.js +++ b/scripts/build-funcs.js @@ -23,6 +23,8 @@ import { writeFile } from './helpers'; /** * Method creates string for file with scriptlets functions, * where dependencies are placed inside scriptlet functions + * + * @returns {string} */ const getScriptletFunctionsString = () => { function wrapInFunc(name, code) { @@ -31,7 +33,8 @@ const getScriptletFunctionsString = () => { // we require scriptlets list dynamically, because scriptletsList file can be not built in the // moment of this script execution - const scriptletsList = require('../tmp/scriptlets-list'); // eslint-disable-line global-require, import/no-unresolved + // eslint-disable-next-line import/no-unresolved,global-require + const scriptletsList = require('../tmp/scriptlets-list'); const scriptletsFunctions = Object.values(scriptletsList); diff --git a/scripts/build-redirects.js b/scripts/build-redirects.js index d12437e47..70e0f7eca 100644 --- a/scripts/build-redirects.js +++ b/scripts/build-redirects.js @@ -143,7 +143,9 @@ const getJsRedirects = async (options = {}) => { // TODO: seems like duplicate of already existed code /** * Returns first line of describing comment from redirect resource file + * * @param {string} rrName redirect resource name + * @returns {string|undefined} */ const getComment = (rrName) => { const { description } = redirectsDescriptions.find((rr) => rr.name === rrName); @@ -197,7 +199,7 @@ export const getPreparedRedirects = async (options) => { /** * Copies non-static redirects sources to dist * - * @param redirectsData + * @param {object[]} redirectsData */ const buildJsRedirectFiles = async (redirectsData) => { const saveRedirectData = async (redirect) => { @@ -212,7 +214,7 @@ const buildJsRedirectFiles = async (redirectsData) => { /** * Prepares static redirects sources to dist * - * @param redirectsData + * @param {object[]} redirectsData */ const buildStaticRedirectFiles = async (redirectsData) => { const prepareRedirectData = async (redirect) => { diff --git a/scripts/build-tests.js b/scripts/build-tests.js index d75871f96..090eb9cbe 100644 --- a/scripts/build-tests.js +++ b/scripts/build-tests.js @@ -14,9 +14,11 @@ const TEST_FILE_NAME_MARKER = '.test.js'; /** * Prepares rollup config for test file + * * @param {string} fileName test file name * @param {string} dirPath resolved directory path * @param {string} subDir subdirectory with test files + * @returns {Object} rollup config */ const getTestConfig = (fileName, dirPath, subDir) => { if (!fs.existsSync(TESTS_DIST)) { diff --git a/scripts/check-sources-updates.js b/scripts/check-sources-updates.js index 99fe89408..f548d3e32 100644 --- a/scripts/check-sources-updates.js +++ b/scripts/check-sources-updates.js @@ -14,8 +14,10 @@ const { /** * Checks if arrays contain the same strings + * * @param {Array} arr1 * @param {Array} arr2 + * @returns {boolean} */ const areArraysOfStringsEqual = (arr1, arr2) => { if (arr1.length !== arr2.length) { @@ -30,6 +32,8 @@ const areArraysOfStringsEqual = (arr1, arr2) => { /** * Returns parsed compatibility table + * + * @returns {Object} */ const getCompatibilityTable = () => { const rawData = fs.readFileSync(COMPATIBILITY_TABLE_DATA_PATH); @@ -39,7 +43,9 @@ const getCompatibilityTable = () => { /** * Returns list of scriptlets listed in table for specified platform + * * @param {"ubo"|"abp"} platform + * @returns {string[]} */ const getScriptletsFromTable = (platform) => { const { scriptlets } = getCompatibilityTable(); @@ -48,22 +54,32 @@ const getScriptletsFromTable = (platform) => { /** * Returns list of redirects listed in table for specified platform + * * @param {"ubo"|"abp"} platform + * @returns {string[]} */ const getRedirectsFromTable = (platform) => { const { redirects } = getCompatibilityTable(); return redirects.map((item) => item[platform]).filter((item) => !!item); }; +/** + * @typedef {Object} Diff + * @property {string[]} added added content + * @property {string[]} removed removed content + */ + /** * Finds a difference between old and new array + * * @param {Array} oldList * @param {Array} newList + * @returns {Diff|null} */ const getDiff = (oldList, newList) => { const diff = { - removed: [], added: [], + removed: [], }; diff.removed = oldList.filter((item) => ( @@ -77,6 +93,7 @@ const getDiff = (oldList, newList) => { /** * Marks removed rules with (removed) and adds new rules to the end of the table + * * @param {{removed: Array, added: Array}} diff Object with diffs for certain type and platform * @param {"scriptlets"|"redirects"} ruleType * @param {"ubo"|"abp"} platform diff --git a/scripts/helpers.js b/scripts/helpers.js index 6a75008bc..8dcec4ef8 100644 --- a/scripts/helpers.js +++ b/scripts/helpers.js @@ -21,6 +21,7 @@ const writeFile = async (filePath, content) => { /** * Gets list of `.js` files in directory + * * @param {string} relativeDirPath relative path to directory * @returns {string[]} array of file names */ @@ -43,7 +44,6 @@ const getFilesList = (relativeDirPath) => { * In one file might be comments describing scriptlet and redirect as well. * * @param {string} filePath absolute path to file - * * @returns {CommentTag[]} */ const getDescribingCommentTags = (filePath) => { @@ -80,7 +80,6 @@ Please add one OR edit the list of NON_SCRIPTLETS_FILES / NON_REDIRECTS_FILES.`) * @typedef {Object} DescribingCommentData * * Collected data from jsdoc-type comment for every scriptlet or redirect. - * * @property {string} type parsed instance tag: * 'scriptlet' for '@scriptlet', 'redirect' for '@redirect' * @property {string} name name of instance which goes after the instance tag @@ -93,7 +92,6 @@ Please add one OR edit the list of NON_SCRIPTLETS_FILES / NON_REDIRECTS_FILES.`) * * @param {CommentTag[]} commentTags parsed tags from describing comment * @param {string} source relative path to file - * * @returns {DescribingCommentData} */ const prepareCommentsData = (commentTags, source) => { @@ -108,9 +106,9 @@ const prepareCommentsData = (commentTags, source) => { /** * Gets data objects which describe every required comment in one directory + * * @param {string[]} filesList list of files in directory * @param {string} relativeDirPath relative path to directory - * * @returns {DescribingCommentData} */ const getDataFromFiles = (filesList, relativeDirPath) => { diff --git a/scripts/rollup-runners.js b/scripts/rollup-runners.js index 4498b0ebe..61e4d976f 100644 --- a/scripts/rollup-runners.js +++ b/scripts/rollup-runners.js @@ -5,7 +5,8 @@ const { log } = console; /** * Builds scriptlets - * @param config config may be list of configs or one config + * + * @param {object|object[]} config config may be list of configs or one config */ export const rollupStandard = async (config) => { const runOneConfig = async (config) => { @@ -26,7 +27,8 @@ export const rollupStandard = async (config) => { /** * Builds scriptlets in the watch mode - * @param config - config may be list of configs or one config + * + * @param {object|object[]} config - config may be list of configs or one config */ export const rollupWatch = (config) => { const watcher = rollup.watch(config); diff --git a/src/helpers/.eslintrc.js b/src/helpers/.eslintrc.js new file mode 100644 index 000000000..29fd65dfe --- /dev/null +++ b/src/helpers/.eslintrc.js @@ -0,0 +1,14 @@ +module.exports = { + extends: [ + '../../.eslintrc', + '../.eslintrc', + ], + rules: { + 'jsdoc/require-jsdoc': 1, + 'jsdoc/require-param': 1, + 'jsdoc/valid-types': 1, + 'jsdoc/no-undefined-types': 1, + 'jsdoc/require-param-description': 1, + 'jsdoc/require-returns-description': 1, + }, +}; diff --git a/src/helpers/add-event-listener-utils.js b/src/helpers/add-event-listener-utils.js index c579dca56..b87375734 100644 --- a/src/helpers/add-event-listener-utils.js +++ b/src/helpers/add-event-listener-utils.js @@ -1,7 +1,8 @@ /** * Validates event type - * @param {*} type - * @returns {boolean} + * + * @param {any} type event type + * @returns {boolean} if type is valid */ export const validateType = (type) => { // https://github.com/AdguardTeam/Scriptlets/issues/125 @@ -10,8 +11,9 @@ export const validateType = (type) => { /** * Validates event listener - * @param {*} listener - * @returns {boolean} + * + * @param {any} listener event listener + * @returns {boolean} if listener callback is valid */ export const validateListener = (listener) => { // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#parameters @@ -23,11 +25,16 @@ export const validateListener = (listener) => { && typeof listener.handleEvent === 'function')); }; +/** + * @typedef {object|Function|null} EventListener + */ + /** * Serialize valid event listener * https://developer.mozilla.org/en-US/docs/Web/API/EventListener + * * @param {EventListener} listener valid listener - * @returns {string} + * @returns {string} listener string */ export const listenerToString = (listener) => { return typeof listener === 'function' diff --git a/src/helpers/adjust-set-utils.js b/src/helpers/adjust-set-utils.js index 791b7b1ea..91b10e35c 100644 --- a/src/helpers/adjust-set-utils.js +++ b/src/helpers/adjust-set-utils.js @@ -4,7 +4,8 @@ export const shouldMatchAnyDelay = (delay) => delay === '*'; /** * Handles input delay value - * @param {*} delay + * + * @param {any} delay matchDelay argument of adjust-* scriptlets * @returns {number} proper number delay value */ export const getMatchDelay = (delay) => { @@ -18,9 +19,10 @@ export const getMatchDelay = (delay) => { /** * Checks delay match condition - * @param {*} inputDelay - * @param {number} realDelay - * @returns {boolean} + * + * @param {any} inputDelay matchDelay argument of adjust-* scriptlets + * @param {number} realDelay delay argument of setTimeout/setInterval + * @returns {boolean} if given delays match */ export const isDelayMatched = (inputDelay, realDelay) => { return shouldMatchAnyDelay(inputDelay) @@ -29,7 +31,8 @@ export const isDelayMatched = (inputDelay, realDelay) => { /** * Handles input boost value - * @param {*} boost + * + * @param {any} boost boost argument of adjust-* scriptlets * @returns {number} proper number boost multiplier value */ export const getBoostMultiplier = (boost) => { diff --git a/src/helpers/array-utils.js b/src/helpers/array-utils.js index 371e42668..9263e434d 100644 --- a/src/helpers/array-utils.js +++ b/src/helpers/array-utils.js @@ -2,7 +2,9 @@ * Some browsers do not support Array.prototype.flat() * for example, Opera 42 which is used for browserstack tests * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat - * @param {Array} input + * + * @param {Array} input arbitrary array + * @returns {Array} flattened array */ export const flatten = (input) => { const stack = []; @@ -24,7 +26,8 @@ export const flatten = (input) => { /** * Predicate method to check if the array item exists - * @param {any} item - * @returns {boolean} + * + * @param {any} item arbitrary + * @returns {boolean} if item is truthy or not */ export const isExisting = (item) => !!item; diff --git a/src/helpers/converter.js b/src/helpers/converter.js index 6dafe9962..54bc28a56 100644 --- a/src/helpers/converter.js +++ b/src/helpers/converter.js @@ -65,8 +65,10 @@ const ADG_REMOVE_CLASS_NAME = REMOVE_CLASS_ALIASES[0]; const REMOVE_ATTR_CLASS_APPLYING = ['asap', 'stay', 'complete']; /** - * Returns array of strings separated by space which not in quotes - * @param {string} str + * Returns array of strings separated by space which is not in quotes + * + * @param {string} str arbitrary string + * @returns {string[]} result array */ const getSentences = (str) => { const reg = /'.*?'|".*?"|\S+/g; @@ -75,8 +77,10 @@ const getSentences = (str) => { /** * Replaces string with data by placeholders - * @param {string} str - * @param {Object} data - where keys are placeholders names + * + * @param {string} str string with placeholders + * @param {Object} data where keys are placeholders names + * @returns {string} string filled with data */ const replacePlaceholders = (str, data) => { return Object.keys(data).reduce((acc, key) => { @@ -104,7 +108,8 @@ const splitArgs = (str) => { /** * Validates remove-attr/class scriptlet args - * @param {string[]} parsedArgs + * + * @param {string[]} parsedArgs scriptlet arguments * @returns {string[]|Error} valid args OR error for invalid selector */ const validateRemoveAttrClassArgs = (parsedArgs) => { @@ -147,8 +152,9 @@ const validateRemoveAttrClassArgs = (parsedArgs) => { /** * Converts string of UBO scriptlet rule to AdGuard scriptlet rule - * @param {string} rule - UBO scriptlet rule - * @returns {string[]} - array with one AdGuard scriptlet rule + * + * @param {string} rule UBO scriptlet rule + * @returns {string[]} array with one AdGuard scriptlet rule */ export const convertUboScriptletToAdg = (rule) => { const domains = getBeforeRegExp(rule, validator.UBO_SCRIPTLET_MASK_REG); @@ -193,9 +199,10 @@ export const convertUboScriptletToAdg = (rule) => { /** * Convert string of ABP snippet rule to AdGuard scriptlet rule - * @param {string} rule - ABP snippet rule - * @returns {Array} - array of AdGuard scriptlet rules - - * one or few items depends on Abp-rule + * + * @param {string} rule ABP snippet rule + * @returns {Array} array of AdGuard scriptlet rules, one or few items depends on Abp-rule + * */ export const convertAbpSnippetToAdg = (rule) => { const SEMICOLON_DIVIDER = /;(?=(?:(?:[^"]*"){2})*[^"]*$)/g; @@ -221,9 +228,9 @@ export const convertAbpSnippetToAdg = (rule) => { /** * Converts scriptlet rule to AdGuard one - * @param {string} rule - * @returns {Array} - array of AdGuard scriptlet rules - - * one item for Adg and Ubo or few items for Abp + * + * @param {string} rule scriptlet rule + * @returns {Array} array of AdGuard scriptlet rules, one item for Adg and Ubo or few items for Abp */ export const convertScriptletToAdg = (rule) => { let result; @@ -240,8 +247,9 @@ export const convertScriptletToAdg = (rule) => { /** * Converts UBO scriptlet rule to AdGuard one - * @param {string} rule - AdGuard scriptlet rule - * @returns {string} - UBO scriptlet rule + * + * @param {string} rule AdGuard scriptlet rule + * @returns {string} UBO scriptlet rule */ export const convertAdgScriptletToUbo = (rule) => { let res; @@ -328,8 +336,9 @@ export const convertAdgScriptletToUbo = (rule) => { /** * Checks whether the ADG scriptlet exists or UBO/ABP scriptlet is compatible to ADG - * @param {string} input - can be ADG or UBO or ABP scriptlet rule - * @returns {boolean} + * + * @param {string} input can be ADG or UBO or ABP scriptlet rule + * @returns {boolean} if scriptlet rule is valid */ export const isValidScriptletRule = (input) => { if (!input) { @@ -350,9 +359,10 @@ export const isValidScriptletRule = (input) => { /** * Gets index and redirect resource marker from UBO/ADG modifiers array - * @param {string[]} modifiers + * + * @param {string[]} modifiers rule modifiers * @param {Object} redirectsData validator.REDIRECT_RULE_TYPES.(UBO|ADG) - * @param {string} rule + * @param {string} rule rule string * @returns {Object} { index, marker } */ const getMarkerData = (modifiers, redirectsData, rule) => { @@ -373,8 +383,9 @@ const getMarkerData = (modifiers, redirectsData, rule) => { /** * Converts Ubo redirect rule to Adg one - * @param {string} rule - * @returns {string} + * + * @param {string} rule ubo redirect rule + * @returns {string} converted adg rule */ export const convertUboRedirectToAdg = (rule) => { const firstPartOfRule = substringBefore(rule, '$'); @@ -403,8 +414,9 @@ export const convertUboRedirectToAdg = (rule) => { /** * Converts Abp redirect rule to Adg one - * @param {string} rule - * @returns {string} + * + * @param {string} rule abp redirect rule + * @returns {string} converted adg rule */ export const convertAbpRedirectToAdg = (rule) => { const firstPartOfRule = substringBefore(rule, '$'); @@ -428,8 +440,9 @@ export const convertAbpRedirectToAdg = (rule) => { /** * Converts redirect rule to AdGuard one - * @param {string} rule - * @returns {string} + * + * @param {string} rule redirect rule + * @returns {string} converted adg rule */ export const convertRedirectToAdg = (rule) => { let result; @@ -452,8 +465,10 @@ export const convertRedirectToAdg = (rule) => { * Source types are chosen according to redirect name * e.g. ||ad.com^$redirect=,important ->> ||ad.com^$redirect=,important,script * 3. Replaces Adg redirect name by Ubo analog - * @param {string} rule - * @returns {string} + * + * @param {string} rule adg rule + * @returns {string} converted ubo rule + * @throws on incompatible rule */ export const convertAdgRedirectToUbo = (rule) => { if (!validator.isAdgRedirectCompatibleWithUbo(rule)) { diff --git a/src/helpers/cookie-utils.js b/src/helpers/cookie-utils.js index eaec3446e..7bebf680b 100644 --- a/src/helpers/cookie-utils.js +++ b/src/helpers/cookie-utils.js @@ -1,15 +1,10 @@ import { nativeIsNaN } from './number-utils'; -/** - * @typedef { import('../scriptlets/index').Source } Source - */ - /** * Checks whether the input path is supported * * @param {string} rawPath input path - * - * @returns {boolean} + * @returns {boolean} if cookie path is valid */ export const isValidCookiePath = (rawPath) => rawPath === '/' || rawPath === 'none'; @@ -17,9 +12,8 @@ export const isValidCookiePath = (rawPath) => rawPath === '/' || rawPath === 'no * Returns 'path=/' if rawPath is '/' * or empty string '' for other cases, `rawPath === 'none'` included * - * @param {string} rawPath - * - * @returns {string} + * @param {string} rawPath path argument of *set-cookie-* scriptlets + * @returns {string} cookie path */ export const getCookiePath = (rawPath) => { if (rawPath === '/') { @@ -33,10 +27,9 @@ export const getCookiePath = (rawPath) => { /** * Combines input cookie name, value, and path into string. * - * @param {string} rawName - * @param {string} rawValue - * @param {string} rawPath - * + * @param {string} rawName name argument of *set-cookie-* scriptlets + * @param {string} rawValue value argument of *set-cookie-* scriptlets + * @param {string} rawPath path argument of *set-cookie-* scriptlets * @returns {string|null} string OR `null` if path is not supported */ export const concatCookieNameValuePath = (rawName, rawValue, rawPath) => { @@ -48,7 +41,6 @@ export const concatCookieNameValuePath = (rawName, rawValue, rawPath) => { * Gets supported cookie value * * @param {string} value input cookie value - * * @returns {string|null} valid cookie string if ok OR null if not */ export const getLimitedCookieValue = (value) => { @@ -94,6 +86,7 @@ export const getLimitedCookieValue = (value) => { /** * Parses cookie string into object + * * @param {string} cookieString string that conforms to document.cookie format * @returns {Object} key:value object that corresponds with incoming cookies keys and values */ @@ -124,10 +117,11 @@ export const parseCookieString = (cookieString) => { /** * Check if cookie with specified name and value is present in a cookie string - * @param {string} cookieString - * @param {string} name - * @param {string} value - * @returns {boolean} + * + * @param {string} cookieString 'document.cookie'-like string + * @param {string} name name argument of *set-cookie-* scriptlets + * @param {string} value value argument of *set-cookie-* scriptlets + * @returns {boolean} if cookie is already set */ export const isCookieSetWithValue = (cookieString, name, value) => { return cookieString.split(';') diff --git a/src/helpers/create-on-error-handler.js b/src/helpers/create-on-error-handler.js index 4b9eca79a..041f8094d 100644 --- a/src/helpers/create-on-error-handler.js +++ b/src/helpers/create-on-error-handler.js @@ -1,8 +1,9 @@ /** * Generates function which silents global errors on page generated by scriptlet * If error doesn't belong to our error we transfer it to the native onError handler + * * @param {string} rid - unique identifier of scriptlet - * @return {onError} + * @returns {Function} window.onerror handler */ export function createOnErrorHandler(rid) { // eslint-disable-next-line consistent-return diff --git a/src/helpers/get-descriptor-addon.js b/src/helpers/get-descriptor-addon.js index 8c930a7b7..1acb3909f 100644 --- a/src/helpers/get-descriptor-addon.js +++ b/src/helpers/get-descriptor-addon.js @@ -1,21 +1,21 @@ import { randomId } from './random-id'; /** - * Prevent infinite loops when trapping props that could be used by scriptlet's own helpers + * Prevents infinite loops when trapping props that could be used by scriptlet's own helpers * Example: window.RegExp, that is used by matchStackTrace > toRegExp * * https://github.com/AdguardTeam/Scriptlets/issues/251 * https://github.com/AdguardTeam/Scriptlets/issues/226 * https://github.com/AdguardTeam/Scriptlets/issues/232 * - * @return {Object} + * @returns {Object} descriptor addon */ export function getDescriptorAddon() { return { isAbortingSuspended: false, isolateCallback(cb, ...args) { this.isAbortingSuspended = true; - // try...catch is required in case if there are more than one inline scripts - // which should be aborted. + // try...catch is required in case there are more than one inline scripts + // which should be aborted, // so after the first successful abortion, `cb(...args);` will throw error, // and we should not stop on that and continue to abort other scripts try { diff --git a/src/helpers/get-property-in-chain.js b/src/helpers/get-property-in-chain.js index a1d71a641..dd1f413b4 100644 --- a/src/helpers/get-property-in-chain.js +++ b/src/helpers/get-property-in-chain.js @@ -1,10 +1,10 @@ import { isEmptyObject } from './object-utils'; /** - * @typedef Chain - * @property {Object} base - * @property {string} prop - * @property {string} [chain] + * @typedef ChainInfo + * @property {Object} base current chain base + * @property {string} prop current chain prop + * @property {string} [chain] string representation */ /** @@ -14,9 +14,9 @@ import { isEmptyObject } from './object-utils'; * defines this property as 'undefined' * and returns base, property name and remaining part of property chain * - * @param {Object} base - * @param {string} chain - * @returns {Chain} + * @param {Object} base object that owns chain + * @param {string} chain chain of owner properties + * @returns {ChainInfo} chain info object */ export function getPropertyInChain(base, chain) { const pos = chain.indexOf('.'); diff --git a/src/helpers/get-wildcard-property-in-chain.js b/src/helpers/get-wildcard-property-in-chain.js index 0274983b0..0b139c8da 100644 --- a/src/helpers/get-wildcard-property-in-chain.js +++ b/src/helpers/get-wildcard-property-in-chain.js @@ -1,8 +1,8 @@ /** - * @typedef Chain - * @property {Object} base - * @property {string} prop - * @property {string} [chain] + * @typedef ChainInfo + * @property {Object} base current chain base + * @property {string} prop current chain prop + * @property {string} [chain] string representation */ /** @@ -10,12 +10,12 @@ * Similar to getPropertyInChain but upgraded for json-prune: * handle wildcard properties and does not define nonexistent base property as 'undefined' * - * @param {Object} base - * @param {string} chain + * @param {Object} base object that owns chain + * @param {string} chain chain of owner properties * @param {boolean} [lookThrough=false] * should the method look through it's props in order to wildcard * @param {Array} [output=[]] result acc - * @returns {Chain[]} array of objects + * @returns {ChainInfo[]} array of objects */ export function getWildcardPropertyInChain(base, chain, lookThrough = false, output = []) { const pos = chain.indexOf('.'); diff --git a/src/helpers/hit.js b/src/helpers/hit.js index 810216efe..8d5c685d3 100644 --- a/src/helpers/hit.js +++ b/src/helpers/hit.js @@ -1,7 +1,9 @@ /* eslint-disable no-console, no-underscore-dangle */ + /** * Hit used only for debug purposes now - * @param {Source} source + * + * @param {Object} source scriptlet properties * use LOG_MARKER = 'log: ' at the start of a message * for logging scriptlets */ diff --git a/src/helpers/injector.js b/src/helpers/injector.js index 80f99e577..74a1958e1 100644 --- a/src/helpers/injector.js +++ b/src/helpers/injector.js @@ -1,6 +1,8 @@ /** * Concat dependencies to scriptlet code + * * @param {string} scriptlet string view of scriptlet + * @returns {string} string view of scriptlet with attached dependencies */ export function attachDependencies(scriptlet) { const { injections = [] } = scriptlet; @@ -11,8 +13,10 @@ export function attachDependencies(scriptlet) { /** * Add scriptlet call to existing code - * @param {Function} scriptlet - * @param {string} code + * + * @param {Function} scriptlet scriptlet func + * @param {string} code scriptlet's string representation + * @returns {string} wrapped scriptlet call */ export function addCall(scriptlet, code) { return `${code} @@ -27,12 +31,6 @@ export function addCall(scriptlet, code) { /** * Wrap function into IIFE (Immediately invoked function expression) * - * @param {Source} source - object with scriptlet properties - * @param {string} code - scriptlet source code with dependencies - * - * @param redirect - * @returns {string} full scriptlet code - * * @example * const source = { * args: ["aaa", "bbb"], @@ -46,6 +44,10 @@ export function addCall(scriptlet, code) { * function noeval(source) { alert(source); } * noeval.apply(this, args); * )({"args": ["aaa", "bbb"], "name":"noeval"}, ["aaa", "bbb"])` + * @param {Object} source - object with scriptlet properties + * @param {string} code - scriptlet source code with dependencies + * @param {boolean} redirect if function is redirect + * @returns {string} full scriptlet code */ export function passSourceAndProps(source, code, redirect = false) { if (source.hit) { @@ -64,7 +66,9 @@ export function passSourceAndProps(source, code, redirect = false) { /** * Wrap code in no name function + * * @param {string} code which must be wrapped + * @returns {string} wrapped code */ export function wrapInNonameFunc(code) { return `function(source, args){\n${code}\n}`; diff --git a/src/helpers/log-message.js b/src/helpers/log-message.js index 0f9d0b781..1a87bf5e3 100644 --- a/src/helpers/log-message.js +++ b/src/helpers/log-message.js @@ -1,13 +1,10 @@ -/** - * @typedef { import('../scriptlets/index').Source } Source - */ - /** * Conditionally logs message to console. * Convention is to log messages by source.verbose if such log * is not a part of scriptlet's functionality, eg on invalid input, * and use 'forced' argument otherwise. - * @param {Source} source required + * + * @param {Object} source required, scriptlet properties * @param {string} message required, message to log * @param {boolean} [forced=false] to log message unconditionally */ diff --git a/src/helpers/match-request-props.js b/src/helpers/match-request-props.js index 63744ddef..2c4f52bdd 100644 --- a/src/helpers/match-request-props.js +++ b/src/helpers/match-request-props.js @@ -5,18 +5,15 @@ import { } from './request-utils'; import { logMessage } from './log-message'; -/** - * @typedef { import('../scriptlets/index').Source } Source - */ - /** * Checks if given propsToMatch string matches with given request data * This is used by prevent-xhr, prevent-fetch, trusted-replace-xhr-response * and trusted-replace-fetch-response scriptlets - * @param {Source} source - * @param {string} propsToMatch + * + * @param {Object} source scriptlet properties + * @param {string} propsToMatch string of space-separated request properties to match * @param {Object} requestData object with standard properties of fetch/xhr like url, method etc - * @returns {boolean} + * @returns {boolean} if request properties match */ export const matchRequestProps = (source, propsToMatch, requestData) => { if (propsToMatch === '' || propsToMatch === '*') { diff --git a/src/helpers/match-stack.js b/src/helpers/match-stack.js index 457e0ce85..8a713f4ab 100644 --- a/src/helpers/match-stack.js +++ b/src/helpers/match-stack.js @@ -5,9 +5,10 @@ import { getNativeRegexpTest } from './regexp-utils'; /** * Checks if the stackTrace contains stackRegexp * https://github.com/AdguardTeam/Scriptlets/issues/82 + * * @param {string|undefined} stackMatch - input stack value to match * @param {string} stackTrace - script error stack trace - * @returns {boolean} + * @returns {boolean} if the stackTrace contains stackRegexp */ export const matchStackTrace = (stackMatch, stackTrace) => { if (!stackMatch || stackMatch === '') { diff --git a/src/helpers/noop-utils.js b/src/helpers/noop-utils.js index 68a15aa2f..5e106b347 100644 --- a/src/helpers/noop-utils.js +++ b/src/helpers/noop-utils.js @@ -1,35 +1,42 @@ /** * Noop function - * @return {undefined} undefined + * + * @returns {undefined} undefined */ export const noopFunc = () => { }; /** - * Function return noopFunc - * @returns {Function} + * Function returns noopFunc + * + * @returns {Function} noopFunc */ export const noopCallbackFunc = () => noopFunc; /** * Function returns null - * @return {null} null + * + * @returns {null} null */ export const noopNull = () => null; /** * Function returns true - * @return {boolean} true + * + * @returns {boolean} true */ export const trueFunc = () => true; /** * Function returns false - * @return {boolean} false + * + * @returns {boolean} false */ export const falseFunc = () => false; /** * Function returns this + * + * @returns {this} this object */ export function noopThis() { return this; @@ -37,24 +44,28 @@ export function noopThis() { /** * Function returns empty string - * @return {string} empty string + * + * @returns {string} empty string */ export const noopStr = () => ''; /** * Function returns empty array - * @return {Array} empty array + * + * @returns {Array} empty array */ export const noopArray = () => []; /** * Function returns empty object - * @return {Object} empty object + * + * @returns {Object} empty object */ export const noopObject = () => ({}); /** * Function throws an error + * * @throws */ export const throwFunc = () => { @@ -63,13 +74,18 @@ export const throwFunc = () => { /** * Function returns Promise.reject() + * + * @returns {Promise} rejected Promise */ export const noopPromiseReject = () => Promise.reject(); // eslint-disable-line compat/compat /** - * Returns Promise object that is resolved value of response body - * @param {string} [url=''] value of response url to set on response object - * @param {string} [response='default'] value of response type to set on response object + * Returns Promise object that is resolved with specified props + * + * @param {string} [responseBody='{}'] value to set as responseBody + * @param {string} [responseUrl=''] value to set as responseUrl + * @param {string} [responseType='default'] value to set as responseType + * @returns {Promise|undefined} resolved Promise or undefined if Response interface is not available */ export const noopPromiseResolve = (responseBody = '{}', responseUrl = '', responseType = 'default') => { if (typeof Response === 'undefined') { diff --git a/src/helpers/number-utils.js b/src/helpers/number-utils.js index 72b50db7b..3a6b9b0f1 100644 --- a/src/helpers/number-utils.js +++ b/src/helpers/number-utils.js @@ -1,8 +1,9 @@ /** * Determines whether the passed value is NaN * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN - * @param {*} num - * @returns {boolean} + * + * @param {any} num arbitrary value + * @returns {boolean} if provided value is NaN */ export const nativeIsNaN = (num) => { // eslint-disable-next-line no-restricted-properties @@ -13,8 +14,9 @@ export const nativeIsNaN = (num) => { /** * Determines whether the passed value is a finite number * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite - * @param {*} num - * @returns {boolean} + * + * @param {any} num arbitrary value + * @returns {boolean} if provided value is finite */ export const nativeIsFinite = (num) => { // eslint-disable-next-line no-restricted-properties @@ -24,8 +26,9 @@ export const nativeIsFinite = (num) => { /** * Parses string for a number, if possible, otherwise returns null. - * @param {*} rawString - * @returns {number|null} + * + * @param {any} rawString arbitrary string + * @returns {number|null} number or null if string not parsable */ export const getNumberFromString = (rawString) => { const parsedDelay = parseInt(rawString, 10); @@ -38,9 +41,10 @@ export const getNumberFromString = (rawString) => { /** * Generate a random integer between two values, inclusive * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_integer_between_two_values_inclusive - * @param {number} min - * @param {number} max - * @returns {number} + * + * @param {number} min range minimum + * @param {number} max range maximum + * @returns {number} random number */ export function getRandomIntInclusive(min, max) { min = Math.ceil(min); diff --git a/src/helpers/object-utils.js b/src/helpers/object-utils.js index 89a7a9b71..d8aa59734 100644 --- a/src/helpers/object-utils.js +++ b/src/helpers/object-utils.js @@ -2,7 +2,8 @@ * Converts object to array of pairs. * Object.entries() polyfill because it is not supported by IE * https://caniuse.com/?search=Object.entries - * @param {Object} object + * + * @param {Object} object arbitrary object * @returns {Array} array of pairs */ export const getObjectEntries = (object) => { @@ -16,8 +17,9 @@ export const getObjectEntries = (object) => { * Converts array of pairs to object. * Object.fromEntries() polyfill because it is not supported by IE * https://caniuse.com/?search=Object.fromEntries + * * @param {Array} entries - array of pairs - * @returns {Object} + * @returns {Object} result object */ export const getObjectFromEntries = (entries) => { const output = entries @@ -32,16 +34,18 @@ export const getObjectFromEntries = (entries) => { /** * Checks whether the obj is an empty object - * @param {Object} obj - * @returns {boolean} + * + * @param {Object} obj arbitrary object + * @returns {boolean} if object is empty */ export const isEmptyObject = (obj) => Object.keys(obj).length === 0 && !obj.prototype; /** - * Checks whether the obj is an empty object - * @param {Object} obj - * @param {string} prop - * @returns {Object|null} + * Safely retrieve property descriptor + * + * @param {Object} obj target object + * @param {string} prop target property + * @returns {object|null} descriptor or null if it's not available or non-configurable */ export const safeGetDescriptor = (obj, prop) => { const descriptor = Object.getOwnPropertyDescriptor(obj, prop); @@ -53,9 +57,10 @@ export const safeGetDescriptor = (obj, prop) => { /** * Set getter and setter to property if it's configurable + * * @param {Object} object target object with property * @param {string} property property name - * @param {PropertyDescriptor} descriptor contains getter and setter functions + * @param {Object} descriptor contains getter and setter functions * @returns {boolean} is operation successful */ export function setPropertyAccess(object, property, descriptor) { diff --git a/src/helpers/observer.js b/src/helpers/observer.js index a8f4d1292..fea1dc9a2 100644 --- a/src/helpers/observer.js +++ b/src/helpers/observer.js @@ -2,8 +2,10 @@ import { throttle } from './throttle'; /** * DOM tree changes observer. Used for 'remove-attr' and 'remove-class' scriptlets - * @param {Function} callback - * @param {boolean} observeAttrs - optional parameter - should observer check attributes changes + * + * @param {Function} callback function to call on each mutation + * @param {boolean} [observeAttrs] if observer should observe attributes changes + * @param {Array} [attrsToObserve] list of attributes to observe */ export const observeDOMChanges = (callback, observeAttrs = false, attrsToObserve = []) => { /** @@ -35,6 +37,11 @@ export const observeDOMChanges = (callback, observeAttrs = false, attrsToObserve const disconnect = () => { observer.disconnect(); }; + + /** + * Callback wrapper to prevent loops + * when callback tinkers with attributes + */ function callbackWrapper() { disconnect(); callback(); diff --git a/src/helpers/open-shadow-dom-utils.js b/src/helpers/open-shadow-dom-utils.js index 8793a2fb3..83797a9aa 100644 --- a/src/helpers/open-shadow-dom-utils.js +++ b/src/helpers/open-shadow-dom-utils.js @@ -2,7 +2,8 @@ import { flatten } from './array-utils'; /** * Finds shadow-dom host (elements with shadowRoot property) in DOM of rootElement. - * @param {HTMLElement} rootElement + * + * @param {HTMLElement} rootElement shadow dom root * @returns {HTMLElement[]} shadow-dom hosts */ export const findHostElements = (rootElement) => { @@ -37,9 +38,10 @@ export const findHostElements = (rootElement) => { * Pierces open shadow-dom in order to find: * - elements by 'selector' matching * - inner shadow-dom hosts - * @param {string} selector - * @param {HTMLElement[]|external:NodeList} hostElements - * @returns {PierceData} + * + * @param {string} selector DOM elements selector + * @param {HTMLElement[]|external:NodeList} hostElements shadow-dom hosts + * @returns {PierceData} object with found elements and shadow-dom hosts */ export const pierceShadowDom = (selector, hostElements) => { let targets = []; diff --git a/src/helpers/parse-flags.js b/src/helpers/parse-flags.js index d28226f5b..5c679f1ad 100644 --- a/src/helpers/parse-flags.js +++ b/src/helpers/parse-flags.js @@ -1,7 +1,17 @@ +/** + * @typedef {Object} FlagsData object that holds info about valid flags + * and provides method for easy access + * @property {string} ASAP asap flag string + * @property {string} COMPLETE complete flag string + * @property {string} STAY stay flag string + * @property {Function} hasFlag to check if given flag is present + */ + /** * Behaviour flags string parser + * * @param {string} flags required, 'applying' argument string - * @return {Object} + * @returns {FlagsData} object with parsed flags */ export const parseFlags = (flags) => { const FLAGS_DIVIDER = ' '; diff --git a/src/helpers/parse-keyword-value.js b/src/helpers/parse-keyword-value.js index 3e0ee5575..e7faecf9a 100644 --- a/src/helpers/parse-keyword-value.js +++ b/src/helpers/parse-keyword-value.js @@ -6,8 +6,8 @@ * - '$now$' - returns current time in ms, e.g 1667915146503 * - '$currentDate$' - returns current date e.g 'Tue Nov 08 2022 13:53:19 GMT+0300' * - * @param {string} rawValue - * @returns {string} + * @param {string} rawValue keyword + * @returns {string} parsed value */ export const parseKeywordValue = (rawValue) => { const NOW_VALUE_KEYWORD = '$now$'; diff --git a/src/helpers/parse-rule.js b/src/helpers/parse-rule.js index 3ca15544f..809a88102 100644 --- a/src/helpers/parse-rule.js +++ b/src/helpers/parse-rule.js @@ -1,9 +1,11 @@ /** * Iterate over iterable argument and evaluate current state with transitions - * @param {string} init first transition name - * @param {Array|Collection|string} iterable + * + * @param {Array|string} iterable rule or list or rules * @param {Object} transitions transtion functions + * @param {string} init first transition name * @param {any} args arguments which should be passed to transition functions + * @returns {string} state */ function iterateWithTransitions(iterable, transitions, init, args) { let state = init || Object.keys(transitions)[0]; @@ -20,6 +22,8 @@ export const ADG_SCRIPTLET_MASK = '#//scriptlet'; /** * Helper to accumulate an array of strings char by char + * + * @returns {Object} object with helper methods */ const wordSaver = () => { let str = ''; @@ -47,8 +51,10 @@ const substringAfter = (str, separator) => { /** * Parse and validate scriptlet rule - * @param {*} ruleText - * @returns {{name: string, args: Array}} + * + * @param {string} ruleText rule string + * @returns {{name: string, args: Array}} parsed rule + * @throws */ export const parseRule = (ruleText) => { ruleText = substringAfter(ruleText, ADG_SCRIPTLET_MASK); @@ -63,10 +69,13 @@ export const parseRule = (ruleText) => { /** * Transition function: the current index position in start, end or between params - * @param {string} rule - * @param {number} index - * @param {Object} Object - * @property {Object} Object.sep contains prop symb with current separator char + * + * @param {string} rule rule string + * @param {number} index index + * @param {Object} Object helper object + * @param {Object} Object.sep contains prop symb with current separator char + * @throws {string} throws if given rule is not a scriptlet + * @returns {string} transition */ const opened = (rule, index, { sep }) => { const char = rule[index]; @@ -99,11 +108,13 @@ export const parseRule = (ruleText) => { }; /** * Transition function: the current index position inside param - * @param {string} rule - * @param {number} index - * @param {Object} Object - * @property {Object} Object.sep contains prop `symb` with current separator char - * @property {Object} Object.saver helper which allow to save strings by car by char + * + * @param {string} rule rule string + * @param {number} index index + * @param {Object} Object helper object + * @param {Object} Object.sep contains prop `symb` with current separator char + * @param {Object} Object.saver helper which allow to save strings by car by char + * @returns {void} */ const param = (rule, index, { saver, sep }) => { const char = rule[index]; diff --git a/src/helpers/prevent-utils.js b/src/helpers/prevent-utils.js index e93270800..d08d3a1d9 100644 --- a/src/helpers/prevent-utils.js +++ b/src/helpers/prevent-utils.js @@ -8,8 +8,9 @@ import { nativeIsNaN } from './number-utils'; /** * Checks whether the passed arg is proper callback - * @param {*} callback - * @returns {boolean} + * + * @param {any} callback arbitrary callback + * @returns {boolean} if callback is valid */ export const isValidCallback = (callback) => { return callback instanceof Function @@ -23,7 +24,8 @@ export const isValidCallback = (callback) => { * Parses delay argument of setTimeout / setInterval methods into * rounded down number for number/string values or passes on for other types. * Needed for prevent-setTimeout and prevent-setInterval - * @param {any} delay + * + * @param {any} delay native method delay arg * @returns {any} number as parsed delay or any input type if `delay` is not parsable */ export const parseRawDelay = (delay) => { @@ -35,8 +37,13 @@ export const parseRawDelay = (delay) => { * Checks whether 'callback' and 'delay' are matching * by given parameters 'matchCallback' and 'matchDelay'. * Used for prevent-setTimeout and prevent-setInterval. - * @param {Object} { callback, delay, matchCallback, matchDelay } - * @returns {boolean} + * + * @param {Object} preventData set of data to determine if scriptlet should match + * @param {Function} preventData.callback method's callback arg + * @param {any} preventData.delay method's delay arg + * @param {string} preventData.matchCallback scriptlets's callback arg + * @param {string} preventData.matchDelay scriptlets's delay arg + * @returns {boolean} if scriptlet should match */ export const isPreventionNeeded = ({ callback, diff --git a/src/helpers/random-id.js b/src/helpers/random-id.js index 288d7339a..291e634c7 100644 --- a/src/helpers/random-id.js +++ b/src/helpers/random-id.js @@ -1,5 +1,7 @@ /** * Generate random seven symbols id + * + * @returns {string} randomized id */ export function randomId() { return Math.random().toString(36).slice(2, 9); diff --git a/src/helpers/request-utils.js b/src/helpers/request-utils.js index 777892e92..240d34d10 100644 --- a/src/helpers/request-utils.js +++ b/src/helpers/request-utils.js @@ -4,7 +4,8 @@ import { getObjectFromEntries } from './object-utils'; /** * Returns array of request props that are supported by fetch/xhr scriptlets. * Includes common 'url' and 'method' props and all other fetch-specific props - * @returns {string[]} + * + * @returns {string[]} list of request props */ export const getRequestProps = () => [ 'url', @@ -24,7 +25,8 @@ export const getRequestProps = () => [ /** * Collects Request options to object - * @param {Request} request + * + * @param {Request} request Request instance to collect properties from * @returns {Object} data object */ export const getRequestData = (request) => { @@ -40,7 +42,8 @@ export const getRequestData = (request) => { /** * Collects fetch args to object - * @param {*} args fetch args + * + * @param {any} args fetch args * @returns {Object} data object */ export const getFetchData = (args) => { @@ -70,12 +73,13 @@ export const getFetchData = (args) => { /** * Collect xhr.open arguments to object - * @param {string} method - * @param {string} url - * @param {string} async - * @param {string} user - * @param {string} password - * @returns {Object} + * + * @param {string} method request method + * @param {string} url request url + * @param {string} async request async prop + * @param {string} user request user prop + * @param {string} password request password prop + * @returns {Object} aggregated request data */ export const getXhrData = (method, url, async, user, password) => { return { @@ -90,7 +94,8 @@ export const getXhrData = (method, url, async, user, password) => { /** * Parse propsToMatch input string into object; * used for prevent-fetch and prevent-xhr - * @param {string} propsToMatchStr + * + * @param {string} propsToMatchStr string of space-separated request properties to match * @returns {Object} object where 'key' is prop name and 'value' is prop value */ export const parseMatchProps = (propsToMatchStr) => { @@ -123,8 +128,9 @@ export const parseMatchProps = (propsToMatchStr) => { /** * Validates parsed data values - * @param {Object} data - * @returns {boolean} + * + * @param {Object} data request data + * @returns {boolean} if data is valid */ export const validateParsedData = (data) => { return Object.values(data) @@ -133,8 +139,9 @@ export const validateParsedData = (data) => { /** * Converts valid parsed data to data obj for further matching - * @param {Object} data - * @returns {Object} + * + * @param {Object} data parsed request data + * @returns {Object} data obj ready for matching */ export const getMatchPropsData = (data) => { const matchData = {}; diff --git a/src/helpers/script-source-utils.js b/src/helpers/script-source-utils.js index 740659da8..c3ff4078a 100644 --- a/src/helpers/script-source-utils.js +++ b/src/helpers/script-source-utils.js @@ -4,9 +4,10 @@ import { startsWith } from './string-utils'; * Determines if type of script is inline or injected * and when it's one of them then return true, otherwise false * https://github.com/AdguardTeam/Scriptlets/issues/201 + * * @param {string|undefined} stackMatch - input stack value to match * @param {string} stackTrace - script error stack trace - * @returns {boolean} + * @returns {boolean} if stacks match */ export const shouldAbortInlineOrInjectedScript = (stackMatch, stackTrace) => { const INLINE_SCRIPT_STRING = 'inlineScript'; diff --git a/src/helpers/storage-utils.js b/src/helpers/storage-utils.js index 9865a6358..acdb3e361 100644 --- a/src/helpers/storage-utils.js +++ b/src/helpers/storage-utils.js @@ -1,17 +1,13 @@ import { nativeIsNaN } from './number-utils'; import { logMessage } from './log-message'; -/** - * @typedef { import('../scriptlets/index').Source } Source - */ - /** * Sets item to a specified storage, if storage isn't full. - * @param {Source} source + * + * @param {Object} source scriptlet's configuration * @param {Storage} storage storage instance to set item into - * @param {string} key - * @param {string} value - * @param {boolean} shouldLog determines if helper should log on a failed set attempt + * @param {string} key storage key + * @param {string} value staroge value */ export const setStorageItem = (source, storage, key, value) => { // setItem() may throw an exception if the storage is full. @@ -25,6 +21,7 @@ export const setStorageItem = (source, storage, key, value) => { /** * Gets supported storage item value + * * @param {string} value input item value * @returns {string|null|undefined|boolean} valid item value if ok OR null if not */ diff --git a/src/helpers/string-utils.js b/src/helpers/string-utils.js index 892ef3c48..2763bd091 100644 --- a/src/helpers/string-utils.js +++ b/src/helpers/string-utils.js @@ -8,29 +8,33 @@ import { /** * String.prototype.replaceAll polyfill + * * @param {string} input input string * @param {string} substr to look for * @param {string} newSubstr replacement - * @returns {string} + * @returns {string} result string */ export const replaceAll = (input, substr, newSubstr) => input.split(substr).join(newSubstr); /** * Escapes special chars in string - * @param {string} str - * @returns {string} + * + * @param {string} str raw string + * @returns {string} string with escaped special characters */ export const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); /** * A literal string or regexp pattern wrapped in forward slashes. * For example, 'simpleStr' or '/adblock|_0x/'. + * * @typedef {string} RawStrPattern */ /** * Converts string to the regexp * TODO think about nested dependencies, but be careful with dependency loops + * * @param {RawStrPattern} [input=''] literal string or regexp pattern; defaults to '' (empty string) * @returns {RegExp} regular expression; defaults to /.?/ * @throws {SyntaxError} Throw an error for invalid regex pattern @@ -50,8 +54,9 @@ export const toRegExp = (input = '') => { /** * Checks whether the input string can be converted to regexp + * * @param {RawStrPattern} input literal string or regexp pattern - * @returns {boolean} + * @returns {boolean} if input can be converted to regexp */ export const isValidStrPattern = (input) => { const FORWARD_SLASH = '/'; @@ -72,8 +77,10 @@ export const isValidStrPattern = (input) => { /** * Get string before regexp first match - * @param {string} str - * @param {RegExp} rx + * + * @param {string} str input string + * @param {RegExp} rx find pattern + * @returns {string} result string */ export const getBeforeRegExp = (str, rx) => { const index = str.search(rx); @@ -82,9 +89,10 @@ export const getBeforeRegExp = (str, rx) => { /** * Checks whether the string starts with the substring + * * @param {string} str full string * @param {string} prefix substring - * @returns {boolean} + * @returns {boolean} if string start with the substring */ export const startsWith = (str, prefix) => { // if str === '', (str && false) will return '' @@ -94,9 +102,10 @@ export const startsWith = (str, prefix) => { /** * Checks whether the string ends with the substring + * * @param {string} str full string * @param {string} ending substring - * @returns {boolean} + * @returns {boolean} string ends with the substring */ export const endsWith = (str, ending) => { // if str === '', (str && false) will return '' @@ -122,7 +131,9 @@ export const substringBefore = (str, separator) => { /** * Wrap str in single quotes and replaces single quotes to double one - * @param {string} str + * + * @param {string} str input string + * @returns {string} string with swapped quotes */ export const wrapInSingleQuotes = (str) => { if ((str[0] === '\'' && str[str.length - 1] === '\'') @@ -137,7 +148,9 @@ export const wrapInSingleQuotes = (str) => { /** * Returns substring enclosed in the widest braces - * @param {string} str + * + * @param {string} str input string + * @returns {string} substring */ export const getStringInBraces = (str) => { const firstIndex = str.indexOf('('); @@ -147,9 +160,10 @@ export const getStringInBraces = (str) => { /** * Prepares RTCPeerConnection config as string for proper logging - * @param {*} config + * + * @param {any} config RTC config * @returns {string} stringified config -*/ + */ export const convertRtcConfigToString = (config) => { const UNDEF_STR = 'undefined'; let str = UNDEF_STR; @@ -178,8 +192,9 @@ export const convertRtcConfigToString = (config) => { /** * Checks whether the match input string can be converted to regexp, * used for match inputs with possible negation + * * @param {string} match literal string or regexp pattern - * @returns {boolean} + * @returns {boolean} true if input can be converted to regexp */ export const isValidMatchStr = (match) => { const INVERT_MARKER = '!'; @@ -193,8 +208,9 @@ export const isValidMatchStr = (match) => { /** * Validates the match input number, * used for match inputs with possible negation + * * @param {string} match string of match number - * @returns {boolean} + * @returns {boolean} if match number is valid */ export const isValidMatchNumber = (match) => { const INVERT_MARKER = '!'; @@ -208,16 +224,17 @@ export const isValidMatchNumber = (match) => { /** * @typedef {Object} MatchData - * @property {boolean} isInvertedMatch - * @property {RegExp} matchRegexp + * @property {boolean} isInvertedMatch if matching should be inverted + * @property {RegExp} matchRegexp match value parsed into regex */ /** * Parses match arg with possible negation for no matching. * Needed for prevent-setTimeout, prevent-setInterval, * prevent-requestAnimationFrame and prevent-window-open - * @param {string} match - * @returns {MatchData} + * + * @param {string} match matching arg + * @returns {MatchData} data prepared for matching */ export const parseMatchArg = (match) => { const INVERT_MARKER = '!'; @@ -229,17 +246,16 @@ export const parseMatchArg = (match) => { /** * @typedef {Object} DelayData - * @property {boolean} isInvertedDelayMatch - * @property {number|null} delayMatch + * @property {boolean} isInvertedDelayMatch if matching should be inverted + * @property {number|null} delayMatch parsed delay or null if delay is invalid */ /** * Parses delay arg with possible negation for no matching. * Needed for prevent-setTimeout and prevent-setInterval - * @param {string} delay - * @returns {DelayData} `{ isInvertedDelayMatch, delayMatch }` where: - * `isInvertedDelayMatch` is boolean, - * `delayMatch` is number OR null for invalid `delay` + * + * @param {string} delay scriptlet's delay arg + * @returns {DelayData} parsed delay data */ export const parseDelayArg = (delay) => { const INVERT_MARKER = '!'; @@ -252,8 +268,9 @@ export const parseDelayArg = (delay) => { /** * Converts object to string for logging + * * @param {Object} obj data object - * @returns {string} + * @returns {string} object's string representation */ export const objectToString = (obj) => { return isEmptyObject(obj) @@ -273,8 +290,9 @@ export const objectToString = (obj) => { /** * Converts types into a string - * @param {*} value - * @returns {string} + * + * @param {any} value input value type + * @returns {string} type's string representation */ export const convertTypeToString = (value) => { let output; @@ -295,8 +313,9 @@ export const convertTypeToString = (value) => { /** * Generate a random string, a length of the string is provided as an argument - * @param {number} length - * @returns {string} + * + * @param {number} length output's length + * @returns {string} random string */ export function getRandomStrByLength(length) { let result = ''; @@ -310,7 +329,8 @@ export function getRandomStrByLength(length) { /** * Generate a random string - * @param {string} customResponseText + * + * @param {string} customResponseText response text to include in output * @returns {string|null} random string or null if passed argument is invalid */ export function generateRandomResponse(customResponseText) { diff --git a/src/helpers/throttle.js b/src/helpers/throttle.js index 45537d12d..419c39ea0 100644 --- a/src/helpers/throttle.js +++ b/src/helpers/throttle.js @@ -1,8 +1,10 @@ /** * Returns a wrapper, passing the call to 'method' at maximum once per 'delay' milliseconds. * Those calls that fall into the "cooldown" period, are ignored - * @param {Function} method - * @param {Number} delay - milliseconds + * + * @param {Function} cb callback + * @param {number} delay - milliseconds + * @returns {Function} throttled callback */ export const throttle = (cb, delay) => { let wait = false; diff --git a/src/helpers/validator.js b/src/helpers/validator.js index e2faf4896..30235b5fe 100644 --- a/src/helpers/validator.js +++ b/src/helpers/validator.js @@ -18,8 +18,9 @@ const COMMENT_MARKER = '!'; /** * Checks if rule text is comment e.g. !!example.org##+js(set-constant.js, test, false) - * @param {string} rule - * @return {boolean} + * + * @param {string} rule rule text + * @returns {boolean} if rule text is comment */ const isComment = (rule) => startsWith(rule, COMMENT_MARKER); @@ -51,7 +52,9 @@ const ADG_CSS_MASK_REG = /#@?\$#.+?\s*\{.*\}\s*$/g; /** * Checks if the `rule` is AdGuard scriptlet rule + * * @param {string} rule - rule text + * @returns {boolean} if given rule is adg rule */ const isAdgScriptletRule = (rule) => { return ( @@ -62,7 +65,9 @@ const isAdgScriptletRule = (rule) => { /** * Checks if the `rule` is uBO scriptlet rule + * * @param {string} rule rule text + * @returns {boolean} if given rule is ubo rule */ const isUboScriptletRule = (rule) => { return ( @@ -77,7 +82,9 @@ const isUboScriptletRule = (rule) => { /** * Checks if the `rule` is AdBlock Plus snippet + * * @param {string} rule rule text + * @returns {boolean} if given rule is abp rule */ const isAbpSnippetRule = (rule) => { return ( @@ -90,7 +97,9 @@ const isAbpSnippetRule = (rule) => { /** * Finds scriptlet by it's name + * * @param {string} name - scriptlet name + * @returns {Function} scriptlet function */ const getScriptletByName = (name) => { const scriptlets = Object.keys(scriptletsList).map((key) => scriptletsList[key]); @@ -107,7 +116,9 @@ const getScriptletByName = (name) => { /** * Checks if the scriptlet name is valid + * * @param {string} name - Scriptlet name + * @returns {boolean} if the scriptlet name is valid */ const isValidScriptletName = (name) => { if (!name) { @@ -260,14 +271,16 @@ const REDIRECT_RULE_TYPES = { /** * Parses redirect rule modifiers - * @param {string} rule - * @returns {Array} + * + * @param {string} rule rule text + * @returns {Array} list of rule modifiers */ const parseModifiers = (rule) => substringAfter(rule, '$').split(','); /** * Gets redirect resource name - * @param {string} rule + * + * @param {string} rule rule text * @param {string} marker - specific Adg/Ubo or Abp redirect resources marker * @returns {string} - redirect resource name */ @@ -281,7 +294,9 @@ const getRedirectName = (rule, marker) => { /** * Checks if the `rule` is AdGuard redirect rule. * Discards comments and JS rules and checks if the `rule` has 'redirect' modifier. + * * @param {string} rule - rule text + * @returns {boolean} if given rule is adg redirect */ const isAdgRedirectRule = (rule) => { const MARKER_IN_BASE_PART_MASK = '/((?!\\$|\\,).{1})redirect((-rule)?)=(.{0,}?)\\$(popup)?/'; @@ -300,8 +315,10 @@ const isAdgRedirectRule = (rule) => { /** * Checks if the `rule` satisfies the `type` + * * @param {string} rule - rule text * @param {'VALID_ADG'|'ADG'|'UBO'|'ABP'} type - type of a redirect rule + * @returns {boolean} if the `rule` satisfies the `type` */ const isRedirectRuleByType = (rule, type) => { const { @@ -340,37 +357,41 @@ const isRedirectRuleByType = (rule, type) => { }; /** -* Checks if the `rule` is **valid** AdGuard redirect resource rule -* @param {string} rule - rule text -* @returns {boolean} -*/ + * Checks if the `rule` is **valid** AdGuard redirect resource rule + * + * @param {string} rule - rule text + * @returns {boolean} if given rule is valid adg redirect + */ const isValidAdgRedirectRule = (rule) => { return isRedirectRuleByType(rule, 'VALID_ADG'); }; /** -* Checks if the AdGuard redirect `rule` has Ubo analog. Needed for Adg->Ubo conversion -* @param {string} rule - AdGuard rule text -* @returns {boolean} - true if the rule can be converted to Ubo -*/ + * Checks if the AdGuard redirect `rule` has Ubo analog. Needed for Adg->Ubo conversion + * + * @param {string} rule - AdGuard rule text + * @returns {boolean} - true if the rule can be converted to Ubo + */ const isAdgRedirectCompatibleWithUbo = (rule) => { return isAdgRedirectRule(rule) && isRedirectRuleByType(rule, 'ADG'); }; /** -* Checks if the Ubo redirect `rule` has AdGuard analog. Needed for Ubo->Adg conversion -* @param {string} rule - Ubo rule text -* @returns {boolean} - true if the rule can be converted to AdGuard -*/ + * Checks if the Ubo redirect `rule` has AdGuard analog. Needed for Ubo->Adg conversion + * + * @param {string} rule - Ubo rule text + * @returns {boolean} - true if the rule can be converted to AdGuard + */ const isUboRedirectCompatibleWithAdg = (rule) => { return isRedirectRuleByType(rule, 'UBO'); }; /** -* Checks if the Abp redirect `rule` has AdGuard analog. Needed for Abp->Adg conversion -* @param {string} rule - Abp rule text -* @returns {boolean} - true if the rule can be converted to AdGuard -*/ + * Checks if the Abp redirect `rule` has AdGuard analog. Needed for Abp->Adg conversion + * + * @param {string} rule - Abp rule text + * @returns {boolean} - true if the rule can be converted to AdGuard + */ const isAbpRedirectCompatibleWithAdg = (rule) => { return isRedirectRuleByType(rule, 'ABP'); }; @@ -388,8 +409,8 @@ const isAbpRedirectCompatibleWithAdg = (rule) => { * $script,redirect=noopvast-2.0 * $xmlhttprequest,redirect=noopvast-2.0 * - * @param {string} rule - * @returns {boolean} + * @param {string} rule rule text + * @returns {boolean} if the rule has specified content type before conversion */ const hasValidContentType = (rule) => { const ruleModifiers = parseModifiers(rule); diff --git a/src/redirects/amazon-apstag.js b/src/redirects/amazon-apstag.js index 5c3847728..959dca690 100644 --- a/src/redirects/amazon-apstag.js +++ b/src/redirects/amazon-apstag.js @@ -2,7 +2,6 @@ import { hit, noopFunc } from '../helpers/index'; /** * @redirect amazon-apstag - * * @description * Mocks Amazon's apstag.js * diff --git a/src/redirects/ati-smarttag.js b/src/redirects/ati-smarttag.js index 034613134..e4de22a17 100644 --- a/src/redirects/ati-smarttag.js +++ b/src/redirects/ati-smarttag.js @@ -2,7 +2,6 @@ import { hit, noopFunc } from '../helpers/index'; /** * @redirect ati-smarttag - * * @description * Mocks AT Internat SmartTag. * https://developers.atinternet-solutions.com/as2-tagging-en/javascript-en/getting-started-javascript-en/tracker-initialisation-javascript-en/ diff --git a/src/redirects/blocking-redirects/click2load.js b/src/redirects/blocking-redirects/click2load.js index 8bff8d06a..e0f19f7b5 100644 --- a/src/redirects/blocking-redirects/click2load.js +++ b/src/redirects/blocking-redirects/click2load.js @@ -27,6 +27,7 @@ function clickToLoad() { * Some browsers does not support URL.searchParams.get() * but we need script run with no error * because frame will be shown anyway if click2load redirect rule used + * * @param {string} rawQueryStr * @returns {Object} key is parameter name and value is parameter value */ @@ -123,6 +124,7 @@ function clickToLoad() { /** * Returns translations data for navigator.language * or 'en' if navigator.language is not supported + * * @returns {Object} data for one locale with 'title' and 'button' keys */ const getTranslations = () => { @@ -150,6 +152,7 @@ function clickToLoad() { /** * Prepares frame url to replace on button click + * * @param {string} originUrl passed origin frame url * @param {string} unblockTokenName param name for further validation * @param {string} unblockTokenValue param value for further validation @@ -215,6 +218,7 @@ function clickToLoad() { /** * Checks whether the rule has 'frame' or 'subdocument' modifier + * * @param {string} rule blocking rules passed into redirect * @returns {boolean} */ @@ -231,6 +235,7 @@ function clickToLoad() { }; /** * Checks whether script runs inside a frame + * * @returns {boolean} */ const isInsideFrame = () => window.self !== window.top; diff --git a/src/redirects/didomi-loader.js b/src/redirects/didomi-loader.js index ba364b461..06b28f13f 100644 --- a/src/redirects/didomi-loader.js +++ b/src/redirects/didomi-loader.js @@ -9,7 +9,6 @@ import { /** * @redirect didomi-loader - * * @description * Mocks Didomi's CMP loader script. * https://developers.didomi.io/ diff --git a/src/redirects/fingerprintjs2.js b/src/redirects/fingerprintjs2.js index 9e93f9d85..a3f04a8d8 100644 --- a/src/redirects/fingerprintjs2.js +++ b/src/redirects/fingerprintjs2.js @@ -3,7 +3,6 @@ import { hit } from '../helpers/index'; /** * @redirect fingerprintjs2 - * * @description * Mocks FingerprintJS v2 * https://github.com/fingerprintjs diff --git a/src/redirects/fingerprintjs3.js b/src/redirects/fingerprintjs3.js index 6f08ca5fb..af1d22b5f 100644 --- a/src/redirects/fingerprintjs3.js +++ b/src/redirects/fingerprintjs3.js @@ -6,7 +6,6 @@ import { /** * @redirect fingerprintjs3 - * * @description * Mocks FingerprintJS v3 * https://github.com/fingerprintjs diff --git a/src/redirects/gemius.js b/src/redirects/gemius.js index 8059a203e..cfaf62849 100644 --- a/src/redirects/gemius.js +++ b/src/redirects/gemius.js @@ -3,7 +3,6 @@ import { hit, noopFunc } from '../helpers/index'; /** * @redirect gemius - * * @description * Mocks Gemius Analytics. * https://flowplayer.com/developers/plugins/gemius diff --git a/src/redirects/google-analytics-ga.js b/src/redirects/google-analytics-ga.js index 559dc542d..9e86a66b9 100644 --- a/src/redirects/google-analytics-ga.js +++ b/src/redirects/google-analytics-ga.js @@ -7,7 +7,6 @@ import { /** * @redirect google-analytics-ga - * * @description * Mocks old Google Analytics API. * diff --git a/src/redirects/google-analytics.js b/src/redirects/google-analytics.js index 4744cea02..e42214d96 100644 --- a/src/redirects/google-analytics.js +++ b/src/redirects/google-analytics.js @@ -7,7 +7,6 @@ import { /** * @redirect google-analytics - * * @description * Mocks Google's Analytics and Tag Manager APIs. * [Covers obsolete googletagmanager-gtm redirect functionality](https://github.com/AdguardTeam/Scriptlets/issues/127). @@ -78,9 +77,9 @@ export function GoogleAnalytics(source) { /** * checks data object and delays callback - * @param {Object|Array} data gtag payload + * + * @param {object|Array} dataObj gtag payload * @param {string} funcName callback prop name - * @returns */ const handleCallback = (dataObj, funcName) => { if (dataObj && typeof dataObj[funcName] === 'function') { @@ -111,7 +110,8 @@ export function GoogleAnalytics(source) { } // https://github.com/AdguardTeam/Scriptlets/issues/81 - if (google_optimize instanceof Object && typeof google_optimize.get === 'function') { // eslint-disable-line camelcase + // eslint-disable-next-line camelcase + if (google_optimize instanceof Object && typeof google_optimize.get === 'function') { const googleOptimizeWrapper = { get: noopFunc, }; diff --git a/src/redirects/google-ima3.js b/src/redirects/google-ima3.js index 90b06e1f0..807bbb799 100644 --- a/src/redirects/google-ima3.js +++ b/src/redirects/google-ima3.js @@ -7,7 +7,6 @@ import { /** * @redirect google-ima3 - * * @description * Mocks the IMA SDK of Google. * diff --git a/src/redirects/googlesyndication-adsbygoogle.js b/src/redirects/googlesyndication-adsbygoogle.js index d65b72438..80832f5a4 100644 --- a/src/redirects/googlesyndication-adsbygoogle.js +++ b/src/redirects/googlesyndication-adsbygoogle.js @@ -3,7 +3,6 @@ import { hit } from '../helpers/index'; /* eslint-disable max-len */ /** * @redirect googlesyndication-adsbygoogle - * * @description * Mocks Google AdSense API. * diff --git a/src/redirects/googletagservices-gpt.js b/src/redirects/googletagservices-gpt.js index 6d04c10e5..3dca77a87 100644 --- a/src/redirects/googletagservices-gpt.js +++ b/src/redirects/googletagservices-gpt.js @@ -11,7 +11,6 @@ import { /** * @redirect googletagservices-gpt - * * @description * Mocks Google Publisher Tag API. * diff --git a/src/redirects/index.js b/src/redirects/index.js index bd8a36b62..6b9b82449 100644 --- a/src/redirects/index.js +++ b/src/redirects/index.js @@ -22,7 +22,9 @@ import { redirectsMap } from '../../tmp/redirects-map'; /** * Finds redirect resource by it's name + * * @param {string} name - redirect name + * @returns {Function} */ const getRedirectByName = (name) => { const redirects = Object.keys(redirectsList).map((key) => redirectsList[key]); @@ -40,6 +42,7 @@ const getRedirectByName = (name) => { /** * Returns redirect code by param + * * @param {Source} source * @returns {string} redirect code */ diff --git a/src/redirects/matomo.js b/src/redirects/matomo.js index 244241248..8bcf2f219 100644 --- a/src/redirects/matomo.js +++ b/src/redirects/matomo.js @@ -3,7 +3,6 @@ import { hit, noopFunc } from '../helpers/index'; /** * @redirect matomo - * * @description * Mocks the piwik.js file of Matomo (formerly Piwik). * diff --git a/src/redirects/metrika-yandex-tag.js b/src/redirects/metrika-yandex-tag.js index 068551c3b..a432926b4 100644 --- a/src/redirects/metrika-yandex-tag.js +++ b/src/redirects/metrika-yandex-tag.js @@ -2,7 +2,6 @@ import { hit, noopFunc } from '../helpers/index'; /** * @redirect metrika-yandex-tag - * * @description * Mocks Yandex Metrika API. * https://yandex.ru/support/metrica/objects/method-reference.html @@ -39,6 +38,8 @@ export function metrikaYandexTag(source) { /** * https://yandex.ru/support/metrica/objects/get-client-id.html + * + * @param {string} id * @param {Function} cb */ const getClientID = (id, cb) => { @@ -65,6 +66,8 @@ export function metrikaYandexTag(source) { /** * https://yandex.ru/support/metrica/objects/reachgoal.html + * + * @param {string} id * @param {string} target * @param {Object} params * @param {Function} callback diff --git a/src/redirects/metrika-yandex-watch.js b/src/redirects/metrika-yandex-watch.js index 048ba89b5..f2646de7a 100644 --- a/src/redirects/metrika-yandex-watch.js +++ b/src/redirects/metrika-yandex-watch.js @@ -2,7 +2,6 @@ import { hit, noopFunc, noopArray } from '../helpers/index'; /** * @redirect metrika-yandex-watch - * * @description * Mocks the old Yandex Metrika API. * https://yandex.ru/support/metrica/objects/_method-reference.html @@ -17,6 +16,7 @@ export function metrikaYandexWatch(source) { /** * Gets callback and its context from options and call it in async way + * * @param {Object} options Yandex Metrika API options */ const asyncCallbackFromOptions = (options = {}) => { diff --git a/src/redirects/naver-wcslog.js b/src/redirects/naver-wcslog.js index 8b93b211f..e84f0f118 100644 --- a/src/redirects/naver-wcslog.js +++ b/src/redirects/naver-wcslog.js @@ -3,7 +3,6 @@ import { hit, noopFunc } from '../helpers/index'; /** * @redirect naver-wcslog - * * @description * Mocks wcslog.js of Naver Analytics. * diff --git a/src/redirects/noeval.js b/src/redirects/noeval.js index 7754392af..698f46427 100644 --- a/src/redirects/noeval.js +++ b/src/redirects/noeval.js @@ -2,7 +2,6 @@ import { noeval } from '../scriptlets/noeval'; /** * @redirect noeval - * * @description * Redirects request to the source which sets static properties to PopAds and popns objects. * diff --git a/src/redirects/pardot-1.0.js b/src/redirects/pardot-1.0.js index eb2d312b1..e23f19040 100644 --- a/src/redirects/pardot-1.0.js +++ b/src/redirects/pardot-1.0.js @@ -8,7 +8,6 @@ import { /** * @redirect pardot-1.0 - * * @description * Mocks the pd.js file of Salesforce. * https://pi.pardot.com/pd.js diff --git a/src/redirects/prebid-ads.js b/src/redirects/prebid-ads.js index 18a209bc3..ff4fccc76 100644 --- a/src/redirects/prebid-ads.js +++ b/src/redirects/prebid-ads.js @@ -3,7 +3,6 @@ import { hit } from '../helpers/index'; /** * @redirect prebid-ads - * * @description * Sets predefined constants on a page: * - `canRunAds`: `true` diff --git a/src/redirects/prebid.js b/src/redirects/prebid.js index c5a8198aa..77356c57a 100644 --- a/src/redirects/prebid.js +++ b/src/redirects/prebid.js @@ -8,7 +8,6 @@ import { /** * @redirect prebid - * * @description * Mocks the prebid.js header bidding suit. * https://docs.prebid.org/ diff --git a/src/redirects/prevent-bab.js b/src/redirects/prevent-bab.js index 56f369281..bbf4feeff 100644 --- a/src/redirects/prevent-bab.js +++ b/src/redirects/prevent-bab.js @@ -2,7 +2,6 @@ import { preventBab as preventBabScriptlet } from '../scriptlets/prevent-bab'; /** * @redirect prevent-bab - * * @description * Prevents BlockAdblock script from detecting an ad blocker. * diff --git a/src/redirects/prevent-bab2.js b/src/redirects/prevent-bab2.js index 28fffe721..42dac9b2d 100644 --- a/src/redirects/prevent-bab2.js +++ b/src/redirects/prevent-bab2.js @@ -3,7 +3,6 @@ import { hit } from '../helpers/index'; /** * @redirect prevent-bab2 - * * @description * Prevents BlockAdblock script from detecting an ad blocker. * diff --git a/src/redirects/prevent-fab-3.2.0.js b/src/redirects/prevent-fab-3.2.0.js index 503caf98c..c4973295c 100644 --- a/src/redirects/prevent-fab-3.2.0.js +++ b/src/redirects/prevent-fab-3.2.0.js @@ -2,7 +2,6 @@ import { preventFab } from '../scriptlets/prevent-fab-3.2.0'; /** * @redirect prevent-fab-3.2.0 - * * @description * Redirects fuckadblock script to the source js file. * diff --git a/src/redirects/prevent-popads-net.js b/src/redirects/prevent-popads-net.js index 187b5a3df..b0d2bb54e 100644 --- a/src/redirects/prevent-popads-net.js +++ b/src/redirects/prevent-popads-net.js @@ -2,7 +2,6 @@ import { preventPopadsNet } from '../scriptlets/prevent-popads-net'; /** * @redirect prevent-popads-net - * * @description * Redirects request to the source which sets static properties to PopAds and popns objects. * diff --git a/src/redirects/redirects.js b/src/redirects/redirects.js index 91435155a..5d90c8064 100644 --- a/src/redirects/redirects.js +++ b/src/redirects/redirects.js @@ -9,20 +9,21 @@ import jsYaml from 'js-yaml'; * contentType: image/gif;base64 * content: R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== * } + * * @typedef {Object} Redirect - * @property {string} title - * @property {string} comment - * @property {string} content - * @property {string} contentType - * @property {string} file - * @property {boolean} [isBlocking] - * @property {string} [sha] + * @property {string} title resource name + * @property {string} comment resource description + * @property {string} content encoded resource content + * @property {string} contentType MIME type + * @property {boolean} [isBlocking] e.g click2load redirect + * @property {string} [sha] hash */ class Redirects { /** * Converts rawYaml into JS object with sources titles used as keys - * @param rawYaml + * + * @param {string} rawYaml * @returns {Object} - return object with titles in the keys and RedirectSources * in the values */ @@ -44,8 +45,9 @@ class Redirects { /** * Returns redirect source object + * * @param {string} title - * @return {Redirect|undefined} Found redirect source object, or `undefined` if not found. + * @returns {Redirect|undefined} Found redirect source object, or `undefined` if not found. */ getRedirect(title) { if (Object.prototype.hasOwnProperty.call(this.redirects, title)) { @@ -66,8 +68,9 @@ class Redirects { /** * Checks if redirect is blocking like click2load.html + * * @param {string} title Title of the redirect. - * @returns True if redirect is blocking otherwise returns `false` even if redirect name is + * @returns {boolean} True if redirect is blocking otherwise returns `false` even if redirect name is * unknown. */ isBlocking(title) { diff --git a/src/redirects/scorecardresearch-beacon.js b/src/redirects/scorecardresearch-beacon.js index 318217de1..9900706a2 100644 --- a/src/redirects/scorecardresearch-beacon.js +++ b/src/redirects/scorecardresearch-beacon.js @@ -2,7 +2,6 @@ import { hit } from '../helpers/index'; /** * @redirect scorecardresearch-beacon - * * @description * Mocks Scorecard Research API. * diff --git a/src/redirects/set-popads-dummy.js b/src/redirects/set-popads-dummy.js index 9ccd9bfc8..70af5001c 100644 --- a/src/redirects/set-popads-dummy.js +++ b/src/redirects/set-popads-dummy.js @@ -2,7 +2,6 @@ import { setPopadsDummy } from '../scriptlets/set-popads-dummy'; /** * @redirect set-popads-dummy - * * @description * Redirects request to the source which sets static properties to PopAds and popns objects. * diff --git a/src/scriptlets/abort-current-inline-script.js b/src/scriptlets/abort-current-inline-script.js index 1c17f42e2..c8092c566 100644 --- a/src/scriptlets/abort-current-inline-script.js +++ b/src/scriptlets/abort-current-inline-script.js @@ -16,7 +16,6 @@ import { /* eslint-disable max-len */ /** * @scriptlet abort-current-inline-script - * * @description * Aborts an inline script when it attempts to **read** or **write to** the specified property * AND when the contents of the `