@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":"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":[],"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,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A,OAAe,CAAA;AAEf;;AAEG;AACH,IAAA,uBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB,CAAA;AAC7B,CAAC,EA9BW,uBAAuB,KAAvB,uBAAuB,GA8BlC,EAAA,CAAA,CAAA,CAAA;AAED;;;;;;;AAOG;AACH,SAAS,yBAAyB,CAAC,WAAgB,EAAA;AAC/C,IAAA,IAAI,WAAW,CAAC,OAAO,KAAK,SAAS,IAAI,OAAO,WAAW,CAAC,OAAO,KAAK,SAAS,EAAE;QAC/E,MAAM,IAAI,KAAK,CAAC,CAAA,aAAA,EAAgB,WAAW,CAAC,EAAE,CAAkC,gCAAA,CAAA,CAAC,CAAC;KACrF;;;AAGL,CAAC;AAED;;;;;;;AAOG;AACH,SAAS,oBAAoB,CAAC,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,EAAE,uBAAuB,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":[],"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,IAAI,gBAAgB,EAAE,EAAE,IAAI,eAA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,CAAC,IAAI,IAAI,WAAW,CAAC;AACtE,IAAA,IAAI,OAAO,KAAK,SAAS,EAAE;AACvB,QAAA,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE;IAC9B;SAAO;QACH,OAAO,CAAC,IAAI,CAAC,CAAA,QAAA,EAAW,WAAW,CAAA,uBAAA,EAA0B,WAAW,CAAC,EAAE,CAAA,CAAA,CAAG,CAAC;QAC/E,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,uBAAuB,CAAC,IAAI,EAAE;IACvE;AACJ;;;;"}
@@ -1 +1 @@
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 { 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":[],"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,CAAiC,sBAAsB,CAAC,CAAC;QACtG,MAAM,WAAW,GAAG,aAAa,GAAG,iBAAiB,CAAC,EAAE,QAAQ,CAAC,CAAC,OAAO,KAAK,OAAO,CAAC,EAAE,KAAK,WAAW,CAAC,CAAC;QAC1G,mBAAmB,CAAC,WAAW,CAAC,CAAC;AACjC,QAAA,OAAO,WAAW,CAAC;KACtB;AAED,IAAA,MAAM,eAAe,GAAA;QACjB,MAAM,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAiC,sBAAsB,CAAC,CAAC;QACtG,MAAM,YAAY,GAAG,aAAa,GAAG,iBAAiB,CAAC,IAAI,EAAE,CAAC;AAC9D,QAAA,YAAY,CAAC,OAAO,CAAC,WAAW,IAAG;YAC/B,mBAAmB,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,CAAC,sBAAsB,CAAC,GAAG,iBAAiB,CAAC,CAAC;AACtF,QAAA,MAAM,WAAW,GAAG,YAAY,EAAE,QAAQ,CAAC,CAAC,OAAoB,KAAK,OAAO,CAAC,EAAE,KAAK,WAAW,CAAC,CAAC;QACjG,mBAAmB,CAAC,WAAW,CAAC,CAAC;AACjC,QAAA,OAAO,WAAW,CAAC;KACtB;AAED,IAAA,MAAM,eAAe,GAAA;AACjB,QAAA,MAAM,YAAY,GAAG,IAAI,CAAC,cAAc,CAAC,sBAAsB,CAAC,GAAG,iBAAiB,CAAC,IAAI,EAAE,CAAC;AAC5F,QAAA,YAAY,CAAC,OAAO,CAAC,WAAW,IAAG;YAC/B,mBAAmB,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":[],"mappings":";;;AAAA;AACA;AAOA;;AAEG;MACU,mCAAmC,CAAA;AAC5C,IAAA,cAAc;AAEd,I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iB,CAAC,IAAI,EAAE;AAC3F,QAAA,YAAY,CAAC,OAAO,CAAC,WAAW,IAAG;YAC/B,mBAAmB,CAAC,WAAW,CAAC;AACpC,QAAA,CAAC,CAAC;AACF,QAAA,OAAO,YAAY;IACvB;AACH;;;;"}
@@ -0,0 +1,140 @@
1
+ import { RecurrencePatternType, RecurrenceRangeType, ONE_DAY_IN_MILLISECONDS, DAYS_PER_WEEK } from './model.js';
2
+ import { addDays, getDayOfWeek, sortDaysOfWeek, calculateWeeklyDayOffset } from './utils.js';
3
+
4
+ // Copyright (c) Microsoft Corporation.
5
+ // Licensed under the MIT license.
6
+ /**
7
+ * Checks if a provided datetime is within any recurring time window specified by the recurrence information
8
+ * @param time A datetime
9
+ * @param recurrenceSpec The recurrence spcification
10
+ * @returns True if the given time is within any recurring time window; otherwise, false
11
+ */
12
+ function matchRecurrence(time, recurrenceSpec) {
13
+ const recurrenceState = findPreviousRecurrence(time, recurrenceSpec);
14
+ if (recurrenceState) {
15
+ return time.getTime() < recurrenceState.previousOccurrence.getTime() + recurrenceSpec.duration;
16
+ }
17
+ return false;
18
+ }
19
+ /**
20
+ * Finds the closest previous recurrence occurrence before the given time according to the recurrence information
21
+ * @param time A datetime
22
+ * @param recurrenceSpec The recurrence specification
23
+ * @returns The recurrence state if any previous occurrence is found; otherwise, undefined
24
+ */
25
+ function findPreviousRecurrence(time, recurrenceSpec) {
26
+ if (time < recurrenceSpec.startTime) {
27
+ return undefined;
28
+ }
29
+ let result;
30
+ const pattern = recurrenceSpec.pattern;
31
+ if (pattern.type === RecurrencePatternType.Daily) {
32
+ result = findPreviousDailyRecurrence(time, recurrenceSpec);
33
+ }
34
+ else if (pattern.type === RecurrencePatternType.Weekly) {
35
+ result = findPreviousWeeklyRecurrence(time, recurrenceSpec);
36
+ }
37
+ else {
38
+ throw new Error("Unsupported recurrence pattern type.");
39
+ }
40
+ const { previousOccurrence, numberOfOccurrences } = result;
41
+ const range = recurrenceSpec.range;
42
+ if (range.type === RecurrenceRangeType.EndDate) {
43
+ if (previousOccurrence > range.endDate) {
44
+ return undefined;
45
+ }
46
+ }
47
+ else if (range.type === RecurrenceRangeType.Numbered) {
48
+ if (numberOfOccurrences > range.numberOfOccurrences) {
49
+ return undefined;
50
+ }
51
+ }
52
+ return result;
53
+ }
54
+ function findPreviousDailyRecurrence(time, recurrenceSpec) {
55
+ const startTime = recurrenceSpec.startTime;
56
+ const timeGap = time.getTime() - startTime.getTime();
57
+ const pattern = recurrenceSpec.pattern;
58
+ const numberOfIntervals = Math.floor(timeGap / (pattern.interval * ONE_DAY_IN_MILLISECONDS));
59
+ return {
60
+ previousOccurrence: addDays(startTime, numberOfIntervals * pattern.interval),
61
+ numberOfOccurrences: numberOfIntervals + 1
62
+ };
63
+ }
64
+ function findPreviousWeeklyRecurrence(time, recurrenceSpec) {
65
+ /*
66
+ * Algorithm:
67
+ * 1. first find day 0 (d0), it's the day representing the start day on the week of `Start`.
68
+ * 2. find start day of the most recent occurring week d0 + floor((time - d0) / (interval * 7)) * (interval * 7)
69
+ * 3. if that's over 7 days ago, then previous occurence is the day with the max offset of the last occurring week
70
+ * 4. if gotten this far, then the current week is the most recent occurring week:
71
+ i. if time > day with min offset, then previous occurence is the day with max offset less than current
72
+ ii. if time < day with min offset, then previous occurence is the day with the max offset of previous occurring week
73
+ */
74
+ const startTime = recurrenceSpec.startTime;
75
+ const startDay = getDayOfWeek(startTime, recurrenceSpec.timezoneOffset);
76
+ const pattern = recurrenceSpec.pattern;
77
+ const sortedDaysOfWeek = sortDaysOfWeek(pattern.daysOfWeek, pattern.firstDayOfWeek);
78
+ /*
79
+ * Example:
80
+ * startTime = 2024-12-11 (Tue)
81
+ * pattern.interval = 2 pattern.firstDayOfWeek = Sun pattern.daysOfWeek = [Wed, Sun]
82
+ * sortedDaysOfWeek = [Sun, Wed]
83
+ * firstDayofStartWeek = 2024-12-08 (Sun)
84
+ *
85
+ * time = 2024-12-23 (Mon) timeGap = 15 days
86
+ * the most recent occurring week: 2024-12-22 ~ 2024-12-28
87
+ * number of intervals before the most recent occurring week = 15 / (2 * 7) = 1 (2024-12-08 ~ 2023-12-21)
88
+ * number of occurrences before the most recent occurring week = 1 * 2 - 1 = 1 (2024-12-11)
89
+ * firstDayOfLastOccurringWeek = 2024-12-22
90
+ */
91
+ const firstDayofStartWeek = addDays(startTime, -calculateWeeklyDayOffset(startDay, pattern.firstDayOfWeek));
92
+ const timeGap = time.getTime() - firstDayofStartWeek.getTime();
93
+ // number of intervals before the most recent occurring week
94
+ const numberOfIntervals = Math.floor(timeGap / (pattern.interval * DAYS_PER_WEEK * ONE_DAY_IN_MILLISECONDS));
95
+ // number of occurrences before the most recent occurring week, it is possible to be negative
96
+ let numberOfOccurrences = numberOfIntervals * sortedDaysOfWeek.length - sortedDaysOfWeek.indexOf(startDay);
97
+ const firstDayOfLatestOccurringWeek = addDays(firstDayofStartWeek, numberOfIntervals * pattern.interval * DAYS_PER_WEEK);
98
+ // the current time is out of the last occurring week
99
+ if (time > addDays(firstDayOfLatestOccurringWeek, DAYS_PER_WEEK)) {
100
+ numberOfOccurrences += sortDaysOfWeek.length;
101
+ // day with max offset in the last occurring week
102
+ const previousOccurrence = addDays(firstDayOfLatestOccurringWeek, calculateWeeklyDayOffset(sortedDaysOfWeek.at(-1), pattern.firstDayOfWeek));
103
+ return {
104
+ previousOccurrence: previousOccurrence,
105
+ numberOfOccurrences: numberOfOccurrences
106
+ };
107
+ }
108
+ let dayWithMinOffset = addDays(firstDayOfLatestOccurringWeek, calculateWeeklyDayOffset(sortedDaysOfWeek[0], pattern.firstDayOfWeek));
109
+ if (dayWithMinOffset < startTime) {
110
+ numberOfOccurrences = 0;
111
+ dayWithMinOffset = startTime;
112
+ }
113
+ let previousOccurrence;
114
+ if (time >= dayWithMinOffset) {
115
+ // the previous occurence is the day with max offset less than current
116
+ previousOccurrence = dayWithMinOffset;
117
+ numberOfOccurrences += 1;
118
+ const dayWithMinOffsetIndex = sortedDaysOfWeek.indexOf(getDayOfWeek(dayWithMinOffset, recurrenceSpec.timezoneOffset));
119
+ for (let i = dayWithMinOffsetIndex + 1; i < sortedDaysOfWeek.length; i++) {
120
+ const day = addDays(firstDayOfLatestOccurringWeek, calculateWeeklyDayOffset(sortedDaysOfWeek[i], pattern.firstDayOfWeek));
121
+ if (time < day) {
122
+ break;
123
+ }
124
+ previousOccurrence = day;
125
+ numberOfOccurrences += 1;
126
+ }
127
+ }
128
+ else {
129
+ const firstDayOfPreviousOccurringWeek = addDays(firstDayOfLatestOccurringWeek, -pattern.interval * DAYS_PER_WEEK);
130
+ // the previous occurence is the day with the max offset of previous occurring week
131
+ previousOccurrence = addDays(firstDayOfPreviousOccurringWeek, calculateWeeklyDayOffset(sortedDaysOfWeek.at(-1), pattern.firstDayOfWeek));
132
+ }
133
+ return {
134
+ previousOccurrence: previousOccurrence,
135
+ numberOfOccurrences: numberOfOccurrences
136
+ };
137
+ }
138
+
139
+ export { matchRecurrence };
140
+ //# 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":[],"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,cAA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B,CAAC,EAAE,CAAC,EAAE,CAAE,EAAE,OAAO,CAAC,cAAe,CAAC,CAAC;IAC9I;IACA,OAAO;AACH,QAAA,kBAAkB,EAAE,kBAAkB;AACtC,QAAA,mBAAmB,EAAE;KACxB;AACL;;;;"}
@@ -0,0 +1,49 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ const DAYS_PER_WEEK = 7;
4
+ const ONE_DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000;
5
+ var DayOfWeek;
6
+ (function (DayOfWeek) {
7
+ DayOfWeek[DayOfWeek["Sunday"] = 0] = "Sunday";
8
+ DayOfWeek[DayOfWeek["Monday"] = 1] = "Monday";
9
+ DayOfWeek[DayOfWeek["Tuesday"] = 2] = "Tuesday";
10
+ DayOfWeek[DayOfWeek["Wednesday"] = 3] = "Wednesday";
11
+ DayOfWeek[DayOfWeek["Thursday"] = 4] = "Thursday";
12
+ DayOfWeek[DayOfWeek["Friday"] = 5] = "Friday";
13
+ DayOfWeek[DayOfWeek["Saturday"] = 6] = "Saturday";
14
+ })(DayOfWeek || (DayOfWeek = {}));
15
+ /**
16
+ * The recurrence pattern describes the frequency by which the time window repeats
17
+ */
18
+ var RecurrencePatternType;
19
+ (function (RecurrencePatternType) {
20
+ /**
21
+ * The pattern where the time window will repeat based on the number of days specified by interval between occurrences
22
+ */
23
+ RecurrencePatternType[RecurrencePatternType["Daily"] = 0] = "Daily";
24
+ /**
25
+ * 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
26
+ */
27
+ RecurrencePatternType[RecurrencePatternType["Weekly"] = 1] = "Weekly";
28
+ })(RecurrencePatternType || (RecurrencePatternType = {}));
29
+ /**
30
+ * The recurrence range specifies the date range over which the time window repeats
31
+ */
32
+ var RecurrenceRangeType;
33
+ (function (RecurrenceRangeType) {
34
+ /**
35
+ * The recurrence has no end and repeats on all the days that fit the corresponding pattern
36
+ */
37
+ RecurrenceRangeType[RecurrenceRangeType["NoEnd"] = 0] = "NoEnd";
38
+ /**
39
+ * The recurrence repeats on all the days that fit the corresponding pattern until or on the specified end date
40
+ */
41
+ RecurrenceRangeType[RecurrenceRangeType["EndDate"] = 1] = "EndDate";
42
+ /**
43
+ * The recurrence repeats for the specified number of occurrences that match the pattern
44
+ */
45
+ RecurrenceRangeType[RecurrenceRangeType["Numbered"] = 2] = "Numbered";
46
+ })(RecurrenceRangeType || (RecurrenceRangeType = {}));
47
+
48
+ export { DAYS_PER_WEEK, DayOfWeek, ONE_DAY_IN_MILLISECONDS, RecurrencePatternType, RecurrenceRangeType };
49
+ //# 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":[],"mappings":"AAAA;AACA;AAEO,MAAM,aAAa,GAAG;AACtB,MAAM,uBAAuB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG;IAE1C;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,EARW,SAAS,KAAT,SAAS,GAAA,EAAA,CAAA,CAAA;AAUrB;;AAEG;IACS;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,EATW,qBAAqB,KAArB,qBAAqB,GAAA,EAAA,CAAA,CAAA;AAWjC;;AAEG;IACS;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,EAbW,mBAAmB,KAAnB,mBAAmB,GAAA,EAAA,CAAA,CAAA;;;;"}
@@ -0,0 +1,48 @@
1
+ import { DAYS_PER_WEEK } from './model.js';
2
+
3
+ // Copyright (c) Microsoft Corporation.
4
+ // Licensed under the MIT license.
5
+ /**
6
+ * Calculates the offset in days between two given days of the week.
7
+ * @param day1 A day of week
8
+ * @param day2 A day of week
9
+ * @returns The number of days to be added to day2 to reach day1
10
+ */
11
+ function calculateWeeklyDayOffset(day1, day2) {
12
+ return (day1 - day2 + DAYS_PER_WEEK) % DAYS_PER_WEEK;
13
+ }
14
+ /**
15
+ * Sorts a collection of days of week based on their offsets from a specified first day of week.
16
+ * @param daysOfWeek A collection of days of week
17
+ * @param firstDayOfWeek The first day of week which will be the first element in the sorted result
18
+ * @returns The sorted days of week
19
+ */
20
+ function sortDaysOfWeek(daysOfWeek, firstDayOfWeek) {
21
+ const sortedDaysOfWeek = daysOfWeek.slice();
22
+ sortedDaysOfWeek.sort((x, y) => calculateWeeklyDayOffset(x, firstDayOfWeek) - calculateWeeklyDayOffset(y, firstDayOfWeek));
23
+ return sortedDaysOfWeek;
24
+ }
25
+ /**
26
+ * Gets the day of week of a given date based on the timezone offset.
27
+ * @param date A UTC date
28
+ * @param timezoneOffsetInMs The timezone offset in milliseconds
29
+ * @returns The day of week (0 for Sunday, 1 for Monday, ..., 6 for Saturday)
30
+ */
31
+ function getDayOfWeek(date, timezoneOffsetInMs) {
32
+ const alignedDate = new Date(date.getTime() + timezoneOffsetInMs);
33
+ return alignedDate.getUTCDay();
34
+ }
35
+ /**
36
+ * Adds a specified number of days to a given date.
37
+ * @param date The date to add days to
38
+ * @param days The number of days to add
39
+ * @returns The new date
40
+ */
41
+ function addDays(date, days) {
42
+ const result = new Date(date);
43
+ result.setDate(result.getDate() + days);
44
+ return result;
45
+ }
46
+
47
+ export { addDays, calculateWeeklyDayOffset, getDayOfWeek, sortDaysOfWeek };
48
+ //# 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":[],"mappings":";;AAAA;AACA;AAIA;;;;;AAKG;AACG,SAAU,wBAAwB,CAAC,IAAe,EAAE,IAAe,EAAA;IACrE,OAAO,CAAC,IAAI,GAAG,IAAI,GAAG,aAAa,IAAI,aAAa;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;;;;"}
@@ -0,0 +1,184 @@
1
+ import { buildInvalidParameterErrorMessage, REQUIRED_PARAMETER_MISSING_ERROR_MESSAGE, VALUE_OUT_OF_RANGE_ERROR_MESSAGE, UNRECOGNIZABLE_VALUE_ERROR_MESSAGE } from '../utils.js';
2
+ import { ONE_DAY_IN_MILLISECONDS, RecurrenceRangeType, RecurrencePatternType, DayOfWeek, DAYS_PER_WEEK } from './model.js';
3
+ import { getDayOfWeek, sortDaysOfWeek, calculateWeeklyDayOffset } from './utils.js';
4
+
5
+ // Copyright (c) Microsoft Corporation.
6
+ // Licensed under the MIT license.
7
+ const START_NOT_MATCHED_ERROR_MESSAGE = "Start date is not a valid first occurrence.";
8
+ const TIME_WINDOW_DURATION_OUT_OF_RANGE_ERROR_MESSAGE = "Time window duration cannot be longer than how frequently it occurs or be longer than 10 years.";
9
+ const PATTERN = "Recurrence.Pattern";
10
+ const PATTERN_TYPE = "Recurrence.Pattern.Type";
11
+ const INTERVAL = "Recurrence.Pattern.Interval";
12
+ const DAYS_OF_WEEK = "Recurrence.Pattern.DaysOfWeek";
13
+ const FIRST_DAY_OF_WEEK = "Recurrence.Pattern.FirstDayOfWeek";
14
+ const RANGE = "Recurrence.Range";
15
+ const RANGE_TYPE = "Recurrence.Range.Type";
16
+ const END_DATE = "Recurrence.Range.EndDate";
17
+ const NUMBER_OF_OCCURRENCES = "Recurrence.Range.NumberOfOccurrences";
18
+ /**
19
+ * Parses @see RecurrenceParameters into a @see RecurrenceSpec object. If the parameter is invalid, an error will be thrown.
20
+ * @param startTime The start time of the base time window
21
+ * @param day2 The end time of the base time window
22
+ * @param recurrenceParameters The @see RecurrenceParameters to parse
23
+ * @param TimeZoneOffset The time zone offset in milliseconds, by default 0
24
+ * @returns A @see RecurrenceSpec object
25
+ */
26
+ function parseRecurrenceParameter(startTime, endTime, recurrenceParameters, TimeZoneOffset = 0) {
27
+ if (startTime === undefined) {
28
+ throw new Error(buildInvalidParameterErrorMessage("Start", REQUIRED_PARAMETER_MISSING_ERROR_MESSAGE));
29
+ }
30
+ if (endTime === undefined) {
31
+ throw new Error(buildInvalidParameterErrorMessage("End", REQUIRED_PARAMETER_MISSING_ERROR_MESSAGE));
32
+ }
33
+ if (startTime >= endTime) {
34
+ throw new Error(buildInvalidParameterErrorMessage("End", VALUE_OUT_OF_RANGE_ERROR_MESSAGE));
35
+ }
36
+ const timeWindowDuration = endTime.getTime() - startTime.getTime();
37
+ if (timeWindowDuration > 10 * 365 * ONE_DAY_IN_MILLISECONDS) { // time window duration cannot be longer than 10 years
38
+ throw new Error(buildInvalidParameterErrorMessage("End", TIME_WINDOW_DURATION_OUT_OF_RANGE_ERROR_MESSAGE));
39
+ }
40
+ return {
41
+ startTime: startTime,
42
+ duration: timeWindowDuration,
43
+ pattern: parseRecurrencePattern(startTime, endTime, recurrenceParameters, TimeZoneOffset),
44
+ range: parseRecurrenceRange(startTime, recurrenceParameters),
45
+ timezoneOffset: TimeZoneOffset
46
+ };
47
+ }
48
+ function parseRecurrencePattern(startTime, endTime, recurrenceParameters, timeZoneOffset) {
49
+ const rawPattern = recurrenceParameters.Pattern;
50
+ if (rawPattern === undefined) {
51
+ throw new Error(buildInvalidParameterErrorMessage(PATTERN, REQUIRED_PARAMETER_MISSING_ERROR_MESSAGE));
52
+ }
53
+ if (rawPattern.Type === undefined) {
54
+ throw new Error(buildInvalidParameterErrorMessage(PATTERN_TYPE, REQUIRED_PARAMETER_MISSING_ERROR_MESSAGE));
55
+ }
56
+ const patternType = RecurrencePatternType[rawPattern.Type];
57
+ if (patternType === undefined) {
58
+ throw new Error(buildInvalidParameterErrorMessage(PATTERN_TYPE, UNRECOGNIZABLE_VALUE_ERROR_MESSAGE));
59
+ }
60
+ let interval = rawPattern.Interval;
61
+ if (interval !== undefined) {
62
+ if (typeof interval !== "number") {
63
+ throw new Error(buildInvalidParameterErrorMessage(INTERVAL, UNRECOGNIZABLE_VALUE_ERROR_MESSAGE));
64
+ }
65
+ else if (interval <= 0 || !Number.isInteger(interval)) {
66
+ throw new Error(buildInvalidParameterErrorMessage(INTERVAL, VALUE_OUT_OF_RANGE_ERROR_MESSAGE));
67
+ }
68
+ }
69
+ else {
70
+ interval = 1;
71
+ }
72
+ const parsedPattern = {
73
+ type: patternType,
74
+ interval: interval
75
+ };
76
+ const timeWindowDuration = endTime.getTime() - startTime.getTime();
77
+ if (patternType === RecurrencePatternType.Daily) {
78
+ if (timeWindowDuration > interval * ONE_DAY_IN_MILLISECONDS) {
79
+ throw new Error(buildInvalidParameterErrorMessage("End", TIME_WINDOW_DURATION_OUT_OF_RANGE_ERROR_MESSAGE));
80
+ }
81
+ }
82
+ else if (patternType === RecurrencePatternType.Weekly) {
83
+ let firstDayOfWeek;
84
+ if (rawPattern.FirstDayOfWeek !== undefined) {
85
+ firstDayOfWeek = DayOfWeek[rawPattern.FirstDayOfWeek];
86
+ if (firstDayOfWeek === undefined) {
87
+ throw new Error(buildInvalidParameterErrorMessage(FIRST_DAY_OF_WEEK, UNRECOGNIZABLE_VALUE_ERROR_MESSAGE));
88
+ }
89
+ }
90
+ else {
91
+ firstDayOfWeek = DayOfWeek.Sunday;
92
+ }
93
+ parsedPattern.firstDayOfWeek = firstDayOfWeek;
94
+ if (rawPattern.DaysOfWeek === undefined || rawPattern.DaysOfWeek.length === 0) {
95
+ throw new Error(buildInvalidParameterErrorMessage(DAYS_OF_WEEK, REQUIRED_PARAMETER_MISSING_ERROR_MESSAGE));
96
+ }
97
+ if (!Array.isArray(rawPattern.DaysOfWeek)) {
98
+ throw new Error(buildInvalidParameterErrorMessage(DAYS_OF_WEEK, UNRECOGNIZABLE_VALUE_ERROR_MESSAGE));
99
+ }
100
+ const daysOfWeek = [...new Set(rawPattern.DaysOfWeek.map(day => DayOfWeek[day]))]; // dedup array
101
+ if (daysOfWeek.some(day => day === undefined)) {
102
+ throw new Error(buildInvalidParameterErrorMessage(DAYS_OF_WEEK, UNRECOGNIZABLE_VALUE_ERROR_MESSAGE));
103
+ }
104
+ if (timeWindowDuration > interval * DAYS_PER_WEEK * ONE_DAY_IN_MILLISECONDS ||
105
+ !isDurationCompliantWithDaysOfWeek(timeWindowDuration, interval, daysOfWeek, firstDayOfWeek)) {
106
+ throw new Error(buildInvalidParameterErrorMessage("End", TIME_WINDOW_DURATION_OUT_OF_RANGE_ERROR_MESSAGE));
107
+ }
108
+ parsedPattern.daysOfWeek = daysOfWeek;
109
+ // check whether "Start" is a valid first occurrence
110
+ const alignedStartDay = getDayOfWeek(startTime, timeZoneOffset);
111
+ if (!daysOfWeek.find(day => day === alignedStartDay)) {
112
+ throw new Error(buildInvalidParameterErrorMessage("Start", START_NOT_MATCHED_ERROR_MESSAGE));
113
+ }
114
+ }
115
+ return parsedPattern;
116
+ }
117
+ function parseRecurrenceRange(startTime, recurrenceParameters) {
118
+ const rawRange = recurrenceParameters.Range;
119
+ if (rawRange === undefined) {
120
+ throw new Error(buildInvalidParameterErrorMessage(RANGE, REQUIRED_PARAMETER_MISSING_ERROR_MESSAGE));
121
+ }
122
+ if (rawRange.Type === undefined) {
123
+ throw new Error(buildInvalidParameterErrorMessage(RANGE_TYPE, REQUIRED_PARAMETER_MISSING_ERROR_MESSAGE));
124
+ }
125
+ const rangeType = RecurrenceRangeType[rawRange.Type];
126
+ if (rangeType === undefined) {
127
+ throw new Error(buildInvalidParameterErrorMessage(RANGE_TYPE, UNRECOGNIZABLE_VALUE_ERROR_MESSAGE));
128
+ }
129
+ const parsedRange = { type: rangeType };
130
+ if (rangeType === RecurrenceRangeType.EndDate) {
131
+ let endDate;
132
+ if (rawRange.EndDate !== undefined) {
133
+ endDate = new Date(rawRange.EndDate);
134
+ if (isNaN(endDate.getTime())) {
135
+ throw new Error(buildInvalidParameterErrorMessage(END_DATE, UNRECOGNIZABLE_VALUE_ERROR_MESSAGE));
136
+ }
137
+ if (endDate < startTime) {
138
+ throw new Error(buildInvalidParameterErrorMessage(END_DATE, VALUE_OUT_OF_RANGE_ERROR_MESSAGE));
139
+ }
140
+ }
141
+ else {
142
+ endDate = new Date(8.64e15); // the maximum date in ECMAScript: https://262.ecma-international.org/5.1/#sec-15.9.1.1
143
+ }
144
+ parsedRange.endDate = endDate;
145
+ }
146
+ else if (rangeType === RecurrenceRangeType.Numbered) {
147
+ let numberOfOccurrences = rawRange.NumberOfOccurrences;
148
+ if (numberOfOccurrences !== undefined) {
149
+ if (typeof numberOfOccurrences !== "number") {
150
+ throw new Error(buildInvalidParameterErrorMessage(NUMBER_OF_OCCURRENCES, UNRECOGNIZABLE_VALUE_ERROR_MESSAGE));
151
+ }
152
+ else if (numberOfOccurrences <= 0 || !Number.isInteger(numberOfOccurrences)) {
153
+ throw new Error(buildInvalidParameterErrorMessage(NUMBER_OF_OCCURRENCES, VALUE_OUT_OF_RANGE_ERROR_MESSAGE));
154
+ }
155
+ }
156
+ else {
157
+ numberOfOccurrences = Number.MAX_SAFE_INTEGER;
158
+ }
159
+ parsedRange.numberOfOccurrences = numberOfOccurrences;
160
+ }
161
+ return parsedRange;
162
+ }
163
+ function isDurationCompliantWithDaysOfWeek(duration, interval, daysOfWeek, firstDayOfWeek) {
164
+ if (daysOfWeek.length === 1) {
165
+ return true;
166
+ }
167
+ const sortedDaysOfWeek = sortDaysOfWeek(daysOfWeek, firstDayOfWeek);
168
+ let prev = sortedDaysOfWeek[0]; // the closest occurrence day to the first day of week
169
+ let minGap = DAYS_PER_WEEK * ONE_DAY_IN_MILLISECONDS;
170
+ for (let i = 1; i < sortedDaysOfWeek.length; i++) { // skip the first day
171
+ const gap = calculateWeeklyDayOffset(sortedDaysOfWeek[i], prev) * ONE_DAY_IN_MILLISECONDS;
172
+ minGap = gap < minGap ? gap : minGap;
173
+ prev = sortedDaysOfWeek[i];
174
+ }
175
+ // It may across weeks. Check the next week if the interval is one week.
176
+ if (interval == 1) {
177
+ const gap = calculateWeeklyDayOffset(sortedDaysOfWeek[0], prev) * ONE_DAY_IN_MILLISECONDS;
178
+ minGap = gap < minGap ? gap : minGap;
179
+ }
180
+ return minGap >= duration;
181
+ }
182
+
183
+ export { DAYS_OF_WEEK, END_DATE, FIRST_DAY_OF_WEEK, INTERVAL, NUMBER_OF_OCCURRENCES, PATTERN, PATTERN_TYPE, RANGE, RANGE_TYPE, START_NOT_MATCHED_ERROR_MESSAGE, TIME_WINDOW_DURATION_OUT_OF_RANGE_ERROR_MESSAGE, parseRecurrenceParameter };
184
+ //# sourceMappingURL=validator.js.map