@microsoft/feature-management 2.1.0 → 2.3.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 (60) hide show
  1. package/dist/commonjs/common/targetingEvaluator.js.map +1 -1
  2. package/dist/commonjs/featureManager.js +5 -5
  3. package/dist/commonjs/featureManager.js.map +1 -1
  4. package/dist/commonjs/featureProvider.js.map +1 -1
  5. package/dist/commonjs/filter/recurrence/evaluator.js +142 -0
  6. package/dist/commonjs/filter/recurrence/evaluator.js.map +1 -0
  7. package/dist/commonjs/filter/recurrence/model.js +52 -0
  8. package/dist/commonjs/filter/recurrence/model.js.map +1 -0
  9. package/dist/commonjs/filter/recurrence/utils.js +53 -0
  10. package/dist/commonjs/filter/recurrence/utils.js.map +1 -0
  11. package/dist/commonjs/filter/recurrence/validator.js +197 -0
  12. package/dist/commonjs/filter/recurrence/validator.js.map +1 -0
  13. package/dist/commonjs/filter/{TargetingFilter.js → targetingFilter.js} +1 -1
  14. package/dist/commonjs/filter/{TargetingFilter.js.map → targetingFilter.js.map} +1 -1
  15. package/dist/commonjs/filter/timeWindowFilter.js +49 -0
  16. package/dist/commonjs/filter/timeWindowFilter.js.map +1 -0
  17. package/dist/commonjs/filter/utils.js +16 -0
  18. package/dist/commonjs/filter/utils.js.map +1 -0
  19. package/dist/commonjs/schema/model.js.map +1 -1
  20. package/dist/commonjs/schema/validator.js.map +1 -1
  21. package/dist/commonjs/telemetry/featureEvaluationEvent.js.map +1 -1
  22. package/dist/commonjs/variant/{Variant.js → variant.js} +1 -1
  23. package/dist/commonjs/variant/variant.js.map +1 -0
  24. package/dist/commonjs/version.js +1 -1
  25. package/dist/commonjs/version.js.map +1 -1
  26. package/dist/esm/common/targetingEvaluator.js.map +1 -1
  27. package/dist/esm/featureManager.js +3 -3
  28. package/dist/esm/featureManager.js.map +1 -1
  29. package/dist/esm/featureProvider.js.map +1 -1
  30. package/dist/esm/filter/recurrence/evaluator.js +140 -0
  31. package/dist/esm/filter/recurrence/evaluator.js.map +1 -0
  32. package/dist/esm/filter/recurrence/model.js +49 -0
  33. package/dist/esm/filter/recurrence/model.js.map +1 -0
  34. package/dist/esm/filter/recurrence/utils.js +48 -0
  35. package/dist/esm/filter/recurrence/utils.js.map +1 -0
  36. package/dist/esm/filter/recurrence/validator.js +184 -0
  37. package/dist/esm/filter/recurrence/validator.js.map +1 -0
  38. package/dist/esm/filter/{TargetingFilter.js → targetingFilter.js} +1 -1
  39. package/dist/esm/filter/{TargetingFilter.js.map → targetingFilter.js.map} +1 -1
  40. package/dist/esm/filter/timeWindowFilter.js +47 -0
  41. package/dist/esm/filter/timeWindowFilter.js.map +1 -0
  42. package/dist/esm/filter/utils.js +11 -0
  43. package/dist/esm/filter/utils.js.map +1 -0
  44. package/dist/esm/schema/model.js.map +1 -1
  45. package/dist/esm/schema/validator.js.map +1 -1
  46. package/dist/esm/telemetry/featureEvaluationEvent.js.map +1 -1
  47. package/dist/esm/variant/{Variant.js → variant.js} +1 -1
  48. package/dist/esm/variant/variant.js.map +1 -0
  49. package/dist/esm/version.js +1 -1
  50. package/dist/esm/version.js.map +1 -1
  51. package/{types → dist/types}/index.d.ts +43 -42
  52. package/dist/umd/index.js +439 -3
  53. package/dist/umd/index.js.map +1 -1
  54. package/package.json +41 -26
  55. package/dist/commonjs/filter/TimeWindowFilter.js +0 -22
  56. package/dist/commonjs/filter/TimeWindowFilter.js.map +0 -1
  57. package/dist/commonjs/variant/Variant.js.map +0 -1
  58. package/dist/esm/filter/TimeWindowFilter.js +0 -20
  59. package/dist/esm/filter/TimeWindowFilter.js.map +0 -1
  60. package/dist/esm/variant/Variant.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"targetingEvaluator.js","sources":["../../../src/common/targetingEvaluator.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Determines if the user is part of the audience, based on the user id and the percentage range.\n *\n * @param userId user id from app context\n * @param hint hint string to be included in the context id\n * @param from percentage range start\n * @param to percentage range end\n * @returns true if the user is part of the audience, false otherwise\n */\nexport async function isTargetedPercentile(userId: string | undefined, hint: string, from: number, to: number): Promise<boolean> {\n if (from < 0 || from > 100) {\n throw new Error(\"The 'from' value must be between 0 and 100.\");\n }\n if (to < 0 || to > 100) {\n throw new Error(\"The 'to' value must be between 0 and 100.\");\n }\n if (from > to) {\n throw new Error(\"The 'from' value cannot be larger than the 'to' value.\");\n }\n\n const audienceContextId = constructAudienceContextId(userId, hint);\n\n // Cryptographic hashing algorithms ensure adequate entropy across hash values.\n const contextMarker = await stringToUint32(audienceContextId);\n const contextPercentage = (contextMarker / 0xFFFFFFFF) * 100;\n\n // Handle edge case of exact 100 bucket\n if (to === 100) {\n return contextPercentage >= from;\n }\n\n return contextPercentage >= from && contextPercentage < to;\n}\n\n/**\n * Determines if the user is part of the audience, based on the groups they belong to.\n *\n * @param sourceGroups user groups from app context\n * @param targetedGroups targeted groups from feature configuration\n * @returns true if the user is part of the audience, false otherwise\n */\nexport function isTargetedGroup(sourceGroups: string[] | undefined, targetedGroups: string[]): boolean {\n if (sourceGroups === undefined) {\n return false;\n }\n\n return sourceGroups.some(group => targetedGroups.includes(group));\n}\n\n/**\n * Determines if the user is part of the audience, based on the user id.\n * @param userId user id from app context\n * @param users targeted users from feature configuration\n * @returns true if the user is part of the audience, false otherwise\n */\nexport function isTargetedUser(userId: string | undefined, users: string[]): boolean {\n if (userId === undefined) {\n return false;\n }\n\n return users.includes(userId);\n}\n\n/**\n * Constructs the context id for the audience.\n * The context id is used to determine if the user is part of the audience for a feature.\n *\n * @param userId userId from app context\n * @param hint hint string to be included in the context id\n * @returns a string that represents the context id for the audience\n */\nfunction constructAudienceContextId(userId: string | undefined, hint: string): string {\n return `${userId ?? \"\"}\\n${hint}`;\n}\n\n/**\n * Converts a string to a uint32 in little-endian encoding.\n * @param str the string to convert.\n * @returns a uint32 value.\n */\nasync function stringToUint32(str: string): Promise<number> {\n let crypto;\n\n // Check for browser environment\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n crypto = window.crypto;\n }\n // Check for Node.js environment\n else if (typeof global !== \"undefined\" && global.crypto) {\n crypto = global.crypto;\n }\n // Fallback to native Node.js crypto module\n else {\n try {\n if (typeof module !== \"undefined\" && module.exports) {\n crypto = require(\"crypto\");\n }\n else {\n crypto = await import(\"crypto\");\n }\n } catch (error) {\n console.error(\"Failed to load the crypto module:\", error.message);\n throw error;\n }\n }\n\n // In the browser, use crypto.subtle.digest\n if (crypto.subtle) {\n const data = new TextEncoder().encode(str);\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", data);\n const dataView = new DataView(hashBuffer);\n const uint32 = dataView.getUint32(0, true);\n return uint32;\n }\n // In Node.js, use the crypto module's hash function\n else {\n const hash = crypto.createHash(\"sha256\").update(str).digest();\n const uint32 = hash.readUInt32LE(0);\n return uint32;\n }\n}\n"],"names":[],"mappings":";;AAAA;AACA;AAEA;;;;;;;;AAQG;AACI,eAAe,oBAAoB,CAAC,MAA0B,EAAE,IAAY,EAAE,IAAY,EAAE,EAAU,EAAA;IACzG,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,GAAG,GAAG,EAAE;AACxB,QAAA,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;KAClE;IACD,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,EAAE;AACpB,QAAA,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAChE;AACD,IAAA,IAAI,IAAI,GAAG,EAAE,EAAE;AACX,QAAA,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;KAC7E;IAED,MAAM,iBAAiB,GAAG,0BAA0B,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;;AAGnE,IAAA,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,iBAAiB,CAAC,CAAC;IAC9D,MAAM,iBAAiB,GAAG,CAAC,aAAa,GAAG,UAAU,IAAI,GA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K,WAAW,IAAI,MAAM,CAAC,OAAO,EAAE;AACjD,gBAAA,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;aAC9B;iBACI;AACD,gBAAA,MAAM,GAAG,MAAM,OAAO,QAAQ,CAAC,CAAC;aACnC;SACJ;QAAC,OAAO,KAAK,EAAE;YACZ,OAAO,CAAC,KAAK,CAAC,mCAAmC,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;AAClE,YAAA,MAAM,KAAK,CAAC;SACf;KACJ;;AAGD,IAAA,IAAI,MAAM,CAAC,MAAM,EAAE;QACf,MAAM,IAAI,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC3C,QAAA,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAC/D,QAAA,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,UAAU,CAAC,CAAC;QAC1C,MAAM,MAAM,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;AAC3C,QAAA,OAAO,MAAM,CAAC;KACjB;;SAEI;AACD,QAAA,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;QAC9D,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;AACpC,QAAA,OAAO,MAAM,CAAC;KACjB;AACL;;;;;;"}
