flagsmith-nodejs 2.0.0-beta.2 → 2.0.0-beta.3

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 (69) hide show
  1. package/.tool-versions +1 -0
  2. package/example/server/api/index.js +5 -0
  3. package/example/server/index.js +3 -0
  4. package/package.json +3 -1
  5. package/sdk/index.ts +66 -7
  6. package/sdk/models.ts +3 -3
  7. package/tests/sdk/data/environment.json +39 -2
  8. package/tests/sdk/flagsmith.test.ts +20 -1
  9. package/.idea/flagsmith-nodejs-client.iml +0 -12
  10. package/.idea/modules.xml +0 -8
  11. package/.idea/vcs.xml +0 -6
  12. package/build/flagsmith-engine/environments/integrations/models.d.ts +0 -4
  13. package/build/flagsmith-engine/environments/integrations/models.js +0 -8
  14. package/build/flagsmith-engine/environments/models.d.ts +0 -25
  15. package/build/flagsmith-engine/environments/models.js +0 -40
  16. package/build/flagsmith-engine/environments/util.d.ts +0 -3
  17. package/build/flagsmith-engine/environments/util.js +0 -19
  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 -32
  21. package/build/flagsmith-engine/features/models.js +0 -85
  22. package/build/flagsmith-engine/features/util.d.ts +0 -3
  23. package/build/flagsmith-engine/features/util.js +0 -20
  24. package/build/flagsmith-engine/identities/models.d.ts +0 -15
  25. package/build/flagsmith-engine/identities/models.js +0 -47
  26. package/build/flagsmith-engine/identities/traits/models.d.ts +0 -5
  27. package/build/flagsmith-engine/identities/traits/models.js +0 -12
  28. package/build/flagsmith-engine/identities/util.d.ts +0 -4
  29. package/build/flagsmith-engine/identities/util.js +0 -22
  30. package/build/flagsmith-engine/index.d.ts +0 -8
  31. package/build/flagsmith-engine/index.js +0 -61
  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 -17
  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 -26
  41. package/build/flagsmith-engine/segments/constants.js +0 -31
  42. package/build/flagsmith-engine/segments/evaluators.d.ts +0 -6
  43. package/build/flagsmith-engine/segments/evaluators.js +0 -29
  44. package/build/flagsmith-engine/segments/models.d.ts +0 -31
  45. package/build/flagsmith-engine/segments/models.js +0 -83
  46. package/build/flagsmith-engine/segments/util.d.ts +0 -4
  47. package/build/flagsmith-engine/segments/util.js +0 -23
  48. package/build/flagsmith-engine/utils/collections.d.ts +0 -4
  49. package/build/flagsmith-engine/utils/collections.js +0 -16
  50. package/build/flagsmith-engine/utils/errors.d.ts +0 -2
  51. package/build/flagsmith-engine/utils/errors.js +0 -6
  52. package/build/flagsmith-engine/utils/hashing/index.d.ts +0 -9
  53. package/build/flagsmith-engine/utils/hashing/index.js +0 -54
  54. package/build/flagsmith-engine/utils/index.d.ts +0 -1
  55. package/build/flagsmith-engine/utils/index.js +0 -14
  56. package/build/index.d.ts +0 -1
  57. package/build/index.js +0 -11
  58. package/build/sdk/analytics.d.ts +0 -28
  59. package/build/sdk/analytics.js +0 -60
  60. package/build/sdk/errors.d.ts +0 -4
  61. package/build/sdk/errors.js +0 -9
  62. package/build/sdk/index.d.ts +0 -98
  63. package/build/sdk/index.js +0 -215
  64. package/build/sdk/models.d.ts +0 -55
  65. package/build/sdk/models.js +0 -102
  66. package/build/sdk/polling_manager.d.ts +0 -9
  67. package/build/sdk/polling_manager.js +0 -31
  68. package/build/sdk/utils.d.ts +0 -12
  69. package/build/sdk/utils.js +0 -45
