@microsoft/feature-management 1.0.0-preview.1 → 2.0.0-preview.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 (56) hide show
  1. package/README.md +2 -0
  2. package/dist/commonjs/common/targetingEvaluator.js +119 -0
  3. package/dist/commonjs/common/targetingEvaluator.js.map +1 -0
  4. package/dist/commonjs/featureManager.js +247 -0
  5. package/dist/commonjs/featureManager.js.map +1 -0
  6. package/dist/commonjs/featureProvider.js +43 -0
  7. package/dist/commonjs/featureProvider.js.map +1 -0
  8. package/{dist-esm → dist/commonjs}/filter/TargetingFilter.js +13 -47
  9. package/dist/commonjs/filter/TargetingFilter.js.map +1 -0
  10. package/dist/commonjs/filter/TimeWindowFilter.js +22 -0
  11. package/dist/commonjs/filter/TimeWindowFilter.js.map +1 -0
  12. package/dist/commonjs/index.js +18 -0
  13. package/dist/commonjs/index.js.map +1 -0
  14. package/dist/commonjs/model.js +12 -0
  15. package/dist/commonjs/model.js.map +1 -0
  16. package/dist/commonjs/variant/Variant.js +15 -0
  17. package/dist/commonjs/variant/Variant.js.map +1 -0
  18. package/dist/commonjs/version.js +8 -0
  19. package/dist/commonjs/version.js.map +1 -0
  20. package/dist/esm/common/targetingEvaluator.js +115 -0
  21. package/dist/esm/common/targetingEvaluator.js.map +1 -0
  22. package/dist/esm/featureManager.js +244 -0
  23. package/dist/esm/featureManager.js.map +1 -0
  24. package/{dist-esm → dist/esm}/featureProvider.js +7 -4
  25. package/dist/esm/featureProvider.js.map +1 -0
  26. package/dist/esm/filter/TargetingFilter.js +68 -0
  27. package/dist/esm/filter/TargetingFilter.js.map +1 -0
  28. package/{dist-esm → dist/esm}/filter/TimeWindowFilter.js +4 -2
  29. package/dist/esm/filter/TimeWindowFilter.js.map +1 -0
  30. package/dist/esm/index.js +4 -0
  31. package/dist/esm/index.js.map +1 -0
  32. package/dist/esm/model.js +9 -0
  33. package/dist/esm/model.js.map +1 -0
  34. package/dist/esm/variant/Variant.js +13 -0
  35. package/dist/esm/variant/Variant.js.map +1 -0
  36. package/dist/esm/version.js +6 -0
  37. package/dist/esm/version.js.map +1 -0
  38. package/dist/umd/index.js +504 -0
  39. package/dist/umd/index.js.map +1 -0
  40. package/package.json +14 -19
  41. package/types/index.d.ts +195 -15
  42. package/dist/index.js +0 -234
  43. package/dist/index.js.map +0 -1
  44. package/dist-esm/featureManager.js +0 -60
  45. package/dist-esm/featureManager.js.map +0 -1
  46. package/dist-esm/featureProvider.js.map +0 -1
  47. package/dist-esm/filter/FeatureFilter.js +0 -4
  48. package/dist-esm/filter/FeatureFilter.js.map +0 -1
  49. package/dist-esm/filter/TargetingFilter.js.map +0 -1
  50. package/dist-esm/filter/TimeWindowFilter.js.map +0 -1
  51. package/dist-esm/gettable.js +0 -6
  52. package/dist-esm/gettable.js.map +0 -1
  53. package/dist-esm/index.js +0 -5
  54. package/dist-esm/index.js.map +0 -1
  55. package/dist-esm/model.js +0 -12
  56. package/dist-esm/model.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