1
+ {"version":3,"file":"targetingEvaluator.js","sources":["../../../src/common/targetingEvaluator.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Determines if the user is part of the audience, based on the user id and the percentage range.\n *\n * @param userId user id from app context\n * @param hint hint string to be included in the context id\n * @param from percentage range start\n * @param to percentage range end\n * @returns true if the user is part of the audience, false otherwise\n */\nexport async function isTargetedPercentile(userId: string | undefined, hint: string, from: number, to: number): Promise<boolean> {\n if (from < 0 || from > 100) {\n throw new Error(\"The 'from' value must be between 0 and 100.\");\n }\n if (to < 0 || to > 100) {\n throw new Error(\"The 'to' value must be between 0 and 100.\");\n }\n if (from > to) {\n throw new Error(\"The 'from' value cannot be larger than the 'to' value.\");\n }\n\n const audienceContextId = constructAudienceContextId(userId, hint);\n\n // Cryptographic hashing algorithms ensure adequate entropy across hash values.\n const contextMarker = await stringToUint32(audienceContextId);\n const contextPercentage = (contextMarker / 0xFFFFFFFF) * 100;\n\n // Handle edge case of exact 100 bucket\n if (to === 100) {\n return contextPercentage >= from;\n }\n\n return contextPercentage >= from && contextPercentage < to;\n}\n\n/**\n * Determines if the user is part of the audience, based on the groups they belong to.\n *\n * @param sourceGroups user groups from app context\n * @param targetedGroups targeted groups from feature configuration\n * @returns true if the user is part of the audience, false otherwise\n */\nexport function isTargetedGroup(sourceGroups: string[] | undefined, targetedGroups: string[]): boolean {\n if (sourceGroups === undefined) {\n return false;\n }\n\n return sourceGroups.some(group => targetedGroups.includes(group));\n}\n\n/**\n * Determines if the user is part of the audience, based on the user id.\n * @param userId user id from app context\n * @param users targeted users from feature configuration\n * @returns true if the user is part of the audience, false otherwise\n */\nexport function isTargetedUser(userId: string | undefined, users: string[]): boolean {\n if (userId === undefined) {\n return false;\n }\n\n return users.includes(userId);\n}\n\n/**\n * Constructs the context id for the audience.\n * The context id is used to determine if the user is part of the audience for a feature.\n *\n * @param userId userId from app context\n * @param hint hint string to be included in the context id\n * @returns a string that represents the context id for the audience\n */\nfunction constructAudienceContextId(userId: string | undefined, hint: string): string {\n return `${userId ?? \"\"}\\n${hint}`;\n}\n\n/**\n * Converts a string to a uint32 in little-endian encoding.\n * @param str the string to convert.\n * @returns a uint32 value.\n */\nasync function stringToUint32(str: string): Promise<number> {\n let crypto;\n\n // Check for browser environment\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n crypto = window.crypto;\n }\n // Check for Node.js environment\n else if (typeof global !== \"undefined\" && global.crypto) {\n crypto = global.crypto;\n }\n // Fallback to native Node.js crypto module\n else {\n try {\n if (typeof module !== \"undefined\" && module.exports) {\n crypto = require(\"crypto\");\n }\n else {\n crypto = await import(\"crypto\");\n }\n } catch (error) {\n console.error(\"Failed to load the crypto module:\", error.message);\n throw error;\n }\n }\n\n // In the browser, use crypto.subtle.digest\n if (crypto.subtle) {\n const data = new TextEncoder().encode(str);\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", data);\n const dataView = new DataView(hashBuffer);\n const uint32 = dataView.getUint32(0, true);\n return uint32;\n }\n // In Node.js, use the crypto module's hash function\n else {\n const hash = crypto.createHash(\"sha256\").update(str).digest();\n const uint32 = hash.readUInt32LE(0);\n return uint32;\n }\n}\n"],"names":[],"mappings":";;AAAA;AACA;AAEA;;;;;;;;AAQG;AACI,eAAe,oBAAoB,CAAC,MAA0B,EAAE,IAAY,EAAE,IAAY,EAAE,EAAU,EAAA;IACzG,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,GAAG,GAAG,EAAE;AACxB,QAAA,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC;IAClE;IACA,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,EAAE;AACpB,QAAA,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC;IAChE;AACA,IAAA,IAAI,IAAI,GAAG,EAAE,EAAE;AACX,QAAA,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC;IAC7E;IAEA,MAAM,iBAAiB,GAAG,0BAA0B,CAAC,MAAM,EAAE,IAAI,CAAC;;AAGlE,IAAA,MAAM,aAAa,GAAG,MAAM,cAAc,CAAC,iBAAiB,CAAC;IAC7D,MAAM,iBAAiB,GAAG,CAAC,aAAa,GAAG,UAAU,IAAI,GAAG;;AAG5D,IAAA,IAAI,EAAE,KAAK,GAAG,EAAE;QACZ,OAAO,iBAAiB,IAAI,IAAI;IACpC;AAEA,IAAA,OAAO,i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YACZ,OAAO,CAAC,KAAK,CAAC,mCAAmC,EAAE,KAAK,CAAC,OAAO,CAAC;AACjE,YAAA,MAAM,KAAK;QACf;IACJ;;AAGA,IAAA,IAAI,MAAM,CAAC,MAAM,EAAE;QACf,MAAM,IAAI,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC;AAC1C,QAAA,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC;AAC9D,QAAA,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,UAAU,CAAC;QACzC,MAAM,MAAM,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC,EAAE,IAAI,CAAC;AAC1C,QAAA,OAAO,MAAM;IACjB;;SAEK;AACD,QAAA,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE;QAC7D,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC;AACnC,QAAA,OAAO,MAAM;IACjB;AACJ;;;;;;"}
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var TimeWindowFilter = require('./filter/TimeWindowFilter.js');
4
- var TargetingFilter = require('./filter/TargetingFilter.js');
5
- var Variant = require('./variant/Variant.js');
3
+ var timeWindowFilter = require('./filter/timeWindowFilter.js');
4
+ var targetingFilter = require('./filter/targetingFilter.js');
5
+ var variant = require('./variant/variant.js');
6
6
  var targetingEvaluator = require('./common/targetingEvaluator.js');
7
7
 
8
8
  // Copyright (c) Microsoft Corporation.
@@ -16,7 +16,7 @@ class FeatureManager {
16
16
  this.#provider = provider;
17
17
  this.#onFeatureEvaluated = options?.onFeatureEvaluated;
18
18
  this.#targetingContextAccessor = options?.targetingContextAccessor;
19
- const builtinFilters = [new TimeWindowFilter.TimeWindowFilter(), new TargetingFilter.TargetingFilter(options?.targetingContextAccessor)];
19
+ const builtinFilters = [new timeWindowFilter.TimeWindowFilter(), new targetingFilter.TargetingFilter(options?.targetingContextAccessor)];
20
20
  // If a custom filter shares a name with an existing filter, the custom filter overrides the existing one.
21
21
  for (const filter of [...builtinFilters, ...(options?.customFilters ?? [])]) {
22
22
  this.#featureFilters.set(filter.name, filter);
@@ -146,7 +146,7 @@ class FeatureManager {
146
146
  }
147
147
  }
148
148
  }
149
- result.variant = variantDef !== undefined ? new Variant.Variant(variantDef.name, variantDef.configuration_value) : undefined;
149
+ result.variant = variantDef !== undefined ? new variant.Variant(variantDef.name, variantDef.configuration_value) : undefined;
150
150
  result.variantAssignmentReason = reason;
151
151
  // Status override for isEnabled