package/.tool-versions ADDED
@@ -0,0 +1 @@
1
+ nodejs 16.14.0
@@ -29,5 +29,10 @@ module.exports = () => {
29
29
  res.json({ fontSize, checkoutV2 });
30
30
  });
31
31
 
32
+ api.get('/:user/segments', async (req, res) => {
33
+ const segments = await flagsmith.getIdentitySegments(req.params.user, { checkout_v2: 1 });
34
+ res.json(segments.map(v => v.name));
35
+ });
36
+
32
37
  return api;
33
38
  };
@@ -22,5 +22,8 @@ console.log('To get an example response for getFlags');
22
22
  console.log();
23
23
  console.log('Go to http://localhost:' + PORT + '/api/flagsmith_sample_user');
24
24
  console.log('To get an example feature state for a user');
25
+ console.log();
26
+ console.log('Go to http://localhost:' + PORT + '/api/flagsmith_sample_user/segments');
27
+ console.log('To get the segments which the user belongs to');
25
28
 
26
29
  module.exports = app;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flagsmith-nodejs",
3
- "version": "2.0.0-beta.2",
3
+ "version": "2.0.0-beta.3",
4
4
  "description": "Flagsmith lets you manage features flags and remote config across web, mobile and server side applications. Deliver true Continuous Integration. Get builds out faster. Control who has access to new features.",
5
5
  "main": "build/index.js",
