@microsoft/feature-management 2.1.0-preview.1 → 2.2.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.
- package/dist/commonjs/featureManager.js +5 -5
- package/dist/commonjs/featureManager.js.map +1 -1
- package/dist/commonjs/featureProvider.js.map +1 -1
- package/dist/commonjs/filter/recurrence/evaluator.js +142 -0
- package/dist/commonjs/filter/recurrence/evaluator.js.map +1 -0
- package/dist/commonjs/filter/recurrence/model.js +52 -0
- package/dist/commonjs/filter/recurrence/model.js.map +1 -0
- package/dist/commonjs/filter/recurrence/utils.js +53 -0
- package/dist/commonjs/filter/recurrence/utils.js.map +1 -0
- package/dist/commonjs/filter/recurrence/validator.js +197 -0
- package/dist/commonjs/filter/recurrence/validator.js.map +1 -0
- package/dist/commonjs/filter/{TargetingFilter.js → targetingFilter.js} +1 -1
- package/dist/commonjs/filter/{TargetingFilter.js.map → targetingFilter.js.map} +1 -1
- package/dist/commonjs/filter/timeWindowFilter.js +49 -0
- package/dist/commonjs/filter/timeWindowFilter.js.map +1 -0
- package/dist/commonjs/filter/utils.js +16 -0
- package/dist/commonjs/filter/utils.js.map +1 -0
- package/dist/commonjs/variant/{Variant.js → variant.js} +1 -1
- package/dist/commonjs/variant/{Variant.js.map → variant.js.map} +1 -1
- package/dist/commonjs/version.js +1 -1
- package/dist/commonjs/version.js.map +1 -1
- package/dist/esm/featureManager.js +3 -3
- package/dist/esm/featureManager.js.map +1 -1
- package/dist/esm/featureProvider.js.map +1 -1
- package/dist/esm/filter/recurrence/evaluator.js +140 -0
- package/dist/esm/filter/recurrence/evaluator.js.map +1 -0
- package/dist/esm/filter/recurrence/model.js +49 -0
- package/dist/esm/filter/recurrence/model.js.map +1 -0
- package/dist/esm/filter/recurrence/utils.js +48 -0
- package/dist/esm/filter/recurrence/utils.js.map +1 -0
- package/dist/esm/filter/recurrence/validator.js +184 -0
- package/dist/esm/filter/recurrence/validator.js.map +1 -0
- package/dist/esm/filter/{TargetingFilter.js → targetingFilter.js} +1 -1
- package/dist/esm/filter/{TargetingFilter.js.map → targetingFilter.js.map} +1 -1
- package/dist/esm/filter/timeWindowFilter.js +47 -0
- package/dist/esm/filter/timeWindowFilter.js.map +1 -0
- package/dist/esm/filter/utils.js +11 -0
- package/dist/esm/filter/utils.js.map +1 -0
- package/dist/esm/variant/{Variant.js → variant.js} +1 -1
- package/dist/esm/variant/{Variant.js.map → variant.js.map} +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.map +1 -1
- package/dist/umd/index.js +439 -3
- package/dist/umd/index.js.map +1 -1
- package/package.json +4 -3
- package/types/index.d.ts +42 -42
- package/dist/commonjs/filter/TimeWindowFilter.js +0 -22
- package/dist/commonjs/filter/TimeWindowFilter.js.map +0 -1
- package/dist/esm/filter/TimeWindowFilter.js +0 -20
- package/dist/esm/filter/TimeWindowFilter.js.map +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
5
|
-
var
|
|
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
|
|
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
|
|
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,CAAC,eAAe,EAAE,CAAC;AACxD,QAAA,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,KAAK,OAAO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,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,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,CAAC,eAAe,EAAE,CAAC;AACxD,QAAA,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,KAAK,OAA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I,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 +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 {
|
|
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,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,K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 +1,142 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var model = require('./model.js');
|
|
4
|
+
var utils = 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;AACa,SAAA,eAAe,CAAC,IAAU,EAAE,cAA8B,EAAA;IACtE,MAAM,eAAe,GAAG,sBAAsB,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;IACrE,IAAI,eAAe,EAAE;AACjB,QAAA,OAAO,IAAI,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC,kBAAkB,CAAC,OAAO,EAAE,GAAG,cAAc,CAAC,QAAQ,CAAC;KAClG;AACD,IAAA,OAAO,KAAK,CAAC;AACjB,CAAC;AAED;;;;;AAKG;AACH,SAAS,sBAAsB,CAAC,IAAU,EAAE,cAA8B,EAAA;AACtE,IAAA,IAAI,IAAI,GAAG,cAAc,CAAC,SAAS,EAAE;AACjC,QAAA,OAAO,SAAS,CAAC;KACpB;AACD,IAAA,IAAI,MAAuB,CAAC;AAC5B,IAAA,MAAM,OAAO,GAAG,cAAc,CAAC,OAAO,CAAC;IACvC,IAAI,OAAO,CAAC,IAAI,KAAKA,2BAAqB,CAAC,KAAK,EAAE;AAC9C,QA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AAGI,mBAAa,CAAC,CAAC;;QAElH,kBAAkB,GAAGJ,aAAO,CAAC,+BAA+B,EAAEG,8BAAwB,CAAC,gBAAgB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAE,EAAE,OAAO,CAAC,cAAe,CAAC,CAAC,CAAC;KAC9I;IACD,OAAO;AACH,QAAA,kBAAkB,EAAE,kBAAkB;AACtC,QAAA,mBAAmB,EAAE,mBAAmB;KAC3C,CAAC;AACN;;;;"}
|
|
@@ -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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CAAA,UAAY,mBAAmB,EAAA;AAC3B;;AAEG;AACH,IAAA,mBAAA,CAAA,mBAAA,CAAA,OAAA,CAAA,GAAA,CAAA,CAAA,GAAA,OAAK,CAAA;AACL;;AAEG;AACH,IAAA,mBAAA,CAAA,mBAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAO,CAAA;AACP;;AAEG;AACH,IAAA,mBAAA,CAAA,mBAAA,CAAA,UAAA,CAAA,GAAA,CAAA,CAAA,GAAA,UAAQ,CAAA;AACZ,CAAC,EAbWA,2BAAmB,KAAnBA,2BAAmB,GAa9B,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;AACa,SAAA,wBAAwB,CAAC,IAAe,EAAE,IAAe,EAAA;IACrE,OAAO,CAAC,IAAI,GAAG,IAAI,GAAGA,mBAAa,IAAIA,mBAAa,CAAC;AACzD,CAAC;AAED;;;;;AAKG;AACa,SAAA,cAAc,CAAC,UAAuB,EAAE,cAAyB,EAAA;AAC7E,IAAA,MAAM,gBAAgB,GAAG,UAAU,CAAC,KAAK,EAAE,CAAC;IAC5C,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,wBAAwB,CAAC,CAAC,EAAE,cAAc,CAAC,GAAG,wBAAwB,CAAC,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC;AAC3H,IAAA,OAAO,gBAAgB,CAAC;AAC5B,CAAC;AAED;;;;;AAKG;AACa,SAAA,YAAY,CAAC,IAAU,EAAE,kBAA0B,EAAA;AAC/D,IAAA,MAAM,WAAW,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,kBAAkB,CAAC,CAAC;AAClE,IAAA,OAAO,WAAW,CAAC,SAAS,EAAE,CAAC;AACnC,CAAC;AAED;;;;;AAKG;AACa,SAAA,OAAO,CAAC,IAAU,EAAE,IAAY,EAAA;AAC5C,IAAA,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;AACxC,IAAA,OAAO,MAAM,CAAC;AAClB;;;;;;;"}
|