flagsmith-nodejs 3.0.0 → 3.0.1

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 (62) hide show
  1. package/.github/workflows/publish.yml +1 -1
  2. package/build/flagsmith-engine/environments/integrations/models.d.ts +4 -0
  3. package/build/flagsmith-engine/environments/integrations/models.js +11 -0
  4. package/build/flagsmith-engine/environments/models.d.ts +25 -0
  5. package/build/flagsmith-engine/environments/models.js +29 -0
  6. package/build/flagsmith-engine/environments/util.d.ts +3 -0
  7. package/build/flagsmith-engine/environments/util.js +21 -0
  8. package/build/flagsmith-engine/features/constants.d.ts +4 -0
  9. package/build/flagsmith-engine/features/constants.js +7 -0
  10. package/build/flagsmith-engine/features/models.d.ts +37 -0
  11. package/build/flagsmith-engine/features/models.js +122 -0
  12. package/build/flagsmith-engine/features/util.d.ts +4 -0
  13. package/build/flagsmith-engine/features/util.js +27 -0
  14. package/build/flagsmith-engine/identities/models.d.ts +15 -0
  15. package/build/flagsmith-engine/identities/models.js +113 -0
  16. package/build/flagsmith-engine/identities/traits/models.d.ts +5 -0
  17. package/build/flagsmith-engine/identities/traits/models.js +11 -0
  18. package/build/flagsmith-engine/identities/util.d.ts +4 -0
  19. package/build/flagsmith-engine/identities/util.js +46 -0
  20. package/build/flagsmith-engine/index.d.ts +15 -0
  21. package/build/flagsmith-engine/index.js +129 -0
  22. package/build/flagsmith-engine/organisations/models.d.ts +9 -0
  23. package/build/flagsmith-engine/organisations/models.js +21 -0
  24. package/build/flagsmith-engine/organisations/util.d.ts +2 -0
  25. package/build/flagsmith-engine/organisations/util.js +8 -0
  26. package/build/flagsmith-engine/projects/models.d.ts +10 -0
  27. package/build/flagsmith-engine/projects/models.js +14 -0
  28. package/build/flagsmith-engine/projects/util.d.ts +2 -0
  29. package/build/flagsmith-engine/projects/util.js +15 -0
  30. package/build/flagsmith-engine/segments/constants.d.ts +34 -0
  31. package/build/flagsmith-engine/segments/constants.js +39 -0
  32. package/build/flagsmith-engine/segments/evaluators.d.ts +7 -0
  33. package/build/flagsmith-engine/segments/evaluators.js +45 -0
  34. package/build/flagsmith-engine/segments/models.d.ts +37 -0
  35. package/build/flagsmith-engine/segments/models.js +144 -0
  36. package/build/flagsmith-engine/segments/util.d.ts +6 -0
  37. package/build/flagsmith-engine/segments/util.js +33 -0
  38. package/build/flagsmith-engine/utils/collections.d.ts +3 -0
  39. package/build/flagsmith-engine/utils/collections.js +26 -0
  40. package/build/flagsmith-engine/utils/errors.d.ts +2 -0
  41. package/build/flagsmith-engine/utils/errors.js +26 -0
  42. package/build/flagsmith-engine/utils/hashing/index.d.ts +9 -0
  43. package/build/flagsmith-engine/utils/hashing/index.js +60 -0
  44. package/build/flagsmith-engine/utils/index.d.ts +1 -0
  45. package/build/flagsmith-engine/utils/index.js +17 -0
  46. package/build/index.d.ts +2 -0
  47. package/build/index.js +24 -0
  48. package/build/sdk/analytics.d.ts +31 -0
  49. package/build/sdk/analytics.js +116 -0
  50. package/build/sdk/errors.d.ts +4 -0
  51. package/build/sdk/errors.js +34 -0
  52. package/build/sdk/index.d.ts +120 -0
  53. package/build/sdk/index.js +527 -0
  54. package/build/sdk/models.d.ts +55 -0
  55. package/build/sdk/models.js +149 -0
  56. package/build/sdk/polling_manager.d.ts +9 -0
  57. package/build/sdk/polling_manager.js +72 -0
  58. package/build/sdk/types.d.ts +27 -0
  59. package/build/sdk/types.js +2 -0
  60. package/build/sdk/utils.d.ts +12 -0
  61. package/build/sdk/utils.js +99 -0
  62. package/package.json +1 -1
