@datadog/mobile-react-native-openfeature 3.9.0 → 3.10.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.
Files changed (61) hide show
  1. package/README.md +118 -10
  2. package/lib/commonjs/datadogCoreProvider.js +129 -0
  3. package/lib/commonjs/datadogCoreProvider.js.map +1 -0
  4. package/lib/commonjs/offlineEvaluation.js +198 -0
  5. package/lib/commonjs/offlineEvaluation.js.map +1 -0
  6. package/lib/commonjs/offlineProvider.js +44 -8
  7. package/lib/commonjs/offlineProvider.js.map +1 -1
  8. package/lib/commonjs/rules-based.js +62 -0
  9. package/lib/commonjs/rules-based.js.map +1 -0
  10. package/lib/module/datadogCoreProvider.js +122 -0
  11. package/lib/module/datadogCoreProvider.js.map +1 -0
  12. package/lib/module/offlineEvaluation.js +192 -0
  13. package/lib/module/offlineEvaluation.js.map +1 -0
  14. package/lib/module/offlineProvider.js +45 -9
  15. package/lib/module/offlineProvider.js.map +1 -1
  16. package/lib/module/rules-based.js +50 -0
  17. package/lib/module/rules-based.js.map +1 -0
  18. package/lib/typescript/core/src/config/FileBasedConfiguration.d.ts.map +1 -1
  19. package/lib/typescript/core/src/config/FileBasedConfiguration.type.d.ts +2 -0
  20. package/lib/typescript/core/src/config/FileBasedConfiguration.type.d.ts.map +1 -1
  21. package/lib/typescript/core/src/config/async/AutoInstrumentationConfiguration.d.ts +4 -0
  22. package/lib/typescript/core/src/config/async/AutoInstrumentationConfiguration.d.ts.map +1 -1
  23. package/lib/typescript/core/src/config/async/PartialInitializationConfiguration.d.ts +2 -0
  24. package/lib/typescript/core/src/config/async/PartialInitializationConfiguration.d.ts.map +1 -1
  25. package/lib/typescript/core/src/config/features/RumConfiguration.d.ts +4 -0
  26. package/lib/typescript/core/src/config/features/RumConfiguration.d.ts.map +1 -1
  27. package/lib/typescript/core/src/config/features/RumConfiguration.type.d.ts +21 -0
  28. package/lib/typescript/core/src/config/features/RumConfiguration.type.d.ts.map +1 -1
  29. package/lib/typescript/core/src/config/features/RumConfigurationNative.d.ts +2 -0
  30. package/lib/typescript/core/src/config/features/RumConfigurationNative.d.ts.map +1 -1
  31. package/lib/typescript/core/src/flags/FlagsClient.d.ts +38 -1
  32. package/lib/typescript/core/src/flags/FlagsClient.d.ts.map +1 -1
  33. package/lib/typescript/core/src/flags/internal.d.ts +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/version.d.ts +1 -1
  38. package/lib/typescript/core/src/version.d.ts.map +1 -1
  39. package/lib/typescript/react-native-openfeature/src/datadogCoreProvider.d.ts +31 -0
  40. package/lib/typescript/react-native-openfeature/src/datadogCoreProvider.d.ts.map +1 -0
  41. package/lib/typescript/react-native-openfeature/src/index.d.ts +1 -0
  42. package/lib/typescript/react-native-openfeature/src/index.d.ts.map +1 -1
  43. package/lib/typescript/react-native-openfeature/src/offlineEvaluation.d.ts +33 -0
  44. package/lib/typescript/react-native-openfeature/src/offlineEvaluation.d.ts.map +1 -0
  45. package/lib/typescript/react-native-openfeature/src/offlineProvider.d.ts +14 -8
  46. package/lib/typescript/react-native-openfeature/src/offlineProvider.d.ts.map +1 -1
  47. package/lib/typescript/react-native-openfeature/src/rules-based.d.ts +17 -0
  48. package/lib/typescript/react-native-openfeature/src/rules-based.d.ts.map +1 -0
  49. package/package.json +8 -4
  50. package/rules-based/package.json +7 -0
  51. package/src/__tests__/__utils__/coreConfiguration.ts +84 -0
  52. package/src/__tests__/datadogCoreProvider.integration.test.ts +230 -0
  53. package/src/__tests__/datadogCoreProvider.test.ts +587 -0
  54. package/src/__tests__/entrypoints.test.ts +35 -0
  55. package/src/__tests__/offlineProvider.delegation.test.ts +795 -0
  56. package/src/__tests__/offlineProvider.test.ts +74 -10
  57. package/src/datadogCoreProvider.ts +223 -0
  58. package/src/index.ts +1 -0
  59. package/src/offlineEvaluation.ts +295 -0
  60. package/src/offlineProvider.ts +64 -13
  61. package/src/rules-based.ts +58 -0