@@ -0,0 +1,9 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ // Feature Management Section fed into feature manager.
4
+ // Converted from https://github.com/Azure/AppConfiguration/blob/main/docs/FeatureManagement/FeatureManagement.v1.0.0.schema.json
5
+ const FEATURE_MANAGEMENT_KEY = "feature_management";
6
+ const FEATURE_FLAGS_KEY = "feature_flags";
7
+
8
+ export { FEATURE_FLAGS_KEY, FEATURE_MANAGEMENT_KEY };
9
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sources":["../../src/model.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n// Converted from:\n// https://github.com/Azure/AppConfiguration/blob/6e544296a5607f922a423df165f60801717c7800/docs/FeatureManagement/FeatureFlag.v2.0.0.schema.json\n\n/**\n * A feature flag is a named property that can be toggled to enable or disable some feature of an application.\n */\nexport interface FeatureFlag {\n /**\n * An ID used to uniquely identify and reference the feature.\n */\n id: string;\n /**\n * A description of the feature.\n */\n description?: string;\n /**\n * A display name for the feature to use for display rather than the ID.\n */\n display_name?: string;\n /**\n * A feature is OFF if enabled is false. If enabled is true, then the feature is ON if there are no conditions (null or empty) or if the conditions are satisfied.\n */\n enabled?: boolean;\n /**\n * The declaration of conditions used to dynamically enable the feature.\n */\n conditions?: FeatureEnablementConditions;\n /**\n * The list of variants defined for this feature. A variant represents a configuration value of a feature flag that can be a string, a number, a boolean, or a JSON object.\n */\n variants?: VariantDefinition[];\n /**\n * Determines how variants should be allocated for the feature to various users.\n */\n allocation?: VariantAllocation;\n /**\n * The declaration of options used to configure telemetry for this feature.\n */\n telemetry?: TelemetryOptions\n}\n\n/**\n* The declaration of conditions used to dynamically enable the feature\n*/\ninterface FeatureEnablementConditions {\n /**\n * Determines whether any or all registered client filters must be evaluated as true for the feature to be considered enabled.\n */\n requirement_type?: RequirementType;\n /**\n * Filters that must run on the client and be evaluated as true for the feature to be considered enabled.\n */\n client_filters?: ClientFilter[];\n}\n\nexport type RequirementType = \"Any\" | \"All\";\n\ninterface ClientFilter {\n /**\n * The name used to refer to a client filter.\n */\n name: string;\n /**\n * Parameters for a given client filter. A client filter can require any set of parameters of any type.\n */\n parameters?: Record<string, unknown>;\n}\n\nexport interface VariantDefinition {\n /**\n * The name used to refer to a feature variant.\n */\n name: string;\n /**\n * The configuration value for this feature variant.\n */\n configuration_value?: unknown;\n /**\n * Overrides the enabled state of the feature if the given variant is assigned. Does not override the state if value is None.\n */\n status_override?: \"None\" | \"Enabled\" | \"Disabled\";\n}\n\n/**\n* Determines how variants should be allocated for the feature to various users.\n*/\ninterface VariantAllocation {\n /**\n * Specifies which variant should be used when the feature is considered disabled.\n */\n default_when_disabled?: string;\n /**\n * Specifies which variant should be used when the feature is considered enabled and no other allocation rules are applicable.\n */\n default_when_enabled?: string;\n /**\n * A list of objects, each containing a variant name and list of users for whom that variant should be used.\n */\n user?: UserAllocation[];\n /**\n * A list of objects, each containing a variant name and list of groups for which that variant should be used.\n */\n group?: GroupAllocation[];\n /**\n * A list of objects, each containing a variant name and percentage range for which that variant should be used.\n */\n percentile?: PercentileAllocation[]\n /**\n * The value percentile calculations are based on. The calculated percentile is consistent across features for a given user if the same nonempty seed is used.\n */\n seed?: string;\n}\n\ninterface UserAllocation {\n /**\n * The name of the variant to use if the user allocation matches the current user.\n */\n variant: string;\n /**\n * Collection of users where if any match the current user, the variant specified in the user allocation is used.\n */\n users: string[];\n}\n\ninterface GroupAllocation {\n /**\n * The name of the variant to use if the group allocation matches a group the current user is in.\n */\n variant: string;\n /**\n * Collection of groups where if the current user is in any of these groups, the variant specified in the group allocation is used.\n */\n groups: string[];\n}\n\ninterface PercentileAllocation {\n /**\n * The name of the variant to use if the calculated percentile for the current user falls in the provided range.\n */\n variant: string;\n /**\n * The lower end of the percentage range for which this variant will be used.\n */\n from: number;\n /**\n * The upper end of the percentage range for which this variant will be used.\n */\n to: number;\n}\n\n/**\n* The declaration of options used to configure telemetry for this feature.\n*/\ninterface TelemetryOptions {\n /**\n * Indicates if telemetry is enabled.\n */\n enabled?: boolean;\n /**\n * A container for metadata that should be bundled with flag telemetry.\n */\n metadata?: Record<string, string>;\n}\n\n// Feature Management Section fed into feature manager.\n// Converted from https://github.com/Azure/AppConfiguration/blob/main/docs/FeatureManagement/FeatureManagement.v1.0.0.schema.json\n\nexport const FEATURE_MANAGEMENT_KEY = \"feature_management\";\nexport const FEATURE_FLAGS_KEY = \"feature_flags\";\n\nexport interface FeatureManagementConfiguration {\n feature_management: FeatureManagement\n}\n\n/**\n * Declares feature management configuration.\n */\nexport interface FeatureManagement {\n feature_flags: FeatureFlag[];\n}\n"],"names":[],"mappings":"AAAA;AACA;AAsKA;AACA;AAEO,MAAM,sBAAsB,GAAG,qBAAqB;AACpD,MAAM,iBAAiB,GAAG;;;;"}
@@ -0,0 +1,13 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ class Variant {
4
+ name;
5
+ configuration;
6
+ constructor(name, configuration) {
7
+ this.name = name;
8
+ this.configuration = configuration;
9
+ }
10
+ }
11
+
12
+ export { Variant };
13
+ //# sourceMappingURL=Variant.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Variant.js","sources":["../../../src/variant/Variant.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport class Variant {\n constructor(\n public name: string,\n public configuration: unknown\n ) {}\n}\n"],"names":[],"mappings":"AAAA;AACA;MAEa,OAAO,CAAA;AAEL,IAAA,IAAA,CAAA;AACA,IAAA,aAAA,CAAA;IAFX,WACW,CAAA,IAAY,EACZ,aAAsB,EAAA;QADtB,IAAI,CAAA,IAAA,GAAJ,IAAI,CAAQ;QACZ,IAAa,CAAA,aAAA,GAAb,aAAa,CAAS;KAC7B;AACP;;;;"}
@@ -0,0 +1,6 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ const VERSION = "2.0.0-preview.1";
4
+
5
+ export { VERSION };
6
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sources":["../../src/version.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport const VERSION = \"2.0.0-preview.1\";\n"],"names":[],"mappings":"AAAA;AACA;AAEO,MAAM,OAAO,GAAG;;;;"}
@@ -0,0 +1,504 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.FeatureManagement = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ // Copyright (c) Microsoft Corporation.
8
+ // Licensed under the MIT license.
9
+ class TimeWindowFilter {
10
+ name = "Microsoft.TimeWindow";
11
+ evaluate(context) {
12
+ const { featureName, parameters } = context;
13
+ const startTime = parameters.Start !== undefined ? new Date(parameters.Start) : undefined;
14
+ const endTime = parameters.End !== undefined ? new Date(parameters.End) : undefined;
15
+ if (startTime === undefined && endTime === undefined) {
16
+ // If neither start nor end time is specified, then the filter is not applicable.
17
+ console.warn(`The ${this.name} feature filter is not valid for feature ${featureName}. It must specify either 'Start', 'End', or both.`);
18
+ return false;
19
+ }
20
+ const now = new Date();
21
+ return (startTime === undefined || startTime <= now) && (endTime === undefined || now < endTime);
22
+ }
23
+ }
24
+
25
+ // Copyright (c) Microsoft Corporation.
26
+ // Licensed under the MIT license.
27
+ /**
28
+ * Determines if the user is part of the audience, based on the user id and the percentage range.
29
+ *
30
+ * @param userId user id from app context
31
+ * @param hint hint string to be included in the context id
32
+ * @param from percentage range start
33
+ * @param to percentage range end
34
+ * @returns true if the user is part of the audience, false otherwise
35
+ */
36
+ async function isTargetedPercentile(userId, hint, from, to) {
37
+ if (from < 0 || from > 100) {
38
+ throw new Error("The 'from' value must be between 0 and 100.");
39
+ }
40
+ if (to < 0 || to > 100) {
41
+ throw new Error("The 'to' value must be between 0 and 100.");
42
+ }
43
+ if (from > to) {
44
+ throw new Error("The 'from' value cannot be larger than the 'to' value.");
45
+ }
46
+ const audienceContextId = constructAudienceContextId(userId, hint);
47
+ // Cryptographic hashing algorithms ensure adequate entropy across hash values.
48
+ const contextMarker = await stringToUint32(audienceContextId);
49
+ const contextPercentage = (contextMarker / 0xFFFFFFFF) * 100;
50
+ // Handle edge case of exact 100 bucket
51
+ if (to === 100) {
52
+ return contextPercentage >= from;
53
+ }
54
+ return contextPercentage >= from && contextPercentage < to;
55
+ }
56
+ /**
57
+ * Determines if the user is part of the audience, based on the groups they belong to.
58
+ *
59
+ * @param sourceGroups user groups from app context
60
+ * @param targetedGroups targeted groups from feature configuration
61
+ * @returns true if the user is part of the audience, false otherwise
62
+ */
63
+ function isTargetedGroup(sourceGroups, targetedGroups) {
64
+ if (sourceGroups === undefined) {
65
+ return false;
66
+ }
67
+ return sourceGroups.some(group => targetedGroups.includes(group));
68
+ }
69
+ /**
70
+ * Determines if the user is part of the audience, based on the user id.
71
+ * @param userId user id from app context
72
+ * @param users targeted users from feature configuration
73
+ * @returns true if the user is part of the audience, false otherwise
74
+ */
75
+ function isTargetedUser(userId, users) {
76
+ if (userId === undefined) {
77
+ return false;
78
+ }
79
+ return users.includes(userId);
80
+ }
81
+ /**
82
+ * Constructs the context id for the audience.
83
+ * The context id is used to determine if the user is part of the audience for a feature.
84
+ *
85
+ * @param userId userId from app context
86
+ * @param hint hint string to be included in the context id
87
+ * @returns a string that represents the context id for the audience
88
+ */
89
+ function constructAudienceContextId(userId, hint) {
90
+ return `${userId ?? ""}\n${hint}`;
91
+ }
92
+ /**
93
+ * Converts a string to a uint32 in little-endian encoding.
94
+ * @param str the string to convert.
95
+ * @returns a uint32 value.
96
+ */
97
+ async function stringToUint32(str) {
98
+ let crypto;
99
+ // Check for browser environment
100
+ if (typeof window !== "undefined" && window.crypto && window.crypto.subtle) {
101
+ crypto = window.crypto;
102
+ }
103
+ // Check for Node.js environment
104
+ else if (typeof global !== "undefined" && global.crypto) {
105
+ crypto = global.crypto;
106
+ }
107
+ // Fallback to native Node.js crypto module
108
+ else {
109
+ try {
110
+ if (typeof module !== "undefined" && module.exports) {
111
+ crypto = require("crypto");
112
+ }
113
+ else {
114
+ crypto = await import('crypto');
115
+ }
116
+ }
117
+ catch (error) {
118
+ console.error("Failed to load the crypto module:", error.message);
119
+ throw error;
120
+ }
121
+ }
122
+ // In the browser, use crypto.subtle.digest
123
+ if (crypto.subtle) {
124
+ const data = new TextEncoder().encode(str);
125
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
126
+ const dataView = new DataView(hashBuffer);
127
+ const uint32 = dataView.getUint32(0, true);
128
+ return uint32;
129
+ }
130
+ // In Node.js, use the crypto module's hash function
131
+ else {
132
+ const hash = crypto.createHash("sha256").update(str).digest();
133
+ const uint32 = hash.readUInt32LE(0);
134
+ return uint32;
135
+ }
136
+ }
137
+
138
+ // Copyright (c) Microsoft Corporation.
139
+ // Licensed under the MIT license.
140
+ class TargetingFilter {
141
+ name = "Microsoft.Targeting";
142
+ async evaluate(context, appContext) {
143
+ const { featureName, parameters } = context;
144
+ TargetingFilter.#validateParameters(parameters);
145
+ if (appContext === undefined) {
146
+ throw new Error("The app context is required for targeting filter.");
147
+ }
148
+ if (parameters.Audience.Exclusion !== undefined) {
149
+ // check if the user is in the exclusion list
150
+ if (appContext?.userId !== undefined &&
151
+ parameters.Audience.Exclusion.Users !== undefined &&
152
+ parameters.Audience.Exclusion.Users.includes(appContext.userId)) {
153
+ return false;
154
+ }
155
+ // check if the user is in a group within exclusion list
156
+ if (appContext?.groups !== undefined &&
157
+ parameters.Audience.Exclusion.Groups !== undefined) {
158
+ for (const excludedGroup of parameters.Audience.Exclusion.Groups) {
159
+ if (appContext.groups.includes(excludedGroup)) {
160
+ return false;
161
+ }
162
+ }
163
+ }
164
+ }
165
+ // check if the user is being targeted directly
166
+ if (appContext?.userId !== undefined &&
167
+ parameters.Audience.Users !== undefined &&
168
+ parameters.Audience.Users.includes(appContext.userId)) {
169
+ return true;
170
+ }
171
+ // check if the user is in a group that is being targeted
172
+ if (appContext?.groups !== undefined &&
173
+ parameters.Audience.Groups !== undefined) {
174
+ for (const group of parameters.Audience.Groups) {
175
+ if (appContext.groups.includes(group.Name)) {
176
+ const hint = `${featureName}\n${group.Name}`;
177
+ if (await isTargetedPercentile(appContext.userId, hint, 0, group.RolloutPercentage)) {
178
+ return true;
179
+ }
180
+ }
181
+ }
182
+ }
183
+ // check if the user is being targeted by a default rollout percentage
184
+ const hint = featureName;
185
+ return isTargetedPercentile(appContext?.userId, hint, 0, parameters.Audience.DefaultRolloutPercentage);
186
+ }
187
+ static #validateParameters(parameters) {
188
+ if (parameters.Audience.DefaultRolloutPercentage < 0 || parameters.Audience.DefaultRolloutPercentage > 100) {
189
+ throw new Error("Audience.DefaultRolloutPercentage must be a number between 0 and 100.");
190
+ }
191
+ // validate RolloutPercentage for each group
192
+ if (parameters.Audience.Groups !== undefined) {
193
+ for (const group of parameters.Audience.Groups) {
194
+ if (group.RolloutPercentage < 0 || group.RolloutPercentage > 100) {
195
+ throw new Error(`RolloutPercentage of group ${group.Name} must be a number between 0 and 100.`);
196
+ }
197
+ }
198
+ }
199
+ }
200
+ }
201
+
202
+ // Copyright (c) Microsoft Corporation.
203
+ // Licensed under the MIT license.
204
+ class Variant {
205
+ name;
206
+ configuration;
207
+ constructor(name, configuration) {
208
+ this.name = name;
209
+ this.configuration = configuration;
210
+ }
211
+ }
212
+
213
+ // Copyright (c) Microsoft Corporation.
214
+ // Licensed under the MIT license.
215
+ class FeatureManager {
216
+ #provider;
217
+ #featureFilters = new Map();
218
+ #onFeatureEvaluated;
219
+ constructor(provider, options) {
220
+ this.#provider = provider;
221
+ const builtinFilters = [new TimeWindowFilter(), new TargetingFilter()];
222
+ // If a custom filter shares a name with an existing filter, the custom filter overrides the existing one.
223
+ for (const filter of [...builtinFilters, ...(options?.customFilters ?? [])]) {
224
+ this.#featureFilters.set(filter.name, filter);
225
+ }
226
+ this.#onFeatureEvaluated = options?.onFeatureEvaluated;
227
+ }
228
+ async listFeatureNames() {
229
+ const features = await this.#provider.getFeatureFlags();
230
+ const featureNameSet = new Set(features.map((feature) => feature.id));
231
+ return Array.from(featureNameSet);
232
+ }
233
+ // If multiple feature flags are found, the first one takes precedence.
234
+ async isEnabled(featureName, context) {
235
+ const result = await this.#evaluateFeature(featureName, context);
236
+ return result.enabled;
237
+ }
238
+ async getVariant(featureName, context) {
239
+ const result = await this.#evaluateFeature(featureName, context);
240
+ return result.variant;
241
+ }
242
+ async #assignVariant(featureFlag, context) {
243
+ // user allocation
244
+ if (featureFlag.allocation?.user !== undefined) {
245
+ for (const userAllocation of featureFlag.allocation.user) {
246
+ if (isTargetedUser(context.userId, userAllocation.users)) {
247
+ return getVariantAssignment(featureFlag, userAllocation.variant, exports.VariantAssignmentReason.User);
248
+ }
249
+ }
250
+ }
251
+ // group allocation
252
+ if (featureFlag.allocation?.group !== undefined) {
253
+ for (const groupAllocation of featureFlag.allocation.group) {
254
+ if (isTargetedGroup(context.groups, groupAllocation.groups)) {
255
+ return getVariantAssignment(featureFlag, groupAllocation.variant, exports.VariantAssignmentReason.Group);
256
+ }
257
+ }
258
+ }
259
+ // percentile allocation
260
+ if (featureFlag.allocation?.percentile !== undefined) {
261
+ for (const percentileAllocation of featureFlag.allocation.percentile) {
262
+ const hint = featureFlag.allocation.seed ?? `allocation\n${featureFlag.id}`;
263
+ if (await isTargetedPercentile(context.userId, hint, percentileAllocation.from, percentileAllocation.to)) {
264
+ return getVariantAssignment(featureFlag, percentileAllocation.variant, exports.VariantAssignmentReason.Percentile);
265
+ }
266
+ }
267
+ }
268
+ return { variant: undefined, reason: exports.VariantAssignmentReason.None };
269
+ }
270
+ async #isEnabled(featureFlag, context) {
271
+ if (featureFlag.enabled !== true) {
272
+ // If the feature is not explicitly enabled, then it is disabled by default.
273
+ return false;
274
+ }
275
+ const clientFilters = featureFlag.conditions?.client_filters;
276
+ if (clientFilters === undefined || clientFilters.length <= 0) {
277
+ // If there are no client filters, then the feature is enabled.
278
+ return true;
279
+ }
280
+ const requirementType = featureFlag.conditions?.requirement_type ?? "Any"; // default to any.
281
+ /**
282
+ * While iterating through the client filters, we short-circuit the evaluation based on the requirement type.
283
+ * - When requirement type is "All", the feature is enabled if all client filters are matched. If any client filter is not matched, the feature is disabled, otherwise it is enabled. `shortCircuitEvaluationResult` is false.
284
+ * - When requirement type is "Any", the feature is enabled if any client filter is matched. If any client filter is matched, the feature is enabled, otherwise it is disabled. `shortCircuitEvaluationResult` is true.
285
+ */
286
+ const shortCircuitEvaluationResult = requirementType === "Any";
287
+ for (const clientFilter of clientFilters) {
288
+ const matchedFeatureFilter = this.#featureFilters.get(clientFilter.name);
289
+ const contextWithFeatureName = { featureName: featureFlag.id, parameters: clientFilter.parameters };
290
+ if (matchedFeatureFilter === undefined) {
291
+ console.warn(`Feature filter ${clientFilter.name} is not found.`);
292
+ return false;
293
+ }
294
+ if (await matchedFeatureFilter.evaluate(contextWithFeatureName, context) === shortCircuitEvaluationResult) {
295
+ return shortCircuitEvaluationResult;
296
+ }
297
+ }
298
+ // If we get here, then we have not found a client filter that matches the requirement type.
299
+ return !shortCircuitEvaluationResult;
300
+ }
301
+ async #evaluateFeature(featureName, context) {
302
+ const featureFlag = await this.#provider.getFeatureFlag(featureName);
303
+ const result = new EvaluationResult(featureFlag);
304
+ if (featureFlag === undefined) {
305
+ return result;
306
+ }
307
+ // Ensure that the feature flag is in the correct format. Feature providers should validate the feature flags, but we do it here as a safeguard.
308
+ // TODO: move to the feature flag provider implementation.
309
+ validateFeatureFlagFormat(featureFlag);
310
+ // Evaluate if the feature is enabled.
311
+ result.enabled = await this.#isEnabled(featureFlag, context);
312
+ const targetingContext = context;
313
+ result.targetingId = targetingContext?.userId;
314
+ // Determine Variant
315
+ let variantDef;
316
+ let reason = exports.VariantAssignmentReason.None;
317
+ // featureFlag.variant not empty
318
+ if (featureFlag.variants !== undefined && featureFlag.variants.length > 0) {
319
+ if (!result.enabled) {
320
+ // not enabled, assign default if specified
321
+ if (featureFlag.allocation?.default_when_disabled !== undefined) {
322
+ variantDef = featureFlag.variants.find(v => v.name == featureFlag.allocation?.default_when_disabled);
323
+ reason = exports.VariantAssignmentReason.DefaultWhenDisabled;
324
+ }
325
+ else {
326
+ // no default specified
327
+ variantDef = undefined;
328
+ reason = exports.VariantAssignmentReason.DefaultWhenDisabled;
329
+ }
330
+ }
331
+ else {
332
+ // enabled, assign based on allocation
333
+ if (context !== undefined && featureFlag.allocation !== undefined) {
334
+ const variantAndReason = await this.#assignVariant(featureFlag, targetingContext);
335
+ variantDef = variantAndReason.variant;
336
+ reason = variantAndReason.reason;
337
+ }
338
+ // allocation failed, assign default if specified
339
+ if (variantDef === undefined && reason === exports.VariantAssignmentReason.None) {
340
+ if (featureFlag.allocation?.default_when_enabled !== undefined) {
341
+ variantDef = featureFlag.variants.find(v => v.name == featureFlag.allocation?.default_when_enabled);
342
+ reason = exports.VariantAssignmentReason.DefaultWhenEnabled;
343
+ }
344
+ else {
345
+ variantDef = undefined;
346
+ reason = exports.VariantAssignmentReason.DefaultWhenEnabled;
347
+ }
348
+ }
349
+ }
350
+ }
351
+ result.variant = variantDef !== undefined ? new Variant(variantDef.name, variantDef.configuration_value) : undefined;
352
+ result.variantAssignmentReason = reason;
353
+ // Status override for isEnabled
354
+ if (variantDef !== undefined && featureFlag.enabled) {
355
+ if (variantDef.status_override === "Enabled") {
356
+ result.enabled = true;
357
+ }
358
+ else if (variantDef.status_override === "Disabled") {
359
+ result.enabled = false;
360
+ }
361
+ }
362
+ // The callback will only be executed if telemetry is enabled for the feature flag
363
+ if (featureFlag.telemetry?.enabled && this.#onFeatureEvaluated !== undefined) {
364
+ this.#onFeatureEvaluated(result);
365
+ }
366
+ return result;
367
+ }
368
+ }
369
+ class EvaluationResult {
370
+ feature;
371
+ enabled;
372
+ targetingId;
373
+ variant;
374
+ variantAssignmentReason;
375
+ constructor(
376
+ // feature flag definition
377
+ feature,
378
+ // enabled state
379
+ enabled = false,
380
+ // variant assignment
381
+ targetingId = undefined, variant = undefined, variantAssignmentReason = exports.VariantAssignmentReason.None) {
382
+ this.feature = feature;
383
+ this.enabled = enabled;
384
+ this.targetingId = targetingId;
385
+ this.variant = variant;
386
+ this.variantAssignmentReason = variantAssignmentReason;
387
+ }
388
+ }
389
+ exports.VariantAssignmentReason = void 0;
390
+ (function (VariantAssignmentReason) {
391
+ /**
392
+ * Variant allocation did not happen. No variant is assigned.
393
+ */
394
+ VariantAssignmentReason["None"] = "None";
395
+ /**
396
+ * The default variant is assigned when a feature flag is disabled.
397
+ */
398
+ VariantAssignmentReason["DefaultWhenDisabled"] = "DefaultWhenDisabled";
399
+ /**
400
+ * The default variant is assigned because of no applicable user/group/percentile allocation when a feature flag is enabled.
401
+ */
402
+ VariantAssignmentReason["DefaultWhenEnabled"] = "DefaultWhenEnabled";
403
+ /**
404
+ * The variant is assigned because of the user allocation when a feature flag is enabled.
405
+ */
406
+ VariantAssignmentReason["User"] = "User";
407
+ /**
408
+ * The variant is assigned because of the group allocation when a feature flag is enabled.
409
+ */
410
+ VariantAssignmentReason["Group"] = "Group";
411
+ /**
412
+ * The variant is assigned because of the percentile allocation when a feature flag is enabled.
413
+ */
414
+ VariantAssignmentReason["Percentile"] = "Percentile";
415
+ })(exports.VariantAssignmentReason || (exports.VariantAssignmentReason = {}));
416
+ /**
417
+ * Validates the format of the feature flag definition.
418
+ *
419
+ * FeatureFlag data objects are from IFeatureFlagProvider, depending on the implementation.
420
+ * Thus the properties are not guaranteed to have the expected types.
421
+ *
422
+ * @param featureFlag The feature flag definition to validate.
423
+ */
424
+ function validateFeatureFlagFormat(featureFlag) {
425
+ if (featureFlag.enabled !== undefined && typeof featureFlag.enabled !== "boolean") {
426
+ throw new Error(`Feature flag ${featureFlag.id} has an invalid 'enabled' value.`);
427
+ }
428
+ // TODO: add more validations.
429
+ // TODO: should be moved to the feature flag provider.
430
+ }
431
+ /**
432
+ * Try to get the variant assignment for the given variant name. If the variant is not found, override the reason with VariantAssignmentReason.None.
433
+ *
434
+ * @param featureFlag feature flag definition
435
+ * @param variantName variant name
436
+ * @param reason variant assignment reason
437
+ * @returns variant assignment containing the variant definition and the reason
438
+ */
439
+ function getVariantAssignment(featureFlag, variantName, reason) {
440
+ const variant = featureFlag.variants?.find(v => v.name == variantName);
441
+ if (variant !== undefined) {
442
+ return { variant, reason };
443
+ }
444
+ else {
445
+ console.warn(`Variant ${variantName} not found for feature ${featureFlag.id}.`);
446
+ return { variant: undefined, reason: exports.VariantAssignmentReason.None };
447
+ }
448
+ }
449
+
450
+ // Copyright (c) Microsoft Corporation.
451
+ // Licensed under the MIT license.
452
+ // Feature Management Section fed into feature manager.
453
+ // Converted from https://github.com/Azure/AppConfiguration/blob/main/docs/FeatureManagement/FeatureManagement.v1.0.0.schema.json
454
+ const FEATURE_MANAGEMENT_KEY = "feature_management";
455
+ const FEATURE_FLAGS_KEY = "feature_flags";
456
+
457
+ // Copyright (c) Microsoft Corporation.
458
+ // Licensed under the MIT license.
459
+ /**
460
+ * A feature flag provider that uses a map-like configuration to provide feature flags.
461
+ */
462
+ class ConfigurationMapFeatureFlagProvider {
463
+ #configuration;
464
+ constructor(configuration) {
465
+ this.#configuration = configuration;
466
+ }
467
+ async getFeatureFlag(featureName) {
468
+ const featureConfig = this.#configuration.get(FEATURE_MANAGEMENT_KEY);
469
+ return featureConfig?.[FEATURE_FLAGS_KEY]?.find((feature) => feature.id === featureName);
470
+ }
471
+ async getFeatureFlags() {
472
+ const featureConfig = this.#configuration.get(FEATURE_MANAGEMENT_KEY);
473
+ return featureConfig?.[FEATURE_FLAGS_KEY] ?? [];
474
+ }
475
+ }
476
+ /**
477
+ * A feature flag provider that uses an object-like configuration to provide feature flags.
478
+ */
479
+ class ConfigurationObjectFeatureFlagProvider {
480
+ #configuration;
481
+ constructor(configuration) {
482
+ this.#configuration = configuration;
483
+ }
484
+ async getFeatureFlag(featureName) {
485
+ const featureFlags = this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY];
486
+ return featureFlags?.find((feature) => feature.id === featureName);
487
+ }
488
+ async getFeatureFlags() {
489
+ return this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY] ?? [];
490
+ }
491
+ }
492
+
493
+ // Copyright (c) Microsoft Corporation.
494
+ // Licensed under the MIT license.
495
+ const VERSION = "2.0.0-preview.1";
496
+
497
+ exports.ConfigurationMapFeatureFlagProvider = ConfigurationMapFeatureFlagProvider;
498
+ exports.ConfigurationObjectFeatureFlagProvider = ConfigurationObjectFeatureFlagProvider;
499
+ exports.EvaluationResult = EvaluationResult;
500
+ exports.FeatureManager = FeatureManager;
501
+ exports.VERSION = VERSION;
502
+
503
+ }));
504
+ //# sourceMappingURL=index.js.map