Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286import {MMKV} from 'react-native-mmkv'import {setPolyfills} from '@growthbook/growthbook'import {type I18n} from '@lingui/core'import {msg} from '@lingui/core/macro'
import {Logger} from '#/logger'import {readFeatureBootstrap} from '#/analytics/features/bootstrap'import {createGrowthBook, refreshGrowthBook} from '#/analytics/features/client'import {Features} from '#/analytics/features/types'import {getNavigationMetadata, type Metadata} from '#/analytics/metadata'import * as env from '#/env'
export {Features} from '#/analytics/features/types'
const logger = Logger.create(Logger.Context.Growthbook)
const CACHE = new MMKV({id: 'bsky_features_cache'})
const BETA_USER_ATTRIBUTE = 'isBetaUser'
setPolyfills({ localStorage: { getItem: key => { const value = CACHE.getString(key) return value != null ? JSON.parse(value) : null }, setItem: (key, value) => { CACHE.set(key, value) }, },})
/** * We vary the amount of time we wait for GrowthBook to fetch feature * gates based on the strategy specified. */export type FeatureFetchStrategy = 'prefer-low-latency' | 'prefer-fresh-gates'
const TIMEOUT_INIT = 500 // TODO should base on p99 or somethingconst TIMEOUT_PREFER_LOW_LATENCY = 250const TIMEOUT_PREFER_FRESH_GATES = 1500
const sdkOptions = { apiHost: env.GROWTHBOOK_API_HOST, clientKey: env.GROWTHBOOK_CLIENT_KEY, enableDevMode: env.IS_INTERNAL,}const bootstrap = readFeatureBootstrap(sdkOptions)
/** * Shared SDK instance. Assumes a single active account context, with attributes * supplied by AnalyticsFeaturesContext before its children evaluate features. */export const features = createGrowthBook(sdkOptions, bootstrap)
// Dev builds only: EXPO_PUBLIC_FORCE_FEATURES=a,b turns those flags on locally.const FORCE_FEATURES: string = process.env.EXPO_PUBLIC_FORCE_FEATURES || ''if (__DEV__ && FORCE_FEATURES) { features.setForcedFeatures( new Map( FORCE_FEATURES.split(',') .map(key => key.trim()) .filter(Boolean) .map(key => [key, true]), ), )}
/** * Initializer promise that must be awaited before using the GrowthBook * instance or rendering the `AnalyticsFeaturesContext`. A valid HTML bootstrap * is available synchronously while this revalidates it. Without one, a slow * initialization may cause a flash of uncustomized content. */export const init = ( bootstrap ? refreshGrowthBook(features, {timeout: TIMEOUT_INIT}) : features.init({timeout: TIMEOUT_INIT, streaming: true}).then(res => { if (!res.success) { logger.warn('GrowthBook initialization failed or timed out', { source: res.source, safeMessage: res.error?.toString(), }) } })).catch(() => { // Swallow errors from GrowthBook init (e.g. CORS failures, cache // corruption). The app should still load without feature gates.})
/** * Refresh feature gates from GrowthBook. */export async function refresh({strategy}: {strategy: FeatureFetchStrategy}) { const options = { timeout: strategy === 'prefer-low-latency' ? TIMEOUT_PREFER_LOW_LATENCY : TIMEOUT_PREFER_FRESH_GATES, } await (bootstrap ? refreshGrowthBook(features, options) : features.refreshFeatures(options))}
export function getFeatures() { return features.getFeatures()}
export function getFeatureDescription(feature: Features, i18n: I18n) { switch (feature) { case Features.PostFeedKnownLikersEnable: return { key: feature, name: i18n._( msg({ message: 'Social proofing on posts', comment: 'Name for a feature flag', }), ), description: i18n._( msg({ message: 'Spot posts your friends and follows have liked.', comment: 'Description of a feature flag (Social proofing on posts)', }), ), } case Features.FollowingV2Enable: // Following v2 behaviour is native-only, see `isFollowingV2Eligible` if (env.IS_WEB) return null return { key: feature, name: i18n._( msg({ message: 'Keep your place in the Following feed', comment: 'Name for a feature flag', }), ), description: i18n._( msg({ message: 'Save your position in the Following feed between sessions. New posts wait above you until you’re ready to view them.', comment: 'Description of a feature flag (Keep your place in the Following feed)', }), ), } case Features.NotificationsV2Enable: return { key: feature, name: i18n._( msg({ message: 'Redesigned notifications', comment: 'Name for a feature flag', }), ), description: i18n._( msg({ message: 'Notifications sorted into tabs – people you follow, followers, replies and activity.', comment: 'Description of a feature flag (Redesigned notifications)', }), ), } case Features.ModerationInboxEnable: return { key: feature, name: i18n._( msg({ message: 'Moderation inbox', comment: 'Name for a feature flag', }), ), description: i18n._( msg({ message: 'Track your reports, review moderation decisions, and submit appeals.', comment: 'Description of a feature flag (Moderation inbox)', }), ), } default: return null }}
/** * Walks a GrowthBook condition tree to determine whether it targets the given * attribute. Conditions can nest via the logical operators `$and`, `$or`, * `$nor` (arrays of sub-conditions) and `$not` (a single sub-condition), so a * flat scan of the top-level keys would miss e.g. * `{$and: [{isBetaUser: true}, ...]}`. Dot-notation access (e.g. * `isBetaUser.foo`) counts as targeting the attribute as well. */function conditionTargetsAttribute( condition: unknown, attribute: string,): boolean { if (!condition || typeof condition !== 'object') return false
for (const [key, value] of Object.entries(condition)) { if (key === attribute || key.startsWith(`${attribute}.`)) return true
if (key === '$and' || key === '$or' || key === '$nor') { if ( Array.isArray(value) && value.some(sub => conditionTargetsAttribute(sub, attribute)) ) { return true } } else if (key === '$not') { if (conditionTargetsAttribute(value, attribute)) return true } }
return false}
export function getTargetedFeatures(i18n: I18n) { const allFeatures = features.getFeatures() const targetedFeatures: {key: Features; name: string; description: string}[] = [] for (const [featureKey, feature] of Object.entries(allFeatures)) { // Check if the feature contains any rules if (!feature.rules) continue
// Determine if any rule targets the beta user attribute const hasTargeting = feature.rules.some(rule => conditionTargetsAttribute(rule.condition, BETA_USER_ATTRIBUTE), )
if (hasTargeting) { const featureName = getFeatureDescription(featureKey as Features, i18n) if (featureName) { targetedFeatures.push(featureName) } } }
return targetedFeatures}
/** * Whether `feature` is on for the current user because they opted in to beta * features, i.e. the rule GrowthBook matched for them targets the beta user * attribute, as the features listed on the Beta features screen do. */export function isOnForBetaUser(feature: Features): boolean { const result = features.evalFeature(feature) if (!result.on || !result.ruleId) return false const rules = features.getFeatures()[feature]?.rules const rule = rules?.find(({id}) => id === result.ruleId) return conditionTargetsAttribute(rule?.condition, BETA_USER_ATTRIBUTE)}
/** * Converts our metadata into GrowthBook attributes and sets them. GrowthBook * attributes are manually configured in the GrowthBook dashboard. So these * values need to match exactly. Therefore, let's add them here manually to and * not spread them to avoid mistakes. * * Analytics session IDs are event metadata only, not feature targeting or * experiment bucketing inputs. They are intentionally excluded from GrowthBook * attributes, so session rotation does not require feature reevaluation. */export function setAttributes({ base, geolocation, session, preferences,}: Metadata) { void features.setAttributes({ deviceId: base.deviceId, platform: base.platform, appVersion: base.appVersion, countryCode: geolocation.countryCode, regionCode: geolocation.regionCode, did: session?.did, isBlackskyPds: session?.isBlackskyPds, appLanguage: preferences?.appLanguage, contentLanguages: preferences?.contentLanguages, currentScreen: getNavigationMetadata()?.currentScreen, isBetaUser: base.isBetaUser, })}