1 import { addDays, endOfDay } from 'date-fns';
3 import { deleteCookie, setCookie } from '@proton/shared/lib/helpers/cookies';
5 import type { FeatureFlagToggle } from '../interface';
7 export const UNLEASH_FLAG_COOKIE_NAME = 'Features';
10 * Invalid characters list
11 * ",": Cookies don't support commas
12 * " ": Cookies don't support spaces
13 * ":": We already use colon to differentiate our flag name and variant
15 const UNLEASH_FLAG_INVALID_CHARS = [',', ':', ' '];
17 const isValidString = (value: string) => UNLEASH_FLAG_INVALID_CHARS.every((char) => !value.includes(char));
20 * @description Stores whitelisted feature flags in a cookie for the data team.
21 * Data is stored in a comma-separated list with the following format: `flagName:variantName`
23 * @param data - List of flags fetched by the Unleash client
24 * @param whitelistedFlags - List of whitelisted flags defined in the app
26 const saveWhitelistedFlagInCookies = (data: FeatureFlagToggle[], whitelistedFlags: string[]) => {
27 const enabledFlags = [];
29 for (const flagName of whitelistedFlags) {
30 // There are cases where data is not an array, better prevent it
31 if (!Array.isArray(data)) {
35 // Map whitelisted flags to valid cookie entries
36 const flagData = data.find((flag) => flag.name === flagName);
38 // If variant is enabled, save flag name + variant
41 flagData?.variant?.enabled &&
42 isValidString(flagData.name) &&
43 isValidString(flagData.variant.name)
45 enabledFlags.push(`${flagData.name}:${flagData.variant.name}`);
49 if (enabledFlags.length > 0) {
51 domain: window.location.hostname,
52 cookieName: UNLEASH_FLAG_COOKIE_NAME,
53 cookieValue: enabledFlags.join(','),
56 expirationDate: endOfDay(addDays(new Date(), 30)).toUTCString(),
60 deleteCookie(UNLEASH_FLAG_COOKIE_NAME);
64 export default saveWhitelistedFlagInCookies;