npm package: @speedkit/rules
Description: Baqend Speed Kit Rules
Author: Baqend
Latest version: 1.2.2-0

# @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](https://www.baqend.com/speed-kit/latest/) to determine caching and optimization behavior.

## Installation

```bash
npm install @speedkit/rules
```

Requires Node.js >= 22.11.0.

## Usage

### Defining Rules

Rules are plain objects matching the `SpeedKitRule` interface:

```typescript
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):**

```typescript
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:**

```typescript
import { RuleSet, AndRule } from '@speedkit/rules';

const ruleSet = new RuleSet([
  new AndRule().fromJSON({ host: /\.example\.com$/ }),
  new AndRule().fromJSON({ contentType: ['document'] }),
]);
```

**Building incrementally:**

```typescript
const ruleSet = new RuleSet();
ruleSet.addRule(new AndRule().fromJSON({ url: /\/checkout/ }));
ruleSet.addRule(new AndRule().fromJSON({ mobile: true }));

ruleSet.removeRule(someRule); // returns true if found
```

**Retrieving the matching rule:**

```typescript
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:

```typescript
const json = ruleSet.toJSON();
const restored = new RuleSet();
restored.fromJSON(json);
```

## Development

```bash
npm install        # Install dependencies
npm run build      # Compile TypeScript
npm run lint       # Run ESLint
npm run test:unit  # Run tests
```

## License

MIT