import type { GrowthBook, GrowthBookClient, StickyBucketService, UserScopedGrowthBook } from ".."; import { AttributePath, ConditionInterface, ParentConditionInterface } from "./mongrule"; declare global { interface Window { _growthbook?: GrowthBook; } } export type VariationMeta = { passthrough?: boolean; key?: string; name?: string; }; export type FeatureRule = { id?: string; condition?: ConditionInterface; parentConditions?: ParentConditionInterface[]; force?: T; variations?: T[]; weights?: number[]; key?: string; hashAttribute?: AttributeKey; fallbackAttribute?: AttributeKey; hashVersion?: number; disableStickyBucketing?: boolean; bucketVersion?: number; minBucketVersion?: number; range?: VariationRange; coverage?: number; /** @deprecated */ namespace?: [string, number, number]; ranges?: VariationRange[]; meta?: VariationMeta[]; filters?: Filter[]; seed?: string; name?: string; phase?: string; tracks?: Array<{ experiment: Experiment; result: Result; }>; contextualBanditRef?: string; contextualVariations?: T[]; metadata?: PayloadMetadata; }; export type ContextualBanditDefinition = { banditVersion?: number; contexts: { leafId: number; condition: Record; weights: number[]; }[]; }; export type ContextualBanditDefinitions = Record; export type InterleavingDefinition = { trackingKey: string; hashAttribute: AttributeKey; seed: string; variations: { key: string; config: Record; }[]; }; export type InterleavingDefinitions = Record>; export interface FeatureDefinition { defaultValue?: T; rules?: FeatureRule[]; metadata?: PayloadMetadata; } /** * Sent when the SDK Connection opts in. A feature in every project has * `allProjects` instead of `projects`, and one in no project has neither. */ export type PayloadMetadata = { projects?: string[]; allProjects?: boolean; tags?: string[]; customFields?: Record; }; export type FeatureResultSource = "unknownFeature" | "defaultValue" | "force" | "override" | "experiment" | "prerequisite" | "cyclicPrerequisite"; export interface FeatureResult { value: T | null; source: FeatureResultSource; on: boolean; off: boolean; ruleId: string; experiment?: Experiment; experimentResult?: Result; } /** @deprecated */ export type ExperimentStatus = "draft" | "running" | "stopped"; export type UrlTargetType = "regex" | "simple"; export type UrlTarget = { include: boolean; type: UrlTargetType; pattern: string; }; export type Experiment = { key: string; variations: [T, T, ...T[]]; ranges?: VariationRange[]; meta?: VariationMeta[]; filters?: Filter[]; seed?: string; name?: string; phase?: string; urlPatterns?: UrlTarget[]; weights?: number[]; condition?: ConditionInterface; parentConditions?: ParentConditionInterface[]; coverage?: number; include?: () => boolean; /** @deprecated */ namespace?: [string, number, number]; force?: number; hashAttribute?: AttributeKey; fallbackAttribute?: AttributeKey; hashVersion?: number; disableStickyBucketing?: boolean; bucketVersion?: number; minBucketVersion?: number; active?: boolean; persistQueryString?: boolean; contextualBandit?: CBContext; /** @deprecated */ status?: ExperimentStatus; /** @deprecated */ url?: RegExp; /** @deprecated */ groups?: string[]; }; export type AutoExperimentChangeType = "redirect" | "visual" | "unknown"; export type AutoExperiment = Experiment & { changeId?: string; manual?: boolean; metadata?: PayloadMetadata; contextualBanditRef?: string; }; export type ExperimentOverride = { condition?: ConditionInterface; weights?: number[]; active?: boolean; status?: ExperimentStatus; force?: number; coverage?: number; groups?: string[]; namespace?: [string, number, number]; url?: RegExp | string; }; export interface Result { value: T; variationId: number; key: string; name?: string; bucket?: number; passthrough?: boolean; inExperiment: boolean; hashUsed?: boolean; hashAttribute: string; hashValue: string; featureId: string | null; stickyBucketUsed?: boolean; leafId?: number; variationWeights?: number[]; banditVersion?: number; } export type CBContext = { leafId: number; variationWeights: number[]; banditVersion?: number; }; export type Attributes = Record; export type AttributeKey = string extends keyof A ? string : { [K in keyof A & string]: unknown extends A[K] ? K : [Extract] extends [never] ? never : K; }[keyof A & string]; /** * Register your app's feature and attribute types once and every GrowthBook * instance and React hook is typed with no generics: * * declare module "@growthbook/growthbook" { * interface Register { * features: AppFeatures; * attributes: AppAttributes; * } * } * * Register `events` (event name -> properties) to check `logEvent` calls: * * events: { * start_checkout: { plan: "pro" | "enterprise" }; * button_click: { button: string }; * }; */ export interface Register { } export type RegisteredFeatures = Register extends { features: infer F; } ? F : Record; export type RegisteredAttributes = Register extends { attributes: infer A; } ? A : Attributes; export type RegisteredEvents = Register extends { events: infer E; } ? E : Record; export type EventArgs

