Skip to content

@xtandard/flags

The root entry point: the core contracts and types, the evaluator, the snapshot model, and the admin/server factories (createFlagsCore, createFetchHandler).

@xtandard/flags — public surface. Storage/auth/authorization/adapter implementations live behind their own subpath exports (e.g. @xtandard/flags/storage/redis).

import { createFetchHandler } from "@xtandard/flags";
import { createRedisStorage } from "@xtandard/flags/storage/redis";
const storage = createRedisStorage({ url: process.env.REDIS_URL, prefix: "flags" });
const { fetch } = createFetchHandler({
sourceStorage: storage,
basePath: "/flags",
title: "My App Flags",
});
Bun.serve({ port: 3000, fetch });
import { … } from "@xtandard/flags";

Also re-exports symbols of @xtandard/flags/core, @xtandard/flags/schema, @xtandard/flags/evaluator, @xtandard/flags/snapshot, documented on those pages.

Name Summary
assertValidDraft Throwing variant of validateDraft; raises DraftValidationError.
buildOpenApiDocument Build the OpenAPI 3.1 document for the admin API. Pure — safe to call anywhere.
clearComparators Remove all globally-registered comparators. Primarily for test isolation.
clearMatchers Remove all globally-registered matchers. Primarily for test isolation.
createFetchHandler Build the panel fetch handler.
emitEvaluation Invoke listener safely off the evaluation return path: synchronous throws are caught and a returned Promise’s rejection is handled, so a broken sink can never fail (or slow, since it is not awaited) an evaluation.
flagStaleness Assess one flag’s staleness against its Flag.lifecycle policy.
hashToUnitInterval Map a string deterministically onto the half-open unit interval [0, 1). Used to pick a bucket within a split’s cumulative weight range.
inlineSegments Inline segments across every flag in a map.
inlineSegmentsInFlag Return a copy of flag with single-key inSegment references in its rules inlined. Flags without such references are returned unchanged (same reference).
isMutatingAction True if the action mutates state.
murmur3 MurmurHash3 x86 32-bit. Returns an unsigned 32-bit integer.
pgListenNotify A WatchSubscribe source for Postgres LISTEN/NOTIFY: the database owns the trigger that pg_notifys channel with the changed key as payload; client is a dedicated listening connection.
referencedSegmentKeys Collect the segment keys referenced (anywhere in the tree) by a flag’s rules.
registerComparator Register a comparator on the process-wide default registry. Consulted by every evaluation, including the bare ./evaluator.evaluateFlag. Later registrations take precedence (first match wins on lookup).
registerMatcher Register a query matcher on the process-wide default registry under name (re-registering a name replaces it). Consulted by every evaluation, including the bare ./evaluator.evaluateFlag.
requirePeer Helper for adapters whose subpath requires an optional peer dependency. Throws a clear, actionable error when the peer is missing.
resolveMatcher Resolve a matcher by name. Lookup order: the active scope (instance + global, inside withMatchers) → the global registry → the always-available builtinMatchers (e.g. "regex"). User registrations shadow built-ins.
resolveSegments Resolve every segment for embedding in a snapshot: single-key inSegment references are inlined (so embedded segments hold only leaf conditions, groups, array inSegment, and notInSegment), which is what ./evaluator.evaluateFlag needs to check membership.
summarizeLifecycle Summarize lifecycle health across many flags — counts plus a 0–100 health score (the share of active flags that are not stale).
usesEmbeddedSegments True if any flag rule (after inlining) needs embedded segments at runtime — i.e. uses notInSegment, or an inSegment with an array value (an OR across segments, which can’t be inlined). Single-key inSegment is inlined, so it doesn’t count.
usesNotInSegment True if any flag rule (after inlining) uses the notInSegment operator.
validateDraft Validate every flag in a draft. Errors are prefixed with the flag key.
validateFlag Validate a single flag: structure + semantic cross-field checks.
validatePrerequisiteGraph Cross-flag prerequisite validation: every referenced flag/variant exists and the dependency graph is acyclic. Returns an empty array when sound.
validateSegment Validate a single reusable Segment: structure + inSegment value checks. Cross-entity reference/cycle checks live in ./segments.validateSegmentReferences.
validateSegmentReferences Validate that every inSegment reference (across flags and nested segments) resolves to an existing segment and that the reference graph is acyclic. Returns an empty array when the references are sound.
withComparators Run fn with registry layered over the global default for the duration of the (synchronous) call. Instance entries take precedence over global ones. Restores the previous scope in a finally, so nesting and throws are safe.
withMatchers Run fn with registry layered over the global default for the duration of the (synchronous) call; instance matchers shadow global ones of the same name. Restores the previous scope in a finally. Safe because the evaluator never awaits between the scope set and its use.
Name Summary
DraftValidationError Raised by assertValidDraft when a draft fails validation.
SegmentResolutionError Thrown when a segment reference cannot be resolved (missing or cyclic).
Name Summary
ComparatorHandlers How to order (and optionally coerce) values of a custom comparable type.
ComparatorResult Outcome of consulting the registry for a pair of operands.
CreateFetchHandlerResult Return shape of createFetchHandler.
EvaluationEvent One resolved evaluation, delivered to an EvaluationListener.
FlagsPanelOptions Options for the panel handler (shared by every framework adapter).
FlagStaleness Lifecycle assessment of a single flag.
LifecycleSummary Aggregate lifecycle health across a set of flags.
OpenApiOptions Options for buildOpenApiDocument.
SegmentReferenceError A single segment-reference problem, with a dotted path into the offending data.
StalenessOptions Options for flagStaleness / summarizeLifecycle.
Name Summary
AfterEvent Event delivered to FlagsHooks.after — the committed mutation. Carries the resulting state (e.g. the stamped flag, the published snapshot).
AfterEventType
AuthorizationProvider Decides whether an action is permitted.
AuthorizeInput Input passed to AuthorizationProvider.authorize.
BeforeEvent Event delivered to FlagsHooks.before — the proposed mutation, before it commits. Throw from the handler to deny it.
BeforeEventType The discriminant strings of BeforeEvent / AfterEvent.
ComparatorEntry A single registry entry: a predicate paired with its handlers.
ComparatorPredicate Tests whether a value belongs to a custom comparable type. Should never throw, but is called defensively.
ComparatorRegistry A set of comparator entries. A Map<predicate, handlers> (as the natural “keyed by predicate” shape) or any iterable of [predicate, handlers] tuples.
EvaluationErrorReporter Reports an error thrown/rejected by an EvaluationListener.
EvaluationListener A fire-and-forget observer of evaluations. Return value (including a Promise) is ignored by the caller; throwing / rejecting never affects the evaluation — failures are routed to the configured error reporter.
FlagsAction The full set of authorizable actions.
FlagsCorsOptions CORS for a cross-origin embed (@xtandard/kit/server): origin (a string, list or predicate), credentials, headers, methods and maxAge.
FlagsHooks A control-plane hook. Implement before, after, or both. Pass one — or an array — to createFlagsCore via hooks. before runs before a mutation commits (throw to deny); after runs once it has committed, for side effects only (errors are isolated and reported via onHookError).
FlagsHooksInput Accepts a single hook, an array, or nothing.
FlagsResource The resource an action targets.
HookErrorReporter Reports an error thrown by an after hook.
MatcherFn Decides whether a matches/notMatches condition is satisfied.
MatcherRegistry A set of named matchers: a Map<name, fn>, a plain Record<name, fn>, or any iterable of [name, fn] tuples.
ValidationError A single validation problem with a dotted path into the offending data.
ValidationResult Result of validateFlag / validateDraft.
Name Summary
DEFAULT_MATCHER Matcher name used when a condition omits matcher.
defaultHookErrorReporter Default after-hook error reporter: warn, but never throw.
flagSchema Structural schema for a Flag. Semantic checks run separately.
MUTATING_ACTIONS Actions that mutate state — blocked in readonly mode.
regexMatcher Built-in, zero-dep matcher backing the "regex" name out of the box. The query is { pattern: string, flags?: string }; the subject (an attribute value, or the whole context) is coerced with String() and tested against the RegExp. A bad pattern throws → the evaluator fails the condition closed.