# Feature Flag Integrations

Integrations for feature flag providers including LaunchDarkly, OpenFeature, Statsig, and Unleash, allowing automatic tracking of feature flag evaluations and usage in your application.

## Capabilities

### LaunchDarkly Integration

Automatic instrumentation for LaunchDarkly feature flag evaluations.

```typescript { .api }
/**
 * Create LaunchDarkly integration for automatic feature flag tracking
 * @param options - LaunchDarkly integration configuration options
 * @returns LaunchDarkly integration instance
 */
function launchDarklyIntegration(options?: LaunchDarklyOptions): Integration;

/**
 * Build a flag used handler for LaunchDarkly client
 * @param client - Sentry client instance
 * @returns Flag used handler function
 */
function buildLaunchDarklyFlagUsedHandler(client: Client): FlagUsedHandler;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import * as ld from "@launchdarkly/node-server-sdk";

// Initialize with LaunchDarkly integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.launchDarklyIntegration({
      captureFlags: true, // Include flag keys and values in context
      captureVariations: true, // Include variation details
    }),
  ],
});

// LaunchDarkly client with Sentry handler
const ldClient = ld.init("YOUR_SDK_KEY", {
  hooks: {
    flagUsed: Sentry.buildLaunchDarklyFlagUsedHandler(Sentry.getClient()),
  },
});

await ldClient.waitForInitialization();

// Feature flag evaluations will be automatically tracked
const showFeature = await ldClient.variation("show-feature", user, false);
const featureConfig = await ldClient.variationDetail("feature-config", user, {});
```

### OpenFeature Integration

Automatic instrumentation for OpenFeature providers and flag evaluations.

```typescript { .api }
/**
 * Create OpenFeature integration for automatic feature flag tracking
 * @param options - OpenFeature integration configuration options
 * @returns OpenFeature integration instance
 */
function openFeatureIntegration(options?: OpenFeatureOptions): Integration;

/**
 * OpenFeature integration hook type
 */
type OpenFeatureIntegrationHook = {
  after: (hookContext: HookContext, details: EvaluationDetails) => void;
  error: (hookContext: HookContext, error: Error) => void;
};
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import { OpenFeature, InMemoryProvider } from "@openfeature/server-sdk";

// Initialize with OpenFeature integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.openFeatureIntegration({
      captureFlags: true,
      captureProviderInfo: true, // Include provider information
    }),
  ],
});

// Set up OpenFeature provider
OpenFeature.setProvider(new InMemoryProvider({
  "show-feature": { variants: { on: true, off: false }, defaultVariant: "off" },
}));

const client = OpenFeature.getClient();

// Feature flag evaluations will be automatically tracked
const showFeature = await client.getBooleanValue("show-feature", false, { userId: "123" });
const featureVariant = await client.getStringValue("feature-variant", "default", { userId: "123" });
```

### Statsig Integration

Automatic instrumentation for Statsig feature flags and experiments.

```typescript { .api }
/**
 * Create Statsig integration for automatic feature flag and experiment tracking
 * @param options - Statsig integration configuration options
 * @returns Statsig integration instance
 */
function statsigIntegration(options?: StatsigOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import Statsig from "statsig-node";

// Initialize with Statsig integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.statsigIntegration({
      captureGates: true, // Include feature gate evaluations
      captureConfigs: true, // Include dynamic config evaluations
      captureExperiments: true, // Include experiment assignments
    }),
  ],
});

// Initialize Statsig
await Statsig.initialize("YOUR_SERVER_SECRET_KEY");

const user = { userID: "123", email: "user@example.com" };

// Feature flag evaluations will be automatically tracked
const showFeature = Statsig.checkGate(user, "show_new_feature");
const config = Statsig.getConfig(user, "app_config");
const experiment = Statsig.getExperiment(user, "button_color_test");
```

### Unleash Integration

Automatic instrumentation for Unleash feature toggle evaluations.

