flagsmith-nodejs 2.0.0-beta.6 → 2.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 (94) hide show
  1. package/.github/workflows/pull_request.yaml +37 -29
  2. package/README.md +7 -0
  3. package/example/server/api/index.js +1 -1
  4. package/flagsmith-engine/features/models.ts +28 -6
  5. package/flagsmith-engine/features/util.ts +9 -0
  6. package/flagsmith-engine/identities/models.ts +1 -1
  7. package/flagsmith-engine/index.ts +7 -5
  8. package/flagsmith-engine/organisations/models.ts +1 -1
  9. package/flagsmith-engine/segments/models.ts +21 -4
  10. package/flagsmith-engine/segments/util.ts +8 -0
  11. package/flagsmith-engine/utils/collections.ts +1 -12
  12. package/flagsmith-engine/utils/hashing/index.ts +5 -2
  13. package/flagsmith-engine/utils/index.ts +6 -2
  14. package/package.json +4 -2
  15. package/sdk/analytics.ts +0 -2
  16. package/sdk/index.ts +84 -28
  17. package/sdk/polling_manager.ts +0 -1
  18. package/sdk/types.ts +8 -0
  19. package/sdk/utils.ts +4 -5
  20. package/tests/engine/unit/{egine.test.ts → engine.test.ts} +20 -0
  21. package/tests/engine/unit/features/models.test.ts +8 -4
  22. package/tests/engine/unit/identities/identities_builders.test.ts +13 -0
  23. package/tests/engine/unit/identities/identities_models.test.ts +3 -14
  24. package/tests/engine/unit/organization/models.test.ts +1 -1
  25. package/tests/engine/unit/segments/segments_model.test.ts +22 -1
  26. package/tests/engine/unit/utils.ts +1 -1
  27. package/tests/sdk/analytics.test.ts +11 -0
  28. package/tests/sdk/flagsmith-cache.test.ts +150 -0
  29. package/tests/sdk/flagsmith-environment-flags.test.ts +197 -0
  30. package/tests/sdk/flagsmith-identity-flags.test.ts +140 -0
  31. package/tests/sdk/flagsmith.test.ts +100 -85
  32. package/tests/sdk/polling.test.ts +25 -0
  33. package/tests/sdk/utils.ts +21 -2
  34. package/tsconfig.json +1 -1
  35. package/build/flagsmith-engine/environments/integrations/models.d.ts +0 -4
  36. package/build/flagsmith-engine/environments/integrations/models.js +0 -11
  37. package/build/flagsmith-engine/environments/models.d.ts +0 -25
  38. package/build/flagsmith-engine/environments/models.js +0 -29
  39. package/build/flagsmith-engine/environments/util.d.ts +0 -3
  40. package/build/flagsmith-engine/environments/util.js +0 -21
  41. package/build/flagsmith-engine/features/constants.d.ts +0 -4
  42. package/build/flagsmith-engine/features/constants.js +0 -7
  43. package/build/flagsmith-engine/features/models.d.ts +0 -32
  44. package/build/flagsmith-engine/features/models.js +0 -102
  45. package/build/flagsmith-engine/features/util.d.ts +0 -3
  46. package/build/flagsmith-engine/features/util.js +0 -20
  47. package/build/flagsmith-engine/identities/models.d.ts +0 -15
  48. package/build/flagsmith-engine/identities/models.js +0 -112
  49. package/build/flagsmith-engine/identities/traits/models.d.ts +0 -5
  50. package/build/flagsmith-engine/identities/traits/models.js +0 -11
  51. package/build/flagsmith-engine/identities/util.d.ts +0 -4
  52. package/build/flagsmith-engine/identities/util.js +0 -46
  53. package/build/flagsmith-engine/index.d.ts +0 -8
  54. package/build/flagsmith-engine/index.js +0 -113
  55. package/build/flagsmith-engine/organisations/models.d.ts +0 -9
  56. package/build/flagsmith-engine/organisations/models.js +0 -21
  57. package/build/flagsmith-engine/organisations/util.d.ts +0 -2
  58. package/build/flagsmith-engine/organisations/util.js +0 -8
  59. package/build/flagsmith-engine/projects/models.d.ts +0 -10
  60. package/build/flagsmith-engine/projects/models.js +0 -14
  61. package/build/flagsmith-engine/projects/util.d.ts +0 -2
  62. package/build/flagsmith-engine/projects/util.js +0 -15
  63. package/build/flagsmith-engine/segments/constants.d.ts +0 -26
  64. package/build/flagsmith-engine/segments/constants.js +0 -31
  65. package/build/flagsmith-engine/segments/evaluators.d.ts +0 -6
  66. package/build/flagsmith-engine/segments/evaluators.js +0 -37
  67. package/build/flagsmith-engine/segments/models.d.ts +0 -31
  68. package/build/flagsmith-engine/segments/models.js +0 -92
  69. package/build/flagsmith-engine/segments/util.d.ts +0 -4
  70. package/build/flagsmith-engine/segments/util.js +0 -25
  71. package/build/flagsmith-engine/utils/collections.d.ts +0 -4
  72. package/build/flagsmith-engine/utils/collections.js +0 -97
  73. package/build/flagsmith-engine/utils/errors.d.ts +0 -2
  74. package/build/flagsmith-engine/utils/errors.js +0 -26
  75. package/build/flagsmith-engine/utils/hashing/index.d.ts +0 -9
  76. package/build/flagsmith-engine/utils/hashing/index.js +0 -57
  77. package/build/flagsmith-engine/utils/index.d.ts +0 -1
  78. package/build/flagsmith-engine/utils/index.js +0 -14
  79. package/build/index.d.ts +0 -1
  80. package/build/index.js +0 -11
  81. package/build/sdk/analytics.d.ts +0 -28
  82. package/build/sdk/analytics.js +0 -103
  83. package/build/sdk/errors.d.ts +0 -4
  84. package/build/sdk/errors.js +0 -34
  85. package/build/sdk/index.d.ts +0 -118
  86. package/build/sdk/index.js +0 -386
  87. package/build/sdk/models.d.ts +0 -55
  88. package/build/sdk/models.js +0 -149
  89. package/build/sdk/polling_manager.d.ts +0 -9
  90. package/build/sdk/polling_manager.js +0 -73
  91. package/build/sdk/utils.d.ts +0 -12
  92. package/build/sdk/utils.js +0 -94
  93. package/tests/engine/engine-tests/engine-test-data/data/environment_n9fbf9h3v4fFgH3U3ngWhb.json +0 -12393
  94. package/tests/engine/engine-tests/engine-test-data/readme.md +0 -30
