flagsmith-nodejs 2.5.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/.github/workflows/publish.yml +25 -0
  2. package/examples/README.md +3 -0
  3. package/flagsmith-engine/identities/models.ts +3 -1
  4. package/flagsmith-engine/segments/evaluators.ts +4 -3
  5. package/package.json +1 -1
  6. package/sdk/index.ts +2 -2
  7. package/sdk/utils.ts +13 -7
  8. package/tests/engine/unit/segments/segment_evaluators.test.ts +46 -6
  9. package/tests/engine/unit/utils/utils.test.ts +0 -1
  10. package/tests/sdk/flagsmith.test.ts +27 -1
  11. package/.vscode/launch.json +0 -18
  12. package/build/flagsmith-engine/environments/integrations/models.d.ts +0 -4
  13. package/build/flagsmith-engine/environments/integrations/models.js +0 -11
  14. package/build/flagsmith-engine/environments/models.d.ts +0 -25
  15. package/build/flagsmith-engine/environments/models.js +0 -29
  16. package/build/flagsmith-engine/environments/util.d.ts +0 -3
  17. package/build/flagsmith-engine/environments/util.js +0 -21
  18. package/build/flagsmith-engine/features/constants.d.ts +0 -4
  19. package/build/flagsmith-engine/features/constants.js +0 -7
  20. package/build/flagsmith-engine/features/models.d.ts +0 -37
  21. package/build/flagsmith-engine/features/models.js +0 -122
  22. package/build/flagsmith-engine/features/util.d.ts +0 -4
  23. package/build/flagsmith-engine/features/util.js +0 -27
  24. package/build/flagsmith-engine/identities/models.d.ts +0 -15
  25. package/build/flagsmith-engine/identities/models.js +0 -112
  26. package/build/flagsmith-engine/identities/traits/models.d.ts +0 -5
  27. package/build/flagsmith-engine/identities/traits/models.js +0 -11
  28. package/build/flagsmith-engine/identities/util.d.ts +0 -4
  29. package/build/flagsmith-engine/identities/util.js +0 -46
  30. package/build/flagsmith-engine/index.d.ts +0 -15
  31. package/build/flagsmith-engine/index.js +0 -129
  32. package/build/flagsmith-engine/organisations/models.d.ts +0 -9
  33. package/build/flagsmith-engine/organisations/models.js +0 -21
  34. package/build/flagsmith-engine/organisations/util.d.ts +0 -2
  35. package/build/flagsmith-engine/organisations/util.js +0 -8
  36. package/build/flagsmith-engine/projects/models.d.ts +0 -10
  37. package/build/flagsmith-engine/projects/models.js +0 -14
  38. package/build/flagsmith-engine/projects/util.d.ts +0 -2
  39. package/build/flagsmith-engine/projects/util.js +0 -15
  40. package/build/flagsmith-engine/segments/constants.d.ts +0 -34
  41. package/build/flagsmith-engine/segments/constants.js +0 -39
  42. package/build/flagsmith-engine/segments/evaluators.d.ts +0 -7
  43. package/build/flagsmith-engine/segments/evaluators.js +0 -44
  44. package/build/flagsmith-engine/segments/models.d.ts +0 -37
  45. package/build/flagsmith-engine/segments/models.js +0 -144
  46. package/build/flagsmith-engine/segments/util.d.ts +0 -6
  47. package/build/flagsmith-engine/segments/util.js +0 -33
  48. package/build/flagsmith-engine/utils/collections.d.ts +0 -3
  49. package/build/flagsmith-engine/utils/collections.js +0 -26
  50. package/build/flagsmith-engine/utils/errors.d.ts +0 -2
  51. package/build/flagsmith-engine/utils/errors.js +0 -26
  52. package/build/flagsmith-engine/utils/hashing/index.d.ts +0 -9
  53. package/build/flagsmith-engine/utils/hashing/index.js +0 -60
  54. package/build/flagsmith-engine/utils/index.d.ts +0 -1
  55. package/build/flagsmith-engine/utils/index.js +0 -17
  56. package/build/index.d.ts +0 -2
  57. package/build/index.js +0 -24
  58. package/build/sdk/analytics.d.ts +0 -31
  59. package/build/sdk/analytics.js +0 -116
  60. package/build/sdk/errors.d.ts +0 -4
  61. package/build/sdk/errors.js +0 -34
  62. package/build/sdk/index.d.ts +0 -120
  63. package/build/sdk/index.js +0 -528
  64. package/build/sdk/models.d.ts +0 -55
  65. package/build/sdk/models.js +0 -149
  66. package/build/sdk/polling_manager.d.ts +0 -9
  67. package/build/sdk/polling_manager.js +0 -72
  68. package/build/sdk/types.d.ts +0 -27
  69. package/build/sdk/types.js +0 -2
  70. package/build/sdk/utils.d.ts +0 -12
  71. package/build/sdk/utils.js +0 -93
  72. package/examples/api-proxy/.babelrc +0 -3
  73. package/examples/api-proxy/.eslintrc +0 -8
  74. package/examples/api-proxy/README.md +0 -12
  75. package/examples/api-proxy/package-lock.json +0 -10889
  76. package/examples/api-proxy/package.json +0 -57
  77. package/examples/api-proxy/src/api/index.js +0 -42
  78. package/examples/api-proxy/src/index.js +0 -29
  79. package/examples/basic/.babelrc +0 -3
  80. package/examples/basic/.eslintrc +0 -8
  81. package/examples/basic/README.md +0 -10
  82. package/examples/basic/package-lock.json +0 -10779
  83. package/examples/basic/package.json +0 -56
  84. package/examples/basic/src/api/index.js +0 -33
  85. package/examples/basic/src/index.js +0 -29
  86. package/examples/caching/.babelrc +0 -3
  87. package/examples/caching/.eslintrc +0 -8
  88. package/examples/caching/README.md +0 -9
  89. package/examples/caching/package-lock.json +0 -6750
  90. package/examples/caching/package.json +0 -56
  91. package/examples/caching/src/api/index.js +0 -38
  92. package/examples/caching/src/index.js +0 -29
  93. package/examples/custom-fetch-agent/.babelrc +0 -3
  94. package/examples/custom-fetch-agent/.eslintrc +0 -8
  95. package/examples/custom-fetch-agent/README.md +0 -12
  96. package/examples/custom-fetch-agent/package-lock.json +0 -6750
  97. package/examples/custom-fetch-agent/package.json +0 -56
  98. package/examples/custom-fetch-agent/src/api/index.js +0 -34
  99. package/examples/custom-fetch-agent/src/index.js +0 -29
  100. package/examples/local-evaluation/.babelrc +0 -3
  101. package/examples/local-evaluation/.eslintrc +0 -8
  102. package/examples/local-evaluation/README.md +0 -18
  103. package/examples/local-evaluation/package-lock.json +0 -6668
  104. package/examples/local-evaluation/package.json +0 -56
  105. package/examples/local-evaluation/src/api/index.js +0 -39
  106. package/examples/local-evaluation/src/index.js +0 -29
  107. package/tests/engine/engine-tests/engine-test-data/data/environment_n9fbf9h3v4fFgH3U3ngWhb.json +0 -12591
  108. package/tests/engine/engine-tests/engine-test-data/readme.md +0 -30
