All files / packages/services/src/launchdarkly service.ts

100% Statements 156/156
100% Branches 76/76
100% Functions 31/31
100% Lines 151/151

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390          2x   2x 2x   2x         2x           70x 69x 69x 69x     69x 69x 69x     69x       52x 6x     46x 46x       46x 46x   46x 3x 3x 3x 3x     43x   43x 43x 43x   43x             42x       42x 42x 42x   1x 1x                 6x 1x     5x   5x 1x           4x 4x   4x 1x     3x 2x 2x   1x                 12x 12x 10x 8x 7x       20x 3x 3x                     6x 2x               1x 1x               1x 1x         1x     1x                 9x 4x     5x 5x   1x         43x           14x       6x 1x     5x   4x 4x 2x         4x 4x   4x       3x 2x         4x 1x     3x 1x           2x 2x   1x                 3x 1x     2x 2x   1x                 3x 1x     2x 2x 2x 1x   1x                 4x 1x     3x   3x 1x     2x 2x 2x 1x 1x   1x                 16x 15x     16x 16x   16x 5x 5x 4x 4x 3x             61x 42x     19x 3x 3x           19x 3x 4x 4x 2x 2x 2x   1x                   19x 19x   2x       2x         4x 4x 2x 2x       2x         2x 2x 2x 2x 2x       5x 2x  
import {
  ReactNativeLDClient,
  type LDOptions,
  type LDContext,
  AutoEnvAttributes,
} from "@launchdarkly/react-native-client-sdk";
 
import { LAUNCHDARKLY_ERROR_CODES } from "@repo/constants/error";
import { LAUNCHDARKLY_ERROR_MESSAGES } from "@repo/constants/messages";
 
import { createLaunchDarklyError } from "./errors";
import {
  createAnonymousContext,
  createUserContext,
  isSameUser,
} from "./helpers";
 
import type { LaunchDarklyUser } from "./types";
 
type FlagChangeHandler = (flagKey: string, newValue: unknown) => void;
 
export class LaunchDarklyService {
  private client: ReactNativeLDClient | null = null;
  private isInitialized = false;
  private initPromise: Promise<void> | null = null;
  private clientSideId: string | undefined;
  private mobileKey: string | undefined;
  private currentContext: LDContext | null = null;
  private hasClientSideId = false;
  private flagChangeListeners: Map<string, Set<FlagChangeHandler>> = new Map();
  private globalChangeHandler:
    | ((context: LDContext, changedKeys: string[]) => void)
    | null = null;
 
  async initHostApp(clientSideId?: string) {
    // Return early if already initialized or initialization in progress
    if ((this.isInitialized && this.client) || this.initPromise) {
      return this.initPromise || Promise.resolve();
    }
 
    this.initPromise = this._doInit(clientSideId);
    return this.initPromise;
  }
 
  private async _doInit(clientSideId?: string): Promise<void> {
    this.clientSideId = clientSideId || process.env.LAUNCHDARKLY_CLIENT_SIDE_ID;
    this.mobileKey = process.env.LAUNCHDARKLY_MOBILE_KEY || this.clientSideId;
 
    if (!this.mobileKey) {
      this.hasClientSideId = false;
      this.isInitialized = true;
      this.initPromise = null;
      return;
    }
 
    this.hasClientSideId = true;
 
    try {
      const defaultContext = createAnonymousContext();
      this.currentContext = defaultContext;
 
      this.client = new ReactNativeLDClient(
        this.mobileKey,
        AutoEnvAttributes.Enabled,
        this._createOptions(),
      );
 
      // Don't await - let it connect in background
      this.client.identify(defaultContext).catch(() => {
        // Non-blocking error, connection will retry
      });
 
      this._setupGlobalChangeHandler();
      this.isInitialized = true;
      this.initPromise = null;
    } catch (error) {
      this._resetState();
      throw createLaunchDarklyError(
        LAUNCHDARKLY_ERROR_CODES.INIT_FAILED,
        LAUNCHDARKLY_ERROR_MESSAGES.INIT_FAILED,
        error,
      );
    }
  }
 
