diff --git a/README.ja.md b/README.ja.md index c5301e9..3caa0a2 100644 --- a/README.ja.md +++ b/README.ja.md @@ -18,6 +18,8 @@ tinyShieldスクリプトは、Adblockコミュニティによって管理され ### クイックスタート このユーザースクリプトを検出するには、次のURLをクリックしてください。 +生成されたスクリプトは標準の `@match` を使用します。元データの `.*` パターンは、具体的なドメインも収集されない限り除外されます。 + https://cdn.jsdelivr.net/npm/@filteringdev/tinyshield@latest/dist/tinyShield.user.js ### ドメイングループ購読ガイド (Apple Safari Extension ユーザー専用) diff --git a/README.ko.md b/README.ko.md index 874af75..c6e6a4e 100644 --- a/README.ko.md +++ b/README.ko.md @@ -27,6 +27,8 @@ tinyShield 유저스크립트는 애드블록 커뮤니티에 의해 관리되 ### 빠른 시작 아래 URL를 클릭하여 설치해주세요: +생성된 스크립트는 표준 `@match`를 사용합니다. 원본의 `.*` 패턴은 구체적인 도메인이 함께 수집되지 않으면 제외됩니다. + https://cdn.jsdelivr.net/npm/@filteringdev/tinyshield@latest/dist/tinyShield.user.js ### 도메인 그룹 구독 가이드 (Apple Safari Extension 사용자 전용) @@ -46,6 +48,8 @@ https://cdn.jsdelivr.net/npm/@filteringdev/tinyshield@latest/dist/tinyShield.use 이 도메인 그룹 분리는 https://github.com/FilteringDev/tinyShield/issues/38 의 영향 범위를 가능한 한 최소화하기 위한 목적입니다. +`metadata.json`은 수집된 구체 도메인을 그룹 파일명에 연결합니다. `example.tld` 같은 그룹 이름이 모든 접미사의 실행을 허용하는 것은 아닙니다. 도메인 그룹이 바뀌면 그룹 파일명도 바뀔 수 있습니다. `SHA386`은 대문자 SHA-384 해시입니다. + ### 설치하는 법 Firefox 및 Chromium 기반 브라우저에서는 **Violentmonkey**를, macOS·iOS·iPadOS의 Safari에서는 **wBlock**을 권장합니다. **Tampermonkey는 권장하지 않습니다.** diff --git a/README.md b/README.md index 9caa0f5..23c6ef0 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ If you believe this userscript is causing issues while in use, please use GitHub ### Quick Start Just click the following URL to detect this userscript. +The generated scripts use standard `@match` rules. Source patterns ending in `.*` are excluded unless concrete domains are also collected. + https://cdn.jsdelivr.net/npm/@filteringdev/tinyshield@latest/dist/tinyShield.user.js ### Domain Group Subscription Guide (Apple Safari Extension Only) @@ -46,6 +48,8 @@ https://cdn.jsdelivr.net/npm/@filteringdev/tinyshield@latest/dist/tinyShield.use This domain-group split is intended to reduce the impact scope of https://github.com/FilteringDev/tinyShield/issues/38 as much as possible. +`metadata.json` maps collected concrete domains to group filenames. Generated group names such as `example.tld` do not themselves authorize every suffix. Group filenames may change when the domain groups change. `SHA386` contains the uppercase SHA-384 digest. + ### How to install **Violentmonkey** is recommended for Firefox and Chromium-based browsers. **wBlock** is recommended for Safari on macOS, iOS, and iPadOS. **Tampermonkey is not recommended.** diff --git a/builder/source/banner/index.ts b/builder/source/banner/index.ts index 89cc27a..c4822b0 100644 --- a/builder/source/banner/index.ts +++ b/builder/source/banner/index.ts @@ -14,6 +14,9 @@ export interface BannerOptions { } export function CreateBanner(Options: BannerOptions): string { + const Domains = [...Options.Domains].filter(Domain => !Domain.endsWith('.*')) + if (Domains.length === 0) throw new Error('No concrete domains available for userscript matching.') + let BannerString: string = '// ==UserScript==\n' BannerString += `// @name ${Options.BuildType === 'production' ? Options.Name : Options.Name + ' (Development)'}\n` BannerString += '//\n' @@ -38,7 +41,7 @@ export function CreateBanner(Options: BannerOptions): string { } BannerString += '//\n' - for (const Domain of Options.Domains) { + for (const Domain of Domains) { BannerString += `// @match *://${Domain}/*\n` BannerString += `// @match *://*.${Domain}/*\n` } diff --git a/builder/source/build-grouped.ts b/builder/source/build-grouped.ts index 1e9d5c7..44896ec 100644 --- a/builder/source/build-grouped.ts +++ b/builder/source/build-grouped.ts @@ -17,14 +17,17 @@ export class GroupedBuild extends Build { super(FromOrOption) } - private TransformDomainSetToFileName(DomainSet: Set>): Set> { - const Result = new Set>() - for (const Value of DomainSet) { - const FileNameSet = new Set() - for (const Domain of Value) { - FileNameSet.add(Domain.endsWith('.*') ? Domain.replaceAll(/\.\*$/g, '.tld') : Domain) - } - Result.add(FileNameSet) + private GetGroups(): Map, Set> { + const Groups = this.FetchedDomains.get('Groups') + if (!Groups) throw new Error('Domain groups are not initialized.') + const Result = new Map, Set>() + for (const [Names, Domains] of Groups) { + const MatchingDomains = new Set([...Domains].filter(Domain => !Domain.endsWith('.*'))) + if (MatchingDomains.size === 0) continue + Result.set( + new Set([...Names].map(Domain => Domain.endsWith('.*') ? Domain.slice(0, -2) + '.tld' : Domain)), + MatchingDomains + ) } return Result } @@ -38,12 +41,8 @@ export class GroupedBuild extends Build { FileMapping: {} } - const FileNameList: Set> = this.TransformDomainSetToFileName(new Set>(this.FetchedDomains.get('EachDomain'))) - const MatchingDomains: Set> = new Set>(this.FetchedDomains.get('EachDomainFull')) - - for (let I = 0; I < FileNameList.size; I++) { - const FileName = [...[...FileNameList][I]][0] - const Domains = [...MatchingDomains][I] + for (const [Names, Domains] of this.GetGroups()) { + const FileName = Names.values().next().value! const FilePath = `${this.ProjectRoot}/dist/grouped/${FileName[0]}/tinyShield-${FileName}.user.js` const FileContent = await Fs.promises.readFile(FilePath) const SHA386Hash = Crypto.createHash('sha384').update(FileContent).digest('hex').toUpperCase() @@ -57,6 +56,7 @@ export class GroupedBuild extends Build { } } + await Fs.promises.mkdir(`${this.ProjectRoot}/dist/grouped`, { recursive: true }) await Fs.promises.writeFile(`${this.ProjectRoot}/dist/grouped/metadata.json`, JSON.stringify(MetadataObj, null, 2), 'utf-8') } @@ -67,19 +67,20 @@ export class GroupedBuild extends Build { this.Options.Version ??= (await PackageJson.load(this.ProjectRoot)).content.version ?? '0.0.0' - const FileNameList: Set> = this.TransformDomainSetToFileName(new Set>(this.FetchedDomains.get('EachDomain'))) - const MatchingDomains: Set> = new Set>(this.FetchedDomains.get('EachDomainFull')) - const Workerpool = new Piscina.Piscina({ filename: Path.resolve(this.ProjectRoot, 'builder/source/build-grouped-worker.ts'), - execArgv: [...Process.execArgv, '--import=tsx'], + execArgv: [...Process.execArgv, `--import=${import.meta.resolve('tsx')}`], workerData: { Config: { ...this.Options, SubscriptionUrl: this.Options.SubscriptionUrl.href }, ProjectRoot: this.ProjectRoot } }) - const WorkerResults: Promise[] = [] - for (let I = 0; I < FileNameList.size; I++) { - WorkerResults.push(Workerpool.run({ FileName: [...FileNameList][I], Domains: [...MatchingDomains][I] })) + try { + const WorkerResults: Promise[] = [] + for (const [FileName, Domains] of this.GetGroups()) { + WorkerResults.push(Workerpool.run({ FileName, Domains })) + } + await Promise.all(WorkerResults) + } finally { + await Workerpool.destroy() } - await Promise.all(WorkerResults) } } \ No newline at end of file diff --git a/libs/source/references/index.ts b/libs/source/references/index.ts index cd921ac..a115647 100644 --- a/libs/source/references/index.ts +++ b/libs/source/references/index.ts @@ -3,8 +3,7 @@ import { CustomDefinedMatches, CustomExcludeMatches } from './custom-defined.js' import { FetchAdShieldDomainsFromFiltersLists } from './filterslists.js' import { FetchIABSellersJsonData } from './iabsellers.js' import { DiscardResolvedDupWildcard } from './utils/discard-resolved-dup-wildcard.js' -import { RegroupDomainTldLevel } from './utils/regroup-domain-tldlevel.js' -import { ConvertWildcardSuffixToRegexPattern } from './utils/wildcard-suffix-converter.js' +import { GetDomainRootLabel, RegroupDomainTldLevel } from './utils/regroup-domain-tldlevel.js' export { CustomDefinedMatches, CustomExcludeMatches } from './custom-defined.js' export { FetchAdShieldDomainsFromFiltersLists } from './filterslists.js' @@ -14,31 +13,35 @@ export { IndexAdShieldDomainsFromUBO } from './filterslists/uBO.js' export { AdShieldCDNDomains, IsAdShieldCDNDomain } from './filterslists/keywords.js' export { DiscardResolvedDupWildcard } from './utils/discard-resolved-dup-wildcard.js' export { RegroupDomainTldLevel } from './utils/regroup-domain-tldlevel.js' -export { ConvertWildcardSuffixToRegexPattern, PublicSuffixList } from './utils/wildcard-suffix-converter.js' export type TASDomainContainer = Map<'Normal', Set> & Map<'Full', Set> & Map<'EachDomain', Set>> & - Map<'EachDomainFull', Set>> + Map<'EachDomainFull', Set>> & + Map<'Groups', Map, Set>> -function ConvertToFlatFullDomains(Origin: Set): Set { - return new Set([...Origin].flatMap(Domain => ConvertWildcardSuffixToRegexPattern(Domain))) -} - -function IsGroupedDomains(Origin: Set | Set>): Origin is Set> { - const FirstValue = Origin.values().next().value - return typeof FirstValue !== 'string' && typeof FirstValue !== 'undefined' -} - -function ConvertToFullDomains(Origin: Set): Set -function ConvertToFullDomains(Origin: Set>): Set> -function ConvertToFullDomains(Origin: Set | Set>): Set | Set> { - if (IsGroupedDomains(Origin)) { - return new Set>([...Origin].map(DomainGroup => ConvertToFlatFullDomains(DomainGroup))) +export function CreateDomainViews(Domains: Set): TASDomainContainer { + const FullDomains = new Set([...Domains].sort()) + const NormalDomains = DiscardResolvedDupWildcard(FullDomains) + const EachDomain = RegroupDomainTldLevel(NormalDomains) + const MatchingGroups = new Map>() + for (const Domain of FullDomains) { + const Root = GetDomainRootLabel(Domain) + const Group = MatchingGroups.get(Root) ?? new Set() + Group.add(Domain) + MatchingGroups.set(Root, Group) } - return ConvertToFlatFullDomains(Origin) + const Groups = new Map([...EachDomain].map(Group => [Group, MatchingGroups.get(GetDomainRootLabel(Group.values().next().value!))!] as const)) + const EachDomainFull = new Set(Groups.values()) + const Result: TASDomainContainer = new Map() + Result.set('Normal', NormalDomains) + Result.set('Full', FullDomains) + Result.set('EachDomain', EachDomain) + Result.set('EachDomainFull', EachDomainFull) + Result.set('Groups', Groups) + return Result } export async function FetchAdShieldDomains(): Promise { @@ -54,16 +57,5 @@ export async function FetchAdShieldDomains(): Promise { }) CustomDefinedMatches.forEach(Match => CombinedDomains.add(Match)) CustomExcludeMatches.forEach(Match => CombinedDomains.delete(Match)) - const Result: TASDomainContainer = new Map() - const NormalDomains = DiscardResolvedDupWildcard(CombinedDomains) - const FullDomains = ConvertToFullDomains(NormalDomains) - const EachDomain = RegroupDomainTldLevel(NormalDomains) - const EachDomainFull = ConvertToFullDomains(EachDomain) - - Result.set('Normal', NormalDomains) - Result.set('Full', FullDomains) - Result.set('EachDomain', EachDomain) - Result.set('EachDomainFull', EachDomainFull) - - return Result + return CreateDomainViews(CombinedDomains) } diff --git a/libs/source/references/utils/discard-resolved-dup-wildcard.ts b/libs/source/references/utils/discard-resolved-dup-wildcard.ts index 2595835..82ee6ff 100644 --- a/libs/source/references/utils/discard-resolved-dup-wildcard.ts +++ b/libs/source/references/utils/discard-resolved-dup-wildcard.ts @@ -1,5 +1,4 @@ import * as TLDTS from 'tldts' -import { PublicSuffixList } from './wildcard-suffix-converter.js' type ParsedEntry = { Entry: string @@ -23,9 +22,6 @@ function ParseEntry(Entry: string): ParsedEntry { } const Parsed = TLDTS.parse(Entry) - if (Parsed.publicSuffix) { - PublicSuffixList.add(Parsed.publicSuffix) - } if (Parsed.hostname && Parsed.publicSuffix && Parsed.hostname.endsWith(`.${Parsed.publicSuffix}`)) { return { @@ -48,7 +44,10 @@ function ParseEntry(Entry: string): ParsedEntry { } function IsCoveredByParent(Child: ParsedEntry, Parent: ParsedEntry): boolean { - if (Child.Stem === Parent.Stem || !Child.Stem.endsWith(`.${Parent.Stem}`)) { + if (Child.Stem === Parent.Stem) { + return Parent.WildcardSuffix && !Child.WildcardSuffix + } + if (!Child.Stem.endsWith(`.${Parent.Stem}`)) { return false } @@ -61,23 +60,22 @@ function IsCoveredByParent(Child: ParsedEntry, Parent: ParsedEntry): boolean { export function DiscardResolvedDupWildcard(OriginSet: Set): Set { const ParsedEntries = [...OriginSet].map(ParseEntry) - const RootsWithWildcard = new Set( - ParsedEntries - .filter(Entry => Entry.WildcardSuffix) - .map(Entry => Entry.RootLabel) - ) - const ConcreteStemCounts = new Map() + const ConcreteSuffixes = new Map>() ParsedEntries - .filter(Entry => !Entry.WildcardSuffix) - .forEach(Entry => ConcreteStemCounts.set(Entry.Stem, (ConcreteStemCounts.get(Entry.Stem) ?? 0) + 1)) + .filter(Entry => !Entry.WildcardSuffix && Entry.PublicSuffix) + .forEach(Entry => { + const Suffixes = ConcreteSuffixes.get(Entry.Stem) ?? new Set() + Suffixes.add(Entry.PublicSuffix!) + ConcreteSuffixes.set(Entry.Stem, Suffixes) + }) const NormalizedEntries = ParsedEntries.map(Entry => { if (Entry.WildcardSuffix) { return Entry } - if (RootsWithWildcard.has(Entry.RootLabel) || (ConcreteStemCounts.get(Entry.Stem) ?? 0) >= 2) { + if ((ConcreteSuffixes.get(Entry.Stem)?.size ?? 0) >= 2) { return ParseEntry(`${Entry.Stem}.*`) } diff --git a/libs/source/references/utils/regroup-domain-tldlevel.ts b/libs/source/references/utils/regroup-domain-tldlevel.ts index e6be615..ca0784e 100644 --- a/libs/source/references/utils/regroup-domain-tldlevel.ts +++ b/libs/source/references/utils/regroup-domain-tldlevel.ts @@ -1,5 +1,4 @@ import * as TLDTS from 'tldts' -import { PublicSuffixList } from './wildcard-suffix-converter.js' type ParsedEntry = { Entry: string @@ -23,9 +22,6 @@ function ParseEntry(Entry: string): ParsedEntry { } const Parsed = TLDTS.parse(Entry) - if (Parsed.publicSuffix) { - PublicSuffixList.add(Parsed.publicSuffix) - } if (Parsed.hostname && Parsed.publicSuffix && Parsed.hostname.endsWith(`.${Parsed.publicSuffix}`)) { return { @@ -47,6 +43,10 @@ function ParseEntry(Entry: string): ParsedEntry { } } +export function GetDomainRootLabel(Entry: string): string { + return ParseEntry(Entry).RootLabel +} + function IsCoveredByParent(Child: ParsedEntry, Parent: ParsedEntry): boolean { if (Child.Stem === Parent.Stem || !Child.Stem.endsWith(`.${Parent.Stem}`)) { return false diff --git a/libs/source/references/utils/wildcard-suffix-converter.ts b/libs/source/references/utils/wildcard-suffix-converter.ts deleted file mode 100644 index 0261193..0000000 --- a/libs/source/references/utils/wildcard-suffix-converter.ts +++ /dev/null @@ -1,12 +0,0 @@ -export const PublicSuffixList = new Set([ - 'com', 'org', 'co', 'de', 'ru', 'fr', 'me', 'it', 'nl', 'io', 'cc', 'in', 'pl', 'xyz', 'es', 'se', 'uk', 'tv', 'info', - 'site', 'us', 'online', 'ch', 'at', 'eu', 'top', 'be', 'cz', 'app', 'ca', 'to', 'jp', 'dev', 'kr' -]) - -export function ConvertWildcardSuffixToRegexPattern(Domain: string): string[] { - const Result: string[] = [] - PublicSuffixList.forEach(Suffix => { - Result.push(Domain.replaceAll(/\.\*$/g, '.' + Suffix)) - }) - return Result -} diff --git a/libs/test/references/banner.test.ts b/libs/test/references/banner.test.ts new file mode 100644 index 0000000..f34810b --- /dev/null +++ b/libs/test/references/banner.test.ts @@ -0,0 +1,31 @@ +import { expect, test } from 'vitest' +import { CreateBanner } from '../../../builder/source/banner/index.js' + +test('banner uses match rules only for collected concrete domains', () => { + const Url = new URL('https://example.com/') + const Banner = CreateBanner({ + Version: '1', BuildType: 'production', Domains: new Set(['example.com', 'example.net', 'wild.*']), + Author: 'author', Name: 'name', Namespace: 'namespace', HomepageURL: Url, SupportURL: Url, + UpdateURL: Url, DownloadURL: Url, License: 'license', Description: { en: 'description' } + }) + expect(Banner.match(/^\/\/ @match\s+.*$/gm)).toEqual([ + '// @match *://example.com/*', + '// @match *://*.example.com/*', + '// @match *://example.net/*', + '// @match *://*.example.net/*' + ]) + expect(Banner).not.toContain('@include') + expect(Banner).not.toContain('wild.*') +}) + +test('banner rejects an empty or wildcard-only matching set', () => { + const Url = new URL('https://example.com/') + const Options = { + Version: '1', BuildType: 'production' as const, Domains: new Set(), + Author: 'author', Name: 'name', Namespace: 'namespace', HomepageURL: Url, SupportURL: Url, + UpdateURL: Url, DownloadURL: Url, License: 'license', Description: { en: 'description' } + } + expect(() => CreateBanner(Options)).toThrow('No concrete domains') + Options.Domains.add('wild.*') + expect(() => CreateBanner(Options)).toThrow('No concrete domains') +}) \ No newline at end of file diff --git a/libs/test/references/discard-resolved-dup-wildcard.test.ts b/libs/test/references/discard-resolved-dup-wildcard.test.ts index c032cd3..414acd6 100644 --- a/libs/test/references/discard-resolved-dup-wildcard.test.ts +++ b/libs/test/references/discard-resolved-dup-wildcard.test.ts @@ -30,14 +30,14 @@ test('DiscardResolvedDupWildcard removes resolved duplicate wildcards with multi test('DiscardResolvedDupWildcard handles nested wildcard scenarios', () => { const Input = new Set(['token.google.*', 'access.google.*', 'tools.google.com', 'google.google.co.kr']) - const Expected = new Set(['token.google.*', 'access.google.*', 'tools.google.*', 'google.google.*']) + const Expected = Input return expect(DiscardResolvedDupWildcard(Input)).toEqual(Expected) }) test('DiscardResolvedDupWildcard handles complex wildcard scenarios', () => { const Input = new Set(['token.google.*', 'access.google.*', 'tools.google.com', 'google.google.co.kr', 'example.*', 'example.com', 'rust-lang.org']) - const Expected = new Set(['token.google.*', 'access.google.*', 'tools.google.*', 'google.google.*', 'example.*', 'rust-lang.org']) + const Expected = new Set(['token.google.*', 'access.google.*', 'tools.google.com', 'google.google.co.kr', 'example.*', 'rust-lang.org']) return expect(DiscardResolvedDupWildcard(Input)).toEqual(Expected) }) diff --git a/libs/test/references/domain-views.test.ts b/libs/test/references/domain-views.test.ts new file mode 100644 index 0000000..00d5de5 --- /dev/null +++ b/libs/test/references/domain-views.test.ts @@ -0,0 +1,32 @@ +import { expect, test } from 'vitest' +import { CreateDomainViews } from '@filteringdev/tinyshield-lib/references' + +test('preserves collected domains and explicit wildcards in matching groups', () => { + const Domains = new Set(['example.com', 'other.org', 'example.net', 'sub.example.com', 'wild.*']) + const Views = CreateDomainViews(Domains) + + expect(Views.get('Normal')).toEqual(new Set(['example.*', 'other.org', 'wild.*'])) + expect(Views.get('Full')).toEqual(Domains) + expect([...Views.get('EachDomain')!]).toEqual([ + new Set(['example.*']), new Set(['other.org']), new Set(['wild.*']) + ]) + expect([...Views.get('EachDomainFull')!]).toEqual([ + new Set(['example.com', 'example.net', 'sub.example.com']), new Set(['other.org']), new Set(['wild.*']) + ]) +}) + +test('explicit wildcards and concrete domains remain one group', () => { + const Domains = new Set(['example.*', 'example.com', 'sub.example.net']) + const Views = CreateDomainViews(Domains) + expect(Views.get('Normal')).toEqual(new Set(['example.*'])) + expect([...Views.get('EachDomainFull')!]).toEqual([Domains]) +}) + +test('domain views and group names do not depend on input order', () => { + const Domains = ['z.example.com', 'a.example.com', 'example.net', 'example.com', 'wild.*'] + const Forward = CreateDomainViews(new Set(Domains)) + const Reverse = CreateDomainViews(new Set([...Domains].reverse())) + expect([...Forward.get('Normal')!]).toEqual([...Reverse.get('Normal')!]) + expect([...Forward.get('Groups')!].map(([Names, Matches]) => [[...Names], [...Matches]])) + .toEqual([...Reverse.get('Groups')!].map(([Names, Matches]) => [[...Names], [...Matches]])) +}) \ No newline at end of file diff --git a/libs/test/references/group-metadata.test.ts b/libs/test/references/group-metadata.test.ts new file mode 100644 index 0000000..cf3abda --- /dev/null +++ b/libs/test/references/group-metadata.test.ts @@ -0,0 +1,74 @@ +import { createHash } from 'node:crypto' +import { access, mkdtemp, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, test } from 'vitest' +import { CreateDomainViews } from '@filteringdev/tinyshield-lib/references' +import { GroupedBuild } from '../../../builder/source/build-grouped.js' +import { StandardBuild } from '../../../builder/source/build.js' + +class TestGroupedBuild extends GroupedBuild { + constructor(Root: string, Domains: Set) { + super({ Minify: false, BuildType: 'development', SubscriptionUrl: 'https://example.com/tinyShield.user.js' }) + this.ProjectRoot = Root + this.FetchedDomains = CreateDomainViews(Domains) + } +} + +class TestStandardBuild extends StandardBuild { + constructor(Root: string, Domains: Set) { + super({ Minify: false, BuildType: 'development', SubscriptionUrl: 'https://example.com/tinyShield.user.js', Version: '1' }) + this.ProjectRoot = Root + this.FetchedDomains = CreateDomainViews(Domains) + } +} + +test('group metadata maps collected domains without expanding wildcard suffixes', async () => { + const Root = await mkdtemp(join(tmpdir(), 'tinyshield-group-')) + try { + const Directory = join(Root, 'dist/grouped/e') + await mkdir(Directory, { recursive: true }) + const Content = 'grouped userscript' + await writeFile(join(Directory, 'tinyShield-example.tld.user.js'), Content) + const Builder = new TestGroupedBuild(Root, new Set(['example.*', 'example.com', 'example.net', 'wild.*'])) + await Builder.MakeGroupMetadata() + const Metadata: unknown = JSON.parse(await readFile(join(Root, 'dist/grouped/metadata.json'), 'utf8')) + expect(Metadata).toEqual({ + DomainMapping: { 'example.com': 'example.tld', 'example.net': 'example.tld' }, + FileMapping: { + 'example.tld': { + SHA386: createHash('sha384').update(Content).digest('hex').toUpperCase(), + FileName: 'tinyShield-example.tld.user.js' + } + } + }) + } finally { + await rm(Root, { recursive: true, force: true }) + } +}) + +test('standard and grouped workers build with collected matching rules', async () => { + const Root = await mkdtemp(join(tmpdir(), 'tinyshield-build-')) + try { + await symlink(new URL('../../../builder/', import.meta.url).pathname, join(Root, 'builder'), 'dir') + await symlink(new URL('../../../userscript/', import.meta.url).pathname, join(Root, 'userscript'), 'dir') + await symlink(new URL('../../../package.json', import.meta.url).pathname, join(Root, 'package.json')) + const Domains = new Set(['example.*', 'example.com', 'example.net', 'wild.*']) + await new TestStandardBuild(Root, Domains).Build() + const Builder = new TestGroupedBuild(Root, Domains) + await Builder.Build() + await Builder.MakeGroupMetadata() + const Standard = await readFile(join(Root, 'dist/tinyShield.dev.user.js'), 'utf8') + const Grouped = await readFile(join(Root, 'dist/grouped/e/tinyShield-example.tld.user.js'), 'utf8') + await expect(access(join(Root, 'dist/grouped/w/tinyShield-wild.tld.user.js'))).rejects.toThrow() + for (const Output of [Standard, Grouped]) { + expect(Output).toContain('@match *://*.example.com/*') + expect(Output).toContain('@match *://*.example.net/*') + expect(Output).not.toContain('example.org') + expect(Output).not.toContain('wild.*') + expect(Output).not.toContain('@include') + } + } finally { + await rm(Root, { recursive: true, force: true }) + } +}) \ No newline at end of file