@@ -4,6 +4,9 @@
4
4
  * Copyright 2016-Present Datadog, Inc.
5
5
  */
6
6
 
7
+ import { InternalLog, SdkVerbosity } from '@datadog/mobile-react-native';
8
+ import type { FlagsClient } from '@datadog/mobile-react-native';
9
+ import type { EvaluationContext } from '@openfeature/web-sdk';
7
10
  import {
8
11
  ErrorCode,
9
12
  GeneralError,
@@ -14,15 +17,34 @@ import {
14
17
 
15
18
  import { DatadogOfflineOpenFeatureProvider } from '../offlineProvider';
16
19
 
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' };
20
+ import {
21
+ precomputedConfiguration,
22
+ rulesConfiguration
23
+ } from './__utils__/coreConfiguration';
24
+
25
+ type ConfigurationResult = ReturnType<FlagsClient['setConfiguration']>;
26
+ const READY: ConfigurationResult = { status: 'ready' };
27
+ const mismatch: ConfigurationResult = {
28
+ status: 'error',
29
+ errorCode: 'INVALID_CONTEXT'
30
+ };
31
+ const notReady: ConfigurationResult = {
32
+ status: 'error',
33
+ errorCode: 'PROVIDER_NOT_READY'
34
+ };
35
+ const generalError: ConfigurationResult = {
36
+ status: 'error',
37
+ errorCode: 'GENERAL'
38
+ };
21
39
 
22
40
  const mockFlagsClient = {
23
- setConfiguration: jest.fn(() => READY),
24
- setEvaluationContextWithoutFetching: jest.fn(() => READY),
25
- resetEvaluationContextWithoutFetching: jest.fn(() => READY),
41
+ setConfiguration: jest.fn((): ConfigurationResult => READY),
42
+ setEvaluationContextWithoutFetching: jest.fn(
43
+ (): ConfigurationResult => READY
44
+ ),
45
+ resetEvaluationContextWithoutFetching: jest.fn(
46
+ (): ConfigurationResult => READY
47
+ ),
26
48
  setEvaluationContext: jest.fn(() => Promise.resolve()),
27
49
  getBooleanDetails: jest.fn(() => ({
28
50
  key: 'flag',
@@ -35,11 +57,13 @@ const mockFlagsClient = {
35
57
  jest.mock('@datadog/mobile-react-native', () => {
36
58
  return {
37
59
  DdFlags: { getClient: jest.fn(() => mockFlagsClient) },
38
- configurationFromString: jest.fn()
60
+ configurationFromString: jest.fn(),
61
+ InternalLog: { log: jest.fn() },
62
+ SdkVerbosity: { WARN: 'warn' }
39
63
  };
40
64
  });
41
65
 
42
- describe('DatadogOfflineOpenFeatureProvider', () => {
66
+ describe('DatadogOfflineOpenFeatureProvider (legacy core SDK without the evaluator bridge)', () => {
43
67
  beforeEach(() => {
44
68
  jest.clearAllMocks();
45
69
  mockFlagsClient.setConfiguration.mockReturnValue(READY);
@@ -51,6 +75,44 @@ describe('DatadogOfflineOpenFeatureProvider', () => {
51
75
  );
52
76
  });
53
77
 
78
+ afterEach(() => {
79
+ jest.restoreAllMocks();
80
+ });
81
+
82
+ it('rejects rules on an older core SDK instead of silently ignoring them or serving stale flags', () => {
83
+ const warning = jest.mocked(InternalLog.log);
84
+ const provider = new DatadogOfflineOpenFeatureProvider();
85
+ const emit = jest.spyOn(provider.events, 'emit');
86
+
87
+ provider.setConfiguration(rulesConfiguration());
88
+
89
+ expect(mockFlagsClient.setConfiguration).toHaveBeenCalledWith({});
90
+ expect(emit).toHaveBeenCalledWith(
91
+ ProviderEvents.Error,
92
+ expect.objectContaining({ errorCode: ErrorCode.GENERAL })
93
+ );
94
+ expect(warning).toHaveBeenCalledWith(
95
+ expect.stringContaining('Update both Datadog packages together'),
96
+ SdkVerbosity.WARN
97
+ );
98
+ });
99
+
100
+ it('keeps usable precomputed data on an older core SDK when only the rules branch failed to parse', () => {
101
+ const warning = jest.mocked(InternalLog.log);
102
+ const provider = new DatadogOfflineOpenFeatureProvider();
103
+ const configuration = {
104
+ ...precomputedConfiguration(),
105
+ rulesError: 'Malformed rules'
106
+ };
107
+
108
+ provider.setConfiguration(configuration);
109
+
110
+ expect(mockFlagsClient.setConfiguration).toHaveBeenCalledWith(
111
+ configuration
112
+ );
113
+ expect(warning).not.toHaveBeenCalled();
114
+ });
115
+
54
116
  it('advertises the offline provider name', () => {
55
117
  expect(new DatadogOfflineOpenFeatureProvider().metadata.name).toBe(
56
118
  'datadog-react-native-offline'
@@ -157,7 +219,9 @@ describe('DatadogOfflineOpenFeatureProvider', () => {
157
219
  it('treats a context with only an undefined targetingKey as empty', () => {
158
220
  const provider = new DatadogOfflineOpenFeatureProvider();
159
221
 
160
- provider.onContextChange({}, { targetingKey: undefined });
222
+ provider.onContextChange({}, ({
223
+ targetingKey: undefined
224
+ } as unknown) as EvaluationContext);
161
225
 
162
226
  // `{ targetingKey: undefined }` carries no information: reset to the embedded context.
163
227
  expect(
@@ -0,0 +1,223 @@
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
+ FlagsConfiguration,
9
+ FlagsConfigurationError,
10
+ FlagTypeToValue
11
+ } from '@datadog/flagging-core';
12
+ import { evaluate, getFlagsConfigurationError } from '@datadog/flagging-core';
13
+ import {
14
+ InvalidContextError,
15
+ OpenFeatureEventEmitter,
16
+ ParseError,
17
+ ProviderEvents,
18
+ ProviderNotReadyError
19
+ } from '@openfeature/web-sdk';
20
+ import type {
21
+ EvaluationContext,
22
+ FlagValueType,
23
+ JsonValue,
24
+ Logger,
25
+ OpenFeatureError,
26
+ Paradigm,
27
+ Provider,
28
+ ProviderEventEmitter,
29
+ ProviderMetadata,
30
+ ResolutionDetails
31
+ } from '@openfeature/web-sdk';
32
+
33
+ /**
34
+ * Evaluates manually supplied configurations in JavaScript using @datadog/flagging-core.
35
+ * Ported from openfeature-js-client's browser DatadogCoreProvider.
36
+ *
37
+ * Unlike the native-backed providers, this provider does not use DdFlags, fetch configuration,
38
+ * or send exposure/RUM events. Load a configuration before registering it with OpenFeature.
39
+ * Precomputed configurations require a matching OpenFeature context, including when it is empty.
40
+ */
41
+ export class DatadogCoreEvaluationProvider implements Provider {
42
+ readonly metadata: ProviderMetadata = { name: 'datadog-core' };
43
+ readonly runsOn: Paradigm = 'client';
44
+ readonly events: ProviderEventEmitter<ProviderEvents> = new OpenFeatureEventEmitter();
45
+
46
+ private flagsConfiguration: FlagsConfiguration | undefined;
47
+ private flagsConfigurationId: string | undefined;
48
+ private context: EvaluationContext | undefined;
49
+
50
+ getConfiguration(): FlagsConfiguration | undefined {
51
+ return this.flagsConfiguration;
52
+ }
53
+
54
+ setConfiguration(configuration: FlagsConfiguration): void {
55
+ const hadEvaluatableConfiguration = this.canEvaluateCurrentContext();
56
+ // Untyped callers can pass a non-object (e.g. `null`), which flagging-core cannot read.
57
+ // Like any other unusable configuration, it replaces the previous one and surfaces
58
+ // PARSE_ERROR until a valid configuration is set.
59
+ if (typeof configuration !== 'object' || configuration === null) {
60
+ this.flagsConfiguration = {
61
+ configurationError: 'Flags configuration must be an object'
62
+ };
63
+ this.flagsConfigurationId = undefined;
64
+ } else {
65
+ this.flagsConfiguration = configuration;
66
+ this.flagsConfigurationId = this.computeConfigurationId(
67
+ configuration
68
+ );
69
+ }
70
+
71
+ if (this.context === undefined) {
72
+ return;
73
+ }
74
+
75
+ const error = toOpenFeatureError(
76
+ getFlagsConfigurationError(this.flagsConfiguration, this.context)
77
+ );
78
+ if (error) {
79
+ // The web-sdk's ErrorEvent type omits errorCode, but its provider wrapper reads it.
80
+ const details = {
81
+ error,
82
+ message: error.message,
83
+ errorCode: error.code
84
+ };
85
+ this.events.emit(ProviderEvents.Error, details);
86
+ return;
87
+ }
88
+
89
+ if (!hadEvaluatableConfiguration) {
90
+ this.events.emit(ProviderEvents.Ready);
91
+ }
92
+ this.events.emit(ProviderEvents.ConfigurationChanged);
93
+ }
94
+
95
+ initialize(context: EvaluationContext = {}): Promise<void> {
96
+ this.context = context;
97
+ const error = toOpenFeatureError(
98
+ getFlagsConfigurationError(this.flagsConfiguration, context)
99
+ );
100
+ return error ? Promise.reject(error) : Promise.resolve();
101
+ }
102
+
103
+ onContextChange(
104
+ _oldContext: EvaluationContext,
105
+ newContext: EvaluationContext
106
+ ): void {
107
+ this.context = newContext;
108
+ const error = toOpenFeatureError(
109
+ getFlagsConfigurationError(this.flagsConfiguration, this.context)
110
+ );
111
+ if (error) {
112
+ throw error;
113
+ }
114
+ }
115
+
116
+ resolveBooleanEvaluation(
117
+ flagKey: string,
118
+ defaultValue: boolean,
119
+ context: EvaluationContext,
120
+ logger: Logger
121
+ ): ResolutionDetails<boolean> {
122
+ return this.resolve('boolean', flagKey, defaultValue, context, logger);
123
+ }
124
+
125
+ resolveStringEvaluation(
126
+ flagKey: string,
127
+ defaultValue: string,
128
+ context: EvaluationContext,
129
+ logger: Logger
130
+ ): ResolutionDetails<string> {
131
+ return this.resolve('string', flagKey, defaultValue, context, logger);
132
+ }
133
+
134
+ resolveNumberEvaluation(
135
+ flagKey: string,
136
+ defaultValue: number,
137
+ context: EvaluationContext,
138
+ logger: Logger
139
+ ): ResolutionDetails<number> {
140
+ return this.resolve('number', flagKey, defaultValue, context, logger);
141
+ }
142
+
143
+ resolveObjectEvaluation<T extends JsonValue>(
144
+ flagKey: string,
145
+ defaultValue: T,
146
+ context: EvaluationContext,
147
+ logger: Logger
148
+ ): ResolutionDetails<T> {
149
+ // OpenFeature requires a specific JsonValue subtype without runtime type information.
150
+ // Callers must provide a default value with the expected shape.
151
+ return this.resolve(
152
+ 'object',
153
+ flagKey,
154
+ defaultValue,
155
+ context,
156
+ logger
157
+ ) as ResolutionDetails<T>;
158
+ }
159
+
160
+ private resolve<T extends FlagValueType>(
161
+ type: T,
162
+ flagKey: string,
163
+ defaultValue: FlagTypeToValue<T>,
164
+ context: EvaluationContext,
165
+ logger: Logger
166
+ ): ResolutionDetails<FlagTypeToValue<T>> {
167
+ const details = evaluate(
168
+ this.flagsConfiguration,
169
+ type,
170
+ flagKey,
171
+ defaultValue,
172
+ context,
173
+ logger
174
+ );
175
+ if (
176
+ this.flagsConfigurationId === undefined ||
177
+ details.flagMetadata?.doLog !== true ||
178
+ typeof details.flagMetadata?.allocationKey !== 'string' ||
179
+ details.variant == null
180
+ ) {
181
+ return details;
182
+ }
183
+
184
+ // Preserve the browser provider's configuration identity for consumers of evaluation metadata.
185
+ return {
186
+ ...details,
187
+ flagMetadata: {
188
+ ...details.flagMetadata,
189
+ __dd_core_configuration_id: this.flagsConfigurationId
190
+ }
191
+ };
192
+ }
193
+
194
+ private canEvaluateCurrentContext(): boolean {
195
+ return (
196
+ this.context !== undefined &&
197
+ !getFlagsConfigurationError(this.flagsConfiguration, this.context)
198
+ );
199
+ }
200
+
201
+ // The `/rules-based` entry adds the browser's configuration identity. Hashing a rules
202
+ // configuration needs the protobuf encoder, which the main entry must not load.
203
+ protected computeConfigurationId(
204
+ _configuration: FlagsConfiguration
205
+ ): string | undefined {
206
+ return undefined;
207
+ }
208
+ }
209
+
210
+ function toOpenFeatureError(
211
+ error: FlagsConfigurationError | undefined
212
+ ): OpenFeatureError | undefined {
213
+ if (!error) {
214
+ return undefined;
215
+ }
216
+ if (error.errorCode === 'PARSE_ERROR') {
217
+ return new ParseError(error.errorMessage);
218
+ }
219
+ if (error.errorCode === 'INVALID_CONTEXT') {
220
+ return new InvalidContextError(error.errorMessage);
221
+ }
222
+ return new ProviderNotReadyError(error.errorMessage);
223
+ }
package/src/index.ts CHANGED
@@ -19,3 +19,4 @@ export {
19
19
  configurationFromString
20
20
  };
21
21
  export type { DatadogOpenFeatureProviderOptions, EnrichableEvaluationContext };
22
+ export type { FlagsConfiguration } from '@datadog/flagging-core';
@@ -0,0 +1,295 @@
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 { configMatchesContext } from '@datadog/flagging-core';
8
+ import type {
9
+ FlagsConfiguration,
10
+ PrecomputedFlag
11
+ } from '@datadog/flagging-core';
12
+ import { InternalLog, SdkVerbosity } from '@datadog/mobile-react-native';
13
+ import type {
14
+ EvaluationContext,
15
+ FlagsClient,
16
+ FlagDetails
17
+ } from '@datadog/mobile-react-native';
18
+ import { ErrorCode, OpenFeatureError } from '@openfeature/web-sdk';
19
+ import type {
20
+ EvaluationContext as OFEvaluationContext,
21
+ FlagValueType,
22
+ JsonValue,
23
+ Logger,
24
+ ResolutionDetails
25
+ } from '@openfeature/web-sdk';
26
+
27
+ import { DatadogCoreEvaluationProvider } from './datadogCoreProvider';
28
+
29
+ // Keep the bridge contract owned by FlagsClient; no OpenFeature dependency enters the core SDK.
30
+ type CreateEvaluator = Parameters<FlagsClient['__ddSetOfflineEvaluator']>[0];
31
+ type CompatibilityHelpers = Parameters<CreateEvaluator>[0];
32
+ type OfflineEvaluator = ReturnType<CreateEvaluator>;
33
+ type FlagCache = ReturnType<CompatibilityHelpers['decodePrecomputedFlags']>;
34
+ type FlagCacheEntry = FlagCache extends Map<string, infer Entry>
35
+ ? Entry
36
+ : never;
37
+
38
+ const logger: Logger = {
39
+ debug: message => InternalLog.log(String(message), SdkVerbosity.DEBUG),
40
+ info: message => InternalLog.log(String(message), SdkVerbosity.INFO),
41
+ warn: message => InternalLog.log(String(message), SdkVerbosity.WARN),
42
+ error: message => InternalLog.log(String(message), SdkVerbosity.ERROR)
43
+ };
44
+
45
+ /**
46
+ * Compatibility adapter for the released offline provider. DatadogCoreProvider owns evaluation;
47
+ * the named FlagsClient owns this adapter and native exposure/RUM delivery. Only the legacy
48
+ * precomputed input/context normalization and native tracking representation are adapted here.
49
+ */
50
+ export class OfflineEvaluation implements OfflineEvaluator {
51
+ private readonly core = new DatadogCoreEvaluationProvider();
52
+ private readonly configuration: FlagsConfiguration;
53
+ private precomputedFlags: FlagCache = new Map();
54
+ private context: EvaluationContext = { targetingKey: '', attributes: {} };
55
+ private coreContext: OFEvaluationContext = {};
56
+ // Whether the active context selects the precomputed snapshot. Fixed until the next reconcile.
57
+ private servesPrecomputed = false;
58
+
59
+ constructor(
60
+ configuration: FlagsConfiguration,
61
+ helpers: CompatibilityHelpers
62
+ ) {
63
+ this.configuration = { ...configuration };
64
+ const precomputed = configuration?.precomputed;
65
+ if (
66
+ !precomputed &&
67
+ !this.configuration.rules &&
68
+ this.configuration.configurationError === undefined &&
69
+ this.configuration.precomputedError === undefined &&
70
+ this.configuration.rulesError === undefined
71
+ ) {
72
+ // A bare {} has no capability. The precomputed-only parser returns it for a rules-only wire.
73
+ InternalLog.log(
74
+ 'DatadogOfflineOpenFeatureProvider received no precomputed or rules configuration. configurationFromString is precomputed-only; parse rules-based wires with coreConfigurationFromString from the /rules-based entry point.',
75
+ SdkVerbosity.WARN
76
+ );
77
+ }
78
+ if (precomputed) {
79
+ try {
80
+ this.precomputedFlags = helpers.decodePrecomputedFlags(
81
+ precomputed.response as Parameters<
82
+ CompatibilityHelpers['decodePrecomputedFlags']
83
+ >[0]
84
+ );
85
+ const flags: Record<
86
+ string,
87
+ PrecomputedFlag
88
+ > = Object.fromEntries(
89
+ Array.from(this.precomputedFlags, ([key, flag]) => [
90
+ key,
91
+ {
92
+ allocationKey: flag.allocationKey,
93
+ variationKey: flag.variationKey,
94
+ // The released client checks the value's runtime type, including integer/float
95
+ // aliases and object-typed payloads containing primitives. Keep that behavior.
96
+ variationType: typeof flag.value as FlagValueType,
97
+ variationValue: flag.value as JsonValue,
98
+ reason: flag.reason,
99
+ doLog: flag.doLog,
100
+ // The native decoder does not keep the split serial ID; read it from the wire.
101
+ serialId:
102
+ precomputed.response.data.attributes.flags[key]
103
+ ?.serialId
104
+ }
105
+ ])
106
+ );
107
+ this.configuration.precomputed = {
108
+ ...precomputed,
109
+ context: precomputed.context
110
+ ? toOpenFeatureContext(
111
+ helpers.normalizeWireContext(precomputed.context)
112
+ )
113
+ : undefined,
114
+ // The native decoder omits malformed entries; flagging-core's parser reports them.
115
+ flagErrors: precomputed.flagErrors,
116
+ response: {
117
+ data: {
118
+ attributes: {
119
+ createdAt:
120
+ precomputed.response.data.attributes
121
+ .createdAt,
122
+ flags
123
+ }
124
+ }
125
+ }
126
+ };
127
+ } catch (error) {
128
+ // A malformed precomputed branch must not hide a usable rules branch.
129
+ this.configuration.precomputed = undefined;
130
+ this.configuration.precomputedError =
131
+ error instanceof Error ? error.message : String(error);
132
+ }
133
+ }
134
+ this.core.setConfiguration(this.configuration);
135
+ }
136
+
137
+ reconcile(
138
+ context: EvaluationContext | undefined,
139
+ hasTargetingKey = typeof context?.targetingKey === 'string'
140
+ ): ReturnType<OfflineEvaluator['reconcile']> {
141
+ // An omitted override adopts the normalized embedded context. Rules-only configurations
142
+ // must not invent an anonymous subject: missing and explicitly empty keys differ.
143
+ const embedded = this.configuration.precomputed?.context;
144
+ this.context =
145
+ context ??
146
+ (embedded
147
+ ? {
148
+ targetingKey: embedded.targetingKey ?? '',
149
+ attributes: withoutTargetingKey(embedded)
150
+ }
151
+ : { targetingKey: '', attributes: {} });
152
+ const normalizedContext = toOpenFeatureContext(this.context);
153
+ // Snapshot matching retains released normalization/adoption. Only rules fallback uses the
154
+ // original subject presence; native tracking still receives the normalized context.
155
+ this.coreContext =
156
+ configMatchesContext(this.configuration, normalizedContext) ||
157
+ hasTargetingKey === true
158
+ ? normalizedContext
159
+ : withoutTargetingKey(normalizedContext);
160
+ this.servesPrecomputed = configMatchesContext(
161
+ this.configuration,
162
+ this.coreContext
163
+ );
164
+ try {
165
+ // Synchronous validation preserves the offline provider's context-change lifecycle.
166
+ this.core.onContextChange({}, this.coreContext);
167
+ return { status: 'ready' };
168
+ } catch (error) {
169
+ const code =
170
+ error instanceof OpenFeatureError
171
+ ? error.code
172
+ : ErrorCode.GENERAL;
173
+ return {
174
+ status: 'error',
175
+ errorCode:
176
+ code === ErrorCode.INVALID_CONTEXT ||
177
+ code === ErrorCode.PROVIDER_NOT_READY ||
178
+ code === ErrorCode.PARSE_ERROR
179
+ ? code
180
+ : ErrorCode.GENERAL
181
+ };
182
+ }
183
+ }
184
+
185
+ evaluate<T>(
186
+ key: string,
187
+ defaultValue: T,
188
+ type: FlagValueType
189
+ ): {
190
+ details: FlagDetails<T>;
191
+ exposure?: { flag: FlagCacheEntry; context: EvaluationContext };
192
+ } {
193
+ const context = this.coreContext;
194
+ const result = this.resolve(key, defaultValue, type, context);
195
+ const allocationKey = result.flagMetadata?.allocationKey;
196
+ const details: FlagDetails<T> = {
197
+ key,
198
+ value: result.value,
199
+ reason: result.reason ?? 'UNKNOWN',
200
+ variant: result.variant,
201
+ allocationKey:
202
+ typeof allocationKey === 'string' ? allocationKey : undefined,
203
+ errorCode: result.errorCode,
204
+ errorMessage: result.errorMessage
205
+ };
206
+ if (
207
+ result.errorCode ||
208
+ typeof allocationKey !== 'string' ||
209
+ result.variant === undefined
210
+ ) {
211
+ return { details };
212
+ }
213
+
214
+ // Reuse original precomputed tracking metadata (including extraLogging and variationType).
215
+ // A rules result has no native cache entry, so build the same native tracking shape from
216
+ // the actual evaluated result, never from the fallback/default value.
217
+ const precomputed = this.servesPrecomputed
218
+ ? this.precomputedFlags.get(key)
219
+ : undefined;
220
+ const serialId = result.flagMetadata?.__dd_split_serial_id;
221
+ const serial =
222
+ typeof serialId === 'number' ? { serialId: String(serialId) } : {};
223
+ const flag: FlagCacheEntry = precomputed
224
+ ? { ...precomputed, ...serial }
225
+ : {
226
+ key,
227
+ value: result.value,
228
+ allocationKey,
229
+ variationKey: result.variant,
230
+ variationType: type,
231
+ variationValue:
232
+ typeof result.value === 'object'
233
+ ? JSON.stringify(result.value)
234
+ : String(result.value),
235
+ reason: result.reason ?? 'UNKNOWN',
236
+ doLog: result.flagMetadata?.doLog === true,
237
+ extraLogging: {},
238
+ ...serial
239
+ };
240
+ // Even doLog=false evaluations reach native code: RUM tracking is independent of exposures.
241
+ return { details, exposure: { flag, context: this.context } };
242
+ }
243
+
244
+ private resolve<T>(
245
+ key: string,
246
+ defaultValue: T,
247
+ type: FlagValueType,
248
+ context: OFEvaluationContext
249
+ ): ResolutionDetails<T> {
250
+ // FlagsClient's typed getters guarantee the default's type. OpenFeature's object method
251
+ // additionally relies on the caller's JSON shape, just as DatadogCoreProvider does.
252
+ switch (type) {
253
+ case 'boolean':
254
+ return this.core.resolveBooleanEvaluation(
255
+ key,
256
+ defaultValue as boolean,
257
+ context,
258
+ logger
259
+ ) as ResolutionDetails<T>;
260
+ case 'string':
261
+ return this.core.resolveStringEvaluation(
262
+ key,
263
+ defaultValue as string,
264
+ context,
265
+ logger
266
+ ) as ResolutionDetails<T>;
267
+ case 'number':
268
+ return this.core.resolveNumberEvaluation(
269
+ key,
270
+ defaultValue as number,
271
+ context,
272
+ logger
273
+ ) as ResolutionDetails<T>;
274
+ case 'object':
275
+ return this.core.resolveObjectEvaluation(
276
+ key,
277
+ defaultValue as JsonValue,
278
+ context,
279
+ logger
280
+ ) as ResolutionDetails<T>;
281
+ }
282
+ }
283
+ }
284
+
285
+ function toOpenFeatureContext(context: EvaluationContext): OFEvaluationContext {
286
+ return { ...context.attributes, targetingKey: context.targetingKey };
287
+ }
288
+
289
+ function withoutTargetingKey(
290
+ context: OFEvaluationContext
291
+ ): NonNullable<EvaluationContext['attributes']> {
292
+ const { targetingKey, ...attributes } = context;
293
+ // This context has already passed through FlagsClient's primitive-only normalization.
294
+ return attributes as NonNullable<EvaluationContext['attributes']>;
295
+ }