API Reference
Complete reference for fast-brake pattern detection API
fast-brake provides a simple, powerful API for pattern detection in JavaScript code using a plugin-based architecture.
Installation
npm install fast-brake
# or
yarn add fast-brake
# or
bun add fast-brake
Core Functions
fastBrakeSync(options?) - FASTEST
Creates a synchronous fast-brake instance with no async overhead. This is the fastest way to use fast-brake for performance-critical applications.
import { fastBrakeSync } from 'fast-brake';
// Create sync instance (no plugins)
const fb = fastBrakeSync();
const isCompatible = fb.check('const x = () => {}', { target: 'es5' });
console.log(isCompatible); // false - instant result
// With plugins and extensions
import { es2015Plugin } from 'fast-brake/plugins/es2015';
import { locExtension } from 'fast-brake/extensions/loc';
const fbWithPlugins = fastBrakeSync({
plugins: [es2015Plugin],
extensions: [locExtension]
});
const features = fbWithPlugins.detect('const x = () => {}');
// [{ name: 'arrow_functions', version: 'es2015' }]
Parameters:
options?(FastBrakeOptions):plugins?(Plugin[]): Array of plugins to useextensions?(Extension[]): Array of extensions to use
Returns: FastBrakeSyncAPI with:
detect(code: string): DetectedFeature[]- Detect patterns synchronouslycheck(code: string, options: DetectionOptions): boolean- Check compatibility synchronously
fastBrake(code) or fastBrake(options)
Can be used in two ways:
- Direct detection: Pass code string for quick pattern detection
- Factory pattern: Pass options to create an async instance with custom plugins
import { fastBrake } from 'fast-brake';
// Direct detection
const results = await fastBrake('const x = () => {}');
// [{ name: 'arrow_functions', version: 'es2015' }]
// Factory pattern
const fb = await fastBrake({
plugins: [es2015Plugin],
extensions: [locExtension]
});
const features = await fb.detect('const x = () => {}');
const isCompatible = await fb.check('const x = () => {}', { target: 'es5' });
Parameters:
- When called with
code(string): Code to analyze - When called with
options(FastBrakeOptions):plugins?(Plugin[]): Array of plugins to useextensions?(Extension[]): Array of extensions to use
Returns:
- With code:
Promise<DetectedFeature[]>- Array with detected patterns - With options:
Promise<FastBrakeAPI>with asyncdetect()andcheck()methods
detect(code)
Returns the first detected pattern using the default ES version plugin. Use this for quick pattern analysis.
import { detect } from 'fast-brake';
const code = `
const arrow = () => {};
const template = \`Hello \${name}\`;
class MyClass {
#private = 'secret';
}
`;
const results = await detect(code);
console.log(results);
// [{ name: 'let_const', version: 'es2015' }]
// Note: Only returns the first detected pattern
// 'version' field contains the rule name from the plugin
Parameters:
code(string): Code to analyze
Returns: Promise<DetectedFeature[]> - Array with single detected pattern or empty array
check(code, options)
Returns a boolean indicating if code is compatible with the target rule/version. Works with the default ES version plugin.
import { check } from 'fast-brake';
// Check ES5 compatibility
const isES5Compatible = await check('var x = 10;', { target: 'es5' });
console.log(isES5Compatible); // true
const hasModernPatterns = await check('const x = () => {};', { target: 'es5' });
console.log(hasModernPatterns); // false
// Check ES2015 compatibility
const isES2015Compatible = await check('const x = () => {};', { target: 'es2015' });
console.log(isES2015Compatible); // true
// Use in conditional logic
if (await check(userCode, { target: 'es2018' })) {
console.log('â Code is compatible with es2018 rules');
} else {
console.log('â Code contains patterns beyond es2018');
}
Parameters:
code(string): Code to analyzeoptions(DetectionOptions):target(string): Target rule to check againstorderedRules?(string[]): Optional ordered rules for comparison
Returns: Promise<boolean>
The Detector Class
The Detector class is the core of fast-brake, providing direct control over pattern detection with custom plugins.
import { Detector } from 'fast-brake';
import { esAll } from 'fast-brake/src/plugins/esversion';
import { telemetryPlugin } from 'fast-brake/src/plugins/telemetry';
// Create a detector instance
const detector = new Detector();
// Initialize with default plugin (esversion)
await detector.initialize();
// Or initialize with custom plugin
const customDetector = new Detector();
await customDetector.initialize(telemetryPlugin);
// Detect patterns
const result = detector.detectFast(code);
console.log(result);
// {
// hasMatch: true,
// mode: 'fast',
// firstMatch: {
// name: 'arrow_functions', // Pattern name from plugin
// match: '=>', // Actual matched text
// spec: 'esversion', // Plugin name
// rule: 'es2015', // Rule from plugin
// index: 11 // Position in code
// }
// }
// Check compatibility with rules
const isCompatible = detector.check(code, {
target: 'es5',
orderedRules: ['es2025', 'es2024', 'es2023', 'es2022', 'es2021', 'es2020', 'es2019', 'es2018', 'es2017', 'es2016', 'es2015', 'es5']
});
console.log(isCompatible); // false
// Detect patterns in a file
const fileResult = detector.detectFile('./src/index.js');
Constructor
new Detector()
Methods
initialize(plugin?: Plugin): Initialize the detector with a plugin (defaults to esversion plugin)detectFast(code: string): Perform fast pattern detection, returns DetectionResultdetectDetailed(code: string): Perform detailed detection with more informationdetectBoolean(code: string): Returns boolean indicating if any patterns detecteddetect(code: string, mode?: 'boolean' | 'fast' | 'detailed'): General detection methoddetectFile(filePath: string, mode?: DetectionMode): Detect patterns in a filecheck(code: string, options: DetectionOptions): Check compatibility with target rule
Additional Classes
Scanner
Utility class for scanning files and directories.
import { Scanner } from 'fast-brake';
const scanner = new Scanner();
// Scanner implementation for file system operations
FastBrakeCache
Cache implementation for performance optimization.
import { FastBrakeCache } from 'fast-brake';
const cache = new FastBrakeCache();
// Cache for storing detection results
Type Definitions
DetectedFeature
Represents a detected pattern. Note: The version field contains the rule name from the plugin.
interface DetectedFeature {
name: string; // Pattern name (e.g., 'arrow_functions', 'console_usage')
version: string; // Rule name from plugin (e.g., 'es2015', 'telemetry')
}
DetectionOptions
Configuration options for the check function.
interface DetectionOptions {
target: string; // Target rule to check against
orderedRules?: string[]; // Optional ordered rules for comparison
}
DetectionResult
Result from detector methods.
interface DetectionResult {
hasMatch: boolean;
mode: 'boolean' | 'fast' | 'detailed';
firstMatch?: DetectionMatch;
}
interface DetectionMatch {
name: string; // Pattern name from plugin
match: string; // Actual matched text
spec: string; // Plugin name
rule: string; // Rule from plugin
index?: number; // Position in code
}
Detection Modes
The Detector class supports three detection modes:
Boolean Mode
Returns only true/false for presence of patterns.
const detector = new Detector();
await detector.initialize();
const hasPatterns = detector.detectBoolean(code);
console.log(hasPatterns); // true or false
Fast Mode (Default)
Returns first match with basic information.
const result = detector.detectFast(code);
// or
const result = detector.detect(code, 'fast');
Detailed Mode
Returns first match with additional context.
const result = detector.detectDetailed(code);
// or
const result = detector.detect(code, 'detailed');
Working with Plugins
Plugins define what patterns to detect. Each plugin can detect different types of patterns:
- ES version features (default plugin)
- Telemetry and tracking code
- Custom patterns you define
import { Detector } from 'fast-brake';
import { es2020 } from 'fast-brake/src/plugins/esversion';
import { telemetryPlugin } from 'fast-brake/src/plugins/telemetry';
// Use ES version plugin to detect ECMAScript patterns
const esDetector = new Detector();
await esDetector.initialize(es2020);
const esResult = esDetector.detectFast(code);
// Use telemetry plugin to detect tracking patterns
const telemetryDetector = new Detector();
await telemetryDetector.initialize(telemetryPlugin);
const telemetryResult = telemetryDetector.detectFast(code);
// Create custom plugin for your patterns
const customPlugin = {
name: "my-patterns",
description: "Detects my custom patterns",
spec: {
orderedRules: ["error", "warning", "info"],
matches: {
"console_log": {
rule: "info",
strings: ["console.log"],
patterns: [{ pattern: "console\\.log\\(" }]
}
}
}
};
const customDetector = new Detector();
await customDetector.initialize(customPlugin);
const customResult = customDetector.detectFast(code);
Default Plugin: ES Version Detection
When using the default functions or initializing Detector without a plugin, fast-brake uses the ES version plugin which detects ECMAScript patterns:
ES2015 (ES6) Patterns
| Pattern Name | Text Pattern | Example Code |
|---|---|---|
arrow_functions | => | const fn = () => {} |
template_literals | ` | `Hello ${name}` |
classes | class | class MyClass {} |
let_const | let/const | const x = 10; let y = 20; |
destructuring | [...]/{...} | const [a, b] = arr; const {x} = obj; |
spread_rest | ... | [...arr]; function fn(...args) {} |
for_of | for...of | for (const item of items) {} |
default_params | param = value | function fn(x = 10) {} |
ES2016 Patterns
| Pattern Name | Text Pattern | Example Code |
|---|---|---|
exponentiation | ** | 2 ** 3 |
ES2017 Patterns
| Pattern Name | Text Pattern | Example Code |
|---|---|---|
async_await | async/await | async function fn() { await promise; } |
ES2018 Patterns
| Pattern Name | Text Pattern | Example Code |
|---|---|---|
async_iteration | for await | for await (const item of asyncIterable) {} |
rest_spread_properties | {...obj} | const newObj = {...obj, extra: true}; |
ES2019 Patterns
| Pattern Name | Text Pattern | Example Code |
|---|---|---|
array_flat | .flat()/.flatMap() | arr.flat(); arr.flatMap(fn); |
ES2020 Patterns
| Pattern Name | Text Pattern | Example Code |
|---|---|---|
optional_chaining | ?. | obj?.prop?.method?.() |
nullish_coalescing | ?? | value ?? 'default' |
bigint | 123n | const big = 123n |
promise_allSettled | Promise.allSettled | Promise.allSettled(promises) |
globalThis | globalThis | globalThis.myVar = 'value' |
ES2021 Patterns
| Pattern Name | Text Pattern | Example Code |
|---|---|---|
logical_assignment | ||=, &&=, ??= | x ??= 'default'; y ||= 'fallback'; |
numeric_separators | 1_000_000 | const million = 1_000_000 |
string_replaceAll | .replaceAll() | str.replaceAll('old', 'new') |
promise_any | Promise.any | Promise.any(promises) |
ES2022 Patterns
| Pattern Name | Text Pattern | Example Code |
|---|---|---|
class_fields / private_fields | #field | class C { #private = 1; } |
static_blocks | static {} | class C { static { /* init */ } } |
array_at | .at() | arr.at(-1); str.at(-1); |
object_hasOwn | Object.hasOwn | Object.hasOwn(obj, 'prop') |
top_level_await | await (module) | const data = await fetch(url); |
Practical Examples
Build Tool Integration
import { check, detect } from 'fast-brake';
// Webpack plugin example
class FastBrakePlugin {
constructor(options = {}) {
this.target = options.target || 'es5';
}
apply(compiler) {
compiler.hooks.compilation.tap('FastBrakePlugin', (compilation) => {
compilation.hooks.optimizeChunkAssets.tapAsync('FastBrakePlugin', async (chunks, callback) => {
for (const chunk of chunks) {
for (const filename of chunk.files) {
const source = compilation.assets[filename].source();
const isCompatible = await check(source, { target: this.target });
if (!isCompatible) {
const patterns = await detect(source);
console.warn(`â ${filename} contains pattern:`, patterns[0]?.name);
}
}
}
callback();
});
});
}
}
Telemetry Detection
import { Detector } from 'fast-brake';
import { telemetryPlugin } from 'fast-brake/src/plugins/telemetry';
async function detectTelemetry(code) {
const detector = new Detector();
await detector.initialize(telemetryPlugin);
const result = detector.detectFast(code);
if (result.hasMatch) {
console.log(`Found telemetry: ${result.firstMatch.name}`);
console.log(`Matched text: "${result.firstMatch.match}"`);
console.log(`Rule: ${result.firstMatch.rule}`);
}
return result.hasMatch;
}
// Example usage
const hasTracking = await detectTelemetry(`
ga('send', 'pageview');
fbq('track', 'PageView');
`);
Custom Pattern Detection
import { Detector } from 'fast-brake';
// Create a security-focused plugin
const securityPlugin = {
name: "security-patterns",
description: "Detects potentially unsafe patterns",
spec: {
orderedRules: ["critical", "warning", "info"],
matches: {
"eval_usage": {
rule: "critical",
strings: ["eval("],
patterns: [{ pattern: "\\beval\\s*\\(" }]
},
"innerHTML": {
rule: "warning",
strings: ["innerHTML"],
patterns: [{ pattern: "\\.innerHTML\\s*=" }]
},
"console_output": {
rule: "info",
strings: ["console."],
patterns: [{ pattern: "console\\.(log|info|warn|error)" }]
}
}
}
};
const detector = new Detector();
await detector.initialize(securityPlugin);
const code = `
eval("alert('XSS')");
element.innerHTML = userInput;
console.log(password);
`;
const result = detector.detectFast(code);
if (result.hasMatch) {
console.log(`Security issue: ${result.firstMatch.name} (${result.firstMatch.rule})`);
}
CI/CD Pipeline Integration
import { check, detect } from 'fast-brake';
import { readFileSync, readdirSync } from 'fs';
import { join } from 'path';
// Validate all source files in CI
async function validateCompatibility() {
const srcDir = 'src';
const target = process.env.ES_TARGET || 'es2018';
let hasErrors = false;
const files = readdirSync(srcDir, { recursive: true })
.filter(file => file.endsWith('.js') || file.endsWith('.ts'))
.map(file => join(srcDir, file));
console.log(`đ Checking ${files.length} files for ${target} compatibility...`);
for (const file of files) {
try {
const code = readFileSync(file, 'utf-8');
const isCompatible = await check(code, { target });
if (isCompatible) {
console.log(`â ${file}`);
} else {
const patterns = await detect(code);
console.error(`â ${file}: Contains ${patterns[0]?.name} (rule: ${patterns[0]?.version})`);
hasErrors = true;
}
} catch (error) {
console.error(`â ${file}: ${error.message}`);
hasErrors = true;
}
}
if (hasErrors) {
console.error(`\nâ Compatibility check failed for target ${target}`);
process.exit(1);
} else {
console.log(`\nâ All files are ${target} compatible`);
}
}
validateCompatibility();
Error Handling
Pattern Detection with Error Handling
import { check, detect } from 'fast-brake';
// Check for patterns and handle results
const isCompatible = await check(code, { target: 'es5' });
if (!isCompatible) {
// Get detailed pattern information
const patterns = await detect(code);
if (patterns.length > 0) {
console.error('Incompatible pattern detected:');
console.error(`- ${patterns[0].name} (rule: ${patterns[0].version})`);
}
} else {
console.log('â Code is compatible');
}
Graceful Degradation
import { detect, check } from 'fast-brake';
async function analyzeCodeSafely(code, target = 'es5') {
try {
// Try detection
const patterns = await detect(code);
const isCompatible = await check(code, { target });
return {
patterns,
isCompatible,
mode: 'default',
error: null
};
} catch (error) {
// Detection failed
return {
patterns: [],
isCompatible: false,
mode: 'failed',
error: error.message
};
}
}
TypeScript Integration
fast-brake includes comprehensive TypeScript definitions:
import {
fastBrake,
detect,
check,
Detector,
FastBrakeCache,
Scanner,
type DetectedFeature,
type DetectionOptions
} from 'fast-brake';
// Type-safe options
const options: DetectionOptions = {
target: 'es2015',
orderedRules: ['es2025', 'es2024', 'es2023', 'es2022', 'es2021', 'es2020', 'es2019', 'es2018', 'es2017', 'es2016', 'es2015', 'es5']
};
// Type-safe results with async/await
const patterns: DetectedFeature[] = await detect(code);
const isCompatible: boolean = await check(code, options);
const results: DetectedFeature[] = await fastBrake(code);
// Custom type guards
function isES2020Pattern(pattern: DetectedFeature): boolean {
return pattern.version === 'es2020';
}
// Filter with type safety
const es2020Patterns = patterns.filter(isES2020Pattern);