6
6
  "repository": {
@@ -43,6 +43,8 @@
43
43
  "scripts": {
44
44
  "lint": "prettier --write .",
45
45
  "test": "jest --coverage --coverageReporters='text'",
46
+ "test:watch": "jest --coverage --watch --coverageReporters='text'",
47
+ "test:debug": "node --inspect-brk node_modules/.bin/jest --coverage --watch --coverageReporters='text'",
46
48
  "build": "tsc",
47
49
  "prepare": "husky install"
48
50
  },
package/sdk/index.ts CHANGED
@@ -10,6 +10,8 @@ import { FlagsmithAPIError, FlagsmithClientError } from './errors';
10
10
  import { DefaultFlag, Flags } from './models';
11
11
  import { EnvironmentDataPollingManager } from './polling_manager';
12
12
  import { generateIdentitiesData, retryFetch } from './utils';
13
+ import { SegmentModel } from '../flagsmith-engine/segments/models';
14
+ import { getIdentitySegments } from '../flagsmith-engine/segments/evaluators';
13
15
 
14
16
  const DEFAULT_API_URL = 'https://api.flagsmith.com/api/v1/';
15
17
 
@@ -20,7 +22,7 @@ export class Flagsmith {
20
22
  requestTimeoutSeconds?: number;
21
23
  enableLocalEvaluation?: boolean = false;
22
24
  environmentRefreshIntervalSeconds: number = 60;
23
- retries?: any;
25
+ retries?: number;
24
26
  enableAnalytics: boolean = false;
25
27
  defaultFlagHandler?: (featureName: string) => DefaultFlag;
26
28
 
@@ -68,7 +70,7 @@ export class Flagsmith {
68
70
  requestTimeoutSeconds?: number;
69
71
  enableLocalEvaluation?: boolean;
70
72
  environmentRefreshIntervalSeconds?: number;
71
- retries?: any;
73
+ retries?: number;
72
74
  enableAnalytics?: boolean;
73
75
  defaultFlagHandler?: (featureName: string) => DefaultFlag;
74
76
  }) {
@@ -88,11 +90,17 @@ export class Flagsmith {
88
90
  this.environmentUrl = `${this.apiUrl}environment-document/`;
89
91
 
90
92
  if (this.enableLocalEvaluation) {
93
+ if (!this.environmentKey.startsWith('ser.')) {
94
+ console.error(
95
+ 'In order to use local evaluation, please generate a server key in the environment settings page.'
96
+ );
97
+ }
91
98
  this.environmentDataPollingManager = new EnvironmentDataPollingManager(
92
99
  this,
93
100
  this.environmentRefreshIntervalSeconds
94
101
  );
95
102
  this.environmentDataPollingManager.start();
103
+ this.updateEnvironment();
96
104
  }
97
105
 
98
106
  this.analyticsProcessor = data.enableAnalytics
@@ -128,20 +136,67 @@ export class Flagsmith {
128
136
  */
129
137
  getIdentityFlags(identifier: string, traits?: { [key: string]: any }): Promise<Flags> {
130
138
  traits = traits || {};
131
- if (this.environment) {
139
+ if (this.enableLocalEvaluation) {
132
140
  return new Promise(resolve =>
133
- resolve(this.getIdentityFlagsFromDocument(identifier, traits || {}))
141
+ this.environmentPromise!.then(() => {
142
+ resolve(this.getIdentityFlagsFromDocument(identifier, traits || {}));
143
+ })
134
144
  );
135
145
  }
136
146
  return this.getIdentityFlagsFromApi(identifier, traits);
137
147
  }
138
148
 
149
+ /**
150
+ * Get the segments for the current environment for a given identity. Will also
151
+ upsert all traits to the Flagsmith API for future evaluations. Providing a
152
+ trait with a value of None will remove the trait from the identity if it exists.
153
+ *
154
+ * @param {string} identifier a unique identifier for the identity in the current
155
+ environment, e.g. email address, username, uuid
156
+ * @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
157
+ Flagsmith, e.g. {"num_orders": 10}
158
+ * @returns Segments that the given identity belongs to.
159
+ */
160
+ getIdentitySegments(
161
+ identifier: string,
162
+ traits?: { [key: string]: any }
163
+ ): Promise<SegmentModel[]> {
164
+ traits = traits || {};
165
+ if (this.enableLocalEvaluation) {
166
+ return this.environmentPromise!.then(() => {
167
+ return new Promise(resolve => {
168
+ const identityModel = this.buildIdentityModel(
169
+ identifier,
170
+ Object.keys(traits || {}).map(key => ({
171
+ key,
172
+ value: traits?.[key]
173
+ }))
174
+ );
175
+
176
+ const segments = getIdentitySegments(this.environment, identityModel);
177
+ return resolve(segments);
178
+ });
179
+ });
180
+ }
181
+ console.error('This function is only permitted with local evaluation.');
182
+ return Promise.resolve([]);
183
+ }
184
+
139
185
  /**
140
186
  * Updates the environment state for local flag evaluation.
187
+ * Sets a local promise to prevent race conditions in getIdentityFlags / getIdentitySegments.
141
188
  * You only need to call this if you wish to bypass environmentRefreshIntervalSeconds.
142
189
  */
143
190
  async updateEnvironment() {
144
- this.environment = await this.getEnvironmentFromApi();
191
+ const request = this.getEnvironmentFromApi();
192
+ if (!this.environmentPromise) {
193
+ this.environmentPromise = request.then(res => {
194
+ this.environment = res;
195
+ });
196
+ await this.environmentPromise;
197
+ } else {
198
+ this.environment = await request;
199
+ }
145
200
  }
146
201
 
147
202
  private async getJSONResponse(
@@ -149,7 +204,7 @@ export class Flagsmith {
149
204
  method: string,
150
205
  body?: { [key: string]: any }
151
206
  ): Promise<any> {
152
- const headers: { [key: string]: any } = {'Content-Type': 'application/json'};
207
+ const headers: { [key: string]: any } = { 'Content-Type': 'application/json' };
153
208
  if (this.environmentKey) {
154
209
  headers['X-Environment-Key'] = this.environmentKey as string;
155
210
  }
@@ -182,6 +237,11 @@ export class Flagsmith {
182
237
  return data.json();
183
238
  }
184
239
 
240
+ /**
241
+ * This promise ensures that the environment is retrieved before attempting to locally evaluate.
242
+ */
243
+ private environmentPromise: Promise<any> | undefined;
244
+
185
245
  private async getEnvironmentFromApi() {
186
246
  const environment_data = await this.getJSONResponse(this.environmentUrl, 'GET');
187
247
  return buildEnvironmentModel(environment_data);
@@ -267,4 +327,3 @@ export class Flagsmith {
267
327
  }
268
328
 
269
329
  export default Flagsmith;
270
- // export = Flagsmith;
package/sdk/models.ts CHANGED
@@ -123,9 +123,9 @@ export class Flags {
123
123
  if (this.defaultFlagHandler) {
124
124
  return this.defaultFlagHandler(featureName);
125
125
  }
126
- throw new FlagsmithClientError(
127
- `Feature does not exist: ${featureName}, implement defaultFlagHandler to handle this case.`
128
- );
126
+
127
+ return { enabled: false, isDefault: true, value: undefined };
128
+
129
129
  }
130
130
 
131
131
  if (this.analyticsProcessor && flag.featureId) {
@@ -11,7 +11,44 @@
11
11
  },
12
12
  "id": 1,
13
13
  "hide_disabled_flags": false,
14
- "segments": []
14
+ "segments": [
15
+ {
16
+ "name": "regular_segment",
17
+ "feature_states": [
18
+ {
19
+ "feature_state_value": "segment_override",
20
+ "multivariate_feature_state_values": [],
21
+ "django_id": 81027,
22
+ "feature": {
23
+ "name": "some_feature",
24
+ "type": "STANDARD",
25
+ "id": 1
26
+ },
27
+ "enabled": false
28
+ }
29
+ ],
30
+ "id": 1,
31
+ "rules": [
32
+ {
33
+ "type": "ALL",
34
+ "conditions": [],
35
+ "rules": [
36
+ {
37
+ "type": "ANY",
38
+ "conditions": [
39
+ {
40
+ "value": "40",
41
+ "property_": "age",
42
+ "operator": "LESS_THAN"
43
+ }
44
+ ],
45
+ "rules": []
46
+ }
47
+ ]
48
+ }
49
+ ]
50
+ }
51
+ ]
15
52
  },
16
53
  "segment_overrides": [],
17
54
  "id": 1,
@@ -30,4 +67,4 @@
30
67
  "enabled": true
31
68
  }
32
69
  ]
33
- }
70
+ }
@@ -14,8 +14,10 @@ beforeEach(() => {
14
14
  });
15
15
 
16
16
  test('test_flagsmith_starts_polling_manager_on_init_if_enabled', () => {
17
+ // @ts-ignore
18
+ fetch.mockReturnValue(Promise.resolve(new Response(environmentJSON())));
17
19
  new Flagsmith({
18
- environmentKey: 'key',
20
+ environmentKey: 'ser.key',
19
21
  enableLocalEvaluation: true
20
22
  });
21
23
  expect(EnvironmentDataPollingManager).toBeCalled();
@@ -31,11 +33,28 @@ test('test_update_environment_sets_environment', async () => {
31
33
  // @ts-ignore
32
34
  flg.environment.featureStates[0].featurestateUUID = undefined;
33
35
  // @ts-ignore
36
+ flg.environment.project.segments[0].featureStates[0].featurestateUUID = undefined;
37
+ // @ts-ignore
34
38
  const model = environmentModel(JSON.parse(environmentJSON()));
35
39
  // @ts-ignore
36
40
  model.featureStates[0].featurestateUUID = undefined;
41
+ // @ts-ignore
42
+ model.project.segments[0].featureStates[0].featurestateUUID = undefined;
37
43
  expect(flg.environment).toStrictEqual(model);
38
44
  });
45
+
46
+ test('test_get_identity_segments', async () => {
47
+ // @ts-ignore
48
+ fetch.mockReturnValue(Promise.resolve(new Response(environmentJSON())));
49
+ const flg = new Flagsmith({
50
+ environmentKey: 'ser.key',
51
+ enableLocalEvaluation: true
52
+ });
53
+ const segments = await flg.getIdentitySegments('user', { age: 21 });
54
+ expect(segments[0].name).toEqual('regular_segment');
55
+ const segments2 = await flg.getIdentitySegments('user', { age: 41 });
56
+ expect(segments2.length).toEqual(0);
57
+ });
39
58
  test('test_get_environment_flags_calls_api_when_no_local_environment', async () => {
40
59
  // @ts-ignore
41
60
  fetch.mockReturnValue(Promise.resolve(new Response(flagsJSON())));
@@ -1,12 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <module type="WEB_MODULE" version="4">
3
- <component name="NewModuleRootManager">
4
- <content url="file://$MODULE_DIR$">
5
- <excludeFolder url="file://$MODULE_DIR$/temp" />
6
- <excludeFolder url="file://$MODULE_DIR$/.tmp" />
7
- <excludeFolder url="file://$MODULE_DIR$/tmp" />
8
- </content>
9
- <orderEntry type="inheritedJdk" />
10
- <orderEntry type="sourceFolder" forTests="false" />
11
- </component>
12
- </module>
package/.idea/modules.xml DELETED
@@ -1,8 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="ProjectModuleManager">
4
- <modules>
5
- <module fileurl="file://$PROJECT_DIR$/.idea/flagsmith-nodejs-client.iml" filepath="$PROJECT_DIR$/.idea/flagsmith-nodejs-client.iml" />
6
- </modules>
7
- </component>
8
- </project>
package/.idea/vcs.xml DELETED
@@ -1,6 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="VcsDirectoryMappings">
4
- <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
- </component>
6
- </project>
@@ -1,4 +0,0 @@
1
- export declare class IntegrationModel {
2
- api_key?: string;
3
- base_url?: string;
4
- }
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.IntegrationModel = void 0;
4
- class IntegrationModel {
5
- api_key = undefined;
6
- base_url = undefined;
7
- }
8
- exports.IntegrationModel = IntegrationModel;
@@ -1,25 +0,0 @@
1
- import { FeatureStateModel } from '../features/models';
2
- import { ProjectModel } from '../projects/models';
3
- import { IntegrationModel } from './integrations/models';
4
- export declare class EnvironmentAPIKeyModel {
5
- id: number;
6
- key: string;
7
- createdAt: number;
8
- name: string;
9
- clientApiKey: string;
10
- expiresAt?: number;
11
- active: boolean;
12
- constructor(id: number, key: string, createdAt: number, name: string, clientApiKey: string, expiresAt?: number);
13
- isValid(): boolean;
14
- }
15
- export declare class EnvironmentModel {
16
- id: number;
17
- apiKey: string;
18
- project: ProjectModel;
19
- featureStates: FeatureStateModel[];
20
- amplitude_config?: IntegrationModel;
21
- segment_config?: IntegrationModel;
22
- mixpanel_config?: IntegrationModel;
23
- heap_config?: IntegrationModel;
24
- constructor(id: number, apiKey: string, project: ProjectModel);
25
- }
@@ -1,40 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EnvironmentModel = exports.EnvironmentAPIKeyModel = void 0;
4
- class EnvironmentAPIKeyModel {
5
- id;
6
- key;
7
- createdAt;
8
- name;
9
- clientApiKey;
10
- expiresAt;
11
- active = true;
12
- constructor(id, key, createdAt, name, clientApiKey, expiresAt) {
13
- this.id = id;
14
- this.key = key;
15
- this.createdAt = createdAt;
16
- this.name = name;
17
- this.clientApiKey = clientApiKey;
18
- this.expiresAt = expiresAt;
19
- }
20
- isValid() {
21
- return !!this.active && (!this.expiresAt || this.expiresAt > Date.now());
22
- }
23
- }
24
- exports.EnvironmentAPIKeyModel = EnvironmentAPIKeyModel;
25
- class EnvironmentModel {
26
- id;
27
- apiKey;
28
- project;
29
- featureStates = [];
30
- amplitude_config;
31
- segment_config;
32
- mixpanel_config;
33
- heap_config;
34
- constructor(id, apiKey, project) {
35
- this.id = id;
36
- this.apiKey = apiKey;
37
- this.project = project;
38
- }
39
- }
40
- exports.EnvironmentModel = EnvironmentModel;
@@ -1,3 +0,0 @@
1
- import { EnvironmentAPIKeyModel, EnvironmentModel } from './models';
2
- export declare function buildEnvironmentModel(environmentJSON: any): EnvironmentModel;
3
- export declare function buildEnvironmentAPIKeyModel(apiKeyJSON: any): EnvironmentAPIKeyModel;
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildEnvironmentAPIKeyModel = exports.buildEnvironmentModel = void 0;
4
- const util_1 = require("../features/util");
5
- const util_2 = require("../projects/util");
6
- const models_1 = require("./models");
7
- function buildEnvironmentModel(environmentJSON) {
8
- const project = (0, util_2.buildProjectModel)(environmentJSON.project);
9
- const featureStates = environmentJSON.feature_states.map((fs) => (0, util_1.buildFeatureStateModel)(fs));
10
- const environmentModel = new models_1.EnvironmentModel(environmentJSON.id, environmentJSON.api_key, project);
11
- environmentModel.featureStates = featureStates;
12
- return environmentModel;
13
- }
14
- exports.buildEnvironmentModel = buildEnvironmentModel;
15
- function buildEnvironmentAPIKeyModel(apiKeyJSON) {
16
- const model = new models_1.EnvironmentAPIKeyModel(apiKeyJSON.id, apiKeyJSON.key, Date.parse(apiKeyJSON.created_at), apiKeyJSON.name, apiKeyJSON.client_api_key);
17
- return model;
18
- }
19
- exports.buildEnvironmentAPIKeyModel = buildEnvironmentAPIKeyModel;
@@ -1,4 +0,0 @@
1
- export declare const CONSTANTS: {
2
- STANDARD: string;
3
- MULTIVARIATE: string;
4
- };
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CONSTANTS = void 0;
4
- exports.CONSTANTS = {
5
- STANDARD: 'STANDARD',
6
- MULTIVARIATE: 'MULTIVARIATE'
7
- };
@@ -1,32 +0,0 @@
1
- export declare class FeatureModel {
2
- id: number;
3
- name: string;
4
- type: string;
5
- constructor(id: number, name: string, type: string);
6
- eq(other: FeatureModel): boolean;
7
- }
8
- export declare class MultivariateFeatureOptionModel {
9
- value: any;
10
- id: number | undefined;
11
- constructor(value: any, id?: number);
12
- }
13
- export declare class MultivariateFeatureStateValueModel {
14
- multivariateFeatureOption: MultivariateFeatureOptionModel;
15
- percentageAllocation: number;
16
- id: number;
17
- mvFsValueUuid: string;
18
- constructor(multivariate_feature_option: MultivariateFeatureOptionModel, percentage_allocation: number, id: number, mvFsValueUuid?: string);
19
- }
20
- export declare class FeatureStateModel {
21
- feature: FeatureModel;
22
- enabled: boolean;
23
- djangoID: number;
24
- featurestateUUID: string;
25
- private value;
26
- multivariateFeatureStateValues: MultivariateFeatureStateValueModel[];
27
- constructor(feature: FeatureModel, enabled: boolean, djangoID: number, value?: any, featurestateUuid?: string);
28
- setValue(value: any): void;
29
- getValue(identityId?: number | string): any;
30
- get_feature_state_value(): any;
31
- getMultivariateValue(identityID: number | string): any;
32
- }
@@ -1,85 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FeatureStateModel = exports.MultivariateFeatureStateValueModel = exports.MultivariateFeatureOptionModel = exports.FeatureModel = void 0;
4
- const uuid_1 = require("uuid");
5
- const hashing_1 = require("../utils/hashing");
6
- class FeatureModel {
7
- id;
8
- name;
9
- type;
10
- constructor(id, name, type) {
11
- this.id = id;
12
- this.name = name;
13
- this.type = type;
14
- }
15
- eq(other) {
16
- return !!other && this.id === other.id;
17
- }
18
- }
19
- exports.FeatureModel = FeatureModel;
20
- class MultivariateFeatureOptionModel {
21
- value;
22
- id;
23
- constructor(value, id) {
24
- this.value = value;
25
- this.id = id;
26
- }
27
- }
28
- exports.MultivariateFeatureOptionModel = MultivariateFeatureOptionModel;
29
- class MultivariateFeatureStateValueModel {
30
- multivariateFeatureOption;
31
- percentageAllocation;
32
- id;
33
- mvFsValueUuid = (0, uuid_1.v4)();
34
- constructor(multivariate_feature_option, percentage_allocation, id, mvFsValueUuid) {
35
- this.id = id;
36
- this.percentageAllocation = percentage_allocation;
37
- this.multivariateFeatureOption = multivariate_feature_option;
38
- this.mvFsValueUuid = mvFsValueUuid || this.mvFsValueUuid;
39
- }
40
- }
41
- exports.MultivariateFeatureStateValueModel = MultivariateFeatureStateValueModel;
42
- class FeatureStateModel {
43
- feature;
44
- enabled;
45
- djangoID;
46
- featurestateUUID = (0, uuid_1.v4)();
47
- value;
48
- multivariateFeatureStateValues = [];
49
- constructor(feature, enabled, djangoID, value, featurestateUuid = (0, uuid_1.v4)()) {
50
- this.feature = feature;
51
- this.enabled = enabled;
52
- this.djangoID = djangoID;
53
- this.value = value;
54
- this.featurestateUUID = featurestateUuid;
55
- }
56
- setValue(value) {
57
- this.value = value;
58
- }
59
- getValue(identityId) {
60
- if (!!identityId && this.multivariateFeatureStateValues.length > 0) {
61
- return this.getMultivariateValue(identityId);
62
- }
63
- return this.value;
64
- }
65
- get_feature_state_value() {
66
- return this.getValue();
67
- }
68
- getMultivariateValue(identityID) {
69
- const percentageValue = (0, hashing_1.getHashedPercentateForObjIds)([
70
- this.djangoID || this.featurestateUUID,
71
- identityID
72
- ]);
73
- let startPercentage = 0;
74
- const sortedF = this.multivariateFeatureStateValues.sort((a, b) => !!(a.id && b.id) ? a.id - b.id : a.mvFsValueUuid > b.mvFsValueUuid ? -1 : 1);
75
- for (const myValue of sortedF) {
76
- const limit = myValue.percentageAllocation + startPercentage;
77
- if (startPercentage <= percentageValue && percentageValue < limit) {
78
- return myValue.multivariateFeatureOption.value;
79
- }
80
- startPercentage = limit;
81
- }
82
- return this.value;
83
- }
84
- }
85
- exports.FeatureStateModel = FeatureStateModel;
@@ -1,3 +0,0 @@
1
- import { FeatureModel, FeatureStateModel } from './models';
2
- export declare function buildFeatureModel(featuresModelJSON: any): FeatureModel;
3
- export declare function buildFeatureStateModel(featuresStateModelJSON: any): FeatureStateModel;
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildFeatureStateModel = exports.buildFeatureModel = void 0;
4
- const models_1 = require("./models");
5
- function buildFeatureModel(featuresModelJSON) {
6
- return new models_1.FeatureModel(featuresModelJSON.id, featuresModelJSON.name, featuresModelJSON.type);
7
- }
8
- exports.buildFeatureModel = buildFeatureModel;
9
- function buildFeatureStateModel(featuresStateModelJSON) {
10
- const featureStateModel = new models_1.FeatureStateModel(buildFeatureModel(featuresStateModelJSON.feature), featuresStateModelJSON.enabled, featuresStateModelJSON.django_id, featuresStateModelJSON.feature_state_value, featuresStateModelJSON.uuid);
11
- const multivariateFeatureStateValues = featuresStateModelJSON.multivariate_feature_state_values
12
- ? featuresStateModelJSON.multivariate_feature_state_values.map((fsv) => {
13
- const featureOption = new models_1.MultivariateFeatureOptionModel(fsv.multivariate_feature_option.value, fsv.multivariate_feature_option.id);
14
- return new models_1.MultivariateFeatureStateValueModel(featureOption, fsv.percentage_allocation, fsv.id);
15
- })
16
- : [];
17
- featureStateModel.multivariateFeatureStateValues = multivariateFeatureStateValues;
18
- return featureStateModel;
19
- }
20
- exports.buildFeatureStateModel = buildFeatureStateModel;
@@ -1,15 +0,0 @@
1
- import { IdentityFeaturesList } from '../utils/collections';
2
- import { TraitModel } from './traits/models';
3
- export declare class IdentityModel {
4
- identifier: string;
5
- environmentApiKey: string;
6
- createdDate?: number;
7
- identityFeatures: IdentityFeaturesList;
8
- identityTraits: TraitModel[];
9
- identityUuid: string;
10
- djangoID: number | undefined;
11
- constructor(created_date: string, identityTraits: TraitModel[], identityFeatures: IdentityFeaturesList, environmentApiKey: string, identifier: string, identityUuid?: string);
12
- get compositeKey(): string;
13
- static generateCompositeKey(env_key: string, identifier: string): string;
14
- update_traits(traits: TraitModel[]): void;
15
- }
@@ -1,47 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.IdentityModel = void 0;
4
- const collections_1 = require("../utils/collections");
5
- const { v4: uuidv4 } = require('uuid');
6
- class IdentityModel {
7
- identifier;
8
- environmentApiKey;
9
- createdDate;
10
- identityFeatures;
11
- identityTraits;
12
- identityUuid;
13
- djangoID;
14
- constructor(created_date, identityTraits, identityFeatures, environmentApiKey, identifier, identityUuid) {
15
- this.identityUuid = identityUuid || uuidv4();
16
- this.createdDate = Date.parse(created_date) || Date.now();
17
- this.identityTraits = identityTraits;
18
- this.identityFeatures = new collections_1.IdentityFeaturesList(...identityFeatures);
19
- this.environmentApiKey = environmentApiKey;
20
- this.identifier = identifier;
21
- }
22
- get compositeKey() {
23
- return IdentityModel.generateCompositeKey(this.environmentApiKey, this.identifier);
24
- }
25
- static generateCompositeKey(env_key, identifier) {
26
- return `${env_key}_${identifier}`;
27
- }
28
- update_traits(traits) {
29
- const existingTraits = new Map();
30
- for (const trait of this.identityTraits) {
31
- existingTraits.set(trait.traitKey, trait);
32
- }
33
- for (const trait of traits) {
34
- if (!!trait.traitValue) {
35
- existingTraits.set(trait.traitKey, trait);
36
- }
37
- else {
38
- existingTraits.delete(trait.traitKey);
39
- }
40
- }
41
- this.identityTraits = [];
42
- for (const [k, v] of existingTraits.entries()) {
43
- this.identityTraits.push(v);
44
- }
45
- }
46
- }
47
- exports.IdentityModel = IdentityModel;
@@ -1,5 +0,0 @@
1
- export declare class TraitModel {
2
- traitKey: string;
3
- traitValue: any;
4
- constructor(key: string, value: any);
5
- }