@datadog/mobile-react-native-openfeature 3.5.2 → 3.5.4

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.
Files changed (58) hide show
  1. package/README.md +77 -0
  2. package/lib/commonjs/coreProvider.js +79 -0
  3. package/lib/commonjs/coreProvider.js.map +1 -0
  4. package/lib/commonjs/index.js +14 -0
  5. package/lib/commonjs/index.js.map +1 -1
  6. package/lib/commonjs/mappers.js +50 -0
  7. package/lib/commonjs/mappers.js.map +1 -0
  8. package/lib/commonjs/offlineProvider.js +149 -0
  9. package/lib/commonjs/offlineProvider.js.map +1 -0
  10. package/lib/commonjs/provider.js +9 -73
  11. package/lib/commonjs/provider.js.map +1 -1
  12. package/lib/module/coreProvider.js +72 -0
  13. package/lib/module/coreProvider.js.map +1 -0
  14. package/lib/module/index.js +3 -1
  15. package/lib/module/index.js.map +1 -1
  16. package/lib/module/mappers.js +42 -0
  17. package/lib/module/mappers.js.map +1 -0
  18. package/lib/module/offlineProvider.js +143 -0
  19. package/lib/module/offlineProvider.js.map +1 -0
  20. package/lib/module/provider.js +7 -71
  21. package/lib/module/provider.js.map +1 -1
  22. package/lib/typescript/core/src/flags/FlagsClient.d.ts +96 -0
  23. package/lib/typescript/core/src/flags/FlagsClient.d.ts.map +1 -1
  24. package/lib/typescript/core/src/flags/configuration/context.d.ts +20 -0
  25. package/lib/typescript/core/src/flags/configuration/context.d.ts.map +1 -0
  26. package/lib/typescript/core/src/flags/configuration/index.d.ts +5 -0
  27. package/lib/typescript/core/src/flags/configuration/index.d.ts.map +1 -0
  28. package/lib/typescript/core/src/flags/configuration/precomputed.d.ts +25 -0
  29. package/lib/typescript/core/src/flags/configuration/precomputed.d.ts.map +1 -0
  30. package/lib/typescript/core/src/flags/configuration/types.d.ts +24 -0
  31. package/lib/typescript/core/src/flags/configuration/types.d.ts.map +1 -0
  32. package/lib/typescript/core/src/flags/configuration/wire.d.ts +2 -0
  33. package/lib/typescript/core/src/flags/configuration/wire.d.ts.map +1 -0
  34. package/lib/typescript/core/src/flags/internal.d.ts.map +1 -1
  35. package/lib/typescript/core/src/flags/types.d.ts +1 -1
  36. package/lib/typescript/core/src/flags/types.d.ts.map +1 -1
  37. package/lib/typescript/core/src/index.d.ts +4 -2
  38. package/lib/typescript/core/src/index.d.ts.map +1 -1
  39. package/lib/typescript/core/src/version.d.ts +1 -1
  40. package/lib/typescript/react-native-openfeature/src/coreProvider.d.ts +34 -0
  41. package/lib/typescript/react-native-openfeature/src/coreProvider.d.ts.map +1 -0
  42. package/lib/typescript/react-native-openfeature/src/index.d.ts +3 -1
  43. package/lib/typescript/react-native-openfeature/src/index.d.ts.map +1 -1
  44. package/lib/typescript/react-native-openfeature/src/mappers.d.ts +20 -0
  45. package/lib/typescript/react-native-openfeature/src/mappers.d.ts.map +1 -0
  46. package/lib/typescript/react-native-openfeature/src/offlineProvider.d.ts +59 -0
  47. package/lib/typescript/react-native-openfeature/src/offlineProvider.d.ts.map +1 -0
  48. package/lib/typescript/react-native-openfeature/src/provider.d.ts +8 -21
  49. package/lib/typescript/react-native-openfeature/src/provider.d.ts.map +1 -1
  50. package/package.json +5 -5
  51. package/src/__tests__/offlineProvider.integration.test.ts +271 -0
  52. package/src/__tests__/offlineProvider.test.ts +252 -0
  53. package/src/__tests__/provider.test.ts +74 -0
  54. package/src/coreProvider.ts +142 -0
  55. package/src/index.ts +8 -1
  56. package/src/mappers.ts +47 -0
  57. package/src/offlineProvider.ts +185 -0
  58. package/src/provider.ts +10 -139