  async identify(user: LaunchDarklyUser) {
    if (!this.hasClientSideId) {
      return;
    }
 
    await this._waitForInitIfNeeded();
 
    if (!this.client || !this.isInitialized) {
      throw createLaunchDarklyError(
        LAUNCHDARKLY_ERROR_CODES.CLIENT_NOT_INITIALIZED,
        LAUNCHDARKLY_ERROR_MESSAGES.CLIENT_NOT_INITIALIZED,
      );
    }
 
    try {
      const context = createUserContext(user);
 
      if (isSameUser(this.currentContext, context)) {
        return;
      }
 
      await this.client.identify(context);
      this.currentContext = context;
      this._setupGlobalChangeHandler();
    } catch (error) {
      throw createLaunchDarklyError(
        LAUNCHDARKLY_ERROR_CODES.IDENTIFY_FAILED,
        LAUNCHDARKLY_ERROR_MESSAGES.IDENTIFY_FAILED,
        error,
      );
    }
  }
 
  private async _ensureInitialized(): Promise<boolean> {
    await this._waitForInitIfNeeded();
    if (!this.hasClientSideId) return false;
    if (this.client === null) return false;
    if (!this.isInitialized) return false;
    return true;
  }
 
  private async _waitForInitIfNeeded(): Promise<void> {
    if (this.initPromise && !this.isInitialized) {
      try {
        await this.initPromise;
      } catch {
        // Ignore init errors
      }
    }
  }
 
  async boolVariation(
    flagKey: string,
    defaultValue: boolean,
  ): Promise<boolean> {
    return this._getVariation(flagKey, defaultValue, (key, defaultVal) =>
      this.client!.boolVariation(key, defaultVal),
    );
  }
 
  async stringVariation(
    flagKey: string,
    defaultValue: string,
  ): Promise<string> {
    return this._getVariation(flagKey, defaultValue, (key, defaultVal) =>
      this.client!.stringVariation(key, defaultVal),
    );
  }
 
  async numberVariation(
    flagKey: string,
    defaultValue: number,
  ): Promise<number> {
    return this._getVariation(flagKey, defaultValue, (key, defaultVal) =>
      this.client!.numberVariation(key, defaultVal),
    );
  }
 
  async jsonVariation<T>(flagKey: string, defaultValue: T): Promise<T> {
    return this._getVariation(
      flagKey,
      defaultValue,
      (key, defaultVal) => this.client!.jsonVariation(key, defaultVal) as T,
    );
  }
 
  private async _getVariation<T>(
    flagKey: string,
    defaultValue: T,
    variationMethod: (key: string, defaultVal: T) => T,
  ): Promise<T> {
    if (!(await this._ensureInitialized())) {
      return defaultValue;
    }
 
    try {
      return variationMethod(flagKey, defaultValue);
    } catch {
      return defaultValue;
    }
  }
 
  private _createOptions(): LDOptions {
    return {
      withReasons: true,
    };
  }
 
  isReady(): boolean {
    return this.isInitialized && this.client !== null;
  }
 
  async waitForReady(timeout: number = 5000): Promise<void> {
    if (this.isReady()) {
      return;
    }
 
    if (this.initPromise) {
      let timeoutId: NodeJS.Timeout;
      const timeoutPromise = new Promise<never>((_, reject) => {
        timeoutId = setTimeout(
          () => reject(new Error("LaunchDarkly initialization timeout")),
          timeout,
        );
      });
 
      try {
        await Promise.race([this.initPromise, timeoutPromise]);
      } finally {
        clearTimeout(timeoutId!);
      }
    }
 
    if (!this.isReady()) {
      throw new Error("LaunchDarkly client is not ready");
    }
  }
 