152
152
  if (variantDef !== undefined && featureFlag.enabled) {
@@ -1 +1 @@
1
- {"version":3,"file":"featureManager.js","sources":["../../src/featureManager.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TimeWindowFilter } from \"./filter/TimeWindowFilter.js\";\nimport { IFeatureFilter } from \"./filter/FeatureFilter.js\";\nimport { FeatureFlag, RequirementType, VariantDefinition } from \"./schema/model.js\";\nimport { IFeatureFlagProvider } from \"./featureProvider.js\";\nimport { TargetingFilter } from \"./filter/TargetingFilter.js\";\nimport { Variant } from \"./variant/Variant.js\";\nimport { IFeatureManager } from \"./IFeatureManager.js\";\nimport { ITargetingContext, ITargetingContextAccessor } from \"./common/targetingContext.js\";\nimport { isTargetedGroup, isTargetedPercentile, isTargetedUser } from \"./common/targetingEvaluator.js\";\n\nexport class FeatureManager implements IFeatureManager {\n readonly #provider: IFeatureFlagProvider;\n readonly #featureFilters: Map<string, IFeatureFilter> = new Map();\n readonly #onFeatureEvaluated?: (event: EvaluationResult) => void;\n readonly #targetingContextAccessor?: ITargetingContextAccessor;\n\n constructor(provider: IFeatureFlagProvider, options?: FeatureManagerOptions) {\n this.#provider = provider;\n this.#onFeatureEvaluated = options?.onFeatureEvaluated;\n this.#targetingContextAccessor = options?.targetingContextAccessor;\n\n const builtinFilters = [new TimeWindowFilter(), new TargetingFilter(options?.targetingContextAccessor)];\n // If a custom filter shares a name with an existing filter, the custom filter overrides the existing one.\n for (const filter of [...builtinFilters, ...(options?.customFilters ?? [])]) {\n this.#featureFilters.set(filter.name, filter);\n }\n }\n\n async listFeatureNames(): Promise<string[]> {\n const features = await this.#provider.getFeatureFlags();\n const featureNameSet = new Set(features.map((feature) => feature.id));\n return Array.from(featureNameSet);\n }\n\n // If multiple feature flags are found, the first one takes precedence.\n async isEnabled(featureName: string, context?: unknown): Promise<boolean> {\n const result = await this.#evaluateFeature(featureName, context);\n return result.enabled;\n }\n\n async getVariant(featureName: string, context?: ITargetingContext): Promise<Variant | undefined> {\n const result = await this.#evaluateFeature(featureName, context);\n return result.variant;\n }\n\n async #assignVariant(featureFlag: FeatureFlag, context: ITargetingContext): Promise<VariantAssignment> {\n // user allocation\n if (featureFlag.allocation?.user !== undefined) {\n for (const userAllocation of featureFlag.allocation.user) {\n if (isTargetedUser(context.userId, userAllocation.users)) {\n return getVariantAssignment(featureFlag, userAllocation.variant, VariantAssignmentReason.User);\n }\n }\n }\n\n // group allocation\n if (featureFlag.allocation?.group !== undefined) {\n for (const groupAllocation of featureFlag.allocation.group) {\n if (isTargetedGroup(context.groups, groupAllocation.groups)) {\n return getVariantAssignment(featureFlag, groupAllocation.variant, VariantAssignmentReason.Group);\n }\n }\n }\n\n // percentile allocation\n if (featureFlag.allocation?.percentile !== undefined) {\n for (const percentileAllocation of featureFlag.allocation.percentile) {\n const hint = featureFlag.allocation.seed ?? `allocation\\n${featureFlag.id}`;\n if (await isTargetedPercentile(context.userId, hint, percentileAllocation.from, percentileAllocation.to)) {\n return getVariantAssignment(featureFlag, percentileAllocation.variant, VariantAssignmentReason.Percentile);\n }\n }\n }\n\n return { variant: undefined, reason: VariantAssignmentReason.None };\n }\n\n async #isEnabled(featureFlag: FeatureFlag, appContext?: unknown): Promise<boolean> {\n if (featureFlag.enabled !== true) {\n // If the feature is not explicitly enabled, then it is disabled by default.\n return false;\n }\n\n const clientFilters = featureFlag.conditions?.client_filters;\n if (clientFilters === undefined || clientFilters.length <= 0) {\n // If there are no client filters, then the feature is enabled.\n return true;\n }\n\n const requirementType: RequirementType = featureFlag.conditions?.requirement_type ?? \"Any\"; // default to any.\n\n /**\n * While iterating through the client filters, we short-circuit the evaluation based on the requirement type.\n * - 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.\n * - 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.\n */\n const shortCircuitEvaluationResult: boolean = requirementType === \"Any\";\n\n for (const clientFilter of clientFilters) {\n const matchedFeatureFilter = this.#featureFilters.get(clientFilter.name);\n const contextWithFeatureName = { featureName: featureFlag.id, parameters: clientFilter.parameters };\n if (matchedFeatureFilter === undefined) {\n console.warn(`Feature filter ${clientFilter.name} is not found.`);\n return false;\n }\n if (await matchedFeatureFilter.evaluate(contextWithFeatureName, appContext) === shortCircuitEvaluationResult) {\n return shortCircuitEvaluationResult;\n }\n }\n\n // If we get here, then we have not found a client filter that matches the requirement type.\n return !shortCircuitEvaluationResult;\n }\n\n async #evaluateFeature(featureName: string, appContext: unknown): Promise<EvaluationResult> {\n const featureFlag = await this.#provider.getFeatureFlag(featureName);\n const result = new EvaluationResult(featureFlag);\n\n if (featureFlag === undefined) {\n return result;\n }\n\n // 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.\n // TODO: move to the feature flag provider implementation.\n validateFeatureFlagFormat(featureFlag);\n\n // Evaluate if the feature is enabled.\n result.enabled = await this.#isEnabled(featureFlag, appContext);\n\n // Get targeting context from the app context or the targeting context accessor\n const targetingContext = this.#getTargetingContext(appContext);\n result.targetingId = targetingContext?.userId;\n\n // Determine Variant\n let variantDef: VariantDefinition | undefined;\n let reason: VariantAssignmentReason = VariantAssignmentReason.None;\n\n // featureFlag.variant not empty\n if (featureFlag.variants !== undefined && featureFlag.variants.length > 0) {\n if (!result.enabled) {\n // not enabled, assign default if specified\n if (featureFlag.allocation?.default_when_disabled !== undefined) {\n variantDef = featureFlag.variants.find(v => v.name == featureFlag.allocation?.default_when_disabled);\n reason = VariantAssignmentReason.DefaultWhenDisabled;\n } else {\n // no default specified\n variantDef = undefined;\n reason = VariantAssignmentReason.DefaultWhenDisabled;\n }\n } else {\n // enabled, assign based on allocation\n if (targetingContext !== undefined && featureFlag.allocation !== undefined) {\n const variantAndReason = await this.#assignVariant(featureFlag, targetingContext);\n variantDef = variantAndReason.variant;\n reason = variantAndReason.reason;\n }\n\n // allocation failed, assign default if specified\n if (variantDef === undefined && reason === VariantAssignmentReason.None) {\n if (featureFlag.allocation?.default_when_enabled !== undefined) {\n variantDef = featureFlag.variants.find(v => v.name == featureFlag.allocation?.default_when_enabled);\n reason = VariantAssignmentReason.DefaultWhenEnabled;\n } else {\n variantDef = undefined;\n reason = VariantAssignmentReason.DefaultWhenEnabled;\n }\n }\n }\n }\n\n result.variant = variantDef !== undefined ? new Variant(variantDef.name, variantDef.configuration_value) : undefined;\n result.variantAssignmentReason = reason;\n\n // Status override for isEnabled\n if (variantDef !== undefined && featureFlag.enabled) {\n if (variantDef.status_override === \"Enabled\") {\n result.enabled = true;\n } else if (variantDef.status_override === \"Disabled\") {\n result.enabled = false;\n }\n }\n\n // The callback will only be executed if telemetry is enabled for the feature flag\n if (featureFlag.telemetry?.enabled && this.#onFeatureEvaluated !== undefined) {\n this.#onFeatureEvaluated(result);\n }\n\n return result;\n }\n\n #getTargetingContext(context: unknown): ITargetingContext | undefined {\n let targetingContext: ITargetingContext | undefined = context as ITargetingContext;\n if (targetingContext?.userId === undefined &&\n targetingContext?.groups === undefined &&\n this.#targetingContextAccessor !== undefined) {\n targetingContext = this.#targetingContextAccessor.getTargetingContext();\n }\n return targetingContext;\n }\n}\n\nexport interface FeatureManagerOptions {\n /**\n * The custom filters to be used by the feature manager.\n */\n customFilters?: IFeatureFilter[];\n\n /**\n * The callback function that is called when a feature flag is evaluated.\n * The callback function is called only when telemetry is enabled for the feature flag.\n */\n onFeatureEvaluated?: (event: EvaluationResult) => void;\n\n /**\n * The accessor function that provides the @see ITargetingContext for targeting evaluation.\n */\n targetingContextAccessor?: ITargetingContextAccessor;\n}\n\nexport class EvaluationResult {\n constructor(\n // feature flag definition\n public readonly feature: FeatureFlag | undefined,\n\n // enabled state\n public enabled: boolean = false,\n\n // variant assignment\n public targetingId: string | undefined = undefined,\n public variant: Variant | undefined = undefined,\n public variantAssignmentReason: VariantAssignmentReason = VariantAssignmentReason.None\n ) { }\n}\n\nexport enum VariantAssignmentReason {\n /**\n * Variant allocation did not happen. No variant is assigned.\n */\n None = \"None\",\n\n /**\n * The default variant is assigned when a feature flag is disabled.\n */\n DefaultWhenDisabled = \"DefaultWhenDisabled\",\n\n /**\n * The default variant is assigned because of no applicable user/group/percentile allocation when a feature flag is enabled.\n */\n DefaultWhenEnabled = \"DefaultWhenEnabled\",\n\n /**\n * The variant is assigned because of the user allocation when a feature flag is enabled.\n */\n User = \"User\",\n\n /**\n * The variant is assigned because of the group allocation when a feature flag is enabled.\n */\n Group = \"Group\",\n\n /**\n * The variant is assigned because of the percentile allocation when a feature flag is enabled.\n */\n Percentile = \"Percentile\"\n}\n\n/**\n * Validates the format of the feature flag definition.\n *\n * FeatureFlag data objects are from IFeatureFlagProvider, depending on the implementation.\n * Thus the properties are not guaranteed to have the expected types.\n *\n * @param featureFlag The feature flag definition to validate.\n */\nfunction validateFeatureFlagFormat(featureFlag: any): void {\n if (featureFlag.enabled !== undefined && typeof featureFlag.enabled !== \"boolean\") {\n throw new Error(`Feature flag ${featureFlag.id} has an invalid 'enabled' value.`);\n }\n // TODO: add more validations.\n // TODO: should be moved to the feature flag provider.\n}\n\n/**\n * Try to get the variant assignment for the given variant name. If the variant is not found, override the reason with VariantAssignmentReason.None.\n *\n * @param featureFlag feature flag definition\n * @param variantName variant name\n * @param reason variant assignment reason\n * @returns variant assignment containing the variant definition and the reason\n */\nfunction getVariantAssignment(featureFlag: FeatureFlag, variantName: string, reason: VariantAssignmentReason): VariantAssignment {\n const variant = featureFlag.variants?.find(v => v.name == variantName);\n if (variant !== undefined) {\n return { variant, reason };\n } else {\n console.warn(`Variant ${variantName} not found for feature ${featureFlag.id}.`);\n return { variant: undefined, reason: VariantAssignmentReason.None };\n }\n}\n\ntype VariantAssignment = {\n variant: VariantDefinition | undefined;\n reason: VariantAssignmentReason;\n};\n"],"names":["TimeWindowFilter","TargetingFilter","isTargetedUser","VariantAssignmentReason","isTargetedGroup","isTargetedPercentile","Variant"],"mappings":";;;;;;;AAAA;AACA;MAYa,cAAc,CAAA;AACd,IAAA,SAAS,CAAuB;AAChC,IAAA,eAAe,GAAgC,IAAI,GAAG,EAAE,CAAC;AACzD,IAAA,mBAAmB,CAAqC;AACxD,IAAA,yBAAyB,CAA6B;IAE/D,WAAY,CAAA,QAA8B,EAAE,OAA+B,EAAA;AACvE,QAAA,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;AAC1B,QAAA,IAAI,CAAC,mBAAmB,GAAG,OAAO,EAAE,kBAAkB,CAAC;AACvD,QAAA,IAAI,CAAC,yBAAyB,GAAG,OAAO,EAAE,wBAAwB,CAAC;AAEnE,QAAA,MAAM,cAAc,GAAG,CAAC,IAAIA,iCAAgB,EAAE,EAAE,IAAIC,+BAAe,CAAC,OAAO,EAAE,wBAAwB,CAAC,CAAC,CAAC;;AAExG,QAAA,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,cAAc,EAAE,IAAI,OAAO,EAAE,aAAa,IAAI,EAAE,CAAC,CAAC,EAAE;YACzE,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;SACjD;KACJ;AAED,IAAA,MAAM,gBAAgB,GAAA;QAClB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,SAAS,CA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WAAwB,EAAE,WAAmB,EAAE,MAA+B,EAAA;AACxG,IAAA,MAAM,OAAO,GAAG,WAAW,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,WAAW,CAAC,CAAC;AACvE,IAAA,IAAI,OAAO,KAAK,SAAS,EAAE;AACvB,QAAA,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;KAC9B;SAAM;QACH,OAAO,CAAC,IAAI,CAAC,CAAW,QAAA,EAAA,WAAW,CAA0B,uBAAA,EAAA,WAAW,CAAC,EAAE,CAAG,CAAA,CAAA,CAAC,CAAC;QAChF,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAEA,+BAAuB,CAAC,IAAI,EAAE,CAAC;KACvE;AACL;;;;;"}
1
+ {"version":3,"file":"featureManager.js","sources":["../../src/featureManager.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TimeWindowFilter } from \"./filter/timeWindowFilter.js\";\nimport { IFeatureFilter } from \"./filter/featureFilter.js\";\nimport { FeatureFlag, RequirementType, VariantDefinition } from \"./schema/model.js\";\nimport { IFeatureFlagProvider, IFeatureManager } from \"./model.js\";\nimport { TargetingFilter } from \"./filter/targetingFilter.js\";\nimport { Variant } from \"./variant/variant.js\";\nimport { ITargetingContext, ITargetingContextAccessor } from \"./common/targetingContext.js\";\nimport { isTargetedGroup, isTargetedPercentile, isTargetedUser } from \"./common/targetingEvaluator.js\";\n\nexport class FeatureManager implements IFeatureManager {\n readonly #provider: IFeatureFlagProvider;\n readonly #featureFilters: Map<string, IFeatureFilter> = new Map();\n readonly #onFeatureEvaluated?: (event: EvaluationResult) => void;\n readonly #targetingContextAccessor?: ITargetingContextAccessor;\n\n constructor(provider: IFeatureFlagProvider, options?: FeatureManagerOptions) {\n this.#provider = provider;\n this.#onFeatureEvaluated = options?.onFeatureEvaluated;\n this.#targetingContextAccessor = options?.targetingContextAccessor;\n\n const builtinFilters = [new TimeWindowFilter(), new TargetingFilter(options?.targetingContextAccessor)];\n // If a custom filter shares a name with an existing filter, the custom filter overrides the existing one.\n for (const filter of [...builtinFilters, ...(options?.customFilters ?? [])]) {\n this.#featureFilters.set(filter.name, filter);\n }\n }\n\n async listFeatureNames(): Promise<string[]> {\n const features = await this.#provider.getFeatureFlags();\n const featureNameSet = new Set(features.map((feature) => feature.id));\n return Array.from(featureNameSet);\n }\n\n // If multiple feature flags are found, the first one takes precedence.\n async isEnabled(featureName: string, context?: unknown): Promise<boolean> {\n const result = await this.#evaluateFeature(featureName, context);\n return result.enabled;\n }\n\n async getVariant(featureName: string, context?: ITargetingContext): Promise<Variant | undefined> {\n const result = await this.#evaluateFeature(featureName, context);\n return result.variant;\n }\n\n async #assignVariant(featureFlag: FeatureFlag, context: ITargetingContext): Promise<VariantAssignment> {\n // user allocation\n if (featureFlag.allocation?.user !== undefined) {\n for (const userAllocation of featureFlag.allocation.user) {\n if (isTargetedUser(context.userId, userAllocation.users)) {\n return getVariantAssignment(featureFlag, userAllocation.variant, VariantAssignmentReason.User);\n }\n }\n }\n\n // group allocation\n if (featureFlag.allocation?.group !== undefined) {\n for (const groupAllocation of featureFlag.allocation.group) {\n if (isTargetedGroup(context.groups, groupAllocation.groups)) {\n return getVariantAssignment(featureFlag, groupAllocation.variant, VariantAssignmentReason.Group);\n }\n }\n }\n\n // percentile allocation\n if (featureFlag.allocation?.percentile !== undefined) {\n for (const percentileAllocation of featureFlag.allocation.percentile) {\n const hint = featureFlag.allocation.seed ?? `allocation\\n${featureFlag.id}`;\n if (await isTargetedPercentile(context.userId, hint, percentileAllocation.from, percentileAllocation.to)) {\n return getVariantAssignment(featureFlag, percentileAllocation.variant, VariantAssignmentReason.Percentile);\n }\n }\n }\n\n return { variant: undefined, reason: VariantAssignmentReason.None };\n }\n\n async #isEnabled(featureFlag: FeatureFlag, appContext?: unknown): Promise<boolean> {\n if (featureFlag.enabled !== true) {\n // If the feature is not explicitly enabled, then it is disabled by default.\n return false;\n }\n\n const clientFilters = featureFlag.conditions?.client_filters;\n if (clientFilters === undefined || clientFilters.length <= 0) {\n // If there are no client filters, then the feature is enabled.\n return true;\n }\n\n const requirementType: RequirementType = featureFlag.conditions?.requirement_type ?? \"Any\"; // default to any.\n\n /**\n * While iterating through the client filters, we short-circuit the evaluation based on the requirement type.\n * - 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.\n * - 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.\n */\n const shortCircuitEvaluationResult: boolean = requirementType === \"Any\";\n\n for (const clientFilter of clientFilters) {\n const matchedFeatureFilter = this.#featureFilters.get(clientFilter.name);\n const contextWithFeatureName = { featureName: featureFlag.id, parameters: clientFilter.parameters };\n if (matchedFeatureFilter === undefined) {\n console.warn(`Feature filter ${clientFilter.name} is not found.`);\n return false;\n }\n if (await matchedFeatureFilter.evaluate(contextWithFeatureName, appContext) === shortCircuitEvaluationResult) {\n return shortCircuitEvaluationResult;\n }\n }\n\n // If we get here, then we have not found a client filter that matches the requirement type.\n return !shortCircuitEvaluationResult;\n }\n\n async #evaluateFeature(featureName: string, appContext: unknown): Promise<EvaluationResult> {\n const featureFlag = await this.#provider.getFeatureFlag(featureName);\n const result = new EvaluationResult(featureFlag);\n\n if (featureFlag === undefined) {\n return result;\n }\n\n // 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.\n // TODO: move to the feature flag provider implementation.\n validateFeatureFlagFormat(featureFlag);\n\n // Evaluate if the feature is enabled.\n result.enabled = await this.#isEnabled(featureFlag, appContext);\n\n // Get targeting context from the app context or the targeting context accessor\n const targetingContext = this.#getTargetingContext(appContext);\n result.targetingId = targetingContext?.userId;\n\n // Determine Variant\n let variantDef: VariantDefinition | undefined;\n let reason: VariantAssignmentReason = VariantAssignmentReason.None;\n\n // featureFlag.variant not empty\n if (featureFlag.variants !== undefined && featureFlag.variants.length > 0) {\n if (!result.enabled) {\n // not enabled, assign default if specified\n if (featureFlag.allocation?.default_when_disabled !== undefined) {\n variantDef = featureFlag.variants.find(v => v.name == featureFlag.allocation?.default_when_disabled);\n reason = VariantAssignmentReason.DefaultWhenDisabled;\n } else {\n // no default specified\n variantDef = undefined;\n reason = VariantAssignmentReason.DefaultWhenDisabled;\n }\n } else {\n // enabled, assign based on allocation\n if (targetingContext !== undefined && featureFlag.allocation !== undefined) {\n const variantAndReason = await this.#assignVariant(featureFlag, targetingContext);\n variantDef = variantAndReason.variant;\n reason = variantAndReason.reason;\n }\n\n // allocation failed, assign default if specified\n if (variantDef === undefined && reason === VariantAssignmentReason.None) {\n if (featureFlag.allocation?.default_when_enabled !== undefined) {\n variantDef = featureFlag.variants.find(v => v.name == featureFlag.allocation?.default_when_enabled);\n reason = VariantAssignmentReason.DefaultWhenEnabled;\n } else {\n variantDef = undefined;\n reason = VariantAssignmentReason.DefaultWhenEnabled;\n }\n }\n }\n }\n\n result.variant = variantDef !== undefined ? new Variant(variantDef.name, variantDef.configuration_value) : undefined;\n result.variantAssignmentReason = reason;\n\n // Status override for isEnabled\n if (variantDef !== undefined && featureFlag.enabled) {\n if (variantDef.status_override === \"Enabled\") {\n result.enabled = true;\n } else if (variantDef.status_override === \"Disabled\") {\n result.enabled = false;\n }\n }\n\n // The callback will only be executed if telemetry is enabled for the feature flag\n if (featureFlag.telemetry?.enabled && this.#onFeatureEvaluated !== undefined) {\n this.#onFeatureEvaluated(result);\n }\n\n return result;\n }\n\n #getTargetingContext(context: unknown): ITargetingContext | undefined {\n let targetingContext: ITargetingContext | undefined = context as ITargetingContext;\n if (targetingContext?.userId === undefined &&\n targetingContext?.groups === undefined &&\n this.#targetingContextAccessor !== undefined) {\n targetingContext = this.#targetingContextAccessor.getTargetingContext();\n }\n return targetingContext;\n }\n}\n\nexport interface FeatureManagerOptions {\n /**\n * The custom filters to be used by the feature manager.\n */\n customFilters?: IFeatureFilter[];\n\n /**\n * The callback function that is called when a feature flag is evaluated.\n * The callback function is called only when telemetry is enabled for the feature flag.\n */\n onFeatureEvaluated?: (event: EvaluationResult) => void;\n\n /**\n * The accessor function that provides the @see ITargetingContext for targeting evaluation.\n */\n targetingContextAccessor?: ITargetingContextAccessor;\n}\n\nexport class EvaluationResult {\n constructor(\n // feature flag definition\n public readonly feature: FeatureFlag | undefined,\n\n // enabled state\n public enabled: boolean = false,\n\n // variant assignment\n public targetingId: string | undefined = undefined,\n public variant: Variant | undefined = undefined,\n public variantAssignmentReason: VariantAssignmentReason = VariantAssignmentReason.None\n ) { }\n}\n\nexport enum VariantAssignmentReason {\n /**\n * Variant allocation did not happen. No variant is assigned.\n */\n None = \"None\",\n\n /**\n * The default variant is assigned when a feature flag is disabled.\n */\n DefaultWhenDisabled = \"DefaultWhenDisabled\",\n\n /**\n * The default variant is assigned because of no applicable user/group/percentile allocation when a feature flag is enabled.\n */\n DefaultWhenEnabled = \"DefaultWhenEnabled\",\n\n /**\n * The variant is assigned because of the user allocation when a feature flag is enabled.\n */\n User = \"User\",\n\n /**\n * The variant is assigned because of the group allocation when a feature flag is enabled.\n */\n Group = \"Group\",\n\n /**\n * The variant is assigned because of the percentile allocation when a feature flag is enabled.\n */\n Percentile = \"Percentile\"\n}\n\n/**\n * Validates the format of the feature flag definition.\n *\n * FeatureFlag data objects are from IFeatureFlagProvider, depending on the implementation.\n * Thus the properties are not guaranteed to have the expected types.\n *\n * @param featureFlag The feature flag definition to validate.\n */\nfunction validateFeatureFlagFormat(featureFlag: any): void {\n if (featureFlag.enabled !== undefined && typeof featureFlag.enabled !== \"boolean\") {\n throw new Error(`Feature flag ${featureFlag.id} has an invalid 'enabled' value.`);\n }\n // TODO: add more validations.\n // TODO: should be moved to the feature flag provider.\n}\n\n/**\n * Try to get the variant assignment for the given variant name. If the variant is not found, override the reason with VariantAssignmentReason.None.\n *\n * @param featureFlag feature flag definition\n * @param variantName variant name\n * @param reason variant assignment reason\n * @returns variant assignment containing the variant definition and the reason\n */\nfunction getVariantAssignment(featureFlag: FeatureFlag, variantName: string, reason: VariantAssignmentReason): VariantAssignment {\n const variant = featureFlag.variants?.find(v => v.name == variantName);\n if (variant !== undefined) {\n return { variant, reason };\n } else {\n console.warn(`Variant ${variantName} not found for feature ${featureFlag.id}.`);\n return { variant: undefined, reason: VariantAssignmentReason.None };\n }\n}\n\ntype VariantAssignment = {\n variant: VariantDefinition | undefined;\n reason: VariantAssignmentReason;\n};\n"],"names":["TimeWindowFilter","TargetingFilter","isTargetedUser","VariantAssignmentReason","isTargetedGroup","isTargetedPercentile","Variant"],"mappings":";;;;;;;AAAA;AACA;MAWa,cAAc,CAAA;AACd,IAAA,SAAS;AACT,IAAA,eAAe,GAAgC,IAAI,GAAG,EAAE;AACxD,IAAA,mBAAmB;AACnB,IAAA,yBAAyB;IAElC,WAAA,CAAY,QAA8B,EAAE,OAA+B,EAAA;AACvE,QAAA,IAAI,CAAC,SAAS,GAAG,QAAQ;AACzB,QAAA,IAAI,CAAC,mBAAmB,GAAG,OAAO,EAAE,kBAAkB;AACtD,QAAA,IAAI,CAAC,yBAAyB,GAAG,OAAO,EAAE,wBAAwB;AAElE,QAAA,MAAM,cAAc,GAAG,CAAC,IAAIA,iCAAgB,EAAE,EAAE,IAAIC,+BAAe,CAAC,OAAO,EAAE,wBAAwB,CAAC,CAAC;;AAEvG,QAAA,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,cAAc,EAAE,IAAI,OAAO,EAAE,aAAa,IAAI,EAAE,CAAC,CAAC,EAAE;YACzE,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC;QACjD;IACJ;AAEA,IAAA,MAAM,gBAAgB,GAAA;QAClB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,eAAe,EAAE;AACvD,QAAA,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,QA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3,"file":"featureProvider.js","sources":["../../src/featureProvider.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { IGettable } from \"./gettable.js\";\nimport { FeatureFlag, FeatureManagementConfiguration, FEATURE_MANAGEMENT_KEY, FEATURE_FLAGS_KEY } from \"./schema/model.js\";\nimport { validateFeatureFlag } from \"./schema/validator.js\";\n\nexport interface IFeatureFlagProvider {\n /**\n * Get all feature flags.\n */\n getFeatureFlags(): Promise<FeatureFlag[]>;\n\n /**\n * Get a feature flag by name.\n * @param featureName The name of the feature flag.\n */\n getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined>;\n}\n\n/**\n * A feature flag provider that uses a map-like configuration to provide feature flags.\n */\nexport class ConfigurationMapFeatureFlagProvider implements IFeatureFlagProvider {\n #configuration: IGettable;\n\n constructor(configuration: IGettable) {\n this.#configuration = configuration;\n }\n async getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined> {\n const featureConfig = this.#configuration.get<FeatureManagementConfiguration>(FEATURE_MANAGEMENT_KEY);\n const featureFlag = featureConfig?.[FEATURE_FLAGS_KEY]?.findLast((feature) => feature.id === featureName);\n validateFeatureFlag(featureFlag);\n return featureFlag;\n }\n\n async getFeatureFlags(): Promise<FeatureFlag[]> {\n const featureConfig = this.#configuration.get<FeatureManagementConfiguration>(FEATURE_MANAGEMENT_KEY);\n const featureFlags = featureConfig?.[FEATURE_FLAGS_KEY] ?? [];\n featureFlags.forEach(featureFlag => {\n validateFeatureFlag(featureFlag);\n });\n return featureFlags;\n }\n}\n\n/**\n * A feature flag provider that uses an object-like configuration to provide feature flags.\n */\nexport class ConfigurationObjectFeatureFlagProvider implements IFeatureFlagProvider {\n #configuration: Record<string, unknown>;\n\n constructor(configuration: Record<string, unknown>) {\n this.#configuration = configuration;\n }\n\n async getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined> {\n const featureFlags = this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY];\n const featureFlag = featureFlags?.findLast((feature: FeatureFlag) => feature.id === featureName);\n validateFeatureFlag(featureFlag);\n return featureFlag;\n }\n\n async getFeatureFlags(): Promise<FeatureFlag[]> {\n const featureFlags = this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY] ?? [];\n featureFlags.forEach(featureFlag => {\n validateFeatureFlag(featureFlag);\n });\n return featureFlags;\n }\n}\n"],"names":["FEATURE_MANAGEMENT_KEY","FEATURE_FLAGS_KEY","validateFeatureFlag"],"mappings":";;;;;AAAA;AACA;AAmBA;;AAEG;MACU,mCAAmC,CAAA;AAC5C,IAAA,cAAc,CAAY;AAE1B,IAAA,WAAA,CAAY,aAAwB,EAAA;AAChC,QAAA,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;KACvC;IACD,MAAM,cAAc,CAAC,WAAmB,EAAA;QACpC,MAAM,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAiCA,4BAAsB,CAAC,CAAC;QACtG,MAAM,WAAW,GAAG,aAAa,GAAGC,uBAAiB,CAAC,EAAE,QAAQ,CAAC,CAAC,OAAO,KAAK,OAAO,CAAC,EAAE,KAAK,WAAW,CAAC,CAAC;QAC1GC,6BAAmB,CAAC,WAAW,CAAC,CAAC;AACjC,QAAA,OAAO,WAAW,CAAC;KACtB;AAED,IAAA,MAAM,eAAe,GAAA;QACjB,MAAM,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAiCF,4BAAsB,CAAC,CAAC;QACtG,MAAM,YAAY,GAAG,aAAa,GAAGC,uBAAiB,CAAC,IAAI,EAAE,CAAC;AAC9D,QAAA,YAAY,CAAC,OAAO,CAAC,WAAW,IAAG;YAC/BC,6BAAmB,CAAC,WAAW,CAAC,CAAC;AACrC,SAAC,CAAC,CAAC;AACH,QAAA,OAAO,YAAY,CAAC;KACvB;AACJ,CAAA;AAED;;AAEG;MACU,sCAAsC,CAAA;AAC/C,IAAA,cAAc,CAA0B;AAExC,IAAA,WAAA,CAAY,aAAsC,EAAA;AAC9C,QAAA,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;KACvC;IAED,MAAM,cAAc,CAAC,WAAmB,EAAA;AACpC,QAAA,MAAM,YAAY,GAAG,IAAI,CAAC,cAAc,CAACF,4BAAsB,CAAC,GAAGC,uBAAiB,CAAC,CAAC;AACtF,QAAA,MAAM,WAAW,GAAG,YAAY,EAAE,QAAQ,CAAC,CAAC,OAAoB,KAAK,OAAO,CAAC,EAAE,KAAK,WAAW,CAAC,CAAC;QACjGC,6BAAmB,CAAC,WAAW,CAAC,CAAC;AACjC,QAAA,OAAO,WAAW,CAAC;KACtB;AAED,IAAA,MAAM,eAAe,GAAA;AACjB,QAAA,MAAM,YAAY,GAAG,IAAI,CAAC,cAAc,CAACF,4BAAsB,CAAC,GAAGC,uBAAiB,CAAC,IAAI,EAAE,CAAC;AAC5F,QAAA,YAAY,CAAC,OAAO,CAAC,WAAW,IAAG;YAC/BC,6BAAmB,CAAC,WAAW,CAAC,CAAC;AACrC,SAAC,CAAC,CAAC;AACH,QAAA,OAAO,YAAY,CAAC;KACvB;AACJ;;;;;"}
1
+ {"version":3,"file":"featureProvider.js","sources":["../../src/featureProvider.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { IGettable } from \"./gettable.js\";\nimport { FeatureFlag, FeatureManagementConfiguration, FEATURE_MANAGEMENT_KEY, FEATURE_FLAGS_KEY } from \"./schema/model.js\";\nimport { IFeatureFlagProvider } from \"./model.js\";\nimport { validateFeatureFlag } from \"./schema/validator.js\";\n\n/**\n * A feature flag provider that uses a map-like configuration to provide feature flags.\n */\nexport class ConfigurationMapFeatureFlagProvider implements IFeatureFlagProvider {\n #configuration: IGettable;\n\n constructor(configuration: IGettable) {\n this.#configuration = configuration;\n }\n async getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined> {\n const featureConfig = this.#configuration.get<FeatureManagementConfiguration>(FEATURE_MANAGEMENT_KEY);\n const featureFlag = featureConfig?.[FEATURE_FLAGS_KEY]?.findLast((feature) => feature.id === featureName);\n validateFeatureFlag(featureFlag);\n return featureFlag;\n }\n\n async getFeatureFlags(): Promise<FeatureFlag[]> {\n const featureConfig = this.#configuration.get<FeatureManagementConfiguration>(FEATURE_MANAGEMENT_KEY);\n const featureFlags = featureConfig?.[FEATURE_FLAGS_KEY] ?? [];\n featureFlags.forEach(featureFlag => {\n validateFeatureFlag(featureFlag);\n });\n return featureFlags;\n }\n}\n\n/**\n * A feature flag provider that uses an object-like configuration to provide feature flags.\n */\nexport class ConfigurationObjectFeatureFlagProvider implements IFeatureFlagProvider {\n #configuration: Record<string, unknown>;\n\n constructor(configuration: Record<string, unknown>) {\n this.#configuration = configuration;\n }\n\n async getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined> {\n const featureFlags = this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY];\n const featureFlag = featureFlags?.findLast((feature: FeatureFlag) => feature.id === featureName);\n validateFeatureFlag(featureFlag);\n return featureFlag;\n }\n\n async getFeatureFlags(): Promise<FeatureFlag[]> {\n const featureFlags = this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY] ?? [];\n featureFlags.forEach(featureFlag => {\n validateFeatureFlag(featureFlag);\n });\n return featureFlags;\n }\n}\n"],"names":["FEATURE_MANAGEMENT_KEY","FEATURE_FLAGS_KEY","validateFeatureFlag"],"mappings":";;;;;AAAA;AACA;AAOA;;AAEG;MACU,mCAAmC,CAAA;AAC5C,IAAA,cAAc;AAEd,IAAA,WAAA,CAAY,aAAwB,EAAA;AAChC,QAAA,IAAI,CAAC,cAAc,GAAG,aAAa;IACvC;IACA,MAAM,cAAc,CAAC,WAAmB,EAAA;QACpC,MAAM,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAiCA,4BAAsB,CAAC;QACrG,MAAM,WAAW,GAAG,aAAa,GAAGC,uBAAiB,CAAC,EAAE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require('./utils.js');
5
+
6
+ // Copyright (c) Microsoft Corporation.
7
+ // Licensed under the MIT license.
8
+ /**
9
+ * Checks if a provided datetime is within any recurring time window specified by the recurrence information
10
+ * @param time A datetime
11
+ * @param recurrenceSpec The recurrence spcification
12
+ * @returns True if the given time is within any recurring time window; otherwise, false
13
+ */
14
+ function matchRecurrence(time, recurrenceSpec) {
15
+ const recurrenceState = findPreviousRecurrence(time, recurrenceSpec);
16
+ if (recurrenceState) {
17
+ return time.getTime() < recurrenceState.previousOccurrence.getTime() + recurrenceSpec.duration;
18
+ }
19
+ return false;
20
+ }
21
+ /**
22
+ * Finds the closest previous recurrence occurrence before the given time according to the recurrence information
23
+ * @param time A datetime
24
+ * @param recurrenceSpec The recurrence specification
25
+ * @returns The recurrence state if any previous occurrence is found; otherwise, undefined
26
+ */
27
+ function findPreviousRecurrence(time, recurrenceSpec) {
28
+ if (time < recurrenceSpec.startTime) {
29
+ return undefined;
30
+ }
31
+ let result;
32
+ const pattern = recurrenceSpec.pattern;
33
+ if (pattern.type === model.RecurrencePatternType.Daily) {
34
+ result = findPreviousDailyRecurrence(time, recurrenceSpec);
35
+ }
36
+ else if (pattern.type === model.RecurrencePatternType.Weekly) {
37
+ result = findPreviousWeeklyRecurrence(time, recurrenceSpec);
38
+ }
39
+ else {
40
+ throw new Error("Unsupported recurrence pattern type.");
41
+ }
42
+ const { previousOccurrence, numberOfOccurrences } = result;
43
+ const range = recurrenceSpec.range;
44
+ if (range.type === model.RecurrenceRangeType.EndDate) {
45
+ if (previousOccurrence > range.endDate) {
46
+ return undefined;
47
+ }
48
+ }
49
+ else if (range.type === model.RecurrenceRangeType.Numbered) {
50
+ if (numberOfOccurrences > range.numberOfOccurrences) {
51
+ return undefined;
52
+ }
53
+ }
54
+ return result;
55
+ }
56
+ function findPreviousDailyRecurrence(time, recurrenceSpec) {
57
+ const startTime = recurrenceSpec.startTime;
58
+ const timeGap = time.getTime() - startTime.getTime();
59
+ const pattern = recurrenceSpec.pattern;
60
+ const numberOfIntervals = Math.floor(timeGap / (pattern.interval * model.ONE_DAY_IN_MILLISECONDS));
61
+ return {
62
+ previousOccurrence: utils.addDays(startTime, numberOfIntervals * pattern.interval),
63
+ numberOfOccurrences: numberOfIntervals + 1
64
+ };
65
+ }
66
+ function findPreviousWeeklyRecurrence(time, recurrenceSpec) {
67
+ /*
68
+ * Algorithm:
69
+ * 1. first find day 0 (d0), it's the day representing the start day on the week of `Start`.
70
+ * 2. find start day of the most recent occurring week d0 + floor((time - d0) / (interval * 7)) * (interval * 7)
71
+ * 3. if that's over 7 days ago, then previous occurence is the day with the max offset of the last occurring week
72
+ * 4. if gotten this far, then the current week is the most recent occurring week:
73
+ i. if time > day with min offset, then previous occurence is the day with max offset less than current
74
+ ii. if time < day with min offset, then previous occurence is the day with the max offset of previous occurring week
75
+ */
76
+ const startTime = recurrenceSpec.startTime;
77
+ const startDay = utils.getDayOfWeek(startTime, recurrenceSpec.timezoneOffset);
78
+ const pattern = recurrenceSpec.pattern;
79
+ const sortedDaysOfWeek = utils.sortDaysOfWeek(pattern.daysOfWeek, pattern.firstDayOfWeek);
80
+ /*
81
+ * Example:
82
+ * startTime = 2024-12-11 (Tue)
83
+ * pattern.interval = 2 pattern.firstDayOfWeek = Sun pattern.daysOfWeek = [Wed, Sun]
84
+ * sortedDaysOfWeek = [Sun, Wed]
85
+ * firstDayofStartWeek = 2024-12-08 (Sun)
86
+ *
87
+ * time = 2024-12-23 (Mon) timeGap = 15 days
88
+ * the most recent occurring week: 2024-12-22 ~ 2024-12-28
89
+ * number of intervals before the most recent occurring week = 15 / (2 * 7) = 1 (2024-12-08 ~ 2023-12-21)
90
+ * number of occurrences before the most recent occurring week = 1 * 2 - 1 = 1 (2024-12-11)
91
+ * firstDayOfLastOccurringWeek = 2024-12-22
92
+ */
93
+ const firstDayofStartWeek = utils.addDays(startTime, -utils.calculateWeeklyDayOffset(startDay, pattern.firstDayOfWeek));
94
+ const timeGap = time.getTime() - firstDayofStartWeek.getTime();
95
+ // number of intervals before the most recent occurring week
96
+ const numberOfIntervals = Math.floor(timeGap / (pattern.interval * model.DAYS_PER_WEEK * model.ONE_DAY_IN_MILLISECONDS));
97
+ // number of occurrences before the most recent occurring week, it is possible to be negative
98
+ let numberOfOccurrences = numberOfIntervals * sortedDaysOfWeek.length - sortedDaysOfWeek.indexOf(startDay);
99
+ const firstDayOfLatestOccurringWeek = utils.addDays(firstDayofStartWeek, numberOfIntervals * pattern.interval * model.DAYS_PER_WEEK);
100
+ // the current time is out of the last occurring week
101
+ if (time > utils.addDays(firstDayOfLatestOccurringWeek, model.DAYS_PER_WEEK)) {
102
+ numberOfOccurrences += utils.sortDaysOfWeek.length;
103
+ // day with max offset in the last occurring week
104
+ const previousOccurrence = utils.addDays(firstDayOfLatestOccurringWeek, utils.calculateWeeklyDayOffset(sortedDaysOfWeek.at(-1), pattern.firstDayOfWeek));
105
+ return {
106
+ previousOccurrence: previousOccurrence,
107
+ numberOfOccurrences: numberOfOccurrences
108
+ };
109
+ }
110
+ let dayWithMinOffset = utils.addDays(firstDayOfLatestOccurringWeek, utils.calculateWeeklyDayOffset(sortedDaysOfWeek[0], pattern.firstDayOfWeek));
111
+ if (dayWithMinOffset < startTime) {
112
+ numberOfOccurrences = 0;
113
+ dayWithMinOffset = startTime;
114
+ }
115
+ let previousOccurrence;
116
+ if (time >= dayWithMinOffset) {
117
+ // the previous occurence is the day with max offset less than current
118
+ previousOccurrence = dayWithMinOffset;
119
+ numberOfOccurrences += 1;
120
+ const dayWithMinOffsetIndex = sortedDaysOfWeek.indexOf(utils.getDayOfWeek(dayWithMinOffset, recurrenceSpec.timezoneOffset));
121
+ for (let i = dayWithMinOffsetIndex + 1; i < sortedDaysOfWeek.length; i++) {
122
+ const day = utils.addDays(firstDayOfLatestOccurringWeek, utils.calculateWeeklyDayOffset(sortedDaysOfWeek[i], pattern.firstDayOfWeek));
123
+ if (time < day) {
124
+ break;
125
+ }
126
+ previousOccurrence = day;
127
+ numberOfOccurrences += 1;
128
+ }
129
+ }
130
+ else {
131
+ const firstDayOfPreviousOccurringWeek = utils.addDays(firstDayOfLatestOccurringWeek, -pattern.interval * model.DAYS_PER_WEEK);
132
+ // the previous occurence is the day with the max offset of previous occurring week
133
+ previousOccurrence = utils.addDays(firstDayOfPreviousOccurringWeek, utils.calculateWeeklyDayOffset(sortedDaysOfWeek.at(-1), pattern.firstDayOfWeek));
134
+ }
135
+ return {
136
+ previousOccurrence: previousOccurrence,
137
+ numberOfOccurrences: numberOfOccurrences
138
+ };
139
+ }
140
+
141
+ exports.matchRecurrence = matchRecurrence;
142
+ //# sourceMappingURL=evaluator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evaluator.js","sources":["../../../../src/filter/recurrence/evaluator.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { RecurrenceSpec, RecurrencePatternType, RecurrenceRangeType, DAYS_PER_WEEK, ONE_DAY_IN_MILLISECONDS } from \"./model.js\";\nimport { calculateWeeklyDayOffset, sortDaysOfWeek, getDayOfWeek, addDays } from \"./utils.js\";\n\ntype RecurrenceState = {\n previousOccurrence: Date;\n numberOfOccurrences: number;\n}\n\n/**\n * Checks if a provided datetime is within any recurring time window specified by the recurrence information\n * @param time A datetime\n * @param recurrenceSpec The recurrence spcification\n * @returns True if the given time is within any recurring time window; otherwise, false\n */\nexport function matchRecurrence(time: Date, recurrenceSpec: RecurrenceSpec): boolean {\n const recurrenceState = findPreviousRecurrence(time, recurrenceSpec);\n if (recurrenceState) {\n return time.getTime() < recurrenceState.previousOccurrence.getTime() + recurrenceSpec.duration;\n }\n return false;\n}\n\n/**\n * Finds the closest previous recurrence occurrence before the given time according to the recurrence information\n * @param time A datetime\n * @param recurrenceSpec The recurrence specification\n * @returns The recurrence state if any previous occurrence is found; otherwise, undefined\n */\nfunction findPreviousRecurrence(time: Date, recurrenceSpec: RecurrenceSpec): RecurrenceState | undefined {\n if (time < recurrenceSpec.startTime) {\n return undefined;\n }\n let result: RecurrenceState;\n const pattern = recurrenceSpec.pattern;\n if (pattern.type === RecurrencePatternType.Daily) {\n result = findPreviousDailyRecurrence(time, recurrenceSpec);\n } else if (pattern.type === RecurrencePatternType.Weekly) {\n result = findPreviousWeeklyRecurrence(time, recurrenceSpec);\n } else {\n throw new Error(\"Unsupported recurrence pattern type.\");\n }\n const { previousOccurrence, numberOfOccurrences } = result;\n\n const range = recurrenceSpec.range;\n if (range.type === RecurrenceRangeType.EndDate) {\n if (previousOccurrence > range.endDate!) {\n return undefined;\n }\n } else if (range.type === RecurrenceRangeType.Numbered) {\n if (numberOfOccurrences > range.numberOfOccurrences!) {\n return undefined;\n }\n }\n return result;\n}\n\nfunction findPreviousDailyRecurrence(time: Date, recurrenceSpec: RecurrenceSpec): RecurrenceState {\n const startTime = recurrenceSpec.startTime;\n const timeGap = time.getTime() - startTime.getTime();\n const pattern = recurrenceSpec.pattern;\n const numberOfIntervals = Math.floor(timeGap / (pattern.interval * ONE_DAY_IN_MILLISECONDS));\n return {\n previousOccurrence: addDays(startTime, numberOfIntervals * pattern.interval),\n numberOfOccurrences: numberOfIntervals + 1\n };\n}\n\nfunction findPreviousWeeklyRecurrence(time: Date, recurrenceSpec: RecurrenceSpec): RecurrenceState {\n /*\n * Algorithm:\n * 1. first find day 0 (d0), it's the day representing the start day on the week of `Start`.\n * 2. find start day of the most recent occurring week d0 + floor((time - d0) / (interval * 7)) * (interval * 7)\n * 3. if that's over 7 days ago, then previous occurence is the day with the max offset of the last occurring week\n * 4. if gotten this far, then the current week is the most recent occurring week:\n i. if time > day with min offset, then previous occurence is the day with max offset less than current\n ii. if time < day with min offset, then previous occurence is the day with the max offset of previous occurring week\n */\n const startTime = recurrenceSpec.startTime;\n const startDay = getDayOfWeek(startTime, recurrenceSpec.timezoneOffset);\n const pattern = recurrenceSpec.pattern;\n const sortedDaysOfWeek = sortDaysOfWeek(pattern.daysOfWeek!, pattern.firstDayOfWeek!);\n\n /*\n * Example:\n * startTime = 2024-12-11 (Tue)\n * pattern.interval = 2 pattern.firstDayOfWeek = Sun pattern.daysOfWeek = [Wed, Sun]\n * sortedDaysOfWeek = [Sun, Wed]\n * firstDayofStartWeek = 2024-12-08 (Sun)\n *\n * time = 2024-12-23 (Mon) timeGap = 15 days\n * the most recent occurring week: 2024-12-22 ~ 2024-12-28\n * number of intervals before the most recent occurring week = 15 / (2 * 7) = 1 (2024-12-08 ~ 2023-12-21)\n * number of occurrences before the most recent occurring week = 1 * 2 - 1 = 1 (2024-12-11)\n * firstDayOfLastOccurringWeek = 2024-12-22\n */\n const firstDayofStartWeek = addDays(startTime, -calculateWeeklyDayOffset(startDay, pattern.firstDayOfWeek!));\n const timeGap = time.getTime() - firstDayofStartWeek.getTime();\n // number of intervals before the most recent occurring week\n const numberOfIntervals = Math.floor(timeGap / (pattern.interval * DAYS_PER_WEEK * ONE_DAY_IN_MILLISECONDS));\n // number of occurrences before the most recent occurring week, it is possible to be negative\n let numberOfOccurrences = numberOfIntervals * sortedDaysOfWeek.length - sortedDaysOfWeek.indexOf(startDay);\n const firstDayOfLatestOccurringWeek = addDays(firstDayofStartWeek, numberOfIntervals * pattern.interval * DAYS_PER_WEEK);\n\n // the current time is out of the last occurring week\n if (time > addDays(firstDayOfLatestOccurringWeek, DAYS_PER_WEEK)) {\n numberOfOccurrences += sortDaysOfWeek.length;\n // day with max offset in the last occurring week\n const previousOccurrence = addDays(firstDayOfLatestOccurringWeek, calculateWeeklyDayOffset(sortedDaysOfWeek.at(-1)!, pattern.firstDayOfWeek!));\n return {\n previousOccurrence: previousOccurrence,\n numberOfOccurrences: numberOfOccurrences\n };\n }\n\n let dayWithMinOffset = addDays(firstDayOfLatestOccurringWeek, calculateWeeklyDayOffset(sortedDaysOfWeek[0], pattern.firstDayOfWeek!));\n if (dayWithMinOffset < startTime) {\n numberOfOccurrences = 0;\n dayWithMinOffset = startTime;\n }\n let previousOccurrence;\n if (time >= dayWithMinOffset) {\n // the previous occurence is the day with max offset less than current\n previousOccurrence = dayWithMinOffset;\n numberOfOccurrences += 1;\n const dayWithMinOffsetIndex = sortedDaysOfWeek.indexOf(getDayOfWeek(dayWithMinOffset, recurrenceSpec.timezoneOffset));\n for (let i = dayWithMinOffsetIndex + 1; i < sortedDaysOfWeek.length; i++) {\n const day = addDays(firstDayOfLatestOccurringWeek, calculateWeeklyDayOffset(sortedDaysOfWeek[i], pattern.firstDayOfWeek!));\n if (time < day) {\n break;\n }\n previousOccurrence = day;\n numberOfOccurrences += 1;\n }\n } else {\n const firstDayOfPreviousOccurringWeek = addDays(firstDayOfLatestOccurringWeek, -pattern.interval * DAYS_PER_WEEK);\n // the previous occurence is the day with the max offset of previous occurring week\n previousOccurrence = addDays(firstDayOfPreviousOccurringWeek, calculateWeeklyDayOffset(sortedDaysOfWeek.at(-1)!, pattern.firstDayOfWeek!));\n }\n return {\n previousOccurrence: previousOccurrence,\n numberOfOccurrences: numberOfOccurrences\n };\n}\n"],"names":["RecurrencePatternType","RecurrenceRangeType","ONE_DAY_IN_MILLISECONDS","addDays","getDayOfWeek","sortDaysOfWeek","calculateWeeklyDayOffset","DAYS_PER_WEEK"],"mappings":";;;;;AAAA;AACA;AAUA;;;;;AAKG;AACG,SAAU,eAAe,CAAC,IAAU,EAAE,cAA8B,EAAA;IACtE,MAAM,eAAe,GAAG,sBAAsB,CAAC,IAAI,EAAE,cAAc,CAAC;IACpE,IAAI,eAAe,EAAE;AACjB,QAAA,OAAO,IAAI,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC,kBAAkB,CAAC,OAAO,EAAE,GAAG,cAAc,CAAC,QAAQ;IAClG;AACA,IAAA,OAAO,KAAK;AAChB;AAEA;;;;;AAKG;AACH,SAAS,sBAAsB,CAAC,IAAU,EAAE,cAA8B,EAAA;AACtE,IAAA,IAAI,IAAI,GAAG,cAAc,CAAC,SAAS,EAAE;AACjC,QAAA,OAAO,SAAS;IACpB;AACA,IAAA,IAAI,MAAuB;AAC3B,IAAA,MAAM,OAAO,GAAG,cA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AC;IAC9I;IACA,OAAO;AACH,QAAA,kBAAkB,EAAE,kBAAkB;AACtC,QAAA,mBAAmB,EAAE;KACxB;AACL;;;;"}
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+
3
+ // Copyright (c) Microsoft Corporation.
4
+ // Licensed under the MIT license.
5
+ const DAYS_PER_WEEK = 7;
6
+ const ONE_DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000;
7
+ exports.DayOfWeek = void 0;
8
+ (function (DayOfWeek) {
9
+ DayOfWeek[DayOfWeek["Sunday"] = 0] = "Sunday";
10
+ DayOfWeek[DayOfWeek["Monday"] = 1] = "Monday";
11
+ DayOfWeek[DayOfWeek["Tuesday"] = 2] = "Tuesday";
12
+ DayOfWeek[DayOfWeek["Wednesday"] = 3] = "Wednesday";
13
+ DayOfWeek[DayOfWeek["Thursday"] = 4] = "Thursday";
14
+ DayOfWeek[DayOfWeek["Friday"] = 5] = "Friday";
15
+ DayOfWeek[DayOfWeek["Saturday"] = 6] = "Saturday";
16
+ })(exports.DayOfWeek || (exports.DayOfWeek = {}));
17
+ /**
18
+ * The recurrence pattern describes the frequency by which the time window repeats
19
+ */
20
+ exports.RecurrencePatternType = void 0;
21
+ (function (RecurrencePatternType) {
22
+ /**
23
+ * The pattern where the time window will repeat based on the number of days specified by interval between occurrences
24
+ */
25
+ RecurrencePatternType[RecurrencePatternType["Daily"] = 0] = "Daily";
26
+ /**
27
+ * The pattern where the time window will repeat on the same day or days of the week, based on the number of weeks between each set of occurrences
28
+ */
29
+ RecurrencePatternType[RecurrencePatternType["Weekly"] = 1] = "Weekly";
30
+ })(exports.RecurrencePatternType || (exports.RecurrencePatternType = {}));
31
+ /**
32
+ * The recurrence range specifies the date range over which the time window repeats
33
+ */
34
+ exports.RecurrenceRangeType = void 0;
35
+ (function (RecurrenceRangeType) {
36
+ /**
37
+ * The recurrence has no end and repeats on all the days that fit the corresponding pattern
38
+ */
39
+ RecurrenceRangeType[RecurrenceRangeType["NoEnd"] = 0] = "NoEnd";
40
+ /**
41
+ * The recurrence repeats on all the days that fit the corresponding pattern until or on the specified end date
42
+ */
43
+ RecurrenceRangeType[RecurrenceRangeType["EndDate"] = 1] = "EndDate";
44
+ /**
45
+ * The recurrence repeats for the specified number of occurrences that match the pattern
46
+ */
47
+ RecurrenceRangeType[RecurrenceRangeType["Numbered"] = 2] = "Numbered";
48
+ })(exports.RecurrenceRangeType || (exports.RecurrenceRangeType = {}));
49
+
50
+ exports.DAYS_PER_WEEK = DAYS_PER_WEEK;
51
+ exports.ONE_DAY_IN_MILLISECONDS = ONE_DAY_IN_MILLISECONDS;
52
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sources":["../../../../src/filter/recurrence/model.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport const DAYS_PER_WEEK = 7;\nexport const ONE_DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000;\n\nexport enum DayOfWeek {\n Sunday = 0,\n Monday = 1,\n Tuesday = 2,\n Wednesday = 3,\n Thursday = 4,\n Friday = 5,\n Saturday = 6\n}\n\n/**\n * The recurrence pattern describes the frequency by which the time window repeats\n */\nexport enum RecurrencePatternType {\n /**\n * The pattern where the time window will repeat based on the number of days specified by interval between occurrences\n */\n Daily,\n /**\n * The pattern where the time window will repeat on the same day or days of the week, based on the number of weeks between each set of occurrences\n */\n Weekly\n}\n\n/**\n * The recurrence range specifies the date range over which the time window repeats\n */\nexport enum RecurrenceRangeType {\n /**\n * The recurrence has no end and repeats on all the days that fit the corresponding pattern\n */\n NoEnd,\n /**\n * The recurrence repeats on all the days that fit the corresponding pattern until or on the specified end date\n */\n EndDate,\n /**\n * The recurrence repeats for the specified number of occurrences that match the pattern\n */\n Numbered\n}\n\n/**\n * The recurrence pattern describes the frequency by which the time window repeats\n */\nexport type RecurrencePattern = {\n /**\n * The type of the recurrence pattern\n */\n type: RecurrencePatternType;\n /**\n * The number of units between occurrences, where units can be in days or weeks, depending on the pattern type\n */\n interval: number;\n /**\n * The days of the week when the time window occurs, which is only applicable for 'Weekly' pattern\n */\n daysOfWeek?: DayOfWeek[];\n /**\n * The first day of the week, which is only applicable for 'Weekly' pattern\n */\n firstDayOfWeek?: DayOfWeek;\n};\n\n/**\n * The recurrence range describes a date range over which the time window repeats\n */\nexport type RecurrenceRange = {\n /**\n * The type of the recurrence range\n */\n type: RecurrenceRangeType;\n /**\n * The date to stop applying the recurrence pattern, which is only applicable for 'EndDate' range\n */\n endDate?: Date;\n /**\n * The number of times to repeat the time window, which is only applicable for 'Numbered' range\n */\n numberOfOccurrences?: number;\n};\n\n/**\n * Specification defines the recurring time window\n */\nexport type RecurrenceSpec = {\n /**\n * The start time of the first/base time window\n */\n startTime: Date;\n /**\n * The duration of each time window in milliseconds\n */\n duration: number;\n /**\n * The recurrence pattern\n */\n pattern: RecurrencePattern;\n /**\n * The recurrence range\n */\n range: RecurrenceRange;\n /**\n * The timezone offset in milliseconds, which helps to determine the day of week of a given date\n */\n timezoneOffset: number;\n};\n"],"names":["DayOfWeek","RecurrencePatternType","RecurrenceRangeType"],"mappings":";;AAAA;AACA;AAEO,MAAM,aAAa,GAAG;AACtB,MAAM,uBAAuB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG;AAE1CA;AAAZ,CAAA,UAAY,SAAS,EAAA;AACjB,IAAA,SAAA,CAAA,SAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACV,IAAA,SAAA,CAAA,SAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACV,IAAA,SAAA,CAAA,SAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAW;AACX,IAAA,SAAA,CAAA,SAAA,CAAA,WAAA,CAAA,GAAA,CAAA,CAAA,GAAA,WAAa;AACb,IAAA,SAAA,CAAA,SAAA,CAAA,UAAA,CAAA,GAAA,CAAA,CAAA,GAAA,UAAY;AACZ,IAAA,SAAA,CAAA,SAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAU;AACV,IAAA,SAAA,CAAA,SAAA,CAAA,UAAA,CAAA,GAAA,CAAA,CAAA,GAAA,UAAY;AAChB,CAAC,EARWA,iBAAS,KAATA,iBAAS,GAAA,EAAA,CAAA,CAAA;AAUrB;;AAEG;AACSC;AAAZ,CAAA,UAAY,qBAAqB,EAAA;AAC7B;;AAEG;AACH,IAAA,qBAAA,CAAA,qBAAA,CAAA,OAAA,CAAA,GAAA,CAAA,CAAA,GAAA,OAAK;AACL;;AAEG;AACH,IAAA,qBAAA,CAAA,qBAAA,CAAA,QAAA,CAAA,GAAA,CAAA,CAAA,GAAA,QAAM;AACV,CAAC,EATWA,6BAAqB,KAArBA,6BAAqB,GAAA,EAAA,CAAA,CAAA;AAWjC;;AAEG;AACSC;AAAZ,CAAA,UAAY,mBAAmB,EAAA;AAC3B;;AAEG;AACH,IAAA,mBAAA,CAAA,mBAAA,CAAA,OAAA,CAAA,GAAA,CAAA,CAAA,GAAA,OAAK;AACL;;AAEG;AACH,IAAA,mBAAA,CAAA,mBAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAO;AACP;;AAEG;AACH,IAAA,mBAAA,CAAA,mBAAA,CAAA,UAAA,CAAA,GAAA,CAAA,CAAA,GAAA,UAAQ;AACZ,CAAC,EAbWA,2BAAmB,KAAnBA,2BAAmB,GAAA,EAAA,CAAA,CAAA;;;;;"}
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+
3
+ var model = require('./model.js');
4
+
5
+ // Copyright (c) Microsoft Corporation.
6
+ // Licensed under the MIT license.
7
+ /**
8
+ * Calculates the offset in days between two given days of the week.
9
+ * @param day1 A day of week
10
+ * @param day2 A day of week
11
+ * @returns The number of days to be added to day2 to reach day1
12
+ */
13
+ function calculateWeeklyDayOffset(day1, day2) {
14
+ return (day1 - day2 + model.DAYS_PER_WEEK) % model.DAYS_PER_WEEK;
15
+ }
16
+ /**
17
+ * Sorts a collection of days of week based on their offsets from a specified first day of week.
18
+ * @param daysOfWeek A collection of days of week
19
+ * @param firstDayOfWeek The first day of week which will be the first element in the sorted result
20
+ * @returns The sorted days of week
21
+ */
22
+ function sortDaysOfWeek(daysOfWeek, firstDayOfWeek) {
23
+ const sortedDaysOfWeek = daysOfWeek.slice();
24
+ sortedDaysOfWeek.sort((x, y) => calculateWeeklyDayOffset(x, firstDayOfWeek) - calculateWeeklyDayOffset(y, firstDayOfWeek));
25
+ return sortedDaysOfWeek;
26
+ }
27
+ /**
28
+ * Gets the day of week of a given date based on the timezone offset.
29
+ * @param date A UTC date
30
+ * @param timezoneOffsetInMs The timezone offset in milliseconds
31
+ * @returns The day of week (0 for Sunday, 1 for Monday, ..., 6 for Saturday)
32
+ */
33
+ function getDayOfWeek(date, timezoneOffsetInMs) {
34
+ const alignedDate = new Date(date.getTime() + timezoneOffsetInMs);
35
+ return alignedDate.getUTCDay();
36
+ }
37
+ /**
38
+ * Adds a specified number of days to a given date.
39
+ * @param date The date to add days to
40
+ * @param days The number of days to add
41
+ * @returns The new date
42
+ */
43
+ function addDays(date, days) {
44
+ const result = new Date(date);
45
+ result.setDate(result.getDate() + days);
46
+ return result;
47
+ }
48
+
49
+ exports.addDays = addDays;
50
+ exports.calculateWeeklyDayOffset = calculateWeeklyDayOffset;
51
+ exports.getDayOfWeek = getDayOfWeek;
52
+ exports.sortDaysOfWeek = sortDaysOfWeek;
53
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sources":["../../../../src/filter/recurrence/utils.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { DayOfWeek, DAYS_PER_WEEK } from \"./model.js\";\n\n/**\n * Calculates the offset in days between two given days of the week.\n * @param day1 A day of week\n * @param day2 A day of week\n * @returns The number of days to be added to day2 to reach day1\n */\nexport function calculateWeeklyDayOffset(day1: DayOfWeek, day2: DayOfWeek): number {\n return (day1 - day2 + DAYS_PER_WEEK) % DAYS_PER_WEEK;\n}\n\n/**\n * Sorts a collection of days of week based on their offsets from a specified first day of week.\n * @param daysOfWeek A collection of days of week\n * @param firstDayOfWeek The first day of week which will be the first element in the sorted result\n * @returns The sorted days of week\n */\nexport function sortDaysOfWeek(daysOfWeek: DayOfWeek[], firstDayOfWeek: DayOfWeek): DayOfWeek[] {\n const sortedDaysOfWeek = daysOfWeek.slice();\n sortedDaysOfWeek.sort((x, y) => calculateWeeklyDayOffset(x, firstDayOfWeek) - calculateWeeklyDayOffset(y, firstDayOfWeek));\n return sortedDaysOfWeek;\n}\n\n/**\n * Gets the day of week of a given date based on the timezone offset.\n * @param date A UTC date\n * @param timezoneOffsetInMs The timezone offset in milliseconds\n * @returns The day of week (0 for Sunday, 1 for Monday, ..., 6 for Saturday)\n */\nexport function getDayOfWeek(date: Date, timezoneOffsetInMs: number): number {\n const alignedDate = new Date(date.getTime() + timezoneOffsetInMs);\n return alignedDate.getUTCDay();\n}\n\n/**\n * Adds a specified number of days to a given date.\n * @param date The date to add days to\n * @param days The number of days to add\n * @returns The new date\n */\nexport function addDays(date: Date, days: number): Date {\n const result = new Date(date);\n result.setDate(result.getDate() + days);\n return result;\n}\n"],"names":["DAYS_PER_WEEK"],"mappings":";;;;AAAA;AACA;AAIA;;;;;AAKG;AACG,SAAU,wBAAwB,CAAC,IAAe,EAAE,IAAe,EAAA;IACrE,OAAO,CAAC,IAAI,GAAG,IAAI,GAAGA,mBAAa,IAAIA,mBAAa;AACxD;AAEA;;;;;AAKG;AACG,SAAU,cAAc,CAAC,UAAuB,EAAE,cAAyB,EAAA;AAC7E,IAAA,MAAM,gBAAgB,GAAG,UAAU,CAAC,KAAK,EAAE;IAC3C,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,wBAAwB,CAAC,CAAC,EAAE,cAAc,CAAC,GAAG,wBAAwB,CAAC,CAAC,EAAE,cAAc,CAAC,CAAC;AAC1H,IAAA,OAAO,gBAAgB;AAC3B;AAEA;;;;;AAKG;AACG,SAAU,YAAY,CAAC,IAAU,EAAE,kBAA0B,EAAA;AAC/D,IAAA,MAAM,WAAW,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,kBAAkB,CAAC;AACjE,IAAA,OAAO,WAAW,CAAC,SAAS,EAAE;AAClC;AAEA;;;;;AAKG;AACG,SAAU,OAAO,CAAC,IAAU,EAAE,IAAY,EAAA;AAC5C,IAAA,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC;IAC7B,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC;AACvC,IAAA,OAAO,MAAM;AACjB;;;;;;;"}