@@ -0,0 +1,252 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ import {
8
+ ErrorCode,
9
+ GeneralError,
10
+ InvalidContextError,
11
+ ProviderEvents,
12
+ ProviderNotReadyError
13
+ } from '@openfeature/web-sdk';
14
+
15
+ import { DatadogOfflineOpenFeatureProvider } from '../offlineProvider';
16
+
17
+ const READY = { status: 'ready' as const };
18
+ const mismatch = { status: 'error' as const, errorCode: 'INVALID_CONTEXT' };
19
+ const notReady = { status: 'error' as const, errorCode: 'PROVIDER_NOT_READY' };
20
+ const generalError = { status: 'error' as const, errorCode: 'GENERAL' };
21
+
22
+ const mockFlagsClient = {
23
+ setConfiguration: jest.fn(() => READY),
24
+ setEvaluationContextWithoutFetching: jest.fn(() => READY),
25
+ resetEvaluationContextWithoutFetching: jest.fn(() => READY),
26
+ setEvaluationContext: jest.fn(() => Promise.resolve()),
27
+ getBooleanDetails: jest.fn(() => ({
28
+ key: 'flag',
29
+ value: true,
30
+ reason: 'STATIC',
31
+ variant: 'true'
32
+ }))
33
+ };
34
+
35
+ jest.mock('@datadog/mobile-react-native', () => {
36
+ return {
37
+ DdFlags: { getClient: jest.fn(() => mockFlagsClient) },
38
+ configurationFromString: jest.fn()
39
+ };
40
+ });
41
+
42
+ describe('DatadogOfflineOpenFeatureProvider', () => {
43
+ beforeEach(() => {
44
+ jest.clearAllMocks();
45
+ mockFlagsClient.setConfiguration.mockReturnValue(READY);
46
+ mockFlagsClient.setEvaluationContextWithoutFetching.mockReturnValue(
47
+ READY
48
+ );
49
+ mockFlagsClient.resetEvaluationContextWithoutFetching.mockReturnValue(
50
+ READY
51
+ );
52
+ });
53
+
54
+ it('advertises the offline provider name', () => {
55
+ expect(new DatadogOfflineOpenFeatureProvider().metadata.name).toBe(
56
+ 'datadog-react-native-offline'
57
+ );
58
+ });
59
+
60
+ it('re-adopts the embedded context on an empty initialize context', async () => {
61
+ const provider = new DatadogOfflineOpenFeatureProvider();
62
+
63
+ await provider.initialize({});
64
+
65
+ // An empty context means "no external override": reset to the embedded context rather
66
+ // than setting an (empty) override.
67
+ expect(
68
+ mockFlagsClient.resetEvaluationContextWithoutFetching
69
+ ).toHaveBeenCalled();
70
+ expect(
71
+ mockFlagsClient.setEvaluationContextWithoutFetching
72
+ ).not.toHaveBeenCalled();
73
+ expect(mockFlagsClient.setEvaluationContext).not.toHaveBeenCalled();
74
+ });
75
+
76
+ it('records a non-empty context without fetching', async () => {
77
+ const provider = new DatadogOfflineOpenFeatureProvider();
78
+
79
+ await provider.initialize({ targetingKey: 'user-1' });
80
+
81
+ expect(
82
+ mockFlagsClient.setEvaluationContextWithoutFetching
83
+ ).toHaveBeenCalledWith(
84
+ expect.objectContaining({ targetingKey: 'user-1' })
85
+ );
86
+ expect(mockFlagsClient.setEvaluationContext).not.toHaveBeenCalled();
87
+ });
88
+
89
+ it('rejects initialize when the initial context does not match', async () => {
90
+ const provider = new DatadogOfflineOpenFeatureProvider();
91
+ mockFlagsClient.setEvaluationContextWithoutFetching.mockReturnValueOnce(
92
+ mismatch
93
+ );
94
+
95
+ await expect(
96
+ provider.initialize({ targetingKey: 'user-2' })
97
+ ).rejects.toThrow(InvalidContextError);
98
+ });
99
+
100
+ it('rejects initialize when no configuration is loaded (provider-first)', async () => {
101
+ const provider = new DatadogOfflineOpenFeatureProvider();
102
+ mockFlagsClient.resetEvaluationContextWithoutFetching.mockReturnValueOnce(
103
+ notReady
104
+ );
105
+
106
+ await expect(provider.initialize({})).rejects.toThrow(
107
+ ProviderNotReadyError
108
+ );
109
+ });
110
+
111
+ it('reconciles a matching context change without fetching or signalling a change', () => {
112
+ const provider = new DatadogOfflineOpenFeatureProvider();
113
+ const emitSpy = jest.spyOn(provider.events, 'emit');
114
+
115
+ provider.onContextChange({}, { targetingKey: 'user-2' });
116
+
117
+ expect(
118
+ mockFlagsClient.setEvaluationContextWithoutFetching
119
+ ).toHaveBeenCalledWith(
120
+ expect.objectContaining({ targetingKey: 'user-2' })
121
+ );
122
+ expect(mockFlagsClient.setEvaluationContext).not.toHaveBeenCalled();
123
+ // The Web SDK owns the READY/CONTEXT_CHANGED transition on a resolving context change;
124
+ // the provider itself emits nothing.
125
+ expect(emitSpy).not.toHaveBeenCalledWith(
126
+ ProviderEvents.ConfigurationChanged
127
+ );
128
+ expect(emitSpy).not.toHaveBeenCalledWith(ProviderEvents.Ready);
129
+ });
130
+
131
+ it('throws synchronously from onContextChange on a mismatching context', () => {
132
+ const provider = new DatadogOfflineOpenFeatureProvider();
133
+ mockFlagsClient.setEvaluationContextWithoutFetching.mockReturnValueOnce(
134
+ mismatch
135
+ );
136
+
137
+ // Synchronous throw so the Web SDK transitions straight to ERROR (no async race).
138
+ expect(() =>
139
+ provider.onContextChange({}, { targetingKey: 'user-2' })
140
+ ).toThrow(InvalidContextError);
141
+ });
142
+
143
+ it('re-adopts the embedded context on clearContext / empty context change', () => {
144
+ const provider = new DatadogOfflineOpenFeatureProvider();
145
+
146
+ provider.onContextChange({ targetingKey: 'user-1' }, {});
147
+
148
+ // Clearing context is not a mismatch: it re-adopts the embedded context and does not throw.
149
+ expect(
150
+ mockFlagsClient.resetEvaluationContextWithoutFetching
151
+ ).toHaveBeenCalled();
152
+ expect(
153
+ mockFlagsClient.setEvaluationContextWithoutFetching
154
+ ).not.toHaveBeenCalled();
155
+ });
156
+
157
+ it('treats a context with only an undefined targetingKey as empty', () => {
158
+ const provider = new DatadogOfflineOpenFeatureProvider();
159
+
160
+ provider.onContextChange({}, { targetingKey: undefined });
161
+
162
+ // `{ targetingKey: undefined }` carries no information: reset to the embedded context.
163
+ expect(
164
+ mockFlagsClient.resetEvaluationContextWithoutFetching
165
+ ).toHaveBeenCalled();
166
+ expect(
167
+ mockFlagsClient.setEvaluationContextWithoutFetching
168
+ ).not.toHaveBeenCalled();
169
+ });
170
+
171
+ it('delegates setConfiguration to the client and emits CONFIGURATION_CHANGED', () => {
172
+ const provider = new DatadogOfflineOpenFeatureProvider();
173
+ const emitSpy = jest.spyOn(provider.events, 'emit');
174
+
175
+ provider.setConfiguration({} as never);
176
+
177
+ expect(mockFlagsClient.setConfiguration).toHaveBeenCalled();
178
+ // A healthy (re)loaded config is a configuration change, not a status transition.
179
+ expect(emitSpy).toHaveBeenCalledWith(
180
+ ProviderEvents.ConfigurationChanged
181
+ );
182
+ expect(emitSpy).not.toHaveBeenCalledWith(ProviderEvents.Ready);
183
+ });
184
+
185
+ it('emits PROVIDER_ERROR with a top-level errorCode on an invalid configuration', () => {
186
+ const provider = new DatadogOfflineOpenFeatureProvider();
187
+ const emitSpy = jest.spyOn(provider.events, 'emit');
188
+
189
+ mockFlagsClient.setConfiguration.mockReturnValueOnce(generalError);
190
+ provider.setConfiguration({} as never);
191
+
192
+ expect(emitSpy).toHaveBeenCalledWith(
193
+ ProviderEvents.Error,
194
+ expect.objectContaining({
195
+ message: expect.any(String),
196
+ errorCode: ErrorCode.GENERAL
197
+ })
198
+ );
199
+ });
200
+
201
+ it('recovers on a later valid configuration, emitting READY then CONFIGURATION_CHANGED', () => {
202
+ const provider = new DatadogOfflineOpenFeatureProvider();
203
+ const emitSpy = jest.spyOn(provider.events, 'emit');
204
+
205
+ mockFlagsClient.setConfiguration.mockReturnValueOnce(mismatch);
206
+ provider.setConfiguration({} as never);
207
+ expect(emitSpy).toHaveBeenCalledWith(
208
+ ProviderEvents.Error,
209
+ expect.objectContaining({ errorCode: ErrorCode.INVALID_CONTEXT })
210
+ );
211
+
212
+ // A subsequent valid config recovers: READY clears the ERROR status, CONFIGURATION_CHANGED
213
+ // signals the new flags.
214
+ provider.setConfiguration({} as never);
215
+ expect(emitSpy).toHaveBeenCalledWith(ProviderEvents.Ready);
216
+ expect(emitSpy).toHaveBeenCalledWith(
217
+ ProviderEvents.ConfigurationChanged
218
+ );
219
+ });
220
+
221
+ it('rejects initialize when a config was loaded (pre-registration) and is invalid', async () => {
222
+ const provider = new DatadogOfflineOpenFeatureProvider();
223
+ mockFlagsClient.setConfiguration.mockReturnValueOnce(generalError);
224
+ provider.setConfiguration({} as never);
225
+
226
+ // A pre-registration setConfiguration error had no listeners, and the empty initialize
227
+ // context reconciles to the same error, so initialize rejects -> the Web SDK starts the
228
+ // provider in ERROR rather than a misleading READY.
229
+ mockFlagsClient.resetEvaluationContextWithoutFetching.mockReturnValueOnce(
230
+ generalError
231
+ );
232
+ await expect(provider.initialize({})).rejects.toThrow(GeneralError);
233
+ });
234
+
235
+ it('resolves boolean evaluation through the client', () => {
236
+ const provider = new DatadogOfflineOpenFeatureProvider();
237
+
238
+ const result = provider.resolveBooleanEvaluation(
239
+ 'flag',
240
+ false,
241
+ {},
242
+ // eslint-disable-next-line no-console
243
+ console as never
244
+ );
245
+
246
+ expect(result.value).toBe(true);
247
+ expect(mockFlagsClient.getBooleanDetails).toHaveBeenCalledWith(
248
+ 'flag',
249
+ false
250
+ );
251
+ });
252
+ });
@@ -0,0 +1,74 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ import { DatadogOpenFeatureProvider } from '../provider';
8
+
9
+ const mockFlagsClient = {
10
+ setEvaluationContext: jest.fn(() => Promise.resolve()),
11
+ setEvaluationContextWithoutFetching: jest.fn(() => 'ready'),
12
+ getBooleanDetails: jest.fn(() => ({
13
+ key: 'flag',
14
+ value: true,
15
+ reason: 'STATIC',
16
+ variant: 'true'
17
+ }))
18
+ };
19
+
20
+ jest.mock('@datadog/mobile-react-native', () => {
21
+ return {
22
+ DdFlags: { getClient: jest.fn(() => mockFlagsClient) },
23
+ configurationFromString: jest.fn()
24
+ };
25
+ });
26
+
27
+ describe('DatadogOpenFeatureProvider', () => {
28
+ beforeEach(() => {
29
+ jest.clearAllMocks();
30
+ });
31
+
32
+ it('advertises the online provider name', () => {
33
+ expect(new DatadogOpenFeatureProvider().metadata.name).toBe(
34
+ 'datadog-react-native'
35
+ );
36
+ });
37
+
38
+ it('fetches on initialize (uses the fetching setEvaluationContext)', async () => {
39
+ const provider = new DatadogOpenFeatureProvider();
40
+
41
+ await provider.initialize({ targetingKey: 'user-1' });
42
+
43
+ expect(mockFlagsClient.setEvaluationContext).toHaveBeenCalledWith(
44
+ expect.objectContaining({ targetingKey: 'user-1' })
45
+ );
46
+ expect(
47
+ mockFlagsClient.setEvaluationContextWithoutFetching
48
+ ).not.toHaveBeenCalled();
49
+ });
50
+
51
+ it('fetches on a context change', async () => {
52
+ const provider = new DatadogOpenFeatureProvider();
53
+
54
+ await provider.onContextChange({}, { targetingKey: 'user-2' });
55
+
56
+ expect(mockFlagsClient.setEvaluationContext).toHaveBeenCalledWith(
57
+ expect.objectContaining({ targetingKey: 'user-2' })
58
+ );
59
+ });
60
+
61
+ it('resolves boolean evaluation through the client', () => {
62
+ const provider = new DatadogOpenFeatureProvider();
63
+
64
+ const result = provider.resolveBooleanEvaluation(
65
+ 'flag',
66
+ false,
67
+ {},
68
+ // eslint-disable-next-line no-console
69
+ console as never
70
+ );
71
+
72
+ expect(result.value).toBe(true);
73
+ });
74
+ });
@@ -0,0 +1,142 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ import { DdFlags } from '@datadog/mobile-react-native';
8
+ import type { FlagDetails, FlagsClient } from '@datadog/mobile-react-native';
9
+ import { OpenFeatureEventEmitter, ErrorCode } from '@openfeature/web-sdk';
10
+ import type {
11
+ EvaluationContext as OFEvaluationContext,
12
+ JsonValue,
13
+ Logger,
14
+ Paradigm,
15
+ Provider,
16
+ ProviderMetadata,
17
+ ResolutionDetails,
18
+ ProviderEventEmitter,
19
+ ProviderEvents
20
+ } from '@openfeature/web-sdk';
21
+
22
+ export interface DatadogOpenFeatureProviderOptions {
23
+ /**
24
+ * The name of the Datadog Flags client to use.
25
+ *
26
+ * Provide this parameter in order to use different Datadog Flags clients for different OpenFeature domains.
27
+ *
28
+ * @default 'default'
29
+ */
30
+ clientName?: string;
31
+ }
32
+
33
+ /**
34
+ * Shared base for the Datadog OpenFeature providers. It owns the `FlagsClient`, the event
35
+ * emitter, and evaluation (`resolveX`) — everything the online and offline providers have in
36
+ * common. It does not decide how the evaluation context is sourced (fetch vs. offline load);
37
+ * concrete providers implement `initialize`/`onContextChange`.
38
+ *
39
+ * Internal: not exported from the package entry point. Customers use
40
+ * `DatadogOpenFeatureProvider` (online) or `DatadogOfflineOpenFeatureProvider` (offline).
41
+ */
42
+ export abstract class DatadogCoreOpenFeatureProvider implements Provider {
43
+ readonly runsOn: Paradigm = 'client';
44
+ abstract readonly metadata: ProviderMetadata;
45
+
46
+ private options: DatadogOpenFeatureProviderOptions;
47
+ protected flagsClient: FlagsClient;
48
+
49
+ readonly events: ProviderEventEmitter<ProviderEvents> = new OpenFeatureEventEmitter();
50
+
51
+ constructor(options: DatadogOpenFeatureProviderOptions = {}) {
52
+ if (!options.clientName) {
53
+ options.clientName = 'default';
54
+ }
55
+
56
+ this.options = options;
57
+
58
+ this.flagsClient = DdFlags.getClient(this.options.clientName);
59
+ }
60
+
61
+ resolveBooleanEvaluation(
62
+ flagKey: string,
63
+ defaultValue: boolean,
64
+ _context: OFEvaluationContext,
65
+ _logger: Logger
66
+ ): ResolutionDetails<boolean> {
67
+ const details = this.flagsClient.getBooleanDetails(
68
+ flagKey,
69
+ defaultValue
70
+ );
71
+ return toFlagResolution(details);
72
+ }
73
+
74
+ resolveStringEvaluation(
75
+ flagKey: string,
76
+ defaultValue: string,
77
+ _context: OFEvaluationContext,
78
+ _logger: Logger
79
+ ): ResolutionDetails<string> {
80
+ const details = this.flagsClient.getStringDetails(
81
+ flagKey,
82
+ defaultValue
83
+ );
84
+ return toFlagResolution(details);
85
+ }
86
+
87
+ resolveNumberEvaluation(
88
+ flagKey: string,
89
+ defaultValue: number,
90
+ _context: OFEvaluationContext,
91
+ _logger: Logger
92
+ ): ResolutionDetails<number> {
93
+ const details = this.flagsClient.getNumberDetails(
94
+ flagKey,
95
+ defaultValue
96
+ );
97
+ return toFlagResolution(details);
98
+ }
99
+
100
+ resolveObjectEvaluation<T extends JsonValue>(
101
+ flagKey: string,
102
+ defaultValue: T,
103
+ _context: OFEvaluationContext,
104
+ _logger: Logger
105
+ ): ResolutionDetails<T> {
106
+ // The OpenFeature spec states that the return value can be any valid JSON value.
107
+ // However, the Datadog Flags feature only supports JSON objects for the JSON feature flag type.
108
+ // Thus, the user should always expect the returned value to be an object instead of any arbitrary JSON value.
109
+ // Also, the user is responsible for providing a proper `defaultValue` that's an object.
110
+
111
+ const details = this.flagsClient.getObjectDetails<T>(
112
+ flagKey,
113
+ defaultValue
114
+ );
115
+ return toFlagResolution(details);
116
+ }
117
+ }
118
+
119
+ const toFlagResolution = <T>(details: FlagDetails<T>): ResolutionDetails<T> => {
120
+ const {
121
+ value,
122
+ reason,
123
+ variant,
124
+ allocationKey,
125
+ errorCode,
126
+ errorMessage
127
+ } = details;
128
+
129
+ const parsedErrorCode =
130
+ errorCode && (ErrorCode[errorCode as ErrorCode] || ErrorCode.GENERAL);
131
+
132
+ const result: ResolutionDetails<T> = {
133
+ value,
134
+ reason,
135
+ variant,
136
+ flagMetadata: allocationKey ? { allocationKey } : undefined,
137
+ errorCode: parsedErrorCode,
138
+ errorMessage
139
+ };
140
+
141
+ return result;
142
+ };
package/src/index.ts CHANGED
@@ -4,8 +4,15 @@
4
4
  * Copyright 2016-Present Datadog, Inc.
