@nexussdk/flags 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/evaluator.ts","../src/sse-manager.ts","../src/storage.ts","../src/client.ts"],"names":["murmur3","key","seed","h","c1","c2","i","length4","k","k2","rem","computeRolloutBucket","userId","flagKey","hashInput","compareSemver","a","b","partsA","partsB","diff","resolveAttribute","ctx","attributePath","parts","current","part","evaluateSingleRule","rule","userCtx","userValue","targets","evaluateFlag","flag","SSEManager","options","url","evt","data","event","delay","computeBackoffMs","STORAGE_KEY_PREFIX","ANON_ID_KEY","FlagStorage","apiKeyPrefix","result","flags","value","id","testKey","raw","parsed","NexusFlagsClient","resolveApiKey","resolveBaseUrl","defaultValue","cached","variantKey","user","callback","flagDef","cb","fetchWithRetry","evaluated"],"mappings":"0FAyBO,SAASA,CAAAA,CAAQC,CAAAA,CAAaC,EAAO,CAAA,CAAW,CACrD,IAAIC,CAAAA,CAAID,CAAAA,GAAS,EACXE,CAAAA,CAAK,UAAA,CACLC,CAAAA,CAAK,SAAA,CAEPC,CAAAA,CAAI,CAAA,CAEFC,EAAU,IAAA,CAAK,KAAA,CAAMN,EAAI,MAAA,CAAS,CAAC,EAAI,CAAA,CAC7C,KAAOK,EAAIC,CAAAA,EAAS,CAClB,IAAIC,CAAAA,CACAP,CAAAA,CAAI,WAAWK,CAAC,CAAA,CAAI,KACpBL,CAAAA,CAAI,UAAA,CAAWK,CAAAA,CAAI,CAAC,CAAA,CAAI,GAAA,GAAS,GACjCL,CAAAA,CAAI,UAAA,CAAWK,EAAI,CAAC,CAAA,CAAI,MAAS,EAAA,CAAA,CACjCL,CAAAA,CAAI,WAAWK,CAAAA,CAAI,CAAC,EAAI,GAAA,GAAS,EAAA,CAErCE,EAAI,IAAA,CAAK,IAAA,CAAKA,EAAGJ,CAAE,CAAA,CACnBI,CAAAA,CAAKA,CAAAA,EAAK,EAAA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,UAClB,CAEA,MAAc,YAAA,EAA8B,CAC1C,GAAI,CACF,IAAMO,EAAS,MAAMiB,cAAAA,CAA4C,CAC/D,GAAA,CAAK,CAAA,EAAG,IAAA,CAAK,OAAO,CAAA,kBAAA,CAAA,CACpB,MAAA,CAAQ,MACR,OAAA,CAAS,CACP,cAAe,CAAA,OAAA,EAAU,IAAA,CAAK,MAAM,CAAA,CAAA,CACpC,iBAAA,CAAmB,KAAK,IAAA,CAAK,EAAA,EAAM,OACnC,iBAAA,CAAmB,IAAA,CAAK,KAAK,OAAA,EAAW,EAC1C,CAAA,CACA,SAAA,CAAW,IAAA,CAAK,SAAA,CAChB,WAAY,CACd,CAAC,EAED,IAAA,GAAW,CAAC9D,EAAKgC,CAAI,CAAA,GAAK,OAAO,OAAA,CAAQa,CAAAA,CAAO,IAAI,CAAA,CAAG,CACrD,KAAK,eAAA,CAAgB,GAAA,CAAI7C,EAAKgC,CAAI,CAAA,CAClC,IAAM+B,CAAAA,CAAYhC,CAAAA,CAAaC,CAAAA,CAAM,KAAK,IAAI,CAAA,CAC9C,KAAK,OAAA,CAAQ,GAAA,CAAIhC,EAAK+D,CAAS,CAAA,CAC/B,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI/D,CAAG,GAAG,OAAA,CAAS6D,CAAAA,EAAOA,EAAGE,CAAS,CAAC,EACxD,CACF,CAAA,KAAQ,CAGR,CACF,CACF","file":"index.mjs","sourcesContent":["/**\n * @fileoverview MurmurHash3 32-bit implementation and ABAC rule evaluator.\n * Pure TypeScript — no external dependencies. Implements deterministic rollout bucketing.\n * @module @nexus/sdk-flags/evaluator\n */\n\nimport type { FeatureFlag, FlagEvaluationResult, TargetingRule, UserContext } from '@nexussdk/contracts';\n\n// ---------------------------------------------------------------------------\n// MurmurHash3 32-bit Implementation (Pure TypeScript)\n// Used for deterministic user-to-bucket mapping without server round-trips.\n// ---------------------------------------------------------------------------\n\n/**\n * Converts a string to a Uint32 MurmurHash3 hash.\n * Implements the MurmurHash3 32-bit algorithm (x86 variant).\n *\n * @param key - Input string to hash.\n * @param seed - Optional seed value. Defaults to 0.\n * @returns Unsigned 32-bit integer hash value.\n *\n * @example\n * const hash = murmur3('user123:checkout_v2', 0);\n * const bucket = hash % 100; // 0-99 deterministic bucket\n */\nexport function murmur3(key: string, seed = 0): number {\n let h = seed >>> 0;\n const c1 = 0xcc9e2d51;\n const c2 = 0x1b873593;\n\n let i = 0;\n // Process 4-byte chunks\n const length4 = Math.floor(key.length / 4) * 4;\n while (i < length4) {\n let k =\n ((key.charCodeAt(i) & 0xff)) |\n ((key.charCodeAt(i + 1) & 0xff) << 8) |\n ((key.charCodeAt(i + 2) & 0xff) << 16) |\n ((key.charCodeAt(i + 3) & 0xff) << 24);\n\n k = Math.imul(k, c1);\n k = (k << 15) | (k >>> 17);\n k = Math.imul(k, c2);\n\n h ^= k;\n h = (h << 13) | (h >>> 19);\n h = (Math.imul(h, 5) + 0xe6546b64) >>> 0;\n i += 4;\n }\n\n // Process remaining bytes\n let k2 = 0;\n const rem = key.length & 3;\n if (rem >= 3) k2 ^= (key.charCodeAt(i + 2) & 0xff) << 16;\n if (rem >= 2) k2 ^= (key.charCodeAt(i + 1) & 0xff) << 8;\n if (rem >= 1) {\n k2 ^= key.charCodeAt(i) & 0xff;\n k2 = Math.imul(k2, c1);\n k2 = (k2 << 15) | (k2 >>> 17);\n k2 = Math.imul(k2, c2);\n h ^= k2;\n }\n\n // Finalization mix\n h ^= key.length;\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n\n return h >>> 0; // Ensure unsigned\n}\n\n/**\n * Computes the deterministic rollout bucket (0-99) for a given user+flag combination.\n * Uses MurmurHash3 for even distribution without server state.\n *\n * @param userId - User's unique identifier (anonymous ID if not authenticated).\n * @param flagKey - Flag programmatic key.\n * @returns Bucket value between 0 and 99 (inclusive).\n *\n * @example\n * const bucket = computeRolloutBucket('usr_12345', 'checkout_v2');\n * // isEnabled = bucket < flag.rolloutPercentage\n */\nexport function computeRolloutBucket(userId: string, flagKey: string): number {\n const hashInput = `${userId}:${flagKey}`;\n return murmur3(hashInput) % 100;\n}\n\n// ---------------------------------------------------------------------------\n// ABAC Rule Evaluator\n// ---------------------------------------------------------------------------\n\n/**\n * Performs a simple semantic version comparison.\n * Compares two semver strings in \"MAJOR.MINOR.PATCH\" format.\n *\n * @param a - First version string.\n * @param b - Second version string.\n * @returns Positive if a > b, negative if a < b, 0 if equal.\n */\nfunction compareSemver(a: string, b: string): number {\n const partsA = a.replace(/^v/, '').split('.').map(Number);\n const partsB = b.replace(/^v/, '').split('.').map(Number);\n for (let i = 0; i < 3; i++) {\n const diff = (partsA[i] ?? 0) - (partsB[i] ?? 0);\n if (diff !== 0) return diff;\n }\n return 0;\n}\n\n/**\n * Extracts a nested attribute value from the UserContext by dot-notation path.\n *\n * @param ctx - UserContext object.\n * @param attributePath - Dot-separated path (e.g. \"custom.tier\", \"country\").\n * @returns The attribute value or `undefined` if not found.\n */\nfunction resolveAttribute(ctx: UserContext, attributePath: string): unknown {\n const parts = attributePath.split('.');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let current: any = ctx;\n for (const part of parts) {\n if (current == null || typeof current !== 'object') return undefined;\n current = current[part];\n }\n return current;\n}\n\n/**\n * Evaluates a single targeting rule against the user context.\n *\n * @param rule - The ABAC targeting rule to evaluate.\n * @param userCtx - The current user context.\n * @returns `true` if the rule passes for this user.\n */\nfunction evaluateSingleRule(rule: TargetingRule, userCtx: UserContext): boolean {\n const userValue = resolveAttribute(userCtx, rule.attribute);\n const targets = rule.values;\n\n switch (rule.operator) {\n case 'EQUALS':\n return userValue === targets[0];\n case 'NOT_EQUALS':\n return userValue !== targets[0];\n case 'IN':\n return targets.includes(userValue as string | number | boolean);\n case 'NOT_IN':\n return !targets.includes(userValue as string | number | boolean);\n case 'CONTAINS':\n return typeof userValue === 'string' && userValue.includes(String(targets[0]));\n case 'NOT_CONTAINS':\n return typeof userValue === 'string' && !userValue.includes(String(targets[0]));\n case 'STARTS_WITH':\n return typeof userValue === 'string' && userValue.startsWith(String(targets[0]));\n case 'ENDS_WITH':\n return typeof userValue === 'string' && userValue.endsWith(String(targets[0]));\n case 'GREATER_THAN':\n return typeof userValue === 'number' && userValue > Number(targets[0]);\n case 'LESS_THAN':\n return typeof userValue === 'number' && userValue < Number(targets[0]);\n case 'SEMVER_GTE':\n return (\n typeof userValue === 'string' &&\n typeof targets[0] === 'string' &&\n compareSemver(userValue, String(targets[0])) >= 0\n );\n case 'SEMVER_LTE':\n return (\n typeof userValue === 'string' &&\n typeof targets[0] === 'string' &&\n compareSemver(userValue, String(targets[0])) <= 0\n );\n default:\n return false;\n }\n}\n\n/**\n * Evaluates a FeatureFlag against a UserContext using the full ABAC + rollout engine.\n *\n * Evaluation Order:\n * 1. Kill-switch check (`isEnabled === false` → KILL_SWITCH)\n * 2. All targeting rules must pass (ABAC evaluation)\n * 3. Percentage rollout via MurmurHash3 bucketing\n * 4. Default enabled state\n *\n * @param flag - The feature flag definition from the cache.\n * @param userCtx - Current user context for targeting evaluation.\n * @returns Full {@link FlagEvaluationResult} with reason explanation.\n *\n * @example\n * const result = evaluateFlag(flag, { id: 'usr_12345', country: 'VN' });\n * if (result.enabled) {\n * console.log(result.variants.discount_rate); // 20\n * }\n */\nexport function evaluateFlag(flag: FeatureFlag, userCtx: UserContext): FlagEvaluationResult {\n // Step 1: Kill-switch\n if (!flag.isEnabled) {\n return {\n key: flag.key,\n enabled: false,\n variants: {},\n reason: 'KILL_SWITCH',\n version: flag.version,\n };\n }\n\n // Step 2: ABAC targeting rules — all must pass (AND logic)\n if (flag.targetingRules.length > 0) {\n const allRulesPass = flag.targetingRules.every((rule) =>\n evaluateSingleRule(rule, userCtx),\n );\n if (!allRulesPass) {\n return {\n key: flag.key,\n enabled: false,\n variants: {},\n reason: 'FALLBACK',\n version: flag.version,\n };\n }\n // All targeting rules matched\n if (flag.rolloutPercentage >= 100) {\n return {\n key: flag.key,\n enabled: true,\n variants: flag.variants,\n reason: 'TARGETING_MATCH',\n version: flag.version,\n };\n }\n }\n\n // Step 3: Percentage rollout (MurmurHash3)\n if (flag.rolloutPercentage > 0) {\n const userId = userCtx.id ?? 'anon';\n const bucket = computeRolloutBucket(userId, flag.key);\n if (bucket < flag.rolloutPercentage) {\n return {\n key: flag.key,\n enabled: true,\n variants: flag.variants,\n reason: flag.targetingRules.length > 0 ? 'TARGETING_MATCH' : 'ROLLOUT_MATCH',\n version: flag.version,\n };\n }\n return {\n key: flag.key,\n enabled: false,\n variants: {},\n reason: 'FALLBACK',\n version: flag.version,\n };\n }\n\n // Step 4: Full kill-switch off (rolloutPercentage === 0 with no rules)\n return {\n key: flag.key,\n enabled: false,\n variants: {},\n reason: 'KILL_SWITCH',\n version: flag.version,\n };\n}\n","/**\n * @fileoverview Singleton SSE Manager with ref-counting and auto-reconnect.\n * Ensures exactly one EventSource connection per API key across all flag subscribers.\n * @module @nexus/sdk-flags/sse-manager\n */\n\nimport type { FlagStreamEvent } from '@nexussdk/contracts';\nimport { computeBackoffMs } from '@nexussdk/core';\n\n/**\n * Options for creating an SSE connection.\n */\nexport interface SSEManagerOptions {\n /** Full SSE stream URL (e.g. \"http://localhost:8080/api/v1/flags/stream\"). */\n url: string;\n /** Public API key for authentication. */\n apiKey: string;\n /** Callback invoked for each received flag stream event. */\n onEvent: (event: FlagStreamEvent) => void;\n /** Callback invoked on connection state changes (optional). */\n onStateChange?: (connected: boolean) => void;\n /** Maximum reconnect attempts. Defaults to Infinity. */\n maxReconnects?: number;\n}\n\n/**\n * Ref-counted Singleton SSE Manager.\n *\n * Multiple consumers sharing the same `apiKey` receive updates\n * from a single shared SSE connection. Connection is torn down when all\n * consumers have called `disconnect()`.\n *\n * Connection lifecycle:\n * 1. `connect()` → opens EventSource or streaming fetch\n * 2. On disconnect: exponential backoff reconnect (max 30s)\n * 3. `disconnect()` → decrements ref count; tears down on 0\n *\n * @example\n * const manager = new SSEManager({\n * url: 'http://localhost:8080/api/v1/flags/stream',\n * apiKey: 'pk_live_...',\n * onEvent: (event) => updateCache(event),\n * });\n * manager.connect();\n * // Later:\n * manager.disconnect();\n */\nexport class SSEManager {\n private readonly options: SSEManagerOptions;\n private eventSource: EventSource | null = null;\n private connected = false;\n private destroyed = false;\n private reconnectAttempt = 0;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private readonly maxReconnects: number;\n\n constructor(options: SSEManagerOptions) {\n this.options = options;\n this.maxReconnects = options.maxReconnects ?? Infinity;\n }\n\n /**\n * Returns whether the SSE connection is currently active.\n *\n * @returns `true` if EventSource is open and receiving events.\n */\n get isConnected(): boolean {\n return this.connected;\n }\n\n /**\n * Opens the SSE connection to the Go-Gin stream endpoint.\n * Safe to call multiple times — no-op if already connected.\n *\n * @example\n * manager.connect();\n */\n connect(): void {\n if (this.destroyed || this.connected || this.eventSource) return;\n this.openConnection();\n }\n\n /**\n * Closes the SSE connection and cancels any pending reconnect timers.\n *\n * @example\n * manager.disconnect();\n */\n disconnect(): void {\n this.destroyed = true;\n this.cleanup();\n }\n\n private openConnection(): void {\n if (this.destroyed) return;\n\n try {\n // Append API key as query parameter for SSE (EventSource doesn't support custom headers)\n const url = new URL(this.options.url);\n url.searchParams.set('apiKey', this.options.apiKey);\n\n this.eventSource = new EventSource(url.toString());\n\n this.eventSource.addEventListener('open', () => {\n this.connected = true;\n this.reconnectAttempt = 0;\n this.options.onStateChange?.(true);\n });\n\n this.eventSource.addEventListener('message', (evt: MessageEvent<string>) => {\n this.handleMessage(evt.data);\n });\n\n // Go-Gin sends events with event type 'message' by default\n // Also listen for explicitly typed events\n this.eventSource.addEventListener('flag_update', (evt: MessageEvent<string>) => {\n this.handleMessage(evt.data);\n });\n\n this.eventSource.addEventListener('error', () => {\n this.connected = false;\n this.options.onStateChange?.(false);\n this.cleanup();\n this.scheduleReconnect();\n });\n } catch {\n this.scheduleReconnect();\n }\n }\n\n private handleMessage(data: string): void {\n try {\n const event = JSON.parse(data) as FlagStreamEvent;\n this.options.onEvent(event);\n } catch {\n // Ignore malformed SSE payloads — never crash the host application\n }\n }\n\n private cleanup(): void {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.reconnectTimer !== null) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n }\n\n private scheduleReconnect(): void {\n if (this.destroyed) return;\n if (this.reconnectAttempt >= this.maxReconnects) return;\n\n const delay = computeBackoffMs(this.reconnectAttempt, 1000, 30_000);\n this.reconnectAttempt++;\n\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n if (!this.destroyed) {\n this.openConnection();\n }\n }, delay);\n }\n}\n","/**\n * @fileoverview In-memory flag storage with LocalStorage sync and incognito fallback.\n * @module @nexus/sdk-flags/storage\n */\n\nimport type { FlagEvaluationResult } from '@nexussdk/contracts';\n\nconst STORAGE_KEY_PREFIX = 'nexus_flags_';\nconst ANON_ID_KEY = 'nexus_anon_id';\n\n/**\n * In-memory flag cache with optional LocalStorage persistence.\n * Falls back to pure in-memory storage in SSR / Incognito / Worker contexts.\n *\n * @example\n * const store = new FlagStorage('pk_live_abc123');\n * store.set('checkout_v2', { key: 'checkout_v2', enabled: true, variants: {}, reason: 'ROLLOUT_MATCH', version: 3 });\n * const result = store.get('checkout_v2');\n */\nexport class FlagStorage {\n private readonly memory = new Map<string, FlagEvaluationResult>();\n private readonly storageKey: string;\n private readonly localStorageAvailable: boolean;\n private broadcastChannel: BroadcastChannel | null = null;\n\n constructor(apiKeyPrefix: string) {\n this.storageKey = `${STORAGE_KEY_PREFIX}${apiKeyPrefix}`;\n this.localStorageAvailable = this.testLocalStorage();\n this.hydrate();\n this.setupBroadcastChannel();\n }\n\n /**\n * Stores a flag evaluation result in memory (and localStorage if available).\n *\n * @param key - Flag programmatic key.\n * @param result - Evaluation result to persist.\n */\n set(key: string, result: FlagEvaluationResult): void {\n this.memory.set(key, result);\n this.persist();\n this.broadcastUpdate(key, result);\n }\n\n /**\n * Retrieves a flag evaluation result by key.\n *\n * @param key - Flag programmatic key.\n * @returns The cached evaluation result or `undefined`.\n */\n get(key: string): FlagEvaluationResult | undefined {\n return this.memory.get(key);\n }\n\n /**\n * Bulk-sets multiple flag results (e.g. after a batch fetch).\n *\n * @param flags - Record of flag key → evaluation result.\n */\n setAll(flags: Record<string, FlagEvaluationResult>): void {\n for (const [key, value] of Object.entries(flags)) {\n this.memory.set(key, value);\n }\n this.persist();\n }\n\n /**\n * Removes a single flag from storage (e.g. on FLAG_DELETE SSE event).\n *\n * @param key - Flag programmatic key.\n */\n delete(key: string): void {\n this.memory.delete(key);\n this.persist();\n }\n\n /**\n * Returns all cached flag results.\n *\n * @returns All stored flag results as a record.\n */\n getAll(): Record<string, FlagEvaluationResult> {\n return Object.fromEntries(this.memory.entries());\n }\n\n /**\n * Clears all cached flags from memory and localStorage.\n */\n clear(): void {\n this.memory.clear();\n if (this.localStorageAvailable) {\n try {\n window.localStorage.removeItem(this.storageKey);\n } catch {\n // Storage access denied\n }\n }\n this.broadcastChannel?.close();\n }\n\n /**\n * Retrieves or creates a persistent anonymous user ID.\n *\n * @returns Anonymous ID string (e.g. \"anon_xyz123abc\").\n */\n getOrCreateAnonymousId(): string {\n if (typeof window === 'undefined') return 'anon-ssr-node';\n\n if (this.localStorageAvailable) {\n try {\n let id = window.localStorage.getItem(ANON_ID_KEY);\n if (!id) {\n id = `anon_${Math.random().toString(36).substring(2, 11)}`;\n window.localStorage.setItem(ANON_ID_KEY, id);\n }\n return id;\n } catch {\n // Incognito / locked storage\n }\n }\n\n return `anon_${Math.random().toString(36).substring(2, 11)}`;\n }\n\n private testLocalStorage(): boolean {\n try {\n if (typeof window === 'undefined') return false;\n const testKey = '__nexus_test__';\n window.localStorage.setItem(testKey, '1');\n window.localStorage.removeItem(testKey);\n return true;\n } catch {\n return false;\n }\n }\n\n private hydrate(): void {\n if (!this.localStorageAvailable) return;\n try {\n const raw = window.localStorage.getItem(this.storageKey);\n if (raw) {\n const parsed = JSON.parse(raw) as Record<string, FlagEvaluationResult>;\n for (const [key, value] of Object.entries(parsed)) {\n this.memory.set(key, value);\n }\n }\n } catch {\n // Corrupt storage — start fresh\n }\n }\n\n private persist(): void {\n if (!this.localStorageAvailable) return;\n try {\n window.localStorage.setItem(\n this.storageKey,\n JSON.stringify(Object.fromEntries(this.memory.entries())),\n );\n } catch {\n // Storage quota exceeded — in-memory only\n }\n }\n\n private setupBroadcastChannel(): void {\n try {\n if (typeof BroadcastChannel !== 'undefined') {\n this.broadcastChannel = new BroadcastChannel(`nexus_flags_${this.storageKey}`);\n this.broadcastChannel.onmessage = (evt: MessageEvent<{ key: string; result: FlagEvaluationResult }>) => {\n // Sync updates from other tabs into local memory cache\n if (evt.data?.key && evt.data?.result) {\n this.memory.set(evt.data.key, evt.data.result);\n }\n };\n }\n } catch {\n // BroadcastChannel unavailable (e.g. Worker context)\n }\n }\n\n private broadcastUpdate(key: string, result: FlagEvaluationResult): void {\n try {\n this.broadcastChannel?.postMessage({ key, result });\n } catch {\n // Broadcast failed — no-op\n }\n }\n}\n","/**\n * @fileoverview NexusFlagsClient — Full-featured feature flags SDK client.\n * In-memory evaluation, SSE real-time sync, ABAC targeting, and MurmurHash3 rollout.\n * @module @nexus/sdk-flags/client\n */\n\nimport type {\n FlagEvaluationResult,\n FlagVariants,\n FeatureFlag,\n UserContext,\n} from '@nexussdk/contracts';\nimport { resolveApiKey, resolveBaseUrl, fetchWithRetry } from '@nexussdk/core';\nimport { evaluateFlag } from './evaluator.js';\nimport { SSEManager } from './sse-manager.js';\nimport { FlagStorage } from './storage.js';\n\n/**\n * Options for initializing the NexusFlagsClient.\n *\n * @example\n * const client = new NexusFlagsClient({\n * apiKey: 'pk_live_...',\n * baseUrl: 'http://localhost:8080',\n * user: { id: 'usr_12345', country: 'VN' },\n * realtime: true,\n * });\n */\nexport interface NexusFlagsOptions {\n /**\n * Public API Key ('pk_live_...' or 'pk_test_...').\n * If omitted, resolved automatically via env variables.\n */\n apiKey?: string;\n /**\n * Base ingestion URL. Defaults to 'https://api.nexus.dev'.\n */\n baseUrl?: string;\n /**\n * Initial user identity context for targeting and percentage rollouts.\n */\n user?: UserContext;\n /**\n * Pre-hydrated flags evaluated on the server (SSR) to prevent client-side UI flicker.\n */\n bootstrap?: Record<string, FlagEvaluationResult>;\n /**\n * Toggle real-time SSE updates. Defaults to true.\n */\n realtime?: boolean;\n /**\n * Network timeout in milliseconds for evaluation fetch. Defaults to 3000ms.\n */\n timeoutMs?: number;\n}\n\n/**\n * Public interface for the NexusFlagsClient.\n */\nexport interface INexusFlagsClient {\n /**\n * Synchronously checks if a flag is active for the current user.\n *\n * @param key - Unique flag identifier.\n * @param defaultValue - Fallback returned if flag is absent or evaluating.\n * @returns `true` if the flag is enabled.\n *\n * @example\n * const showBanner = client.isEnabled('promo_banner_v2', false);\n */\n isEnabled(key: string, defaultValue?: boolean): boolean;\n\n /**\n * Synchronously retrieves a specific dynamic configuration variant.\n *\n * @param key - Unique flag identifier.\n * @param variantKey - Property inside the variant object.\n * @param defaultValue - Fallback returned if flag/variant is missing.\n * @returns The variant value cast to type T.\n *\n * @example\n * const rate = client.getVariant<number>('promo_banner_v2', 'discount_rate', 10);\n */\n getVariant<T = unknown>(key: string, variantKey: string, defaultValue?: T): T;\n\n /**\n * Updates current user context and re-evaluates all flags.\n *\n * @param user - New user context to apply.\n * @returns Promise that resolves after flags are refreshed.\n *\n * @example\n * await client.identify({ id: 'usr_99', country: 'SG' });\n */\n identify(user: UserContext): Promise<void>;\n\n /**\n * Resets user context to an anonymous persistent device identifier.\n *\n * @example\n * client.reset(); // called on logout\n */\n reset(): void;\n\n /**\n * Subscribes to runtime flag changes triggered by SSE updates.\n *\n * @param key - Flag key to observe.\n * @param callback - Called with new evaluation result when the flag changes.\n * @returns Unsubscribe function — call to remove the listener.\n *\n * @example\n * const unsub = client.onFlagChange('checkout_v2', (result) => {\n * setCheckoutEnabled(result.enabled);\n * });\n * // On component unmount:\n * unsub();\n */\n onFlagChange(key: string, callback: (result: FlagEvaluationResult) => void): () => void;\n\n /**\n * Gracefully shuts down active SSE connections and observers.\n *\n * @example\n * client.destroy();\n */\n destroy(): void;\n}\n\n/**\n * Feature Flags Client — the primary SDK entry point for flag evaluation.\n *\n * @implements {INexusFlagsClient}\n *\n * @example\n * const client = new NexusFlagsClient({ apiKey: 'pk_live_...' });\n * const enabled = client.isEnabled('new_checkout', false);\n */\nexport class NexusFlagsClient implements INexusFlagsClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private user: UserContext;\n private readonly storage: FlagStorage;\n private readonly listeners = new Map<string, Set<(res: FlagEvaluationResult) => void>>();\n private sseManager?: SSEManager;\n private flagDefinitions = new Map<string, FeatureFlag>();\n\n constructor(options: NexusFlagsOptions = {}) {\n this.apiKey = resolveApiKey(options.apiKey);\n this.baseUrl = resolveBaseUrl(options.baseUrl);\n this.timeoutMs = options.timeoutMs ?? 3_000;\n this.storage = new FlagStorage(this.apiKey.substring(0, 16));\n this.user = options.user ?? { id: this.storage.getOrCreateAnonymousId() };\n\n // Hydrate bootstrap flags (SSR pre-evaluation)\n if (options.bootstrap) {\n this.storage.setAll(options.bootstrap);\n }\n\n if (options.realtime !== false) {\n this.initRealtimeSync();\n }\n\n // Prefetch flags asynchronously on init\n void this.refreshFlags();\n }\n\n /**\n * Evaluates whether a given feature flag is enabled for the current context.\n */\n public isEnabled(key: string, defaultValue = false): boolean {\n const cached = this.storage.get(key);\n return cached !== undefined ? cached.enabled : defaultValue;\n }\n\n /**\n * Retrieves a typed variant configuration for an active feature flag.\n */\n public getVariant<T = unknown>(key: string, variantKey: string, defaultValue?: T): T {\n const cached = this.storage.get(key);\n if (!cached?.enabled || !cached.variants) {\n return defaultValue as T;\n }\n const value = (cached.variants as FlagVariants)[variantKey];\n return value !== undefined ? (value as T) : (defaultValue as T);\n }\n\n /**\n * Identifies an authenticated user and triggers a flag evaluation refresh.\n */\n public async identify(user: UserContext): Promise<void> {\n this.user = { ...this.user, ...user };\n await this.refreshFlags();\n }\n\n /**\n * Resets the active user context to a new anonymous identifier.\n */\n public reset(): void {\n this.user = { id: this.storage.getOrCreateAnonymousId() };\n void this.refreshFlags();\n }\n\n /**\n * Registers a listener callback invoked when a flag's evaluation state changes.\n */\n public onFlagChange(key: string, callback: (result: FlagEvaluationResult) => void): () => void {\n if (!this.listeners.has(key)) {\n this.listeners.set(key, new Set());\n }\n this.listeners.get(key)!.add(callback);\n return () => this.listeners.get(key)?.delete(callback);\n }\n\n /**\n * Destroys the client, terminating SSE connections and clearing listeners.\n */\n public destroy(): void {\n this.sseManager?.disconnect();\n this.listeners.clear();\n this.storage.clear();\n }\n\n private initRealtimeSync(): void {\n this.sseManager = new SSEManager({\n url: `${this.baseUrl}/api/v1/flags/stream`,\n apiKey: this.apiKey,\n onEvent: (event) => {\n if (event.type === 'FLAG_UPDATE' && event.data) {\n // Use locally evaluated result if we have the flag definition\n const flagDef = this.flagDefinitions.get(event.key);\n const result = flagDef\n ? evaluateFlag(flagDef, this.user)\n : event.data;\n\n this.storage.set(event.key, result);\n this.listeners.get(event.key)?.forEach((cb) => cb(result));\n } else if (event.type === 'FLAG_DELETE') {\n this.storage.delete(event.key);\n this.flagDefinitions.delete(event.key);\n }\n },\n });\n this.sseManager.connect();\n }\n\n private async refreshFlags(): Promise<void> {\n try {\n const result = await fetchWithRetry<Record<string, FeatureFlag>>({\n url: `${this.baseUrl}/api/v1/flags/eval`,\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Nexus-User-Id': this.user.id ?? 'anon',\n 'X-Nexus-Country': this.user.country ?? '',\n },\n timeoutMs: this.timeoutMs,\n maxRetries: 2,\n });\n\n for (const [key, flag] of Object.entries(result.data)) {\n this.flagDefinitions.set(key, flag);\n const evaluated = evaluateFlag(flag, this.user);\n this.storage.set(key, evaluated);\n this.listeners.get(key)?.forEach((cb) => cb(evaluated));\n }\n } catch {\n // Offline fallback: retain existing in-memory cache silently\n // Never throw from a background refresh — host app must not be affected\n }\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@nexussdk/flags",
3
+ "version": "0.0.1",
4
+ "private": false,
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "description": "Ultra-lightweight feature flags and remote config client SDK for browsers and edge runtimes",
9
+ "main": "./dist/index.cjs",
10
+ "module": "./dist/index.mjs",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.mjs",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "@nexussdk/contracts": "0.0.1",
21
+ "@nexussdk/core": "0.0.1"
22
+ },
23
+ "devDependencies": {
24
+ "tsup": "^8.0.2",
25
+ "typescript": "^5.4.5",
26
+ "rimraf": "^5.0.5"
27
+ },
28
+ "scripts": {
29
+ "build": "tsup",
30
+ "dev": "tsup --watch",
31
+ "lint": "tsc --noEmit",
32
+ "clean": "rimraf dist"
33
+ }
34
+ }
package/src/client.ts ADDED
@@ -0,0 +1,273 @@
1
+ /**
2
+ * @fileoverview NexusFlagsClient — Full-featured feature flags SDK client.
3
+ * In-memory evaluation, SSE real-time sync, ABAC targeting, and MurmurHash3 rollout.
4
+ * @module @nexus/sdk-flags/client
5
+ */
6
+
7
+ import type {
8
+ FlagEvaluationResult,
9
+ FlagVariants,
10
+ FeatureFlag,
11
+ UserContext,
12
+ } from '@nexussdk/contracts';
13
+ import { resolveApiKey, resolveBaseUrl, fetchWithRetry } from '@nexussdk/core';
14
+ import { evaluateFlag } from './evaluator.js';
15
+ import { SSEManager } from './sse-manager.js';
16
+ import { FlagStorage } from './storage.js';
17
+
18
+ /**
19
+ * Options for initializing the NexusFlagsClient.
20
+ *
21
+ * @example
22
+ * const client = new NexusFlagsClient({
23
+ * apiKey: 'pk_live_...',
24
+ * baseUrl: 'http://localhost:8080',
25
+ * user: { id: 'usr_12345', country: 'VN' },
26
+ * realtime: true,
27
+ * });
28
+ */
29
+ export interface NexusFlagsOptions {
30
+ /**
31
+ * Public API Key ('pk_live_...' or 'pk_test_...').
32
+ * If omitted, resolved automatically via env variables.
33
+ */
34
+ apiKey?: string;
35
+ /**
36
+ * Base ingestion URL. Defaults to 'https://api.nexus.dev'.
37
+ */
38
+ baseUrl?: string;
39
+ /**
40
+ * Initial user identity context for targeting and percentage rollouts.
41
+ */
42
+ user?: UserContext;
43
+ /**
44
+ * Pre-hydrated flags evaluated on the server (SSR) to prevent client-side UI flicker.
45
+ */
46
+ bootstrap?: Record<string, FlagEvaluationResult>;
47
+ /**
48
+ * Toggle real-time SSE updates. Defaults to true.
49
+ */
50
+ realtime?: boolean;
51
+ /**
52
+ * Network timeout in milliseconds for evaluation fetch. Defaults to 3000ms.
53
+ */
54
+ timeoutMs?: number;
55
+ }
56
+
57
+ /**
58
+ * Public interface for the NexusFlagsClient.
59
+ */
60
+ export interface INexusFlagsClient {
61
+ /**
62
+ * Synchronously checks if a flag is active for the current user.
63
+ *
64
+ * @param key - Unique flag identifier.
65
+ * @param defaultValue - Fallback returned if flag is absent or evaluating.
66
+ * @returns `true` if the flag is enabled.
67
+ *
68
+ * @example
69
+ * const showBanner = client.isEnabled('promo_banner_v2', false);
70
+ */
71
+ isEnabled(key: string, defaultValue?: boolean): boolean;
72
+
73
+ /**
74
+ * Synchronously retrieves a specific dynamic configuration variant.
75
+ *
76
+ * @param key - Unique flag identifier.
77
+ * @param variantKey - Property inside the variant object.
78
+ * @param defaultValue - Fallback returned if flag/variant is missing.
79
+ * @returns The variant value cast to type T.
80
+ *
81
+ * @example
82
+ * const rate = client.getVariant<number>('promo_banner_v2', 'discount_rate', 10);
83
+ */
84
+ getVariant<T = unknown>(key: string, variantKey: string, defaultValue?: T): T;
85
+
86
+ /**
87
+ * Updates current user context and re-evaluates all flags.
88
+ *
89
+ * @param user - New user context to apply.
90
+ * @returns Promise that resolves after flags are refreshed.
91
+ *
92
+ * @example
93
+ * await client.identify({ id: 'usr_99', country: 'SG' });
94
+ */
95
+ identify(user: UserContext): Promise<void>;
96
+
97
+ /**
98
+ * Resets user context to an anonymous persistent device identifier.
99
+ *
100
+ * @example
101
+ * client.reset(); // called on logout
102
+ */
103
+ reset(): void;
104
+
105
+ /**
106
+ * Subscribes to runtime flag changes triggered by SSE updates.
107
+ *
108
+ * @param key - Flag key to observe.
109
+ * @param callback - Called with new evaluation result when the flag changes.
110
+ * @returns Unsubscribe function — call to remove the listener.
111
+ *
112
+ * @example
113
+ * const unsub = client.onFlagChange('checkout_v2', (result) => {
114
+ * setCheckoutEnabled(result.enabled);
115
+ * });
116
+ * // On component unmount:
117
+ * unsub();
118
+ */
119
+ onFlagChange(key: string, callback: (result: FlagEvaluationResult) => void): () => void;
120
+
121
+ /**
122
+ * Gracefully shuts down active SSE connections and observers.
123
+ *
124
+ * @example
125
+ * client.destroy();
126
+ */
127
+ destroy(): void;
128
+ }
129
+
130
+ /**
131
+ * Feature Flags Client — the primary SDK entry point for flag evaluation.
132
+ *
133
+ * @implements {INexusFlagsClient}
134
+ *
135
+ * @example
136
+ * const client = new NexusFlagsClient({ apiKey: 'pk_live_...' });
137
+ * const enabled = client.isEnabled('new_checkout', false);
138
+ */
139
+ export class NexusFlagsClient implements INexusFlagsClient {
140
+ private readonly apiKey: string;
141
+ private readonly baseUrl: string;
142
+ private readonly timeoutMs: number;
143
+ private user: UserContext;
144
+ private readonly storage: FlagStorage;
145
+ private readonly listeners = new Map<string, Set<(res: FlagEvaluationResult) => void>>();
146
+ private sseManager?: SSEManager;
147
+ private flagDefinitions = new Map<string, FeatureFlag>();
148
+
149
+ constructor(options: NexusFlagsOptions = {}) {
150
+ this.apiKey = resolveApiKey(options.apiKey);
151
+ this.baseUrl = resolveBaseUrl(options.baseUrl);
152
+ this.timeoutMs = options.timeoutMs ?? 3_000;
153
+ this.storage = new FlagStorage(this.apiKey.substring(0, 16));
154
+ this.user = options.user ?? { id: this.storage.getOrCreateAnonymousId() };
155
+
156
+ // Hydrate bootstrap flags (SSR pre-evaluation)
157
+ if (options.bootstrap) {
158
+ this.storage.setAll(options.bootstrap);
159
+ }
160
+
161
+ if (options.realtime !== false) {
162
+ this.initRealtimeSync();
163
+ }
164
+
165
+ // Prefetch flags asynchronously on init
166
+ void this.refreshFlags();
167
+ }
168
+
169
+ /**
170
+ * Evaluates whether a given feature flag is enabled for the current context.
171
+ */
172
+ public isEnabled(key: string, defaultValue = false): boolean {
173
+ const cached = this.storage.get(key);
174
+ return cached !== undefined ? cached.enabled : defaultValue;
175
+ }
176
+
177
+ /**
178
+ * Retrieves a typed variant configuration for an active feature flag.
179
+ */
180
+ public getVariant<T = unknown>(key: string, variantKey: string, defaultValue?: T): T {
181
+ const cached = this.storage.get(key);
182
+ if (!cached?.enabled || !cached.variants) {
183
+ return defaultValue as T;
184
+ }
185
+ const value = (cached.variants as FlagVariants)[variantKey];
186
+ return value !== undefined ? (value as T) : (defaultValue as T);
187
+ }
188
+
189
+ /**
190
+ * Identifies an authenticated user and triggers a flag evaluation refresh.
191
+ */
192
+ public async identify(user: UserContext): Promise<void> {
193
+ this.user = { ...this.user, ...user };
194
+ await this.refreshFlags();
195
+ }
196
+
197
+ /**
198
+ * Resets the active user context to a new anonymous identifier.
199
+ */
200
+ public reset(): void {
201
+ this.user = { id: this.storage.getOrCreateAnonymousId() };
202
+ void this.refreshFlags();
203
+ }
204
+
205
+ /**
206
+ * Registers a listener callback invoked when a flag's evaluation state changes.
207
+ */
208
+ public onFlagChange(key: string, callback: (result: FlagEvaluationResult) => void): () => void {
209
+ if (!this.listeners.has(key)) {
210
+ this.listeners.set(key, new Set());
211
+ }
212
+ this.listeners.get(key)!.add(callback);
213
+ return () => this.listeners.get(key)?.delete(callback);
214
+ }
215
+
216
+ /**
217
+ * Destroys the client, terminating SSE connections and clearing listeners.
218
+ */
219
+ public destroy(): void {
220
+ this.sseManager?.disconnect();
221
+ this.listeners.clear();
222
+ this.storage.clear();
223
+ }
224
+
225
+ private initRealtimeSync(): void {
226
+ this.sseManager = new SSEManager({
227
+ url: `${this.baseUrl}/api/v1/flags/stream`,
228
+ apiKey: this.apiKey,
229
+ onEvent: (event) => {
230
+ if (event.type === 'FLAG_UPDATE' && event.data) {
231
+ // Use locally evaluated result if we have the flag definition
232
+ const flagDef = this.flagDefinitions.get(event.key);
233
+ const result = flagDef
234
+ ? evaluateFlag(flagDef, this.user)
235
+ : event.data;
236
+
237
+ this.storage.set(event.key, result);
238
+ this.listeners.get(event.key)?.forEach((cb) => cb(result));
239
+ } else if (event.type === 'FLAG_DELETE') {
240
+ this.storage.delete(event.key);
241
+ this.flagDefinitions.delete(event.key);
242
+ }
243
+ },
244
+ });
245
+ this.sseManager.connect();
246
+ }
247
+
248
+ private async refreshFlags(): Promise<void> {
249
+ try {
250
+ const result = await fetchWithRetry<Record<string, FeatureFlag>>({
251
+ url: `${this.baseUrl}/api/v1/flags/eval`,
252
+ method: 'GET',
253
+ headers: {
254
+ Authorization: `Bearer ${this.apiKey}`,
255
+ 'X-Nexus-User-Id': this.user.id ?? 'anon',
256
+ 'X-Nexus-Country': this.user.country ?? '',
257
+ },
258
+ timeoutMs: this.timeoutMs,
259
+ maxRetries: 2,
260
+ });
261
+
262
+ for (const [key, flag] of Object.entries(result.data)) {
263
+ this.flagDefinitions.set(key, flag);
264
+ const evaluated = evaluateFlag(flag, this.user);
265
+ this.storage.set(key, evaluated);
266
+ this.listeners.get(key)?.forEach((cb) => cb(evaluated));
267
+ }
268
+ } catch {
269
+ // Offline fallback: retain existing in-memory cache silently
270
+ // Never throw from a background refresh — host app must not be affected
271
+ }
272
+ }
273
+ }
@@ -0,0 +1,268 @@
1
+ /**
2
+ * @fileoverview MurmurHash3 32-bit implementation and ABAC rule evaluator.
3
+ * Pure TypeScript — no external dependencies. Implements deterministic rollout bucketing.
4
+ * @module @nexus/sdk-flags/evaluator
5
+ */
6
+
7
+ import type { FeatureFlag, FlagEvaluationResult, TargetingRule, UserContext } from '@nexussdk/contracts';
8
+
9
+ // ---------------------------------------------------------------------------
10
+ // MurmurHash3 32-bit Implementation (Pure TypeScript)
11
+ // Used for deterministic user-to-bucket mapping without server round-trips.
12
+ // ---------------------------------------------------------------------------
13
+
14
+ /**
15
+ * Converts a string to a Uint32 MurmurHash3 hash.
16
+ * Implements the MurmurHash3 32-bit algorithm (x86 variant).
17
+ *
18
+ * @param key - Input string to hash.
19
+ * @param seed - Optional seed value. Defaults to 0.
20
+ * @returns Unsigned 32-bit integer hash value.
21
+ *
22
+ * @example
23
+ * const hash = murmur3('user123:checkout_v2', 0);
24
+ * const bucket = hash % 100; // 0-99 deterministic bucket
25
+ */
26
+ export function murmur3(key: string, seed = 0): number {
27
+ let h = seed >>> 0;
28
+ const c1 = 0xcc9e2d51;
29
+ const c2 = 0x1b873593;
30
+
31
+ let i = 0;
32
+ // Process 4-byte chunks
33
+ const length4 = Math.floor(key.length / 4) * 4;
34
+ while (i < length4) {
35
+ let k =
36
+ ((key.charCodeAt(i) & 0xff)) |
37
+ ((key.charCodeAt(i + 1) & 0xff) << 8) |
38
+ ((key.charCodeAt(i + 2) & 0xff) << 16) |
39
+ ((key.charCodeAt(i + 3) & 0xff) << 24);
40
+
41
+ k = Math.imul(k, c1);
42
+ k = (k << 15) | (k >>> 17);
43
+ k = Math.imul(k, c2);
44
+
45
+ h ^= k;
46
+ h = (h << 13) | (h >>> 19);
47
+ h = (Math.imul(h, 5) + 0xe6546b64) >>> 0;
48
+ i += 4;
49
+ }
50
+
51
+ // Process remaining bytes
52
+ let k2 = 0;
53
+ const rem = key.length & 3;
54
+ if (rem >= 3) k2 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
55
+ if (rem >= 2) k2 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
56
+ if (rem >= 1) {
57
+ k2 ^= key.charCodeAt(i) & 0xff;
58
+ k2 = Math.imul(k2, c1);
59
+ k2 = (k2 << 15) | (k2 >>> 17);
60
+ k2 = Math.imul(k2, c2);
61
+ h ^= k2;
62
+ }
63
+
64
+ // Finalization mix
65
+ h ^= key.length;
66
+ h ^= h >>> 16;
67
+ h = Math.imul(h, 0x85ebca6b);
68
+ h ^= h >>> 13;
69
+ h = Math.imul(h, 0xc2b2ae35);
70
+ h ^= h >>> 16;
71
+
72
+ return h >>> 0; // Ensure unsigned
73
+ }
74
+
75
+ /**
76
+ * Computes the deterministic rollout bucket (0-99) for a given user+flag combination.
77
+ * Uses MurmurHash3 for even distribution without server state.
78
+ *
79
+ * @param userId - User's unique identifier (anonymous ID if not authenticated).
80
+ * @param flagKey - Flag programmatic key.
81
+ * @returns Bucket value between 0 and 99 (inclusive).
82
+ *
83
+ * @example
84
+ * const bucket = computeRolloutBucket('usr_12345', 'checkout_v2');
85
+ * // isEnabled = bucket < flag.rolloutPercentage
86
+ */
87
+ export function computeRolloutBucket(userId: string, flagKey: string): number {
88
+ const hashInput = `${userId}:${flagKey}`;
89
+ return murmur3(hashInput) % 100;
90
+ }
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // ABAC Rule Evaluator
94
+ // ---------------------------------------------------------------------------
95
+
96
+ /**
97
+ * Performs a simple semantic version comparison.
98
+ * Compares two semver strings in "MAJOR.MINOR.PATCH" format.
99
+ *
100
+ * @param a - First version string.
101
+ * @param b - Second version string.
102
+ * @returns Positive if a > b, negative if a < b, 0 if equal.
103
+ */
104
+ function compareSemver(a: string, b: string): number {
105
+ const partsA = a.replace(/^v/, '').split('.').map(Number);
106
+ const partsB = b.replace(/^v/, '').split('.').map(Number);
107
+ for (let i = 0; i < 3; i++) {
108
+ const diff = (partsA[i] ?? 0) - (partsB[i] ?? 0);
109
+ if (diff !== 0) return diff;
110
+ }
111
+ return 0;
112
+ }
113
+
114
+ /**
115
+ * Extracts a nested attribute value from the UserContext by dot-notation path.
116
+ *
117
+ * @param ctx - UserContext object.
118
+ * @param attributePath - Dot-separated path (e.g. "custom.tier", "country").
119
+ * @returns The attribute value or `undefined` if not found.
120
+ */
121
+ function resolveAttribute(ctx: UserContext, attributePath: string): unknown {
122
+ const parts = attributePath.split('.');
123
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
124
+ let current: any = ctx;
125
+ for (const part of parts) {
126
+ if (current == null || typeof current !== 'object') return undefined;
127
+ current = current[part];
128
+ }
129
+ return current;
130
+ }
131
+
132
+ /**
133
+ * Evaluates a single targeting rule against the user context.
134
+ *
135
+ * @param rule - The ABAC targeting rule to evaluate.
136
+ * @param userCtx - The current user context.
137
+ * @returns `true` if the rule passes for this user.
138
+ */
139
+ function evaluateSingleRule(rule: TargetingRule, userCtx: UserContext): boolean {
140
+ const userValue = resolveAttribute(userCtx, rule.attribute);
141
+ const targets = rule.values;
142
+
143
+ switch (rule.operator) {
144
+ case 'EQUALS':
145
+ return userValue === targets[0];
146
+ case 'NOT_EQUALS':
147
+ return userValue !== targets[0];
148
+ case 'IN':
149
+ return targets.includes(userValue as string | number | boolean);
150
+ case 'NOT_IN':
151
+ return !targets.includes(userValue as string | number | boolean);
152
+ case 'CONTAINS':
153
+ return typeof userValue === 'string' && userValue.includes(String(targets[0]));
154
+ case 'NOT_CONTAINS':
155
+ return typeof userValue === 'string' && !userValue.includes(String(targets[0]));
156
+ case 'STARTS_WITH':
157
+ return typeof userValue === 'string' && userValue.startsWith(String(targets[0]));
158
+ case 'ENDS_WITH':
159
+ return typeof userValue === 'string' && userValue.endsWith(String(targets[0]));
160
+ case 'GREATER_THAN':
161
+ return typeof userValue === 'number' && userValue > Number(targets[0]);
162
+ case 'LESS_THAN':
163
+ return typeof userValue === 'number' && userValue < Number(targets[0]);
164
+ case 'SEMVER_GTE':
165
+ return (
166
+ typeof userValue === 'string' &&
167
+ typeof targets[0] === 'string' &&
168
+ compareSemver(userValue, String(targets[0])) >= 0
169
+ );
170
+ case 'SEMVER_LTE':
171
+ return (
172
+ typeof userValue === 'string' &&
173
+ typeof targets[0] === 'string' &&
174
+ compareSemver(userValue, String(targets[0])) <= 0
175
+ );
176
+ default:
177
+ return false;
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Evaluates a FeatureFlag against a UserContext using the full ABAC + rollout engine.
183
+ *
184
+ * Evaluation Order:
185
+ * 1. Kill-switch check (`isEnabled === false` → KILL_SWITCH)
186
+ * 2. All targeting rules must pass (ABAC evaluation)
187
+ * 3. Percentage rollout via MurmurHash3 bucketing
188
+ * 4. Default enabled state
189
+ *
190
+ * @param flag - The feature flag definition from the cache.
191
+ * @param userCtx - Current user context for targeting evaluation.
192
+ * @returns Full {@link FlagEvaluationResult} with reason explanation.
193
+ *
194
+ * @example
195
+ * const result = evaluateFlag(flag, { id: 'usr_12345', country: 'VN' });
196
+ * if (result.enabled) {
197
+ * console.log(result.variants.discount_rate); // 20
198
+ * }
199
+ */
200
+ export function evaluateFlag(flag: FeatureFlag, userCtx: UserContext): FlagEvaluationResult {
201
+ // Step 1: Kill-switch
202
+ if (!flag.isEnabled) {
203
+ return {
204
+ key: flag.key,
205
+ enabled: false,
206
+ variants: {},
207
+ reason: 'KILL_SWITCH',
208
+ version: flag.version,
209
+ };
210
+ }
211
+
212
+ // Step 2: ABAC targeting rules — all must pass (AND logic)
213
+ if (flag.targetingRules.length > 0) {
214
+ const allRulesPass = flag.targetingRules.every((rule) =>
215
+ evaluateSingleRule(rule, userCtx),
216
+ );
217
+ if (!allRulesPass) {
218
+ return {
219
+ key: flag.key,
220
+ enabled: false,
221
+ variants: {},
222
+ reason: 'FALLBACK',
223
+ version: flag.version,
224
+ };
225
+ }
226
+ // All targeting rules matched
227
+ if (flag.rolloutPercentage >= 100) {
228
+ return {
229
+ key: flag.key,
230
+ enabled: true,
231
+ variants: flag.variants,
232
+ reason: 'TARGETING_MATCH',
233
+ version: flag.version,
234
+ };
235
+ }
236
+ }
237
+
238
+ // Step 3: Percentage rollout (MurmurHash3)
239
+ if (flag.rolloutPercentage > 0) {
240
+ const userId = userCtx.id ?? 'anon';
241
+ const bucket = computeRolloutBucket(userId, flag.key);
242
+ if (bucket < flag.rolloutPercentage) {
243
+ return {
244
+ key: flag.key,
245
+ enabled: true,
246
+ variants: flag.variants,
247
+ reason: flag.targetingRules.length > 0 ? 'TARGETING_MATCH' : 'ROLLOUT_MATCH',
248
+ version: flag.version,
249
+ };
250
+ }
251
+ return {
252
+ key: flag.key,
253
+ enabled: false,
254
+ variants: {},
255
+ reason: 'FALLBACK',
256
+ version: flag.version,
257
+ };
258
+ }
259
+
260
+ // Step 4: Full kill-switch off (rolloutPercentage === 0 with no rules)
261
+ return {
262
+ key: flag.key,
263
+ enabled: false,
264
+ variants: {},
265
+ reason: 'KILL_SWITCH',
266
+ version: flag.version,
267
+ };
268
+ }