@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
@@ -2,52 +2,59 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OpenFeatureSplitProvider = void 0;
4
4
  var tslib_1 = require("tslib");
5
- /* eslint-disable @typescript-eslint/no-explicit-any */
6
5
  /* eslint-disable @typescript-eslint/no-unused-vars */
7
6
  var web_sdk_1 = require("@openfeature/web-sdk");
8
- var CONTROL_VALUE_ERROR_MESSAGE = "Received the 'control' value from Split.";
9
- var CONTROL_TREATMENT = 'control';
7
+ var context_1 = require("./context");
8
+ var events_1 = require("./events");
9
+ var evaluation_1 = require("./evaluation");
10
+ var parsers_1 = require("./parsers");
10
11
  var OpenFeatureSplitProvider = /** @class */ (function () {
11
12
  function OpenFeatureSplitProvider(splitFactory) {
12
- this.metadata = {
13
- name: "split",
14
- };
13
+ this.metadata = { name: "split" };
14
+ /** Readiness of the bound client (rejects if it timed out). */
15
+ this.ready = Promise.resolve();
15
16
  this.events = new web_sdk_1.OpenFeatureEventEmitter();
16
- // Asume 'user' as default traffic type'
17
17
  this.trafficType = 'user';
18
18
  this.factory = splitFactory;
19
19
  this.client = splitFactory.client();
20
20
  }
21
- OpenFeatureSplitProvider.prototype.onContextChange = function (oldContext, newContext) {
22
- var _this = this;
23
- var oldTargetingKey = oldContext.targetingKey;
24
- var newTargetingKey = newContext.targetingKey, newTrafficType = newContext.trafficType;
25
- this.trafficType = newTrafficType && newTrafficType !== this.trafficType ? newTrafficType : this.trafficType;
26
- if (newTargetingKey && newTargetingKey !== oldTargetingKey) {
27
- this.client = this.factory.client(newTargetingKey);
28
- return new Promise(function (resolve, reject) {
29
- var emitContextChange = function () {
30
- _this.events.emit(web_sdk_1.ProviderEvents.ConfigurationChanged);
31
- resolve();
32
- };
33
- _this.eventsHandler(emitContextChange, reject);
34
- });
35
- }
36
- return Promise.resolve();
21
+ /**
22
+ * Warn through the Split SDK logger, so it follows the SDK log settings (`debug`, `factory.Logger`).
23
+ * `settings.log` is internal: the public typings only expose `factory.Logger`, which has no `warn`.
24
+ */
25
+ OpenFeatureSplitProvider.prototype.warn = function (message) {
26
+ var _a, _b, _c;
27
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
28
+ (_c = (_b = (_a = this.factory.settings) === null || _a === void 0 ? void 0 : _a.log) === null || _b === void 0 ? void 0 : _b.warn) === null || _c === void 0 ? void 0 : _c.call(_b, "[".concat(this.metadata.name, "-openfeature] ").concat(message));
29
+ };
30
+ /** Warn once per context set; evaluations reuse the context and would repeat it. */
31
+ OpenFeatureSplitProvider.prototype.warnIfBucketingKeyIgnored = function (context) {
32
+ var warning = (0, context_1.bucketingKeyWarning)(context);
33
+ if (warning)
34
+ this.warn(warning);
37
35
  };
38
- OpenFeatureSplitProvider.prototype.initialize = function () {
36
+ OpenFeatureSplitProvider.prototype.initialize = function (context) {
39
37
  return tslib_1.__awaiter(this, void 0, void 0, function () {
38
+ var key;
40
39
  var _this = this;
41
40
  return tslib_1.__generator(this, function (_a) {
42
41
  switch (_a.label) {
43
- case 0: return [4 /*yield*/, new Promise(function (resolve, reject) {
42
+ case 0:
43
+ if (context)
44
+ this.warnIfBucketingKeyIgnored(context);
45
+ key = context && (0, context_1.toSplitKey)((0, context_1.transformContext)(context, this.trafficType));
46
+ if (key)
47
+ this.client = this.factory.client(key);
48
+ this.ready = new Promise(function (resolve, reject) {
44
49
  try {
45
- _this.eventsHandler(resolve, reject);
50
+ (0, events_1.attachSplitReadyHandlers)(_this.client, _this.events, { onSdkReady: resolve, onSdkTimedOut: reject }, _this.metadata.name);
51
+ (0, events_1.attachSplitUpdateHandler)(_this.client, _this.events, _this.metadata.name);
46
52
  }
47
53
  catch (_a) {
48
54
  reject();
49
55
  }
50
- })];
56
+ });
57
+ return [4 /*yield*/, this.ready];
51
58
  case 1:
52
59
  _a.sent();
53
60
  return [2 /*return*/];
@@ -55,58 +62,64 @@ var OpenFeatureSplitProvider = /** @class */ (function () {
55
62
  });
56
63
  });
57
64
  };
58
- OpenFeatureSplitProvider.prototype.resolveBooleanEvaluation = function (flagKey, _, context, _logger) {
59
- var details = this.evaluateTreatment(flagKey, this.transformContext(context));
60
- var treatment = details.value.toLowerCase();
61
- if (treatment === 'on' || treatment === 'true') {
62
- return tslib_1.__assign(tslib_1.__assign({}, details), { value: true });
63
- }
64
- if (treatment === 'off' || treatment === 'false') {
65
- return tslib_1.__assign(tslib_1.__assign({}, details), { value: false });
65
+ OpenFeatureSplitProvider.prototype.onContextChange = function (oldContext, newContext) {
66
+ var _this = this;
67
+ this.warnIfBucketingKeyIgnored(newContext);
68
+ var newTrafficType = newContext.trafficType;
69
+ this.trafficType =
70
+ newTrafficType && newTrafficType !== this.trafficType
71
+ ? newTrafficType
72
+ : this.trafficType;
73
+ var oldConsumer = (0, context_1.transformContext)(oldContext, this.trafficType);
74
+ var newConsumer = (0, context_1.transformContext)(newContext, this.trafficType);
75
+ var newKey = (0, context_1.toSplitKey)(newConsumer);
76
+ var keyChanged = newConsumer.targetingKey !== oldConsumer.targetingKey ||
77
+ newConsumer.bucketingKey !== oldConsumer.bucketingKey;
78
+ if (!newKey || !keyChanged) {
79
+ // Same client: OpenFeature marks the provider READY when this resolves, so wait if it is still loading
80
+ // (a timeout during that load must still surface as ERROR). If it already timed out, that was reported
81
+ // and this.ready stays rejected, so resolve instead of moving the provider to ERROR on a no-key change.
82
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
+ var _a = this.client.__getStatus(), isReady = _a.isReady, hasTimedout = _a.hasTimedout;
84
+ return isReady || hasTimedout ? Promise.resolve() : this.ready;
66
85
  }
67
- throw new web_sdk_1.ParseError("Invalid boolean value for ".concat(treatment));
86
+ this.client = this.factory.client(newKey);
87
+ this.ready = new Promise(function (resolve, reject) {
88
+ var emitContextChange = function () {
89
+ _this.events.emit(web_sdk_1.ProviderEvents.ConfigurationChanged);
90
+ resolve();
91
+ };
92
+ (0, events_1.attachSplitReadyHandlers)(_this.client, _this.events, { onSdkReady: emitContextChange, onSdkTimedOut: reject }, _this.metadata.name);
93
+ (0, events_1.attachSplitUpdateHandler)(_this.client, _this.events, _this.metadata.name);
94
+ });
95
+ return this.ready;
96
+ };
97
+ OpenFeatureSplitProvider.prototype.resolveBooleanEvaluation = function (flagKey, _, context, _logger) {
98
+ var details = (0, evaluation_1.evaluateTreatment)(this.client, flagKey, (0, context_1.transformContext)(context, this.trafficType));
99
+ var value = (0, parsers_1.parseBooleanTreatment)(details.value);
100
+ return tslib_1.__assign(tslib_1.__assign({}, details), { value: value });
68
101
  };
69
102
  OpenFeatureSplitProvider.prototype.resolveStringEvaluation = function (flagKey, _, context, _logger) {
70
- var details = this.evaluateTreatment(flagKey, this.transformContext(context));
71
- return details;
103
+ return (0, evaluation_1.evaluateTreatment)(this.client, flagKey, (0, context_1.transformContext)(context, this.trafficType));
72
104
  };
73
105
  OpenFeatureSplitProvider.prototype.resolveNumberEvaluation = function (flagKey, _, context, _logger) {
74
- var details = this.evaluateTreatment(flagKey, this.transformContext(context));
75
- return tslib_1.__assign(tslib_1.__assign({}, details), { value: this.parseValidNumber(details.value) });
106
+ var details = (0, evaluation_1.evaluateTreatment)(this.client, flagKey, (0, context_1.transformContext)(context, this.trafficType));
107
+ return tslib_1.__assign(tslib_1.__assign({}, details), { value: (0, parsers_1.parseValidNumber)(details.value) });
76
108
  };
77
109
  OpenFeatureSplitProvider.prototype.resolveObjectEvaluation = function (flagKey, _, context, _logger) {
78
- var details = this.evaluateTreatment(flagKey, this.transformContext(context));
79
- return tslib_1.__assign(tslib_1.__assign({}, details), { value: this.parseValidJsonObject(details.value) });
80
- };
81
- OpenFeatureSplitProvider.prototype.evaluateTreatment = function (flagKey, consumer) {
82
- if (flagKey == null || flagKey === '') {
83
- throw new web_sdk_1.FlagNotFoundError('flagKey must be a non-empty string');
84
- }
85
- var treatment = this.client.getTreatmentWithConfig(flagKey, consumer.attributes);
86
- var value = treatment.treatment, config = treatment.config;
87
- if (value === CONTROL_TREATMENT) {
88
- throw new web_sdk_1.FlagNotFoundError(CONTROL_VALUE_ERROR_MESSAGE);
89
- }
90
- var flagMetadata = { config: config ? config : '' };
91
- var details = {
92
- value: value,
93
- variant: value,
94
- flagMetadata: flagMetadata,
95
- reason: web_sdk_1.StandardResolutionReasons.TARGETING_MATCH,
96
- };
97
- return details;
110
+ var details = (0, evaluation_1.evaluateTreatment)(this.client, flagKey, (0, context_1.transformContext)(context, this.trafficType));
111
+ return tslib_1.__assign(tslib_1.__assign({}, details), { value: (0, parsers_1.parseValidJsonObject)(details.value) });
98
112
  };
99
113
  OpenFeatureSplitProvider.prototype.track = function (trackingEventName, context, details) {
100
- // eventName is always required
101
- if (trackingEventName == null || trackingEventName === '')
114
+ if (trackingEventName == null || trackingEventName === '') {
102
115
  throw new web_sdk_1.ParseError('Missing eventName, required to track');
103
- var trafficType = this.transformContext(context).trafficType;
116
+ }
117
+ var trafficType = (0, context_1.transformContext)(context, this.trafficType).trafficType;
104
118
  var value;
105
119
  var properties = {};
106
120
  if (details != null) {
107
- if (details.value != null) {
121
+ if (details.value != null)
108
122
  value = details.value;
109
- }
110
123
  if (details.properties != null) {
111
124
  properties = details.properties;
112
125
  }
@@ -120,81 +133,6 @@ var OpenFeatureSplitProvider = /** @class */ (function () {
120
133
  });
121
134
  });
122
135
  };
123
- //Transform the context into an object useful for the Split API, an key string with arbitrary Split "Attributes".
124
- OpenFeatureSplitProvider.prototype.transformContext = function (context) {
125
- var targetingKey = context.targetingKey, ttVal = context.trafficType, attributes = tslib_1.__rest(context, ["targetingKey", "trafficType"]);
126
- var trafficType = ttVal != null && typeof ttVal === 'string' && ttVal.trim() !== ''
127
- ? ttVal
128
- : this.trafficType;
129
- return {
130
- targetingKey: targetingKey,
131
- trafficType: trafficType,
132
- // Stringify context objects include date.
133
- attributes: JSON.parse(JSON.stringify(attributes)),
134
- };
135
- };
136
- OpenFeatureSplitProvider.prototype.parseValidNumber = function (stringValue) {
137
- if (stringValue === undefined) {
138
- throw new web_sdk_1.ParseError("Invalid 'undefined' value.");
139
- }
140
- var result = Number.parseFloat(stringValue);
141
- if (Number.isNaN(result)) {
142
- throw new web_sdk_1.ParseError("Invalid numeric value ".concat(stringValue));
143
- }
144
- return result;
145
- };
146
- OpenFeatureSplitProvider.prototype.parseValidJsonObject = function (stringValue) {
147
- if (stringValue === undefined) {
148
- throw new web_sdk_1.ParseError("Invalid 'undefined' JSON value.");
149
- }
150
- // we may want to allow the parsing to be customized.
151
- try {
152
- var value = JSON.parse(stringValue);
153
- if (typeof value !== "object") {
154
- throw new web_sdk_1.ParseError("Flag value ".concat(stringValue, " had unexpected type ").concat(typeof value, ", expected \"object\""));
155
- }
156
- return value;
157
- }
158
- catch (err) {
159
- throw new web_sdk_1.ParseError("Error parsing ".concat(stringValue, " as JSON, ").concat(err));
160
- }
161
- };
162
- OpenFeatureSplitProvider.prototype.eventsHandler = function (onSdkReady, onSdkTimedOut) {
163
- return tslib_1.__awaiter(this, void 0, void 0, function () {
164
- var onSdkReadyFromCache, clientStatus;
165
- var _this = this;
166
- return tslib_1.__generator(this, function (_a) {
167
- onSdkReadyFromCache = function () {
168
- _this.events.emit(web_sdk_1.ProviderEvents.Stale, {
169
- message: "Split ready from cache",
170
- });
171
- };
172
- clientStatus = this.client.__getStatus();
173
- if (clientStatus.isReady) {
174
- onSdkReady();
175
- }
176
- else {
177
- if (clientStatus.isReadyFromCache) {
178
- onSdkReadyFromCache();
179
- }
180
- else {
181
- this.client.on(this.client.Event.SDK_READY_FROM_CACHE, onSdkReadyFromCache);
182
- }
183
- if (clientStatus.hasTimedout) {
184
- onSdkTimedOut();
185
- }
186
- else {
187
- this.client.on(this.client.Event.SDK_READY_TIMED_OUT, onSdkTimedOut);
188
- }
189
- this.client.on(this.client.Event.SDK_READY, onSdkReady);
190
- }
191
- this.client.on(this.client.Event.SDK_UPDATE, function () {
192
- _this.events.emit(web_sdk_1.ProviderEvents.ConfigurationChanged);
193
- });
194
- return [2 /*return*/];
195
- });
196
- });
197
- };
198
136
  return OpenFeatureSplitProvider;
199
137
  }());
200
138
  exports.OpenFeatureSplitProvider = OpenFeatureSplitProvider;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseBooleanTreatment = exports.parseValidJsonObject = exports.parseValidNumber = void 0;
4
+ var web_sdk_1 = require("@openfeature/web-sdk");
5
+ function parseValidNumber(stringValue) {
6
+ if (stringValue === undefined) {
7
+ throw new web_sdk_1.ParseError("Invalid 'undefined' value.");
8
+ }
9
+ var result = Number.parseFloat(stringValue);
10
+ if (Number.isNaN(result)) {
11
+ throw new web_sdk_1.ParseError("Invalid numeric value ".concat(stringValue));
12
+ }
13
+ return result;
14
+ }
15
+ exports.parseValidNumber = parseValidNumber;
16
+ function parseValidJsonObject(stringValue) {
17
+ if (stringValue === undefined) {
18
+ throw new web_sdk_1.ParseError("Invalid 'undefined' JSON value.");
19
+ }
20
+ try {
21
+ var value = JSON.parse(stringValue);
22
+ if (typeof value !== "object") {
23
+ throw new web_sdk_1.ParseError("Flag value ".concat(stringValue, " had unexpected type ").concat(typeof value, ", expected \"object\""));
24
+ }
25
+ return value;
26
+ }
27
+ catch (err) {
28
+ throw new web_sdk_1.ParseError("Error parsing ".concat(stringValue, " as JSON, ").concat(err));
29
+ }
30
+ }
31
+ exports.parseValidJsonObject = parseValidJsonObject;
32
+ /**
33
+ * Map a string treatment to a boolean for boolean flag resolution.
34
+ * @throws ParseError if treatment is not a valid boolean representation
35
+ */
36
+ function parseBooleanTreatment(treatment) {
37
+ var lower = treatment.toLowerCase();
38
+ if (lower === 'on' || lower === 'true')
39
+ return true;
40
+ if (lower === 'off' || lower === 'false')
41
+ return false;
42
+ throw new web_sdk_1.ParseError("Invalid boolean value for ".concat(treatment));
43
+ }
44
+ exports.parseBooleanTreatment = parseBooleanTreatment;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONTROL_VALUE_ERROR_MESSAGE = exports.CONTROL_TREATMENT = void 0;
4
+ exports.CONTROL_TREATMENT = 'control';
5
+ exports.CONTROL_VALUE_ERROR_MESSAGE = "Received the 'control' value from Split.";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@splitsoftware/openfeature-web-split-provider",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Split OpenFeature Web Provider",
5
5
  "files": [
6
6
  "README.md",
@@ -37,7 +37,7 @@
37
37
  "devDependencies": {
38
38
  "@eslint/js": "^9.35.0",
39
39
  "@openfeature/web-sdk": "^1.6.1",
40
- "@splitsoftware/splitio-browserjs": "^1.4.0",
40
+ "@splitsoftware/splitio-browserjs": "^1.7.0",
41
41
  "copyfiles": "^2.4.1",
42
42
  "cross-env": "^7.0.3",
43
43
  "eslint": "^9.35.0",
@@ -0,0 +1,145 @@
1
+ import { ProviderEvents } from '@openfeature/web-sdk';
2
+ import { OpenFeatureSplitProvider } from '../lib/js-split-provider';
3
+
4
+ const keyId = (key) => (typeof key === 'string' ? key : `${key.matchingKey}|${key.bucketingKey}`);
5
+
6
+ function makeClient() {
7
+ return {
8
+ __getStatus: () => ({ isReady: true }),
9
+ Event: { SDK_READY: 'SDK_READY', SDK_READY_FROM_CACHE: 'SDK_READY_FROM_CACHE', SDK_READY_TIMED_OUT: 'SDK_READY_TIMED_OUT', SDK_UPDATE: 'SDK_UPDATE' },
10
+ on: jest.fn(),
11
+ getTreatmentWithConfig: jest.fn(() => ({ treatment: 'on', config: null })),
12
+ };
13
+ }
14
+
15
+ /** Mock browser factory: one cached client per key, like the SDK. */
16
+ function makeFactory() {
17
+ const clients = {};
18
+ const factory = {
19
+ client: jest.fn((key = 'factory-key') => (clients[keyId(key)] ||= makeClient())),
20
+ settings: { log: { warn: jest.fn(), error: jest.fn(), info: jest.fn() } },
21
+ };
22
+ return { factory, clients };
23
+ }
24
+
25
+ /** factory.client calls made after the constructor. */
26
+ const clientCalls = (factory) => factory.client.mock.calls.slice(1).map((c) => c[0]);
27
+
28
+ describe('bucketingKey', () => {
29
+ test('initialize(context) binds { matchingKey, bucketingKey } and evaluates with that client', async () => {
30
+ const { factory, clients } = makeFactory();
31
+ const provider = new OpenFeatureSplitProvider(factory);
32
+ await provider.initialize({ targetingKey: 'u1', bucketingKey: 'b1' });
33
+ expect(clientCalls(factory)).toEqual([{ matchingKey: 'u1', bucketingKey: 'b1' }]);
34
+ provider.resolveStringEvaluation('flag', 'x', { targetingKey: 'u1', bucketingKey: 'b1', plan: 'pro' }, console);
35
+ expect(clients['u1|b1'].getTreatmentWithConfig).toHaveBeenCalledWith('flag', { plan: 'pro' });
36
+ });
37
+
38
+ test('initialize without a targeting key keeps the factory client', async () => {
39
+ const { factory } = makeFactory();
40
+ await new OpenFeatureSplitProvider(factory).initialize({ bucketingKey: 'b1' });
41
+ await new OpenFeatureSplitProvider(factory).initialize();
42
+ expect(factory.client.mock.calls.map((c) => c[0])).toEqual([undefined, undefined]);
43
+ });
44
+
45
+ describe('onContextChange', () => {
46
+ const base = { targetingKey: 'u1', bucketingKey: 'b1' };
47
+ let factory, clients, provider;
48
+
49
+ beforeEach(async () => {
50
+ ({ factory, clients } = makeFactory());
51
+ provider = new OpenFeatureSplitProvider(factory);
52
+ await provider.initialize(base);
53
+ factory.client.mockClear();
54
+ });
55
+
56
+ test('bucketingKey-only change binds a new client and emits ConfigurationChanged', async () => {
57
+ const emit = jest.spyOn(provider.events, 'emit');
58
+ await provider.onContextChange(base, { targetingKey: 'u1', bucketingKey: 'b2' });
59
+ expect(factory.client.mock.calls.map((c) => c[0])).toEqual([{ matchingKey: 'u1', bucketingKey: 'b2' }]);
60
+ expect(emit).toHaveBeenCalledWith(ProviderEvents.ConfigurationChanged);
61
+ });
62
+
63
+ test('removing the bucketingKey binds the targeting-key client', async () => {
64
+ await provider.onContextChange(base, { targetingKey: 'u1' });
65
+ expect(factory.client.mock.calls.map((c) => c[0])).toEqual(['u1']);
66
+ provider.resolveBooleanEvaluation('flag', false, { targetingKey: 'u1' }, console);
67
+ expect(clients.u1.getTreatmentWithConfig).toHaveBeenCalled();
68
+ });
69
+
70
+ test.each([
71
+ ['attributes-only change', { ...base, plan: 'pro' }],
72
+ ['bucketingKey only whitespace-different', { targetingKey: 'u1', bucketingKey: ' b1 ' }],
73
+ ['no targeting key', { bucketingKey: 'b2' }],
74
+ ])('%s: no new client', async (_, newContext) => {
75
+ await provider.onContextChange(base, newContext);
76
+ expect(factory.client).not.toHaveBeenCalled();
77
+ });
78
+ });
79
+
80
+ test('attribute-only change resolves when the bound client timed out', async () => {
81
+ const { factory, clients } = makeFactory();
82
+ const provider = new OpenFeatureSplitProvider(factory);
83
+ clients['u1|b1'] = {
84
+ ...makeClient(),
85
+ __getStatus: () => ({ isReady: false, isReadyFromCache: false, hasTimedout: true }),
86
+ };
87
+ await expect(provider.initialize({ targetingKey: 'u1', bucketingKey: 'b1' })).rejects.toBeUndefined();
88
+ factory.client.mockClear();
89
+
90
+ await expect(
91
+ provider.onContextChange({ targetingKey: 'u1', bucketingKey: 'b1' }, { targetingKey: 'u1', bucketingKey: 'b1', plan: 'pro' })
92
+ ).resolves.toBeUndefined();
93
+ expect(factory.client).not.toHaveBeenCalled();
94
+ });
95
+
96
+ describe('warnings', () => {
97
+ const warnings = (factory) => factory.settings.log.warn.mock.calls.map((c) => c[0]);
98
+
99
+ test('initialize warns through the Split logger with the reason, never the value', async () => {
100
+ const { factory } = makeFactory();
101
+ await new OpenFeatureSplitProvider(factory).initialize({ targetingKey: 'u1', bucketingKey: 'x'.repeat(251) });
102
+ expect(warnings(factory)).toEqual([
103
+ '[split-openfeature] bucketingKey ignored because it is longer than 250 characters; using the targeting key only.',
104
+ ]);
105
+ expect(factory.settings.log.error).not.toHaveBeenCalled();
106
+ expect(factory.settings.log.info).not.toHaveBeenCalled();
107
+ });
108
+
109
+ test('initialize warns when a bucketingKey comes without a targeting key', async () => {
110
+ const { factory } = makeFactory();
111
+ await new OpenFeatureSplitProvider(factory).initialize({ bucketingKey: 'b1' });
112
+ expect(warnings(factory)).toEqual(['[split-openfeature] bucketingKey ignored because the context has no targetingKey.']);
113
+ });
114
+
115
+ test.each([
116
+ ['non-string', { targetingKey: 'u1', bucketingKey: 7 }, 'it is not a string'],
117
+ ['blank', { targetingKey: 'u1', bucketingKey: ' ' }, 'it is blank'],
118
+ ['too long', { targetingKey: 'u2', bucketingKey: 'b'.repeat(251) }, 'it is longer than 250 characters'],
119
+ ['no targeting key', { bucketingKey: 'b2' }, 'the context has no targetingKey'],
120
+ ])('onContextChange warns for a %s bucketingKey', async (_, newContext, reason) => {
121
+ const { factory } = makeFactory();
122
+ const provider = new OpenFeatureSplitProvider(factory);
123
+ await provider.initialize({ targetingKey: 'u1', bucketingKey: 'b1' });
124
+ await provider.onContextChange({ targetingKey: 'u1', bucketingKey: 'b1' }, newContext);
125
+ expect(warnings(factory)).toHaveLength(1);
126
+ expect(warnings(factory)[0]).toContain(`bucketingKey ignored because ${reason}`);
127
+ expect(warnings(factory)[0]).not.toMatch(/for attribute/i);
128
+ });
129
+
130
+ test('valid contexts and evaluations do not warn', async () => {
131
+ const { factory } = makeFactory();
132
+ const provider = new OpenFeatureSplitProvider(factory);
133
+ await provider.initialize({ targetingKey: 'u1', bucketingKey: 'b1' });
134
+ await provider.onContextChange({ targetingKey: 'u1', bucketingKey: 'b1' }, { targetingKey: 'u1' });
135
+ provider.resolveBooleanEvaluation('flag', false, { targetingKey: 'u1', bucketingKey: ' ' }, console);
136
+ expect(factory.settings.log.warn).not.toHaveBeenCalled();
137
+ });
138
+
139
+ test('a factory without settings.log does not throw', async () => {
140
+ const { factory } = makeFactory();
141
+ delete factory.settings;
142
+ await expect(new OpenFeatureSplitProvider(factory).initialize({ bucketingKey: 'b1' })).resolves.toBeUndefined();
143
+ });
144
+ });
145
+ });
@@ -0,0 +1,146 @@
1
+ import { bucketingKeyWarning, toSplitKey, transformContext } from '../lib/context';
2
+
3
+ describe('context', () => {
4
+ describe('transformContext', () => {
5
+ const defaultTrafficType = 'user';
6
+
7
+ test('uses defaultTrafficType when context has no trafficType', () => {
8
+ const result = transformContext({ targetingKey: 'key-1' }, defaultTrafficType);
9
+ expect(result.trafficType).toBe('user');
10
+ expect(result.targetingKey).toBe('key-1');
11
+ expect(result.attributes).toEqual({});
12
+ });
13
+
14
+ test('uses context trafficType when present and non-empty', () => {
15
+ const result = transformContext(
16
+ { targetingKey: 'key-1', trafficType: 'account' },
17
+ defaultTrafficType
18
+ );
19
+ expect(result.trafficType).toBe('account');
20
+ expect(result.targetingKey).toBe('key-1');
21
+ expect(result.attributes).toEqual({});
22
+ });
23
+
24
+ test('falls back to default when trafficType is empty string', () => {
25
+ const result = transformContext(
26
+ { targetingKey: 'key-1', trafficType: '' },
27
+ defaultTrafficType
28
+ );
29
+ expect(result.trafficType).toBe('user');
30
+ });
31
+
32
+ test('falls back to default when trafficType is whitespace', () => {
33
+ const result = transformContext(
34
+ { targetingKey: 'key-1', trafficType: ' ' },
35
+ defaultTrafficType
36
+ );
37
+ expect(result.trafficType).toBe('user');
38
+ });
39
+
40
+ test('passes remaining context as attributes', () => {
41
+ const result = transformContext(
42
+ {
43
+ targetingKey: 'key-1',
44
+ trafficType: 'user',
45
+ region: 'eu',
46
+ plan: 'pro',
47
+ },
48
+ defaultTrafficType
49
+ );
50
+ expect(result.attributes).toEqual({ region: 'eu', plan: 'pro' });
51
+ });
52
+
53
+ test('deep-clones attributes (no reference)', () => {
54
+ const attrs = { nested: { value: 1 } };
55
+ const result = transformContext(
56
+ { targetingKey: 'k', ...attrs },
57
+ defaultTrafficType
58
+ );
59
+ expect(result.attributes).toEqual({ nested: { value: 1 } });
60
+ expect(result.attributes).not.toBe(attrs);
61
+ expect(result.attributes.nested).not.toBe(attrs.nested);
62
+ });
63
+ });
64
+
65
+ describe('transformContext bucketingKey', () => {
66
+ test('valid bucketingKey is trimmed and not forwarded as an attribute', () => {
67
+ const result = transformContext({ targetingKey: 'u1', bucketingKey: ' b1 ', plan: 'pro' }, 'user');
68
+ expect(result.bucketingKey).toBe('b1');
69
+ expect(result.attributes).toEqual({ plan: 'pro' });
70
+ });
71
+
72
+ test.each([undefined, null, '', ' ', 7, true, { x: 1 }, 'b'.repeat(251)])(
73
+ 'unusable bucketingKey %p is ignored and not forwarded',
74
+ (value) => {
75
+ const result = transformContext({ targetingKey: 'u1', bucketingKey: value }, 'user');
76
+ expect(result.bucketingKey).toBeUndefined();
77
+ expect(result.attributes).toEqual({});
78
+ }
79
+ );
80
+
81
+ test('other spellings stay attributes', () => {
82
+ const result = transformContext({ targetingKey: 'u1', BucketingKey: 'x', bucketing_key: 'y' }, 'user');
83
+ expect(result.bucketingKey).toBeUndefined();
84
+ expect(result.attributes).toEqual({ BucketingKey: 'x', bucketing_key: 'y' });
85
+ });
86
+ });
87
+
88
+ describe('toSplitKey', () => {
89
+ const key = (context) => toSplitKey(transformContext(context, 'user'));
90
+
91
+ test('targeting + bucketing key gives a composite key', () => {
92
+ expect(key({ targetingKey: 'u1', bucketingKey: 'b1' })).toEqual({ matchingKey: 'u1', bucketingKey: 'b1' });
93
+ });
94
+
95
+ test('no bucketingKey gives the targeting key', () => {
96
+ expect(key({ targetingKey: 'u1' })).toBe('u1');
97
+ });
98
+
99
+ test('missing or empty targeting key gives undefined', () => {
100
+ expect(key({ bucketingKey: 'b1' })).toBeUndefined();
101
+ expect(key({ targetingKey: '', bucketingKey: 'b1' })).toBeUndefined();
102
+ });
103
+ });
104
+
105
+ describe('bucketingKeyWarning', () => {
106
+ test.each([
107
+ [7, 'it is not a string'],
108
+ [true, 'it is not a string'],
109
+ [{ x: 1 }, 'it is not a string'],
110
+ ['', 'it is blank'],
111
+ [' ', 'it is blank'],
112
+ ['b'.repeat(251), 'it is longer than 250 characters'],
113
+ ])('unusable bucketingKey %p names the reason', (value, reason) => {
114
+ const warning = bucketingKeyWarning({ targetingKey: 'u1', bucketingKey: value });
115
+ expect(warning).toBe(`bucketingKey ignored because ${reason}; using the targeting key only.`);
116
+ });
117
+
118
+ test('invalid bucketingKey without a targeting key does not mention the targeting key', () => {
119
+ expect(bucketingKeyWarning({ bucketingKey: ' ' })).toBe('bucketingKey ignored because it is blank.');
120
+ expect(bucketingKeyWarning({ targetingKey: '', bucketingKey: 7 })).toBe('bucketingKey ignored because it is not a string.');
121
+ });
122
+
123
+ test('never includes the value', () => {
124
+ const secret = 's3cr3t-'.repeat(40);
125
+ expect(bucketingKeyWarning({ targetingKey: 'u1', bucketingKey: secret })).not.toContain('s3cr3t');
126
+ expect(bucketingKeyWarning({ bucketingKey: 's3cr3t' })).not.toContain('s3cr3t');
127
+ });
128
+
129
+ test.each([{}, { targetingKey: '' }])('valid bucketingKey without a targeting key: %p', (context) => {
130
+ expect(bucketingKeyWarning({ ...context, bucketingKey: 'b1' })).toBe(
131
+ 'bucketingKey ignored because the context has no targetingKey.'
132
+ );
133
+ });
134
+
135
+ test.each([
136
+ { targetingKey: 'u1' },
137
+ { targetingKey: 'u1', bucketingKey: null },
138
+ { bucketingKey: null },
139
+ { targetingKey: 'u1', bucketingKey: ' b1 ' },
140
+ { targetingKey: 'u1', bucketingKey: 'b'.repeat(250) },
141
+ {},
142
+ ])('nothing to report for %p', (context) => {
143
+ expect(bucketingKeyWarning(context)).toBeUndefined();
144
+ });
145
+ });
146
+ });