@@ -0,0 +1,527 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __values = (this && this.__values) || function(o) {
39
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
40
+ if (m) return m.call(o);
41
+ if (o && typeof o.length === "number") return {
42
+ next: function () {
43
+ if (o && i >= o.length) o = void 0;
44
+ return { value: o && o[i++], done: !o };
45
+ }
46
+ };
47
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
+ };
49
+ var __read = (this && this.__read) || function (o, n) {
50
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
51
+ if (!m) return o;
52
+ var i = m.call(o), r, ar = [], e;
53
+ try {
54
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
+ }
56
+ catch (error) { e = { error: error }; }
57
+ finally {
58
+ try {
59
+ if (r && !r.done && (m = i["return"])) m.call(i);
60
+ }
61
+ finally { if (e) throw e.error; }
62
+ }
63
+ return ar;
64
+ };
65
+ var __importDefault = (this && this.__importDefault) || function (mod) {
66
+ return (mod && mod.__esModule) ? mod : { "default": mod };
67
+ };
68
+ Object.defineProperty(exports, "__esModule", { value: true });
69
+ exports.Flagsmith = exports.EnvironmentDataPollingManager = exports.Flags = exports.DefaultFlag = exports.FlagsmithClientError = exports.FlagsmithAPIError = exports.AnalyticsProcessor = void 0;
70
+ var flagsmith_engine_1 = require("../flagsmith-engine");
71
+ var util_1 = require("../flagsmith-engine/environments/util");
72
+ var models_1 = require("../flagsmith-engine/identities/models");
73
+ var models_2 = require("../flagsmith-engine/identities/traits/models");
74
+ var analytics_1 = require("./analytics");
75
+ var errors_1 = require("./errors");
76
+ var models_3 = require("./models");
77
+ var polling_manager_1 = require("./polling_manager");
78
+ var utils_1 = require("./utils");
79
+ var evaluators_1 = require("../flagsmith-engine/segments/evaluators");
80
+ var pino_1 = __importDefault(require("pino"));
81
+ var analytics_2 = require("./analytics");
82
+ Object.defineProperty(exports, "AnalyticsProcessor", { enumerable: true, get: function () { return analytics_2.AnalyticsProcessor; } });
83
+ var errors_2 = require("./errors");
84
+ Object.defineProperty(exports, "FlagsmithAPIError", { enumerable: true, get: function () { return errors_2.FlagsmithAPIError; } });
85
+ Object.defineProperty(exports, "FlagsmithClientError", { enumerable: true, get: function () { return errors_2.FlagsmithClientError; } });
86
+ var models_4 = require("./models");
87
+ Object.defineProperty(exports, "DefaultFlag", { enumerable: true, get: function () { return models_4.DefaultFlag; } });
88
+ Object.defineProperty(exports, "Flags", { enumerable: true, get: function () { return models_4.Flags; } });
89
+ var polling_manager_2 = require("./polling_manager");
90
+ Object.defineProperty(exports, "EnvironmentDataPollingManager", { enumerable: true, get: function () { return polling_manager_2.EnvironmentDataPollingManager; } });
91
+ var DEFAULT_API_URL = 'https://edge.api.flagsmith.com/api/v1/';
92
+ var Flagsmith = /** @class */ (function () {
93
+ /**
94
+ * A Flagsmith client.
95
+ *
96
+ * Provides an interface for interacting with the Flagsmith http API.
97
+ * Basic Usage::
98
+ *
99
+ * import flagsmith from Flagsmith
100
+ * const flagsmith = new Flagsmith({environmentKey: '<your API key>'});
101
+ * const environmentFlags = flagsmith.getEnvironmentFlags();
102
+ * const featureEnabled = environmentFlags.isFeatureEnabled('foo');
103
+ * const identityFlags = flagsmith.getIdentityFlags('identifier', {'foo': 'bar'});
104
+ * const featureEnabledForIdentity = identityFlags.isFeatureEnabled("foo")
105
+ *
106
+ * @param {string} data.environmentKey: The environment key obtained from Flagsmith interface
107
+ @param {string} data.apiUrl: Override the URL of the Flagsmith API to communicate with
108
+ @param data.customHeaders: Additional headers to add to requests made to the
109
+ Flagsmith API
110
+ @param {number} data.requestTimeoutSeconds: Number of seconds to wait for a request to
111
+ complete before terminating the request
112
+ @param {boolean} data.enableLocalEvaluation: Enables local evaluation of flags
113
+ @param {number} data.environmentRefreshIntervalSeconds: If using local evaluation,
114
+ specify the interval period between refreshes of local environment data
115
+ @param {number} data.retries: a urllib3.Retry object to use on all http requests to the
116
+ Flagsmith API
117
+ @param {boolean} data.enableAnalytics: if enabled, sends additional requests to the Flagsmith
118
+ API to power flag analytics charts
119
+ @param data.defaultFlagHandler: callable which will be used in the case where
120
+ flags cannot be retrieved from the API or a non existent feature is
121
+ requested
122
+ @param data.logger: an instance of the pino Logger class to use for logging
123
+ */
124
+ function Flagsmith(data) {
125
+ this.apiUrl = DEFAULT_API_URL;
126
+ this.enableLocalEvaluation = false;
127
+ this.environmentRefreshIntervalSeconds = 60;
128
+ this.enableAnalytics = false;
129
+ this.agent = data.agent;
130
+ this.environmentKey = data.environmentKey;
131
+ this.apiUrl = data.apiUrl || this.apiUrl;
132
+ this.customHeaders = data.customHeaders;
133
+ this.requestTimeoutSeconds = data.requestTimeoutSeconds;
134
+ this.requestTimeoutMs = data.requestTimeoutSeconds ? data.requestTimeoutSeconds * 1000 : undefined;
135
+ this.enableLocalEvaluation = data.enableLocalEvaluation;
136
+ this.environmentRefreshIntervalSeconds =
137
+ data.environmentRefreshIntervalSeconds || this.environmentRefreshIntervalSeconds;
138
+ this.retries = data.retries;
139
+ this.enableAnalytics = data.enableAnalytics || false;
140
+ this.defaultFlagHandler = data.defaultFlagHandler;
141
+ this.environmentFlagsUrl = "".concat(this.apiUrl, "flags/");
142
+ this.identitiesUrl = "".concat(this.apiUrl, "identities/");
143
+ this.environmentUrl = "".concat(this.apiUrl, "environment-document/");
144
+ this.onEnvironmentChange = data.onEnvironmentChange;
145
+ this.logger = data.logger || (0, pino_1.default)();
146
+ if (!!data.cache) {
147
+ var missingMethods = ['has', 'get', 'set'].filter(function (method) { return data.cache && !data.cache[method]; });
148
+ if (missingMethods.length > 0) {
149
+ throw new Error("Please implement the following methods in your cache: ".concat(missingMethods.join(', ')));
150
+ }
151
+ this.cache = data.cache;
152
+ }
153
+ if (this.enableLocalEvaluation) {
154
+ if (!this.environmentKey.startsWith('ser.')) {
155
+ console.error('In order to use local evaluation, please generate a server key in the environment settings page.');
156
+ }
157
+ this.environmentDataPollingManager = new polling_manager_1.EnvironmentDataPollingManager(this, this.environmentRefreshIntervalSeconds);
158
+ this.environmentDataPollingManager.start();
159
+ this.updateEnvironment();
160
+ }
161
+ this.analyticsProcessor = data.enableAnalytics
162
+ ? new analytics_1.AnalyticsProcessor({
163
+ environmentKey: this.environmentKey,
164
+ baseApiUrl: this.apiUrl,
165
+ requestTimeoutMs: this.requestTimeoutMs,
166
+ logger: this.logger
167
+ })
168
+ : undefined;
169
+ }
170
+ /**
171
+ * Get all the default for flags for the current environment.
172
+ *
173
+ * @returns Flags object holding all the flags for the current environment.
174
+ */
175
+ Flagsmith.prototype.getEnvironmentFlags = function () {
176
+ return __awaiter(this, void 0, void 0, function () {
177
+ var cachedItem, _a;
178
+ var _this = this;
179
+ return __generator(this, function (_b) {
180
+ switch (_b.label) {
181
+ case 0:
182
+ _a = !!this.cache;
183
+ if (!_a) return [3 /*break*/, 2];
184
+ return [4 /*yield*/, this.cache.get("flags")];
185
+ case 1:
186
+ _a = (_b.sent());
187
+ _b.label = 2;
188
+ case 2:
189
+ cachedItem = _a;
190
+ if (!!cachedItem) {
191
+ return [2 /*return*/, cachedItem];
192
+ }
193
+ if (this.enableLocalEvaluation) {
194
+ return [2 /*return*/, new Promise(function (resolve, reject) {
195
+ return _this.environmentPromise.then(function () {
196
+ resolve(_this.getEnvironmentFlagsFromDocument());
197
+ }).catch(function (e) { return reject(e); });
198
+ })];
199
+ }
200
+ if (this.environment) {
201
+ return [2 /*return*/, this.getEnvironmentFlagsFromDocument()];
202
+ }
203
+ return [2 /*return*/, this.getEnvironmentFlagsFromApi()];
204
+ }
205
+ });
206
+ });
207
+ };
208
+ /**
209
+ * Get all the flags for the current environment for a given identity. Will also
210
+ upsert all traits to the Flagsmith API for future evaluations. Providing a
211
+ trait with a value of None will remove the trait from the identity if it exists.
212
+ *
213
+ * @param {string} identifier a unique identifier for the identity in the current
214
+ environment, e.g. email address, username, uuid
215
+ * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
216
+ Flagsmith, e.g. {"num_orders": 10}
217
+ * @returns Flags object holding all the flags for the given identity.
218
+ */
219
+ Flagsmith.prototype.getIdentityFlags = function (identifier, traits) {
220
+ return __awaiter(this, void 0, void 0, function () {
221
+ var cachedItem, _a;
222
+ var _this = this;
223
+ return __generator(this, function (_b) {
224
+ switch (_b.label) {
225
+ case 0:
226
+ if (!identifier) {
227
+ throw new Error("`identifier` argument is missing or invalid.");
228
+ }
229
+ _a = !!this.cache;
230
+ if (!_a) return [3 /*break*/, 2];
231
+ return [4 /*yield*/, this.cache.get("flags-".concat(identifier))];
232
+ case 1:
233
+ _a = (_b.sent());
234
+ _b.label = 2;
235
+ case 2:
236
+ cachedItem = _a;
237
+ if (!!cachedItem) {
238
+ return [2 /*return*/, cachedItem];
239
+ }
240
+ traits = traits || {};
241
+ if (this.enableLocalEvaluation) {
242
+ return [2 /*return*/, new Promise(function (resolve, reject) {
243
+ return _this.environmentPromise.then(function () {
244
+ resolve(_this.getIdentityFlagsFromDocument(identifier, traits || {}));
245
+ }).catch(function (e) { return reject(e); });
246
+ })];
247
+ }
248
+ return [2 /*return*/, this.getIdentityFlagsFromApi(identifier, traits)];
249
+ }
250
+ });
251
+ });
252
+ };
253
+ /**
254
+ * Get the segments for the current environment for a given identity. Will also
255
+ upsert all traits to the Flagsmith API for future evaluations. Providing a
256
+ trait with a value of None will remove the trait from the identity if it exists.
257
+ *
258
+ * @param {string} identifier a unique identifier for the identity in the current
259
+ environment, e.g. email address, username, uuid
260
+ * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
261
+ Flagsmith, e.g. {"num_orders": 10}
262
+ * @returns Segments that the given identity belongs to.
263
+ */
264
+ Flagsmith.prototype.getIdentitySegments = function (identifier, traits) {
265
+ var _this = this;
266
+ if (!identifier) {
267
+ throw new Error("`identifier` argument is missing or invalid.");
268
+ }
269
+ traits = traits || {};
270
+ if (this.enableLocalEvaluation) {
271
+ return new Promise(function (resolve, reject) {
272
+ return _this.environmentPromise.then(function () {
273
+ var identityModel = _this.buildIdentityModel(identifier, Object.keys(traits || {}).map(function (key) { return ({
274
+ key: key,
275
+ value: traits === null || traits === void 0 ? void 0 : traits[key]
276
+ }); }));
277
+ var segments = (0, evaluators_1.getIdentitySegments)(_this.environment, identityModel);
278
+ return resolve(segments);
279
+ }).catch(function (e) { return reject(e); });
280
+ });
281
+ }
282
+ console.error('This function is only permitted with local evaluation.');
283
+ return Promise.resolve([]);
284
+ };
285
+ /**
286
+ * Updates the environment state for local flag evaluation.
287
+ * Sets a local promise to prevent race conditions in getIdentityFlags / getIdentitySegments.
288
+ * You only need to call this if you wish to bypass environmentRefreshIntervalSeconds.
289
+ */
290
+ Flagsmith.prototype.updateEnvironment = function () {
291
+ return __awaiter(this, void 0, void 0, function () {
292
+ var request, _a, e_1;
293
+ var _this = this;
294
+ return __generator(this, function (_b) {
295
+ switch (_b.label) {
296
+ case 0:
297
+ _b.trys.push([0, 5, , 6]);
298
+ request = this.getEnvironmentFromApi();
299
+ if (!!this.environmentPromise) return [3 /*break*/, 2];
300
+ this.environmentPromise = request.then(function (res) {
301
+ _this.environment = res;
302
+ });
303
+ return [4 /*yield*/, this.environmentPromise];
304
+ case 1:
305
+ _b.sent();
306
+ return [3 /*break*/, 4];
307
+ case 2:
308
+ _a = this;
309
+ return [4 /*yield*/, request];
310
+ case 3:
311
+ _a.environment = _b.sent();
312
+ _b.label = 4;
313
+ case 4:
314
+ if (this.onEnvironmentChange) {
315
+ this.onEnvironmentChange(null, this.environment);
316
+ }
317
+ return [3 /*break*/, 6];
318
+ case 5:
319
+ e_1 = _b.sent();
320
+ if (this.onEnvironmentChange) {
321
+ this.onEnvironmentChange(e_1, this.environment);
322
+ }
323
+ return [3 /*break*/, 6];
324
+ case 6: return [2 /*return*/];
325
+ }
326
+ });
327
+ });
328
+ };
329
+ Flagsmith.prototype.close = function () {
330
+ var _a;
331
+ return __awaiter(this, void 0, void 0, function () {
332
+ return __generator(this, function (_b) {
333
+ (_a = this.environmentDataPollingManager) === null || _a === void 0 ? void 0 : _a.stop();
334
+ return [2 /*return*/];
335
+ });
336
+ });
337
+ };
338
+ Flagsmith.prototype.getJSONResponse = function (url, method, body) {
339
+ return __awaiter(this, void 0, void 0, function () {
340
+ var headers, _a, _b, _c, k, v, data;
341
+ var e_2, _d;
342
+ return __generator(this, function (_e) {
343
+ switch (_e.label) {
344
+ case 0:
345
+ headers = { 'Content-Type': 'application/json' };
346
+ if (this.environmentKey) {
347
+ headers['X-Environment-Key'] = this.environmentKey;
348
+ }
349
+ if (this.customHeaders) {
350
+ try {
351
+ for (_a = __values(Object.entries(this.customHeaders)), _b = _a.next(); !_b.done; _b = _a.next()) {
352
+ _c = __read(_b.value, 2), k = _c[0], v = _c[1];
353
+ headers[k] = v;
354
+ }
355
+ }
356
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
357
+ finally {
358
+ try {
359
+ if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
360
+ }
361
+ finally { if (e_2) throw e_2.error; }
362
+ }
363
+ }
364
+ return [4 /*yield*/, (0, utils_1.retryFetch)(url, {
365
+ agent: this.agent,
366
+ method: method,
367
+ body: JSON.stringify(body),
368
+ headers: headers
369
+ }, this.retries, this.requestTimeoutMs || undefined)];
370
+ case 1:
371
+ data = _e.sent();
372
+ if (data.status !== 200) {
373
+ throw new errors_1.FlagsmithAPIError("Invalid request made to Flagsmith API. Response status code: ".concat(data.status));
374
+ }
375
+ return [2 /*return*/, data.json()];
376
+ }
377
+ });
378
+ });
379
+ };
380
+ Flagsmith.prototype.getEnvironmentFromApi = function () {
381
+ return __awaiter(this, void 0, void 0, function () {
382
+ var environment_data;
383
+ return __generator(this, function (_a) {
384
+ switch (_a.label) {
385
+ case 0: return [4 /*yield*/, this.getJSONResponse(this.environmentUrl, 'GET')];
386
+ case 1:
387
+ environment_data = _a.sent();
388
+ return [2 /*return*/, (0, util_1.buildEnvironmentModel)(environment_data)];
389
+ }
390
+ });
391
+ });
392
+ };
393
+ Flagsmith.prototype.getEnvironmentFlagsFromDocument = function () {
394
+ return __awaiter(this, void 0, void 0, function () {
395
+ var flags;
396
+ return __generator(this, function (_a) {
397
+ switch (_a.label) {
398
+ case 0:
399
+ flags = models_3.Flags.fromFeatureStateModels({
400
+ featureStates: (0, flagsmith_engine_1.getEnvironmentFeatureStates)(this.environment),
401
+ analyticsProcessor: this.analyticsProcessor,
402
+ defaultFlagHandler: this.defaultFlagHandler
403
+ });
404
+ if (!!!this.cache) return [3 /*break*/, 2];
405
+ // @ts-ignore node-cache types are incorrect, ttl should be optional
406
+ return [4 /*yield*/, this.cache.set('flags', flags)];
407
+ case 1:
408
+ // @ts-ignore node-cache types are incorrect, ttl should be optional
409
+ _a.sent();
410
+ _a.label = 2;
411
+ case 2: return [2 /*return*/, flags];
412
+ }
413
+ });
414
+ });
415
+ };
416
+ Flagsmith.prototype.getIdentityFlagsFromDocument = function (identifier, traits) {
417
+ return __awaiter(this, void 0, void 0, function () {
418
+ var identityModel, featureStates, flags;
419
+ return __generator(this, function (_a) {
420
+ switch (_a.label) {
421
+ case 0:
422
+ identityModel = this.buildIdentityModel(identifier, Object.keys(traits).map(function (key) { return ({
423
+ key: key,
424
+ value: traits[key]
425
+ }); }));
426
+ featureStates = (0, flagsmith_engine_1.getIdentityFeatureStates)(this.environment, identityModel);
427
+ flags = models_3.Flags.fromFeatureStateModels({
428
+ featureStates: featureStates,
429
+ analyticsProcessor: this.analyticsProcessor,
430
+ defaultFlagHandler: this.defaultFlagHandler,
431
+ identityID: identityModel.djangoID || identityModel.compositeKey
432
+ });
433
+ if (!!!this.cache) return [3 /*break*/, 2];
434
+ // @ts-ignore node-cache types are incorrect, ttl should be optional
435
+ return [4 /*yield*/, this.cache.set("flags-".concat(identifier), flags)];
436
+ case 1:
437
+ // @ts-ignore node-cache types are incorrect, ttl should be optional
438
+ _a.sent();
439
+ _a.label = 2;
440
+ case 2: return [2 /*return*/, flags];
441
+ }
442
+ });
443
+ });
444
+ };
445
+ Flagsmith.prototype.getEnvironmentFlagsFromApi = function () {
446
+ return __awaiter(this, void 0, void 0, function () {
447
+ var apiFlags, flags, e_3;
448
+ return __generator(this, function (_a) {
449
+ switch (_a.label) {
450
+ case 0:
451
+ _a.trys.push([0, 4, , 5]);
452
+ return [4 /*yield*/, this.getJSONResponse(this.environmentFlagsUrl, 'GET')];
453
+ case 1:
454
+ apiFlags = _a.sent();
455
+ flags = models_3.Flags.fromAPIFlags({
456
+ apiFlags: apiFlags,
457
+ analyticsProcessor: this.analyticsProcessor,
458
+ defaultFlagHandler: this.defaultFlagHandler
459
+ });
460
+ if (!!!this.cache) return [3 /*break*/, 3];
461
+ // @ts-ignore node-cache types are incorrect, ttl should be optional
462
+ return [4 /*yield*/, this.cache.set('flags', flags)];
463
+ case 2:
464
+ // @ts-ignore node-cache types are incorrect, ttl should be optional
465
+ _a.sent();
466
+ _a.label = 3;
467
+ case 3: return [2 /*return*/, flags];
468
+ case 4:
469
+ e_3 = _a.sent();
470
+ if (this.defaultFlagHandler) {
471
+ return [2 /*return*/, new models_3.Flags({
472
+ flags: {},
473
+ defaultFlagHandler: this.defaultFlagHandler
474
+ })];
475
+ }
476
+ throw e_3;
477
+ case 5: return [2 /*return*/];
478
+ }
479
+ });
480
+ });
481
+ };
482
+ Flagsmith.prototype.getIdentityFlagsFromApi = function (identifier, traits) {
483
+ return __awaiter(this, void 0, void 0, function () {
484
+ var data, jsonResponse, flags, e_4;
485
+ return __generator(this, function (_a) {
486
+ switch (_a.label) {
487
+ case 0:
488
+ _a.trys.push([0, 4, , 5]);
489
+ data = (0, utils_1.generateIdentitiesData)(identifier, traits);
490
+ return [4 /*yield*/, this.getJSONResponse(this.identitiesUrl, 'POST', data)];
491
+ case 1:
492
+ jsonResponse = _a.sent();
493
+ flags = models_3.Flags.fromAPIFlags({
494
+ apiFlags: jsonResponse['flags'],
495
+ analyticsProcessor: this.analyticsProcessor,
496
+ defaultFlagHandler: this.defaultFlagHandler
497
+ });
498
+ if (!!!this.cache) return [3 /*break*/, 3];
499
+ // @ts-ignore node-cache types are incorrect, ttl should be optional
500
+ return [4 /*yield*/, this.cache.set("flags-".concat(identifier), flags)];
501
+ case 2:
502
+ // @ts-ignore node-cache types are incorrect, ttl should be optional
503
+ _a.sent();
504
+ _a.label = 3;
505
+ case 3: return [2 /*return*/, flags];
506
+ case 4:
507
+ e_4 = _a.sent();
508
+ if (this.defaultFlagHandler) {
509
+ return [2 /*return*/, new models_3.Flags({
510
+ flags: {},
511
+ defaultFlagHandler: this.defaultFlagHandler
512
+ })];
513
+ }
514
+ throw e_4;
515
+ case 5: return [2 /*return*/];
516
+ }
517
+ });
518
+ });
519
+ };
520
+ Flagsmith.prototype.buildIdentityModel = function (identifier, traits) {
521
+ var traitModels = traits.map(function (trait) { return new models_2.TraitModel(trait.key, trait.value); });
522
+ return new models_1.IdentityModel('0', traitModels, [], this.environment.apiKey, identifier);
523
+ };
524
+ return Flagsmith;
525
+ }());
526
+ exports.Flagsmith = Flagsmith;
527
+ exports.default = Flagsmith;
@@ -0,0 +1,55 @@
1
+ import { FeatureStateModel } from '../flagsmith-engine/features/models';
2
+ import { AnalyticsProcessor } from './analytics';
3
+ export declare class BaseFlag {
4
+ enabled: boolean;
5
+ value: string | number | boolean | undefined;
6
+ isDefault: boolean;
7
+ constructor(value: string | number | boolean | undefined, enabled: boolean, isDefault: boolean);
8
+ }
9
+ export declare class DefaultFlag extends BaseFlag {
10
+ constructor(value: string | number | boolean | undefined, enabled: boolean);
11
+ }
12
+ export declare class Flag extends BaseFlag {
13
+ featureId: number;
14
+ featureName: string;
15
+ constructor(params: {
16
+ value: string | number | boolean | undefined;
17
+ enabled: boolean;
18
+ isDefault?: boolean;
19
+ featureId: number;
20
+ featureName: string;
21
+ });
22
+ static fromFeatureStateModel(fsm: FeatureStateModel, identityId: number | string | undefined): Flag;
23
+ static fromAPIFlag(flagData: any): Flag;
24
+ }
25
+ export declare class Flags {
26
+ flags: {
27
+ [key: string]: Flag;
28
+ };
29
+ defaultFlagHandler?: (featureName: string) => DefaultFlag;
30
+ analyticsProcessor?: AnalyticsProcessor;
31
+ constructor(data: {
32
+ flags: {
33
+ [key: string]: Flag;
34
+ };
35
+ defaultFlagHandler?: (v: string) => DefaultFlag;
36
+ analyticsProcessor?: AnalyticsProcessor;
37
+ });
38
+ static fromFeatureStateModels(data: {
39
+ featureStates: FeatureStateModel[];
40
+ analyticsProcessor?: AnalyticsProcessor;
41
+ defaultFlagHandler?: (f: string) => DefaultFlag;
42
+ identityID?: string | number;
43
+ }): Flags;
44
+ static fromAPIFlags(data: {
45
+ apiFlags: {
46
+ [key: string]: any;
47
+ }[];
48
+ analyticsProcessor?: AnalyticsProcessor;
49
+ defaultFlagHandler?: (v: string) => DefaultFlag;
50
+ }): Flags;
51
+ allFlags(): Flag[];
52
+ getFlag(featureName: string): BaseFlag;
53
+ getFeatureValue(featureName: string): any;
54
+ isFeatureEnabled(featureName: string): boolean;
55
+ }