@splitsoftware/openfeature-web-split-provider 1.0.0 → 1.2.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 (37) hide show
  1. package/CHANGES.txt +13 -2
  2. package/README.md +190 -16
  3. package/es/lib/context.js +55 -0
  4. package/es/lib/evaluation.js +21 -0
  5. package/es/lib/events.js +69 -0
  6. package/es/lib/js-split-provider.js +80 -142
  7. package/es/lib/parsers.js +38 -0
  8. package/es/lib/types.js +2 -0
  9. package/lib/lib/context.js +61 -0
  10. package/lib/lib/evaluation.js +25 -0
  11. package/lib/lib/events.js +74 -0
  12. package/lib/lib/js-split-provider.js +78 -140
  13. package/lib/lib/parsers.js +44 -0
  14. package/lib/lib/types.js +5 -0
  15. package/package.json +2 -2
  16. package/src/__tests__/bucketingKey.spec.js +145 -0
  17. package/src/__tests__/context.spec.js +146 -0
  18. package/src/__tests__/evaluation.spec.js +76 -0
  19. package/src/__tests__/events.spec.js +182 -0
  20. package/src/__tests__/integration/bucketing-key.test.js +81 -0
  21. package/src/__tests__/integration/e2e-events.test.js +1 -8
  22. package/src/__tests__/integration/openfeature-evaluation.test.js +162 -0
  23. package/src/__tests__/parsers.spec.js +115 -0
  24. package/src/__tests__/provider.spec.js +59 -3
  25. package/src/__tests__/types.spec.js +15 -0
  26. package/src/lib/context.ts +62 -0
  27. package/src/lib/evaluation.ts +33 -0
  28. package/src/lib/events.ts +105 -0
  29. package/src/lib/js-split-provider.ts +103 -180
  30. package/src/lib/parsers.ts +43 -0
  31. package/src/lib/types.ts +12 -0
  32. package/types/lib/context.d.ts +15 -0
  33. package/types/lib/evaluation.d.ts +7 -0
  34. package/types/lib/events.d.ts +20 -0
  35. package/types/lib/js-split-provider.d.ts +11 -7
  36. package/types/lib/parsers.d.ts +8 -0
  37. package/types/lib/types.d.ts +10 -0
