import { MetricsAdapter } from './core/metrics.mjs'; import { TypedFlagKey } from './core/flag-types.mjs'; interface InvalidationMessage { scope: "flag" | "all"; key?: string; action?: string; sourceId?: string; ts?: number; } type InvalidationListener = (message: InvalidationMessage) => void | Promise; /** * Cross-process invalidation bus for keeping L1 caches and SSE streams coherent * across multiple SDK instances. */ interface InvalidationBus { publish(message: InvalidationMessage): Promise; subscribe(listener: InvalidationListener): Promise<() => void> | (() => void); close?(): Promise; } /** * Database adapter interface for all Rollease flag operations. * Implement this interface to connect Rollease to any database. * All `rl_*` tables are owned and managed by Rollease. */ interface DbAdapter { /** Create a new flag. Throws FlagConflictError if key exists. */ createFlag(input: CreateFlagInput): Promise; /** Get a flag by key. Returns null if not found. */ getFlag(key: string): Promise; /** List flags with filtering, search, and pagination. */ listFlags(input: ListFlagsInput): Promise; /** Update a flag's metadata. Returns updated flag. */ updateFlag(key: string, input: UpdateFlagInput): Promise; /** Set flag status (active, killed, archived). */ setFlagStatus(key: string, status: FlagStatus): Promise; /** Permanently delete a flag and all associated data. */ deleteFlag(key: string): Promise; /** Clone a flag to a new key. */ cloneFlag(sourceKey: string, newKey: string, includeRules: boolean, includeRollout: boolean): Promise; /** Set/update rollout configuration for a flag. */ setRollout(key: string, rollout: { percentage?: number; sticky?: boolean; hashKey?: string; rampSchedule?: { at: string; percentage: number; }[]; }): Promise; /** Add a targeting rule to a flag. Returns created rule. */ addRule(flagKey: string, input: AddRuleInput): Promise; /** Update an existing rule. Returns updated rule. */ updateRule(flagKey: string, ruleId: string, input: UpdateRuleInput): Promise; /** Remove a rule from a flag. */ removeRule(flagKey: string, ruleId: string): Promise; /** List all rules for a flag, sorted by priority. */ listRules(flagKey: string): Promise; /** Reorder rules by setting new priorities. */ reorderRules(flagKey: string, ordering: RuleOrdering[]): Promise; /** Create a new segment. Throws FlagConflictError if key exists. */ createSegment(input: CreateSegmentInput): Promise; /** Update a segment. */ updateSegment(key: string, input: UpdateSegmentInput): Promise; /** Delete a segment. */ deleteSegment(key: string): Promise; /** List all segments. */ listSegments(): Promise; /** Get a segment by key. */ getSegment(key: string): Promise; /** Find which flags reference a segment. */ getSegmentUsage(key: string): Promise; /** Create a new release (batch of flag changes). */ createRelease(input: CreateReleaseInput): Promise; /** Get a release by ID. */ getRelease(releaseId: string): Promise; /** List releases with filtering. */ listReleases(filters?: { environment?: string; status?: string; limit?: number; }): Promise; /** Mark a release as deployed and apply all its changes atomically. */ deployRelease(releaseId: string, deployedBy?: string): Promise; /** Mark a release as rolled back and revert all its changes. */ rollbackRelease(releaseId: string, rolledBackBy?: string, reason?: string): Promise; /** Approve a release by appending the approver. */ approveRelease?(releaseId: string, approverId: string): Promise; /** Reject a release with an optional reason. */ rejectRelease?(releaseId: string, rejectorId: string, reason?: string): Promise; /** Create a new exclusion layer. */ createExclusionLayer?(input: ExclusionLayer): Promise; /** Get an exclusion layer by key. */ getExclusionLayer?(key: string): Promise; /** Update an exclusion layer's allocations. */ updateExclusionLayer?(key: string, allocations: ExclusionLayerAllocation[]): Promise; /** Delete an exclusion layer. */ deleteExclusionLayer?(key: string): Promise; /** List all exclusion layers. */ listExclusionLayers?(): Promise; /** Get a user's sticky variant assignment for a flag. */ getUserAssignment(flagKey: string, userId: string): Promise; /** * Batched variant: return assignments for many flags in one round-trip. * Optional — when omitted, FlagManager.evaluateAll falls back to N calls. * Implement in production adapters to avoid N+1 queries on bulk evaluate. */ getUserAssignments?(flagKeys: string[], userId: string): Promise>; /** Set a user's sticky variant assignment. */ setUserAssignment(flagKey: string, userId: string, variantKey: string): Promise; /** Record a history entry for a flag. */ addHistory(entry: Omit): Promise; /** Get history for a flag. */ getHistory(flagKey: string, opts?: { limit?: number; }): Promise; /** Record an evaluation impression. */ trackImpression?(params: { flagKey: string; userId: string; value: unknown; variant: string | null; reason: string; }): Promise; /** Record a custom tracking/conversion event. */ trackEvent?(event: TrackEventInput): Promise; /** Optional test/admin helper for reading tracked events. */ listTrackingEvents?(filters?: { userId?: string; event?: string; limit?: number; }): Promise; /** * Return impression records for a specific user — supports right-to-explanation. * Optional: fall back to filtering all impressions when absent. */ getUserImpressions?(userId: string, opts?: { limit?: number; flagKey?: string; }): Promise>; /** * Get all active flags for bulk evaluation. Supports pagination so very * large flag tables don't have to be loaded into memory at once. */ getAllActiveFlags(opts?: { namespace?: string; tags?: string[]; keys?: string[]; limit?: number; offset?: number; }): Promise; /** Add tags to a flag. */ addTags(flagKey: string, tags: string[]): Promise; /** Remove tags from a flag. */ removeTags(flagKey: string, tags: string[]): Promise; /** Update the lastEvaluatedAt timestamp for a flag (fire-and-forget). */ touchFlagEvaluation?(key: string): Promise; /** * Delete all personal data for a user (GDPR right-to-erasure). * Scope defaults to all data types when omitted. */ forgetUser?(userId: string, scope?: Array<"impressions" | "assignments" | "history" | "events">): Promise; /** * Return releases whose scheduledAt <= now and status is 'pending' or * 'scheduled'. Used by rl.flags.runScheduledReleases(). */ listScheduledReleases?(): Promise; /** * Delete impression records older than `cutoff`. Used by * `FlagManager.runRetentionPolicies()` when `privacy.impressionRetentionDays` * is configured. */ deleteImpressionsBefore?(cutoff: Date): Promise; /** * Delete history entries older than `cutoff`. Used by * `FlagManager.runRetentionPolicies()` when `privacy.auditRetentionDays` * is configured. */ deleteHistoryBefore?(cutoff: Date): Promise; /** * Execute `fn` inside an atomic transaction. On error, all writes inside * `fn` are rolled back. When absent, the manager falls back to sequential * writes (no rollback on partial failure). * * Implement this in production SQL adapters for safe deployRelease and * bulk mutations. */ transaction?(fn: (tx: DbAdapter) => Promise): Promise; /** Close any active database connections. */ close?(): Promise; } /** * Cache adapter interface for L2 (shared) caching. */ interface CacheAdapter { get(key: string): Promise; set(key: string, value: string, ttlMs: number): Promise; del(key: string): Promise; delPattern?(pattern: string): Promise; close?(): Promise; } type FlagKey = TypedFlagKey; type UserId = string; interface RolleaseConfig { /** Database adapter — handles all rl_* table operations */ db: DbAdapter; /** Secret for signing internal tokens */ secret: string; /** Cache configuration */ cache?: CacheConfig; /** L1 (in-process) cache TTL in milliseconds (default: 5000) */ l1TtlMs?: number; /** Enable local developer overrides via .rolleaserc.json (default: true in dev) */ localOverrides?: boolean; /** Override file path (default: '.rolleaserc.json') */ localOverridesFile?: string; /** Per-evaluation impression tracking */ impressions?: ImpressionConfig; /** Lifecycle hooks for extension (RBAC/ABAC, custom audit, metrics) */ hooks?: RolleaseHooks; /** Logging configuration (level + sink). When unset, falls back to console. */ logging?: LoggingConfig; /** Page size used by evaluateAll/getAllActiveFlags (default 1000). */ evaluateAllPageSize?: number; /** * When enabled, the SDK automatically evaluates segment definitions from * the database against the user context to populate `context.segments`. * Skipped when the caller pre-populates `context.segments`. * Default: false (opt-in for backward compatibility). */ autoResolveSegments?: boolean; /** Webhook configurations for flag change notifications */ webhooks?: WebhookConfig[]; /** Environment name — filters all flag operations to this environment */ environment?: string; /** Resilience: graceful degradation, retries, circuit breaker */ resilience?: ResilienceConfig; /** Privacy: PII attribute scrubbing, data retention */ privacy?: PrivacyConfig; /** OpenTelemetry / custom telemetry integration */ telemetry?: TelemetryAdapter; /** * Pluggable metrics adapter. Use `createPrometheusAdapter()` from * `rollease/metrics` or supply any `MetricsAdapter` implementation. * When provided, the SDK automatically tracks evaluations, cache hits/misses, * errors, impressions, and DB latency. */ metrics?: MetricsAdapter; /** Cross-process invalidation bus for multi-replica cache/SSE coherence. */ invalidation?: InvalidationBus; /** * Optional read-replica DB adapter. When provided, all evaluation reads * (getFlag, listRules, getUserAssignment) use this adapter; all writes use * the primary `db` adapter. */ dbReader?: DbAdapter; /** * Namespace prefix added to all L1/L2 cache keys. * Set this to `tenantId` when using `createTenantAdapter` with a shared * Redis cache to prevent cross-tenant cache collisions. * Example: `"acme"` → cache keys become `rollease:acme:flag:`. */ cacheNamespace?: string; /** * Audit logging configuration. When enabled, every flag mutation writes * a structured AuditEvent to the configured sink. * `"db"` uses the addHistory path (always on). * `"stdout"` logs via the configured `logging.sink`. * Pass an AuditSink object for custom destinations (Datadog, S3, etc.). */ audit?: AuditConfig; /** * Signing key ring for SDK key rotation. * The key matching `currentSigningKeyId` is used to sign new tokens. * All keys in the ring are accepted for verification (allows gradual rotation). * When omitted, the single `secret` field is used for both sign and verify. */ signingKeys?: Array<{ kid: string; secret: string; }>; /** * The `kid` from `signingKeys` to use for signing new tokens. * Ignored when `signingKeys` is not provided. */ currentSigningKeyId?: string; /** * Pluggable analytics sink. All `trackEvent()` calls are forwarded here in * addition to the database adapter. Use to dual-write to Segment, Mixpanel, * PostHog, etc. */ analyticsSink?: AnalyticsSink; } interface ResilienceConfig { /** * When true, DB errors during evaluate() return a fallback result * ({ value: null, reason: 'error_fallback' }) instead of throwing. * @default false */ fallbackOnError?: boolean; /** Retry configuration for DB operations. */ retry?: { /** Max retry attempts. @default 3 */ attempts?: number; /** Base delay between retries in ms. @default 100 */ backoffMs?: number; /** Add random jitter to retry delay. @default true */ jitter?: boolean; }; /** * Simple circuit breaker: after `threshold` consecutive failures * within `windowMs`, open the circuit and return fallback results * for `resetAfterMs` before retrying. */ circuitBreaker?: { threshold?: number; windowMs?: number; resetAfterMs?: number; }; } interface PrivacyConfig { /** * Context attribute keys to scrub before passing to impression tracking, * audit history, and evaluation hooks. Values are replaced with '[REDACTED]'. */ privateAttributes?: string[]; /** Automatically delete impression records older than N days. */ impressionRetentionDays?: number; /** Automatically delete audit history older than N days. */ auditRetentionDays?: number; } /** Span object returned by TelemetryAdapter.startSpan(). */ interface TelemetrySpan { setAttribute(key: string, value: string | number | boolean): void; end(status?: "ok" | "error", error?: Error): void; } /** * Plug-in telemetry adapter. Use `createOtelAdapter(tracer)` from * `rollease/telemetry` to integrate with `@opentelemetry/api`. */ interface TelemetryAdapter { startSpan(name: string, attrs?: Record): TelemetrySpan; } /** Returned by `rl.health()` and `GET /api/rollease/health`. */ interface RolleaseHealthResult { status: "healthy" | "degraded" | "unhealthy"; db: "ok" | "error"; cache: "ok" | "error" | "disabled"; circuit?: "closed" | "open" | "half_open" | "disabled"; latencyMs: number; evalCount: number; cacheHits: number; cacheMisses: number; cacheHitRate: number; uptimeMs: number; ts: number; } interface ImpressionConfig { /** Disable impression tracking entirely (default: enabled when db.trackImpression exists) */ enabled?: boolean; /** Sample rate 0..1 (default 1.0). 0 disables, 1 tracks every evaluation. */ sampleRate?: number; /** * Deduplication settings for impression tracking. When enabled, the SDK * suppresses duplicate impressions for the same user+flag+value within a * time window. Without this, every evaluate() call records an impression. */ dedupe?: { /** Window in ms within which duplicate impressions are suppressed. Default: 60_000 (1 min). */ windowMs?: number; /** Max dedup cache entries before eviction. Default: 10_000. */ maxEntries?: number; /** Fields that form the dedup key. Default: ["flagKey","userId","value"]. */ keyFields?: Array<"flagKey" | "userId" | "value" | "variant" | "reason">; }; } /** * Pluggable analytics sink. When configured, all `trackEvent()` calls are also * forwarded to this sink — useful for dual-writing to Segment, Mixpanel, etc. */ interface AnalyticsSink { track(event: TrackingEvent): void | Promise; } interface TrackEventInput { userId?: string; anonymousId?: string; event: string; value?: number; metadata?: Record; context?: FlagContext; ts?: number | string | Date; /** SDK name auto-attached by the SDK (e.g. 'rollease-server', 'rollease-browser'). */ sdkName?: string; /** SDK version auto-attached by the SDK. */ sdkVersion?: string; } interface TrackingEvent { id: string; userId?: string; anonymousId?: string; event: string; value?: number; metadata?: Record; context?: FlagContext; environment?: string; sdkName?: string; sdkVersion?: string; createdAt: Date; } interface RolleaseHooks { /** * Called before any write operation. Throwing aborts the operation (use for RBAC denials). * `flagKey` is undefined for global operations like killAll. */ onBeforeMutation?: (ctx: { action: HistoryAction; flagKey?: string; actor?: AuditActor; }) => Promise | void; /** * Called before a single flag evaluation. Throwing aborts evaluation. * Returning a `FlagContext` object replaces the evaluation context — use this * to enrich or canonicalize context (e.g. resolve GeoIP, inject tenant fields). * Throwing aborts the evaluation (use for RBAC denials at read time). */ onBeforeEvaluation?: (ctx: { flagKey: string; context: FlagContext; }) => Promise | FlagContext | void; /** * Called after every evaluation (single or bulk). Fire-and-forget — errors are logged. */ onEvaluate?: (result: FlagResult, context: FlagContext) => Promise | void; } type LogLevel = "silent" | "error" | "warn" | "info" | "debug"; interface LoggingConfig { /** Threshold below which messages are dropped. Default 'warn'. */ level?: LogLevel; /** Custom sink. Default writes to console.. */ sink?: (level: Exclude, message: string, meta?: Record) => void; } /** * Identifies the actor performing a write operation. Used in audit history * and surfaced to permission hooks. */ interface AuditActor { id: string; type: "user" | "service" | "system"; name?: string; metadata?: Record; } interface CacheConfig { driver: "memory" | "redis"; redis?: { url: string; }; /** L2 cache TTL in seconds (default: 60) */ ttl?: number; } interface AuditConfig { enabled: boolean; sink: "db" | "stdout" | AuditSink; /** Fields to scrub from audit events */ scrubFields?: string[]; } interface AuditSink { write(event: AuditEvent): Promise; } /** * Context passed to flag evaluation. * All fields are optional — pass what's relevant. */ interface FlagContext { /** User identifier — required for user targeting and percentage hash */ userId?: string; /** Runtime environment: 'dev' | 'staging' | 'production' */ environment?: string; /** App/API semver string for version-based targeting (e.g. '2.1.0') */ version?: string; /** Geographic region code (e.g. 'eu', 'us', 'ca', 'apac') */ region?: string; /** User cohort from your user model (e.g. 'beta', 'alpha', 'internal') */ userType?: string; /** Pre-resolved segment keys (e.g. ['power_users', 'enterprise']) */ segments?: string[]; /** Arbitrary key-value attributes for custom targeting rules */ attributes?: Record; /** IP address for GeoIP resolution (optional) */ ip?: string; /** Multi-tenant isolation key */ tenantId?: string; } type FlagType = "boolean" | "multivariate" | "percentage" | "string" | "number" | "json"; type FlagStatus = "active" | "killed" | "archived"; interface Flag { id: string; key: FlagKey; type: FlagType; status: FlagStatus; defaultValue: unknown; description?: string; namespace?: string; tags?: string[]; locked?: boolean; lockedReason?: string; /** Per-environment configurations */ environments?: string[]; /** Multivariate variant definitions */ variants?: FlagVariantDef[]; /** Rollout configuration */ rollout?: RolloutConfig; /** Auto-activation date */ scheduledAt?: Date | string | null; /** Auto-deactivation date */ expiresAt?: Date | string | null; /** * Flag prerequisites — this flag only evaluates if ALL prerequisites * return their required variation. Prevents enabling features without * their dependencies. */ prerequisites?: FlagPrerequisite[]; /** Per-environment default value overrides (e.g. { production: false, staging: true }) */ environmentDefaults?: Record; /** Last time this flag was evaluated (set by touchFlagEvaluation) */ lastEvaluatedAt?: Date | null; /** Exclusion layer key this flag belongs to */ exclusionLayer?: string; /** Whether this flag may be exposed through public browser/client keys. */ clientVisible?: boolean; createdAt: Date; updatedAt: Date; } /** * A prerequisite relationship. The prerequisite flag must evaluate to the * specified variation before this flag's rules are considered. */ interface FlagPrerequisite { /** Key of the prerequisite flag */ flagKey: string; /** Required value — prerequisite must evaluate to this value */ variation: unknown; } interface FlagVariantDef { id: string; key: string; value: unknown; /** Weight for weighted random distribution (0-100, all weights should sum to 100) */ weight: number; description?: string; } interface Variant { key: string; value: unknown; reason: EvalReason; } interface RolloutConfig { /** Percentage of users who get the "on" value (0-100) */ percentage: number; /** Whether the same user always gets the same bucket (default: true) */ sticky: boolean; /** Which context field to hash on (default: 'userId') */ hashKey: string; /** * Optional salt mixed into the bucket hash. Changing this reshuffles which * users fall in/out of rollout without re-keying the flag. Useful for * re-running experiments or fixing biased splits. * @default '' (empty string — uses the flag key as the sole hash input) */ salt?: string; /** Auto-ramp schedule — percentage increases automatically at given dates */ rampSchedule?: RampStep[]; } interface RampStep { /** ISO date string — when this percentage becomes active */ at: string; /** Target percentage at this date */ percentage: number; } interface FlagRule { id: string; flagKey: FlagKey; name?: string; /** Lower priority number = evaluated first */ priority: number; /** Value to return when this rule matches */ value: unknown; /** Targeting conditions (AND/OR/NOT groups) */ conditions: FlagConditionGroup; /** Whether this rule is active */ enabled: boolean; /** Per-rule rollout percentage — only X% of matched users get the value */ rolloutPct?: number; /** Holdout flag — matched users get defaultValue (control group) */ isHoldout?: boolean; /** Specific variant ID to assign (for multivariate flags) */ variantId?: string; /** Explicit user allow-list — if set, rule only matches these users */ userIds?: string[]; /** Human-readable description of what this rule does */ description?: string; /** Arbitrary metadata (e.g. ticket ID, owner, created date) */ metadata?: Record; } type FlagDimensionKey = "environment" | "version" | "userType" | "region" | "userId" | "segment" | "attribute" | "device" | "channel" | string; type FlagOperator = "eq" | "neq" | "in" | "nin" | "gt" | "gte" | "lt" | "lte" | "contains" | "startsWith" | "endsWith" | "regex" | "semverGte" | "semverLte" | "exists" | "dateAfter" | "dateBefore"; interface FlagConditionLeaf { dimension: FlagDimensionKey; op: FlagOperator; value: unknown; } interface FlagConditionGroup { all?: (FlagConditionLeaf | FlagConditionGroup)[]; any?: (FlagConditionLeaf | FlagConditionGroup)[]; none?: (FlagConditionLeaf | FlagConditionGroup)[]; } interface Segment { key: string; description?: string; rules: FlagConditionGroup; createdAt: Date; updatedAt: Date; } interface SegmentUsage { flagKey: string; ruleId: string; } type EvalReason = "kill_switch" | "disabled" | "expired" | "not_scheduled" | "prerequisite_not_met" | "exclusion_group_miss" | "exclusion_layer_not_found" | "override" | "assignment" | "rule_match" | "percentage" | "weighted_random" | "error_fallback" | "default"; interface EvaluationTraceStep { step: number; name: string; matched: boolean; detail?: string; } interface EvaluationTrace { steps: EvaluationTraceStep[]; matchedRuleId?: string; matchedVariantId?: string; } interface FlagResult { key: string; value: T; variant: string | null; enabled: boolean; reason: EvalReason; ruleId: string | null; evaluatedAt: Date; /** Populated when evaluate() is called with { trace: true }. */ trace?: EvaluationTrace; } type FlagMap = Record; type DetailedFlagMap = Record; type ReleaseStatus = "pending" | "deployed" | "rolled_back" | "scheduled"; interface Release { id: string; name: string; description?: string; environment?: string; status: ReleaseStatus; changes: ReleaseChange[]; /** * Before-snapshots captured at deploy time so rollback can restore exact prior state. * Populated by deployRelease(); absent on releases created before snapshots were added. */ snapshots?: ReleaseSnapshot[]; scheduledAt?: string | null; deployedAt?: Date | null; deployedBy?: string; rolledBackAt?: Date | null; rolledBackBy?: string; rollbackReason?: string; requiresApproval?: boolean; requiredApprovers?: string[]; approvalStatus?: "pending" | "approved" | "rejected"; approvals?: string[]; rejectionReason?: string; createdAt: Date; } /** * Per-flag state captured before a release change is applied. * Used by rollbackRelease() to restore the exact prior value/status/rollout. */ interface ReleaseSnapshot { flagKey: string; beforeValue: unknown; beforeStatus: FlagStatus; beforeRollout?: RolloutConfig; } type ReleaseAction = "enable" | "disable" | "setValue" | "setRollout" | "kill" | "restore"; interface ReleaseChange { flagKey: string; action: ReleaseAction; value?: unknown; rollout?: Partial; reason?: string; } interface ReleasePreview { flagKey: string; before: { value: unknown; status: FlagStatus; }; after: { value: unknown; status: FlagStatus; }; } type HistoryAction = "flag.created" | "flag.updated" | "flag.archived" | "flag.restored" | "flag.killed" | "flag.deleted" | "flag.locked" | "flag.unlocked" | "flag.cloned" | "rule.added" | "rule.updated" | "rule.removed" | "rule.reordered" | "rollout.set" | "variant.updated" | "release.created" | "release.deployed" | "release.rolled_back" | "release.approved" | "release.rejected" | "segment.created" | "segment.updated" | "segment.deleted" | "tags.added" | "tags.removed"; interface HistoryEntry { id: string; flagKey?: string; action: HistoryAction; /** * Actor who performed the action. String form is preserved for backwards * compatibility (older audit logs); new code should pass an AuditActor. */ by?: string | AuditActor; at: Date; changes?: Record; reason?: string; releaseId?: string; } interface AuditEvent { id?: string; eventType: string; userId?: string; actorId?: string; resource?: string; action?: string; outcome?: string; metadata?: Record; createdAt: Date; } interface GeoContext { ip: string; country: string; continent: string; region: string; city: string; timezone: string; } interface GeoIPAdapter { resolve(ip: string): Promise; } interface CreateFlagInput { key: string; type: FlagType; defaultValue: unknown; description?: string; namespace?: string; tags?: string[]; environments?: string[]; variants?: Omit[]; rollout?: RolloutConfig; scheduledAt?: string | null; expiresAt?: string | null; /** Flag prerequisites (Flag B only evaluates if Flag A returns variation X) */ prerequisites?: FlagPrerequisite[]; /** Per-environment default value overrides */ environmentDefaults?: Record; /** Exclusion layer key this flag belongs to */ exclusionLayer?: string; /** Whether this flag may be exposed through public browser/client keys. */ clientVisible?: boolean; actor?: AuditActor; } interface UpdateFlagInput { defaultValue?: unknown; description?: string; tags?: string[]; /** * @deprecated Use `setLock(key, { locked, reason, actor })` instead. Passing * `locked` on a currently-locked flag is rejected — see FlagLockedError. */ locked?: boolean; /** @deprecated Use setLock(). */ lockedReason?: string; environments?: string[]; scheduledAt?: string | null; expiresAt?: string | null; /** Exclusion layer key this flag belongs to */ exclusionLayer?: string; /** Whether this flag may be exposed through public browser/client keys. */ clientVisible?: boolean; actor?: AuditActor; } interface SetLockInput { locked: boolean; reason?: string; actor?: AuditActor; } interface ListFlagsInput { namespace?: string; tags?: string[]; status?: FlagStatus; environment?: string; search?: string; /** Only return flags not evaluated since this ISO date (stale flag detection) */ staleAfter?: string; limit?: number; offset?: number; } interface ListFlagsResult { data: Flag[]; total: number; hasMore: boolean; } interface AddRuleInput { name?: string; priority: number; value: unknown; conditions: FlagConditionGroup; enabled?: boolean; rolloutPct?: number; isHoldout?: boolean; variantId?: string; /** Explicit user allow-list — if set, rule only matches these users */ userIds?: string[]; /** Human-readable description of what this rule does */ description?: string; /** Arbitrary metadata (e.g. ticket ID, owner) */ metadata?: Record; actor?: AuditActor; } interface UpdateRuleInput { name?: string; priority?: number; value?: unknown; conditions?: FlagConditionGroup; enabled?: boolean; rolloutPct?: number; isHoldout?: boolean; variantId?: string; /** Explicit user allow-list — if set, rule only matches these users */ userIds?: string[]; /** Human-readable description of what this rule does */ description?: string; /** Arbitrary metadata (e.g. ticket ID, owner) */ metadata?: Record; actor?: AuditActor; } interface RuleOrdering { ruleId: string; priority: number; } interface CreateSegmentInput { key: string; description?: string; rules: FlagConditionGroup; actor?: AuditActor; } interface UpdateSegmentInput { description?: string; rules?: FlagConditionGroup; actor?: AuditActor; } interface CreateReleaseInput { name: string; description?: string; environment?: string; changes: ReleaseChange[]; scheduledAt?: string | null; requiresApproval?: boolean; requiredApprovers?: string[]; actor?: AuditActor; } interface KillFlagInput { reason?: string; killedBy?: string; actor?: AuditActor; } interface RestoreFlagInput { restoredBy?: string; reason?: string; actor?: AuditActor; } interface ArchiveFlagInput { reason?: string; archivedBy?: string; actor?: AuditActor; } interface DeployReleaseInput { deployedBy?: string; actor?: AuditActor; } interface RollbackReleaseInput { rolledBackBy?: string; reason?: string; actor?: AuditActor; } interface CloneFlagInput { newKey: string; includeRules?: boolean; includeRollout?: boolean; actor?: AuditActor; } interface BulkCreateResult { created: Flag[]; errors: Array<{ key: string; error: string; }>; } interface BulkUpdateResult { updated: Flag[]; errors: Array<{ key: string; error: string; }>; } interface WebhookConfig { url: string; secret?: string; events?: HistoryAction[]; headers?: Record; /** Retry configuration. @default { attempts: 3, backoffMs: 500, jitter: true } */ retry?: { attempts?: number; backoffMs?: number; jitter?: boolean; }; /** * Dead-letter queue sink: called with the payload and last error after all * retries are exhausted. Use to persist failed events to a queue or log. */ dlq?: (payload: WebhookPayload, error: Error) => Promise | void; } interface WebhookPayload { event: HistoryAction; flagKey?: string; timestamp: string; data: Record; } interface MultiContext { contexts: Record; primaryKey?: string; } interface ExclusionLayerAllocation { flagKey: string; startBucket: number; endBucket: number; } interface ExclusionLayer { key: string; description?: string; flagKeys: string[]; allocations: ExclusionLayerAllocation[]; } export type { Release as $, AddRuleInput as A, BulkCreateResult as B, CacheAdapter as C, DbAdapter as D, EvalReason as E, Flag as F, FlagResult as G, FlagRule as H, FlagStatus as I, FlagType as J, FlagVariantDef as K, GeoContext as L, GeoIPAdapter as M, HistoryAction as N, HistoryEntry as O, ImpressionConfig as P, InvalidationBus as Q, InvalidationListener as R, InvalidationMessage as S, KillFlagInput as T, ListFlagsInput as U, ListFlagsResult as V, LogLevel as W, LoggingConfig as X, MultiContext as Y, PrivacyConfig as Z, RampStep as _, AnalyticsSink as a, ReleaseAction as a0, ReleaseChange as a1, ReleasePreview as a2, ReleaseSnapshot as a3, ReleaseStatus as a4, ResilienceConfig as a5, RestoreFlagInput as a6, RollbackReleaseInput as a7, RolleaseConfig as a8, RolleaseHealthResult as a9, RolleaseHooks as aa, RolloutConfig as ab, RuleOrdering as ac, Segment as ad, SegmentUsage as ae, SetLockInput as af, TelemetryAdapter as ag, TelemetrySpan as ah, TrackEventInput as ai, TrackingEvent as aj, UpdateFlagInput as ak, UpdateRuleInput as al, UpdateSegmentInput as am, UserId as an, Variant as ao, WebhookConfig as ap, WebhookPayload as aq, ArchiveFlagInput as b, AuditActor as c, AuditConfig as d, AuditEvent as e, AuditSink as f, BulkUpdateResult as g, CacheConfig as h, CloneFlagInput as i, CreateFlagInput as j, CreateReleaseInput as k, CreateSegmentInput as l, DeployReleaseInput as m, DetailedFlagMap as n, EvaluationTrace as o, EvaluationTraceStep as p, ExclusionLayer as q, ExclusionLayerAllocation as r, FlagConditionGroup as s, FlagConditionLeaf as t, FlagContext as u, FlagDimensionKey as v, FlagKey as w, FlagMap as x, FlagOperator as y, FlagPrerequisite as z };