CLAUDE.md - AI Assistant Guide
This document provides essential context for AI assistants working with the adblock-compiler codebase.
Project Overview
AdBlock Compiler is a Compiler-as-a-Service for adblock filter lists. It transforms, optimizes, and combines filter lists from multiple sources with real-time progress tracking.
- Version: 0.7.12
- Runtime: Deno 2.4+ (primary), Node.js compatible, Cloudflare Workers compatible
- Language: TypeScript (strict mode, 100% type-safe)
- License: GPL-3.0
- JSR Package:
@jk-com/adblock-compiler
Quick Commands
# Development
deno task dev # Development with watch mode
deno task compile # Run compiler CLI
# Testing
deno task test # Run all tests
deno task test:watch # Tests in watch mode
deno task test:coverage # Generate coverage reports
# Code Quality
deno task lint # Lint code
deno task fmt # Format code
deno task fmt:check # Check formatting
deno task check # Type check
# Build & Deploy
deno task build # Build standalone executable
deno task wrangler:dev # Run wrangler dev server (port 8787)
deno task wrangler:deploy # Deploy to Cloudflare Workers
# Benchmarks
deno task bench # Run performance benchmarks
Project Structure
src/
├── cli/ # CLI implementation (ArgumentParser, ConfigurationLoader)
├── compiler/ # Core compilation (FilterCompiler, SourceCompiler)
├── configuration/ # Config validation (pure TypeScript, no AJV)
├── transformations/ # 11 rule transformations (see below)
├── downloader/ # Content fetching & preprocessing
├── platform/ # Platform abstraction (Workers, Deno, Node.js)
├── storage/ # Caching & health monitoring
├── filters/ # Rule filtering utilities
├── utils/ # Utilities (RuleUtils, Wildcard, TldUtils, etc.)
├── types/ # TypeScript interfaces (IConfiguration, ISource)
├── index.ts # Library exports
├── mod.ts # Deno module exports
└── cli.deno.ts # Deno CLI entry point
worker/
├── worker.ts # Cloudflare Worker (main API handler)
└── html.ts # HTML templates
public/ # Static web UI assets
examples/ # Example filter list configurations
docs/ # Additional documentation
Architecture Patterns
The codebase uses these key patterns:
- Strategy Pattern: Transformations (SyncTransformation, AsyncTransformation)
- Builder Pattern: TransformationPipeline construction
- Factory Pattern: TransformationRegistry
- Composite Pattern: CompositeFetcher for chaining fetchers
- Adapter Pattern: Platform abstraction layer
Two Compiler Classes
- FilterCompiler (
src/compiler/) - File system-based, for Deno/Node.js CLI - WorkerCompiler (
src/platform/) - Platform-agnostic, for Workers/browsers
Transformation System
11 available transformations applied in order:
ConvertToAscii- Non-ASCII to PunycodeRemoveComments- Remove ! and # comment linesCompress- Hosts to adblock syntax conversionRemoveModifiers- Strip unsupported modifiersValidate- Remove dangerous/incompatible rulesValidateAllowIp- Like Validate but keeps IPsDeduplicate- Remove duplicate rulesInvertAllow- Convert blocks to allow rulesRemoveEmptyLines- Remove blank linesTrimLines- Remove leading/trailing whitespaceInsertFinalNewLine- Add final newline
All transformations extend SyncTransformation or AsyncTransformation base classes in src/transformations/base/.
Code Conventions
Naming
- Classes: PascalCase (
FilterCompiler,RemoveCommentsTransformation) - Functions/methods: camelCase (
executeSync,validate) - Constants: UPPER_SNAKE_CASE (
CACHE_TTL,RATE_LIMIT_MAX_REQUESTS) - Interfaces: I-prefixed (
IConfiguration,ILogger,ISource) - Enums: PascalCase (
TransformationType,SourceType)
File Organization
- Each module in its own directory with
index.tsexports - Tests co-located as
*.test.tsnext to source files - No deeply nested directory structures
TypeScript
- Strict mode enabled (all strict options)
- No implicit any
- Explicit return types on public methods
- Use interfaces over type aliases for object shapes
Error Handling
- Custom error types for specific scenarios
- Validation results over exceptions where possible
- Retry logic with exponential backoff for network operations
Testing
Tests use Deno's native testing framework:
# Run all tests
deno test --allow-read --allow-write --allow-net --allow-env
# Run specific test file
deno test src/utils/RuleUtils.test.ts --allow-read
# Run with coverage
deno task test:coverage
Test file conventions:
- Co-located with source:
FileName.ts->FileName.test.ts - Use
Deno.test()with descriptive names - Mock external dependencies (network, file system)
Configuration Schema
interface IConfiguration {
name: string; // Required
description?: string;
homepage?: string;
license?: string;
version?: string;
sources: ISource[]; // Required, non-empty
transformations?: TransformationType[];
exclusions?: string[]; // Patterns to exclude
inclusions?: string[]; // Patterns to include
}
interface ISource {
source: string; // URL or file path
name?: string;
type?: 'adblock' | 'hosts';
transformations?: TransformationType[];
exclusions?: string[];
inclusions?: string[];
}
Pattern types: plain string (contains), *.wildcard, /regex/
API Endpoints (Worker)
POST /compile- JSON compilation APIPOST /compile/stream- Streaming with SSEPOST /compile/batch- Batch up to 10 listsPOST /compile/async- Queue-based async compilationPOST /compile/batch/async- Queue-based batch compilationGET /metrics- Performance metricsGET /- Interactive web UI
Key Files to Know
| File | Purpose |
|---|---|
src/compiler/FilterCompiler.ts | Main compilation logic |
src/platform/WorkerCompiler.ts | Platform-agnostic compiler |
src/transformations/TransformationRegistry.ts | Transformation management |
src/configuration/ConfigurationValidator.ts | Config validation |
src/downloader/FilterDownloader.ts | Content fetching with retries |
src/types/index.ts | Core type definitions |
worker/worker.ts | Cloudflare Worker API handler |
deno.json | Deno tasks and configuration |
wrangler.toml | Cloudflare Workers config |
Platform Support
The codebase supports multiple runtimes through the platform abstraction layer:
- Deno (primary) - Full file system access
- Node.js - npm-compatible via
package.json - Cloudflare Workers - No file system, HTTP-only
- Web Workers - Browser background threads
Use FilterCompiler for CLI/server environments, WorkerCompiler for edge/browser.
Dependencies
Minimal external dependencies:
@luca/cases(JSR) - String case conversion@std/*(Deno Standard Library) - Core utilitiestldts(npm) - TLD/domain parsingwrangler(dev) - Cloudflare deployment
Common Tasks
Adding a New Transformation
- Create
src/transformations/MyTransformation.ts - Extend
SyncTransformationorAsyncTransformation - Implement
execute(lines: string[]): string[] - Register in
TransformationRegistry.ts - Add to
TransformationTypeenum insrc/types/index.ts - Write co-located tests
Modifying the API
- Edit
worker/worker.ts - Update route handlers
- Test with
deno task wrangler:dev - Deploy with
deno task wrangler:deploy
Adding CLI Options
- Add to
ParsedArgumentsinterface insrc/cli/ArgumentParser.ts - Update
parseArgs()insrc/cli/ArgumentParser.ts(add toboolean,string, orcollectarrays) - Add to
ICliArgsinterface insrc/cli/CliApp.deno.ts - Update
parseArgs()insrc/cli/CliApp.deno.ts - Handle the new flag in
buildTransformations(),createConfig(),readConfig(), orrun()as appropriate - Add the field to
CliArgumentsOutputtype andCliArgumentsSchemainsrc/configuration/schemas.ts - Update
showHelp()in bothArgumentParser.tsandCliApp.deno.ts - Update
docs/usage/CLI.md
CI/CD Pipeline
GitHub Actions workflow (.github/workflows/ci.yml):
- Test: Run all tests with coverage
- Type Check: Full TypeScript validation
- Security: Trivy vulnerability scanning
- JSR Publish: Auto-publish on master push
- Worker Deploy: Deploy to Cloudflare Workers
- Pages Deploy: Deploy static assets
Environment Variables
See .env.example for available options:
PORT- Server port (default: 8787)DENO_DIR- Deno cache directory- Cloudflare bindings configured in
wrangler.toml
Useful Links
- README.md - Full project documentation
- TESTING.md - Testing guide
- docs/api/README.md - API documentation
- docs/EXTENSIBILITY.md - Custom extensions
- CHANGELOG.md - Version history