@splitsoftware/splitio-commons 1.10.1-rc.4 → 1.12.0-rc.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 (109) hide show
  1. package/CHANGES.txt +16 -10
  2. package/cjs/evaluator/index.js +22 -3
  3. package/cjs/logger/constants.js +6 -4
  4. package/cjs/logger/messages/warn.js +5 -3
  5. package/cjs/sdkClient/client.js +19 -16
  6. package/cjs/sdkClient/clientInputValidation.js +16 -16
  7. package/cjs/sdkFactory/index.js +1 -1
  8. package/cjs/sdkManager/index.js +14 -13
  9. package/cjs/storages/KeyBuilder.js +1 -1
  10. package/cjs/storages/inLocalStorage/SplitsCacheInLocal.js +3 -10
  11. package/cjs/storages/inMemory/SplitsCacheInMemory.js +2 -10
  12. package/cjs/storages/inRedis/RedisAdapter.js +32 -13
  13. package/cjs/storages/inRedis/SegmentsCacheInRedis.js +2 -2
  14. package/cjs/storages/inRedis/SplitsCacheInRedis.js +38 -22
  15. package/cjs/storages/inRedis/index.js +1 -1
  16. package/cjs/storages/pluggable/SplitsCachePluggable.js +27 -11
  17. package/cjs/storages/pluggable/index.js +1 -1
  18. package/cjs/utils/constants/index.js +16 -2
  19. package/cjs/utils/inputValidation/index.js +5 -5
  20. package/cjs/utils/inputValidation/{splitExistance.js → splitExistence.js} +3 -3
  21. package/cjs/utils/inputValidation/{trafficTypeExistance.js → trafficTypeExistence.js} +6 -6
  22. package/cjs/utils/lang/sets.js +11 -1
  23. package/cjs/utils/settingsValidation/index.js +1 -1
  24. package/cjs/utils/settingsValidation/splitFilters.js +25 -17
  25. package/esm/evaluator/index.js +23 -4
  26. package/esm/logger/constants.js +4 -2
  27. package/esm/logger/messages/warn.js +5 -3
  28. package/esm/sdkClient/client.js +20 -17
  29. package/esm/sdkClient/clientInputValidation.js +18 -18
  30. package/esm/sdkFactory/index.js +1 -1
  31. package/esm/sdkManager/index.js +11 -10
  32. package/esm/storages/KeyBuilder.js +1 -1
  33. package/esm/storages/inLocalStorage/SplitsCacheInLocal.js +4 -11
  34. package/esm/storages/inMemory/SplitsCacheInMemory.js +3 -11
  35. package/esm/storages/inRedis/RedisAdapter.js +32 -13
  36. package/esm/storages/inRedis/SegmentsCacheInRedis.js +2 -2
  37. package/esm/storages/inRedis/SplitsCacheInRedis.js +40 -24
  38. package/esm/storages/inRedis/index.js +1 -1
  39. package/esm/storages/pluggable/SplitsCachePluggable.js +29 -13
  40. package/esm/storages/pluggable/index.js +1 -1
  41. package/esm/utils/constants/index.js +14 -0
  42. package/esm/utils/inputValidation/index.js +2 -2
  43. package/esm/utils/inputValidation/{splitExistance.js → splitExistence.js} +1 -1
  44. package/esm/utils/inputValidation/{trafficTypeExistance.js → trafficTypeExistence.js} +4 -4
  45. package/esm/utils/lang/sets.js +9 -0
  46. package/esm/utils/settingsValidation/index.js +1 -1
  47. package/esm/utils/settingsValidation/splitFilters.js +17 -9
  48. package/package.json +1 -1
  49. package/src/evaluator/index.ts +28 -5
  50. package/src/logger/constants.ts +4 -2
  51. package/src/logger/messages/warn.ts +9 -7
  52. package/src/sdkClient/client.ts +18 -18
  53. package/src/sdkClient/clientInputValidation.ts +18 -18
  54. package/src/sdkFactory/index.ts +1 -1
  55. package/src/sdkFactory/types.ts +3 -7
  56. package/src/sdkManager/index.ts +14 -14
  57. package/src/storages/AbstractSplitsCacheAsync.ts +1 -1
  58. package/src/storages/AbstractSplitsCacheSync.ts +1 -1
  59. package/src/storages/KeyBuilder.ts +1 -1
  60. package/src/storages/inLocalStorage/SplitsCacheInLocal.ts +8 -15
  61. package/src/storages/inMemory/SplitsCacheInMemory.ts +6 -14
  62. package/src/storages/inRedis/EventsCacheInRedis.ts +3 -3
  63. package/src/storages/inRedis/ImpressionCountsCacheInRedis.ts +3 -3
  64. package/src/storages/inRedis/ImpressionsCacheInRedis.ts +3 -3
  65. package/src/storages/inRedis/RedisAdapter.ts +38 -16
  66. package/src/storages/inRedis/SegmentsCacheInRedis.ts +5 -5
  67. package/src/storages/inRedis/SplitsCacheInRedis.ts +49 -28
  68. package/src/storages/inRedis/TelemetryCacheInRedis.ts +2 -2
  69. package/src/storages/inRedis/UniqueKeysCacheInRedis.ts +3 -3
  70. package/src/storages/inRedis/index.ts +1 -1
  71. package/src/storages/pluggable/SplitsCachePluggable.ts +35 -13
  72. package/src/storages/pluggable/index.ts +1 -1
  73. package/src/storages/types.ts +5 -5
  74. package/src/trackers/impressionObserver/utils.ts +1 -1
  75. package/src/types.ts +0 -2
  76. package/src/utils/constants/index.ts +16 -0
  77. package/src/utils/inputValidation/index.ts +2 -2
  78. package/src/utils/inputValidation/{splitExistance.ts → splitExistence.ts} +1 -1
  79. package/src/utils/inputValidation/{trafficTypeExistance.ts → trafficTypeExistence.ts} +4 -4
  80. package/src/utils/lang/sets.ts +9 -1
  81. package/src/utils/redis/RedisMock.ts +1 -3
  82. package/src/utils/settingsValidation/index.ts +1 -1
  83. package/src/utils/settingsValidation/splitFilters.ts +19 -11
  84. package/types/evaluator/index.d.ts +1 -1
  85. package/types/logger/constants.d.ts +4 -2
  86. package/types/sdkFactory/types.d.ts +3 -3
  87. package/types/sdkManager/index.d.ts +2 -3
  88. package/types/storages/AbstractSplitsCacheAsync.d.ts +1 -1
  89. package/types/storages/AbstractSplitsCacheSync.d.ts +1 -1
  90. package/types/storages/inLocalStorage/SplitsCacheInLocal.d.ts +1 -1
  91. package/types/storages/inMemory/SplitsCacheInMemory.d.ts +1 -1
  92. package/types/storages/inRedis/EventsCacheInRedis.d.ts +2 -2
  93. package/types/storages/inRedis/ImpressionCountsCacheInRedis.d.ts +3 -2
  94. package/types/storages/inRedis/ImpressionsCacheInRedis.d.ts +2 -2
  95. package/types/storages/inRedis/RedisAdapter.d.ts +1 -1
  96. package/types/storages/inRedis/SegmentsCacheInRedis.d.ts +3 -3
  97. package/types/storages/inRedis/SplitsCacheInRedis.d.ts +10 -14
  98. package/types/storages/inRedis/TelemetryCacheInRedis.d.ts +2 -2
  99. package/types/storages/inRedis/UniqueKeysCacheInRedis.d.ts +3 -2
  100. package/types/storages/pluggable/SplitsCachePluggable.d.ts +10 -9
  101. package/types/storages/types.d.ts +5 -5
  102. package/types/trackers/impressionObserver/utils.d.ts +1 -1
  103. package/types/types.d.ts +0 -2
  104. package/types/utils/constants/index.d.ts +12 -0
  105. package/types/utils/inputValidation/index.d.ts +2 -2
  106. package/types/utils/inputValidation/splitExistence.d.ts +7 -0
  107. package/types/utils/inputValidation/trafficTypeExistence.d.ts +9 -0
  108. package/types/utils/lang/sets.d.ts +1 -0
  109. package/types/utils/settingsValidation/splitFilters.d.ts +3 -2
