@flipswitch-io/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,305 @@
1
+ import { ProviderMetadata, EvaluationContext, ResolutionDetails, JsonValue } from '@openfeature/core';
2
+
3
+ /**
4
+ * Configuration options for the Flipswitch provider.
5
+ */
6
+ interface FlipswitchOptions {
7
+ /**
8
+ * The API key for your environment.
9
+ * Obtain this from your Flipswitch dashboard.
10
+ */
11
+ apiKey: string;
12
+ /**
13
+ * The base URL of your Flipswitch server.
14
+ * @default 'https://api.flipswitch.io'
15
+ */
16
+ baseUrl?: string;
17
+ /**
18
+ * Enable real-time flag updates via SSE.
19
+ * When enabled, the provider will connect to the SSE endpoint
20
+ * and automatically invalidate cached flags when changes occur.
21
+ * @default true
22
+ */
23
+ enableRealtime?: boolean;
24
+ /**
25
+ * Enable telemetry collection.
26
+ * When enabled, the SDK sends usage statistics (SDK version, runtime version,
27
+ * OS, architecture) to help improve the service. No personal data is collected.
28
+ * @default true
29
+ */
30
+ enableTelemetry?: boolean;
31
+ /**
32
+ * Custom fetch function for making HTTP requests.
33
+ * Useful for testing or custom networking needs.
34
+ */
35
+ fetchImplementation?: typeof fetch;
36
+ }
37
+ /**
38
+ * Event emitted when a flag changes.
39
+ */
40
+ interface FlagChangeEvent {
41
+ /**
42
+ * The ID of the environment where the change occurred.
43
+ */
44
+ environmentId: number;
45
+ /**
46
+ * The key of the flag that changed, or null for bulk invalidation.
47
+ */
48
+ flagKey: string | null;
49
+ /**
50
+ * ISO timestamp of when the change occurred.
51
+ */
52
+ timestamp: string;
53
+ }
54
+ /**
55
+ * SSE connection status.
56
+ */
57
+ type SseConnectionStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
58
+ /**
59
+ * Event handler types for the provider.
60
+ */
61
+ interface FlipswitchEventHandlers {
62
+ /**
63
+ * Called when a flag changes.
64
+ */
65
+ onFlagChange?: (event: FlagChangeEvent) => void;
66
+ /**
67
+ * Called when the SSE connection status changes.
68
+ */
69
+ onConnectionStatusChange?: (status: SseConnectionStatus) => void;
70
+ }
71
+ /**
72
+ * Represents the result of evaluating a single flag.
73
+ */
74
+ interface FlagEvaluation {
75
+ /**
76
+ * The flag key.
77
+ */
78
+ key: string;
79
+ /**
80
+ * The evaluated value.
81
+ */
82
+ value: unknown;
83
+ /**
84
+ * The inferred type of the value.
85
+ */
86
+ valueType: 'boolean' | 'string' | 'number' | 'object' | 'array' | 'null' | 'unknown';
87
+ /**
88
+ * The reason for this evaluation result.
89
+ */
90
+ reason: string | null;
91
+ /**
92
+ * The variant that matched, if applicable.
93
+ */
94
+ variant: string | null;
95
+ }
96
+
97
+ type ProviderStatus = 'NOT_READY' | 'READY' | 'ERROR' | 'STALE';
98
+ type ProviderEvent = 'PROVIDER_READY' | 'PROVIDER_ERROR' | 'PROVIDER_STALE' | 'PROVIDER_CONFIGURATION_CHANGED';
99
+ type EventHandler = () => void;
100
+ /**
101
+ * Flipswitch OpenFeature provider with real-time SSE support.
102
+ *
103
+ * This provider wraps the OFREP provider for flag evaluation and adds
104
+ * real-time updates via Server-Sent Events (SSE).
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * import { FlipswitchProvider } from '@flipswitch-io/sdk';
109
+ * import { OpenFeature } from '@openfeature/web-sdk';
110
+ *
111
+ * // Only API key is required - defaults to https://api.flipswitch.io
112
+ * const provider = new FlipswitchProvider({
113
+ * apiKey: 'your-api-key'
114
+ * });
115
+ *
116
+ * await OpenFeature.setProviderAndWait(provider);
117
+ * const client = OpenFeature.getClient();
118
+ * const darkMode = await client.getBooleanValue('dark-mode', false);
119
+ * ```
120
+ */
121
+ declare class FlipswitchProvider {
122
+ readonly metadata: ProviderMetadata;
123
+ readonly rulesFromFlagValue = false;
124
+ private readonly baseUrl;
125
+ private readonly apiKey;
126
+ private readonly enableRealtime;
127
+ private readonly enableTelemetry;
128
+ private readonly fetchImpl;
129
+ private readonly ofrepProvider;
130
+ private sseClient;
131
+ private _status;
132
+ private eventHandlers;
133
+ private userEventHandlers;
134
+ constructor(options: FlipswitchOptions, eventHandlers?: FlipswitchEventHandlers);
135
+ private getTelemetrySdkHeader;
136
+ private getTelemetryRuntimeHeader;
137
+ private getTelemetryOsHeader;
138
+ private getTelemetryFeaturesHeader;
139
+ private getTelemetryHeaders;
140
+ get status(): ProviderStatus;
141
+ /**
142
+ * Initialize the provider.
143
+ * Validates the API key and starts SSE connection if real-time is enabled.
144
+ */
145
+ initialize(context?: EvaluationContext): Promise<void>;
146
+ /**
147
+ * Called when the provider is shut down.
148
+ */
149
+ onClose(): Promise<void>;
150
+ /**
151
+ * Start the SSE connection for real-time updates.
152
+ */
153
+ private startSseConnection;
154
+ /**
155
+ * Get telemetry headers as a map.
156
+ */
157
+ private getTelemetryHeadersMap;
158
+ /**
159
+ * Handle a flag change event from SSE.
160
+ * Emits PROVIDER_CONFIGURATION_CHANGED to trigger re-evaluation.
161
+ */
162
+ private handleFlagChange;
163
+ /**
164
+ * Emit an event to registered handlers.
165
+ */
166
+ private emit;
167
+ /**
168
+ * Register an event handler.
169
+ */
170
+ onProviderEvent?(event: ProviderEvent, handler: EventHandler): void;
171
+ resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext): ResolutionDetails<boolean>;
172
+ resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext): ResolutionDetails<string>;
173
+ resolveNumberEvaluation(flagKey: string, defaultValue: number, context: EvaluationContext): ResolutionDetails<number>;
174
+ resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T, context: EvaluationContext): ResolutionDetails<T>;
175
+ /**
176
+ * Get SSE connection status.
177
+ */
178
+ getSseStatus(): SseConnectionStatus;
179
+ /**
180
+ * Force reconnect SSE connection.
181
+ */
182
+ reconnectSse(): void;
183
+ /**
184
+ * Transform OpenFeature context to OFREP context format.
185
+ */
186
+ private transformContext;
187
+ /**
188
+ * Infer the type of a value.
189
+ */
190
+ private inferType;
191
+ /**
192
+ * Get flag type from metadata or infer from value.
193
+ */
194
+ private getFlagType;
195
+ /**
196
+ * Format a value for display.
197
+ */
198
+ formatValue(value: unknown): string;
199
+ /**
200
+ * Evaluate all flags for the given context.
201
+ * Returns a list of all flag evaluations with their keys, values, types, and reasons.
202
+ *
203
+ * Note: This method makes direct HTTP calls since OFREP providers don't expose
204
+ * the bulk evaluation API.
205
+ *
206
+ * @param context The evaluation context
207
+ * @returns List of flag evaluations
208
+ */
209
+ evaluateAllFlags(context: EvaluationContext): Promise<FlagEvaluation[]>;
210
+ /**
211
+ * Evaluate a single flag and return its evaluation result.
212
+ *
213
+ * Note: This method makes direct HTTP calls for demo purposes.
214
+ * For standard flag evaluation, use the OpenFeature client methods.
215
+ *
216
+ * @param flagKey The flag key to evaluate
217
+ * @param context The evaluation context
218
+ * @returns The flag evaluation, or null if the flag doesn't exist
219
+ */
220
+ evaluateFlag(flagKey: string, context: EvaluationContext): Promise<FlagEvaluation | null>;
221
+ }
222
+
223
+ /**
224
+ * SSE client for real-time flag change notifications.
225
+ * Handles automatic reconnection with exponential backoff.
226
+ */
227
+ declare class SseClient {
228
+ private readonly baseUrl;
229
+ private readonly apiKey;
230
+ private readonly onFlagChange;
231
+ private readonly onStatusChange?;
232
+ private readonly telemetryHeaders?;
233
+ private eventSource;
234
+ private retryDelay;
235
+ private reconnectTimeout;
236
+ private closed;
237
+ private status;
238
+ constructor(baseUrl: string, apiKey: string, onFlagChange: (event: FlagChangeEvent) => void, onStatusChange?: ((status: SseConnectionStatus) => void) | undefined, telemetryHeaders?: Record<string, string> | undefined);
239
+ /**
240
+ * Start the SSE connection.
241
+ */
242
+ connect(): void;
243
+ /**
244
+ * Connect using fetch-based SSE (supports custom headers).
245
+ */
246
+ private connectWithFetch;
247
+ /**
248
+ * Connect using native EventSource (for environments that support it).
249
+ * Note: This requires server-side support for API key in query params.
250
+ */
251
+ private connectWithPolyfill;
252
+ /**
253
+ * Handle incoming SSE events.
254
+ */
255
+ private handleEvent;
256
+ /**
257
+ * Schedule a reconnection attempt with exponential backoff.
258
+ */
259
+ private scheduleReconnect;
260
+ /**
261
+ * Update and broadcast connection status.
262
+ */
263
+ private updateStatus;
264
+ /**
265
+ * Get current connection status.
266
+ */
267
+ getStatus(): SseConnectionStatus;
268
+ /**
269
+ * Close the SSE connection and stop reconnection attempts.
270
+ */
271
+ close(): void;
272
+ }
273
+
274
+ /**
275
+ * Simple in-memory cache for flag values with TTL support.
276
+ */
277
+ declare class FlagCache {
278
+ private cache;
279
+ private readonly ttlMs;
280
+ /**
281
+ * Create a new FlagCache.
282
+ * @param ttlMs Time-to-live in milliseconds (default: 5 minutes)
283
+ */
284
+ constructor(ttlMs?: number);
285
+ /**
286
+ * Get a value from the cache.
287
+ * Returns undefined if the key doesn't exist or has expired.
288
+ */
289
+ get<T>(key: string): T | undefined;
290
+ /**
291
+ * Set a value in the cache.
292
+ */
293
+ set<T>(key: string, value: T): void;
294
+ /**
295
+ * Invalidate a specific key or all keys if no key is provided.
296
+ */
297
+ invalidate(key?: string): void;
298
+ /**
299
+ * Handle a flag change event from SSE.
300
+ * Invalidates the specific flag or all flags if flagKey is null.
301
+ */
302
+ handleFlagChange(event: FlagChangeEvent): void;
303
+ }
304
+
305
+ export { FlagCache, type FlagChangeEvent, type FlagEvaluation, type FlipswitchEventHandlers, type FlipswitchOptions, FlipswitchProvider, SseClient, type SseConnectionStatus };