5
5
  */
6
6
 
7
+ import { configurationFromString } from '@datadog/mobile-react-native';
8
+
9
+ import { DatadogOfflineOpenFeatureProvider } from './offlineProvider';
7
10
  import { DatadogOpenFeatureProvider } from './provider';
8
11
  import type { DatadogOpenFeatureProviderOptions } from './provider';
9
12
 
10
- export { DatadogOpenFeatureProvider };
13
+ export {
14
+ DatadogOpenFeatureProvider,
15
+ DatadogOfflineOpenFeatureProvider,
16
+ configurationFromString
17
+ };
11
18
  export type { DatadogOpenFeatureProviderOptions };
package/src/mappers.ts ADDED
@@ -0,0 +1,47 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ import type {
8
+ EvaluationContext as DdEvaluationContext,
9
+ PrimitiveValue
10
+ } from '@datadog/mobile-react-native';
11
+ import type { EvaluationContext as OFEvaluationContext } from '@openfeature/web-sdk';
12
+
13
+ /**
14
+ * Convert an OpenFeature evaluation context into the Datadog Flags shape.
15
+ */
16
+ export const toDdContext = (
17
+ context: OFEvaluationContext
18
+ ): DdEvaluationContext => {
19
+ const { targetingKey, ...attributes } = context;
20
+
21
+ // Important ⚠️
22
+ // The Flags SDK doesn't support nested non-primitive values in the evaluation context as per OF.3 FFE SDK requirement.
23
+ // However, we let the SDK handle this inside of FlagsClient since it does this processing anyways.
24
+ const ddContextAttributes = attributes as Record<string, PrimitiveValue>;
25
+
26
+ return {
27
+ // Allow flag evaluations without a provided targeting key.
28
+ targetingKey: targetingKey ?? '',
29
+ attributes: ddContextAttributes
30
+ };
31
+ };
32
+
33
+ /**
34
+ * Whether an OpenFeature evaluation context carries no information — no targeting key and no
35
+ * attributes with a defined value (so `{}` and `{ targetingKey: undefined }` are both empty).
36
+ * Used by the offline provider to avoid overwriting a configuration's embedded context with an
37
+ * empty context stamped by the OpenFeature lifecycle.
38
+ *
39
+ * Note: an explicit `targetingKey: ''` is **not** empty. An empty string is a real (anonymous)
40
+ * targeting key — a distinct subject — not the absence of a context. Only a genuinely absent
41
+ * context (`{}` / `clearContext()`) re-adopts the configuration's embedded context; `{ targetingKey:
42
+ * '' }` is reconciled as a real context, so it must match the precomputed snapshot or the provider
43
+ * enters `ERROR` (serving coded defaults) rather than silently serving another subject's flags.
44
+ */
45
+ export const isEmptyContext = (context: OFEvaluationContext): boolean => {
46
+ return Object.values(context).every(value => value === undefined);
47
+ };