```typescript { .api }
/**
 * Create Unleash integration for automatic feature toggle tracking
 * @param options - Unleash integration configuration options
 * @returns Unleash integration instance
 */
function unleashIntegration(options?: UnleashOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import { initialize, isEnabled, getVariant } from "unleash-client";

// Initialize with Unleash integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.unleashIntegration({
      captureToggles: true, // Include toggle evaluations
      captureVariants: true, // Include variant selections
    }),
  ],
});

// Initialize Unleash client
const unleash = initialize({
  url: "https://your-unleash-instance.com/api/",
  appName: "my-node-app",
  instanceId: "my-unique-instance-id",
});

await unleash.start();

const unleashContext = {
  userId: "123",
  sessionId: "session-123",
  remoteAddress: "127.0.0.1",
};

// Feature toggle evaluations will be automatically tracked  
const showFeature = isEnabled("show_new_feature", unleashContext);
const variant = getVariant("feature_variant", unleashContext);
```

### Generic Feature Flags Integration

General-purpose feature flags integration for custom providers.

```typescript { .api }
/**
 * Create generic feature flags integration for custom flag tracking
 * @param options - Feature flags integration configuration options
 * @returns Feature flags integration instance
 */
function featureFlagsIntegration(options?: FeatureFlagsOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";

// Initialize with generic feature flags integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.featureFlagsIntegration({
      provider: "custom", // Your provider name
      autoCapture: false, // Manual flag tracking
    }),
  ],
});

// Manual feature flag tracking
function evaluateFeatureFlag(flagKey: string, userId: string, defaultValue: boolean): boolean {
  const result = yourCustomFlagProvider.evaluate(flagKey, userId, defaultValue);
  
  // Manually track feature flag evaluation
  Sentry.setContext("feature_flags", {
    [flagKey]: {
      value: result,
      userId,
      provider: "custom",
      timestamp: Date.now(),
    },
  });
  
  return result;
}

// Usage
const showFeature = evaluateFeatureFlag("show_new_feature", "user-123", false);
```

## Types

### Integration Options

```typescript { .api }
interface LaunchDarklyOptions {
  /** Include flag keys and values in context */
  captureFlags?: boolean;
  /** Include variation details in spans */
  captureVariations?: boolean;
  /** Maximum number of flags to capture per evaluation */
  maxFlags?: number;
}

interface OpenFeatureOptions {
  /** Include flag keys and values in context */
  captureFlags?: boolean;
  /** Include provider information in context */
  captureProviderInfo?: boolean;
  /** Maximum number of flags to capture per evaluation */
  maxFlags?: number;
}

interface StatsigOptions {
  /** Include feature gate evaluations */
  captureGates?: boolean;
  /** Include dynamic config evaluations */
  captureConfigs?: boolean;
  /** Include experiment assignments */
  captureExperiments?: boolean;
  /** Maximum number of evaluations to capture */
  maxEvaluations?: number;
}

interface UnleashOptions {
  /** Include toggle evaluations */
  captureToggles?: boolean;
  /** Include variant selections */
  captureVariants?: boolean;
  /** Maximum number of toggles to capture per evaluation */
  maxToggles?: number;
}

interface FeatureFlagsOptions {
  /** Provider name for identification */
  provider?: string;
  /** Automatically capture flag evaluations */
  autoCapture?: boolean;
  /** Custom flag evaluation handler */
  onFlagEvaluated?: (flagData: FlagEvaluationData) => void;
}

interface FlagEvaluationData {
  /** Flag key/name */
  key: string;
  /** Evaluated value */
  value: any;
  /** User context */
  user?: any;
  /** Provider name */
  provider?: string;
  /** Evaluation timestamp */
  timestamp?: number;
  /** Additional metadata */
  metadata?: Record<string, any>;
}

type FlagUsedHandler = (flagKey: string, value: any, variationDetail?: any) => void;
```