@adguard/filters-downloader

中文文档
3.0.1发布于 2026/10/30GPL-3.0TypeScriptCommonJS近 30 天下载 8487

Downloads filter source files

原始使用文档
文档目录18 节
  1. Table of Contents
  2. Overview
  3. Installation
  4. Importing
  5. Key Concepts
  6. Condition constants ( DefinedExpressions )
  7. Preprocessor directives
  8. Checksums
  9. Differential updates
  10. API Reference
  11. download(url, definedExpressions?, options?)
  12. downloadWithRaw(url, options)
  13. compile(rules, filterOrigin?, definedExpressions?)
  14. resolveConditions(rules, definedExpressions?)
  15. resolveIncludes(rules, filterOrigin?, definedExpressions?)
  16. getFilterUrlOrigin(url)
  17. Documentation
  18. Projects using FiltersDownloader

@adguard/filters-downloader

A library that downloads filter list source files by resolving preprocessor directives. It handles conditional compilation, file inclusion, checksum validation, and differential (patch-based) filter updates. The library works in both Node.js and browser environments.

Note: This package is developed in AdGuardSoftwareLimited/ext-filters-downloader. The AdguardTeam/FiltersDownloader repository is a public mirror.

Table of Contents

Overview

Filter lists used by ad blockers are often composed of multiple source files and contain platform-specific rules gated behind preprocessor directives. This library takes a filter URL (or an array of rules) and produces a flat, ready-to-use list of rules by:

  • Resolving !#include directives — fetches and inlines referenced files
  • Resolving !#if/!#else/!#endif directives — includes or excludes rule blocks based on caller-provided condition constants
  • Validating checksums — optionally verifies the MD5 checksum embedded in the filter header
  • Applying differential updates — when a previously downloaded raw filter is supplied, attempts to update it via a binary patch instead of a full re-download

Installation

pnpm add @adguard/filters-downloader
# or
npm install @adguard/filters-downloader
# or
yarn add @adguard/filters-downloader

Importing

Node.js (CommonJS / ESM):

import { FiltersDownloader } from '@adguard/filters-downloader';

Browser (ESM):

import { FiltersDownloader } from '@adguard/filters-downloader/browser';

Key Concepts

Condition constants (DefinedExpressions)

When compiling a filter, you pass a DefinedExpressions object that declares which platform constants are true for the current ad blocker. The library evaluates !#if expressions against these constants and includes only the rules that apply to your platform.

Recognized constants:

ConstantDescription
adguardAdGuard product (any)
adguard_ext_chromiumAdGuard for Chromium-based browsers
adguard_ext_chromium_mv3AdGuard for Chromium MV3
adguard_ext_firefoxAdGuard for Firefox
adguard_ext_edgeAdGuard for Edge
adguard_ext_safariAdGuard for Safari
adguard_ext_operaAdGuard for Opera
adguard_ext_android_cbAdGuard for Android Content Blocker

Any constant not present in the DefinedExpressions object is treated as false. See the AdGuard conditions directive docs for the full list of recognized constants.

Preprocessor directives

Conditional blocks

!#if (adguard && !adguard_ext_safari)
||example.org^$third-party
!#endif
!#if adguard_ext_firefox
!#include https://example.org/path/firefox-rules.txt
!#else
!#include https://example.org/path/other-rules.txt
!#endif
  • !#if / !#else / !#endif delimit conditional blocks.
  • Conditions support &&, ||, !, and parentheses.
  • Only the block whose condition evaluates to true is included in the output.

File inclusion

!
! Valid (same origin, absolute path):
!#include https://example.org/path/includedfile.txt
!
! Valid (relative path):
!#include /includedfile.txt
!#include ../path2/includedfile.txt
!
! Invalid (different origin — rejected):
!#include https://example.com/path/includedfile.txt

!#include fetches the referenced file and splices its rules into the output at that position. Included files may themselves contain directives. Only files from the same origin as the parent filter are permitted.

Checksums

A filter file may embed an MD5 checksum in its header (e.g. ! Checksum: <base64-md5>). When validateChecksum: true is passed, the library verifies the checksum after downloading. Use validateChecksumStrict: true to treat a missing checksum as an error.

Differential updates

downloadWithRaw keeps the raw (uncompiled) filter text alongside the compiled output. On subsequent calls, passing the previously stored rawFilter lets the library apply a binary patch (if the server provides one) instead of downloading the entire filter again, reducing bandwidth usage.

For a source URL that contains credentials, the library always downloads the full filter. Only the Node.js build supports such URLs.

API Reference

All methods are on the FiltersDownloader object.

download(url, definedExpressions?, options?)

Downloads a filter from url, resolves all directives, and returns the compiled rules as a string[].

const rules: string[] = await FiltersDownloader.download(
    'https://example.org/filter.txt',
    { adguard: true, adguard_ext_firefox: true },
);

Options (LegacyDownloadOptions):

OptionTypeDefaultDescription
validateChecksumbooleanfalseVerify the embedded MD5 checksum
validateChecksumStrictbooleanfalseError if no checksum is present
allowEmptyResponsebooleanfalseAllow downloading an empty filter file

