import type { EvaluationContext, Hook, JsonValue, Paradigm, Provider, ProviderMetadata, ResolutionDetails, TrackingEventDetails, } from '@openfeature/server-sdk'; import { ErrorCode, OpenFeatureEventEmitter, ProviderEvents, StandardResolutionReasons, } from '@openfeature/server-sdk'; import { createSafeLogger, type LDLogger } from '@launchdarkly/js-sdk-common'; import type { OpenFeatureLDClientContract } from './OpenFeatureLDClientContract'; import { translateContext } from './translateContext'; import { translateResult } from './translateResult'; import { translateTrackingEventDetails } from './translateTrackingEventDetails'; /** * Create a ResolutionDetails for an evaluation that produced a type different * than the expected type. * @param value The default value to populate the ResolutionDetails with. * @returns A ResolutionDetails with the default value. */ function wrongTypeResult(value: T): ResolutionDetails { return { value, reason: StandardResolutionReasons.ERROR, errorCode: ErrorCode.TYPE_MISMATCH, }; } /** * Configuration for constructing a {@link BaseOpenFeatureProvider}. */ export interface BaseProviderConfig { /** The logger to use for diagnostics. */ logger: LDLogger; /** The provider name reported in OpenFeature metadata. */ providerName: string; /** * The maximum number of seconds initialization waits for the LaunchDarkly client to become * ready. Defaults to 10. Zero does not wait, and 'forever' waits indefinitely. */ initTimeoutSeconds?: number | 'forever'; } /** * Base OpenFeature provider for LaunchDarkly server-side SDKs. * * Subclasses must: * 1. Construct or receive an LDClient and pass it to {@link setClient} in their constructor. * 2. Optionally wire SDK-specific events by calling {@link emitConfigurationChanged}. */ export abstract class BaseOpenFeatureProvider< TClient extends OpenFeatureLDClientContract = OpenFeatureLDClientContract, > implements Provider { readonly metadata: ProviderMetadata; readonly runsOn: Paradigm = 'server'; readonly events = new OpenFeatureEventEmitter(); private _client?: TClient; private _clientConstructionError?: unknown; private _logger: LDLogger; private _initTimeoutSeconds: number | 'forever'; protected constructor(config: BaseProviderConfig) { this.metadata = { name: config.providerName }; this._logger = createSafeLogger(config.logger); this._initTimeoutSeconds = config.initTimeoutSeconds === undefined ? 10 : config.initTimeoutSeconds; } /** * Called by subclass constructors to register the LDClient instance. */ protected setClient(client: TClient): void { this._client = client; } /** * Called by subclass constructors when client construction throws. * The error will be re-thrown from {@link initialize}. */ protected setClientError(error: unknown): void { this._clientConstructionError = error; this._logger.error(`Encountered unrecoverable initialization error, ${error}`); } /** * Emit an OpenFeature ConfigurationChanged event for the given flag key. * Per-SDK providers call this from their event wiring. */ protected emitConfigurationChanged(flagKey: string): void { this.events.emit(ProviderEvents.ConfigurationChanged, { flagsChanged: [flagKey], }); } // eslint-disable-next-line @typescript-eslint/no-unused-vars async initialize(context?: EvaluationContext): Promise { if (!this._client) { if (this._clientConstructionError) { throw this._clientConstructionError; } throw new Error('Unknown problem encountered during initialization'); } if (this._initTimeoutSeconds === 'forever') { await this._client.waitForInitialization(); return; } if (this._initTimeoutSeconds === 0) { const pending = this._client.waitForInitialization({ timeout: 0 }); pending.catch(() => {}); await Promise.race([ pending, Promise.reject( new Error( 'The LaunchDarkly client was not ready and the initialization timeout was zero', ), ), ]); return; } await this._client.waitForInitialization({ timeout: this._initTimeoutSeconds }); } /** * Determines the boolean variation of a feature flag for a context, along with information about * how it was calculated. * * If the flag does not evaluate to a boolean value, then the defaultValue will be returned. * * @param flagKey The unique key of the feature flag. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @returns A promise which will resolve to a ResolutionDetails. */ async resolveBooleanEvaluation( flagKey: string, defaultValue: boolean, context: EvaluationContext, ): Promise> { const res = await this._client!.variationDetail( flagKey, translateContext(this._logger, context), defaultValue, ); if (typeof res.value === 'boolean') { return translateResult(res); } return wrongTypeResult(defaultValue); } /** * Determines the string variation of a feature flag for a context, along with information about * how it was calculated. * * If the flag does not evaluate to a string value, then the defaultValue will be returned. * * @param flagKey The unique key of the feature flag. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @returns A promise which will resolve to a ResolutionDetails. */ async resolveStringEvaluation( flagKey: string, defaultValue: string, context: EvaluationContext, ): Promise> { const res = await this._client!.variationDetail( flagKey, translateContext(this._logger, context), defaultValue, ); if (typeof res.value === 'string') { return translateResult(res); } return wrongTypeResult(defaultValue); } /** * Determines the numeric variation of a feature flag for a context, along with information about * how it was calculated. * * If the flag does not evaluate to a numeric value, then the defaultValue will be returned. * * @param flagKey The unique key of the feature flag. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @returns A promise which will resolve to a ResolutionDetails. */ async resolveNumberEvaluation( flagKey: string, defaultValue: number, context: EvaluationContext, ): Promise> { const res = await this._client!.variationDetail( flagKey, translateContext(this._logger, context), defaultValue, ); if (typeof res.value === 'number') { return translateResult(res); } return wrongTypeResult(defaultValue); } /** * Determines the object variation of a feature flag for a context, along with information about * how it was calculated. * * If the flag does not evaluate to a JSON object value, then the defaultValue will be returned. * * @param flagKey The unique key of the feature flag. * @param defaultValue The default value of the flag, to be used if the value is not available * from LaunchDarkly. * @param context The context requesting the flag. The client will generate an analytics event to * register this context with LaunchDarkly if the context does not already exist. * @returns A promise which will resolve to a ResolutionDetails. */ async resolveObjectEvaluation( flagKey: string, defaultValue: U, context: EvaluationContext, ): Promise> { const res = await this._client!.variationDetail( flagKey, translateContext(this._logger, context), defaultValue, ); if (res.value !== null && typeof res.value === 'object') { return translateResult(res); } return wrongTypeResult(defaultValue); } /** * Returns the OpenFeature hooks registered for this provider. The * LaunchDarkly provider does not currently register any provider-level * hooks, so this always returns an empty array. */ get hooks(): Hook[] { return []; } /** * Get the LDClient instance used by this provider. * * @returns The client for this provider. */ getClient(): TClient { return this._client!; } async onClose(): Promise { try { await this._client?.flush(); } finally { this._client?.close(); } } track( trackingEventName: string, context: EvaluationContext, trackingEventDetails?: TrackingEventDetails, ): void { this._client?.track( trackingEventName, translateContext(this._logger, context), trackingEventDetails ? translateTrackingEventDetails(trackingEventDetails) : undefined, trackingEventDetails?.value, ); } }