@@ -1,8 +1,8 @@
1
- import { __extends } from "tslib";
1
+ import { __extends, __spreadArray } from "tslib";
2
2
  import { isFiniteNumber, isNaNNumber } from '../../utils/lang';
3
3
  import { LOG_PREFIX } from './constants';
4
4
  import { AbstractSplitsCacheAsync } from '../AbstractSplitsCacheAsync';
5
- import { _Set } from '../../utils/lang/sets';
5
+ import { _Set, returnDifference } from '../../utils/lang/sets';
6
6
  /**
7
7
  * Discard errors for an answer of multiple operations.
8
8
  */
@@ -19,11 +19,12 @@ function processPipelineAnswer(results) {
19
19
  */
20
20
  var SplitsCacheInRedis = /** @class */ (function (_super) {
21
21
  __extends(SplitsCacheInRedis, _super);
22
- function SplitsCacheInRedis(log, keys, redis) {
22
+ function SplitsCacheInRedis(log, keys, redis, splitFiltersValidation) {
23
23
  var _this = _super.call(this) || this;
24
24
  _this.log = log;
25
25
  _this.redis = redis;
26
26
  _this.keys = keys;
27
+ _this.flagSetsFilter = splitFiltersValidation ? splitFiltersValidation.groupedFilters.bySet : [];
27
28
  // There is no need to listen for redis 'error' event, because in that case ioredis calls will be rejected and handled by redis storage adapters.
28
29
  // But it is done just to avoid getting the ioredis message `Unhandled error event`.
29
30
  _this.redis.on('error', function (e) {
@@ -46,6 +47,18 @@ var SplitsCacheInRedis = /** @class */ (function (_super) {
46
47
  var ttKey = this.keys.buildTrafficTypeKey(split.trafficTypeName);
47
48
  return this.redis.incr(ttKey);
48
49
  };
50
+ SplitsCacheInRedis.prototype._updateFlagSets = function (featureFlagName, flagSetsOfRemovedFlag, flagSetsOfAddedFlag) {
51
+ var _this = this;
52
+ var removeFromFlagSets = returnDifference(flagSetsOfRemovedFlag, flagSetsOfAddedFlag);
53
+ var addToFlagSets = returnDifference(flagSetsOfAddedFlag, flagSetsOfRemovedFlag);
54
+ if (this.flagSetsFilter.length > 0) {
55
+ addToFlagSets = addToFlagSets.filter(function (flagSet) {
56
+ return _this.flagSetsFilter.some(function (filterFlagSet) { return filterFlagSet === flagSet; });
57
+ });
58
+ }
59
+ var items = [featureFlagName];
60
+ return Promise.all(__spreadArray(__spreadArray([], removeFromFlagSets.map(function (flagSetName) { return _this.redis.srem(_this.keys.buildFlagSetKey(flagSetName), items); }), true), addToFlagSets.map(function (flagSetName) { return _this.redis.sadd(_this.keys.buildFlagSetKey(flagSetName), items); }), true));
61
+ };
49
62
  /**
50
63
  * Add a given split.
51
64
  * The returned promise is resolved when the operation success
@@ -55,16 +68,16 @@ var SplitsCacheInRedis = /** @class */ (function (_super) {
55
68
  var _this = this;
56
69
  var splitKey = this.keys.buildSplitKey(name);
57
70
  return this.redis.get(splitKey).then(function (splitFromStorage) {
58
- // handling parsing errors
59
- var parsedPreviousSplit, newStringifiedSplit;
71
+ // handling parsing error
72
+ var parsedPreviousSplit, stringifiedNewSplit;
60
73
  try {
61
74
  parsedPreviousSplit = splitFromStorage ? JSON.parse(splitFromStorage) : undefined;
62
- newStringifiedSplit = JSON.stringify(split);
75
+ stringifiedNewSplit = JSON.stringify(split);
63
76
  }
64
77
  catch (e) {
65
78
  throw new Error('Error parsing feature flag definition: ' + e);
66
79
  }
67
- return _this.redis.set(splitKey, newStringifiedSplit).then(function () {
80
+ return _this.redis.set(splitKey, stringifiedNewSplit).then(function () {
68
81
  // avoid unnecessary increment/decrement operations
69
82
  if (parsedPreviousSplit && parsedPreviousSplit.trafficTypeName === split.trafficTypeName)
70
83
  return;
@@ -73,7 +86,7 @@ var SplitsCacheInRedis = /** @class */ (function (_super) {
73
86
  if (parsedPreviousSplit)
74
87
  return _this._decrementCounts(parsedPreviousSplit);
75
88
  });
76
- });
89
+ }).then(function () { return _this._updateFlagSets(name, parsedPreviousSplit && parsedPreviousSplit.sets, split.sets); });
77
90
  }).then(function () { return true; });
78
91
  };
79
92
  /**
@@ -94,8 +107,9 @@ var SplitsCacheInRedis = /** @class */ (function (_super) {
94
107
  var _this = this;
95
108
  return this.getSplit(name).then(function (split) {
96
109
  if (split) {
97
- _this._decrementCounts(split);
110
+ return _this._decrementCounts(split).then(function () { return _this._updateFlagSets(name, split.sets); });
98
111
  }
112
+ }).then(function () {
99
113
  return _this.redis.del(_this.keys.buildSplitKey(name));
100
114
  });
101
115
  };
@@ -170,14 +184,20 @@ var SplitsCacheInRedis = /** @class */ (function (_super) {
170
184
  return this.redis.keys(this.keys.searchPatternForSplitKeys()).then(function (listOfKeys) { return listOfKeys.map(_this.keys.extractKey); });
171
185
  };
172
186
  /**
173
- * Get list of split names related to a given flag set names list.
174
- * The returned promise is resolved with the list of split names,
175
- * or rejected if wrapper operation fails.
176
- * @todo this is a no-op method to be implemented
187
+ * Get list of feature flag names related to a given list of flag set names.
188
+ * The returned promise is resolved with the list of feature flag names per flag set,
189
+ * or rejected if the pipelined redis operation fails (e.g., timeout).
177
190
  */
178
- SplitsCacheInRedis.prototype.getNamesByFlagSets = function () {
179
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
180
- return new Promise(function (flagSets) { return new _Set([]); });
191
+ SplitsCacheInRedis.prototype.getNamesByFlagSets = function (flagSets) {
192
+ var _this = this;
193
+ return this.redis.pipeline(flagSets.map(function (flagSet) { return ['smembers', _this.keys.buildFlagSetKey(flagSet)]; })).exec()
194
+ .then(function (results) { return results.map(function (_a, index) {
195
+ var e = _a[0], value = _a[1];
196
+ if (e === null)
197
+ return value;
198
+ _this.log.error(LOG_PREFIX + ("Could not read result from get members of flag set " + flagSets[index] + " due to an error: " + e));
199
+ }); })
200
+ .then(function (namesByFlagSets) { return namesByFlagSets.map(function (namesByFlagSet) { return new _Set(namesByFlagSet); }); });
181
201
  };
182
202
  /**
183
203
  * Check traffic type existence.
@@ -194,24 +214,20 @@ var SplitsCacheInRedis = /** @class */ (function (_super) {
194
214
  return false; // if entry doesn't exist, means that TT doesn't exist
195
215
  ttCount = parseInt(ttCount, 10);
196
216
  if (!isFiniteNumber(ttCount) || ttCount < 0) {
197
- _this.log.info(LOG_PREFIX + ("Could not validate traffic type existance of " + trafficType + " due to data corruption of some sorts."));
217
+ _this.log.info(LOG_PREFIX + ("Could not validate traffic type existence of " + trafficType + " due to data corruption of some sorts."));
198
218
  return false;
199
219
  }
200
220
  return ttCount > 0;
201
221
  })
202
222
  .catch(function (e) {
203
- _this.log.error(LOG_PREFIX + ("Could not validate traffic type existance of " + trafficType + " due to an error: " + e + "."));
223
+ _this.log.error(LOG_PREFIX + ("Could not validate traffic type existence of " + trafficType + " due to an error: " + e + "."));
204
224
  // If there is an error, bypass the validation so the event can get tracked.
205
225
  return true;
206
226
  });
207
227
  };
208
- /**
209
- * Delete everything in the current database.
210
- *
211
- * @NOTE documentation says it never fails.
212
- */
228
+ // @TODO remove or implement. It is not being used.
213
229
  SplitsCacheInRedis.prototype.clear = function () {
214
- return this.redis.flushdb().then(function (status) { return status === 'OK'; });
230
+ return Promise.resolve();
215
231
  };
216
232
  /**
217
233
  * Fetches multiple splits definitions.
@@ -36,7 +36,7 @@ export function InRedisStorage(options) {
36
36
  telemetry.recordConfig();
37
37
  });
38
38
  return {
39
- splits: new SplitsCacheInRedis(log, keys, redisClient),
39
+ splits: new SplitsCacheInRedis(log, keys, redisClient, settings.sync.__splitFiltersValidation),
40
40
  segments: new SegmentsCacheInRedis(log, keys, redisClient),
41
41
  impressions: new ImpressionsCacheInRedis(log, keys.buildImpressionsKey(), redisClient, metadata),
42
42
  impressionCounts: impressionCountsCache,
@@ -1,8 +1,8 @@
1
- import { __extends } from "tslib";
1
+ import { __extends, __spreadArray } from "tslib";
2
2
  import { isFiniteNumber, isNaNNumber } from '../../utils/lang';
3
3
  import { LOG_PREFIX } from './constants';
4
4
  import { AbstractSplitsCacheAsync } from '../AbstractSplitsCacheAsync';
5
- import { _Set } from '../../utils/lang/sets';
5
+ import { _Set, returnDifference } from '../../utils/lang/sets';
6
6
  /**
7
7
  * ISplitsCacheAsync implementation for pluggable storages.
8
8
  */
@@ -14,11 +14,12 @@ var SplitsCachePluggable = /** @class */ (function (_super) {
14
14
  * @param keys Key builder.
15
15
  * @param wrapper Adapted wrapper storage.
16
16
  */
17
- function SplitsCachePluggable(log, keys, wrapper) {
17
+ function SplitsCachePluggable(log, keys, wrapper, splitFiltersValidation) {
18
18
  var _this = _super.call(this) || this;
19
19
  _this.log = log;
20
20
  _this.keys = keys;
21
21
  _this.wrapper = wrapper;
22
+ _this.flagSetsFilter = splitFiltersValidation ? splitFiltersValidation.groupedFilters.bySet : [];
22
23
  return _this;
23
24
  }
24
25
  SplitsCachePluggable.prototype._decrementCounts = function (split) {
@@ -33,6 +34,18 @@ var SplitsCachePluggable = /** @class */ (function (_super) {
33
34
  var ttKey = this.keys.buildTrafficTypeKey(split.trafficTypeName);
34
35
  return this.wrapper.incr(ttKey);
35
36
  };
37
+ SplitsCachePluggable.prototype._updateFlagSets = function (featureFlagName, flagSetsOfRemovedFlag, flagSetsOfAddedFlag) {
38
+ var _this = this;
39
+ var removeFromFlagSets = returnDifference(flagSetsOfRemovedFlag, flagSetsOfAddedFlag);
40
+ var addToFlagSets = returnDifference(flagSetsOfAddedFlag, flagSetsOfRemovedFlag);
41
+ if (this.flagSetsFilter.length > 0) {
42
+ addToFlagSets = addToFlagSets.filter(function (flagSet) {
43
+ return _this.flagSetsFilter.some(function (filterFlagSet) { return filterFlagSet === flagSet; });
44
+ });
45
+ }
46
+ var items = [featureFlagName];
47
+ return Promise.all(__spreadArray(__spreadArray([], removeFromFlagSets.map(function (flagSetName) { return _this.wrapper.removeItems(_this.keys.buildFlagSetKey(flagSetName), items); }), true), addToFlagSets.map(function (flagSetName) { return _this.wrapper.addItems(_this.keys.buildFlagSetKey(flagSetName), items); }), true));
48
+ };
36
49
  /**
37
50
  * Add a given split.
38
51
  * The returned promise is resolved when the operation success
@@ -60,7 +73,7 @@ var SplitsCachePluggable = /** @class */ (function (_super) {
60
73
  if (parsedPreviousSplit)
61
74
  return _this._decrementCounts(parsedPreviousSplit);
62
75
  });
63
- });
76
+ }).then(function () { return _this._updateFlagSets(name, parsedPreviousSplit && parsedPreviousSplit.sets, split.sets); });
64
77
  }).then(function () { return true; });
65
78
  };
66
79
  /**
@@ -81,8 +94,9 @@ var SplitsCachePluggable = /** @class */ (function (_super) {
81
94
  var _this = this;
82
95
  return this.getSplit(name).then(function (split) {
83
96
  if (split) {
84
- _this._decrementCounts(split);
97
+ return _this._decrementCounts(split).then(function () { return _this._updateFlagSets(name, split.sets); });
85
98
  }
99
+ }).then(function () {
86
100
  return _this.wrapper.del(_this.keys.buildSplitKey(name));
87
101
  });
88
102
  };
@@ -144,14 +158,16 @@ var SplitsCachePluggable = /** @class */ (function (_super) {
144
158
  return this.wrapper.getKeysByPrefix(this.keys.buildSplitKeyPrefix()).then(function (listOfKeys) { return listOfKeys.map(_this.keys.extractKey); });
145
159
  };
146
160
  /**
147
- * Get list of split names related to a given flag set names list.
148
- * The returned promise is resolved with the list of split names,
149
- * or rejected if wrapper operation fails.
150
- * @todo this is a no-op method to be implemented
151
- */
152
- SplitsCachePluggable.prototype.getNamesByFlagSets = function () {
153
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
154
- return new Promise(function (flagSets) { return new _Set([]); });
161
+ * Get list of feature flag names related to a given list of flag set names.
162
+ * The returned promise is resolved with the list of feature flag names per flag set.
163
+ * It never rejects (If there is a wrapper error for some flag set, an empty set is returned for it).
164
+ */
165
+ SplitsCachePluggable.prototype.getNamesByFlagSets = function (flagSets) {
166
+ var _this = this;
167
+ return Promise.all(flagSets.map(function (flagSet) {
168
+ var flagSetKey = _this.keys.buildFlagSetKey(flagSet);
169
+ return _this.wrapper.getItems(flagSetKey).catch(function () { return []; });
170
+ })).then(function (namesByFlagSets) { return namesByFlagSets.map(function (namesByFlagSet) { return new _Set(namesByFlagSet); }); });
155
171
  };
156
172
  /**
157
173
  * Check traffic type existence.
@@ -89,7 +89,7 @@ export function PluggableStorage(options) {
89
89
  return e; // Propagate error for shared clients
90
90
  });
91
91
  return {
92
- splits: new SplitsCachePluggable(log, keys, wrapper),
92
+ splits: new SplitsCachePluggable(log, keys, wrapper, settings.sync.__splitFiltersValidation),
93
93
  segments: new SegmentsCachePluggable(log, keys, wrapper),
94
94
  impressions: isPartialConsumer ? new ImpressionsCacheInMemory(impressionsQueueSize) : new ImpressionsCachePluggable(log, keys.buildImpressionsKey(), wrapper, metadata),
95
95
  impressionCounts: impressionCountsCache,
@@ -29,6 +29,20 @@ export var STORAGE_PLUGGABLE = 'PLUGGABLE';
29
29
  export var CONSENT_GRANTED = 'GRANTED'; // The user has granted consent for tracking events and impressions
30
30
  export var CONSENT_DECLINED = 'DECLINED'; // The user has declined consent for tracking events and impressions
31
31
  export var CONSENT_UNKNOWN = 'UNKNOWN'; // The user has neither granted nor declined consent for tracking events and impressions
32
+ // Client method names
33
+ export var GET_TREATMENT = 'getTreatment';
34
+ export var GET_TREATMENTS = 'getTreatments';
35
+ export var GET_TREATMENT_WITH_CONFIG = 'getTreatmentWithConfig';
36
+ export var GET_TREATMENTS_WITH_CONFIG = 'getTreatmentsWithConfig';
37
+ export var GET_TREATMENTS_BY_FLAG_SET = 'getTreatmentsByFlagSet';
38
+ export var GET_TREATMENTS_BY_FLAG_SETS = 'getTreatmentsByFlagSets';
39
+ export var GET_TREATMENTS_WITH_CONFIG_BY_FLAG_SET = 'getTreatmentsWithConfigByFlagSet';
40
+ export var GET_TREATMENTS_WITH_CONFIG_BY_FLAG_SETS = 'getTreatmentsWithConfigByFlagSets';
41
+ export var TRACK_FN_LABEL = 'track';
42
+ // Manager method names
43
+ export var SPLIT_FN_LABEL = 'split';
44
+ export var SPLITS_FN_LABEL = 'splits';
45
+ export var NAMES_FN_LABEL = 'names';
32
46
  // Telemetry
33
47
  export var QUEUED = 0;
34
48
  export var DROPPED = 1;
@@ -8,6 +8,6 @@ export { validateSplit } from './split';
8
8
  export { validateSplits } from './splits';
9
9
  export { validateTrafficType } from './trafficType';
10
10
  export { validateIfNotDestroyed, validateIfOperational } from './isOperational';
11
- export { validateSplitExistance } from './splitExistance';
12
- export { validateTrafficTypeExistance } from './trafficTypeExistance';
11
+ export { validateSplitExistence } from './splitExistence';
12
+ export { validateTrafficTypeExistence } from './trafficTypeExistence';
13
13
  export { validatePreloadedData } from './preloadedData';
@@ -4,7 +4,7 @@ import { WARN_NOT_EXISTENT_SPLIT } from '../../logger/constants';
4
4
  * This is defined here and in this format mostly because of the logger and the fact that it's considered a validation at product level.
5
5
  * But it's not going to run on the input validation layer. In any case, the most compeling reason to use it as we do is to avoid going to Redis and get a split twice.
6
6
  */
7
- export function validateSplitExistance(log, readinessManager, splitName, labelOrSplitObj, method) {
7
+ export function validateSplitExistence(log, readinessManager, splitName, labelOrSplitObj, method) {
8
8
  if (readinessManager.isReady()) { // Only if it's ready we validate this, otherwise it may just be that the SDK is not ready yet.
9
9
  if (labelOrSplitObj === SPLIT_NOT_FOUND || labelOrSplitObj == null) {
10
10
  log.warn(WARN_NOT_EXISTENT_SPLIT, [method, splitName]);
@@ -1,13 +1,13 @@
1
1
  import { thenable } from '../promise/thenable';
2
2
  import { LOCALHOST_MODE } from '../constants';
3
3
  import { WARN_NOT_EXISTENT_TT } from '../../logger/constants';
4
- function logTTExistanceWarning(log, maybeTT, method) {
4
+ function logTTExistenceWarning(log, maybeTT, method) {
5
5
  log.warn(WARN_NOT_EXISTENT_TT, [method, maybeTT]);
6
6
  }
7
7
  /**
8
8
  * Separated from the previous method since on some cases it'll be async.
9
9
  */
10
- export function validateTrafficTypeExistance(log, readinessManager, splitsCache, mode, maybeTT, method) {
10
+ export function validateTrafficTypeExistence(log, readinessManager, splitsCache, mode, maybeTT, method) {
11
11
  // If not ready or in localhost mode, we won't run the validation
12
12
  if (!readinessManager.isReady() || mode === LOCALHOST_MODE)
13
13
  return true;
@@ -15,13 +15,13 @@ export function validateTrafficTypeExistance(log, readinessManager, splitsCache,
15
15
  if (thenable(res)) {
16
16
  return res.then(function (isValid) {
17
17
  if (!isValid)
18
- logTTExistanceWarning(log, maybeTT, method);
18
+ logTTExistenceWarning(log, maybeTT, method);
19
19
  return isValid; // propagate result
20
20
  });
21
21
  }
22
22
  else {
23
23
  if (!res)
24
- logTTExistanceWarning(log, maybeTT, method);
24
+ logTTExistenceWarning(log, maybeTT, method);
25
25
  return res;
26
26
  }
27
27
  }
@@ -102,3 +102,12 @@ export function returnSetsUnion(set, set2) {
102
102
  });
103
103
  return result;
104
104
  }
105
+ export function returnDifference(list, list2) {
106
+ if (list === void 0) { list = []; }
107
+ if (list2 === void 0) { list2 = []; }
108
+ var result = new _Set(list);
109
+ list2.forEach(function (item) {
110
+ result.delete(item);
111
+ });
112
+ return setToArray(result);
113
+ }
@@ -176,7 +176,7 @@ export function settingsValidation(config, validationParams) {
176
176
  withDefaults.sync.enabled = true;
177
177
  }
178
178
  // validate the `splitFilters` settings and parse splits query
179
- var splitFiltersValidation = validateSplitFilters(log, withDefaults.sync.splitFilters);
179
+ var splitFiltersValidation = validateSplitFilters(log, withDefaults.sync.splitFilters, withDefaults.mode);
180
180
  withDefaults.sync.splitFilters = splitFiltersValidation.validFilters;
181
181
  withDefaults.sync.__splitFiltersValidation = splitFiltersValidation;
182
182
  // ensure a valid user consent value
@@ -1,5 +1,6 @@
1
+ import { CONSUMER_MODE, CONSUMER_PARTIAL_MODE } from '../constants';
1
2
  import { validateSplits } from '../inputValidation/splits';
2
- import { WARN_SPLITS_FILTER_EMPTY, WARN_SPLITS_FILTER_INVALID, SETTINGS_SPLITS_FILTER, LOG_PREFIX_SETTINGS, ERROR_SETS_FILTER_EXCLUSIVE, WARN_SPLITS_FILTER_LOWERCASE_SET, WARN_SPLITS_FILTER_INVALID_SET, WARN_FLAGSET_NOT_CONFIGURED } from '../../logger/constants';
3
+ import { WARN_SPLITS_FILTER_IGNORED, WARN_SPLITS_FILTER_EMPTY, WARN_SPLITS_FILTER_INVALID, SETTINGS_SPLITS_FILTER, LOG_PREFIX_SETTINGS, ERROR_SETS_FILTER_EXCLUSIVE, WARN_LOWERCASE_FLAGSET, WARN_INVALID_FLAGSET, WARN_FLAGSET_NOT_CONFIGURED } from '../../logger/constants';
3
4
  import { objectAssign } from '../lang/objectAssign';
4
5
  import { find, uniq } from '../lang';
5
6
  // Split filters metadata.
@@ -44,7 +45,7 @@ function validateSplitFilter(log, type, values, maxLength) {
44
45
  var result = validateSplits(log, values, LOG_PREFIX_SETTINGS, type + " filter", type + " filter value");
45
46
  if (result) {
46
47
  if (type === 'bySet') {
47
- result = sanitizeFlagSets(log, result);
48
+ result = sanitizeFlagSets(log, result, LOG_PREFIX_SETTINGS);
48
49
  }
49
50
  // check max length
50
51
  if (result.length > maxLength)
@@ -77,7 +78,7 @@ function queryStringBuilder(groupedFilters) {
77
78
  return queryParams.length > 0 ? '&' + queryParams.join('&') : null;
78
79
  }
79
80
  /**
80
- * Sanitizes set names list taking in account:
81
+ * Sanitizes set names list taking into account:
81
82
  * - It should be lowercase
82
83
  * - Must adhere the following regular expression /^[a-z0-9][_a-z0-9]{0,49}$/ that means
83
84
  * - must start with a letter or number
@@ -87,20 +88,21 @@ function queryStringBuilder(groupedFilters) {
87
88
  *
88
89
  * @param {ILogger} log
89
90
  * @param {string[]} flagSets
91
+ * @param {string} method
90
92
  * @returns sanitized list of set names
91
93
  */
92
- function sanitizeFlagSets(log, flagSets) {
94
+ function sanitizeFlagSets(log, flagSets, method) {
93
95
  var sanitizedSets = flagSets
94
96
  .map(function (flagSet) {
95
97
  if (CAPITAL_LETTERS_REGEX.test(flagSet)) {
96
- log.warn(WARN_SPLITS_FILTER_LOWERCASE_SET, [flagSet]);
98
+ log.warn(WARN_LOWERCASE_FLAGSET, [method, flagSet]);
97
99
  flagSet = flagSet.toLowerCase();
98
100
  }
99
101
  return flagSet;
100
102
  })
101
103
  .filter(function (flagSet) {
102
104
  if (!VALID_FLAGSET_REGEX.test(flagSet)) {
103
- log.warn(WARN_SPLITS_FILTER_INVALID_SET, [flagSet, VALID_FLAGSET_REGEX, flagSet]);
105
+ log.warn(WARN_INVALID_FLAGSET, [method, flagSet, VALID_FLAGSET_REGEX, flagSet]);
104
106
  return false;
105
107
  }
106
108
  if (typeof flagSet !== 'string')
@@ -117,6 +119,7 @@ function configuredFilter(validFilters, filterType) {
117
119
  *
118
120
  * @param {ILogger} log logger
119
121
  * @param {any} maybeSplitFilters split filters configuration param provided by the user
122
+ * @param {string} mode settings mode
120
123
  * @returns it returns an object with the following properties:
121
124
  * - `validFilters`: the validated `splitFilters` configuration object defined by the user.
122
125
  * - `queryString`: the parsed split filter query. it is null if all filters are invalid or all values in filters are invalid.
@@ -124,7 +127,7 @@ function configuredFilter(validFilters, filterType) {
124
127
  *
125
128
  * @throws Error if the some of the grouped list of values per filter exceeds the max allowed length
126
129
  */
127
- export function validateSplitFilters(log, maybeSplitFilters) {
130
+ export function validateSplitFilters(log, maybeSplitFilters, mode) {
128
131
  // Validation result schema
129
132
  var res = {
130
133
  validFilters: [],
@@ -134,6 +137,11 @@ export function validateSplitFilters(log, maybeSplitFilters) {
134
137
  // do nothing if `splitFilters` param is not a non-empty array or mode is not STANDALONE
135
138
  if (!maybeSplitFilters)
136
139
  return res;
140
+ // Warn depending on the mode
141
+ if (mode === CONSUMER_MODE || mode === CONSUMER_PARTIAL_MODE) {
142
+ log.warn(WARN_SPLITS_FILTER_IGNORED);
143
+ return res;
144
+ }
137
145
  // Check collection type
138
146
  if (!Array.isArray(maybeSplitFilters) || maybeSplitFilters.length === 0) {
139
147
  log.warn(WARN_SPLITS_FILTER_EMPTY);
@@ -168,9 +176,9 @@ export function validateSplitFilters(log, maybeSplitFilters) {
168
176
  log.debug(SETTINGS_SPLITS_FILTER, [res.queryString]);
169
177
  return res;
170
178
  }
171
- export function flagSetsAreValid(log, method, flagSets, flagSetsInConfig) {
179
+ export function validateFlagSets(log, method, flagSets, flagSetsInConfig) {
172
180
  var sets = validateSplits(log, flagSets, method, 'flag sets', 'flag set');
173
- var toReturn = sets ? sanitizeFlagSets(log, sets) : [];
181
+ var toReturn = sets ? sanitizeFlagSets(log, sets, method) : [];
174
182
  if (flagSetsInConfig.length > 0) {
175
183
  toReturn = toReturn.filter(function (flagSet) {
176
184
  if (flagSetsInConfig.indexOf(flagSet) > -1) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@splitsoftware/splitio-commons",
3
- "version": "1.10.1-rc.4",
3
+ "version": "1.12.0-rc.0",
4
4
  "description": "Split Javascript SDK common components",
5
5
  "main": "cjs/index.js",
6
6
  "module": "esm/index.js",
@@ -7,7 +7,8 @@ import { IStorageAsync, IStorageSync } from '../storages/types';
7
7
  import { IEvaluationResult } from './types';
8
8
  import { SplitIO } from '../types';
9
9
  import { ILogger } from '../logger/types';
10
- import { ISet, setToArray } from '../utils/lang/sets';
10
+ import { ISet, setToArray, returnSetsUnion, _Set } from '../utils/lang/sets';
11
+ import { WARN_FLAGSET_WITHOUT_FLAGS } from '../logger/constants';
11
12
 
12
13
  const treatmentException = {
13
14
  treatment: CONTROL,
@@ -94,8 +95,27 @@ export function evaluateFeaturesByFlagSets(
94
95
  flagSets: string[],
95
96
  attributes: SplitIO.Attributes | undefined,
96
97
  storage: IStorageSync | IStorageAsync,
97
- ): MaybeThenable<Record<string,IEvaluationResult>> {
98
- let storedFlagNames: MaybeThenable<ISet<string>>;
98
+ method: string,
99
+ ): MaybeThenable<Record<string, IEvaluationResult>> {
100
+ let storedFlagNames: MaybeThenable<ISet<string>[]>;
101
+
102
+ function evaluate(
103
+ featureFlagsByFlagSets: ISet<string>[],
104
+ ) {
105
+ let featureFlags = new _Set();
106
+ for (let i = 0; i < flagSets.length; i++) {
107
+ const featureFlagByFlagSet = featureFlagsByFlagSets[i];
108
+ if (featureFlagByFlagSet.size) {
109
+ featureFlags = returnSetsUnion(featureFlags, featureFlagByFlagSet);
110
+ } else {
111
+ log.warn(WARN_FLAGSET_WITHOUT_FLAGS, [method, flagSets[i]]);
112
+ }
113
+ }
114
+
115
+ return featureFlags.size ?
116
+ evaluateFeatures(log, key, setToArray(featureFlags), attributes, storage) :
117
+ {};
118
+ }
99
119
 
100
120
  // get features by flag sets
101
121
  try {
@@ -107,8 +127,11 @@ export function evaluateFeaturesByFlagSets(
107
127
 
108
128
  // evaluate related features
109
129
  return thenable(storedFlagNames) ?
110
- storedFlagNames.then((splitNames) => evaluateFeatures(log, key, setToArray(splitNames), attributes, storage)) :
111
- evaluateFeatures(log, key, setToArray(storedFlagNames), attributes, storage);
130
+ storedFlagNames.then((storedFlagNames) => evaluate(storedFlagNames))
131
+ .catch(() => {
132
+ return {};
133
+ }) :
134
+ evaluate(storedFlagNames);
112
135
  }
113
136
 
114
137
  function getEvaluation(
@@ -91,14 +91,16 @@ export const WARN_NOT_EXISTENT_SPLIT = 215;
91
91
  export const WARN_LOWERCASE_TRAFFIC_TYPE = 216;
92
92
  export const WARN_NOT_EXISTENT_TT = 217;
93
93
  export const WARN_INTEGRATION_INVALID = 218;
94
+ export const WARN_SPLITS_FILTER_IGNORED = 219;
94
95
  export const WARN_SPLITS_FILTER_INVALID = 220;
95
96
  export const WARN_SPLITS_FILTER_EMPTY = 221;
96
97
  export const WARN_SDK_KEY = 222;
97
98
  export const STREAMING_PARSING_MY_SEGMENTS_UPDATE_V2 = 223;
98
99
  export const STREAMING_PARSING_SPLIT_UPDATE = 224;
99
- export const WARN_SPLITS_FILTER_INVALID_SET = 225;
100
- export const WARN_SPLITS_FILTER_LOWERCASE_SET = 226;
100
+ export const WARN_INVALID_FLAGSET = 225;
101
+ export const WARN_LOWERCASE_FLAGSET = 226;
101
102
  export const WARN_FLAGSET_NOT_CONFIGURED = 227;
103
+ export const WARN_FLAGSET_WITHOUT_FLAGS = 228;
102
104
 
103
105
  export const ERROR_ENGINE_COMBINER_IFELSEIF = 300;
104
106
  export const ERROR_LOGLEVEL_INVALID = 301;
@@ -24,15 +24,17 @@ export const codesWarn: [number, string][] = codesError.concat([
24
24
  [c.WARN_NOT_EXISTENT_SPLIT, '%s: feature flag "%s" does not exist in this environment. Please double check what feature flags exist in the Split user interface.'],
25
25
  [c.WARN_LOWERCASE_TRAFFIC_TYPE, '%s: traffic_type_name should be all lowercase - converting string to lowercase.'],
26
26
  [c.WARN_NOT_EXISTENT_TT, '%s: traffic type "%s" does not have any corresponding feature flag in this environment, make sure you\'re tracking your events to a valid traffic type defined in the Split user interface.'],
27
- [c.WARN_FLAGSET_NOT_CONFIGURED, '%s: : you passed %s wich is not part of the configured FlagSetsFilter, ignoring Flag Set.'],
27
+ [c.WARN_FLAGSET_NOT_CONFIGURED, '%s: you passed %s which is not part of the configured FlagSetsFilter, ignoring Flag Set.'],
28
28
  // initialization / settings validation
29
- [c.WARN_INTEGRATION_INVALID, c.LOG_PREFIX_SETTINGS+': %s integration item(s) at settings is invalid. %s'],
30
- [c.WARN_SPLITS_FILTER_INVALID, c.LOG_PREFIX_SETTINGS+': feature flag filter at position %s is invalid. It must be an object with a valid filter type ("bySet", "byName" or "byPrefix") and a list of "values".'],
31
- [c.WARN_SPLITS_FILTER_EMPTY, c.LOG_PREFIX_SETTINGS+': feature flag filter configuration must be a non-empty array of filter objects.'],
32
- [c.WARN_SDK_KEY, c.LOG_PREFIX_SETTINGS+': You already have %s. We recommend keeping only one instance of the factory at all times (Singleton pattern) and reusing it throughout your application'],
29
+ [c.WARN_INTEGRATION_INVALID, c.LOG_PREFIX_SETTINGS + ': %s integration item(s) at settings is invalid. %s'],
30
+ [c.WARN_SPLITS_FILTER_IGNORED, c.LOG_PREFIX_SETTINGS + ': feature flag filters are not applicable for Consumer modes where the SDK does not keep rollout data in sync. Filters were discarded'],
31
+ [c.WARN_SPLITS_FILTER_INVALID, c.LOG_PREFIX_SETTINGS + ': feature flag filter at position %s is invalid. It must be an object with a valid filter type ("bySet", "byName" or "byPrefix") and a list of "values".'],
32
+ [c.WARN_SPLITS_FILTER_EMPTY, c.LOG_PREFIX_SETTINGS + ': feature flag filter configuration must be a non-empty array of filter objects.'],
33
+ [c.WARN_SDK_KEY, c.LOG_PREFIX_SETTINGS + ': You already have %s. We recommend keeping only one instance of the factory at all times (Singleton pattern) and reusing it throughout your application'],
33
34
 
34
35
  [c.STREAMING_PARSING_MY_SEGMENTS_UPDATE_V2, c.LOG_PREFIX_SYNC_STREAMING + 'Fetching MySegments due to an error processing %s notification: %s'],
35
36
  [c.STREAMING_PARSING_SPLIT_UPDATE, c.LOG_PREFIX_SYNC_STREAMING + 'Fetching SplitChanges due to an error processing SPLIT_UPDATE notification: %s'],
36
- [c.WARN_SPLITS_FILTER_INVALID_SET, c.LOG_PREFIX_SETTINGS+': you passed %s, flag set must adhere to the regular expressions %s. This means a flag set must start with a letter or number, be in lowercase, alphanumeric and have a max length of 50 characters. %s was discarded.'],
37
- [c.WARN_SPLITS_FILTER_LOWERCASE_SET, c.LOG_PREFIX_SETTINGS+': flag set %s should be all lowercase - converting string to lowercase.'],
37
+ [c.WARN_INVALID_FLAGSET, '%s: you passed %s, flag set must adhere to the regular expressions %s. This means a flag set must start with a letter or number, be in lowercase, alphanumeric and have a max length of 50 characters. %s was discarded.'],
38
+ [c.WARN_LOWERCASE_FLAGSET, '%s: flag set %s should be all lowercase - converting string to lowercase.'],
39
+ [c.WARN_FLAGSET_WITHOUT_FLAGS, '%s: you passed %s flag set that does not contain cached feature flag names. Please double check what flag sets are in use in the Split user interface.'],
38
40
  ]);