@@ -0,0 +1,76 @@
1
+ /* eslint-disable @typescript-eslint/no-unused-vars */
2
+ import { FlagNotFoundError, StandardResolutionReasons } from '@openfeature/web-sdk';
3
+ import { evaluateTreatment } from '../lib/evaluation';
4
+ import { CONTROL_TREATMENT } from '../lib/types';
5
+
6
+ describe('evaluation', () => {
7
+ describe('evaluateTreatment', () => {
8
+ let mockClient;
9
+
10
+ beforeEach(() => {
11
+ mockClient = {
12
+ getTreatmentWithConfig: jest.fn((flagKey, attributes) => ({
13
+ treatment: 'v1',
14
+ config: '{"x":1}',
15
+ })),
16
+ };
17
+ });
18
+
19
+ test('returns resolution details with value, variant, flagMetadata, reason', () => {
20
+ const consumer = { targetingKey: 'u1', trafficType: 'user', attributes: {} };
21
+ const result = evaluateTreatment(mockClient, 'my-flag', consumer);
22
+
23
+ expect(result.value).toBe('v1');
24
+ expect(result.variant).toBe('v1');
25
+ expect(result.flagMetadata).toEqual({ config: '{"x":1}' });
26
+ expect(result.reason).toBe(StandardResolutionReasons.TARGETING_MATCH);
27
+ expect(mockClient.getTreatmentWithConfig).toHaveBeenCalledWith('my-flag', {});
28
+ });
29
+
30
+ test('calls getTreatmentWithConfig with consumer attributes', () => {
31
+ const consumer = {
32
+ targetingKey: 'u1',
33
+ trafficType: 'account',
34
+ attributes: { region: 'eu', plan: 'pro' },
35
+ };
36
+ evaluateTreatment(mockClient, 'flag', consumer);
37
+ expect(mockClient.getTreatmentWithConfig).toHaveBeenCalledWith('flag', {
38
+ region: 'eu',
39
+ plan: 'pro',
40
+ });
41
+ });
42
+
43
+ test('uses empty string for config when config is falsy', () => {
44
+ mockClient.getTreatmentWithConfig.mockReturnValue({ treatment: 'on', config: null });
45
+ const result = evaluateTreatment(mockClient, 'f', {
46
+ targetingKey: undefined,
47
+ trafficType: 'user',
48
+ attributes: {},
49
+ });
50
+ expect(result.flagMetadata.config).toBe('');
51
+ });
52
+
53
+ test('throws FlagNotFoundError when flagKey is null', () => {
54
+ const consumer = { targetingKey: 'u1', trafficType: 'user', attributes: {} };
55
+ expect(() => evaluateTreatment(mockClient, null, consumer)).toThrow(FlagNotFoundError);
56
+ expect(() => evaluateTreatment(mockClient, null, consumer)).toThrow(
57
+ /flagKey must be a non-empty string/
58
+ );
59
+ });
60
+
61
+ test('throws FlagNotFoundError when flagKey is empty string', () => {
62
+ const consumer = { targetingKey: 'u1', trafficType: 'user', attributes: {} };
63
+ expect(() => evaluateTreatment(mockClient, '', consumer)).toThrow(FlagNotFoundError);
64
+ });
65
+
66
+ test('throws FlagNotFoundError when treatment is control', () => {
67
+ mockClient.getTreatmentWithConfig.mockReturnValue({
68
+ treatment: CONTROL_TREATMENT,
69
+ config: '',
70
+ });
71
+ const consumer = { targetingKey: 'u1', trafficType: 'user', attributes: {} };
72
+ expect(() => evaluateTreatment(mockClient, 'flag', consumer)).toThrow(FlagNotFoundError);
73
+ expect(() => evaluateTreatment(mockClient, 'flag', consumer)).toThrow(/control/);
74
+ });
75
+ });
76
+ });
@@ -0,0 +1,182 @@
1
+ import { ProviderEvents } from '@openfeature/web-sdk';
2
+ import {
3
+ attachSplitReadyHandlers,
4
+ attachSplitUpdateHandler,
5
+ } from '../lib/events';
6
+
7
+ describe('events', () => {
8
+ const providerName = 'split';
9
+
10
+ describe('attachSplitReadyHandlers', () => {
11
+ test('calls onSdkReady immediately when client is already ready (no SdkReadyMetadata)', () => {
12
+ const onSdkReady = jest.fn();
13
+ const onSdkTimedOut = jest.fn();
14
+ const emit = jest.fn();
15
+ const client = {
16
+ __getStatus: () => ({ isReady: true, isReadyFromCache: false, hasTimedout: false }),
17
+ on: jest.fn(),
18
+ Event: {
19
+ SDK_READY: 'SDK_READY',
20
+ SDK_READY_FROM_CACHE: 'SDK_READY_FROM_CACHE',
21
+ SDK_READY_TIMED_OUT: 'SDK_READY_TIMED_OUT',
22
+ },
23
+ };
24
+ const eventsEmitter = { emit };
25
+
26
+ attachSplitReadyHandlers(client, eventsEmitter, { onSdkReady, onSdkTimedOut }, providerName);
27
+
28
+ expect(emit).toHaveBeenCalledWith(ProviderEvents.Ready, {
29
+ providerName,
30
+ metadata: {},
31
+ });
32
+ expect(onSdkReady).toHaveBeenCalledTimes(1);
33
+ expect(onSdkTimedOut).not.toHaveBeenCalled();
34
+ expect(client.on).not.toHaveBeenCalled();
35
+ });
36
+
37
+ test('calls onSdkReadyFromCache and onSdkTimedOut when ready from cache and timed out', () => {
38
+ const onSdkReady = jest.fn();
39
+ const onSdkTimedOut = jest.fn();
40
+ const emit = jest.fn();
41
+ const client = {
42
+ __getStatus: () => ({ isReady: false, isReadyFromCache: true, hasTimedout: true }),
43
+ on: jest.fn(() => ({})),
44
+ Event: {
45
+ SDK_READY: 'SDK_READY',
46
+ SDK_READY_FROM_CACHE: 'SDK_READY_FROM_CACHE',
47
+ SDK_READY_TIMED_OUT: 'SDK_READY_TIMED_OUT',
48
+ },
49
+ };
50
+ const eventsEmitter = { emit };
51
+
52
+ attachSplitReadyHandlers(client, eventsEmitter, { onSdkReady, onSdkTimedOut }, providerName);
53
+
54
+ expect(emit).toHaveBeenCalledWith(ProviderEvents.Stale, {
55
+ message: 'Split ready from cache',
56
+ });
57
+ expect(onSdkTimedOut).toHaveBeenCalled();
58
+ });
59
+
60
+ test('registers SDK_READY and on fire emits Ready with Split SdkReadyMetadata', () => {
61
+ const onSdkReady = jest.fn();
62
+ const onSdkTimedOut = jest.fn();
63
+ const emit = jest.fn();
64
+ let sdkReadyCallback;
65
+ const client = {
66
+ __getStatus: () => ({ isReady: false, isReadyFromCache: false, hasTimedout: false }),
67
+ on: jest.fn((event, callback) => {
68
+ if (event === 'SDK_READY') sdkReadyCallback = callback;
69
+ return {};
70
+ }),
71
+ Event: {
72
+ SDK_READY: 'SDK_READY',
73
+ SDK_READY_FROM_CACHE: 'SDK_READY_FROM_CACHE',
74
+ SDK_READY_TIMED_OUT: 'SDK_READY_TIMED_OUT',
75
+ },
76
+ };
77
+ const eventsEmitter = { emit };
78
+
79
+ attachSplitReadyHandlers(client, eventsEmitter, { onSdkReady, onSdkTimedOut }, providerName);
80
+
81
+ expect(client.on).toHaveBeenCalledWith('SDK_READY', expect.any(Function));
82
+ const sdkReadyMetadata = { initialCacheLoad: false, lastUpdateTimestamp: 1234567890 };
83
+ sdkReadyCallback(sdkReadyMetadata);
84
+ expect(emit).toHaveBeenCalledWith(ProviderEvents.Ready, {
85
+ providerName,
86
+ metadata: { initialCacheLoad: false, lastUpdateTimestamp: 1234567890 },
87
+ });
88
+ expect(emit.mock.calls[0][1].metadata).toHaveProperty('initialCacheLoad');
89
+ expect(onSdkReady).toHaveBeenCalled();
90
+ });
91
+
92
+ test('Ready metadata omits lastUpdateTimestamp when undefined (initialCacheLoad true)', () => {
93
+ const emit = jest.fn();
94
+ let sdkReadyCallback;
95
+ const client = {
96
+ __getStatus: () => ({ isReady: false, isReadyFromCache: false, hasTimedout: false }),
97
+ on: jest.fn((event, callback) => {
98
+ if (event === 'SDK_READY') sdkReadyCallback = callback;
99
+ return {};
100
+ }),
101
+ Event: {
102
+ SDK_READY: 'SDK_READY',
103
+ SDK_READY_FROM_CACHE: 'SDK_READY_FROM_CACHE',
104
+ SDK_READY_TIMED_OUT: 'SDK_READY_TIMED_OUT',
105
+ },
106
+ };
107
+ attachSplitReadyHandlers(client, { emit }, { onSdkReady: () => {}, onSdkTimedOut: () => {} }, providerName);
108
+ sdkReadyCallback({ initialCacheLoad: true });
109
+ expect(emit.mock.calls[0][1].metadata).toEqual({ initialCacheLoad: true });
110
+ expect(emit.mock.calls[0][1].metadata).not.toHaveProperty('lastUpdateTimestamp');
111
+ });
112
+ });
113
+
114
+ describe('attachSplitUpdateHandler', () => {
115
+ test('registers SDK_UPDATE listener', () => {
116
+ const emit = jest.fn();
117
+ let updateCallback;
118
+ const client = {
119
+ on: jest.fn((event, callback) => {
120
+ if (event === 'SDK_UPDATE') updateCallback = callback;
121
+ return {};
122
+ }),
123
+ Event: { SDK_UPDATE: 'SDK_UPDATE' },
124
+ };
125
+ const eventsEmitter = { emit };
126
+
127
+ attachSplitUpdateHandler(client, eventsEmitter, providerName);
128
+
129
+ expect(client.on).toHaveBeenCalledWith('SDK_UPDATE', expect.any(Function));
130
+
131
+ updateCallback({ type: 'FLAGS_UPDATE', names: ['flag-a', 'flag-b'] });
132
+
133
+ expect(emit).toHaveBeenCalledWith(ProviderEvents.ConfigurationChanged, {
134
+ providerName,
135
+ metadata: { type: 'FLAGS_UPDATE' },
136
+ flagsChanged: ['flag-a', 'flag-b'],
137
+ });
138
+ });
139
+
140
+ test('emits with only providerName when updateMetadata is undefined', () => {
141
+ const emit = jest.fn();
142
+ let updateCallback;
143
+ const client = {
144
+ on: jest.fn((event, callback) => {
145
+ if (event === 'SDK_UPDATE') updateCallback = callback;
146
+ return {};
147
+ }),
148
+ Event: { SDK_UPDATE: 'SDK_UPDATE' },
149
+ };
150
+ const eventsEmitter = { emit };
151
+
152
+ attachSplitUpdateHandler(client, eventsEmitter, providerName);
153
+ updateCallback(undefined);
154
+
155
+ expect(emit).toHaveBeenCalledWith(ProviderEvents.ConfigurationChanged, {
156
+ providerName,
157
+ });
158
+ });
159
+
160
+ test('emits metadata without flagsChanged when type is not FLAGS_UPDATE', () => {
161
+ const emit = jest.fn();
162
+ let updateCallback;
163
+ const client = {
164
+ on: jest.fn((event, callback) => {
165
+ if (event === 'SDK_UPDATE') updateCallback = callback;
166
+ return {};
167
+ }),
168
+ Event: { SDK_UPDATE: 'SDK_UPDATE' },
169
+ };
170
+ const eventsEmitter = { emit };
171
+
172
+ attachSplitUpdateHandler(client, eventsEmitter, providerName);
173
+ updateCallback({ type: 'SPLIT_KILL', names: ['x'] });
174
+
175
+ expect(emit).toHaveBeenCalledWith(ProviderEvents.ConfigurationChanged, {
176
+ providerName,
177
+ metadata: { type: 'SPLIT_KILL' },
178
+ flagsChanged: ['x'],
179
+ });
180
+ });
181
+ });
182
+ });
@@ -0,0 +1,81 @@
1
+ import { OpenFeature, ProviderEvents } from '@openfeature/web-sdk';
2
+ import { SplitFactory } from '@splitsoftware/splitio-browserjs';
3
+ import { OpenFeatureSplitProvider } from '../../lib/js-split-provider';
4
+
5
+ // Context switching on one initialized provider with the real browser SDK (localhost mode):
6
+ // evaluate → add bucketingKey → evaluate → change it → remove it → blank → close.
7
+ describe('bucketingKey with the localhost browser SDK', () => {
8
+ let impressions;
9
+ let client;
10
+ let events;
11
+
12
+ beforeAll(async () => {
13
+ impressions = [];
14
+ const factory = SplitFactory({
15
+ core: { authorizationKey: 'localhost', key: 'factory-key' },
16
+ features: { my_feature: 'on' },
17
+ impressionListener: { logImpression: (data) => impressions.push({ ...data.impression, attributes: data.attributes }) },
18
+ });
19
+ events = [];
20
+ [ProviderEvents.Reconciling, ProviderEvents.ContextChanged, ProviderEvents.Error].forEach((e) =>
21
+ OpenFeature.addHandler(e, () => events.push(e))
22
+ );
23
+ await OpenFeature.setContext({ targetingKey: 'u1' });
24
+ await OpenFeature.setProviderAndWait(new OpenFeatureSplitProvider(factory));
25
+ client = OpenFeature.getClient();
26
+ });
27
+
28
+ afterAll(async () => {
29
+ await OpenFeature.close();
30
+ });
31
+
32
+ /** Evaluates with no invocation context and returns the impression's [keyName, bucketingKey]. */
33
+ async function evaluate() {
34
+ const before = impressions.length;
35
+ const details = client.getBooleanDetails('my_feature', false);
36
+ expect(details.errorCode).toBeUndefined();
37
+ expect(details.value).toBe(true);
38
+ await new Promise((r) => setTimeout(r, 0)); // the impression listener is called asynchronously
39
+ expect(impressions.length).toBe(before + 1);
40
+ const imp = impressions[impressions.length - 1];
41
+ return [imp.keyName, imp.bucketingKey];
42
+ }
43
+
44
+ test('initial context is applied at initialize', async () => {
45
+ expect(await evaluate()).toEqual(['u1', undefined]);
46
+ });
47
+
48
+ test('add, change, remove and blank bucketingKey switch the key; no Error', async () => {
49
+ events.length = 0;
50
+ await OpenFeature.setContext({ targetingKey: 'u1', bucketingKey: 'b1' });
51
+ expect(await evaluate()).toEqual(['u1', 'b1']);
52
+
53
+ await OpenFeature.setContext({ targetingKey: 'u1', bucketingKey: ' b2 ' });
54
+ expect(await evaluate()).toEqual(['u1', 'b2']);
55
+
56
+ await OpenFeature.setContext({ targetingKey: 'u1' });
57
+ expect(await evaluate()).toEqual(['u1', undefined]);
58
+
59
+ await OpenFeature.setContext({ targetingKey: 'u1', bucketingKey: 'b1' });
60
+ expect(await evaluate()).toEqual(['u1', 'b1']);
61
+
62
+ await OpenFeature.setContext({ targetingKey: 'u1', bucketingKey: ' ' });
63
+ expect(await evaluate()).toEqual(['u1', undefined]);
64
+
65
+ expect(events).not.toContain(ProviderEvents.Error);
66
+ expect(events.filter((e) => e === ProviderEvents.ContextChanged)).toHaveLength(5);
67
+ });
68
+
69
+ test('over-length bucketingKey falls back to the targeting key; no Error', async () => {
70
+ events.length = 0;
71
+ await OpenFeature.setContext({ targetingKey: 'u2', bucketingKey: 'b'.repeat(251) });
72
+ expect(await evaluate()).toEqual(['u2', undefined]);
73
+ expect(events).not.toContain(ProviderEvents.Error);
74
+ });
75
+
76
+ test('bucketingKey is not sent as an attribute; other spellings are', async () => {
77
+ await OpenFeature.setContext({ targetingKey: 'u1', bucketingKey: 'b1', plan: 'pro', BucketingKey: 'x' });
78
+ expect(await evaluate()).toEqual(['u1', 'b1']);
79
+ expect(impressions[impressions.length - 1].attributes).toEqual({ plan: 'pro', BucketingKey: 'x' });
80
+ });
81
+ });
@@ -84,9 +84,6 @@ describe('OpenFeature Split Provider - E2E Integration Tests', () => {
84
84
  OpenFeature.setProvider(provider);
85
85
  const client = OpenFeature.getClient();
86
86
  await new Promise((resolve, reject) => {
87
- client.addHandler(ProviderEvents.Stale, () => {
88
- reject('should not emit stale');
89
- });
90
87
  client.addHandler(ProviderEvents.Ready, () => {
91
88
  const splitClient = splitFactory.client();
92
89
  try {
@@ -122,11 +119,7 @@ describe('OpenFeature Split Provider - E2E Integration Tests', () => {
122
119
  const splitFactory = SplitFactory(config);
123
120
  const client = OpenFeature.getClient();
124
121
 
125
- await new Promise((resolve, reject) => {
126
-
127
- client.addHandler(ProviderEvents.Stale, () => {
128
- reject('should not emit stale');
129
- });
122
+ await new Promise((resolve) => {
130
123
 
131
124
  client.addHandler(ProviderEvents.Ready, () => {
132
125
 
@@ -0,0 +1,162 @@
1
+ /**
2
+ * OpenFeature evaluation tests: validate the Split provider through the
3
+ * OpenFeature Web SDK Evaluation API (get*Value, get*Details) and provider lifecycle.
4
+ */
5
+ import { OpenFeature, StandardResolutionReasons } from '@openfeature/web-sdk';
6
+ import { OpenFeatureSplitProvider } from '../../lib/js-split-provider';
7
+
8
+ describe('OpenFeature evaluation – Split provider', () => {
9
+ let mockSplitClient;
10
+ let provider;
11
+ let client;
12
+
13
+ beforeAll(() => {
14
+ mockSplitClient = {
15
+ __getStatus: () => ({ isReady: true, isReadyFromCache: false, hasTimedout: false }),
16
+ on: jest.fn((event, callback) => {
17
+ if (event === 'SDK_READY') setTimeout(() => callback(), 0);
18
+ return { id: 'mock-listener' };
19
+ }),
20
+ Event: {
21
+ SDK_READY: 'SDK_READY',
22
+ SDK_READY_FROM_CACHE: 'SDK_READY_FROM_CACHE',
23
+ SDK_READY_TIMED_OUT: 'SDK_READY_TIMED_OUT',
24
+ SDK_UPDATE: 'SDK_UPDATE',
25
+ },
26
+ getTreatmentWithConfig: jest.fn((flagKey) => {
27
+ if (flagKey === 'bool_on') return { treatment: 'on', config: '{}' };
28
+ if (flagKey === 'bool_off') return { treatment: 'off', config: '' };
29
+ if (flagKey === 'str_flag') return { treatment: 'v1', config: '{"x":1}' };
30
+ if (flagKey === 'num_flag') return { treatment: '99', config: '{}' };
31
+ if (flagKey === 'obj_flag') return { treatment: '{"a":1}', config: '' };
32
+ return { treatment: 'control', config: '' };
33
+ }),
34
+ track: jest.fn(),
35
+ destroy: jest.fn(() => Promise.resolve()),
36
+ };
37
+
38
+ const factory = {
39
+ client: () => mockSplitClient,
40
+ destroy: jest.fn(() => Promise.resolve()),
41
+ };
42
+ provider = new OpenFeatureSplitProvider(factory);
43
+ });
44
+
45
+ beforeEach(async () => {
46
+ await OpenFeature.setProviderAndWait(provider);
47
+ client = OpenFeature.getClient('evaluation-test');
48
+ });
49
+
50
+ afterEach(async () => {
51
+ await OpenFeature.clearProviders();
52
+ await OpenFeature.clearHandlers();
53
+ await OpenFeature.close();
54
+ });
55
+
56
+ describe('Provider metadata', () => {
57
+ test('provider has required metadata.name', () => {
58
+ expect(provider.metadata).toBeDefined();
59
+ expect(provider.metadata.name).toBe('split');
60
+ });
61
+ });
62
+
63
+ describe('Evaluation API – boolean', () => {
64
+ test('getBooleanValue returns true for on', async () => {
65
+ const value = await client.getBooleanValue('bool_on', false);
66
+ expect(value).toBe(true);
67
+ });
68
+
69
+ test('getBooleanValue returns false for off', async () => {
70
+ const value = await client.getBooleanValue('bool_off', true);
71
+ expect(value).toBe(false);
72
+ });
73
+
74
+ test('getBooleanDetails returns correct ResolutionDetails shape', async () => {
75
+ const details = await client.getBooleanDetails('bool_on', false);
76
+ expect(details.value).toBe(true);
77
+ expect(details.flagKey).toBe('bool_on');
78
+ expect(details.variant).toBe('on');
79
+ expect(details.reason).toBe(StandardResolutionReasons.TARGETING_MATCH);
80
+ expect(details.flagMetadata).toBeDefined();
81
+ expect(details.flagMetadata.config).toBeDefined();
82
+ });
83
+ });
84
+
85
+ describe('Evaluation API – string', () => {
86
+ test('getStringValue returns treatment as string', async () => {
87
+ const value = await client.getStringValue('str_flag', 'default');
88
+ expect(value).toBe('v1');
89
+ });
90
+
91
+ test('getStringDetails returns correct ResolutionDetails shape', async () => {
92
+ const details = await client.getStringDetails('str_flag', 'default');
93
+ expect(details.value).toBe('v1');
94
+ expect(details.flagKey).toBe('str_flag');
95
+ expect(details.variant).toBe('v1');
96
+ expect(details.reason).toBe(StandardResolutionReasons.TARGETING_MATCH);
97
+ expect(details.flagMetadata.config).toBe('{"x":1}');
98
+ });
99
+ });
100
+
101
+ describe('Evaluation API – number', () => {
102
+ test('getNumberValue returns parsed number', async () => {
103
+ const value = await client.getNumberValue('num_flag', 0);
104
+ expect(value).toBe(99);
105
+ });
106
+
107
+ test('getNumberDetails returns correct ResolutionDetails shape', async () => {
108
+ const details = await client.getNumberDetails('num_flag', 0);
109
+ expect(details.value).toBe(99);
110
+ expect(details.flagKey).toBe('num_flag');
111
+ expect(details.variant).toBe('99');
112
+ expect(details.reason).toBe(StandardResolutionReasons.TARGETING_MATCH);
113
+ });
114
+ });
115
+
116
+ describe('Evaluation API – object', () => {
117
+ test('getObjectValue returns parsed JSON object', async () => {
118
+ const value = await client.getObjectValue('obj_flag', {});
119
+ expect(value).toEqual({ a: 1 });
120
+ });
121
+
122
+ test('getObjectDetails returns correct ResolutionDetails shape', async () => {
123
+ const details = await client.getObjectDetails('obj_flag', {});
124
+ expect(details.value).toEqual({ a: 1 });
125
+ expect(details.flagKey).toBe('obj_flag');
126
+ expect(details.reason).toBe(StandardResolutionReasons.TARGETING_MATCH);
127
+ });
128
+ });
129
+
130
+ describe('Context and targeting', () => {
131
+ test('getTreatmentWithConfig is called with context attributes', async () => {
132
+ await client.getBooleanValue('bool_on', false);
133
+ expect(mockSplitClient.getTreatmentWithConfig).toHaveBeenCalledWith('bool_on', {});
134
+ });
135
+
136
+ test('context attributes are passed to Split', async () => {
137
+ await OpenFeature.setContext({ targetingKey: 'user-1', region: 'eu' });
138
+ await client.getBooleanValue('bool_on', false);
139
+ expect(mockSplitClient.getTreatmentWithConfig).toHaveBeenCalledWith('bool_on', { region: 'eu' });
140
+ });
141
+ });
142
+
143
+ describe('Control / flag not found', () => {
144
+ test('control treatment: client returns default value', async () => {
145
+ const value = await client.getStringValue('unknown_flag', 'default');
146
+ expect(value).toBe('default');
147
+ });
148
+ test('control treatment: getStringDetails reveals FLAG_NOT_FOUND', async () => {
149
+ const details = await client.getStringDetails('unknown_flag', 'default');
150
+ expect(details.value).toBe('default');
151
+ expect(details.reason).toBe(StandardResolutionReasons.ERROR);
152
+ });
153
+ });
154
+
155
+ describe('Provider events', () => {
156
+ test('provider exposes events emitter', () => {
157
+ expect(provider.events).toBeDefined();
158
+ expect(typeof provider.events.emit).toBe('function');
159
+ expect(typeof provider.events.addHandler).toBe('function');
160
+ });
161
+ });
162
+ });
@@ -0,0 +1,115 @@
1
+ import {
2
+ parseValidNumber,
3
+ parseValidJsonObject,
4
+ parseBooleanTreatment,
5
+ } from '../lib/parsers';
6
+ import { ParseError } from '@openfeature/web-sdk';
7
+
8
+ describe('parsers', () => {
9
+ describe('parseValidNumber', () => {
10
+ test('parses integer string', () => {
11
+ expect(parseValidNumber('42')).toBe(42);
12
+ });
13
+
14
+ test('parses float string', () => {
15
+ expect(parseValidNumber('3.14')).toBe(3.14);
16
+ });
17
+
18
+ test('parses zero', () => {
19
+ expect(parseValidNumber('0')).toBe(0);
20
+ });
21
+
22
+ test('parses negative number', () => {
23
+ expect(parseValidNumber('-10')).toBe(-10);
24
+ });
25
+
26
+ test('throws ParseError for undefined', () => {
27
+ expect(() => parseValidNumber(undefined)).toThrow(ParseError);
28
+ expect(() => parseValidNumber(undefined)).toThrow(/undefined/);
29
+ });
30
+
31
+ test('throws ParseError for non-numeric string', () => {
32
+ expect(() => parseValidNumber('not-a-number')).toThrow(ParseError);
33
+ expect(() => parseValidNumber('not-a-number')).toThrow(/Invalid numeric value/);
34
+ });
35
+
36
+ test('throws ParseError for empty string', () => {
37
+ expect(() => parseValidNumber('')).toThrow(ParseError);
38
+ });
39
+ });
40
+
41
+ describe('parseValidJsonObject', () => {
42
+ test('parses plain object', () => {
43
+ expect(parseValidJsonObject('{"a":1}')).toEqual({ a: 1 });
44
+ });
45
+
46
+ test('parses nested object', () => {
47
+ expect(parseValidJsonObject('{"key":"value","nested":{"inner":"data"}}')).toEqual({
48
+ key: 'value',
49
+ nested: { inner: 'data' },
50
+ });
51
+ });
52
+
53
+ test('parses array (object type)', () => {
54
+ expect(parseValidJsonObject('[1,2,3]')).toEqual([1, 2, 3]);
55
+ });
56
+
57
+ test('throws ParseError for undefined', () => {
58
+ expect(() => parseValidJsonObject(undefined)).toThrow(ParseError);
59
+ expect(() => parseValidJsonObject(undefined)).toThrow(/undefined/);
60
+ });
61
+
62
+ test('throws ParseError for non-object JSON (string)', () => {
63
+ expect(() => parseValidJsonObject('"hello"')).toThrow(ParseError);
64
+ expect(() => parseValidJsonObject('"hello"')).toThrow(/expected "object"/);
65
+ });
66
+
67
+ test('throws ParseError for non-object JSON (number)', () => {
68
+ expect(() => parseValidJsonObject('42')).toThrow(ParseError);
69
+ });
70
+
71
+ test('throws ParseError for invalid JSON', () => {
72
+ expect(() => parseValidJsonObject('{ invalid }')).toThrow(ParseError);
73
+ expect(() => parseValidJsonObject('{ invalid }')).toThrow(/Error parsing/);
74
+ });
75
+ });
76
+
77
+ describe('parseBooleanTreatment', () => {
78
+ test('returns true for "on"', () => {
79
+ expect(parseBooleanTreatment('on')).toBe(true);
80
+ });
81
+
82
+ test('returns true for "ON" (case insensitive)', () => {
83
+ expect(parseBooleanTreatment('ON')).toBe(true);
84
+ });
85
+
86
+ test('returns true for "true"', () => {
87
+ expect(parseBooleanTreatment('true')).toBe(true);
88
+ });
89
+
90
+ test('returns true for "TRUE"', () => {
91
+ expect(parseBooleanTreatment('TRUE')).toBe(true);
92
+ });
93
+
94
+ test('returns false for "off"', () => {
95
+ expect(parseBooleanTreatment('off')).toBe(false);
96
+ });
97
+
98
+ test('returns false for "OFF"', () => {
99
+ expect(parseBooleanTreatment('OFF')).toBe(false);
100
+ });
101
+
102
+ test('returns false for "false"', () => {
103
+ expect(parseBooleanTreatment('false')).toBe(false);
104
+ });
105
+
106
+ test('throws ParseError for invalid treatment', () => {
107
+ expect(() => parseBooleanTreatment('maybe')).toThrow(ParseError);
108
+ expect(() => parseBooleanTreatment('maybe')).toThrow(/Invalid boolean value for maybe/);
109
+ });
110
+
111
+ test('throws ParseError for unknown string', () => {
112
+ expect(() => parseBooleanTreatment('v1')).toThrow(ParseError);
113
+ });
114
+ });
115
+ });