@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
@@ -0,0 +1,795 @@
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 { configurationToString } from '@datadog/flagging-core/rules-based';
8
+ import type { FlagsConfiguration } from '@datadog/flagging-core';
9
+ import {
10
+ configurationFromString,
11
+ DdFlags,
12
+ InternalLog
13
+ } from '@datadog/mobile-react-native';
14
+ import type { EvaluationContext } from '@openfeature/web-sdk';
15
+ import {
16
+ ErrorCode,
17
+ OpenFeature,
18
+ ProviderEvents,
19
+ ProviderStatus
20
+ } from '@openfeature/web-sdk';
21
+
22
+ import NativeDdFlagsModule from '../../../core/src/specs/NativeDdFlags';
23
+ import { DatadogCoreEvaluationProvider } from '../datadogCoreProvider';
24
+ import { DatadogOfflineOpenFeatureProvider } from '../index';
25
+ import { coreConfigurationFromString } from '../rules-based';
26
+
27
+ import {
28
+ matchingContext,
29
+ precomputedConfiguration,
30
+ rulesConfiguration,
31
+ rulesWire
32
+ } from './__utils__/coreConfiguration';
33
+
34
+ jest.mock('../../../core/src/specs/NativeDdFlags', () => ({
35
+ __esModule: true,
36
+ default: {
37
+ enable: jest.fn(() => Promise.resolve()),
38
+ setEvaluationContext: jest.fn(() => Promise.resolve({})),
39
+ trackEvaluation: jest.fn(() => Promise.resolve())
40
+ }
41
+ }));
42
+
43
+ const NativeDdFlags = jest.mocked(
44
+ NativeDdFlagsModule as NonNullable<typeof NativeDdFlagsModule>
45
+ );
46
+
47
+ let sequence = 0;
48
+ const logger = {
49
+ debug: jest.fn(),
50
+ info: jest.fn(),
51
+ warn: jest.fn(),
52
+ error: jest.fn()
53
+ };
54
+
55
+ function setup(configuration: FlagsConfiguration) {
56
+ const name = `offline-delegation-${sequence++}`;
57
+ const provider = new DatadogOfflineOpenFeatureProvider({
58
+ clientName: name
59
+ });
60
+ provider.setConfiguration(configuration);
61
+ return { provider, name, flagsClient: DdFlags.getClient(name) };
62
+ }
63
+
64
+ describe('Offline provider delegates to DatadogCoreProvider', () => {
65
+ beforeEach(() => {
66
+ jest.clearAllMocks();
67
+ });
68
+
69
+ afterEach(async () => {
70
+ await OpenFeature.clearProviders();
71
+ await OpenFeature.clearContext();
72
+ OpenFeature.clearHandlers();
73
+ jest.restoreAllMocks();
74
+ });
75
+
76
+ it('delegates all precomputed types and tracks each result once with the embedded context', async () => {
77
+ const boolean = jest.spyOn(
78
+ DatadogCoreEvaluationProvider.prototype,
79
+ 'resolveBooleanEvaluation'
80
+ );
81
+ const string = jest.spyOn(
82
+ DatadogCoreEvaluationProvider.prototype,
83
+ 'resolveStringEvaluation'
84
+ );
85
+ const number = jest.spyOn(
86
+ DatadogCoreEvaluationProvider.prototype,
87
+ 'resolveNumberEvaluation'
88
+ );
89
+ const object = jest.spyOn(
90
+ DatadogCoreEvaluationProvider.prototype,
91
+ 'resolveObjectEvaluation'
92
+ );
93
+ const { provider, name } = setup(precomputedConfiguration());
94
+ await OpenFeature.setProviderAndWait(provider);
95
+ const client = OpenFeature.getClient();
96
+ expect(client.getBooleanValue('boolean-flag', false)).toBe(true);
97
+ expect(client.getStringValue('string-flag', 'default')).toBe('hello');
98
+ expect(client.getNumberValue('number-flag', 0)).toBe(3.14);
99
+ expect(client.getObjectValue('object-flag', {})).toEqual({
100
+ nested: { enabled: true },
101
+ list: [1, 2]
102
+ });
103
+ for (const resolver of [boolean, string, number, object]) {
104
+ expect(resolver).toHaveBeenCalledTimes(1);
105
+ expect(resolver).toHaveBeenCalledWith(
106
+ expect.any(String),
107
+ expect.anything(),
108
+ matchingContext,
109
+ expect.any(Object)
110
+ );
111
+ }
112
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenCalledTimes(4);
113
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenCalledWith(
114
+ name,
115
+ 'object-flag',
116
+ expect.objectContaining({
117
+ value: { nested: { enabled: true }, list: [1, 2] },
118
+ variationValue: '{"nested":{"enabled":true},"list":[1,2]}',
119
+ variationType: 'object',
120
+ doLog: false
121
+ }),
122
+ 'user-1',
123
+ { country: 'US' }
124
+ );
125
+ expect(NativeDdFlags.setEvaluationContext).not.toHaveBeenCalled();
126
+ });
127
+
128
+ it('changes a rules-based value through real OpenFeature context changes and tracks the selected allocation', async () => {
129
+ const resolve = jest.spyOn(
130
+ DatadogCoreEvaluationProvider.prototype,
131
+ 'resolveBooleanEvaluation'
132
+ );
133
+ const { provider, name } = setup(
134
+ coreConfigurationFromString(rulesWire)
135
+ );
136
+ await OpenFeature.setProviderAndWait(provider, {
137
+ targetingKey: 'user-1',
138
+ country: 'CA'
139
+ });
140
+ const client = OpenFeature.getClient();
141
+ expect(client.getBooleanDetails('test-flag', true)).toMatchObject({
142
+ value: false,
143
+ variant: 'off',
144
+ reason: 'SPLIT',
145
+ flagMetadata: { allocationKey: 'fallback' }
146
+ });
147
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenLastCalledWith(
148
+ name,
149
+ 'test-flag',
150
+ expect.objectContaining({
151
+ value: false,
152
+ variationValue: 'false',
153
+ variationKey: 'off',
154
+ allocationKey: 'fallback',
155
+ doLog: false,
156
+ serialId: '7'
157
+ }),
158
+ 'user-1',
159
+ { country: 'CA' }
160
+ );
161
+
162
+ await OpenFeature.setContext(matchingContext);
163
+ expect(client.providerStatus).toBe(ProviderStatus.READY);
164
+ expect(client.getBooleanDetails('test-flag', false)).toMatchObject({
165
+ value: true,
166
+ variant: 'on',
167
+ reason: 'TARGETING_MATCH'
168
+ });
169
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenLastCalledWith(
170
+ name,
171
+ 'test-flag',
172
+ expect.objectContaining({
173
+ value: true,
174
+ variationValue: 'true',
175
+ variationKey: 'on',
176
+ allocationKey: 'allocation',
177
+ doLog: true,
178
+ serialId: '7'
179
+ }),
180
+ 'user-1',
181
+ { country: 'US' }
182
+ );
183
+ expect(resolve).toHaveBeenCalledTimes(2);
184
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenCalledTimes(2);
185
+ expect(NativeDdFlags.setEvaluationContext).not.toHaveBeenCalled();
186
+ });
187
+
188
+ it.each([
189
+ {},
190
+ { country: 'CA' },
191
+ { targetingKey: undefined, country: 'CA' },
192
+ { targetingKey: null, country: 'CA' }
193
+ ])(
194
+ 'does not shard a missing/null subject, but permits an explicitly empty subject: %j',
195
+ async context => {
196
+ const { provider, flagsClient } = setup(rulesConfiguration());
197
+ // Null is untrusted runtime input, not a valid typed OpenFeature targeting key.
198
+ await OpenFeature.setProviderAndWait(
199
+ provider,
200
+ (context as unknown) as EvaluationContext
201
+ );
202
+ const client = OpenFeature.getClient();
203
+ expect(client.getBooleanDetails('test-flag', true)).toMatchObject({
204
+ value: true,
205
+ reason: 'ERROR',
206
+ errorCode: ErrorCode.TARGETING_KEY_MISSING
207
+ });
208
+ expect(
209
+ flagsClient.getBooleanDetails('test-flag', true)
210
+ ).toMatchObject({
211
+ value: true,
212
+ errorCode: ErrorCode.TARGETING_KEY_MISSING
213
+ });
214
+ expect(NativeDdFlags.trackEvaluation).not.toHaveBeenCalled();
215
+
216
+ await OpenFeature.setContext({ targetingKey: '', country: 'CA' });
217
+ expect(client.getBooleanDetails('test-flag', true)).toMatchObject({
218
+ value: false,
219
+ reason: 'SPLIT'
220
+ });
221
+ expect(
222
+ NativeDdFlags.trackEvaluation
223
+ ).toHaveBeenLastCalledWith(
224
+ expect.any(String),
225
+ 'test-flag',
226
+ expect.objectContaining({ value: false }),
227
+ '',
228
+ { country: 'CA' }
229
+ );
230
+ expect(NativeDdFlags.setEvaluationContext).not.toHaveBeenCalled();
231
+ }
232
+ );
233
+
234
+ it('still evaluates unsharded rules without a subject and normalizes native tracking only', async () => {
235
+ const configuration = rulesConfiguration();
236
+ const allocation =
237
+ configuration.rules.response.flags['test-flag'].allocations[0];
238
+ allocation.partitionKey = [];
239
+ allocation.splits.forEach(split => {
240
+ split.ranges = [];
241
+ });
242
+ const { provider } = setup(
243
+ coreConfigurationFromString(configurationToString(configuration))
244
+ );
245
+ await OpenFeature.setProviderAndWait(provider, { country: 'US' });
246
+ expect(
247
+ OpenFeature.getClient().getBooleanDetails('test-flag', false)
248
+ ).toMatchObject({
249
+ value: true,
250
+ reason: 'TARGETING_MATCH'
251
+ });
252
+ expect(
253
+ NativeDdFlags.trackEvaluation
254
+ ).toHaveBeenLastCalledWith(
255
+ expect.any(String),
256
+ 'test-flag',
257
+ expect.objectContaining({ value: true }),
258
+ '',
259
+ { country: 'US' }
260
+ );
261
+ });
262
+
263
+ it('retains precomputed anonymous normalization for missing, null and explicit-empty contexts', async () => {
264
+ const configuration = precomputedConfiguration();
265
+ configuration.precomputed.context = { country: 'CA' };
266
+ const { provider } = setup(configuration);
267
+ await OpenFeature.setProviderAndWait(provider);
268
+ const client = OpenFeature.getClient();
269
+ expect(client.getBooleanValue('boolean-flag', false)).toBe(true);
270
+ for (const context of [
271
+ { country: 'CA' },
272
+ { targetingKey: null, country: 'CA' },
273
+ { targetingKey: '', country: 'CA' }
274
+ ]) {
275
+ // Reconcile each transition on the same client before asserting its value.
276
+ // eslint-disable-next-line no-await-in-loop
277
+ await OpenFeature.setContext(
278
+ (context as unknown) as EvaluationContext
279
+ );
280
+ expect(client.getBooleanValue('boolean-flag', false)).toBe(true);
281
+ }
282
+ expect(NativeDdFlags.setEvaluationContext).not.toHaveBeenCalled();
283
+ });
284
+
285
+ it('shares subject presence across aliases, replacements, resets and combined-source selection', async () => {
286
+ const { provider, name, flagsClient } = setup(rulesConfiguration());
287
+ const alias = new DatadogOfflineOpenFeatureProvider({
288
+ clientName: name
289
+ });
290
+ await OpenFeature.setProviderAndWait(provider, { country: 'CA' });
291
+ alias.setConfiguration(rulesConfiguration());
292
+ expect(flagsClient.getBooleanDetails('test-flag', true).errorCode).toBe(
293
+ ErrorCode.TARGETING_KEY_MISSING
294
+ );
295
+
296
+ const snapshot = precomputedConfiguration();
297
+ snapshot.precomputed.context = { targetingKey: '', country: 'CA' };
298
+ alias.setConfiguration({ ...rulesConfiguration(), ...snapshot });
299
+ // Precomputed matching still uses normalized anonymous context, not raw subject presence.
300
+ expect(flagsClient.getBooleanValue('boolean-flag', false)).toBe(true);
301
+ expect(flagsClient.getBooleanDetails('test-flag', true).errorCode).toBe(
302
+ ErrorCode.FLAG_NOT_FOUND
303
+ );
304
+ await OpenFeature.setContext({ country: 'FR' });
305
+ expect(flagsClient.getBooleanDetails('test-flag', true).errorCode).toBe(
306
+ ErrorCode.TARGETING_KEY_MISSING
307
+ );
308
+ await OpenFeature.clearContext();
309
+ expect(flagsClient.getBooleanValue('boolean-flag', false)).toBe(true);
310
+ alias.setConfiguration(rulesConfiguration());
311
+ expect(flagsClient.getBooleanDetails('test-flag', true).errorCode).toBe(
312
+ ErrorCode.TARGETING_KEY_MISSING
313
+ );
314
+ flagsClient.setEvaluationContextWithoutFetching({
315
+ targetingKey: '',
316
+ attributes: { country: 'CA' }
317
+ });
318
+ expect(OpenFeature.getClient().getBooleanValue('test-flag', true)).toBe(
319
+ false
320
+ );
321
+ expect(NativeDdFlags.setEvaluationContext).not.toHaveBeenCalled();
322
+ });
323
+
324
+ it('evaluates string, number, and object rules and encodes their native tracking values', async () => {
325
+ const configuration = rulesConfiguration();
326
+ const response = configuration.rules.response;
327
+ const base = response.flags['test-flag'];
328
+ const stringIndex = response.strings.push('hello') - 1;
329
+ const jsonIndex = response.jsonStrings.push('{"enabled":true}') - 1;
330
+ // UFC variation types: STRING=1, NUMERIC=3, JSON=5. Round-trip the wire so the evaluator
331
+ // rebuilds its prepared-rule indexes rather than relying on mutations to a prepared response.
332
+ response.flags['string-flag'] = {
333
+ ...base,
334
+ variationType: 1,
335
+ variations: base.variations.map(variation => ({
336
+ ...variation,
337
+ value: { case: 'stringValueIndex', value: stringIndex }
338
+ }))
339
+ };
340
+ response.flags['number-flag'] = {
341
+ ...base,
342
+ variationType: 3,
343
+ variations: base.variations.map(variation => ({
344
+ ...variation,
345
+ value: { case: 'numericValue', value: 3.14 }
346
+ }))
347
+ };
348
+ response.flags['object-flag'] = {
349
+ ...base,
350
+ variationType: 5,
351
+ variations: base.variations.map(variation => ({
352
+ ...variation,
353
+ value: { case: 'jsonStringIndex', value: jsonIndex }
354
+ }))
355
+ };
356
+ const { provider, name } = setup(
357
+ coreConfigurationFromString(configurationToString(configuration))
358
+ );
359
+ await OpenFeature.setProviderAndWait(provider, matchingContext);
360
+ const client = OpenFeature.getClient();
361
+ expect(client.getStringValue('string-flag', 'default')).toBe('hello');
362
+ expect(client.getNumberValue('number-flag', 0)).toBe(3.14);
363
+ expect(client.getObjectValue('object-flag', {})).toEqual({
364
+ enabled: true
365
+ });
366
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenCalledTimes(3);
367
+ for (const [key, type, value] of [
368
+ ['string-flag', 'string', 'hello'],
369
+ ['number-flag', 'number', '3.14'],
370
+ ['object-flag', 'object', '{"enabled":true}']
371
+ ]) {
372
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenCalledWith(
373
+ name,
374
+ key,
375
+ expect.objectContaining({
376
+ variationType: type,
377
+ variationValue: value,
378
+ doLog: true
379
+ }),
380
+ 'user-1',
381
+ { country: 'US' }
382
+ );
383
+ }
384
+ });
385
+
386
+ it('uses matching precomputed data first and falls back to rules after a context change', async () => {
387
+ const configuration = {
388
+ ...rulesConfiguration(),
389
+ ...precomputedConfiguration()
390
+ };
391
+ const original = JSON.stringify(configuration, (_key, value) =>
392
+ typeof value === 'bigint' ? String(value) : value
393
+ );
394
+ const { provider } = setup(configuration);
395
+ await OpenFeature.setProviderAndWait(provider);
396
+ const client = OpenFeature.getClient();
397
+ expect(client.getStringValue('string-flag', 'default')).toBe('hello');
398
+ expect(client.getBooleanDetails('test-flag', false).errorCode).toBe(
399
+ ErrorCode.FLAG_NOT_FOUND
400
+ );
401
+ await OpenFeature.setContext({
402
+ targetingKey: 'other-user',
403
+ country: 'US'
404
+ });
405
+ expect(client.providerStatus).toBe(ProviderStatus.READY);
406
+ expect(client.getBooleanValue('test-flag', false)).toBe(true);
407
+ await OpenFeature.clearContext();
408
+ expect(client.getStringValue('string-flag', 'default')).toBe('hello');
409
+ expect(
410
+ JSON.stringify(configuration, (_key, value) =>
411
+ typeof value === 'bigint' ? String(value) : value
412
+ )
413
+ ).toBe(original);
414
+ });
415
+
416
+ it('adopts a replacement snapshot context, while explicit overrides remain authoritative', async () => {
417
+ const { provider } = setup(precomputedConfiguration());
418
+ await OpenFeature.setProviderAndWait(provider);
419
+ const replacement = precomputedConfiguration();
420
+ replacement.precomputed.context = { targetingKey: 'user-2' };
421
+ provider.setConfiguration(replacement);
422
+ const client = OpenFeature.getClient();
423
+ expect(client.providerStatus).toBe(ProviderStatus.READY);
424
+ expect(client.getBooleanValue('boolean-flag', false)).toBe(true);
425
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenLastCalledWith(
426
+ expect.any(String),
427
+ 'boolean-flag',
428
+ expect.any(Object),
429
+ 'user-2',
430
+ {}
431
+ );
432
+ await OpenFeature.setContext(matchingContext);
433
+ expect(client.providerStatus).toBe(ProviderStatus.ERROR);
434
+ await OpenFeature.clearContext();
435
+ expect(client.providerStatus).toBe(ProviderStatus.READY);
436
+ });
437
+
438
+ it('normalizes both embedded and active contexts and preserves legacy tracking metadata', async () => {
439
+ const configuration = precomputedConfiguration();
440
+ configuration.precomputed.context = {
441
+ ...matchingContext,
442
+ nested: { ignored: true }
443
+ };
444
+ const flag =
445
+ configuration.precomputed.response.data.attributes.flags[
446
+ 'boolean-flag'
447
+ ];
448
+ Object.assign(flag, { extraLogging: { source: 'legacy' } });
449
+ const { provider, name } = setup(configuration);
450
+ await OpenFeature.setProviderAndWait(provider, {
451
+ ...matchingContext,
452
+ nested: { different: true }
453
+ });
454
+ expect(
455
+ OpenFeature.getClient().getBooleanValue('boolean-flag', false)
456
+ ).toBe(true);
457
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenLastCalledWith(
458
+ name,
459
+ 'boolean-flag',
460
+ expect.objectContaining({ extraLogging: { source: 'legacy' } }),
461
+ 'user-1',
462
+ { country: 'US' }
463
+ );
464
+ });
465
+
466
+ it('preserves integer/float aliases and skips malformed individual precomputed flags', async () => {
467
+ const configuration = precomputedConfiguration();
468
+ Object.assign(
469
+ configuration.precomputed.response.data.attributes.flags[
470
+ 'number-flag'
471
+ ],
472
+ { variationType: 'float' }
473
+ );
474
+ Object.assign(
475
+ configuration.precomputed.response.data.attributes.flags[
476
+ 'boolean-flag'
477
+ ],
478
+ { doLog: 'invalid' }
479
+ );
480
+ const { provider } = setup(configuration);
481
+ await OpenFeature.setProviderAndWait(provider);
482
+ const client = OpenFeature.getClient();
483
+ expect(client.getNumberValue('number-flag', 0)).toBe(3.14);
484
+ expect(client.getBooleanDetails('boolean-flag', false).errorCode).toBe(
485
+ ErrorCode.FLAG_NOT_FOUND
486
+ );
487
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenCalledTimes(1);
488
+ expect(
489
+ NativeDdFlags.trackEvaluation
490
+ ).toHaveBeenLastCalledWith(
491
+ expect.any(String),
492
+ 'number-flag',
493
+ expect.objectContaining({ variationType: 'float' }),
494
+ 'user-1',
495
+ { country: 'US' }
496
+ );
497
+ });
498
+
499
+ it('does not track defaults or type mismatches and reports PARSE_ERROR for invalid precomputed input', async () => {
500
+ const { provider } = setup(precomputedConfiguration());
501
+ await OpenFeature.setProviderAndWait(provider);
502
+ const client = OpenFeature.getClient();
503
+ expect(client.getBooleanDetails('missing', true).errorCode).toBe(
504
+ ErrorCode.FLAG_NOT_FOUND
505
+ );
506
+ expect(
507
+ client.getStringDetails('boolean-flag', 'default').errorCode
508
+ ).toBe(ErrorCode.TYPE_MISMATCH);
509
+ provider.setConfiguration({});
510
+ expect(client.providerStatus).toBe(ProviderStatus.ERROR);
511
+ expect(client.getBooleanDetails('boolean-flag', false).errorCode).toBe(
512
+ ErrorCode.PARSE_ERROR
513
+ );
514
+ expect(NativeDdFlags.trackEvaluation).not.toHaveBeenCalled();
515
+ });
516
+
517
+ it('recovers from malformed rules, supports replacement rules, and only emits one configuration event', async () => {
518
+ const { provider } = setup({ rulesError: 'Malformed rules' });
519
+ await expect(
520
+ OpenFeature.setProviderAndWait(provider, matchingContext)
521
+ ).rejects.toMatchObject({ code: ErrorCode.PARSE_ERROR });
522
+ const changed = jest.fn();
523
+ provider.events.addHandler(
524
+ ProviderEvents.ConfigurationChanged,
525
+ changed
526
+ );
527
+ provider.setConfiguration(coreConfigurationFromString(rulesWire));
528
+ const client = OpenFeature.getClient();
529
+ expect(client.providerStatus).toBe(ProviderStatus.READY);
530
+ expect(client.getBooleanValue('test-flag', false)).toBe(true);
531
+ expect(changed).toHaveBeenCalledTimes(1);
532
+ const replacement = rulesConfiguration();
533
+ replacement.rules.response.flags['test-flag'].variations[0].value = {
534
+ case: 'booleanValue',
535
+ value: false
536
+ };
537
+ provider.setConfiguration(
538
+ coreConfigurationFromString(configurationToString(replacement))
539
+ );
540
+ expect(client.getBooleanValue('test-flag', true)).toBe(false);
541
+ expect(changed).toHaveBeenCalledTimes(2);
542
+ });
543
+
544
+ it('reports PARSE_ERROR for a malformed precomputed flag parsed by coreConfigurationFromString', async () => {
545
+ const configuration = precomputedConfiguration();
546
+ Object.assign(
547
+ configuration.precomputed.response.data.attributes.flags[
548
+ 'boolean-flag'
549
+ ],
550
+ { doLog: 'invalid' }
551
+ );
552
+ const parsed = coreConfigurationFromString(
553
+ configurationToString(configuration)
554
+ );
555
+ expect(parsed.precomputed?.flagErrors).toHaveProperty('boolean-flag');
556
+ const { provider } = setup(parsed);
557
+ await OpenFeature.setProviderAndWait(provider);
558
+ const client = OpenFeature.getClient();
559
+ expect(client.getBooleanDetails('boolean-flag', false)).toMatchObject({
560
+ value: false,
561
+ errorCode: ErrorCode.PARSE_ERROR
562
+ });
563
+ expect(client.providerStatus).toBe(ProviderStatus.READY);
564
+ expect(client.getStringValue('string-flag', 'default')).toBe('hello');
565
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenCalledTimes(1);
566
+ });
567
+
568
+ it('reports PARSE_ERROR for a rules flag with an unsafe int64 value while the provider stays ready', async () => {
569
+ // A protobuf rules flag whose integer variation exceeds Number.MAX_SAFE_INTEGER.
570
+ const unsafeIntegerWire = JSON.stringify({
571
+ version: 1,
572
+ rules: {
573
+ response:
574
+ 'EgR0ZXN0GjIKD2ludmFsaWQtZmVhdHVyZRIfEAIaCRiBgICAgICAECIQCgphbGxvY2F0aW9uIgIgAyoGdW5zYWZl'
575
+ }
576
+ });
577
+ const { provider } = setup(
578
+ coreConfigurationFromString(unsafeIntegerWire)
579
+ );
580
+ await OpenFeature.setProviderAndWait(provider, matchingContext);
581
+ const client = OpenFeature.getClient();
582
+ expect(client.getNumberDetails('invalid-feature', 0)).toMatchObject({
583
+ value: 0,
584
+ errorCode: ErrorCode.PARSE_ERROR
585
+ });
586
+ expect(client.providerStatus).toBe(ProviderStatus.READY);
587
+ expect(NativeDdFlags.trackEvaluation).not.toHaveBeenCalled();
588
+ });
589
+
590
+ it('reports PARSE_ERROR on the error event when a running provider loads malformed rules', async () => {
591
+ const { provider } = setup(rulesConfiguration());
592
+ await OpenFeature.setProviderAndWait(provider, matchingContext);
593
+ const emit = jest.spyOn(provider.events, 'emit');
594
+ provider.setConfiguration({ rulesError: 'Malformed rules' });
595
+ expect(emit).toHaveBeenCalledWith(
596
+ ProviderEvents.Error,
597
+ expect.objectContaining({ errorCode: ErrorCode.PARSE_ERROR })
598
+ );
599
+ });
600
+
601
+ it('tracks the rules result, not a same-key precomputed entry, when the snapshot does not match', async () => {
602
+ const configuration = {
603
+ ...rulesConfiguration(),
604
+ ...precomputedConfiguration()
605
+ };
606
+ configuration.precomputed.response.data.attributes.flags[
607
+ 'test-flag'
608
+ ] = {
609
+ allocationKey: 'snapshot-allocation',
610
+ variationKey: 'snapshot-off',
611
+ variationType: 'boolean',
612
+ variationValue: false,
613
+ reason: 'STATIC',
614
+ doLog: true
615
+ };
616
+ const { provider, name } = setup(configuration);
617
+ await OpenFeature.setProviderAndWait(provider, {
618
+ targetingKey: 'other-user',
619
+ country: 'US'
620
+ });
621
+ const client = OpenFeature.getClient();
622
+ expect(client.getBooleanValue('test-flag', false)).toBe(true);
623
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenLastCalledWith(
624
+ name,
625
+ 'test-flag',
626
+ expect.objectContaining({
627
+ value: true,
628
+ allocationKey: 'allocation',
629
+ variationKey: 'on',
630
+ serialId: '7'
631
+ }),
632
+ 'other-user',
633
+ { country: 'US' }
634
+ );
635
+ await OpenFeature.clearContext();
636
+ expect(client.getBooleanValue('test-flag', true)).toBe(false);
637
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenLastCalledWith(
638
+ name,
639
+ 'test-flag',
640
+ expect.objectContaining({
641
+ value: false,
642
+ allocationKey: 'snapshot-allocation'
643
+ }),
644
+ 'user-1',
645
+ { country: 'US' }
646
+ );
647
+ });
648
+
649
+ it('sends the precomputed split serial ID to native tracking', async () => {
650
+ const configuration = precomputedConfiguration();
651
+ Object.assign(
652
+ configuration.precomputed.response.data.attributes.flags[
653
+ 'boolean-flag'
654
+ ],
655
+ { serialId: 42 }
656
+ );
657
+ const { provider, name } = setup(configuration);
658
+ await OpenFeature.setProviderAndWait(provider);
659
+ OpenFeature.getClient().getBooleanValue('boolean-flag', false);
660
+ expect(NativeDdFlags.trackEvaluation).toHaveBeenLastCalledWith(
661
+ name,
662
+ 'boolean-flag',
663
+ expect.objectContaining({
664
+ allocationKey: 'allocation',
665
+ serialId: '42'
666
+ }),
667
+ 'user-1',
668
+ { country: 'US' }
669
+ );
670
+ });
671
+
672
+ it('names the precomputed-only parser when a rules wire yields no configuration', () => {
673
+ const log = jest.spyOn(InternalLog, 'log');
674
+ const { provider } = setup(configurationFromString(rulesWire));
675
+ expect(provider).toBeDefined();
676
+ expect(log).toHaveBeenCalledWith(
677
+ expect.stringContaining(
678
+ 'configurationFromString is precomputed-only'
679
+ ),
680
+ expect.anything()
681
+ );
682
+ });
683
+
684
+ it('does not warn about a missing configuration when one is loaded', () => {
685
+ const log = jest.spyOn(InternalLog, 'log');
686
+ setup(rulesConfiguration());
687
+ expect(log).not.toHaveBeenCalledWith(
688
+ expect.stringContaining('received no precomputed or rules'),
689
+ expect.anything()
690
+ );
691
+ });
692
+
693
+ it('reports PARSE_ERROR instead of throwing for a missing configuration', () => {
694
+ const provider = new DatadogOfflineOpenFeatureProvider({
695
+ clientName: `offline-delegation-${sequence++}`
696
+ });
697
+ const emit = jest.spyOn(provider.events, 'emit');
698
+ expect(() =>
699
+ provider.setConfiguration((null as unknown) as FlagsConfiguration)
700
+ ).not.toThrow();
701
+ expect(emit).toHaveBeenCalledWith(
702
+ ProviderEvents.Error,
703
+ expect.objectContaining({ errorCode: ErrorCode.PARSE_ERROR })
704
+ );
705
+ });
706
+
707
+ it('keeps usable rules when the precomputed branch is unsupported or malformed', async () => {
708
+ const configuration = {
709
+ ...rulesConfiguration(),
710
+ ...precomputedConfiguration()
711
+ };
712
+ Object.assign(configuration.precomputed.response.data.attributes, {
713
+ obfuscated: true
714
+ });
715
+ const { provider } = setup(configuration);
716
+ await OpenFeature.setProviderAndWait(provider, matchingContext);
717
+ expect(
718
+ OpenFeature.getClient().getBooleanValue('test-flag', false)
719
+ ).toBe(true);
720
+ });
721
+
722
+ it('shares configuration with providers/native getters using the same clientName, but isolates other clients', async () => {
723
+ const { provider, name, flagsClient } = setup(rulesConfiguration());
724
+ const sameClientProvider = new DatadogOfflineOpenFeatureProvider({
725
+ clientName: name
726
+ });
727
+ const other = setup(precomputedConfiguration());
728
+ await provider.initialize(matchingContext);
729
+ expect(
730
+ sameClientProvider.resolveBooleanEvaluation(
731
+ 'test-flag',
732
+ false,
733
+ {},
734
+ logger
735
+ ).value
736
+ ).toBe(true);
737
+ expect(flagsClient.getBooleanValue('test-flag', false)).toBe(true);
738
+ sameClientProvider.setConfiguration({});
739
+ expect(
740
+ provider.resolveBooleanEvaluation('test-flag', false, {}, logger)
741
+ .errorCode
742
+ ).toBe(ErrorCode.PARSE_ERROR);
743
+ expect(other.flagsClient.getBooleanValue('boolean-flag', false)).toBe(
744
+ true
745
+ );
746
+ });
747
+
748
+ it('discards delegated rules before an online fetch, including when that fetch fails', async () => {
749
+ const { flagsClient } = setup(rulesConfiguration());
750
+ flagsClient.setEvaluationContextWithoutFetching({
751
+ targetingKey: 'user-1',
752
+ attributes: { country: 'US' }
753
+ });
754
+ expect(flagsClient.getBooleanValue('test-flag', false)).toBe(true);
755
+ jest.mocked(NativeDdFlags.setEvaluationContext).mockRejectedValueOnce(
756
+ new Error('fetch failed')
757
+ );
758
+ await expect(
759
+ flagsClient.setEvaluationContext({ targetingKey: 'user-2' })
760
+ ).rejects.toThrow('fetch failed');
761
+ expect(flagsClient.getBooleanValue('test-flag', false)).toBe(false);
762
+ });
763
+
764
+ it('allows a direct native configuration load to replace the delegate and a later provider load to restore it', () => {
765
+ const { provider, flagsClient } = setup(rulesConfiguration());
766
+ flagsClient.setConfiguration(
767
+ configurationFromString(
768
+ configurationToString(precomputedConfiguration())
769
+ )
770
+ );
771
+ expect(flagsClient.getStringValue('string-flag', 'default')).toBe(
772
+ 'hello'
773
+ );
774
+ provider.setConfiguration(rulesConfiguration());
775
+ flagsClient.setEvaluationContextWithoutFetching({
776
+ targetingKey: 'user-1',
777
+ attributes: { country: 'US' }
778
+ });
779
+ expect(flagsClient.getBooleanValue('test-flag', false)).toBe(true);
780
+ });
781
+
782
+ it('logs native tracking failures without changing the evaluated result', async () => {
783
+ const log = jest.spyOn(InternalLog, 'log');
784
+ const { flagsClient } = setup(precomputedConfiguration());
785
+ jest.mocked(NativeDdFlags.trackEvaluation).mockRejectedValueOnce(
786
+ new Error('tracking failed')
787
+ );
788
+ expect(flagsClient.getBooleanValue('boolean-flag', false)).toBe(true);
789
+ await Promise.resolve();
790
+ expect(log).toHaveBeenCalledWith(
791
+ 'Error tracking flag evaluation: tracking failed',
792
+ expect.anything()
793
+ );
794
+ });
795
+ });