  async track(eventName: string, data?: Record<string, unknown>) {
    if (!this.hasClientSideId) {
      return;
    }
 
    if (!(await this._ensureInitialized())) {
      throw createLaunchDarklyError(
        LAUNCHDARKLY_ERROR_CODES.CLIENT_NOT_INITIALIZED,
        LAUNCHDARKLY_ERROR_MESSAGES.CLIENT_NOT_INITIALIZED,
      );
    }
 
    try {
      await this.client!.track(eventName, data);
    } catch (error) {
      throw createLaunchDarklyError(
        LAUNCHDARKLY_ERROR_CODES.TRACK_FAILED,
        `${LAUNCHDARKLY_ERROR_MESSAGES.TRACK_FAILED}: ${eventName}`,
        error,
      );
    }
  }
 
  async flush() {
    if (!this.client || !this.isInitialized) {
      return;
    }
 
    try {
      await this.client.flush();
    } catch (error) {
      throw createLaunchDarklyError(
        LAUNCHDARKLY_ERROR_CODES.FLUSH_FAILED,
        LAUNCHDARKLY_ERROR_MESSAGES.FLUSH_FAILED,
        error,
      );
    }
  }
 
  async close() {
    if (!this.client) {
      return;
    }
 
    try {
      this.removeAllFlagChangeListeners();
      await this.client.close();
      this._resetState();
    } catch (error) {
      throw createLaunchDarklyError(
        LAUNCHDARKLY_ERROR_CODES.CLOSE_FAILED,
        LAUNCHDARKLY_ERROR_MESSAGES.CLOSE_FAILED,
        error,
      );
    }
  }
 
  async clearUser() {
    if (!this.hasClientSideId) {
      return;
    }
 
    await this._waitForInitIfNeeded();
 
    if (!this.client || !this.isInitialized) {
      return;
    }
 
    try {
      const anonymousContext = createAnonymousContext();
      await this.client.identify(anonymousContext);
      this.currentContext = anonymousContext;
      this._setupGlobalChangeHandler();
    } catch (error) {
      throw createLaunchDarklyError(
        LAUNCHDARKLY_ERROR_CODES.CLEAR_USER_FAILED,
        LAUNCHDARKLY_ERROR_MESSAGES.CLEAR_USER_FAILED,
        error,
      );
    }
  }
 
  onFlagChange(flagKey: string, handler: FlagChangeHandler): () => void {
    if (!this.flagChangeListeners.has(flagKey)) {
      this.flagChangeListeners.set(flagKey, new Set());
    }
 
    this.flagChangeListeners.get(flagKey)!.add(handler);
    this._setupGlobalChangeHandler();
 
    return () => {
      const listeners = this.flagChangeListeners.get(flagKey);
      if (listeners) {
        listeners.delete(handler);
        if (listeners.size === 0) {
          this.flagChangeListeners.delete(flagKey);
        }
      }
    };
  }
 
  private _setupGlobalChangeHandler(): void {
    if (!this.client || !this.isInitialized) {
      return;
    }
 
    if (this.globalChangeHandler) {
      try {
        this.client.off("change", this.globalChangeHandler);
      } catch {
        // Non-critical
      }
    }
 
    this.globalChangeHandler = (_context: LDContext, changedKeys: string[]) => {
      for (const flagKey of changedKeys) {
        const listeners = this.flagChangeListeners.get(flagKey);
        if (listeners?.size) {
          listeners.forEach((handler) => {
            try {
              handler(flagKey, undefined);
            } catch (error) {
              console.error(
                `[LaunchDarkly] Error in flag change handler for ${flagKey}:`,
                error,
              );
            }
          });
        }
      }
    };
 
    try {
      this.client.on("change", this.globalChangeHandler);
    } catch (error) {
      console.error(
        "[LaunchDarkly] Failed to register change listener:",
        error,
      );
      this.globalChangeHandler = null;
    }
  }
 
  removeAllFlagChangeListeners(): void {
    this.flagChangeListeners.clear();
    if (this.client && this.globalChangeHandler) {
      try {
        this.client.off("change", this.globalChangeHandler);
      } catch {
        // Non-critical
      }
      this.globalChangeHandler = null;
    }
  }
 
  private _resetState(): void {
    this.client = null;
    this.currentContext = null;
    this.isInitialized = false;
    this.hasClientSideId = false;
    this.initPromise = null;
  }
}
 
export const launchdarklyService = new LaunchDarklyService();
export default launchdarklyService;