@@ -1,120 +0,0 @@
1
- import { RequestInit } from "node-fetch";
2
- import { EnvironmentModel } from '../flagsmith-engine/environments/models';
3
- import { DefaultFlag, Flags } from './models';
4
- import { EnvironmentDataPollingManager } from './polling_manager';
5
- import { SegmentModel } from '../flagsmith-engine/segments/models';
6
- import { FlagsmithConfig } from './types';
7
- export { AnalyticsProcessor } from './analytics';
8
- export { FlagsmithAPIError, FlagsmithClientError } from './errors';
9
- export { DefaultFlag, Flags } from './models';
10
- export { EnvironmentDataPollingManager } from './polling_manager';
11
- export { FlagsmithCache, FlagsmithConfig } from './types';
12
- export declare class Flagsmith {
13
- environmentKey?: string;
14
- apiUrl: string;
15
- customHeaders?: {
16
- [key: string]: any;
17
- };
18
- requestTimeoutSeconds?: number;
19
- agent: RequestInit['agent'];
20
- requestTimeoutMs?: number;
21
- enableLocalEvaluation?: boolean;
22
- environmentRefreshIntervalSeconds: number;
23
- retries?: number;
24
- enableAnalytics: boolean;
25
- defaultFlagHandler?: (featureName: string) => DefaultFlag;
26
- environmentFlagsUrl: string;
27
- identitiesUrl: string;
28
- environmentUrl: string;
29
- environmentDataPollingManager?: EnvironmentDataPollingManager;
30
- environment: EnvironmentModel;
31
- private cache?;
32
- private onEnvironmentChange?;
33
- private analyticsProcessor?;
34
- private logger;
35
- /**
36
- * A Flagsmith client.
37
- *
38
- * Provides an interface for interacting with the Flagsmith http API.
39
- * Basic Usage::
40
- *
41
- * import flagsmith from Flagsmith
42
- * const flagsmith = new Flagsmith({environmentKey: '<your API key>'});
43
- * const environmentFlags = flagsmith.getEnvironmentFlags();
44
- * const featureEnabled = environmentFlags.isFeatureEnabled('foo');
45
- * const identityFlags = flagsmith.getIdentityFlags('identifier', {'foo': 'bar'});
46
- * const featureEnabledForIdentity = identityFlags.isFeatureEnabled("foo")
47
- *
48
- * @param {string} data.environmentKey: The environment key obtained from Flagsmith interface
49
- @param {string} data.apiUrl: Override the URL of the Flagsmith API to communicate with
50
- @param data.customHeaders: Additional headers to add to requests made to the
51
- Flagsmith API
52
- @param {number} data.requestTimeoutSeconds: Number of seconds to wait for a request to
53
- complete before terminating the request
54
- @param {boolean} data.enableLocalEvaluation: Enables local evaluation of flags
55
- @param {number} data.environmentRefreshIntervalSeconds: If using local evaluation,
56
- specify the interval period between refreshes of local environment data
57
- @param {number} data.retries: a urllib3.Retry object to use on all http requests to the
58
- Flagsmith API
59
- @param {boolean} data.enableAnalytics: if enabled, sends additional requests to the Flagsmith
60
- API to power flag analytics charts
61
- @param data.defaultFlagHandler: callable which will be used in the case where
62
- flags cannot be retrieved from the API or a non existent feature is
63
- requested
64
- @param data.logger: an instance of the pino Logger class to use for logging
65
- */
66
- constructor(data: FlagsmithConfig);
67
- /**
68
- * Get all the default for flags for the current environment.
69
- *
70
- * @returns Flags object holding all the flags for the current environment.
71
- */
72
- getEnvironmentFlags(): Promise<Flags>;
73
- /**
74
- * Get all the flags for the current environment for a given identity. Will also
75
- upsert all traits to the Flagsmith API for future evaluations. Providing a
76
- trait with a value of None will remove the trait from the identity if it exists.
77
- *
78
- * @param {string} identifier a unique identifier for the identity in the current
79
- environment, e.g. email address, username, uuid
80
- * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
81
- Flagsmith, e.g. {"num_orders": 10}
82
- * @returns Flags object holding all the flags for the given identity.
83
- */
84
- getIdentityFlags(identifier: string, traits?: {
85
- [key: string]: any;
86
- }): Promise<Flags>;
87
- /**
88
- * Get the segments for the current environment for a given identity. Will also
89
- upsert all traits to the Flagsmith API for future evaluations. Providing a
90
- trait with a value of None will remove the trait from the identity if it exists.
91
- *
92
- * @param {string} identifier a unique identifier for the identity in the current
93
- environment, e.g. email address, username, uuid
94
- * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
95
- Flagsmith, e.g. {"num_orders": 10}
96
- * @returns Segments that the given identity belongs to.
97
- */
98
- getIdentitySegments(identifier: string, traits?: {
99
- [key: string]: any;
100
- }): Promise<SegmentModel[]>;
101
- /**
102
- * Updates the environment state for local flag evaluation.
103
- * Sets a local promise to prevent race conditions in getIdentityFlags / getIdentitySegments.
104
- * You only need to call this if you wish to bypass environmentRefreshIntervalSeconds.
105
- */
106
- updateEnvironment(): Promise<void>;
107
- close(): Promise<void>;
108
- private getJSONResponse;
109
- /**
110
- * This promise ensures that the environment is retrieved before attempting to locally evaluate.
111
- */
112
- private environmentPromise;
113
- private getEnvironmentFromApi;
114
- private getEnvironmentFlagsFromDocument;
115
- private getIdentityFlagsFromDocument;
116
- private getEnvironmentFlagsFromApi;
117
- private getIdentityFlagsFromApi;
118
- private buildIdentityModel;
119
- }
120
- export default Flagsmith;
@@ -1,528 +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
- 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
- timeout: this.requestTimeoutMs || undefined,
368
- body: JSON.stringify(body),
369
- headers: headers
370
- }, this.retries)];
371
- case 1:
372
- data = _e.sent();
373
- if (data.status !== 200) {
374
- throw new errors_1.FlagsmithAPIError("Invalid request made to Flagsmith API. Response status code: ".concat(data.status));
375
- }
376
- return [2 /*return*/, data.json()];
377
- }
378
- });
379
- });
380
- };
381
- Flagsmith.prototype.getEnvironmentFromApi = function () {
382
- return __awaiter(this, void 0, void 0, function () {
383
- var environment_data;
384
- return __generator(this, function (_a) {
385
- switch (_a.label) {
386
- case 0: return [4 /*yield*/, this.getJSONResponse(this.environmentUrl, 'GET')];
387
- case 1:
388
- environment_data = _a.sent();
389
- return [2 /*return*/, (0, util_1.buildEnvironmentModel)(environment_data)];
390
- }
391
- });
392
- });
393
- };
394
- Flagsmith.prototype.getEnvironmentFlagsFromDocument = function () {
395
- return __awaiter(this, void 0, void 0, function () {
396
- var flags;
397
- return __generator(this, function (_a) {
398
- switch (_a.label) {
399
- case 0:
400
- flags = models_3.Flags.fromFeatureStateModels({
401
- featureStates: (0, flagsmith_engine_1.getEnvironmentFeatureStates)(this.environment),
402
- analyticsProcessor: this.analyticsProcessor,
403
- defaultFlagHandler: this.defaultFlagHandler
404
- });
405
- if (!!!this.cache) return [3 /*break*/, 2];
406
- // @ts-ignore node-cache types are incorrect, ttl should be optional
407
- return [4 /*yield*/, this.cache.set('flags', flags)];
408
- case 1:
409
- // @ts-ignore node-cache types are incorrect, ttl should be optional
410
- _a.sent();
411
- _a.label = 2;
412
- case 2: return [2 /*return*/, flags];
413
- }
414
- });
415
- });
416
- };
417
- Flagsmith.prototype.getIdentityFlagsFromDocument = function (identifier, traits) {
418
- return __awaiter(this, void 0, void 0, function () {
419
- var identityModel, featureStates, flags;
420
- return __generator(this, function (_a) {
421
- switch (_a.label) {
422
- case 0:
423
- identityModel = this.buildIdentityModel(identifier, Object.keys(traits).map(function (key) { return ({
424
- key: key,
425
- value: traits[key]
426
- }); }));
427
- featureStates = (0, flagsmith_engine_1.getIdentityFeatureStates)(this.environment, identityModel);
428
- flags = models_3.Flags.fromFeatureStateModels({
429
- featureStates: featureStates,
430
- analyticsProcessor: this.analyticsProcessor,
431
- defaultFlagHandler: this.defaultFlagHandler,
432
- identityID: identityModel.djangoID || identityModel.compositeKey
433
- });
434
- if (!!!this.cache) return [3 /*break*/, 2];
435
- // @ts-ignore node-cache types are incorrect, ttl should be optional
436
- return [4 /*yield*/, this.cache.set("flags-".concat(identifier), flags)];
437
- case 1:
438
- // @ts-ignore node-cache types are incorrect, ttl should be optional
439
- _a.sent();
440
- _a.label = 2;
441
- case 2: return [2 /*return*/, flags];
442
- }
443
- });
444
- });
445
- };
446
- Flagsmith.prototype.getEnvironmentFlagsFromApi = function () {
447
- return __awaiter(this, void 0, void 0, function () {
448
- var apiFlags, flags, e_3;
449
- return __generator(this, function (_a) {
450
- switch (_a.label) {
451
- case 0:
452
- _a.trys.push([0, 4, , 5]);
453
- return [4 /*yield*/, this.getJSONResponse(this.environmentFlagsUrl, 'GET')];
454
- case 1:
455
- apiFlags = _a.sent();
456
- flags = models_3.Flags.fromAPIFlags({
457
- apiFlags: apiFlags,
458
- analyticsProcessor: this.analyticsProcessor,
459
- defaultFlagHandler: this.defaultFlagHandler
460
- });
461
- if (!!!this.cache) return [3 /*break*/, 3];
462
- // @ts-ignore node-cache types are incorrect, ttl should be optional
463
- return [4 /*yield*/, this.cache.set('flags', flags)];
464
- case 2:
465
- // @ts-ignore node-cache types are incorrect, ttl should be optional
466
- _a.sent();
467
- _a.label = 3;
468
- case 3: return [2 /*return*/, flags];
469
- case 4:
470
- e_3 = _a.sent();
471
- if (this.defaultFlagHandler) {
472
- return [2 /*return*/, new models_3.Flags({
473
- flags: {},
474
- defaultFlagHandler: this.defaultFlagHandler
475
- })];
476
- }
477
- throw e_3;
478
- case 5: return [2 /*return*/];
479
- }
480
- });
481
- });
482
- };
483
- Flagsmith.prototype.getIdentityFlagsFromApi = function (identifier, traits) {
484
- return __awaiter(this, void 0, void 0, function () {
485
- var data, jsonResponse, flags, e_4;
486
- return __generator(this, function (_a) {
487
- switch (_a.label) {
488
- case 0:
489
- _a.trys.push([0, 4, , 5]);
490
- data = (0, utils_1.generateIdentitiesData)(identifier, traits);
491
- return [4 /*yield*/, this.getJSONResponse(this.identitiesUrl, 'POST', data)];
492
- case 1:
493
- jsonResponse = _a.sent();
494
- flags = models_3.Flags.fromAPIFlags({
495
- apiFlags: jsonResponse['flags'],
496
- analyticsProcessor: this.analyticsProcessor,
497
- defaultFlagHandler: this.defaultFlagHandler
498
- });
499
- if (!!!this.cache) return [3 /*break*/, 3];
500
- // @ts-ignore node-cache types are incorrect, ttl should be optional
501
- return [4 /*yield*/, this.cache.set("flags-".concat(identifier), flags)];
502
- case 2:
503
- // @ts-ignore node-cache types are incorrect, ttl should be optional
504
- _a.sent();
505
- _a.label = 3;
506
- case 3: return [2 /*return*/, flags];
507
- case 4:
508
- e_4 = _a.sent();
509
- if (this.defaultFlagHandler) {
510
- return [2 /*return*/, new models_3.Flags({
511
- flags: {},
512
- defaultFlagHandler: this.defaultFlagHandler
513
- })];
514
- }
515
- throw e_4;
516
- case 5: return [2 /*return*/];
517
- }
518
- });
519
- });
520
- };
521
- Flagsmith.prototype.buildIdentityModel = function (identifier, traits) {
522
- var traitModels = traits.map(function (trait) { return new models_2.TraitModel(trait.key, trait.value); });
523
- return new models_1.IdentityModel('0', traitModels, [], this.environment.apiKey, identifier);
524
- };
525
- return Flagsmith;
526
- }());
527
- exports.Flagsmith = Flagsmith;
528
- exports.default = Flagsmith;