@speedkit/rules
v1.1.6-0
Published
Baqend Speed Kit Rules
Readme
@speedkit/rules
A TypeScript rule engine for matching HTTP requests based on URL patterns, device type, cookies, storage, content type, and more. Used by Baqend Speed Kit to determine caching and optimization behavior.
Installation
npm install @speedkit/rulesRequires Node.js >= 22.11.0.
Usage
Defining Rules
Rules are plain objects matching the SpeedKitRule interface:
import { RuleSet, AndRule } from '@speedkit/rules';
import type { SpeedKitRule } from '@speedkit/rules';
const rule: SpeedKitRule = {
host: /\.baqend\.com$/,
contentType: ['script', 'style'],
mobile: true,
};Evaluating Rules
Use RuleSet to test requests against a collection of rules.
From JSON (most common):
const ruleSet = new RuleSet().fromJSON([
{ host: /\.baqend\.com$/, contentType: ['script', 'style'] },
{ pathname: /^\/api\/v1/, mobile: true },
]);
const matches = ruleSet.matches(request, { contentType: 'script' });With pre-built AndRule instances:
import { RuleSet, AndRule } from '@speedkit/rules';
const ruleSet = new RuleSet([
new AndRule().fromJSON({ host: /\.example\.com$/ }),
new AndRule().fromJSON({ contentType: ['document'] }),
]);Building incrementally:
const ruleSet = new RuleSet();
ruleSet.addRule(new AndRule().fromJSON({ url: /\/checkout/ }));
ruleSet.addRule(new AndRule().fromJSON({ mobile: true }));
ruleSet.removeRule(someRule); // returns true if foundRetrieving the matching rule:
const matchingRule = ruleSet.getMatchingRule(request, { contentType: 'document' });
if (matchingRule) {
// first rule that matched
}Available Conditions
| Property | Matches Against | Example |
|---------------|------------------------------------|--------------------------------------|
| url | Full URL (host + path + query) | /^www\.example\.com\// |
| host | Domain and port | /\.example\.com$/ |
| pathname | Path and search params | /^\/api\/v1/ |
| hashparam | URL fragment parameters | /campaign/ |
| cookie | Cookie name/value pairs or callback| /^PHPSESSID$/ |
| storage | localStorage/sessionStorage entries| /^userLoggedIn=true$/ |
| contentType | Resource MIME type categories | ['document', 'style', 'script'] |
| mobile | Mobile device | true |
| desktop | Desktop device | true |
| tablet | Tablet device | true |
Condition Types
Conditions accept several formats:
- String -- prefix matching
- RegExp -- pattern matching
- Array -- OR logic (matches if any element matches)
- Function -- custom logic (cookies and storage only)
JSON Serialization
Rules support JSON serialization with special handling for RegExp and Function values:
const json = ruleSet.toJSON();
const restored = new RuleSet();
restored.fromJSON(json);Development
npm install # Install dependencies
npm run build # Compile TypeScript
npm run lint # Run ESLint
npm run test:unit # Run testsLicense
MIT