@@ -1,118 +0,0 @@
1
- import { EnvironmentModel } from '../flagsmith-engine/environments/models';
2
- import { DefaultFlag, Flags } from './models';
3
- import { EnvironmentDataPollingManager } from './polling_manager';
4
- import { SegmentModel } from '../flagsmith-engine/segments/models';
5
- export declare class Flagsmith {
6
- environmentKey?: string;
7
- apiUrl: string;
8
- customHeaders?: {
9
- [key: string]: any;
10
- };
11
- requestTimeoutSeconds?: number;
12
- enableLocalEvaluation?: boolean;
13
- environmentRefreshIntervalSeconds: number;
14
- retries?: number;
15
- enableAnalytics: boolean;
16
- defaultFlagHandler?: (featureName: string) => DefaultFlag;
17
- environmentFlagsUrl: string;
18
- identitiesUrl: string;
19
- environmentUrl: string;
20
- environmentDataPollingManager?: EnvironmentDataPollingManager;
21
- environment: EnvironmentModel;
22
- private analyticsProcessor?;
23
- /**
24
- * A Flagsmith client.
25
- *
26
- * Provides an interface for interacting with the Flagsmith http API.
27
- * Basic Usage::
28
- *
29
- * import flagsmith from Flagsmith
30
- * const flagsmith = new Flagsmith({environmentKey: '<your API key>'});
31
- * const environmentFlags = flagsmith.getEnvironmentFlags();
32
- * const featureEnabled = environmentFlags.isFeatureEnabled('foo');
33
- * const identityFlags = flagsmith.getIdentityFlags('identifier', {'foo': 'bar'});
34
- * const featureEnabledForIdentity = identityFlags.isFeatureEnabled("foo")
35
- *
36
- * @param {string} data.environmentKey: The environment key obtained from Flagsmith interface
37
- @param {string} data.apiUrl: Override the URL of the Flagsmith API to communicate with
38
- @param data.customHeaders: Additional headers to add to requests made to the
39
- Flagsmith API
40
- @param {number} data.requestTimeoutSeconds: Number of seconds to wait for a request to
41
- complete before terminating the request
42
- @param {boolean} data.enableLocalEvaluation: Enables local evaluation of flags
43
- @param {number} data.environmentRefreshIntervalSeconds: If using local evaluation,
44
- specify the interval period between refreshes of local environment data
45
- @param {number} data.retries: a urllib3.Retry object to use on all http requests to the
46
- Flagsmith API
47
- @param {boolean} data.enableAnalytics: if enabled, sends additional requests to the Flagsmith
48
- API to power flag analytics charts
49
- @param data.defaultFlagHandler: callable which will be used in the case where
50
- flags cannot be retrieved from the API or a non existent feature is
51
- requested
52
- */
53
- constructor(data: {
54
- environmentKey: string;
55
- apiUrl?: string;
56
- customHeaders?: {
57
- [key: string]: any;
58
- };
59
- requestTimeoutSeconds?: number;
60
- enableLocalEvaluation?: boolean;
61
- environmentRefreshIntervalSeconds?: number;
62
- retries?: number;
63
- enableAnalytics?: boolean;
64
- defaultFlagHandler?: (featureName: string) => DefaultFlag;
65
- });
66
- /**
67
- * Get all the default for flags for the current environment.
68
- *
69
- * @returns Flags object holding all the flags for the current environment.
70
- */
71
- getEnvironmentFlags(): Promise<Flags>;
72
- /**
73
- * Get all the flags for the current environment for a given identity. Will also
74
- upsert all traits to the Flagsmith API for future evaluations. Providing a
75
- trait with a value of None will remove the trait from the identity if it exists.
76
- *
77
- * @param {string} identifier a unique identifier for the identity in the current
78
- environment, e.g. email address, username, uuid
79
- * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
80
- Flagsmith, e.g. {"num_orders": 10}
81
- * @returns Flags object holding all the flags for the given identity.
82
- */
83
- getIdentityFlags(identifier: string, traits?: {
84
- [key: string]: any;
85
- }): Promise<Flags>;
86
- /**
87
- * Get the segments for the current environment for a given identity. Will also
88
- upsert all traits to the Flagsmith API for future evaluations. Providing a
89
- trait with a value of None will remove the trait from the identity if it exists.
90
- *
91
- * @param {string} identifier a unique identifier for the identity in the current
92
- environment, e.g. email address, username, uuid
93
- * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
94
- Flagsmith, e.g. {"num_orders": 10}
95
- * @returns Segments that the given identity belongs to.
96
- */
97
- getIdentitySegments(identifier: string, traits?: {
98
- [key: string]: any;
99
- }): Promise<SegmentModel[]>;
100
- /**
101
- * Updates the environment state for local flag evaluation.
102
- * Sets a local promise to prevent race conditions in getIdentityFlags / getIdentitySegments.
103
- * You only need to call this if you wish to bypass environmentRefreshIntervalSeconds.
104
- */
105
- updateEnvironment(): Promise<void>;
106
- private getJSONResponse;
107
- /**
108
- * This promise ensures that the environment is retrieved before attempting to locally evaluate.
109
- */
110
- private environmentPromise;
111
- private getEnvironmentFromApi;
112
- private getEnvironmentFlagsFromDocument;
113
- private getIdentityFlagsFromDocument;
114
- private getEnvironmentFlagsFromApi;
115
- private getIdentityFlagsFromApi;
116
- private buildIdentityModel;
117
- }
118
- export default Flagsmith;
@@ -1,386 +0,0 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
66
- exports.Flagsmith = void 0;
67
- var flagsmith_engine_1 = require("../flagsmith-engine");
68
- var util_1 = require("../flagsmith-engine/environments/util");
69
- var models_1 = require("../flagsmith-engine/identities/models");
70
- var models_2 = require("../flagsmith-engine/identities/traits/models");
71
- var analytics_1 = require("./analytics");
72
- var errors_1 = require("./errors");
73
- var models_3 = require("./models");
74
- var polling_manager_1 = require("./polling_manager");
75
- var utils_1 = require("./utils");
76
- var evaluators_1 = require("../flagsmith-engine/segments/evaluators");
77
- var DEFAULT_API_URL = 'https://api.flagsmith.com/api/v1/';
78
- var Flagsmith = /** @class */ (function () {
79
- /**
80
- * A Flagsmith client.
81
- *
82
- * Provides an interface for interacting with the Flagsmith http API.
83
- * Basic Usage::
84
- *
85
- * import flagsmith from Flagsmith
86
- * const flagsmith = new Flagsmith({environmentKey: '<your API key>'});
87
- * const environmentFlags = flagsmith.getEnvironmentFlags();
88
- * const featureEnabled = environmentFlags.isFeatureEnabled('foo');
89
- * const identityFlags = flagsmith.getIdentityFlags('identifier', {'foo': 'bar'});
90
- * const featureEnabledForIdentity = identityFlags.isFeatureEnabled("foo")
91
- *
92
- * @param {string} data.environmentKey: The environment key obtained from Flagsmith interface
93
- @param {string} data.apiUrl: Override the URL of the Flagsmith API to communicate with
94
- @param data.customHeaders: Additional headers to add to requests made to the
95
- Flagsmith API
96
- @param {number} data.requestTimeoutSeconds: Number of seconds to wait for a request to
97
- complete before terminating the request
98
- @param {boolean} data.enableLocalEvaluation: Enables local evaluation of flags
99
- @param {number} data.environmentRefreshIntervalSeconds: If using local evaluation,
100
- specify the interval period between refreshes of local environment data
101
- @param {number} data.retries: a urllib3.Retry object to use on all http requests to the
102
- Flagsmith API
103
- @param {boolean} data.enableAnalytics: if enabled, sends additional requests to the Flagsmith
104
- API to power flag analytics charts
105
- @param data.defaultFlagHandler: callable which will be used in the case where
106
- flags cannot be retrieved from the API or a non existent feature is
107
- requested
108
- */
109
- function Flagsmith(data) {
110
- this.apiUrl = DEFAULT_API_URL;
111
- this.enableLocalEvaluation = false;
112
- this.environmentRefreshIntervalSeconds = 60;
113
- this.enableAnalytics = false;
114
- this.environmentKey = data.environmentKey;
115
- this.apiUrl = data.apiUrl || this.apiUrl;
116
- this.customHeaders = data.customHeaders;
117
- this.requestTimeoutSeconds = data.requestTimeoutSeconds;
118
- this.enableLocalEvaluation = data.enableLocalEvaluation;
119
- this.environmentRefreshIntervalSeconds =
120
- data.environmentRefreshIntervalSeconds || this.environmentRefreshIntervalSeconds;
121
- this.retries = data.retries;
122
- this.enableAnalytics = data.enableAnalytics || false;
123
- this.defaultFlagHandler = data.defaultFlagHandler;
124
- this.environmentFlagsUrl = "".concat(this.apiUrl, "flags/");
125
- this.identitiesUrl = "".concat(this.apiUrl, "identities/");
126
- this.environmentUrl = "".concat(this.apiUrl, "environment-document/");
127
- if (this.enableLocalEvaluation) {
128
- if (!this.environmentKey.startsWith('ser.')) {
129
- console.error('In order to use local evaluation, please generate a server key in the environment settings page.');
130
- }
131
- this.environmentDataPollingManager = new polling_manager_1.EnvironmentDataPollingManager(this, this.environmentRefreshIntervalSeconds);
132
- this.environmentDataPollingManager.start();
133
- this.updateEnvironment();
134
- }
135
- this.analyticsProcessor = data.enableAnalytics
136
- ? new analytics_1.AnalyticsProcessor({
137
- environmentKey: this.environmentKey,
138
- baseApiUrl: this.apiUrl,
139
- timeout: this.requestTimeoutSeconds
140
- })
141
- : undefined;
142
- }
143
- /**
144
- * Get all the default for flags for the current environment.
145
- *
146
- * @returns Flags object holding all the flags for the current environment.
147
- */
148
- Flagsmith.prototype.getEnvironmentFlags = function () {
149
- return __awaiter(this, void 0, void 0, function () {
150
- var _this = this;
151
- return __generator(this, function (_a) {
152
- if (this.environment) {
153
- return [2 /*return*/, new Promise(function (resolve) { return resolve(_this.getEnvironmentFlagsFromDocument()); })];
154
- }
155
- return [2 /*return*/, this.getEnvironmentFlagsFromApi()];
156
- });
157
- });
158
- };
159
- /**
160
- * Get all the flags for the current environment for a given identity. Will also
161
- upsert all traits to the Flagsmith API for future evaluations. Providing a
162
- trait with a value of None will remove the trait from the identity if it exists.
163
- *
164
- * @param {string} identifier a unique identifier for the identity in the current
165
- environment, e.g. email address, username, uuid
166
- * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
167
- Flagsmith, e.g. {"num_orders": 10}
168
- * @returns Flags object holding all the flags for the given identity.
169
- */
170
- Flagsmith.prototype.getIdentityFlags = function (identifier, traits) {
171
- var _this = this;
172
- traits = traits || {};
173
- if (this.enableLocalEvaluation) {
174
- return new Promise(function (resolve) {
175
- return _this.environmentPromise.then(function () {
176
- resolve(_this.getIdentityFlagsFromDocument(identifier, traits || {}));
177
- });
178
- });
179
- }
180
- return this.getIdentityFlagsFromApi(identifier, traits);
181
- };
182
- /**
183
- * Get the segments for the current environment for a given identity. Will also
184
- upsert all traits to the Flagsmith API for future evaluations. Providing a
185
- trait with a value of None will remove the trait from the identity if it exists.
186
- *
187
- * @param {string} identifier a unique identifier for the identity in the current
188
- environment, e.g. email address, username, uuid
189
- * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
190
- Flagsmith, e.g. {"num_orders": 10}
191
- * @returns Segments that the given identity belongs to.
192
- */
193
- Flagsmith.prototype.getIdentitySegments = function (identifier, traits) {
194
- var _this = this;
195
- traits = traits || {};
196
- if (this.enableLocalEvaluation) {
197
- return this.environmentPromise.then(function () {
198
- return new Promise(function (resolve) {
199
- var identityModel = _this.buildIdentityModel(identifier, Object.keys(traits || {}).map(function (key) { return ({
200
- key: key,
201
- value: traits === null || traits === void 0 ? void 0 : traits[key]
202
- }); }));
203
- var segments = (0, evaluators_1.getIdentitySegments)(_this.environment, identityModel);
204
- return resolve(segments);
205
- });
206
- });
207
- }
208
- console.error('This function is only permitted with local evaluation.');
209
- return Promise.resolve([]);
210
- };
211
- /**
212
- * Updates the environment state for local flag evaluation.
213
- * Sets a local promise to prevent race conditions in getIdentityFlags / getIdentitySegments.
214
- * You only need to call this if you wish to bypass environmentRefreshIntervalSeconds.
215
- */
216
- Flagsmith.prototype.updateEnvironment = function () {
217
- return __awaiter(this, void 0, void 0, function () {
218
- var request, _a;
219
- var _this = this;
220
- return __generator(this, function (_b) {
221
- switch (_b.label) {
222
- case 0:
223
- request = this.getEnvironmentFromApi();
224
- if (!!this.environmentPromise) return [3 /*break*/, 2];
225
- this.environmentPromise = request.then(function (res) {
226
- _this.environment = res;
227
- });
228
- return [4 /*yield*/, this.environmentPromise];
229
- case 1:
230
- _b.sent();
231
- return [3 /*break*/, 4];
232
- case 2:
233
- _a = this;
234
- return [4 /*yield*/, request];
235
- case 3:
236
- _a.environment = _b.sent();
237
- _b.label = 4;
238
- case 4: return [2 /*return*/];
239
- }
240
- });
241
- });
242
- };
243
- Flagsmith.prototype.getJSONResponse = function (url, method, body) {
244
- return __awaiter(this, void 0, void 0, function () {
245
- var headers, _a, _b, _c, k, v, data;
246
- var e_1, _d;
247
- return __generator(this, function (_e) {
248
- switch (_e.label) {
249
- case 0:
250
- headers = { 'Content-Type': 'application/json' };
251
- if (this.environmentKey) {
252
- headers['X-Environment-Key'] = this.environmentKey;
253
- }
254
- if (this.customHeaders) {
255
- try {
256
- for (_a = __values(Object.entries(this.customHeaders)), _b = _a.next(); !_b.done; _b = _a.next()) {
257
- _c = __read(_b.value, 2), k = _c[0], v = _c[1];
258
- headers[k] = v;
259
- }
260
- }
261
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
262
- finally {
263
- try {
264
- if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
265
- }
266
- finally { if (e_1) throw e_1.error; }
267
- }
268
- }
269
- return [4 /*yield*/, (0, utils_1.retryFetch)(url, {
270
- method: method,
271
- timeout: this.requestTimeoutSeconds || undefined,
272
- body: JSON.stringify(body),
273
- headers: headers
274
- }, this.retries, 1000, (this.requestTimeoutSeconds || 10) * 1000)];
275
- case 1:
276
- data = _e.sent();
277
- if (data.status !== 200) {
278
- throw new errors_1.FlagsmithAPIError("Invalid request made to Flagsmith API. Response status code: ".concat(data.status));
279
- }
280
- return [2 /*return*/, data.json()];
281
- }
282
- });
283
- });
284
- };
285
- Flagsmith.prototype.getEnvironmentFromApi = function () {
286
- return __awaiter(this, void 0, void 0, function () {
287
- var environment_data;
288
- return __generator(this, function (_a) {
289
- switch (_a.label) {
290
- case 0: return [4 /*yield*/, this.getJSONResponse(this.environmentUrl, 'GET')];
291
- case 1:
292
- environment_data = _a.sent();
293
- return [2 /*return*/, (0, util_1.buildEnvironmentModel)(environment_data)];
294
- }
295
- });
296
- });
297
- };
298
- Flagsmith.prototype.getEnvironmentFlagsFromDocument = function () {
299
- return models_3.Flags.fromFeatureStateModels({
300
- featureStates: (0, flagsmith_engine_1.getEnvironmentFeatureStates)(this.environment),
301
- analyticsProcessor: this.analyticsProcessor,
302
- defaultFlagHandler: this.defaultFlagHandler
303
- });
304
- };
305
- Flagsmith.prototype.getIdentityFlagsFromDocument = function (identifier, traits) {
306
- var identityModel = this.buildIdentityModel(identifier, Object.keys(traits).map(function (key) { return ({
307
- key: key,
308
- value: traits[key]
309
- }); }));
310
- var featureStates = (0, flagsmith_engine_1.getIdentityFeatureStates)(this.environment, identityModel);
311
- return models_3.Flags.fromFeatureStateModels({
312
- featureStates: featureStates,
313
- analyticsProcessor: this.analyticsProcessor,
314
- defaultFlagHandler: this.defaultFlagHandler
315
- });
316
- };
317
- Flagsmith.prototype.getEnvironmentFlagsFromApi = function () {
318
- return __awaiter(this, void 0, void 0, function () {
319
- var apiFlags, e_2;
320
- return __generator(this, function (_a) {
321
- switch (_a.label) {
322
- case 0:
323
- _a.trys.push([0, 2, , 3]);
324
- return [4 /*yield*/, this.getJSONResponse(this.environmentFlagsUrl, 'GET')];
325
- case 1:
326
- apiFlags = _a.sent();
327
- return [2 /*return*/, models_3.Flags.fromAPIFlags({
328
- apiFlags: apiFlags,
329
- analyticsProcessor: this.analyticsProcessor,
330
- defaultFlagHandler: this.defaultFlagHandler
331
- })];
332
- case 2:
333
- e_2 = _a.sent();
334
- if (this.defaultFlagHandler) {
335
- return [2 /*return*/, new models_3.Flags({
336
- flags: {},
337
- defaultFlagHandler: this.defaultFlagHandler
338
- })];
339
- }
340
- throw e_2;
341
- case 3: return [2 /*return*/];
342
- }
343
- });
344
- });
345
- };
346
- Flagsmith.prototype.getIdentityFlagsFromApi = function (identifier, traits) {
347
- return __awaiter(this, void 0, void 0, function () {
348
- var data, jsonResponse, e_3;
349
- return __generator(this, function (_a) {
350
- switch (_a.label) {
351
- case 0:
352
- _a.trys.push([0, 2, , 3]);
353
- data = (0, utils_1.generateIdentitiesData)(identifier, traits);
354
- return [4 /*yield*/, this.getJSONResponse(this.identitiesUrl, 'POST', data)];
355
- case 1:
356
- jsonResponse = _a.sent();
357
- return [2 /*return*/, models_3.Flags.fromAPIFlags({
358
- apiFlags: jsonResponse['flags'],
359
- analyticsProcessor: this.analyticsProcessor,
360
- defaultFlagHandler: this.defaultFlagHandler
361
- })];
362
- case 2:
363
- e_3 = _a.sent();
364
- if (this.defaultFlagHandler) {
365
- return [2 /*return*/, new models_3.Flags({
366
- flags: {},
367
- defaultFlagHandler: this.defaultFlagHandler
368
- })];
369
- }
370
- throw e_3;
371
- case 3: return [2 /*return*/];
372
- }
373
- });
374
- });
375
- };
376
- Flagsmith.prototype.buildIdentityModel = function (identifier, traits) {
377
- if (!this.environment) {
378
- throw new errors_1.FlagsmithClientError('Unable to build identity model when no local environment present.');
379
- }
380
- var traitModels = traits.map(function (trait) { return new models_2.TraitModel(trait.key, trait.value); });
381
- return new models_1.IdentityModel('0', traitModels, [], this.environment.apiKey, identifier);
382
- };
383
- return Flagsmith;
384
- }());
385
- exports.Flagsmith = Flagsmith;
386
- exports.default = Flagsmith;
@@ -1,55 +0,0 @@
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
- }