@splitsoftware/openfeature-web-split-provider 1.0.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.
- package/CHANGES.txt +3 -0
- package/CONTRIBUTORS-GUIDE.md +28 -0
- package/LICENSE +13 -0
- package/README.md +137 -0
- package/es/index.js +1 -0
- package/es/lib/js-split-provider.js +197 -0
- package/lib/index.js +4 -0
- package/lib/lib/js-split-provider.js +200 -0
- package/package.json +78 -0
- package/src/__tests__/integration/debug.test.js +79 -0
- package/src/__tests__/integration/e2e-events.test.js +202 -0
- package/src/__tests__/integration/e2e.test.js +155 -0
- package/src/__tests__/integration/mock.test.js +99 -0
- package/src/__tests__/integration/working.test.js +76 -0
- package/src/__tests__/mocks/memberships.emiliano@split.io.json +15 -0
- package/src/__tests__/mocks/memberships.emmanuel@split.io.json +9 -0
- package/src/__tests__/mocks/memberships.nicolas@split.io.json +9 -0
- package/src/__tests__/mocks/splitchanges.since.-1.json +1732 -0
- package/src/__tests__/provider.spec.js +163 -0
- package/src/__tests__/webSuites/client.spec.js +210 -0
- package/src/index.ts +1 -0
- package/src/lib/js-split-provider.ts +271 -0
- package/types/index.d.ts +1 -0
- package/types/lib/js-split-provider.d.ts +25 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/* eslint-disable jest/no-conditional-expect */
|
|
2
|
+
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
3
|
+
import { OpenFeatureSplitProvider } from '../lib/js-split-provider';
|
|
4
|
+
|
|
5
|
+
describe('OpenFeatureSplitProvider Unit Tests', () => {
|
|
6
|
+
let provider;
|
|
7
|
+
let mockSplitClient;
|
|
8
|
+
|
|
9
|
+
beforeEach(() => {
|
|
10
|
+
// Create a properly mocked Split client specifically for the provider
|
|
11
|
+
mockSplitClient = {
|
|
12
|
+
// Add ready method needed by provider
|
|
13
|
+
ready: jest.fn(() => true),
|
|
14
|
+
__getStatus: () => ({isReady: true}),
|
|
15
|
+
|
|
16
|
+
// Add event support
|
|
17
|
+
on: jest.fn((event, callback) => {
|
|
18
|
+
if (event === 'SDK_READY') {
|
|
19
|
+
// Immediately call the callback
|
|
20
|
+
setTimeout(() => callback(), 0);
|
|
21
|
+
}
|
|
22
|
+
return { id: 'mock-listener' };
|
|
23
|
+
}),
|
|
24
|
+
// Define SDK_READY event constant
|
|
25
|
+
Event: { SDK_READY: 'SDK_READY' },
|
|
26
|
+
|
|
27
|
+
// Mock the treatments
|
|
28
|
+
getTreatmentWithConfig: jest.fn((flagKey, _attributes) => {
|
|
29
|
+
// Return specific values for our test cases
|
|
30
|
+
if (flagKey === 'boolean-flag') return { treatment: 'on', config: '{"desc": "this is a test"}' };
|
|
31
|
+
if (flagKey === 'boolean-flag-off') return { treatment: 'off', config: {} };
|
|
32
|
+
if (flagKey === 'string-flag') return { treatment: 'a-string-treatment', config: {} };
|
|
33
|
+
if (flagKey === 'number-flag') return { treatment: '42', config: {} };
|
|
34
|
+
if (flagKey === 'object-flag') return { treatment: '{"key":"value","nested":{"inner":"data"}}', config: {} };
|
|
35
|
+
if (flagKey === 'non-existent') return { treatment: 'control', config: {} };
|
|
36
|
+
return { treatment: 'control', config: {} };
|
|
37
|
+
}),
|
|
38
|
+
// mock tracking
|
|
39
|
+
track: jest.fn(() => {}),
|
|
40
|
+
|
|
41
|
+
// Clean up
|
|
42
|
+
destroy: jest.fn(() => Promise.resolve())
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// Create the provider with our mock client
|
|
46
|
+
provider = new OpenFeatureSplitProvider({
|
|
47
|
+
client: () => mockSplitClient
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('should transform boolean ON treatment to true', () => {
|
|
52
|
+
const result = provider.resolveBooleanEvaluation(
|
|
53
|
+
'boolean-flag',
|
|
54
|
+
false, // default value
|
|
55
|
+
{ targetingKey: 'user-key' },
|
|
56
|
+
console // logger
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
expect(result.value).toBe(true);
|
|
60
|
+
expect(result.variant).toBe('on');
|
|
61
|
+
expect(result.flagMetadata.config).toBe('{"desc": "this is a test"}');
|
|
62
|
+
expect(mockSplitClient.getTreatmentWithConfig).toHaveBeenCalledWith(
|
|
63
|
+
'boolean-flag',
|
|
64
|
+
{}
|
|
65
|
+
);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('should transform boolean OFF treatment to false', () => {
|
|
69
|
+
const result = provider.resolveBooleanEvaluation(
|
|
70
|
+
'boolean-flag-off',
|
|
71
|
+
true, // default value
|
|
72
|
+
{ targetingKey: 'user-key' },
|
|
73
|
+
console // logger
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
expect(result.value).toBe(false);
|
|
77
|
+
expect(result.variant).toBe('off');
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('should handle string treatments', () => {
|
|
81
|
+
const result = provider.resolveStringEvaluation(
|
|
82
|
+
'string-flag',
|
|
83
|
+
'default', // default value
|
|
84
|
+
{ targetingKey: 'user-key' },
|
|
85
|
+
console // logger
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
expect(result.value).toBe('a-string-treatment');
|
|
89
|
+
expect(result.variant).toBe('a-string-treatment');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('should handle number treatments', () => {
|
|
93
|
+
const result = provider.resolveNumberEvaluation(
|
|
94
|
+
'number-flag',
|
|
95
|
+
0, // default value
|
|
96
|
+
{ targetingKey: 'user-key' },
|
|
97
|
+
console // logger
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
expect(result.value).toBe(42);
|
|
101
|
+
expect(result.variant).toBe('42');
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('should handle object treatments', () => {
|
|
105
|
+
const result = provider.resolveObjectEvaluation(
|
|
106
|
+
'object-flag',
|
|
107
|
+
{}, // default value
|
|
108
|
+
{ targetingKey: 'user-key' },
|
|
109
|
+
console // logger
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
expect(result.value).toEqual({ key: 'value', nested: { inner: 'data' } });
|
|
113
|
+
expect(result.variant).toBe('{"key":"value","nested":{"inner":"data"}}');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test('should handle control treatment as error', () => {
|
|
117
|
+
expect(() => {
|
|
118
|
+
provider.resolveStringEvaluation(
|
|
119
|
+
'non-existent',
|
|
120
|
+
'default', // default value
|
|
121
|
+
{ targetingKey: 'user-key' },
|
|
122
|
+
console // logger
|
|
123
|
+
);
|
|
124
|
+
}).toThrow(/control/);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test('track: throws when missing eventName', () => {
|
|
128
|
+
try {
|
|
129
|
+
provider.track('', { trafficType: 'user' }, {});
|
|
130
|
+
} catch (e) {
|
|
131
|
+
expect(e.message).toBe('Missing eventName, required to track');
|
|
132
|
+
expect(e.code).toBe('PARSE_ERROR');
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('track: throws when missing trafficType', () => {
|
|
137
|
+
try {
|
|
138
|
+
provider.track('evt', {}, {});
|
|
139
|
+
} catch (e) {
|
|
140
|
+
expect(e.message).toBe('Missing trafficType variable, required to track');
|
|
141
|
+
expect(e.code).toBe('INVALID_CONTEXT');
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test('track: ok without details', () => {
|
|
146
|
+
const trackSpy = jest.spyOn(mockSplitClient, 'track');
|
|
147
|
+
provider.track('view', { trafficType: 'user' }, null);
|
|
148
|
+
expect(trackSpy).toHaveBeenCalledTimes(1);
|
|
149
|
+
expect(trackSpy).toHaveBeenCalledWith('user', 'view', undefined, {});
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test('track: ok with details', () => {
|
|
153
|
+
const trackSpy = jest.spyOn(mockSplitClient, 'track');
|
|
154
|
+
provider.track(
|
|
155
|
+
'purchase',
|
|
156
|
+
{ trafficType: 'user' },
|
|
157
|
+
{ value: 9.99, properties: { plan: 'pro', beta: true } }
|
|
158
|
+
);
|
|
159
|
+
expect(trackSpy).toHaveBeenCalledTimes(1);
|
|
160
|
+
expect(trackSpy).toHaveBeenCalledWith('user', 'purchase', 9.99, { plan: 'pro', beta: true });
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
});
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { OpenFeature } from '@openfeature/web-sdk';
|
|
2
|
+
import { SplitFactory } from '@splitsoftware/splitio-browserjs';
|
|
3
|
+
import { OpenFeatureSplitProvider } from '../..';
|
|
4
|
+
|
|
5
|
+
// Mock Split features for browser testing
|
|
6
|
+
const mockFeatures = {
|
|
7
|
+
'my_feature': {
|
|
8
|
+
treatment: 'on',
|
|
9
|
+
config: '{"desc" : "this applies only to ON treatment"}'
|
|
10
|
+
},
|
|
11
|
+
'some_other_feature': {
|
|
12
|
+
treatment: 'off'
|
|
13
|
+
},
|
|
14
|
+
'int_feature': {
|
|
15
|
+
treatment: '32'
|
|
16
|
+
},
|
|
17
|
+
'obj_feature': {
|
|
18
|
+
treatment: '{"key": "value"}'
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
let mockSplitClient;
|
|
22
|
+
|
|
23
|
+
// Mock SplitIO SDK - Web version
|
|
24
|
+
jest.mock('@splitsoftware/splitio-browserjs', () => {
|
|
25
|
+
mockSplitClient = {
|
|
26
|
+
// Add ready method for web SDK
|
|
27
|
+
ready: jest.fn(() => true),
|
|
28
|
+
__getStatus: () => ({isReady: true}),
|
|
29
|
+
Event: {
|
|
30
|
+
'SDK_UPDATE': 'SDK_UPDATE'
|
|
31
|
+
},
|
|
32
|
+
on: () => {},
|
|
33
|
+
// Add event registration compatible with web SDK
|
|
34
|
+
addListener: jest.fn(({ event, handler }) => {
|
|
35
|
+
if (event === 'SDK_READY') {
|
|
36
|
+
handler(); // Call handler immediately as we're mocking a ready client
|
|
37
|
+
}
|
|
38
|
+
return { id: 'mock-listener-id' };
|
|
39
|
+
}),
|
|
40
|
+
getTreatmentWithConfig: jest.fn((splitName) => {
|
|
41
|
+
if (splitName === 'my_feature') return { treatment: 'on'};
|
|
42
|
+
if (splitName === 'int_feature') return { treatment: '32'};
|
|
43
|
+
if (splitName === 'obj_feature') return { treatment: '{"key": "value"}'};
|
|
44
|
+
if (splitName === 'my_feature') {
|
|
45
|
+
return {
|
|
46
|
+
treatment: 'on',
|
|
47
|
+
config: '{"desc" : "this applies only to ON treatment"}'
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
treatment: mockFeatures[splitName]?.treatment || 'control',
|
|
52
|
+
config: null
|
|
53
|
+
};
|
|
54
|
+
}),
|
|
55
|
+
track: jest.fn(()=>{}),
|
|
56
|
+
destroy: jest.fn(() => Promise.resolve())
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
SplitFactory: jest.fn(() => ({
|
|
61
|
+
client: jest.fn(() => mockSplitClient)
|
|
62
|
+
}))
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// Configure Split client for web environment
|
|
67
|
+
let splitFactory = SplitFactory({
|
|
68
|
+
core: {
|
|
69
|
+
authorizationKey: 'localhost'
|
|
70
|
+
},
|
|
71
|
+
features: mockFeatures,
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
let provider = new OpenFeatureSplitProvider(splitFactory);
|
|
75
|
+
OpenFeature.setProviderAndWait(provider);
|
|
76
|
+
|
|
77
|
+
let evaluationContext = {
|
|
78
|
+
targetingKey: 'key'
|
|
79
|
+
};
|
|
80
|
+
OpenFeature.setContext(evaluationContext);
|
|
81
|
+
let client = OpenFeature.getClient('test');
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
describe('OpenFeatureSplitProvider Unit Tests', () => {
|
|
85
|
+
|
|
86
|
+
test('useDefaultTest', () => {
|
|
87
|
+
let flagName = 'random-non-existent-feature';
|
|
88
|
+
|
|
89
|
+
let result = client.getBooleanValue(flagName, false);
|
|
90
|
+
expect(result).toEqual(false);
|
|
91
|
+
|
|
92
|
+
let result2 = client.getBooleanValue(flagName, true);
|
|
93
|
+
expect(result2).toEqual(true);
|
|
94
|
+
|
|
95
|
+
let defaultString = 'blah';
|
|
96
|
+
let resultString = client.getStringValue(flagName, defaultString);
|
|
97
|
+
expect(resultString).toEqual(defaultString);
|
|
98
|
+
|
|
99
|
+
let defaultInt = 100;
|
|
100
|
+
let resultInt = client.getNumberValue(flagName, defaultInt);
|
|
101
|
+
expect(resultInt).toEqual(defaultInt);
|
|
102
|
+
|
|
103
|
+
let defaultStructure = {
|
|
104
|
+
foo: 'bar'
|
|
105
|
+
};
|
|
106
|
+
let resultStructure = client.getObjectValue(flagName, defaultStructure);
|
|
107
|
+
expect(resultStructure).toEqual(defaultStructure);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('getControlVariantNonExistentSplit', () => {
|
|
111
|
+
let details = client.getBooleanDetails('non-existent-feature', false);
|
|
112
|
+
expect(details.value).toEqual(false);
|
|
113
|
+
expect(details.errorCode).toEqual('FLAG_NOT_FOUND');
|
|
114
|
+
expect(details.reason).toEqual('ERROR');
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('getBooleanSplitTest', () => {
|
|
118
|
+
let result = client.getBooleanValue('some_other_feature', true);
|
|
119
|
+
expect(result).toEqual(false);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test('getStringSplitTest', () => {
|
|
123
|
+
let result = client.getStringValue('some_other_feature', 'on');
|
|
124
|
+
expect(result).toEqual('off');
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test('getNumberSplitTest', () => {
|
|
128
|
+
let result = client.getNumberValue('int_feature', 0);
|
|
129
|
+
expect(result).toEqual(32);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test('getObjectSplitTest', () => {
|
|
133
|
+
let result = client.getObjectValue('obj_feature', {});
|
|
134
|
+
expect(result).toEqual({ 'key': 'value' });
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('getMetadataNameTest', () => {
|
|
138
|
+
expect(client.metadata.name).toEqual('test');
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test('getBooleanDetailsTest', () => {
|
|
142
|
+
let details = client.getBooleanDetails('some_other_feature', true);
|
|
143
|
+
expect(details.flagKey).toBe('some_other_feature');
|
|
144
|
+
expect(details.reason).toBe('TARGETING_MATCH');
|
|
145
|
+
expect(details.value).toBe(false);
|
|
146
|
+
expect(details.variant).toBe('off');
|
|
147
|
+
expect(details.errorCode).toBe(undefined);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('getNumberDetailsTest', () => {
|
|
151
|
+
let details = client.getNumberDetails('int_feature', 0);
|
|
152
|
+
expect(details.flagKey).toBe('int_feature');
|
|
153
|
+
expect(details.reason).toBe('TARGETING_MATCH');
|
|
154
|
+
expect(details.value).toBe(32);
|
|
155
|
+
expect(details.variant).toBe('32');
|
|
156
|
+
expect(details.errorCode).toBe(undefined);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test('getStringDetailsTest', () => {
|
|
160
|
+
let details = client.getStringDetails('some_other_feature', 'blah');
|
|
161
|
+
expect(details.flagKey).toBe('some_other_feature');
|
|
162
|
+
expect(details.reason).toBe('TARGETING_MATCH');
|
|
163
|
+
expect(details.value).toBe('off');
|
|
164
|
+
expect(details.variant).toBe('off');
|
|
165
|
+
expect(details.errorCode).toBe(undefined);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
test('getObjectDetailsTest', () => {
|
|
169
|
+
let details = client.getObjectDetails('obj_feature', {});
|
|
170
|
+
expect(details.flagKey).toBe('obj_feature');
|
|
171
|
+
expect(details.reason).toBe('TARGETING_MATCH');
|
|
172
|
+
expect(details.value).toEqual({ key: 'value' });
|
|
173
|
+
expect(details.variant).toBe('{"key": "value"}');
|
|
174
|
+
expect(details.errorCode).toBe(undefined);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
test('getBooleanFailTest', () => {
|
|
178
|
+
let value = client.getBooleanValue('obj_feature', false);
|
|
179
|
+
expect(value).toBe(false);
|
|
180
|
+
|
|
181
|
+
let details = client.getBooleanDetails('obj_feature', false);
|
|
182
|
+
expect(details.value).toBe(false);
|
|
183
|
+
expect(details.errorCode).toBe('PARSE_ERROR');
|
|
184
|
+
expect(details.reason).toBe('ERROR');
|
|
185
|
+
expect(details.variant).toBe(undefined);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
test('getNumberFailTest', () => {
|
|
189
|
+
let value = client.getNumberValue('obj_feature', 10);
|
|
190
|
+
expect(value).toBe(10);
|
|
191
|
+
|
|
192
|
+
let details = client.getNumberDetails('obj_feature', 10);
|
|
193
|
+
expect(details.value).toBe(10);
|
|
194
|
+
expect(details.errorCode).toBe('PARSE_ERROR');
|
|
195
|
+
expect(details.reason).toBe('ERROR');
|
|
196
|
+
expect(details.variant).toBe(undefined);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
test('getObjectFailTest', () => {
|
|
200
|
+
let defaultObject = { foo: 'bar' };
|
|
201
|
+
let value = client.getObjectValue('int_feature', defaultObject);
|
|
202
|
+
expect(value).toEqual(defaultObject);
|
|
203
|
+
|
|
204
|
+
let details = client.getObjectDetails('int_feature', defaultObject);
|
|
205
|
+
expect(details.value).toEqual(defaultObject);
|
|
206
|
+
expect(details.errorCode).toBe('PARSE_ERROR');
|
|
207
|
+
expect(details.reason).toBe('ERROR');
|
|
208
|
+
expect(details.variant).toBe(undefined);
|
|
209
|
+
});
|
|
210
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './lib/js-split-provider';
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
3
|
+
import {
|
|
4
|
+
EvaluationContext,
|
|
5
|
+
Provider,
|
|
6
|
+
ResolutionDetails,
|
|
7
|
+
ParseError,
|
|
8
|
+
FlagNotFoundError,
|
|
9
|
+
JsonValue,
|
|
10
|
+
StandardResolutionReasons,
|
|
11
|
+
Logger,
|
|
12
|
+
ProviderEvents,
|
|
13
|
+
OpenFeatureEventEmitter,
|
|
14
|
+
TrackingEventDetails,
|
|
15
|
+
} from "@openfeature/web-sdk";
|
|
16
|
+
import type SplitIO from "@splitsoftware/splitio-browserjs/types/splitio";
|
|
17
|
+
|
|
18
|
+
type Consumer = {
|
|
19
|
+
targetingKey: string | undefined;
|
|
20
|
+
trafficType: string;
|
|
21
|
+
attributes: SplitIO.Attributes;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const CONTROL_VALUE_ERROR_MESSAGE = "Received the 'control' value from Split.";
|
|
25
|
+
const CONTROL_TREATMENT = 'control';
|
|
26
|
+
|
|
27
|
+
export class OpenFeatureSplitProvider implements Provider {
|
|
28
|
+
metadata = {
|
|
29
|
+
name: "split",
|
|
30
|
+
};
|
|
31
|
+
private client: SplitIO.IBrowserClient;
|
|
32
|
+
private factory: SplitIO.IBrowserSDK;
|
|
33
|
+
private trafficType: string;
|
|
34
|
+
public events = new OpenFeatureEventEmitter();
|
|
35
|
+
|
|
36
|
+
onContextChange(oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void> {
|
|
37
|
+
const { targetingKey: oldTargetingKey } = oldContext;
|
|
38
|
+
const { targetingKey: newTargetingKey, trafficType: newTrafficType } = newContext;
|
|
39
|
+
|
|
40
|
+
this.trafficType = newTrafficType && newTrafficType !== this.trafficType ? newTrafficType as string : this.trafficType ;
|
|
41
|
+
if (newTargetingKey && newTargetingKey !== oldTargetingKey) {
|
|
42
|
+
this.client = this.factory.client(newTargetingKey);
|
|
43
|
+
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const emitContextChange = () => {
|
|
46
|
+
this.events.emit(ProviderEvents.ConfigurationChanged);
|
|
47
|
+
resolve();
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
this.eventsHandler(emitContextChange, reject);
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return Promise.resolve();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
constructor(splitFactory: SplitIO.IBrowserSDK) {
|
|
57
|
+
// Asume 'user' as default traffic type'
|
|
58
|
+
this.trafficType = 'user';
|
|
59
|
+
this.factory = splitFactory;
|
|
60
|
+
this.client = splitFactory.client();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async initialize(): Promise<void> {
|
|
64
|
+
|
|
65
|
+
await new Promise ((resolve, reject) => {
|
|
66
|
+
try {
|
|
67
|
+
this.eventsHandler(resolve, reject);
|
|
68
|
+
} catch {
|
|
69
|
+
reject();
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
resolveBooleanEvaluation(
|
|
75
|
+
flagKey: string,
|
|
76
|
+
_: boolean,
|
|
77
|
+
context: EvaluationContext,
|
|
78
|
+
_logger: Logger
|
|
79
|
+
): ResolutionDetails<boolean> {
|
|
80
|
+
const details = this.evaluateTreatment(
|
|
81
|
+
flagKey,
|
|
82
|
+
this.transformContext(context),
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
const treatment = details.value.toLowerCase();
|
|
86
|
+
|
|
87
|
+
if ( treatment === 'on' || treatment === 'true' ) {
|
|
88
|
+
return { ...details, value: true };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if ( treatment === 'off' || treatment === 'false' ) {
|
|
92
|
+
return { ...details, value: false };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
throw new ParseError(`Invalid boolean value for ${treatment}`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
resolveStringEvaluation(
|
|
99
|
+
flagKey: string,
|
|
100
|
+
_: string,
|
|
101
|
+
context: EvaluationContext,
|
|
102
|
+
_logger: Logger
|
|
103
|
+
): ResolutionDetails<string> {
|
|
104
|
+
const details = this.evaluateTreatment(
|
|
105
|
+
flagKey,
|
|
106
|
+
this.transformContext(context),
|
|
107
|
+
);
|
|
108
|
+
return details;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
resolveNumberEvaluation(
|
|
112
|
+
flagKey: string,
|
|
113
|
+
_: number,
|
|
114
|
+
context: EvaluationContext,
|
|
115
|
+
_logger: Logger
|
|
116
|
+
): ResolutionDetails<number> {
|
|
117
|
+
const details = this.evaluateTreatment(
|
|
118
|
+
flagKey,
|
|
119
|
+
this.transformContext(context),
|
|
120
|
+
);
|
|
121
|
+
return { ...details, value: this.parseValidNumber(details.value) };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
resolveObjectEvaluation<U extends JsonValue>(
|
|
125
|
+
flagKey: string,
|
|
126
|
+
_: U,
|
|
127
|
+
context: EvaluationContext,
|
|
128
|
+
_logger: Logger
|
|
129
|
+
): ResolutionDetails<U> {
|
|
130
|
+
const details = this.evaluateTreatment(
|
|
131
|
+
flagKey,
|
|
132
|
+
this.transformContext(context)
|
|
133
|
+
);
|
|
134
|
+
return { ...details, value: this.parseValidJsonObject(details.value) };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private evaluateTreatment(
|
|
138
|
+
flagKey: string,
|
|
139
|
+
consumer: Consumer
|
|
140
|
+
): ResolutionDetails<string> {
|
|
141
|
+
if (flagKey == null || flagKey === '') {
|
|
142
|
+
throw new FlagNotFoundError(
|
|
143
|
+
'flagKey must be a non-empty string'
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
const treatment: SplitIO.TreatmentWithConfig = this.client.getTreatmentWithConfig(
|
|
147
|
+
flagKey,
|
|
148
|
+
consumer.attributes
|
|
149
|
+
);
|
|
150
|
+
const {treatment: value, config} = treatment;
|
|
151
|
+
|
|
152
|
+
if (value === CONTROL_TREATMENT) {
|
|
153
|
+
throw new FlagNotFoundError(CONTROL_VALUE_ERROR_MESSAGE);
|
|
154
|
+
}
|
|
155
|
+
const flagMetadata = { config: config ? config : '' };
|
|
156
|
+
const details: ResolutionDetails<string> = {
|
|
157
|
+
value: value,
|
|
158
|
+
variant: value,
|
|
159
|
+
flagMetadata: flagMetadata,
|
|
160
|
+
reason: StandardResolutionReasons.TARGETING_MATCH,
|
|
161
|
+
};
|
|
162
|
+
return details;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
track(
|
|
166
|
+
trackingEventName: string,
|
|
167
|
+
context: EvaluationContext,
|
|
168
|
+
details: TrackingEventDetails
|
|
169
|
+
): void {
|
|
170
|
+
|
|
171
|
+
// eventName is always required
|
|
172
|
+
if (trackingEventName == null || trackingEventName === '')
|
|
173
|
+
throw new ParseError('Missing eventName, required to track');
|
|
174
|
+
|
|
175
|
+
const {trafficType} = this.transformContext(context);
|
|
176
|
+
let value;
|
|
177
|
+
let properties: SplitIO.Properties = {};
|
|
178
|
+
if (details != null) {
|
|
179
|
+
if (details.value != null) {
|
|
180
|
+
value = details.value;
|
|
181
|
+
}
|
|
182
|
+
if (details.properties != null) {
|
|
183
|
+
properties = details.properties as SplitIO.Properties;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
this.client.track(trafficType, trackingEventName, value, properties);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async onClose?(): Promise<void> {
|
|
191
|
+
return this.factory.destroy();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
//Transform the context into an object useful for the Split API, an key string with arbitrary Split "Attributes".
|
|
195
|
+
private transformContext(context: EvaluationContext): Consumer {
|
|
196
|
+
const { targetingKey, trafficType: ttVal, ...attributes } = context;
|
|
197
|
+
const trafficType =
|
|
198
|
+
ttVal != null && typeof ttVal === 'string' && ttVal.trim() !== ''
|
|
199
|
+
? ttVal
|
|
200
|
+
: this.trafficType;
|
|
201
|
+
return {
|
|
202
|
+
targetingKey,
|
|
203
|
+
trafficType,
|
|
204
|
+
// Stringify context objects include date.
|
|
205
|
+
attributes: JSON.parse(JSON.stringify(attributes)),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private parseValidNumber(stringValue: string | undefined) {
|
|
210
|
+
if (stringValue === undefined) {
|
|
211
|
+
throw new ParseError(`Invalid 'undefined' value.`);
|
|
212
|
+
}
|
|
213
|
+
const result = Number.parseFloat(stringValue);
|
|
214
|
+
if (Number.isNaN(result)) {
|
|
215
|
+
throw new ParseError(`Invalid numeric value ${stringValue}`);
|
|
216
|
+
}
|
|
217
|
+
return result;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private parseValidJsonObject<T extends JsonValue>(
|
|
221
|
+
stringValue: string | undefined
|
|
222
|
+
): T {
|
|
223
|
+
if (stringValue === undefined) {
|
|
224
|
+
throw new ParseError(`Invalid 'undefined' JSON value.`);
|
|
225
|
+
}
|
|
226
|
+
// we may want to allow the parsing to be customized.
|
|
227
|
+
try {
|
|
228
|
+
const value = JSON.parse(stringValue);
|
|
229
|
+
if (typeof value !== "object") {
|
|
230
|
+
throw new ParseError(
|
|
231
|
+
`Flag value ${stringValue} had unexpected type ${typeof value}, expected "object"`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
return value;
|
|
235
|
+
} catch (err) {
|
|
236
|
+
throw new ParseError(`Error parsing ${stringValue} as JSON, ${err}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private async eventsHandler(onSdkReady: (params?: any) => void, onSdkTimedOut: () => void): Promise <void> {
|
|
241
|
+
|
|
242
|
+
const onSdkReadyFromCache = () => {
|
|
243
|
+
this.events.emit(ProviderEvents.Stale, {
|
|
244
|
+
message: `Split ready from cache`,
|
|
245
|
+
});
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const clientStatus = (this.client as any).__getStatus();
|
|
249
|
+
if (clientStatus.isReady) {
|
|
250
|
+
onSdkReady();
|
|
251
|
+
} else {
|
|
252
|
+
|
|
253
|
+
if (clientStatus.isReadyFromCache) {
|
|
254
|
+
onSdkReadyFromCache();
|
|
255
|
+
} else {
|
|
256
|
+
this.client.on(this.client.Event.SDK_READY_FROM_CACHE, onSdkReadyFromCache);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (clientStatus.hasTimedout) {
|
|
260
|
+
onSdkTimedOut();
|
|
261
|
+
} else {
|
|
262
|
+
this.client.on(this.client.Event.SDK_READY_TIMED_OUT, onSdkTimedOut);
|
|
263
|
+
}
|
|
264
|
+
this.client.on(this.client.Event.SDK_READY, onSdkReady);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
this.client.on(this.client.Event.SDK_UPDATE, () => {
|
|
268
|
+
this.events.emit(ProviderEvents.ConfigurationChanged);
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
}
|
package/types/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './lib/js-split-provider';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { EvaluationContext, Provider, ResolutionDetails, JsonValue, Logger, OpenFeatureEventEmitter, TrackingEventDetails } from "@openfeature/web-sdk";
|
|
2
|
+
import type SplitIO from "@splitsoftware/splitio-browserjs/types/splitio";
|
|
3
|
+
export declare class OpenFeatureSplitProvider implements Provider {
|
|
4
|
+
metadata: {
|
|
5
|
+
name: string;
|
|
6
|
+
};
|
|
7
|
+
private client;
|
|
8
|
+
private factory;
|
|
9
|
+
private trafficType;
|
|
10
|
+
events: OpenFeatureEventEmitter;
|
|
11
|
+
onContextChange(oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void>;
|
|
12
|
+
constructor(splitFactory: SplitIO.IBrowserSDK);
|
|
13
|
+
initialize(): Promise<void>;
|
|
14
|
+
resolveBooleanEvaluation(flagKey: string, _: boolean, context: EvaluationContext, _logger: Logger): ResolutionDetails<boolean>;
|
|
15
|
+
resolveStringEvaluation(flagKey: string, _: string, context: EvaluationContext, _logger: Logger): ResolutionDetails<string>;
|
|
16
|
+
resolveNumberEvaluation(flagKey: string, _: number, context: EvaluationContext, _logger: Logger): ResolutionDetails<number>;
|
|
17
|
+
resolveObjectEvaluation<U extends JsonValue>(flagKey: string, _: U, context: EvaluationContext, _logger: Logger): ResolutionDetails<U>;
|
|
18
|
+
private evaluateTreatment;
|
|
19
|
+
track(trackingEventName: string, context: EvaluationContext, details: TrackingEventDetails): void;
|
|
20
|
+
onClose?(): Promise<void>;
|
|
21
|
+
private transformContext;
|
|
22
|
+
private parseValidNumber;
|
|
23
|
+
private parseValidJsonObject;
|
|
24
|
+
private eventsHandler;
|
|
25
|
+
}
|