/** * vapor-chamber - Extra plugins * * cache, circuitBreaker, rateLimit, metrics * * These are optional, tree-shaken, and declared as parts (PluginParts) the bus places. * * ON THE DUPLICATION IN HERE, so it is not "cleaned up" a second time. * * Two pairs look extractable: the bounded eviction in `cache()` and * `idempotent()`, and the "compact when more than half the buffer is dead" * block in `rateLimit()` and `metrics()`. Both extractions were built, * measured and rejected. * * Shared `evictOldest` + `compactHead` helpers made the `.` ESM entry +66 * bytes minified / +24 gzip. The generic parameters they need - an optional * remove callback, a container object for the head buffer - cost more than * the ~15 duplicated lines they save, because a minifier already handles * small repeated patterns well. Nothing else moved: these plugins are absent * from all three IIFE variants (`plugins.ts` re-exports only plugins-core and * plugins-io), so `check-size.mjs` cannot see them, and the treeshake * ceiling scenario does not include them either. * * The two evictions follow one rule: oldest first, down to the bound, after * the insert, so `idempotent({ maxSize: 0 })` remembers nothing * (tests/plugins-extra-gaps.test.ts). An extraction changes bytes only, on * the one entry that ships this code. */ import type { ActionScope, Command, PluginParts } from './command-bus'; import type { ActionFilter } from './action-filter'; export type CacheOptions = { /** Cache TTL in milliseconds. Default: 30_000 (30s). */ ttl?: number; /** Max entries in the cache. Default: 100. LRU eviction. */ maxSize?: number; /** Which actions to cache. Glob patterns supported. An {@link ActionScope}. */ actions?: ActionScope; /** Selects actions by name, ANDed with `actions`: an {@link ActionFilter} (`createActionFilter`). Log s35.152. */ actionFilter?: ActionFilter; /** Custom cache key. Default: commandKey(action, target). */ key?: (cmd: Command) => string; }; /** * cache - memoize handler results by (action, target) key. * Use with `query()` for read-only commands. The plugin intercepts the * dispatch/query pipeline and returns the cached result if fresh. * * @example * bus.use(cache({ ttl: 60_000, actions: ['getUser*'] })); * bus.query('getUser', { id: 42 }); // handler runs * bus.query('getUser', { id: 42 }); // cache hit, handler skipped */ export declare function cache(options?: CacheOptions): PluginParts & { /** Clear the entire cache. */ clear(): void; /** Current cache size. */ size(): number; }; export type CircuitBreakerOptions = { /** Number of consecutive failures before the circuit opens. Default: 5. */ threshold?: number; /** Time in ms the circuit stays open before trying half-open. Default: 30_000. */ resetTimeout?: number; /** Which actions to protect. Glob patterns. An {@link ActionScope}. */ actions?: ActionScope; /** Selects actions by name, ANDed with `actions`: an {@link ActionFilter} (`createActionFilter`). Log s35.152. */ actionFilter?: ActionFilter; /** Called when circuit opens. */ onOpen?: (action: string, failCount: number) => void; /** Called when circuit resets (half-open succeeds). */ onClose?: (action: string) => void; }; type CircuitState = 'closed' | 'open' | 'half-open'; /** * circuitBreaker - trips after N consecutive failures, rejects fast while open. * * @example * bus.use(circuitBreaker({ threshold: 3, resetTimeout: 10_000, actions: ['api*'] })); */ export declare function circuitBreaker(options?: CircuitBreakerOptions): PluginParts & { /** Get the current circuit state for an action. */ getState(action: string): CircuitState; /** Manually reset a circuit. */ reset(action: string): void; }; export type RateLimitOptions = { /** Max dispatches per window. Default: 10. */ max?: number; /** Window size in milliseconds. Default: 1_000 (1 second). */ window?: number; /** Which actions to rate limit. Glob patterns. An {@link ActionScope}. */ actions?: ActionScope; /** Selects actions by name, ANDed with `actions`: an {@link ActionFilter} (`createActionFilter`). Log s35.152. */ actionFilter?: ActionFilter; }; /** * rateLimit - per-action sliding window rate limiter. * Unlike a throttle (`pace`: one run per `wait` per action+target, the rest * rejected until it ends), rateLimit allows `max` per sliding window per action and * rejects the excess immediately. * * @example * bus.use(rateLimit({ max: 5, window: 1000, actions: ['api*'] })); */ export declare function rateLimit(options?: RateLimitOptions): PluginParts; export type MetricsEntry = { action: string; ok: boolean; durationMs: number; timestamp: number; }; export type MetricsOptions = { /** Max entries to keep. Default: 1000. Oldest evicted first. */ maxSize?: number; /** Which actions to track. An {@link ActionScope}. */ actions?: ActionScope; /** Selects actions by name, ANDed with `actions`: an {@link ActionFilter} (`createActionFilter`). Log s35.152. */ actionFilter?: ActionFilter; /** Called after each dispatch with the metrics entry. */ onEntry?: (entry: MetricsEntry) => void; }; /** * metrics - lightweight telemetry plugin. * Tracks dispatch count, success rate, and avg duration per action. * A `started` and a `settled` part (PluginParts): it times every outcome, * a rule's refusal and a query included, wherever it is installed. A * command that settles with no start (aborted before it started) records * 0 ms. tests/metrics-parts.test.ts. * * @example * const m = metrics({ maxSize: 500 }); * bus.use(m); * console.log(m.summary()); // { cartAdd: { count: 42, avgMs: 1.2, errorRate: 0.02 } } * console.log(m.entries()); // raw entries */ export declare function metrics(options?: MetricsOptions): PluginParts & { /** Get all raw metric entries. */ entries(): MetricsEntry[]; /** Get a summary per action: count, avgMs, errorRate. */ summary(): Record; /** Clear all entries. */ clear(): void; }; export type IdempotentOptions = { /** * Derive a stable idempotency key from a command. Commands with the same key * are the same logical operation. Return `null`/`undefined` to skip a command. * Given, it is also the wire key, sent as given. Default: * `commandKey(action, [target, payload])`, or `commandKey(action, target)` * with no payload, kept local: the wire key is then the dispatch's * `meta.id`. A key of unreserved characters (letters, digits, `-`, `_`, * `.`, `~`) goes out as it is. Any other key is percent-encoded on every * send: about 110 ns a command on an Apple M3, Node 24.21.0 (log 36.48). * tests/idempotency-key.test.ts. */ key?: (cmd: Command) => string | null | undefined; /** * How long (ms) a *completed* key is remembered for dedup - the window in * which a repeat (double-click, retry, reconnect replay) is collapsed to the * first result instead of hitting the handler/backend again. Default: 60_000. */ ttl?: number; /** Restrict to specific actions (glob patterns). An {@link ActionScope}. */ actions?: ActionScope; /** Selects actions by name, ANDed with `actions`: an {@link ActionFilter} (`createActionFilter`). Log s35.152. */ actionFilter?: ActionFilter; /** * Also stamp a wire key onto `cmd.meta.idempotencyKey` so transports forward * it (the HTTP transport sends it as an `Idempotency-Key` header): the `key` * option's value, else the dispatch's `meta.id`. A key already stamped (an * outbox replay's) stays. Default: true. */ stampMeta?: boolean; /** * Max completed keys remembered at once - oldest is evicted first, so memory * stays bounded on long-lived buses with many distinct targets. Default: 500. */ maxSize?: number; }; /** * idempotent - make duplicate dispatches a no-op against the handler/backend. * * The client-side half of exactly-once delivery: it collapses repeats of the * same logical command - double-clicked Checkout, an auto-retry, a reconnect * that replays a queued action - so the handler (and the backend it calls) runs * **once**. Concurrent duplicates share the first in-flight promise; sequential * duplicates within `ttl` get the cached result. Failures are NOT cached, so a * genuine retry after an error still runs. * * Pairs with `register({ exclusive })` (orders same-key commands locally) and the HTTP * transport, which forwards the stamped `cmd.meta.idempotencyKey` as an * `Idempotency-Key` header so the backend runs a re-sent request once - the * wire half of exactly-once. That key is the dispatch's id, or the `key` * option's value: the content key stays in the browser. The transport is the * work, inside every plugin, so the key is stamped before the request is built. * * @example * const bus = createAsyncCommandBus({ transport: httpTransport({ endpoint: '/commands', csrf: true }) }); * bus.use(idempotent({ actions: ['order*'] })); * // two rapid orderCreate dispatches -> one handler run, one backend write */ export declare function idempotent(options?: IdempotentOptions): PluginParts; export type SupersedeOptions = { /** * Derive the supersede key from a command. Commands resolving to the SAME * key auto-cancel their predecessor; different keys race independently. * Return `null`/`undefined` to skip superseding for that command. * Default: `commandKey(action, target)`: a newer dispatch on the same * target cancels the one in flight whatever its payload (a search box's * next keystroke). It includes the action name, so distinct actions never * collide and are never silently dropped by this plugin. */ key?: (cmd: Command) => string | null | undefined; /** Restrict to specific actions (glob patterns). An {@link ActionScope}. */ actions?: ActionScope; /** Selects actions by name, ANDed with `actions`: an {@link ActionFilter} (`createActionFilter`). Log s35.152. */ actionFilter?: ActionFilter; }; /** * supersede - auto-cancel the previous in-flight dispatch for the same key. * * Built for rapid-fire reads that can overwrite each other in flight - a * search box re-querying on every keystroke, a filter changing before the * previous fetch lands. Without it, a slow first response can arrive AFTER a * faster second one and clobber it with stale data. With it, the first * dispatch's AbortSignal fires the instant a second dispatch for the same key * starts - `httpTransport` forwards `cmd.signal` to `fetch()`, so the * stale request is genuinely cancelled, not merely ignored once it resolves. * With `batch`, it settles the stale command at once, drops it * from a batch not yet sent, and cancels a sent batch once every command in * it has aborted (tests/batching-abort.test.ts). A handler that passes `cmd.signal` to * `createHttpClient().get()` is cancelled the same way, even when its GET * joined one already in flight (see the client's `dedupe`). * * **Async bus only**: its `begin` step hands the bus the signal the work * runs under, which only a cancelable async dispatch carries. * * @example * const bus = createAsyncCommandBus({ transport: httpTransport({ endpoint: '/api/vc' }) }); * bus.use(supersede({ actions: ['productSearch'] })); * // three quick productSearch dispatches -> only the last one's response is * // ever awaited; the first two are aborted mid-flight, not just discarded */ export declare function supersede(options?: SupersedeOptions): PluginParts; export {}; //# sourceMappingURL=plugins-extra.d.ts.map