import { ReflagContext, ReflagDeprecatedContext } from './context'; import { Feedback, FeedbackOptions, RequestFeedbackData } from './feedback/feedback'; import { FallbackFlagOverride, OptInFlag, RawFlags } from './flag/flags'; import { HookArgs, State } from './hooksManager'; import { Logger } from './logger'; import { EventSourceFactory } from './sse'; import { StorageAdapter } from './storage'; import { ToolbarPosition } from './ui/types'; /** * (Internal) User context. * * @internal */ export type User = { /** * Identifier of the user. */ userId: string; /** * User attributes. */ attributes?: { /** * Name of the user. */ name?: string; /** * Email of the user. */ email?: string; /** * Avatar URL of the user. */ avatar?: string; /** * Custom attributes of the user. */ [key: string]: any; }; /** * Custom context of the user. */ context?: PayloadContext; }; /** * (Internal) Company context. * * @internal */ export type Company = { /** * User identifier. */ userId: string; /** * Company identifier. */ companyId: string; /** * Company attributes. */ attributes?: { /** * Name of the company. */ name?: string; /** * Custom attributes of the company. */ [key: string]: any; }; context?: PayloadContext; }; /** * Tracked event. */ export type TrackedEvent = { /** * Event name. */ event: string; /** * User identifier. */ userId: string; /** * Company identifier. */ companyId?: string; /** * Event attributes. */ attributes?: Record; /** * Custom context of the event. */ context?: PayloadContext; }; /** * (Internal) Custom context of the event. * * @internal */ export type PayloadContext = { /** * Whether the company and user associated with the event are active. */ active?: boolean; }; /** * ReflagClient configuration. */ export interface Config { /** * Base URL of Reflag servers. */ apiBaseUrl: string; /** * Base URL of the Reflag web app. */ appBaseUrl: string; /** * Base URL used for pubsub SSE connections. * Defaults to `apiBaseUrl`. */ sseBaseUrl: string; /** * Whether to enable tracking. */ enableTracking: boolean; /** * Whether to enable offline mode. */ offline: boolean; /** * Whether the client is bootstrapped. */ bootstrapped: boolean; } /** * Toolbar options. */ export type ToolbarOptions = boolean | { show?: boolean; position?: ToolbarPosition; }; /** * Flag definitions. */ export type FlagDefinitions = Readonly>; /** * Pre-fetched evaluated state used to bootstrap the client. */ export type BootstrappedState = { context: ReflagContext; flags: RawFlags; flagStateVersion?: number; }; /** * ReflagClient initialization options. */ export type InitOptions = ReflagDeprecatedContext & { /** * Publishable key for authentication */ publishableKey: string; /** * You can provide a logger to see the logs of the network calls. * This is undefined by default. * For debugging purposes you can just set the browser console to this property: * ```javascript * options.logger = window.console; * ``` */ logger?: Logger; /** * Base URL of Reflag servers. You can override this to use your mocked server. */ apiBaseUrl?: string; /** * Base URL of the Reflag web app. Links open ín this app by default. */ appBaseUrl?: string; /** * Whether to enable offline mode. Defaults to `false`. */ offline?: boolean; /** * Flag keys for which `isEnabled` should fallback to true * if SDK fails to fetch flags from Reflag servers. If a record * is supplied instead of array, the values of each key represent the * configuration values and `isEnabled` is assume `true`. */ fallbackFlags?: string[] | Record; /** * Timeout in milliseconds when fetching flags */ timeoutMs?: number; /** * If set to true stale flags will be returned while refetching flags */ staleWhileRevalidate?: boolean; /** * If set, flags will be cached between page loads for this duration */ expireTimeMs?: number; /** * Stale flags will be returned if staleWhileRevalidate is true if no new flags can be fetched */ staleTimeMs?: number; /** * When proxying requests, you may want to include credentials like cookies * so you can authorize the request in the proxy. * This option controls the `credentials` option of the fetch API. */ credentials?: "include" | "same-origin" | "omit"; /** * @deprecated SSE now uses the same origin as `apiBaseUrl` by default. * Override only if you need a separate pubsub host temporarily. */ sseBaseUrl?: string; /** * AutoFeedback specific configuration */ feedback?: FeedbackOptions; /** * Version of the SDK */ sdkVersion?: string; /** * Whether to enable tracking. Defaults to `true`. */ enableTracking?: boolean; /** * Whether to enable live flag updates. * * When enabled, the SDK opens a Server-Sent Events (SSE) connection and * refreshes flag definitions automatically whenever they change on the * server, without relying on context changes or manual refreshes. * * Defaults to `false` in the browser SDK. */ enableLiveFlagUpdates?: boolean; /** * Optional factory used to create SSE connections. * * By default the SDK uses the global `EventSource` implementation available * in browsers. This option is intended for alternative runtimes where you * need to provide an EventSource-compatible transport manually. The React * Native wrapper already injects a transport automatically. */ eventSourceFactory?: EventSourceFactory; /** * Toolbar configuration */ toolbar?: ToolbarOptions; /** * Pre-fetched evaluated state used for the initial flag state. * The client fetches opt-in metadata on demand when opt-in flags are requested. */ bootstrappedState?: BootstrappedState; /** * Pre-fetched flags used for the initial flag state. * The client fetches opt-in metadata on demand when opt-in flags are requested. * @deprecated Use `bootstrappedState` instead. */ bootstrappedFlags?: RawFlags; /** * Optional storage adapter used for caching flags and overrides. * Useful for React Native (AsyncStorage). */ storage?: StorageAdapter; /** * Queue settings for tracking updates sent to `/bulk`. * Applies to user/company updates, check events, and prompt events. * Events are buffered in memory and flushed in the background. */ trackingQueue?: { /** * Delay in milliseconds before flushing queued events. * Lower values send sooner; slightly higher values batch better. * Defaults to 200ms. */ flushDelayMs?: number; /** * Maximum number of queued events retained locally. * Oldest events are dropped when the cap is exceeded. * Defaults to 100. */ maxSize?: number; /** * Deprecated: retries are no longer performed for bulk delivery. */ retryBaseDelayMs?: number; /** * Deprecated: retries are no longer performed for bulk delivery. */ retryMaxDelayMs?: number; }; }; /** * A remotely managed configuration value for a flag. */ export type FlagRemoteConfig = { /** * The key of the matched configuration value. */ key: string; /** * The optional user-supplied payload data. */ payload: any; } | { key: undefined; payload: undefined; }; /** * Options for changing the current user or company's opt-in membership. */ export type SetOptInOptions = { /** * Whether the scoped subject has opted in. */ optedIn: boolean; /** * Whether to update the current user or current company. Defaults to `user`. */ scope?: "user" | "company"; }; export interface Flag { /** * Result of flag flag evaluation. * Note: Does not take local overrides into account. */ isEnabled: boolean; config: FlagRemoteConfig; /** * Function to send analytics events for this flag. */ track: () => Promise; /** * Function to request feedback for this flag. */ requestFeedback: (options: Omit) => void; /** * The current override status of isEnabled for the flag. */ isEnabledOverride: boolean | null; /** * Set the override status for isEnabled for the flag. * Set to `null` to remove the override. */ setIsEnabledOverride(isEnabled: boolean | null): void; } /** * ReflagClient lets you interact with the Reflag API. */ export declare class ReflagClient { private state; private initializationFinished; private contextUpdateLoading; private readonly publishableKey; private context; private config; private requestFeedbackOptions; private readonly httpClient; private readonly autoFeedback; private autoFeedbackInit; private readonly enableLiveFlagUpdates; private readonly eventSourceFactory; private readonly credentials; private readonly sdkVersion; private pubSubChannel; private pubSubInit; private latestFlagStateVersionSeen; private readonly flagsClient; private readonly bulkQueue; private readonly handleBeforeUnload?; readonly logger: Logger; private readonly hooks; private toolbarToggleShown; /** * Create a new ReflagClient instance. */ constructor(opts: InitOptions); /** * Initialize the Reflag SDK. * * Must be called before calling other SDK methods. */ initialize(): Promise; /** * Stop the SDK. * This will stop any automated feedback surveys. * **/ stop(): Promise; getState(): State; /** * Add an event listener * * @param type Type of events to listen for * @param handler The function to call when the event is triggered. * @returns A function to remove the hook. */ on(type: THookType, handler: (args0: HookArgs[THookType]) => void): () => void; /** * Remove an event listener * * @param type Type of event to remove. * @param handler The same function that was passed to `on`. * * @returns A function to remove the hook. */ off(type: THookType, handler: (args0: HookArgs[THookType]) => void): void; /** * Get the current context. */ getContext(): ReflagContext; /** * Get the current configuration. */ getConfig(): Config; /** * Update the user context. * Performs a shallow merge with the existing user context. * It will not update the context if nothing has changed. * * @param user */ updateUser(user: { [key: string]: string | number | undefined; }): Promise; /** * Update the company context. * Performs a shallow merge with the existing company context. * It will not update the context if nothing has changed. * * @param company The company details. */ updateCompany(company: { [key: string]: string | number | undefined; }): Promise; /** * Update the company context. * Performs a shallow merge with the existing company context. * It will not update the context if nothing has changed. * * @param otherContext Additional context. */ updateOtherContext(otherContext: { [key: string]: string | number | undefined; }): Promise; /** * Update the context. * Replaces the existing context with a new context. * * @param context The context to update. */ setContext(context: ReflagDeprecatedContext): Promise; private applyContext; applyBootstrappedState(bootstrappedState: BootstrappedState, triggerEvent?: boolean): void; /** * Update the flags. * * @param flags The flags to update. * @param triggerEvent Whether to trigger the `flagsUpdated` event. */ updateFlags(flags: RawFlags, triggerEvent?: boolean, flagStateVersion?: number): void; /** * Track an event in Reflag. * * @param eventName The name of the event. * @param attributes Any attributes you want to attach to the event. */ track(eventName: string, attributes?: Record | null): Promise; /** * Submit user feedback to Reflag. Must include either `score` or `comment`, or both. * * @param payload The feedback details to submit. * @returns The server response. */ feedback(payload: Feedback): Promise; /** * Display the Reflag feedback form UI programmatically. * * This can be used to collect feedback from users in Reflag in cases where Automated Feedback Surveys isn't appropriate. * * @param options */ requestFeedback(options: RequestFeedbackData): void; /** * @deprecated Use `getFlags` instead. */ getFeatures(): RawFlags; /** * Returns a map of enabled flags. * Accessing a flag will *not* send a check event * and `isEnabled` does not take any flag overrides * into account. * * @returns Map of flags. */ getFlags(): RawFlags; /** * Force refresh flags from the API, bypassing cache. */ refresh(): Promise; /** * Returns opt-in-enabled flags for the current context. */ getOptInFlags(): OptInFlag[]; /** * Returns whether opt-in flags are loading for the current context. * * Calling this method requests opt-in metadata if it is not already available. */ getIsLoadingOptInFlags(): boolean; /** * Set whether the current user or company has opted into a flag. * * A successful Response is returned after the refreshed flag state confirms * the membership change. HTTP failures return a non-OK Response without * refreshing flags. Offline mode, invalid arguments, or missing scoped context * return undefined. Network and confirmation failures reject the promise; * a confirmation failure may occur after membership changed remotely. */ setOptIn(flagKey: string, options: SetOptInOptions): Promise; /** * @deprecated Use `getFlag` instead. */ getFeature(flagKey: string): Flag; /** * Return a flag. Accessing `isEnabled` or `config` will automatically send a `check` event. * * @param flagKey - The key of the flag to get. * @returns A flag. */ getFlag(flagKey: string): Flag; showToolbarToggle(position?: ToolbarPosition): void; private finishContextUpdate; private setState; private sendCheckEvent; /** * Send attributes to Reflag for the current user */ private user; /** * Send attributes to Reflag for the current company. */ private company; private wantsPubSub; private hasPubSubTransport; private initializePubSub; private handlePubSubMessage; private reconcileFlagsWithLatestPubSubVersion; private updateAutoFeedbackUser; } //# sourceMappingURL=client.d.ts.map