= Record extends P ? [properties?: P] : [properties: P]; export type NoInferType = [T][T extends unknown ? 0 : never]; export type TrackingUserContext = Pick, "attributes" | "url">; export interface TrackingData { experiment: Experiment; result: Result; user?: TrackingUserContext; } export interface TrackingDataWithUser { experiment: Experiment; result: Result; user: TrackingUserContext; } export type TrackingCallback = (experiment: Experiment, result: Result, user?: TrackingUserContext) => Promise | void; export type TrackingCallbackWithUser = (experiment: Experiment, result: Result, user: TrackingUserContext) => Promise | void; export type FeatureUsageCallback = (key: string, result: FeatureResult) => void; export type FeatureUsageCallbackWithUser = (key: string, result: FeatureResult, user: TrackingUserContext) => void; export type FeatureUsageSubCallback = (key: string, result: Readonly>) => void; export type CustomEventSubCallback = (eventName: string, properties: Readonly>) => void; export type ExperimentViewedSubCallback = (experiment: Readonly>, result: Readonly>, user: TrackingUserContext) => void; export type Plugin = (gb: GrowthBook | UserScopedGrowthBook | GrowthBookClient) => void; export type EventProperties = Record; export type EventLogger = (eventName: string, properties: EventProperties, userContext: TrackingUserContext) => void | Promise; export type NavigateCallback = (url: string) => void | Promise; export type ApplyDomChangesCallback = (changes: AutoExperimentVariation) => () => void; export type RenderFunction = () => void; export type Options = { enabled?: boolean; attributes?: AppAttributes; /** The user's remote saved groups; wins over a `__gb_remoteGroupIds` attribute. */ remoteGroupIds?: string[]; url?: string; features?: Record; experiments?: AutoExperiment[]; forcedVariations?: Record; forcedFeatureValues?: Map; attributeOverrides?: Partial; blockedChangeIds?: string[]; disableVisualExperiments?: boolean; disableJsInjection?: boolean; jsInjectionNonce?: string; disableUrlRedirectExperiments?: boolean; disableCrossOriginUrlRedirectExperiments?: boolean; disableExperimentsOnLoad?: boolean; stickyBucketAssignmentDocs?: Record; stickyBucketService?: StickyBucketService; debug?: boolean; log?: (msg: string, ctx: any) => void; qaMode?: boolean; /** @deprecated */ backgroundSync?: boolean; /** @deprecated */ subscribeToChanges?: boolean; /** * The hash version for percentage rollouts and experiments that don't set * their own `hashVersion`. Defaults to 1, which is slightly biased. Changing * it reassigns the users of those rollouts and experiments. */ defaultHashVersion?: number; enableDevMode?: boolean; disableCache?: boolean; /** @deprecated */ disableDevTools?: boolean; trackingCallback?: TrackingCallback; onFeatureUsage?: FeatureUsageCallback; eventLogger?: EventLogger; cacheKeyAttributes?: (keyof Attributes)[]; /** @deprecated */ user?: { id?: string; anonId?: string; [key: string]: string | undefined; }; /** @deprecated */ overrides?: Record; /** @deprecated */ groups?: Record; apiHost?: string; streamingHost?: string; apiHostRequestHeaders?: Record; streamingHostRequestHeaders?: Record; clientKey?: string; renderer?: null | RenderFunction; decryptionKey?: string; remoteEval?: boolean; navigate?: NavigateCallback; navigateDelay?: number; maxNavigateDelay?: number; /** @deprecated */ antiFlicker?: boolean; /** @deprecated */ antiFlickerTimeout?: number; applyDomChangesCallback?: ApplyDomChangesCallback; savedGroups?: SavedGroupsPayload; contextualBandits?: ContextualBanditDefinitions; plugins?: Plugin[]; }; export type ClientOptions = { enabled?: boolean; debug?: boolean; globalAttributes?: Partial; forcedVariations?: Record; forcedFeatureValues?: Map; log?: (msg: string, ctx: any) => void; qaMode?: boolean; /** * The hash version for percentage rollouts and experiments that don't set * their own `hashVersion`. Defaults to 1, which is slightly biased. Changing * it reassigns the users of those rollouts and experiments. */ defaultHashVersion?: number; disableCache?: boolean; trackingCallback?: TrackingCallbackWithUser; onFeatureUsage?: (key: string, result: FeatureResult, user: TrackingUserContext) => void; eventLogger?: EventLogger; apiHost?: string; streamingHost?: string; apiHostRequestHeaders?: Record; streamingHostRequestHeaders?: Record; clientKey?: string; decryptionKey?: string; savedGroups?: SavedGroupsPayload; contextualBandits?: ContextualBanditDefinitions; plugins?: Plugin[]; }; export type GlobalContext = { log: (msg: string, ctx: any) => void; debug?: boolean; features?: FeatureDefinitions; experiments?: AutoExperiment[]; enabled?: boolean; qaMode?: boolean; defaultHashVersion?: number; savedGroups?: SavedGroupsPayload; contextualBandits?: ContextualBanditDefinitions; forcedVariations?: Record; forcedFeatureValues?: Map; trackingCallback?: TrackingCallbackWithUser; onFeatureUsage?: FeatureUsageCallbackWithUser; onExperimentEval?: (experiment: Experiment, result: Result) => void; saveDeferredTrack?: (data: TrackingData) => void; recordChangeId?: (changeId: string) => void; eventLogger?: EventLogger; /** @deprecated */ overrides?: Record; /** @deprecated */ groups?: Record; /** @deprecated */ user?: { id?: string; anonId?: string; [key: string]: string | undefined; }; }; export type UserContext = { enabled?: boolean; qaMode?: boolean; enableDevMode?: boolean; attributes?: AppAttributes; /** The user's remote saved groups; wins over a `__gb_remoteGroupIds` attribute. */ remoteGroupIds?: string[]; url?: string; blockedChangeIds?: string[]; stickyBucketAssignmentDocs?: Record; saveStickyBucketAssignmentDoc?: (doc: StickyAssignmentsDocument) => Promise; forcedVariations?: Record; forcedFeatureValues?: Map; attributeOverrides?: Partial; trackingCallback?: TrackingCallback; onFeatureUsage?: FeatureUsageCallback; trackedExperiments?: Set; trackedFeatureUsage?: Record; devLogs?: LogUnion[]; featureUsageSubs?: Set; experimentViewedSubs?: Set; }; export type StackContext = { id?: string; evaluatedFeatures: Set; }; export type EvalContext = { global: GlobalContext; user: UserContext; stack: StackContext; }; export type PrefetchOptions = Pick & { clientKey: string; streaming?: boolean; skipCache?: boolean; }; export type SubscriptionFunction = (experiment: Experiment, result: Result) => void; export type VariationRange = [number, number]; export interface InitResponse { success: boolean; source: "init" | "cache" | "network" | "error" | "timeout"; error?: Error; } export interface FetchResponse { data: FeatureApiResponse | null; success: boolean; source: "cache" | "network" | "error" | "timeout"; error?: Error; } export type JSONValue = null | number | string | boolean | Array | Record | { [key: string]: JSONValue; }; export type WidenPrimitives = T extends string ? string : T extends number ? number : T extends boolean ? boolean : T; export type FeatureValueOrFallback = [V] extends [null] ? T | null : WidenPrimitives; export type DOMMutation = { selector: string; action: string; attribute: string; value?: string; parentSelector?: string; insertBeforeSelector?: string; }; export type AutoExperimentVariation = { domMutations?: DOMMutation[]; css?: string; js?: string; urlRedirect?: string; }; export type FeatureDefinitions = Record, AppAttributes extends Attributes = any> = string extends keyof AppFeatures ? Record> : { [K in keyof AppFeatures]?: FeatureDefinition; }; export type FeatureApiResponse = Record, AppAttributes extends Attributes = any> = { features?: FeatureDefinitions; dateUpdated?: string; encryptedFeatures?: string; experiments?: AutoExperiment[]; encryptedExperiments?: string; savedGroups?: SavedGroupsPayload; encryptedSavedGroups?: string; contextualBandits?: ContextualBanditDefinitions; encryptedContextualBandits?: string; interleavings?: InterleavingDefinitions; encryptedInterleavings?: string; }; export type GrowthBookPayload = FeatureApiResponse; /** * A payload written in code, such as the `fallbackPayload` given to `init`, * checked against your attributes as well as your features. Targeting * conditions, hash attributes and saved groups must use real attributes, with * operators and values that fit each attribute's type. * * const fallbackPayload: Payload = {...}; * * Uses the registered features and attributes when none are given. */ export type Payload = RegisteredFeatures, AppAttributes extends Attributes = RegisteredAttributes> = FeatureApiResponse; /** A rule in `LocalFeatures`. A percentage rollout needs a `hashAttribute`. */ export type LocalFeatureRule = { force: T; condition?: ConditionInterface; } & ({ coverage: number; hashAttribute: AttributeKey; /** Hashed with the user instead of the feature key */ seed?: string; } | { coverage?: never; hashAttribute?: never; seed?: never; }); /** * Feature flags hard-coded in a local file and passed to `initSync` as the * payload's `features`. Stricter than `Payload`: every feature must be defined * with a `defaultValue`, and rules are limited to `force`, `condition` and * percentage rollouts. A feature that's optional in your features type may be * left out. * * export const features: LocalFeatures = {...}; * new GrowthBook().initSync({ payload: { features } }); * * Uses the registered features and attributes when none are given. */ export type LocalFeatures = RegisteredFeatures, AppAttributes extends Attributes = RegisteredAttributes> = { [K in keyof AppFeatures]: { defaultValue: Exclude; rules?: LocalFeatureRule, AppAttributes>[]; }; }; /** Each filter is an array, and any one of its values is enough */ export type PayloadFilters = { projects?: string[]; tags?: string[]; customFields?: Record; }; export type ReducePayloadOptions = { userContext?: UserContext; /** Keep only the features and auto experiments that match every filter */ include?: PayloadFilters; /** Remove the features and auto experiments that match any filter */ exclude?: PayloadFilters; /** * "keep" (default) sends the prerequisites of what is kept even when the * filters remove them, so the client evaluates the same as the full payload. * "filter" applies the filters to them too. */ prerequisites?: "keep" | "filter"; }; export type Polyfills = { fetch: any; SubtleCrypto: any; EventSource: any; localStorage?: LocalStorageCompat; }; export type Helpers = { fetchFeaturesCall: ({ host, clientKey, headers, }: { host: string; clientKey: string; headers?: Record; }) => Promise; fetchRemoteEvalCall: ({ host, clientKey, payload, headers, }: { host: string; clientKey: string; payload: any; headers?: Record; }) => Promise; eventSourceCall: ({ host, clientKey, headers, }: { host: string; clientKey: string; headers?: Record; }) => EventSource; startIdleListener: () => (() => void) | void; stopIdleListener: () => void; }; export interface LocalStorageCompat { getItem(key: string): string | null | Promise; setItem(key: string, value: string): void | Promise; } export type CacheSettings = { backgroundSync: boolean; cacheKey: string; staleTTL: number; maxAge: number; maxEntries: number; disableIdleStreams: boolean; idleStreamInterval: number; disableCache: boolean; }; export type ApiHost = string; export type ClientKey = string; export type InitOptions = Record> = { timeout?: number; skipCache?: boolean; payload?: FeatureApiResponse; /** Used when the fetch fails or times out and there is no cached payload, e.g. a copy bundled at build time. */ fallbackPayload?: FeatureApiResponse; streaming?: boolean; /** Refresh the payload on this interval (ms). Ignored when streaming is active. */ pollingInterval?: number; cacheSettings?: CacheSettings; }; export type InitSyncOptions = Record> = { payload: FeatureApiResponse; streaming?: boolean; /** Refresh the payload on this interval (ms). Ignored when streaming is active. */ pollingInterval?: number; }; export type LoadFeaturesOptions = { /** @deprecated */ autoRefresh?: boolean; timeout?: number; skipCache?: boolean; }; export type RefreshFeaturesOptions = { timeout?: number; skipCache?: boolean; }; export type DestroyOptions = { destroyAllStreams?: boolean; }; export interface Filter { attribute?: AttributeKey; seed: string; hashVersion: number; ranges: VariationRange[]; } export type StickyAttributeKey = string; export type StickyExperimentKey = string; export type StickyAssignments = Record; export interface StickyAssignmentsDocument { attributeName: string; attributeValue: string; assignments: StickyAssignments; } /** The v1 shape: an ID list's values. New code should use SavedGroupsPayload. */ export type SavedGroupsValues = Record; /** The savedGroupReferencesV2 shape of one saved group, of any type. */ export type SavedGroupPayloadEntry = { type: "list"; attributeKey: AttributePath; values: (string | number)[]; } | { type: "condition"; condition: ConditionInterface; } | { type: "remote"; attributeKey: AttributePath; /** * Set on a derived group (ID `:`): the remote group * whose IDs `attributeKey`'s value is looked up in. */ valuesFrom?: string; }; /** A remote saved group from the payload, as a resolver sees it. */ export type RemoteSavedGroup = { id: string; attributeKey: string; /** For a derived group, the remote group whose IDs it checks. */ valuesFrom?: string; }; /** * Looks up which of `groups` a user is in, from their `attributes` (only the * ones remote groups use). Returns the group IDs. */ export type SavedGroupResolver = (args: { attributes: Attributes; groups: RemoteSavedGroup[]; }) => Promise; /** The `savedGroups` payload field. Entries may use either shape above. */ export type SavedGroupsPayload = Record>; export type BaseLog = { timestamp: string; }; export type EventLog = BaseLog & { logType: "event"; eventName: string; properties?: Record; }; export type ExperimentLog = BaseLog & { logType: "experiment"; experiment: Experiment; result: Result; }; export type FeatureLog = BaseLog & { logType: "feature"; featureKey: string; result: FeatureResult; }; export type LogUnion = EventLog | ExperimentLog | FeatureLog; //# sourceMappingURL=growthbook.d.ts.map