UNPKG

@atlaskit/editor-common

Version:

A package that contains common classes and components for editor and renderer

63 lines (61 loc) 1.99 kB
import camelCase from 'lodash/camelCase'; import kebabCase from 'lodash/kebabCase'; const EMPTY = {}; function isObjectFlagKey(key, value, objectFlagKeys) { return Boolean(typeof value === 'string' && (objectFlagKeys === null || objectFlagKeys === void 0 ? void 0 : objectFlagKeys.includes(key))); } function isValidJSONObject(value) { try { let result = JSON.parse(value); if (typeof result === 'object' && result !== null) { return true; } return false; } catch (err) { return false; } } /** * Normalise and filter a free Record<string, unknown> to match * the rules for feature flags in editor and renderer * * Input has to match to not be filtered output: * 1. cased in kebab-case (match [a-z-]) * 2. has any value * * Output matches * 1. cased in camelCase (match [a-zA-Z]) * 2. has boolean value or object {} value * * @param rawFeatureFlags */ export function normalizeFeatureFlags(rawFeatureFlags, options) { if (!rawFeatureFlags) { return EMPTY; } return Object.entries(rawFeatureFlags).filter(e => { if (typeof e[1] === 'boolean') { return true; } if (isObjectFlagKey(camelCase(e[0]), e[1], options === null || options === void 0 ? void 0 : options.objectFlagKeys) && isValidJSONObject(e[1])) { return true; } return false; }).filter(([key]) => kebabCase(key) === key).map(([key, value]) => [camelCase(key), value]).reduce((flags, [key, value]) => { if (isObjectFlagKey(key, value, options === null || options === void 0 ? void 0 : options.objectFlagKeys)) { flags[key] = JSON.parse(value); } if (typeof value === 'boolean') { flags[key] = value; } return flags; }, {}); } /** * Transforms FeatureFlags to a type safe string array of the enabled feature flags. * * Useful for analytics and analysis purposes. */ export function getEnabledFeatureFlagKeys(featureFlags) { return Object.keys(featureFlags).filter(key => featureFlags[key] === true); }