TSUrlFilter 服务器
这是一个执行AdGuard内容屏蔽规则的TypeScript库.
思想
想法是有一个单一的库,我们可以重复用于以下任务:
- 在 Chrome 和 Firefox 扩展中屏蔽内容( 显然)
- 使用此库来解析规则并转换为 Safari 兼容 内容封禁列表 (见 萨法里守护, (中文(简体) ), IOS 的守护(中文(简体) )
- 使用此库验证和显示过滤列表 (见 过滤器记录, (中文(简体) ), 守护符(中文(简体) )
安装
您可以通过 :
- 雅伦数字 :
yarn add @adguard/tsurlfilter - 国家预防机制数字 :
npm install @adguard/tsurlfilter - 菲律宾数字 :
pnpm install @adguard/tsurlfilter
API 描述
公共财产
TSURLFILTER_VERSION
类型 : string
图书馆版本.
公共课程
发动机
引擎是这个库的主要类. 它代表了已装入规则的过滤功能
工厂
你可以通过工厂制造引擎. 有两种模式:同步和同步.
重要编号: content 输入 EngineFactoryOptions 接受其中之一
一个生字符串或一个 FilterList 举个例子.
如果您提供了字符串, 它会自动被包裹
在一个 FilterList 并转会.
如果你提供 FilterList 实例,您完全控制
以可选方式提供转换数据取代转换进程
页:1 FilterList 建筑师.
说明数字 : tsurlfilter 只支持 AdGuard 过滤语法.
如果您需要从其他语法转换规则
(例如:uBlock Origin, Adblock Plus),使用 FilterList 类
将规则自动转换为 AdGuard 格式
通过 RawRuleConverter.convertToAdg()。 。 。 .
此转换应在过滤列表级别进行
在引擎处理规则之前.
同步模式
创建引擎同步 .
/**
* Creates an instance of the network engine in sync mode.
*
* @param options Engine factory options.
*
* @returns An instance of the network engine.
*/
public static createSync(options: EngineFactoryOptions): Engine;
同步模式
同步创建引擎 。 我们在AdGuard浏览器扩展中使用了这种方法来避免UI的滞后.
/**
* Creates an instance of the network engine in async mode.
*
* @param options Engine factory options.
*
* @returns An instance of the network engine.
*/
public static createAsync(options: EngineFactoryOptions): Promise<Engine>;
示例
const engine = await Engine.createAsync({
filters: [
{
id: 1,
content: '||example.com^',
},
],
});
匹配请求
/**
* Matches the specified request against the filtering engine and returns the matching result.
* In case frameRules parameter is not specified, frame rules will be selected matching request.sourceUrl.
*
* @param request - request to check
* @param frameRules - source rules or undefined
* @returns matching result
*/
matchRequest(request: Request, frameRule: NetworkRule | null = null): MatchingResult;
匹配图像
/**
* Matches current frame and returns document-level allowlist rule if found.
*
* @param frameUrl
*/
matchFrame(frameUrl: string): NetworkRule | null;
启动引擎
import { Engine, setConfiguration } from '@adguard/tsurlfilter';
const rawFilter = [
'[AdGuard]',
'! Title: Example filter',
'! Description: This is just an example filter.',
'example.com##h1',
].join('\n');
const config = {
engine: 'extension',
version: '1.0.0',
verbose: true,
};
setConfiguration(config);
// Create engine using the factory method
const engine = Engine.createSync({
filters: [
{
id: 0,
content: rawFilter,
},
],
});
console.log(`Engine loaded with ${engine.getRulesCount()} rule(s)`);
匹配请求
const request = new Request(url, sourceUrl, RequestType.Document);
const result = engine.matchRequest(request);
获取化妆品数据
const cosmeticResult = engine.getCosmeticResult(request, CosmeticOption.CosmeticOptionAll);
匹配结果
匹配Result包含所有匹配网络请求的规则, 并提供了定义网络请求的方法 应处理
获取基本结果
/**
* GetBasicResult returns a rule that should be applied to the web request.
* Possible outcomes are:
* returns null -- bypass the request.
* returns a allowlist rule -- bypass the request.
* returns a blocking rule -- block the request.
*
* @returns basic result rule
*/
getBasicResult(): NetworkRule | null;
获取文档锁定结果
/**
* Returns a rule that should block a document request.
*
* @returns Document blocking rule if any, null otherwise.
*/
getDocumentBlockingResult(): NetworkRule | null;
获得可选择性
此旗帜应用于 getCosmeticResult(request: Request, option: CosmeticOption)
/**
* Returns a bit-flag with the list of cosmetic options
*
* @returns {CosmeticOption} mask
*/
getCosmeticOption(): CosmeticOption;
其他规则
/**
* Return an array of replace rules
*/
getReplaceRules(): NetworkRule[]
/**
* Returns an array of csp rules
*/
getCspRules(): NetworkRule[]
/**
* Returns an array of cookie rules
*/
getCookieRules(): NetworkRule[]
化妆品
化妆品的结果是代表相匹配的化妆品规则. 它包含以下属性:
/**
* Storage of element hiding rules
*/
public elementHiding: CosmeticStylesResult;
/**
* Storage of CSS rules
*/
public CSS: CosmeticStylesResult;
/**
* Storage of JS rules
*/
public JS: CosmeticScriptsResult;
/**
* Storage of Html filtering rules
*/
public Html: CosmeticHtmlResult;
/**
* Script rules
*/
public getScriptRules(): CosmeticRule[];
应用化妆品结果 - CSS
const css = [...cosmeticResult.elementHiding.generic, ...cosmeticResult.elementHiding.specific]
.map((rule) => `${rule.getContent()} { display: none!important; }`);
const styleText = css.join('\n');
const injectDetails = {
code: styleText,
runAt: 'document_start',
};
chrome.tabs.insertCSS(tabId, injectDetails);
应用化妆品结果 - 脚本
const cosmeticRules = cosmeticResult.getScriptRules();
const scriptsCode = cosmeticRules.map((x) => x.getScript()).join('\r\n');
const toExecute = buildScriptText(scriptsCode);
chrome.tabs.executeScript(tabId, {
code: toExecute,
});
DnsEngine (英语)
DNSEngine结合了主机规则和网络规则,并且应该迅速找到主机名的匹配规则.
构造器
/**
* Builds an instance of dns engine
*
* @param storage
*/
constructor(storage: RuleStorage);
匹配
/**
* Match searches over all filtering and host rules loaded to the engine
*
* @param hostname to check
* @returns dns result object
*/
public match(hostname: string): DnsResult;
匹配主机名
const dnsResult = dnsEngine.match(hostname);
if (dnsResult.basicRule && !dnsResult.basicRule.isAllowlist()) {
// blocking rule found
...
}
if (dnsResult.hostRules.length > 0) {
// hosts rules found
...
}
规则语法Utils
此模块不直接用于引擎, 但可用于其他库
公共方法
/**
* Checks if rule can be matched by domain
*
* @param ruleText Rule text
* @param domain Domain to check
*/
public static isRuleForDomain(ruleText: string, domain: string): boolean
/**
* Checks if rule can be matched by URL
*
* @param ruleText Rule text
* @param url URL to check
*/
public static isRuleForUrl(ruleText: string, url: string): boolean;
过滤列表
FilterList 是代表已转换过滤器列表的类
能够有效访问转换后和原规则内容.
关键特性
- 自动规则转换: 使用 AdGuard 格式转换过滤规则
RawRuleConverter.convertToAdg() - O(1) 访问:通过转换数据提供对原始过滤规则的经常性访问
- 双向绘图: 维持转换规则和原规则之间的映射
- 内容恢复: 从已转换的内容恢复原始过滤列表
构造器
/**
* Creates a new FilterList instance.
*
* @param content Filter list content.
* @param data Optional conversion data. If not provided, the filter list will be prepared.
*/
constructor(content: string, data?: ConversionData)
转换数据结构
这个 ConversionData 界面跟踪已转换规则和原规则之间的关系 :
interface ConversionData {
/**
* Original filter list rules that were converted.
*/
originals: string[];
/**
* Conversion map.
* Maps line start offsets in the converted content to indexes in the originals array.
* Keys are 0-based line start offsets, values are 0-based indexes in originals array.
*/
conversions: Record<number, number>;
}
主要方法
获取转换内容
/**
* Returns the converted content.
*/
public getContent(): string;
获取规则文本
/**
* Returns the rule text for a given offset in the converted content.
* This may be a converted rule.
*
* @param offset Line start offset in the converted content.
* @returns Rule as string, or null if not found.
*/
public getRuleText(offset: number): string | null;
获取原始规则文本
/**
* Returns the original rule text for a given offset.
* If the rule was converted, returns the original from conversion data.
* If not converted, returns the rule text (which is already the original).
*
* @param offset Line start offset in the converted content.
* @returns Original rule text, or null if offset is invalid.
*/
public getOriginalRuleText(offset: number): string | null;
正在转换规则正本( Strict)
/**
* Returns the original rule text only if the rule was actually converted.
* Unlike getOriginalRuleText(), this returns null for unconverted rules.
*
* @param offset Line start offset in the converted content.
* @returns Original rule text if converted, or null if not converted or invalid offset.
*/
public getConvertedRuleOriginal(offset: number): string | null;
恢复原始内容
/**
* Restores the original filter list content from the converted content.
*
* @returns Original filter list content.
*/
public getOriginalContent(): string;
静态方法
/**
* Creates an empty converted filter list.
*/
public static createEmpty(): FilterList;
/**
* Creates an empty conversion data.
*/
public static createEmptyConversionData(): ConversionData;
用法示例
import { FilterList } from '@adguard/tsurlfilter';
// Create a filter list (automatically converts rules)
const filterList = new FilterList('||example.com^$third-party');
// Get converted content
const converted = filterList.getContent();
// Get rule at specific offset
const rule = filterList.getRuleText(0);
// Get original rule if it was converted
const original = filterList.getOriginalRuleText(0);
// Restore full original content
const originalContent = filterList.getOriginalContent();
// Create from existing conversion data (no re-conversion)
const data = filterList.getConversionData();
const filterList2 = new FilterList(converted, data);