By default an empty top-level response throws 'Response is empty'. Included files may be empty regardless of this option.


downloadWithRaw(url, options)

Downloads a filter and returns both the compiled rules and the raw (uncompiled) filter text. On subsequent calls, supply the stored rawFilter so the library can apply a differential patch instead of a full re-download.

// First download — no previous raw filter
const { filter, rawFilter } = await FiltersDownloader.downloadWithRaw(
    'https://example.org/filter.txt',
    { definedExpressions: { adguard: true } },
);

// Store rawFilter and use it next time
const { filter: updated, rawFilter: newRaw, isPatchUpdateFailed } =
    await FiltersDownloader.downloadWithRaw(
        'https://example.org/filter.txt',
        {
            rawFilter,           // previously stored raw filter
            definedExpressions: { adguard: true },
        },
    );

Returns (DownloadResult):

FieldTypeDescription
filterstring[]Compiled rules
rawFilterstringRaw filter text before directive resolution
isPatchUpdateFailedboolean | undefinedtrue if a patch was attempted but failed (full re-download was used instead)
headersobject | undefinedHTTP response headers from the filter download (see below)

headers shape:

FieldTypeDescription
lastModifiedstring | undefinedThe value of the Last-Modified HTTP response header

Note: headers.lastModified can be used as a fallback update timestamp when filter metadata does not contain a TimeUpdated field.

Options (DownloadWithRawOptions):

OptionTypeDefaultDescription
forcebooleanfalseSkip patch attempt and force a full re-download
rawFilterstringundefinedPreviously stored raw filter to diff against
definedExpressionsDefinedExpressionsundefinedCondition constants for directive resolution
validateChecksumbooleanfalseVerify the embedded MD5 checksum
validateChecksumStrictbooleanfalseError if no checksum is present
allowEmptyResponsebooleanfalseAllow an empty filter response
verbosebooleanfalseEnable detailed logging for troubleshooting

compile(rules, filterOrigin?, definedExpressions?)

Resolves all directives in an already-fetched string[] of rules. Useful when you have the raw lines in memory and do not need an HTTP download.

const rawRules = [
    '!#if adguard_ext_firefox',
    '||firefox-only.example.org^',
    '!#endif',
    '||example.org^',
];

const compiled: string[] = await FiltersDownloader.compile(
    rawRules,
    'https://example.org/filter.txt', // used to resolve relative !#include paths
    { adguard_ext_firefox: true },
);
// → ['||firefox-only.example.org^', '||example.org^']

resolveConditions(rules, definedExpressions?)

Evaluates !#if / !#else / !#endif directives and returns a new string[] with non-matching blocks removed. Does not fetch !#include references.

const filtered = FiltersDownloader.resolveConditions(rules, { adguard: true });

resolveIncludes(rules, filterOrigin?, definedExpressions?)

Fetches and inlines all !#include references. Does not evaluate !#if conditions.

const expanded = await FiltersDownloader.resolveIncludes(
    rules,
    'https://example.org/filter.txt',
    { adguard: true },
);

getFilterUrlOrigin(url)

Returns the base directory URL of url (everything up to and including the last /). Used internally to resolve relative !#include paths.

FiltersDownloader.getFilterUrlOrigin('https://example.org/path/filter.txt');
// → 'https://example.org/path'

Documentation

Projects using FiltersDownloader

版本与发布记录

@adguard/filters-downloader 共发布 38 个版本,首次发布于 2021/06/29;过去 12 个月发布了 6 个版本。

版本发布日期距今
3.0.1latest2026/10/308 天前
3.0.02026/10/2711 天前
3.0.0-beta.0beta2026/10/2415 天前
2.4.52026/07/143 个月前
2.4.42026/04/146 个月前
2.4.32026/04/047 个月前

关于 @adguard/filters-downloader 的常见问题

@adguard/filters-downloader 是什么?

Downloads filter source files

如何安装 @adguard/filters-downloader?

在项目目录运行 npm install @adguard/filters-downloader,或使用 pnpm add / yarn add / bun add。

@adguard/filters-downloader 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@adguard/filters-downloader 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@adguard/filters-downloader 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^22.21.0 || >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@adguard/filters-downloader 可以商用吗?

@adguard/filters-downloader 使用 GPL-3.0 许可。强 Copyleft:分发包含该代码的软件时,整个作品需以 GPL-3.0 兼容许可开源,并附带专利与反锁定条款。仅内部使用不触发此义务。以上为概括,不构成法律意见,请以许可原文为准。

@adguard/filters-downloader 的下载量有多少?

根据 npm 官方下载统计,@adguard/filters-downloader 在 2026/10/05 – 2026/11/03 这 30 天内被下载 8,487 次,日均约 283 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adguard/filters-downloader 还在维护吗?

最新版本 3.0.1 发布于 2026/10/30(8 天前);至今共发布 38 个版本,其中过去 12 个月发布了 6 个;首次发布于 2021/06/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。