@launchdarkly/js-client-sdk 0.1.0 → 0.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.
- package/CHANGELOG.md +36 -0
- package/dist/compat.cjs +1 -0
- package/dist/compat.d.cts +182 -0
- package/dist/compat.d.ts +182 -0
- package/dist/compat.js +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +205 -0
- package/dist/index.d.ts +205 -0
- package/dist/index.js +1 -0
- package/dist/metafile-cjs.json +1 -0
- package/dist/metafile-esm.json +1 -0
- package/package.json +29 -16
- package/dist/index.cjs.js +0 -2
- package/dist/index.cjs.js.map +0 -1
- package/dist/index.es.js +0 -2
- package/dist/index.es.js.map +0 -1
- package/dist/src/BrowserApi.d.ts +0 -48
- package/dist/src/BrowserApi.d.ts.map +0 -1
- package/dist/src/BrowserClient.d.ts +0 -68
- package/dist/src/BrowserClient.d.ts.map +0 -1
- package/dist/src/BrowserDataManager.d.ts +0 -20
- package/dist/src/BrowserDataManager.d.ts.map +0 -1
- package/dist/src/BrowserIdentifyOptions.d.ts +0 -23
- package/dist/src/BrowserIdentifyOptions.d.ts.map +0 -1
- package/dist/src/BrowserStateDetector.d.ts +0 -2
- package/dist/src/BrowserStateDetector.d.ts.map +0 -1
- package/dist/src/bootstrap.d.ts +0 -5
- package/dist/src/bootstrap.d.ts.map +0 -1
- package/dist/src/goals/GoalManager.d.ts +0 -20
- package/dist/src/goals/GoalManager.d.ts.map +0 -1
- package/dist/src/goals/GoalTracker.d.ts +0 -16
- package/dist/src/goals/GoalTracker.d.ts.map +0 -1
- package/dist/src/goals/Goals.d.ts +0 -33
- package/dist/src/goals/Goals.d.ts.map +0 -1
- package/dist/src/goals/LocationWatcher.d.ts +0 -6
- package/dist/src/goals/LocationWatcher.d.ts.map +0 -1
- package/dist/src/index.d.ts +0 -35
- package/dist/src/index.d.ts.map +0 -1
- package/dist/src/options.d.ts +0 -49
- package/dist/src/options.d.ts.map +0 -1
- package/dist/src/platform/Backoff.d.ts +0 -42
- package/dist/src/platform/Backoff.d.ts.map +0 -1
- package/dist/src/platform/BrowserCrypto.d.ts +0 -7
- package/dist/src/platform/BrowserCrypto.d.ts.map +0 -1
- package/dist/src/platform/BrowserEncoding.d.ts +0 -10
- package/dist/src/platform/BrowserEncoding.d.ts.map +0 -1
- package/dist/src/platform/BrowserHasher.d.ts +0 -10
- package/dist/src/platform/BrowserHasher.d.ts.map +0 -1
- package/dist/src/platform/BrowserInfo.d.ts +0 -6
- package/dist/src/platform/BrowserInfo.d.ts.map +0 -1
- package/dist/src/platform/BrowserPlatform.d.ts +0 -10
- package/dist/src/platform/BrowserPlatform.d.ts.map +0 -1
- package/dist/src/platform/BrowserRequests.d.ts +0 -7
- package/dist/src/platform/BrowserRequests.d.ts.map +0 -1
- package/dist/src/platform/DefaultBrowserEventSource.d.ts +0 -33
- package/dist/src/platform/DefaultBrowserEventSource.d.ts.map +0 -1
- package/dist/src/platform/LocalStorage.d.ts +0 -16
- package/dist/src/platform/LocalStorage.d.ts.map +0 -1
- package/dist/src/platform/randomUuidV4.d.ts +0 -12
- package/dist/src/platform/randomUuidV4.d.ts.map +0 -1
package/dist/index.es.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../../../shared/common/dist/esm/index.mjs","../../../shared/sdk-client/dist/esm/index.mjs","../../src/BrowserApi.ts","../../src/BrowserDataManager.ts","../../src/bootstrap.ts","../../src/BrowserStateDetector.ts","../../../../node_modules/escape-string-regexp/index.js","../../src/goals/GoalTracker.ts","../../src/goals/LocationWatcher.ts","../../src/goals/GoalManager.ts","../../src/options.ts","../../src/platform/BrowserHasher.ts","../../src/platform/randomUuidV4.ts","../../src/platform/BrowserCrypto.ts","../../src/platform/BrowserEncoding.ts","../../src/platform/BrowserInfo.ts","../../src/platform/Backoff.ts","../../src/platform/DefaultBrowserEventSource.ts","../../src/platform/BrowserRequests.ts","../../src/platform/LocalStorage.ts","../../src/platform/BrowserPlatform.ts","../../src/BrowserClient.ts","../../src/goals/Goals.ts","../../src/index.ts"],"sourcesContent":["/**\n * Converts a literal to a ref string.\n * @param value\n * @returns An escaped literal which can be used as a ref.\n */\nfunction toRefString(value) {\n return `/${value.replace(/~/g, '~0').replace(/\\//g, '~1')}`;\n}\n/**\n * Produce a literal from a ref component.\n * @param ref\n * @returns A literal version of the ref.\n */\nfunction unescape(ref) {\n return ref.indexOf('~') ? ref.replace(/~1/g, '/').replace(/~0/g, '~') : ref;\n}\nfunction getComponents(reference) {\n const referenceWithoutPrefix = reference.startsWith('/') ? reference.substring(1) : reference;\n return referenceWithoutPrefix.split('/').map((component) => unescape(component));\n}\nfunction isLiteral(reference) {\n return !reference.startsWith('/');\n}\nfunction validate(reference) {\n return !reference.match(/\\/\\/|(^\\/.*~[^0|^1])|~$/);\n}\nclass AttributeReference {\n /**\n * Take an attribute reference string, or literal string, and produce\n * an attribute reference.\n *\n * Legacy user objects would have been created with names not\n * references. So, in that case, we need to use them as a component\n * without escaping them.\n *\n * e.g. A user could contain a custom attribute of `/a` which would\n * become the literal `a` if treated as a reference. Which would cause\n * it to no longer be redacted.\n * @param refOrLiteral The attribute reference string or literal string.\n * @param literal it true the value should be treated as a literal.\n */\n constructor(refOrLiteral, literal = false) {\n if (!literal) {\n this.redactionName = refOrLiteral;\n if (refOrLiteral === '' || refOrLiteral === '/' || !validate(refOrLiteral)) {\n this.isValid = false;\n this._components = [];\n return;\n }\n if (isLiteral(refOrLiteral)) {\n this._components = [refOrLiteral];\n }\n else if (refOrLiteral.indexOf('/', 1) < 0) {\n this._components = [unescape(refOrLiteral.slice(1))];\n }\n else {\n this._components = getComponents(refOrLiteral);\n }\n // The items inside of '_meta' are not intended to be addressable.\n // Excluding it as a valid reference means that we can make it non-addressable\n // without having to copy all the attributes out of the context object\n // provided by the user.\n if (this._components[0] === '_meta') {\n this.isValid = false;\n }\n else {\n this.isValid = true;\n }\n }\n else {\n const literalVal = refOrLiteral;\n this._components = [literalVal];\n this.isValid = literalVal !== '';\n // Literals which start with '/' need escaped to prevent ambiguity.\n this.redactionName = literalVal.startsWith('/') ? toRefString(literalVal) : literalVal;\n }\n }\n get(target) {\n const { _components: components, isValid } = this;\n if (!isValid) {\n return undefined;\n }\n let current = target;\n // This doesn't use a range based for loops, because those use generators.\n // See `no-restricted-syntax`.\n // It also doesn't use a collection method because this logic is more\n // straightforward with a loop.\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (current !== null &&\n current !== undefined &&\n // See https://eslint.org/docs/rules/no-prototype-builtins\n Object.prototype.hasOwnProperty.call(current, component) &&\n typeof current === 'object' &&\n // We do not want to allow indexing into an array.\n !Array.isArray(current)) {\n current = current[component];\n }\n else {\n return undefined;\n }\n }\n return current;\n }\n getComponent(depth) {\n return this._components[depth];\n }\n get depth() {\n return this._components.length;\n }\n get isKind() {\n return this._components.length === 1 && this._components[0] === 'kind';\n }\n compare(other) {\n return (this.depth === other.depth &&\n this._components.every((value, index) => value === other.getComponent(index)));\n }\n}\n/**\n * For use as invalid references when deserializing Flag/Segment data.\n */\nAttributeReference.InvalidReference = new AttributeReference('');\n\n/* eslint-disable class-methods-use-this */\n/* eslint-disable max-classes-per-file */\n/**\n * Validate a factory or instance.\n */\nclass FactoryOrInstance {\n is(factoryOrInstance) {\n if (Array.isArray(factoryOrInstance)) {\n return false;\n }\n const anyFactory = factoryOrInstance;\n const typeOfFactory = typeof anyFactory;\n return typeOfFactory === 'function' || typeOfFactory === 'object';\n }\n getType() {\n return 'factory method or object';\n }\n}\n/**\n * Validate a basic type.\n */\nclass Type {\n constructor(typeName, example) {\n this._typeName = typeName;\n this.typeOf = typeof example;\n }\n is(u) {\n if (Array.isArray(u)) {\n return false;\n }\n return typeof u === this.typeOf;\n }\n getType() {\n return this._typeName;\n }\n}\n/**\n * Validate an array of the specified type.\n *\n * This does not validate instances of types. All class instances\n * of classes will simply objects.\n */\nclass TypeArray {\n constructor(typeName, example) {\n this._typeName = typeName;\n this.typeOf = typeof example;\n }\n is(u) {\n if (Array.isArray(u)) {\n if (u.length > 0) {\n return u.every((val) => typeof val === this.typeOf);\n }\n return true;\n }\n return false;\n }\n getType() {\n return this._typeName;\n }\n}\n/**\n * Validate a value is a number and is greater or eval than a minimum.\n */\nclass NumberWithMinimum extends Type {\n constructor(min) {\n super(`number with minimum value of ${min}`, 0);\n this.min = min;\n }\n is(u) {\n return typeof u === this.typeOf && u >= this.min;\n }\n}\n/**\n * Validate a value is a string and it matches the given expression.\n */\nclass StringMatchingRegex extends Type {\n constructor(expression) {\n super(`string matching ${expression}`, '');\n this.expression = expression;\n }\n is(u) {\n return typeof u === 'string' && !!u.match(this.expression);\n }\n}\n/**\n * Validate a value is a function.\n */\nclass Function {\n is(u) {\n // We cannot inspect the parameters and there isn't really\n // a generic function type we can instantiate.\n // So the type guard is here just to make TS comfortable\n // calling something after using this guard.\n return typeof u === 'function';\n }\n getType() {\n return 'function';\n }\n}\nclass NullableBoolean {\n is(u) {\n return typeof u === 'boolean' || typeof u === 'undefined' || u === null;\n }\n getType() {\n return 'boolean | undefined | null';\n }\n}\n// Our reference SDK, Go, parses date/time strings with the time.RFC3339Nano format.\n// This regex should match strings that are valid in that format, and no others.\n// Acceptable:\n// 2019-10-31T23:59:59Z, 2019-10-31T23:59:59.100Z,\n// 2019-10-31T23:59:59-07, 2019-10-31T23:59:59-07:00, etc.\n// Unacceptable: no \"T\", no time zone designation\nconst DATE_REGEX = /^\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(\\.\\d\\d*)?(Z|[-+]\\d\\d(:\\d\\d)?)/;\n/**\n * Validate a value is a date. Values which are numbers are treated as dates and any string\n * which if compliant with `time.RFC3339Nano` is a date.\n */\nclass DateValidator {\n is(u) {\n return typeof u === 'number' || (typeof u === 'string' && DATE_REGEX.test(u));\n }\n getType() {\n return 'date';\n }\n}\n/**\n * Validates that a string is a valid kind.\n */\nclass KindValidator extends StringMatchingRegex {\n constructor() {\n super(/^(\\w|\\.|-)+$/);\n }\n is(u) {\n return super.is(u) && u !== 'kind';\n }\n}\n/**\n * A set of standard type validators.\n */\nclass TypeValidators {\n static createTypeArray(typeName, example) {\n return new TypeArray(typeName, example);\n }\n static numberWithMin(min) {\n return new NumberWithMinimum(min);\n }\n static stringMatchingRegex(expression) {\n return new StringMatchingRegex(expression);\n }\n}\nTypeValidators.String = new Type('string', '');\nTypeValidators.Number = new Type('number', 0);\nTypeValidators.ObjectOrFactory = new FactoryOrInstance();\nTypeValidators.Object = new Type('object', {});\nTypeValidators.StringArray = new TypeArray('string[]', '');\nTypeValidators.Boolean = new Type('boolean', true);\nTypeValidators.Function = new Function();\nTypeValidators.Date = new DateValidator();\nTypeValidators.Kind = new KindValidator();\nTypeValidators.NullableBoolean = new NullableBoolean();\n\n/**\n * Check if a context is a single kind context.\n * @param context\n * @returns true if the context is a single kind context.\n */\nfunction isSingleKind(context) {\n if ('kind' in context) {\n return TypeValidators.String.is(context.kind) && context.kind !== 'multi';\n }\n return false;\n}\n/**\n * Check if a context is a multi-kind context.\n * @param context\n * @returns true if it is a multi-kind context.\n */\nfunction isMultiKind(context) {\n if ('kind' in context) {\n return TypeValidators.String.is(context.kind) && context.kind === 'multi';\n }\n return false;\n}\n/**\n * Check if a context is a legacy user context.\n * @param context\n * @returns true if it is a legacy user context.\n */\nfunction isLegacyUser(context) {\n return !('kind' in context) || context.kind === null || context.kind === undefined;\n}\n\n// The general strategy for the context is to transform the passed in context\n// as little as possible. We do convert the legacy users to a single kind\n// context, but we do not translate all passed contexts into a rigid structure.\n// The context will have to be copied for events, but we want to avoid any\n// copying that we can.\n// So we validate that the information we are given is correct, and then we\n// just proxy calls with a nicely typed interface.\n// This is to reduce work on the hot-path. Later, for event processing, deeper\n// cloning of the context will be done.\n// When no kind is specified, then this kind will be used.\nconst DEFAULT_KIND = 'user';\n// The API allows for calling with an `LDContext` which is\n// `LDUser | LDSingleKindContext | LDMultiKindContext`. When ingesting a context\n// first the type must be determined to allow us to put it into a consistent type.\n/**\n * The partial URL encoding is needed because : is a valid character in context keys.\n *\n * Partial encoding is the replacement of all colon (:) characters with the URL\n * encoded equivalent (%3A) and all percent (%) characters with the URL encoded\n * equivalent (%25).\n * @param key The key to encode.\n * @returns Partially URL encoded key.\n */\nfunction encodeKey(key) {\n if (key.includes('%') || key.includes(':')) {\n return key.replace(/%/g, '%25').replace(/:/g, '%3A');\n }\n return key;\n}\n/**\n * Check if the given value is a LDContextCommon.\n * @param kindOrContext\n * @returns true if it is an LDContextCommon\n *\n * Due to a limitation in the expressiveness of these highly polymorphic types any field\n * in a multi-kind context can either be a context or 'kind'. So we need to re-assure\n * the compiler that it isn't the word multi.\n *\n * Because we do not allow top level values in a multi-kind context we can validate\n * that as well.\n */\nfunction isContextCommon(kindOrContext) {\n return kindOrContext && TypeValidators.Object.is(kindOrContext);\n}\n/**\n * Validate a context kind.\n * @param kind\n * @returns true if the kind is valid.\n */\nfunction validKind(kind) {\n return TypeValidators.Kind.is(kind);\n}\n/**\n * Validate a context key.\n * @param key\n * @returns true if the key is valid.\n */\nfunction validKey(key) {\n return TypeValidators.String.is(key) && key !== '';\n}\nfunction processPrivateAttributes(privateAttributes, literals = false) {\n if (privateAttributes) {\n return privateAttributes.map((privateAttribute) => new AttributeReference(privateAttribute, literals));\n }\n return [];\n}\nfunction defined(value) {\n return value !== null && value !== undefined;\n}\n/**\n * Convert a legacy user to a single kind context.\n * @param user\n * @returns A single kind context.\n */\nfunction legacyToSingleKind(user) {\n const singleKindContext = {\n // Key was coerced to a string for eval and events, so we can do that up-front.\n ...(user.custom || []),\n kind: 'user',\n key: String(user.key),\n };\n // For legacy users we never established a difference between null\n // and undefined for inputs. Because anonymous can be used in evaluations\n // we would want it to not possibly match true/false unless defined.\n // Which is different than coercing a null/undefined anonymous as `false`.\n if (defined(user.anonymous)) {\n const anonymous = !!user.anonymous;\n delete singleKindContext.anonymous;\n singleKindContext.anonymous = anonymous;\n }\n if (user.name !== null && user.name !== undefined) {\n singleKindContext.name = user.name;\n }\n if (user.ip !== null && user.ip !== undefined) {\n singleKindContext.ip = user.ip;\n }\n if (user.firstName !== null && user.firstName !== undefined) {\n singleKindContext.firstName = user.firstName;\n }\n if (user.lastName !== null && user.lastName !== undefined) {\n singleKindContext.lastName = user.lastName;\n }\n if (user.email !== null && user.email !== undefined) {\n singleKindContext.email = user.email;\n }\n if (user.avatar !== null && user.avatar !== undefined) {\n singleKindContext.avatar = user.avatar;\n }\n if (user.country !== null && user.country !== undefined) {\n singleKindContext.country = user.country;\n }\n if (user.privateAttributeNames !== null && user.privateAttributeNames !== undefined) {\n singleKindContext._meta = {\n privateAttributes: user.privateAttributeNames,\n };\n }\n // We are not pulling private attributes over because we will serialize\n // those from attribute references for events.\n return singleKindContext;\n}\n/**\n * Container for a context/contexts. Because contexts come from external code\n * they must be thoroughly validated and then formed to comply with\n * the type system.\n */\nclass Context {\n /**\n * Contexts should be created using the static factory method {@link Context.fromLDContext}.\n * @param kind The kind of the context.\n *\n * The factory methods are static functions within the class because they access private\n * implementation details, so they cannot be free functions.\n */\n constructor(valid, kind, message) {\n this._isMulti = false;\n this._isUser = false;\n this._wasLegacy = false;\n this._contexts = {};\n this.kind = kind;\n this.valid = valid;\n this.message = message;\n }\n static _contextForError(kind, message) {\n return new Context(false, kind, message);\n }\n static _getValueFromContext(reference, context) {\n if (!context || !reference.isValid) {\n return undefined;\n }\n if (reference.depth === 1 && reference.getComponent(0) === 'anonymous') {\n return !!context?.anonymous;\n }\n return reference.get(context);\n }\n _contextForKind(kind) {\n if (this._isMulti) {\n return this._contexts[kind];\n }\n if (this.kind === kind) {\n return this._context;\n }\n return undefined;\n }\n static _fromMultiKindContext(context) {\n const kinds = Object.keys(context).filter((key) => key !== 'kind');\n const kindsValid = kinds.every(validKind);\n if (!kinds.length) {\n return Context._contextForError('multi', 'A multi-kind context must contain at least one kind');\n }\n if (!kindsValid) {\n return Context._contextForError('multi', 'Context contains invalid kinds');\n }\n const privateAttributes = {};\n let contextsAreObjects = true;\n const contexts = kinds.reduce((acc, kind) => {\n const singleContext = context[kind];\n if (isContextCommon(singleContext)) {\n acc[kind] = singleContext;\n privateAttributes[kind] = processPrivateAttributes(singleContext._meta?.privateAttributes);\n }\n else {\n // No early break isn't the most efficient, but it is an error condition.\n contextsAreObjects = false;\n }\n return acc;\n }, {});\n if (!contextsAreObjects) {\n return Context._contextForError('multi', 'Context contained contexts that were not objects');\n }\n if (!Object.values(contexts).every((part) => validKey(part.key))) {\n return Context._contextForError('multi', 'Context contained invalid keys');\n }\n // There was only a single kind in the multi-kind context.\n // So we can just translate this to a single-kind context.\n if (kinds.length === 1) {\n const kind = kinds[0];\n const created = new Context(true, kind);\n created._context = { ...contexts[kind], kind };\n created._privateAttributeReferences = privateAttributes;\n created._isUser = kind === 'user';\n return created;\n }\n const created = new Context(true, context.kind);\n created._contexts = contexts;\n created._privateAttributeReferences = privateAttributes;\n created._isMulti = true;\n return created;\n }\n static _fromSingleKindContext(context) {\n const { key, kind } = context;\n const kindValid = validKind(kind);\n const keyValid = validKey(key);\n if (!kindValid) {\n return Context._contextForError(kind ?? 'unknown', 'The kind was not valid for the context');\n }\n if (!keyValid) {\n return Context._contextForError(kind, 'The key for the context was not valid');\n }\n // The JSON interfaces uses dangling _.\n // eslint-disable-next-line no-underscore-dangle\n const privateAttributeReferences = processPrivateAttributes(context._meta?.privateAttributes);\n const created = new Context(true, kind);\n created._isUser = kind === 'user';\n created._context = context;\n created._privateAttributeReferences = {\n [kind]: privateAttributeReferences,\n };\n return created;\n }\n static _fromLegacyUser(context) {\n const keyValid = context.key !== undefined && context.key !== null;\n // For legacy users we allow empty keys.\n if (!keyValid) {\n return Context._contextForError('user', 'The key for the context was not valid');\n }\n const created = new Context(true, 'user');\n created._isUser = true;\n created._wasLegacy = true;\n created._context = legacyToSingleKind(context);\n created._privateAttributeReferences = {\n user: processPrivateAttributes(context.privateAttributeNames, true),\n };\n return created;\n }\n /**\n * Attempt to create a {@link Context} from an {@link LDContext}.\n * @param context The input context to create a Context from.\n * @returns a {@link Context}, if the context was not valid, then the returned contexts `valid`\n * property will be false.\n */\n static fromLDContext(context) {\n if (!context) {\n return Context._contextForError('unknown', 'No context specified. Returning default value');\n }\n if (isSingleKind(context)) {\n return Context._fromSingleKindContext(context);\n }\n if (isMultiKind(context)) {\n return Context._fromMultiKindContext(context);\n }\n if (isLegacyUser(context)) {\n return Context._fromLegacyUser(context);\n }\n return Context._contextForError('unknown', 'Context was not of a valid kind');\n }\n /**\n * Creates a {@link LDContext} from a {@link Context}.\n * @param context to be converted\n * @returns an {@link LDContext} if input was valid, otherwise undefined\n */\n static toLDContext(context) {\n if (!context.valid) {\n return undefined;\n }\n const contexts = context.getContexts();\n if (!context._isMulti) {\n return contexts[0][1];\n }\n const result = {\n kind: 'multi',\n };\n contexts.forEach((kindAndContext) => {\n const kind = kindAndContext[0];\n const nestedContext = kindAndContext[1];\n result[kind] = nestedContext;\n });\n return result;\n }\n /**\n * Attempt to get a value for the given context kind using the given reference.\n * @param reference The reference to the value to get.\n * @param kind The kind of the context to get the value for.\n * @returns a value or `undefined` if one is not found.\n */\n valueForKind(reference, kind = DEFAULT_KIND) {\n if (reference.isKind) {\n return this.kinds;\n }\n return Context._getValueFromContext(reference, this._contextForKind(kind));\n }\n /**\n * Attempt to get a key for the specified kind.\n * @param kind The kind to get a key for.\n * @returns The key for the specified kind, or undefined.\n */\n key(kind = DEFAULT_KIND) {\n return this._contextForKind(kind)?.key;\n }\n /**\n * True if this is a multi-kind context.\n */\n get isMultiKind() {\n return this._isMulti;\n }\n /**\n * Get the canonical key for this context.\n */\n get canonicalKey() {\n if (this._isUser) {\n return this._context.key;\n }\n if (this._isMulti) {\n return Object.keys(this._contexts)\n .sort()\n .map((key) => `${key}:${encodeKey(this._contexts[key].key)}`)\n .join(':');\n }\n return `${this.kind}:${encodeKey(this._context.key)}`;\n }\n /**\n * Get the kinds of this context.\n */\n get kinds() {\n if (this._isMulti) {\n return Object.keys(this._contexts);\n }\n return [this.kind];\n }\n /**\n * Get the kinds, and their keys, for this context.\n */\n get kindsAndKeys() {\n if (this._isMulti) {\n return Object.entries(this._contexts).reduce((acc, [kind, context]) => {\n acc[kind] = context.key;\n return acc;\n }, {});\n }\n return { [this.kind]: this._context.key };\n }\n /**\n * Get the attribute references.\n *\n * @param kind\n */\n privateAttributes(kind) {\n return this._privateAttributeReferences?.[kind] || [];\n }\n /**\n * Get the underlying context objects from this context.\n *\n * This method is intended to be used in event generation.\n *\n * The returned objects should not be modified.\n */\n getContexts() {\n if (this._isMulti) {\n return Object.entries(this._contexts);\n }\n return [[this.kind, this._context]];\n }\n get legacy() {\n return this._wasLegacy;\n }\n}\nContext.UserKind = DEFAULT_KIND;\n\n// _meta is part of the specification.\n// These attributes cannot be removed via a private attribute.\nconst protectedAttributes = ['key', 'kind', '_meta', 'anonymous'].map((str) => new AttributeReference(str, true));\n// Attributes that should be stringified for legacy users.\nconst legacyTopLevelCopyAttributes = [\n 'name',\n 'ip',\n 'firstName',\n 'lastName',\n 'email',\n 'avatar',\n 'country',\n];\nfunction compare(a, b) {\n return a.depth === b.length && b.every((value, index) => value === a.getComponent(index));\n}\nfunction cloneWithRedactions(target, references) {\n const stack = [];\n const cloned = {};\n const excluded = [];\n stack.push(...Object.keys(target).map((key) => ({\n key,\n ptr: [key],\n source: target,\n parent: cloned,\n visited: [target],\n })));\n while (stack.length) {\n const item = stack.pop();\n const redactRef = references.find((ref) => compare(ref, item.ptr));\n if (!redactRef) {\n const value = item.source[item.key];\n // Handle null because it overlaps with object, which we will want to handle later.\n if (value === null) {\n item.parent[item.key] = value;\n }\n else if (Array.isArray(value)) {\n item.parent[item.key] = [...value];\n }\n else if (typeof value === 'object') {\n // Arrays and null must already be handled.\n // Prevent cycles by not visiting the same object\n // with in the same branch. Different branches\n // may contain the same object.\n //\n // Same object visited twice in different branches.\n // A -> B -> D\n // -> C -> D\n // This is fine, which is why it doesn't just check if the object\n // was visited ever.\n if (!item.visited.includes(value)) {\n item.parent[item.key] = {};\n stack.push(...Object.keys(value).map((key) => ({\n key,\n ptr: [...item.ptr, key],\n source: value,\n parent: item.parent[item.key],\n visited: [...item.visited, value],\n })));\n }\n }\n else {\n item.parent[item.key] = value;\n }\n }\n else {\n excluded.push(redactRef.redactionName);\n }\n }\n return { cloned, excluded: excluded.sort() };\n}\nclass ContextFilter {\n constructor(_allAttributesPrivate, _privateAttributes) {\n this._allAttributesPrivate = _allAttributesPrivate;\n this._privateAttributes = _privateAttributes;\n }\n filter(context, redactAnonymousAttributes = false) {\n const contexts = context.getContexts();\n if (contexts.length === 1) {\n return this._filterSingleKind(context, contexts[0][1], contexts[0][0], redactAnonymousAttributes);\n }\n const filteredMulti = {\n kind: 'multi',\n };\n contexts.forEach(([kind, single]) => {\n filteredMulti[kind] = this._filterSingleKind(context, single, kind, redactAnonymousAttributes);\n });\n return filteredMulti;\n }\n _getAttributesToFilter(context, single, kind, redactAllAttributes) {\n return (redactAllAttributes\n ? Object.keys(single).map((k) => new AttributeReference(k, true))\n : [...this._privateAttributes, ...context.privateAttributes(kind)]).filter((attr) => !protectedAttributes.some((protectedAttr) => protectedAttr.compare(attr)));\n }\n _filterSingleKind(context, single, kind, redactAnonymousAttributes) {\n const redactAllAttributes = this._allAttributesPrivate || (redactAnonymousAttributes && single.anonymous === true);\n const { cloned, excluded } = cloneWithRedactions(single, this._getAttributesToFilter(context, single, kind, redactAllAttributes));\n if (context.legacy) {\n legacyTopLevelCopyAttributes.forEach((name) => {\n if (name in cloned) {\n cloned[name] = String(cloned[name]);\n }\n });\n }\n if (excluded.length) {\n if (!cloned._meta) {\n cloned._meta = {};\n }\n cloned._meta.redactedAttributes = excluded;\n }\n if (cloned._meta) {\n delete cloned._meta.privateAttributes;\n if (Object.keys(cloned._meta).length === 0) {\n delete cloned._meta;\n }\n }\n return cloned;\n }\n}\n\nvar DataSourceErrorKind;\n(function (DataSourceErrorKind) {\n /// An unexpected error, such as an uncaught exception, further\n /// described by the error message.\n DataSourceErrorKind[\"Unknown\"] = \"UNKNOWN\";\n /// An I/O error such as a dropped connection.\n DataSourceErrorKind[\"NetworkError\"] = \"NETWORK_ERROR\";\n /// The LaunchDarkly service returned an HTTP response with an error\n /// status, available in the status code.\n DataSourceErrorKind[\"ErrorResponse\"] = \"ERROR_RESPONSE\";\n /// The SDK received malformed data from the LaunchDarkly service.\n DataSourceErrorKind[\"InvalidData\"] = \"INVALID_DATA\";\n})(DataSourceErrorKind || (DataSourceErrorKind = {}));\n\nclass LDFileDataSourceError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyFileDataSourceError';\n }\n}\nclass LDPollingError extends Error {\n constructor(kind, message, status, recoverable = true) {\n super(message);\n this.kind = kind;\n this.status = status;\n this.name = 'LaunchDarklyPollingError';\n this.recoverable = recoverable;\n }\n}\nclass LDStreamingError extends Error {\n constructor(kind, message, code, recoverable = true) {\n super(message);\n this.kind = kind;\n this.code = code;\n this.name = 'LaunchDarklyStreamingError';\n this.recoverable = recoverable;\n }\n}\n\n/* eslint-disable import/prefer-default-export */\n/**\n * Enable / disable Auto environment attributes. When enabled, the SDK will automatically\n * provide data about the mobile environment where the application is running. This data makes it simpler to target\n * your mobile customers based on application name or version, or on device characteristics including manufacturer,\n * model, operating system, locale, and so on. We recommend enabling this when you configure the SDK. To learn more,\n * read [Automatic environment attributes](https://docs.launchdarkly.com/sdk/features/environment-attributes).\n * for more documentation.\n *\n * The default is disabled.\n */\nvar AutoEnvAttributes;\n(function (AutoEnvAttributes) {\n AutoEnvAttributes[AutoEnvAttributes[\"Disabled\"] = 0] = \"Disabled\";\n AutoEnvAttributes[AutoEnvAttributes[\"Enabled\"] = 1] = \"Enabled\";\n})(AutoEnvAttributes || (AutoEnvAttributes = {}));\n\nvar LDEventType;\n(function (LDEventType) {\n LDEventType[LDEventType[\"AnalyticsEvents\"] = 0] = \"AnalyticsEvents\";\n LDEventType[LDEventType[\"DiagnosticEvent\"] = 1] = \"DiagnosticEvent\";\n})(LDEventType || (LDEventType = {}));\nvar LDDeliveryStatus;\n(function (LDDeliveryStatus) {\n LDDeliveryStatus[LDDeliveryStatus[\"Succeeded\"] = 0] = \"Succeeded\";\n LDDeliveryStatus[LDDeliveryStatus[\"Failed\"] = 1] = \"Failed\";\n LDDeliveryStatus[LDDeliveryStatus[\"FailedAndMustShutDown\"] = 2] = \"FailedAndMustShutDown\";\n})(LDDeliveryStatus || (LDDeliveryStatus = {}));\n\nvar index$1 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n get LDDeliveryStatus () { return LDDeliveryStatus; },\n get LDEventType () { return LDEventType; }\n});\n\n/**\n * Attempt to produce a string representation of a value.\n * The format should be roughly comparable to `util.format`\n * aside from object which will be JSON versus the `util.inspect`\n * format.\n * @param val\n * @returns A string representation of the value if possible.\n */\nfunction tryStringify(val) {\n if (typeof val === 'string') {\n return val;\n }\n if (val === undefined) {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (Object.prototype.hasOwnProperty.call(val, 'toString')) {\n try {\n return val.toString();\n }\n catch {\n /* Keep going */\n }\n }\n if (typeof val === 'bigint') {\n return `${val}n`;\n }\n try {\n return JSON.stringify(val);\n }\n catch (error) {\n if (error instanceof TypeError && error.message.indexOf('circular') >= 0) {\n return '[Circular]';\n }\n return '[Not Stringifiable]';\n }\n}\n/**\n * Attempt to produce a numeric representation.\n * BigInts have an `n` suffix.\n * @param val\n * @returns The numeric representation or 'NaN' if not numeric.\n */\nfunction toNumber(val) {\n // Symbol has to be treated special because it will\n // throw an exception if an attempt is made to convert it.\n if (typeof val === 'symbol') {\n return 'NaN';\n }\n if (typeof val === 'bigint') {\n return `${val}n`;\n }\n return String(Number(val));\n}\n/**\n * Attempt to produce an integer representation.\n * BigInts have an `n` suffix.\n * @param val\n * @returns The integer representation or 'NaN' if not numeric.\n */\nfunction toInt(val) {\n if (typeof val === 'symbol') {\n return 'NaN';\n }\n if (typeof val === 'bigint') {\n return `${val}n`;\n }\n return String(parseInt(val, 10));\n}\n/**\n * Attempt to produce a float representation.\n * BigInts have an `n` suffix.\n * @param val\n * @returns The integer representation or 'NaN' if not numeric.\n */\nfunction toFloat(val) {\n if (typeof val === 'symbol') {\n return 'NaN';\n }\n return String(parseFloat(val));\n}\n// Based on:\n// https://nodejs.org/api/util.html#utilformatformat-args\n// The result will not match node exactly, but it should get the\n// right information through.\nconst escapes = {\n s: (val) => tryStringify(val),\n d: (val) => toNumber(val),\n i: (val) => toInt(val),\n f: (val) => toFloat(val),\n j: (val) => tryStringify(val),\n o: (val) => tryStringify(val),\n // eslint-disable-next-line @typescript-eslint/naming-convention\n O: (val) => tryStringify(val),\n c: () => '',\n};\n/**\n * A basic formatted for use where `util.format` is not available.\n * This will not be as performant, but it will produce formatted\n * messages.\n *\n * @internal\n *\n * @param args\n * @returns Formatted string.\n */\nfunction format(...args) {\n const formatString = args.shift();\n if (TypeValidators.String.is(formatString)) {\n let out = '';\n let i = 0;\n while (i < formatString.length) {\n const char = formatString.charAt(i);\n if (char === '%') {\n const nextIndex = i + 1;\n if (nextIndex < formatString.length) {\n const nextChar = formatString.charAt(i + 1);\n if (nextChar in escapes && args.length) {\n const value = args.shift();\n // This rule is for math.\n // eslint-disable-next-line no-unsafe-optional-chaining\n out += escapes[nextChar]?.(value);\n }\n else if (nextChar === '%') {\n out += '%';\n }\n else {\n out += `%${nextChar}`;\n }\n i += 2;\n }\n }\n else {\n out += char;\n i += 1;\n }\n }\n // If there are any args left after we exhaust the format string\n // then just stick those on the end.\n if (args.length) {\n if (out.length) {\n out += ' ';\n }\n out += args.map(tryStringify).join(' ');\n }\n return out;\n }\n return args.map(tryStringify).join(' ');\n}\n\nconst LogPriority = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n none: 4,\n};\nconst LevelNames = ['debug', 'info', 'warn', 'error', 'none'];\n/**\n * A basic logger which handles filtering by level.\n *\n * With the default options it will write to `console.error`\n * and it will use the formatting provided by `console.error`.\n * If the destination is overwritten, then it will use an included\n * formatter similar to `util.format`.\n *\n * If a formatter is available, then that should be overridden\n * as well for performance.\n */\nclass BasicLogger {\n /**\n * This should only be used as a default fallback and not as a convenient\n * solution. In most cases you should construct a new instance with the\n * appropriate options for your specific needs.\n */\n static get() {\n return new BasicLogger({});\n }\n constructor(options) {\n this._logLevel = LogPriority[options.level ?? 'info'] ?? LogPriority.info;\n this._name = options.name ?? 'LaunchDarkly';\n // eslint-disable-next-line no-console\n this._destination = options.destination;\n this._formatter = options.formatter;\n }\n _tryFormat(...args) {\n try {\n if (this._formatter) {\n // In case the provided formatter fails.\n return this._formatter?.(...args);\n }\n return format(...args);\n }\n catch {\n return format(...args);\n }\n }\n _tryWrite(msg) {\n try {\n this._destination(msg);\n }\n catch {\n // eslint-disable-next-line no-console\n console.error(msg);\n }\n }\n _log(level, args) {\n if (level >= this._logLevel) {\n const prefix = `${LevelNames[level]}: [${this._name}]`;\n try {\n if (this._destination) {\n this._tryWrite(`${prefix} ${this._tryFormat(...args)}`);\n }\n else {\n // `console.error` has its own formatter.\n // So we don't need to do anything.\n // eslint-disable-next-line no-console\n console.error(...args);\n }\n }\n catch {\n // If all else fails do not break.\n // eslint-disable-next-line no-console\n console.error(...args);\n }\n }\n }\n error(...args) {\n this._log(LogPriority.error, args);\n }\n warn(...args) {\n this._log(LogPriority.warn, args);\n }\n info(...args) {\n this._log(LogPriority.info, args);\n }\n debug(...args) {\n this._log(LogPriority.debug, args);\n }\n}\n\nconst loggerRequirements = {\n error: TypeValidators.Function,\n warn: TypeValidators.Function,\n info: TypeValidators.Function,\n debug: TypeValidators.Function,\n};\n/**\n * The safeLogger logic exists because we allow the application to pass in a custom logger, but\n * there is no guarantee that the logger works correctly and if it ever throws exceptions there\n * could be serious consequences (e.g. an uncaught exception within an error event handler, due\n * to the SDK trying to log the error, can terminate the application). An exception could result\n * from faulty logic in the logger implementation, or it could be that this is not a logger at\n * all but some other kind of object; the former is handled by a catch block that logs an error\n * message to the SDK's default logger, and we can at least partly guard against the latter by\n * checking for the presence of required methods at configuration time.\n */\nclass SafeLogger {\n /**\n * Construct a safe logger with the specified logger.\n * @param logger The logger to use.\n * @param fallback A fallback logger to use in case an issue is encountered using\n * the provided logger.\n */\n constructor(logger, fallback) {\n Object.entries(loggerRequirements).forEach(([level, validator]) => {\n if (!validator.is(logger[level])) {\n throw new Error(`Provided logger instance must support logger.${level}(...) method`);\n // Note that the SDK normally does not throw exceptions to the application, but that rule\n // does not apply to LDClient.init() which will throw an exception if the parameters are so\n // invalid that we cannot proceed with creating the client. An invalid logger meets those\n // criteria since the SDK calls the logger during nearly all of its operations.\n }\n });\n this._logger = logger;\n this._fallback = fallback;\n }\n _log(level, args) {\n try {\n this._logger[level](...args);\n }\n catch {\n // If all else fails do not break.\n this._fallback[level](...args);\n }\n }\n error(...args) {\n this._log('error', args);\n }\n warn(...args) {\n this._log('warn', args);\n }\n info(...args) {\n this._log('info', args);\n }\n debug(...args) {\n this._log('debug', args);\n }\n}\n\nconst createSafeLogger = (logger) => {\n const basicLogger = new BasicLogger({\n level: 'info',\n // eslint-disable-next-line no-console\n destination: console.error,\n formatter: format,\n });\n return logger ? new SafeLogger(logger, basicLogger) : basicLogger;\n};\n\n/**\n * Messages for issues which can be encountered from processing the configuration options.\n */\nclass OptionMessages {\n static deprecated(oldName, newName) {\n return `\"${oldName}\" is deprecated, please use \"${newName}\"`;\n }\n static optionBelowMinimum(name, value, min) {\n return `Config option \"${name}\" had invalid value of ${value}, using minimum of ${min} instead`;\n }\n static unknownOption(name) {\n return `Ignoring unknown config option \"${name}\"`;\n }\n static wrongOptionType(name, expectedType, actualType) {\n return `Config option \"${name}\" should be of type ${expectedType}, got ${actualType}, using default value`;\n }\n static wrongOptionTypeBoolean(name, actualType) {\n return `Config option \"${name}\" should be a boolean, got ${actualType}, converting to boolean`;\n }\n static invalidTagValue(name) {\n return `Config option \"${name}\" must only contain letters, numbers, ., _ or -.`;\n }\n static tagValueTooLong(name) {\n return `Value of \"${name}\" was longer than 64 characters and was discarded.`;\n }\n static partialEndpoint(name) {\n return `You have set custom uris without specifying the ${name} URI; connections may not work properly`;\n }\n}\n\n/**\n * Expression to validate characters that are allowed in tag keys and values.\n */\nconst allowedTagCharacters = /^(\\w|\\.|-)+$/;\nconst regexValidator = TypeValidators.stringMatchingRegex(allowedTagCharacters);\nconst tagValidator = {\n is: (u, name) => {\n if (regexValidator.is(u)) {\n if (u.length > 64) {\n return { valid: false, message: OptionMessages.tagValueTooLong(name) };\n }\n return { valid: true };\n }\n return { valid: false, message: OptionMessages.invalidTagValue(name) };\n },\n};\n/**\n * Class for managing tags.\n */\nclass ApplicationTags {\n constructor(options) {\n const tags = {};\n const application = options?.application;\n const logger = options?.logger;\n if (application) {\n Object.entries(application).forEach(([key, value]) => {\n if (value !== null && value !== undefined) {\n const { valid, message } = tagValidator.is(value, `application.${key}`);\n if (!valid) {\n logger?.warn(message);\n }\n else if (key === 'versionName') {\n tags[`application-version-name`] = [value];\n }\n else {\n tags[`application-${key}`] = [value];\n }\n }\n });\n }\n const tagKeys = Object.keys(tags);\n if (tagKeys.length) {\n this.value = tagKeys\n .sort()\n .flatMap((key) => tags[key].sort().map((value) => `${key}/${value}`))\n .join(' ');\n }\n }\n}\n\n/**\n * The client context provides basic configuration and platform support which are required\n * when building SDK components.\n */\nclass ClientContext {\n constructor(sdkKey, configuration, platform) {\n this.platform = platform;\n this.basicConfiguration = {\n tags: configuration.tags,\n logger: configuration.logger,\n offline: configuration.offline,\n serviceEndpoints: configuration.serviceEndpoints,\n sdkKey,\n };\n }\n}\n\nfunction canonicalizeUri(uri) {\n return uri.replace(/\\/+$/, '');\n}\nfunction canonicalizePath(path) {\n return path.replace(/^\\/+/, '').replace(/\\?$/, '');\n}\n/**\n * Specifies the base service URIs used by SDK components.\n */\nclass ServiceEndpoints {\n constructor(streaming, polling, events = ServiceEndpoints.DEFAULT_EVENTS, analyticsEventPath = '/bulk', diagnosticEventPath = '/diagnostic', includeAuthorizationHeader = true, payloadFilterKey) {\n this.streaming = canonicalizeUri(streaming);\n this.polling = canonicalizeUri(polling);\n this.events = canonicalizeUri(events);\n this.analyticsEventPath = analyticsEventPath;\n this.diagnosticEventPath = diagnosticEventPath;\n this.includeAuthorizationHeader = includeAuthorizationHeader;\n this.payloadFilterKey = payloadFilterKey;\n }\n}\n// eslint-disable-next-line @typescript-eslint/naming-convention\nServiceEndpoints.DEFAULT_EVENTS = 'https://events.launchdarkly.com';\nfunction getWithParams(uri, parameters) {\n if (parameters.length === 0) {\n return uri;\n }\n const parts = parameters.map(({ key, value }) => `${key}=${value}`);\n return `${uri}?${parts.join('&')}`;\n}\n/**\n * Get the URI for the streaming endpoint.\n *\n * @param endpoints The service endpoints.\n * @param path The path to the resource, devoid of any query parameters or hrefs.\n * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.\n */\nfunction getStreamingUri(endpoints, path, parameters) {\n const canonicalizedPath = canonicalizePath(path);\n const combinedParameters = [...parameters];\n if (endpoints.payloadFilterKey) {\n combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });\n }\n return getWithParams(`${endpoints.streaming}/${canonicalizedPath}`, combinedParameters);\n}\n/**\n * Get the URI for the polling endpoint.\n *\n * @param endpoints The service endpoints.\n * @param path The path to the resource, devoid of any query parameters or hrefs.\n * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.\n */\nfunction getPollingUri(endpoints, path, parameters) {\n const canonicalizedPath = canonicalizePath(path);\n const combinedParameters = [...parameters];\n if (endpoints.payloadFilterKey) {\n combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });\n }\n return getWithParams(`${endpoints.polling}/${canonicalizedPath}`, combinedParameters);\n}\n/**\n * Get the URI for the events endpoint.\n *\n * @param endpoints The service endpoints.\n * @param path The path to the resource, devoid of any query parameters or hrefs.\n * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.\n */\nfunction getEventsUri(endpoints, path, parameters) {\n const canonicalizedPath = canonicalizePath(path);\n return getWithParams(`${endpoints.events}/${canonicalizedPath}`, parameters);\n}\n\n// These classes are of trivial complexity. If they become\n// more complex, then they could be independent files.\n/* eslint-disable max-classes-per-file */\nclass LDUnexpectedResponseError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyUnexpectedResponseError';\n }\n}\nclass LDClientError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyClientError';\n }\n}\nclass LDTimeoutError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyTimeoutError';\n }\n}\n/**\n * Check if the HTTP error is recoverable. This will return false if a request\n * made with any payload could not recover. If the reason for the failure\n * is payload specific, for instance a payload that is too large, then\n * it could recover with a different payload.\n */\nfunction isHttpRecoverable(status) {\n if (status >= 400 && status < 500) {\n return status === 400 || status === 408 || status === 429;\n }\n return true;\n}\n/**\n * Returns true if the status could recover for a different payload.\n *\n * When used with event processing this indicates that we should discard\n * the payload, but that a subsequent payload may succeed. Therefore we should\n * not stop event processing.\n */\nfunction isHttpLocallyRecoverable(status) {\n if (status === 413) {\n return true;\n }\n return isHttpRecoverable(status);\n}\n\n/**\n * Returns a promise which errors after t seconds.\n *\n * @param t Timeout in seconds.\n * @param taskName Name of task being timed for logging and error reporting.\n */\nfunction cancelableTimedPromise(t, taskName) {\n let timeout;\n let resolve;\n const promise = new Promise((_res, reject) => {\n resolve = _res;\n timeout = setTimeout(() => {\n const e = `${taskName} timed out after ${t} seconds.`;\n reject(new LDTimeoutError(e));\n }, t * 1000);\n });\n return {\n promise,\n cancel: () => {\n resolve();\n clearTimeout(timeout);\n },\n };\n}\n\nfunction clone(obj) {\n if (obj === undefined || obj === null) {\n return obj;\n }\n return JSON.parse(JSON.stringify(obj));\n}\n\n// eslint-disable-next-line import/prefer-default-export\nfunction secondsToMillis(sec) {\n return Math.trunc(sec * 1000);\n}\n\n/**\n * Wait before calling the same function. Useful for expensive calls.\n * Adapted from https://amitd.co/code/typescript/debounce.\n *\n * @return The debounced function.\n *\n * @example\n *\n * ```js\n * const debouncedFunction = debounce(e => {\n * console.log(e);\n * }, 5000);\n *\n * // Console logs 'Hello world again ' after 5 seconds\n * debouncedFunction('Hello world');\n * debouncedFunction('Hello world again');\n * ```\n * @param fn The function to be debounced.\n * @param delayMs Defaults to 5 seconds.\n */\nconst debounce = (fn, delayMs = 5000) => {\n let timer;\n return (...args) => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n fn(...args);\n }, delayMs);\n };\n};\n\nconst isEmptyObject = (obj) => JSON.stringify(obj) === '{}';\n\n/**\n * Strips all falsy and empty {} from a given object. Returns a new object with only truthy values.\n * Sourced from below but modified to include checks for empty object and ignoring keys.\n * https://www.w3resource.com/javascript-exercises/javascript-array-exercise-47.php\n *\n * @param obj\n * @param ignoreKeys\n */\nconst deepCompact = (obj, ignoreKeys) => {\n if (!obj) {\n return obj;\n }\n return Object.entries(obj).reduce((acc, [key, value]) => {\n if (Boolean(value) && !isEmptyObject(value) && !ignoreKeys?.includes(key)) {\n acc[key] = typeof value === 'object' ? deepCompact(value, ignoreKeys) : value;\n }\n return acc;\n }, {});\n};\n\n/* eslint-disable */\n// Ripped from https://github.com/epoberezkin/fast-deep-fastDeepEqual\n// {{? it.es6 }}\n// var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';\n// {{?}}\nfunction fastDeepEqual(a, b) {\n if (a === b)\n return true;\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor)\n return false;\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length)\n return false;\n for (i = length; i-- !== 0;)\n if (!fastDeepEqual(a[i], b[i]))\n return false;\n return true;\n }\n // {{? it.es6 }}\n if (a instanceof Map && b instanceof Map) {\n if (a.size !== b.size)\n return false;\n for (i of a.entries())\n if (!b.has(i[0]))\n return false;\n for (i of a.entries())\n if (!fastDeepEqual(i[1], b.get(i[0])))\n return false;\n return true;\n }\n if (a instanceof Set && b instanceof Set) {\n if (a.size !== b.size)\n return false;\n for (i of a.entries())\n if (!b.has(i[0]))\n return false;\n return true;\n }\n if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {\n // @ts-ignore\n length = a.length;\n // @ts-ignore\n if (length != b.length)\n return false;\n for (i = length; i-- !== 0;) {\n // @ts-ignore\n if (a[i] !== b[i])\n return false;\n }\n return true;\n }\n // {{?}}\n if (a.constructor === RegExp)\n return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf)\n return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString)\n return a.toString() === b.toString();\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length)\n return false;\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i]))\n return false;\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n // {{? it.react }}\n // if (key === '_owner' && a.$$typeof) {\n // // React-specific: avoid traversing React elements' _owner.\n // // _owner contains circular references\n // // and is not needed when comparing the actual elements (and not their owners)\n // continue;\n // }\n // {{?}}\n if (!fastDeepEqual(a[key], b[key]))\n return false;\n }\n return true;\n }\n // true if both NaN, false otherwise\n return a !== a && b !== b;\n}\n\nfunction defaultHeaders(sdkKey, info, tags, includeAuthorizationHeader = true, userAgentHeaderName = 'user-agent') {\n const { userAgentBase, version, wrapperName, wrapperVersion } = info.sdkData();\n const headers = {\n [userAgentHeaderName]: `${userAgentBase ?? 'NodeJSClient'}/${version}`,\n };\n // edge sdks sets this to false because they use the clientSideID\n // and they don't need the authorization header\n if (includeAuthorizationHeader) {\n headers.authorization = sdkKey;\n }\n if (wrapperName) {\n headers['x-launchdarkly-wrapper'] = wrapperVersion\n ? `${wrapperName}/${wrapperVersion}`\n : wrapperName;\n }\n if (tags?.value) {\n headers['x-launchdarkly-tags'] = tags.value;\n }\n return headers;\n}\nfunction httpErrorMessage(err, context, retryMessage) {\n let desc;\n if (err.status) {\n desc = `error ${err.status}${err.status === 401 ? ' (invalid SDK key)' : ''}`;\n }\n else {\n desc = `I/O error (${err.message || 'unknown error'})`;\n }\n const action = retryMessage ?? 'giving up permanently';\n return `Received ${desc} for ${context} - ${action}`;\n}\nfunction shouldRetry({ status }) {\n return status ? isHttpRecoverable(status) : true;\n}\n/**\n * In react-native use base64-js to polyfill btoa. This is safe\n * because the react-native repo uses it too. Set the global.btoa to the encode\n * function of base64-js.\n * https://github.com/beatgammit/base64-js\n * https://github.com/axios/axios/issues/2235#issuecomment-512204616\n *\n * Ripped from https://thewoods.blog/base64url/\n */\nconst base64UrlEncode = (s, encoding) => encoding.btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n\nvar noop = () => { };\n\nconst sleep = async (delayMillis = 1000) => new Promise((resolve) => {\n setTimeout(resolve, delayMillis);\n});\n\n/**\n * Returns a promise which errors after t seconds.\n *\n * @param t Timeout in seconds.\n * @param taskName Name of task being timed for logging and error reporting.\n */\nconst timedPromise = (t, taskName) => new Promise((_res, reject) => {\n setTimeout(() => {\n const e = `${taskName} timed out after ${t} seconds.`;\n reject(new LDTimeoutError(e));\n }, t * 1000);\n});\n\nclass DiagnosticsManager {\n constructor(sdkKey, _platform, _diagnosticInitConfig) {\n this._platform = _platform;\n this._diagnosticInitConfig = _diagnosticInitConfig;\n this._streamInits = [];\n this._startTime = Date.now();\n this._dataSinceDate = this._startTime;\n this._id = {\n diagnosticId: _platform.crypto.randomUUID(),\n sdkKeySuffix: sdkKey.length > 6 ? sdkKey.substring(sdkKey.length - 6) : sdkKey,\n };\n }\n /**\n * Creates the initial event that is sent by the event processor when the SDK starts up. This will\n * not be repeated during the lifetime of the SDK client.\n */\n createInitEvent() {\n const sdkData = this._platform.info.sdkData();\n const platformData = this._platform.info.platformData();\n return {\n kind: 'diagnostic-init',\n id: this._id,\n creationDate: this._startTime,\n sdk: sdkData,\n configuration: this._diagnosticInitConfig,\n platform: {\n name: platformData.name,\n osArch: platformData.os?.arch,\n osName: platformData.os?.name,\n osVersion: platformData.os?.version,\n ...(platformData.additional || {}),\n },\n };\n }\n /**\n * Records a stream connection attempt (called by the stream processor).\n *\n * @param timestamp Time of the *beginning* of the connection attempt.\n * @param failed True if the connection failed, or we got a read timeout before receiving a \"put\".\n * @param durationMillis Elapsed time between starting timestamp and when we either gave up/lost\n * the connection or received a successful \"put\".\n */\n recordStreamInit(timestamp, failed, durationMillis) {\n const item = { timestamp, failed, durationMillis };\n this._streamInits.push(item);\n }\n /**\n * Creates a periodic event containing time-dependent stats, and resets the state of the manager\n * with regard to those stats.\n *\n * Note: the reason droppedEvents, deduplicatedUsers, and eventsInLastBatch are passed into this\n * function, instead of being properties of the DiagnosticsManager, is that the event processor is\n * the one who's calling this function and is also the one who's tracking those stats.\n */\n createStatsEventAndReset(droppedEvents, deduplicatedUsers, eventsInLastBatch) {\n const currentTime = Date.now();\n const evt = {\n kind: 'diagnostic',\n id: this._id,\n creationDate: currentTime,\n dataSinceDate: this._dataSinceDate,\n droppedEvents,\n deduplicatedUsers,\n eventsInLastBatch,\n streamInits: this._streamInits,\n };\n this._streamInits = [];\n this._dataSinceDate = currentTime;\n return evt;\n }\n}\n\n/**\n * Different kinds of error which may be encountered during evaluation.\n */\nvar ErrorKinds;\n(function (ErrorKinds) {\n ErrorKinds[\"MalformedFlag\"] = \"MALFORMED_FLAG\";\n ErrorKinds[\"UserNotSpecified\"] = \"USER_NOT_SPECIFIED\";\n ErrorKinds[\"FlagNotFound\"] = \"FLAG_NOT_FOUND\";\n ErrorKinds[\"ClientNotReady\"] = \"CLIENT_NOT_READY\";\n ErrorKinds[\"WrongType\"] = \"WRONG_TYPE\";\n})(ErrorKinds || (ErrorKinds = {}));\nvar ErrorKinds$1 = ErrorKinds;\n\n/**\n * Messages for issues which can be encountered processing client requests.\n */\nclass ClientMessages {\n static invalidMetricValue(badType) {\n return ('The track function was called with a non-numeric \"metricValue\"' +\n ` (${badType}), only numeric metric values are supported.`);\n }\n}\nClientMessages.MissingContextKeyNoEvent = 'Context was unspecified or had no key; event will not be sent';\n\nclass EventSender {\n constructor(clientContext, baseHeaders) {\n const { basicConfiguration, platform } = clientContext;\n const { serviceEndpoints: { analyticsEventPath, diagnosticEventPath }, } = basicConfiguration;\n const { crypto, requests } = platform;\n this._defaultHeaders = { ...baseHeaders };\n this._eventsUri = getEventsUri(basicConfiguration.serviceEndpoints, analyticsEventPath, []);\n this._diagnosticEventsUri = getEventsUri(basicConfiguration.serviceEndpoints, diagnosticEventPath, []);\n this._requests = requests;\n this._crypto = crypto;\n }\n async _tryPostingEvents(events, uri, payloadId, canRetry) {\n const tryRes = {\n status: LDDeliveryStatus.Succeeded,\n };\n const headers = {\n ...this._defaultHeaders,\n 'content-type': 'application/json',\n };\n if (payloadId) {\n headers['x-launchdarkly-payload-id'] = payloadId;\n headers['x-launchDarkly-event-schema'] = '4';\n }\n let error;\n try {\n const { status, headers: resHeaders } = await this._requests.fetch(uri, {\n headers,\n body: JSON.stringify(events),\n method: 'POST',\n // When sending events from browser environments the request should be completed even\n // if the user is navigating away from the page.\n keepalive: true,\n });\n const serverDate = Date.parse(resHeaders.get('date') || '');\n if (serverDate) {\n tryRes.serverTime = serverDate;\n }\n if (status <= 204) {\n return tryRes;\n }\n error = new LDUnexpectedResponseError(httpErrorMessage({ status, message: 'some events were dropped' }, 'event posting'));\n if (!isHttpRecoverable(status)) {\n // If the HTTP request isn't recoverable. Meaning if we made the same request it\n // would not recover, then we check if a different request could recover.\n // If a different request could not recover, then we shutdown. If a different request could\n // recover, then we just don't retry this specific request.\n if (!isHttpLocallyRecoverable(status)) {\n tryRes.status = LDDeliveryStatus.FailedAndMustShutDown;\n }\n else {\n tryRes.status = LDDeliveryStatus.Failed;\n }\n tryRes.error = error;\n return tryRes;\n }\n }\n catch (err) {\n error = err;\n }\n // recoverable but not retrying\n if (error && !canRetry) {\n tryRes.status = LDDeliveryStatus.Failed;\n tryRes.error = error;\n return tryRes;\n }\n // wait 1 second before retrying\n await sleep();\n return this._tryPostingEvents(events, this._eventsUri, payloadId, false);\n }\n async sendEventData(type, data) {\n const payloadId = type === LDEventType.AnalyticsEvents ? this._crypto.randomUUID() : undefined;\n const uri = type === LDEventType.AnalyticsEvents ? this._eventsUri : this._diagnosticEventsUri;\n return this._tryPostingEvents(data, uri, payloadId, true);\n }\n}\n\nfunction isFeature(u) {\n return u.kind === 'feature';\n}\nfunction isIdentify(u) {\n return u.kind === 'identify';\n}\nfunction isMigration(u) {\n return u.kind === 'migration_op';\n}\n\n/**\n * @internal\n */\nclass SummaryCounter {\n constructor(count, key, value, defValue, version, variation) {\n this.count = count;\n this.key = key;\n this.value = value;\n this.version = version;\n this.variation = variation;\n this.default = defValue;\n }\n increment() {\n this.count += 1;\n }\n}\n\nfunction counterKey(event) {\n return `${event.key}:${event.variation !== null && event.variation !== undefined ? event.variation : ''}:${event.version !== null && event.version !== undefined ? event.version : ''}`;\n}\n/**\n * @internal\n */\nclass EventSummarizer {\n constructor() {\n this._startDate = 0;\n this._endDate = 0;\n this._counters = {};\n this._contextKinds = {};\n }\n summarizeEvent(event) {\n if (isFeature(event) && !event.excludeFromSummaries) {\n const countKey = counterKey(event);\n const counter = this._counters[countKey];\n let kinds = this._contextKinds[event.key];\n if (!kinds) {\n kinds = new Set();\n this._contextKinds[event.key] = kinds;\n }\n event.context.kinds.forEach((kind) => kinds.add(kind));\n if (counter) {\n counter.increment();\n }\n else {\n this._counters[countKey] = new SummaryCounter(1, event.key, event.value, event.default, event.version, event.variation);\n }\n if (this._startDate === 0 || event.creationDate < this._startDate) {\n this._startDate = event.creationDate;\n }\n if (event.creationDate > this._endDate) {\n this._endDate = event.creationDate;\n }\n }\n }\n getSummary() {\n const features = Object.values(this._counters).reduce((acc, counter) => {\n let flagSummary = acc[counter.key];\n if (!flagSummary) {\n flagSummary = {\n default: counter.default,\n counters: [],\n contextKinds: [...this._contextKinds[counter.key]],\n };\n acc[counter.key] = flagSummary;\n }\n const counterOut = {\n value: counter.value,\n count: counter.count,\n };\n if (counter.variation !== undefined && counter.variation !== null) {\n counterOut.variation = counter.variation;\n }\n if (counter.version !== undefined && counter.version !== null) {\n counterOut.version = counter.version;\n }\n else {\n counterOut.unknown = true;\n }\n flagSummary.counters.push(counterOut);\n return acc;\n }, {});\n return {\n startDate: this._startDate,\n endDate: this._endDate,\n features,\n kind: 'summary',\n };\n }\n clearSummary() {\n this._startDate = 0;\n this._endDate = 0;\n this._counters = {};\n this._contextKinds = {};\n }\n}\n\nclass LDInvalidSDKKeyError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyInvalidSDKKeyError';\n }\n}\n\n/**\n * The contents of this file are for event sampling. They are not used for\n * any purpose requiring cryptographic security.\n * */\nfunction shouldSample(ratio) {\n const truncated = Math.trunc(ratio);\n // A radio of 1 means 1 in 1. So that will always sample. No need\n // to draw a random number.\n if (truncated === 1) {\n return true;\n }\n if (truncated === 0) {\n return false;\n }\n // Math.random() * truncated) would return 0, 1, ... (ratio - 1).\n // Checking for any number in the range will have approximately a 1 in X\n // chance. So we check for 0 as it is part of any range.\n return Math.floor(Math.random() * truncated) === 0;\n}\n\nclass EventProcessor {\n constructor(_config, clientContext, baseHeaders, _contextDeduplicator, _diagnosticsManager, start = true) {\n this._config = _config;\n this._contextDeduplicator = _contextDeduplicator;\n this._diagnosticsManager = _diagnosticsManager;\n this._summarizer = new EventSummarizer();\n this._queue = [];\n this._lastKnownPastTime = 0;\n this._droppedEvents = 0;\n this._deduplicatedUsers = 0;\n this._exceededCapacity = false;\n this._eventsInLastBatch = 0;\n this._shutdown = false;\n this._flushUsersTimer = null;\n this._capacity = _config.eventsCapacity;\n this._logger = clientContext.basicConfiguration.logger;\n this._eventSender = new EventSender(clientContext, baseHeaders);\n this._contextFilter = new ContextFilter(_config.allAttributesPrivate, _config.privateAttributes.map((ref) => new AttributeReference(ref)));\n if (start) {\n this.start();\n }\n }\n start() {\n if (this._contextDeduplicator?.flushInterval !== undefined) {\n this._flushUsersTimer = setInterval(() => {\n this._contextDeduplicator?.flush();\n }, this._contextDeduplicator.flushInterval * 1000);\n }\n this._flushTimer = setInterval(async () => {\n try {\n await this.flush();\n }\n catch (e) {\n // Log errors and swallow them\n this._logger?.debug(`Flush failed: ${e}`);\n }\n }, this._config.flushInterval * 1000);\n if (this._diagnosticsManager) {\n const initEvent = this._diagnosticsManager.createInitEvent();\n this._postDiagnosticEvent(initEvent);\n this._diagnosticsTimer = setInterval(() => {\n const statsEvent = this._diagnosticsManager.createStatsEventAndReset(this._droppedEvents, this._deduplicatedUsers, this._eventsInLastBatch);\n this._droppedEvents = 0;\n this._deduplicatedUsers = 0;\n this._postDiagnosticEvent(statsEvent);\n }, this._config.diagnosticRecordingInterval * 1000);\n }\n this._logger?.debug('Started EventProcessor.');\n }\n _postDiagnosticEvent(event) {\n this._eventSender.sendEventData(LDEventType.DiagnosticEvent, event);\n }\n close() {\n clearInterval(this._flushTimer);\n if (this._flushUsersTimer) {\n clearInterval(this._flushUsersTimer);\n }\n if (this._diagnosticsTimer) {\n clearInterval(this._diagnosticsTimer);\n }\n }\n async flush() {\n if (this._shutdown) {\n throw new LDInvalidSDKKeyError('Events cannot be posted because a permanent error has been encountered. ' +\n 'This is most likely an invalid SDK key. The specific error information ' +\n 'is logged independently.');\n }\n const eventsToFlush = this._queue;\n this._queue = [];\n const summary = this._summarizer.getSummary();\n this._summarizer.clearSummary();\n if (Object.keys(summary.features).length) {\n eventsToFlush.push(summary);\n }\n if (!eventsToFlush.length) {\n return;\n }\n this._eventsInLastBatch = eventsToFlush.length;\n this._logger?.debug('Flushing %d events', eventsToFlush.length);\n await this._tryPostingEvents(eventsToFlush);\n }\n sendEvent(inputEvent) {\n if (this._shutdown) {\n return;\n }\n if (isMigration(inputEvent)) {\n // These conditions are not combined, because we always want to stop\n // processing at this point for a migration event. It cannot generate\n // an index event or debug event.\n if (shouldSample(inputEvent.samplingRatio)) {\n const migrationEvent = {\n ...inputEvent,\n };\n if (migrationEvent.samplingRatio === 1) {\n delete migrationEvent.samplingRatio;\n }\n this._enqueue(migrationEvent);\n }\n return;\n }\n this._summarizer.summarizeEvent(inputEvent);\n const isFeatureEvent = isFeature(inputEvent);\n const addFullEvent = (isFeatureEvent && inputEvent.trackEvents) || !isFeatureEvent;\n const addDebugEvent = this._shouldDebugEvent(inputEvent);\n const isIdentifyEvent = isIdentify(inputEvent);\n const shouldNotDeduplicate = this._contextDeduplicator?.processContext(inputEvent.context);\n // If there is no cache, then it will never be in the cache.\n if (!shouldNotDeduplicate) {\n if (!isIdentifyEvent) {\n this._deduplicatedUsers += 1;\n }\n }\n const addIndexEvent = shouldNotDeduplicate && !isIdentifyEvent;\n if (addIndexEvent) {\n this._enqueue(this._makeOutputEvent({\n kind: 'index',\n creationDate: inputEvent.creationDate,\n context: inputEvent.context,\n samplingRatio: 1,\n }, false));\n }\n if (addFullEvent && shouldSample(inputEvent.samplingRatio)) {\n this._enqueue(this._makeOutputEvent(inputEvent, false));\n }\n if (addDebugEvent && shouldSample(inputEvent.samplingRatio)) {\n this._enqueue(this._makeOutputEvent(inputEvent, true));\n }\n }\n _makeOutputEvent(event, debug) {\n switch (event.kind) {\n case 'feature': {\n const out = {\n kind: debug ? 'debug' : 'feature',\n creationDate: event.creationDate,\n context: this._contextFilter.filter(event.context, !debug),\n key: event.key,\n value: event.value,\n default: event.default,\n };\n if (event.samplingRatio !== 1) {\n out.samplingRatio = event.samplingRatio;\n }\n if (event.prereqOf) {\n out.prereqOf = event.prereqOf;\n }\n if (event.variation !== undefined) {\n out.variation = event.variation;\n }\n if (event.version !== undefined) {\n out.version = event.version;\n }\n if (event.reason) {\n out.reason = event.reason;\n }\n return out;\n }\n case 'index': // Intentional fallthrough.\n case 'identify': {\n const out = {\n kind: event.kind,\n creationDate: event.creationDate,\n context: this._contextFilter.filter(event.context),\n };\n if (event.samplingRatio !== 1) {\n out.samplingRatio = event.samplingRatio;\n }\n return out;\n }\n case 'custom': {\n const out = {\n kind: 'custom',\n creationDate: event.creationDate,\n key: event.key,\n contextKeys: event.context.kindsAndKeys,\n };\n if (event.samplingRatio !== 1) {\n out.samplingRatio = event.samplingRatio;\n }\n if (event.data !== undefined) {\n out.data = event.data;\n }\n if (event.metricValue !== undefined) {\n out.metricValue = event.metricValue;\n }\n if (event.url !== undefined) {\n out.url = event.url;\n }\n return out;\n }\n case 'click': {\n const out = {\n kind: 'click',\n creationDate: event.creationDate,\n contextKeys: event.context.kindsAndKeys,\n key: event.key,\n url: event.url,\n selector: event.selector,\n };\n return out;\n }\n case 'pageview': {\n const out = {\n kind: 'pageview',\n creationDate: event.creationDate,\n contextKeys: event.context.kindsAndKeys,\n key: event.key,\n url: event.url,\n };\n return out;\n }\n default:\n // This would happen during the addition of a new event type to the SDK.\n return event;\n }\n }\n _enqueue(event) {\n if (this._queue.length < this._capacity) {\n this._queue.push(event);\n this._exceededCapacity = false;\n }\n else {\n if (!this._exceededCapacity) {\n this._exceededCapacity = true;\n this._logger?.warn('Exceeded event queue capacity. Increase capacity to avoid dropping events.');\n }\n this._droppedEvents += 1;\n }\n }\n _shouldDebugEvent(event) {\n return (isFeature(event) &&\n event.debugEventsUntilDate &&\n event.debugEventsUntilDate > this._lastKnownPastTime &&\n event.debugEventsUntilDate > Date.now());\n }\n async _tryPostingEvents(events) {\n const res = await this._eventSender.sendEventData(LDEventType.AnalyticsEvents, events);\n if (res.status === LDDeliveryStatus.FailedAndMustShutDown) {\n this._shutdown = true;\n }\n if (res.serverTime) {\n this._lastKnownPastTime = res.serverTime;\n }\n if (res.error) {\n throw res.error;\n }\n }\n}\n\nclass InputCustomEvent {\n constructor(context, key, data, metricValue, \n // Currently custom events are not sampled, but this is here to make the handling\n // code more uniform.\n samplingRatio = 1, \n // Browser SDKs can include a URL for custom events.\n url) {\n this.context = context;\n this.key = key;\n this.data = data;\n this.metricValue = metricValue;\n this.samplingRatio = samplingRatio;\n this.url = url;\n this.kind = 'custom';\n this.creationDate = Date.now();\n this.context = context;\n }\n}\n\nclass InputEvalEvent {\n constructor(withReasons, context, key, value, defValue, // default is a reserved keyword in this context.\n version, variation, trackEvents, prereqOf, reason, debugEventsUntilDate, excludeFromSummaries, samplingRatio = 1) {\n this.withReasons = withReasons;\n this.context = context;\n this.key = key;\n this.samplingRatio = samplingRatio;\n this.kind = 'feature';\n this.creationDate = Date.now();\n this.value = value;\n this.default = defValue;\n if (version !== undefined) {\n this.version = version;\n }\n if (variation !== undefined) {\n this.variation = variation;\n }\n if (trackEvents !== undefined) {\n this.trackEvents = trackEvents;\n }\n if (prereqOf !== undefined) {\n this.prereqOf = prereqOf;\n }\n if (reason !== undefined) {\n this.reason = reason;\n }\n if (debugEventsUntilDate !== undefined) {\n this.debugEventsUntilDate = debugEventsUntilDate;\n }\n if (excludeFromSummaries !== undefined) {\n this.excludeFromSummaries = excludeFromSummaries;\n }\n }\n}\n\nclass InputIdentifyEvent {\n constructor(context, samplingRatio = 1) {\n this.context = context;\n this.samplingRatio = samplingRatio;\n this.kind = 'identify';\n this.creationDate = Date.now();\n }\n}\n\nclass NullEventProcessor {\n close() { }\n async flush() {\n // empty comment to keep ts and eslint happy\n }\n sendEvent() { }\n}\n\nclass EventFactoryBase {\n constructor(_withReasons) {\n this._withReasons = _withReasons;\n }\n evalEvent(e) {\n return new InputEvalEvent(this._withReasons, e.context, e.flagKey, e.value, e.defaultVal, e.version, \n // Exclude null as a possibility.\n e.variation ?? undefined, e.trackEvents || e.addExperimentData, e.prereqOfFlagKey, this._withReasons || e.addExperimentData ? e.reason : undefined, e.debugEventsUntilDate, e.excludeFromSummaries, e.samplingRatio);\n }\n unknownFlagEvent(key, defVal, context) {\n return new InputEvalEvent(this._withReasons, context, key, defVal, defVal, \n // This isn't ideal, but the purpose of the factory is to at least\n // handle this situation.\n undefined, // version\n undefined, // variation index\n undefined, // track events\n undefined, // prereqOf\n undefined, // reason\n undefined, // debugEventsUntilDate\n undefined, // exclude from summaries\n undefined);\n }\n /* eslint-disable-next-line class-methods-use-this */\n identifyEvent(context) {\n // Currently sampling for identify events is always 1.\n return new InputIdentifyEvent(context, 1);\n }\n /* eslint-disable-next-line class-methods-use-this */\n customEvent(key, context, data, metricValue, samplingRatio = 1) {\n return new InputCustomEvent(context, key, data ?? undefined, metricValue ?? undefined, samplingRatio);\n }\n}\n\nconst reportJsonError = (type, data, logger, errorHandler) => {\n logger?.error(`Stream received invalid data in \"${type}\" message`);\n logger?.debug(`Invalid JSON follows: ${data}`);\n errorHandler?.(new LDStreamingError(DataSourceErrorKind.InvalidData, 'Malformed JSON data in event stream'));\n};\n// TODO: SDK-156 - Move to Server SDK specific location\nclass StreamingProcessor {\n constructor(clientContext, streamUriPath, parameters, _listeners, baseHeaders, _diagnosticsManager, _errorHandler, _streamInitialReconnectDelay = 1) {\n this._listeners = _listeners;\n this._diagnosticsManager = _diagnosticsManager;\n this._errorHandler = _errorHandler;\n this._streamInitialReconnectDelay = _streamInitialReconnectDelay;\n const { basicConfiguration, platform } = clientContext;\n const { logger } = basicConfiguration;\n const { requests } = platform;\n this._headers = { ...baseHeaders };\n this._logger = logger;\n this._requests = requests;\n this._streamUri = getStreamingUri(basicConfiguration.serviceEndpoints, streamUriPath, parameters);\n }\n _logConnectionStarted() {\n this._connectionAttemptStartTime = Date.now();\n }\n _logConnectionResult(success) {\n if (this._connectionAttemptStartTime && this._diagnosticsManager) {\n this._diagnosticsManager.recordStreamInit(this._connectionAttemptStartTime, !success, Date.now() - this._connectionAttemptStartTime);\n }\n this._connectionAttemptStartTime = undefined;\n }\n /**\n * This is a wrapper around the passed errorHandler which adds additional\n * diagnostics and logging logic.\n *\n * @param err The error to be logged and handled.\n * @return boolean whether to retry the connection.\n *\n * @private\n */\n _retryAndHandleError(err) {\n if (!shouldRetry(err)) {\n this._logConnectionResult(false);\n this._errorHandler?.(new LDStreamingError(DataSourceErrorKind.ErrorResponse, err.message, err.status));\n this._logger?.error(httpErrorMessage(err, 'streaming request'));\n return false;\n }\n this._logger?.warn(httpErrorMessage(err, 'streaming request', 'will retry'));\n this._logConnectionResult(false);\n this._logConnectionStarted();\n return true;\n }\n start() {\n this._logConnectionStarted();\n // TLS is handled by the platform implementation.\n const eventSource = this._requests.createEventSource(this._streamUri, {\n headers: this._headers,\n errorFilter: (error) => this._retryAndHandleError(error),\n initialRetryDelayMillis: 1000 * this._streamInitialReconnectDelay,\n readTimeoutMillis: 5 * 60 * 1000,\n retryResetIntervalMillis: 60 * 1000,\n });\n this._eventSource = eventSource;\n eventSource.onclose = () => {\n this._logger?.info('Closed LaunchDarkly stream connection');\n };\n eventSource.onerror = () => {\n // The work is done by `errorFilter`.\n };\n eventSource.onopen = () => {\n this._logger?.info('Opened LaunchDarkly stream connection');\n };\n eventSource.onretrying = (e) => {\n this._logger?.info(`Will retry stream connection in ${e.delayMillis} milliseconds`);\n };\n this._listeners.forEach(({ deserializeData, processJson }, eventName) => {\n eventSource.addEventListener(eventName, (event) => {\n this._logger?.debug(`Received ${eventName} event`);\n if (event?.data) {\n this._logConnectionResult(true);\n const { data } = event;\n const dataJson = deserializeData(data);\n if (!dataJson) {\n reportJsonError(eventName, data, this._logger, this._errorHandler);\n return;\n }\n processJson(dataJson);\n }\n else {\n this._errorHandler?.(new LDStreamingError(DataSourceErrorKind.Unknown, 'Unexpected payload from event stream'));\n }\n });\n });\n }\n stop() {\n this._eventSource?.close();\n this._eventSource = undefined;\n }\n close() {\n this.stop();\n }\n}\n\nvar index = /*#__PURE__*/Object.freeze({\n __proto__: null,\n ClientMessages: ClientMessages,\n DiagnosticsManager: DiagnosticsManager,\n ErrorKinds: ErrorKinds$1,\n EventFactoryBase: EventFactoryBase,\n EventProcessor: EventProcessor,\n InputCustomEvent: InputCustomEvent,\n InputEvalEvent: InputEvalEvent,\n InputIdentifyEvent: InputIdentifyEvent,\n NullEventProcessor: NullEventProcessor,\n StreamingProcessor: StreamingProcessor,\n isLegacyUser: isLegacyUser,\n isMultiKind: isMultiKind,\n isSingleKind: isSingleKind,\n shouldSample: shouldSample\n});\n\nexport { ApplicationTags, AttributeReference, AutoEnvAttributes, BasicLogger, ClientContext, Context, ContextFilter, DataSourceErrorKind, DateValidator, FactoryOrInstance, Function, KindValidator, LDClientError, LDFileDataSourceError, LDPollingError, LDStreamingError, LDTimeoutError, LDUnexpectedResponseError, NullableBoolean, NumberWithMinimum, OptionMessages, SafeLogger, ServiceEndpoints, StringMatchingRegex, Type, TypeArray, TypeValidators, base64UrlEncode, cancelableTimedPromise, clone, createSafeLogger, debounce, deepCompact, defaultHeaders, fastDeepEqual, getEventsUri, getPollingUri, getStreamingUri, httpErrorMessage, index as internal, isHttpLocallyRecoverable, isHttpRecoverable, noop, secondsToMillis, shouldRetry, sleep, index$1 as subsystem, timedPromise };\n//# sourceMappingURL=index.mjs.map\n","import { getPollingUri, TypeValidators, createSafeLogger, ServiceEndpoints, ApplicationTags, OptionMessages, NumberWithMinimum, SafeLogger, internal, deepCompact, clone, secondsToMillis, ClientContext, fastDeepEqual, defaultHeaders, Context, timedPromise, AutoEnvAttributes, LDClientError, isHttpRecoverable, httpErrorMessage, LDPollingError, DataSourceErrorKind, getStreamingUri, shouldRetry, LDStreamingError } from '@launchdarkly/js-sdk-common';\nexport * from '@launchdarkly/js-sdk-common';\nimport * as jsSdkCommon from '@launchdarkly/js-sdk-common';\nexport { jsSdkCommon as platform };\n\nvar DataSourceState;\n(function (DataSourceState) {\n DataSourceState[\"Initializing\"] = \"INITIALIZING\";\n DataSourceState[\"Valid\"] = \"VALID\";\n DataSourceState[\"Interrupted\"] = \"INTERRUPTED\";\n DataSourceState[\"SetOffline\"] = \"SET_OFFLINE\";\n DataSourceState[\"Closed\"] = \"CLOSED\";\n // TODO: SDK-702 - Implement network availability behaviors\n // NetworkUnavailable,\n})(DataSourceState || (DataSourceState = {}));\n\n// eslint-disable-next-line max-classes-per-file\nfunction isOk(status) {\n return status >= 200 && status <= 299;\n}\nclass LDRequestError extends Error {\n constructor(message, status) {\n super(message);\n this.status = status;\n this.name = 'LaunchDarklyRequestError';\n }\n}\n/**\n * Note: The requestor is implemented independently from polling such that it can be used to\n * make a one-off request.\n */\nclass Requestor {\n constructor(_requests, _uri, _headers, _method, _body) {\n this._requests = _requests;\n this._uri = _uri;\n this._headers = _headers;\n this._method = _method;\n this._body = _body;\n }\n async requestPayload() {\n let status;\n try {\n const res = await this._requests.fetch(this._uri, {\n method: this._method,\n headers: this._headers,\n body: this._body,\n });\n if (isOk(res.status)) {\n return await res.text();\n }\n // Assigning so it can be thrown after the try/catch.\n status = res.status;\n }\n catch (err) {\n throw new LDRequestError(err?.message);\n }\n throw new LDRequestError(`Unexpected status code: ${status}`, status);\n }\n}\nfunction makeRequestor(plainContextString, serviceEndpoints, paths, requests, encoding, baseHeaders, baseQueryParams, withReasons, useReport, secureModeHash) {\n let body;\n let method = 'GET';\n const headers = { ...baseHeaders };\n if (useReport) {\n method = 'REPORT';\n headers['content-type'] = 'application/json';\n body = plainContextString; // context is in body for REPORT\n }\n const path = useReport\n ? paths.pathReport(encoding, plainContextString)\n : paths.pathGet(encoding, plainContextString);\n const parameters = [...(baseQueryParams ?? [])];\n if (withReasons) {\n parameters.push({ key: 'withReasons', value: 'true' });\n }\n if (secureModeHash) {\n parameters.push({ key: 'h', value: secureModeHash });\n }\n const uri = getPollingUri(serviceEndpoints, path, parameters);\n return new Requestor(requests, uri, headers, method, body);\n}\n\n// eslint-disable-next-line max-classes-per-file\nconst validators = {\n logger: TypeValidators.Object,\n maxCachedContexts: TypeValidators.numberWithMin(0),\n baseUri: TypeValidators.String,\n streamUri: TypeValidators.String,\n eventsUri: TypeValidators.String,\n capacity: TypeValidators.numberWithMin(1),\n diagnosticRecordingInterval: TypeValidators.numberWithMin(2),\n flushInterval: TypeValidators.numberWithMin(2),\n streamInitialReconnectDelay: TypeValidators.numberWithMin(0),\n allAttributesPrivate: TypeValidators.Boolean,\n debug: TypeValidators.Boolean,\n diagnosticOptOut: TypeValidators.Boolean,\n withReasons: TypeValidators.Boolean,\n sendEvents: TypeValidators.Boolean,\n pollInterval: TypeValidators.numberWithMin(30),\n useReport: TypeValidators.Boolean,\n privateAttributes: TypeValidators.StringArray,\n applicationInfo: TypeValidators.Object,\n wrapperName: TypeValidators.String,\n wrapperVersion: TypeValidators.String,\n payloadFilterKey: TypeValidators.stringMatchingRegex(/^[a-zA-Z0-9](\\w|\\.|-)*$/),\n hooks: TypeValidators.createTypeArray('Hook[]', {}),\n inspectors: TypeValidators.createTypeArray('LDInspection', {}),\n};\n\nconst DEFAULT_POLLING_INTERVAL = 60 * 5;\nconst DEFAULT_POLLING = 'https://clientsdk.launchdarkly.com';\nconst DEFAULT_STREAM = 'https://clientstream.launchdarkly.com';\nfunction ensureSafeLogger(logger) {\n if (logger instanceof SafeLogger) {\n return logger;\n }\n // Even if logger is not defined this will produce a valid logger.\n return createSafeLogger(logger);\n}\nclass ConfigurationImpl {\n constructor(pristineOptions = {}, internalOptions = {}) {\n this.logger = createSafeLogger();\n // Naming conventions is not followed for these lines because the config validation\n // accesses members based on the keys of the options. (sdk-763)\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.baseUri = DEFAULT_POLLING;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.eventsUri = ServiceEndpoints.DEFAULT_EVENTS;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.streamUri = DEFAULT_STREAM;\n this.maxCachedContexts = 5;\n this.capacity = 100;\n this.diagnosticRecordingInterval = 900;\n this.flushInterval = 30;\n this.streamInitialReconnectDelay = 1;\n this.allAttributesPrivate = false;\n this.debug = false;\n this.diagnosticOptOut = false;\n this.sendEvents = true;\n this.sendLDHeaders = true;\n this.useReport = false;\n this.withReasons = false;\n this.privateAttributes = [];\n this.pollInterval = DEFAULT_POLLING_INTERVAL;\n this.hooks = [];\n this.inspectors = [];\n this.logger = ensureSafeLogger(pristineOptions.logger);\n const errors = this._validateTypesAndNames(pristineOptions);\n errors.forEach((e) => this.logger.warn(e));\n this.serviceEndpoints = new ServiceEndpoints(this.streamUri, this.baseUri, this.eventsUri, internalOptions.analyticsEventPath, internalOptions.diagnosticEventPath, internalOptions.includeAuthorizationHeader, pristineOptions.payloadFilterKey);\n this.useReport = pristineOptions.useReport ?? false;\n this.tags = new ApplicationTags({ application: this.applicationInfo, logger: this.logger });\n this.userAgentHeaderName = internalOptions.userAgentHeaderName ?? 'user-agent';\n this.trackEventModifier = internalOptions.trackEventModifier ?? ((event) => event);\n }\n _validateTypesAndNames(pristineOptions) {\n const errors = [];\n Object.entries(pristineOptions).forEach(([k, v]) => {\n const validator = validators[k];\n if (validator) {\n if (!validator.is(v)) {\n const validatorType = validator.getType();\n if (validatorType === 'boolean') {\n errors.push(OptionMessages.wrongOptionTypeBoolean(k, typeof v));\n this[k] = !!v;\n }\n else if (validatorType === 'boolean | undefined | null') {\n errors.push(OptionMessages.wrongOptionTypeBoolean(k, typeof v));\n if (typeof v !== 'boolean' && typeof v !== 'undefined' && v !== null) {\n this[k] = !!v;\n }\n }\n else if (validator instanceof NumberWithMinimum && TypeValidators.Number.is(v)) {\n const { min } = validator;\n errors.push(OptionMessages.optionBelowMinimum(k, v, min));\n this[k] = min;\n }\n else {\n errors.push(OptionMessages.wrongOptionType(k, validator.getType(), typeof v));\n }\n }\n else if (k === 'logger') ;\n else {\n // if an option is explicitly null, coerce to undefined\n this[k] = v ?? undefined;\n }\n }\n else {\n errors.push(OptionMessages.unknownOption(k));\n }\n });\n return errors;\n }\n}\n\nasync function digest(hasher, encoding) {\n if (hasher.digest) {\n return hasher.digest(encoding);\n }\n if (hasher.asyncDigest) {\n return hasher.asyncDigest(encoding);\n }\n // This represents an error in platform implementation.\n throw new Error('Platform must implement digest or asyncDigest');\n}\n\n/**\n * This function will retrieve a previously generated key for the given {@link storageKey} if it\n * exists or generate and store one on the fly if it does not already exist.\n * @param storageKey keyed storage location where the generated key should live. See {@link namespaceForGeneratedContextKey}\n * for related exmaples of generating a storage key and usage.\n * @param platform crypto and storage implementations for necessary operations\n * @returns the generated key\n */\nconst getOrGenerateKey = async (storageKey, { crypto, storage }) => {\n let generatedKey = await storage?.get(storageKey);\n if (!generatedKey) {\n generatedKey = crypto.randomUUID();\n await storage?.set(storageKey, generatedKey);\n }\n return generatedKey;\n};\n\n/**\n * Hashes the input and encodes it as base64\n */\nfunction hashAndBase64Encode(crypto) {\n return async (input) => digest(crypto.createHash('sha256').update(input), 'base64');\n}\nconst noop = async (input) => input; // no-op transform\nasync function concatNamespacesAndValues(parts) {\n const processedParts = await Promise.all(parts.map((part) => part.transform(part.value))); // use the transform from each part to transform the value\n return processedParts.join('_');\n}\nasync function namespaceForEnvironment(crypto, sdkKey) {\n return concatNamespacesAndValues([\n { value: 'LaunchDarkly', transform: noop },\n { value: sdkKey, transform: hashAndBase64Encode(crypto) }, // hash sdk key and encode it\n ]);\n}\n/**\n * @deprecated prefer {@link namespaceForGeneratedContextKey}. At one time we only generated keys for\n * anonymous contexts and they were namespaced in LaunchDarkly_AnonymousKeys. Eventually we started\n * generating context keys for non-anonymous contexts such as for the Auto Environment Attributes\n * feature and those were namespaced in LaunchDarkly_ContextKeys. This function can be removed\n * when the data under the LaunchDarkly_AnonymousKeys namespace is merged with data under the\n * LaunchDarkly_ContextKeys namespace.\n */\nasync function namespaceForAnonymousGeneratedContextKey(kind) {\n return concatNamespacesAndValues([\n { value: 'LaunchDarkly', transform: noop },\n { value: 'AnonymousKeys', transform: noop },\n { value: kind, transform: noop }, // existing SDKs are not hashing or encoding this kind, though they should have\n ]);\n}\nasync function namespaceForGeneratedContextKey(kind) {\n return concatNamespacesAndValues([\n { value: 'LaunchDarkly', transform: noop },\n { value: 'ContextKeys', transform: noop },\n { value: kind, transform: noop }, // existing SDKs are not hashing or encoding this kind, though they should have\n ]);\n}\nasync function namespaceForContextIndex(environmentNamespace) {\n return concatNamespacesAndValues([\n { value: environmentNamespace, transform: noop },\n { value: 'ContextIndex', transform: noop },\n ]);\n}\nasync function namespaceForContextData(crypto, environmentNamespace, context) {\n return concatNamespacesAndValues([\n { value: environmentNamespace, transform: noop },\n { value: context.canonicalKey, transform: hashAndBase64Encode(crypto) }, // hash and encode canonical key\n ]);\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nconst { isLegacyUser: isLegacyUser$1, isSingleKind: isSingleKind$1, isMultiKind: isMultiKind$1 } = internal;\nconst defaultAutoEnvSchemaVersion = '1.0';\nconst toMulti = (c) => {\n const { kind, ...contextCommon } = c;\n return {\n kind: 'multi',\n [kind]: contextCommon,\n };\n};\n/**\n * Clones the LDApplication object and populates the key, envAttributesVersion, id and version fields.\n *\n * @param crypto\n * @param info\n * @param applicationInfo\n * @param config\n * @return An LDApplication object with populated key, envAttributesVersion, id and version.\n */\nconst addApplicationInfo = async ({ crypto, info }, { applicationInfo }) => {\n const { ld_application } = info.platformData();\n let app = deepCompact(ld_application) ?? {};\n const id = applicationInfo?.id || app?.id;\n if (id) {\n const version = applicationInfo?.version || app?.version;\n const name = applicationInfo?.name || app?.name;\n const versionName = applicationInfo?.versionName || app?.versionName;\n app = {\n ...app,\n id,\n // only add props if they are defined\n ...(version ? { version } : {}),\n ...(name ? { name } : {}),\n ...(versionName ? { versionName } : {}),\n };\n app.key = await digest(crypto.createHash('sha256').update(id), 'base64');\n app.envAttributesVersion = app.envAttributesVersion || defaultAutoEnvSchemaVersion;\n return app;\n }\n return undefined;\n};\n/**\n * Clones the LDDevice object and populates the key and envAttributesVersion field.\n *\n * @param platform\n * @return An LDDevice object with populated key and envAttributesVersion.\n */\nconst addDeviceInfo = async (platform) => {\n const { ld_device, os } = platform.info.platformData();\n const device = deepCompact(ld_device) ?? {};\n const name = os?.name || device.os?.name;\n const version = os?.version || device.os?.version;\n const family = device.os?.family;\n // only add device.os if there's data\n if (name || version || family) {\n device.os = {\n // only add props if they are defined\n ...(name ? { name } : {}),\n ...(version ? { version } : {}),\n ...(family ? { family } : {}),\n };\n }\n // Check if device has any meaningful data before we return it.\n if (Object.keys(device).filter((k) => k !== 'key' && k !== 'envAttributesVersion').length) {\n const ldDeviceNamespace = await namespaceForGeneratedContextKey('ld_device');\n device.key = await getOrGenerateKey(ldDeviceNamespace, platform);\n device.envAttributesVersion = device.envAttributesVersion || defaultAutoEnvSchemaVersion;\n return device;\n }\n return undefined;\n};\nconst addAutoEnv = async (context, platform, config) => {\n // LDUser is not supported for auto env reporting\n if (isLegacyUser$1(context)) {\n return context;\n }\n let ld_application;\n let ld_device;\n // Check if customer contexts exist. Only override if they are not provided.\n if ((isSingleKind$1(context) && context.kind !== 'ld_application') ||\n (isMultiKind$1(context) && !context.ld_application)) {\n ld_application = await addApplicationInfo(platform, config);\n }\n else {\n config.logger.warn('Not adding ld_application environment attributes because it already exists.');\n }\n if ((isSingleKind$1(context) && context.kind !== 'ld_device') ||\n (isMultiKind$1(context) && !context.ld_device)) {\n ld_device = await addDeviceInfo(platform);\n }\n else {\n config.logger.warn('Not adding ld_device environment attributes because it already exists.');\n }\n // Unable to automatically add environment attributes for kind: {}. {} already exists.\n if (ld_application || ld_device) {\n const multi = isSingleKind$1(context) ? toMulti(context) : context;\n return {\n ...multi,\n ...(ld_application ? { ld_application } : {}),\n ...(ld_device ? { ld_device } : {}),\n };\n }\n return context;\n};\n\nconst { isLegacyUser, isMultiKind, isSingleKind } = internal;\n/**\n * This is the root ensureKey function. All other ensureKey functions reduce to this.\n *\n * - ensureKeyCommon // private root function\n * - ensureKeySingle\n * - ensureKeyMulti\n * - ensureKeyLegacy\n * - ensureKey // exported for external use\n *\n * @param kind The LDContext kind\n * @param c The LDContext object\n * @param platform Platform containing crypto and storage needed for storing and querying keys.\n */\nconst ensureKeyCommon = async (kind, c, platform) => {\n const { anonymous, key } = c;\n if (anonymous && !key) {\n const storageKey = await namespaceForAnonymousGeneratedContextKey(kind);\n // This mutates a cloned copy of the original context from ensureyKey so this is safe.\n // eslint-disable-next-line no-param-reassign\n c.key = await getOrGenerateKey(storageKey, platform);\n }\n};\nconst ensureKeySingle = async (c, platform) => {\n await ensureKeyCommon(c.kind, c, platform);\n};\nconst ensureKeyMulti = async (multiContext, platform) => {\n const { kind, ...singleContexts } = multiContext;\n return Promise.all(Object.entries(singleContexts).map(([k, c]) => ensureKeyCommon(k, c, platform)));\n};\nconst ensureKeyLegacy = async (c, platform) => {\n await ensureKeyCommon('user', c, platform);\n};\n/**\n * Ensure a key is always present in anonymous contexts. Non-anonymous contexts\n * are not processed and will just be returned as is.\n *\n * @param context\n * @param platform\n */\nconst ensureKey = async (context, platform) => {\n const cloned = clone(context);\n if (isSingleKind(cloned)) {\n await ensureKeySingle(cloned, platform);\n }\n if (isMultiKind(cloned)) {\n await ensureKeyMulti(cloned, platform);\n }\n if (isLegacyUser(cloned)) {\n await ensureKeyLegacy(cloned, platform);\n }\n return cloned;\n};\n\nconst createDiagnosticsInitConfig = (config) => ({\n customBaseURI: config.serviceEndpoints.polling !== DEFAULT_POLLING,\n customStreamURI: config.serviceEndpoints.streaming !== DEFAULT_STREAM,\n customEventsURI: config.serviceEndpoints.events !== ServiceEndpoints.DEFAULT_EVENTS,\n eventsCapacity: config.capacity,\n eventsFlushIntervalMillis: secondsToMillis(config.flushInterval),\n reconnectTimeMillis: secondsToMillis(config.streamInitialReconnectDelay),\n diagnosticRecordingIntervalMillis: secondsToMillis(config.diagnosticRecordingInterval),\n allAttributesPrivate: config.allAttributesPrivate,\n // TODO: Implement when corresponding features are implemented.\n usingSecureMode: false,\n bootstrapMode: false,\n});\n\nconst createDiagnosticsManager = (clientSideID, config, platform) => {\n if (config.sendEvents && !config.diagnosticOptOut) {\n return new internal.DiagnosticsManager(clientSideID, platform, createDiagnosticsInitConfig(config));\n }\n return undefined;\n};\n\nfunction createErrorEvaluationDetail(errorKind, def) {\n return {\n value: def ?? null,\n variationIndex: null,\n reason: { kind: 'ERROR', errorKind },\n };\n}\nfunction createSuccessEvaluationDetail(value, variationIndex, reason) {\n const res = {\n value,\n variationIndex: variationIndex ?? null,\n reason: reason ?? null,\n };\n return res;\n}\n\nconst createEventProcessor = (clientSideID, config, platform, baseHeaders, diagnosticsManager) => {\n if (config.sendEvents) {\n return new internal.EventProcessor({ ...config, eventsCapacity: config.capacity }, new ClientContext(clientSideID, config, platform), baseHeaders, undefined, diagnosticsManager, false);\n }\n return undefined;\n};\n\n/**\n * @internal\n */\nclass EventFactory extends internal.EventFactoryBase {\n evalEventClient(flagKey, value, defaultVal, flag, context, reason) {\n const { trackEvents, debugEventsUntilDate, trackReason, flagVersion, version, variation } = flag;\n return super.evalEvent({\n addExperimentData: trackReason,\n context,\n debugEventsUntilDate,\n defaultVal,\n flagKey,\n reason,\n trackEvents: !!trackEvents,\n value,\n variation,\n version: flagVersion ?? version,\n });\n }\n}\n\n/**\n * An index for tracking the most recently used contexts by timestamp with the ability to\n * update entry timestamps and prune out least used contexts above a max capacity provided.\n */\nclass ContextIndex {\n constructor() {\n this.container = { index: new Array() };\n }\n /**\n * Creates a {@link ContextIndex} from its JSON representation (likely retrieved from persistence).\n * @param json representation of the {@link ContextIndex}\n * @returns the {@link ContextIndex}\n */\n static fromJson(json) {\n const contextIndex = new ContextIndex();\n try {\n contextIndex.container = JSON.parse(json);\n }\n catch (e) {\n /* ignoring error and returning empty index */\n }\n return contextIndex;\n }\n /**\n * @returns the JSON representation of the {@link ContextIndex} (like for saving to persistence)\n */\n toJson() {\n return JSON.stringify(this.container);\n }\n /**\n * Notice that a context has been used and when it was used. This will update an existing record\n * with the given timestamp, or create a new record if one doesn't exist.\n * @param id of the corresponding context\n * @param timestamp in millis since epoch\n */\n notice(id, timestamp) {\n const entry = this.container.index.find((it) => it.id === id);\n if (entry === undefined) {\n this.container.index.push({ id, timestamp });\n }\n else {\n entry.timestamp = timestamp;\n }\n }\n /**\n * Prune the index to the specified max size and then return the IDs\n * @param maxContexts the maximum number of contexts to retain after this prune\n * @returns an array of removed entries\n */\n prune(maxContexts) {\n const clampedMax = Math.max(maxContexts, 0); // clamp to [0, infinity)\n if (this.container.index.length > clampedMax) {\n // sort by timestamp so that older timestamps appear first in the array\n this.container.index.sort((a, b) => a.timestamp - b.timestamp);\n // delete the first N many elements above capacity. splice returns removed elements\n return this.container.index.splice(0, this.container.index.length - clampedMax);\n }\n return [];\n }\n}\n\n/**\n * This class handles persisting and loading flag values from a persistent\n * store. It intercepts updates and forwards them to the flag updater and\n * then persists changes after the updater has completed.\n */\nclass FlagPersistence {\n constructor(_platform, _environmentNamespace, _maxCachedContexts, _flagStore, _flagUpdater, _logger, _timeStamper = () => Date.now()) {\n this._platform = _platform;\n this._environmentNamespace = _environmentNamespace;\n this._maxCachedContexts = _maxCachedContexts;\n this._flagStore = _flagStore;\n this._flagUpdater = _flagUpdater;\n this._logger = _logger;\n this._timeStamper = _timeStamper;\n this._indexKeyPromise = namespaceForContextIndex(this._environmentNamespace);\n }\n /**\n * Inits flag persistence for the provided context with the provided flags. This will result\n * in the underlying {@link FlagUpdater} switching its active context.\n */\n async init(context, newFlags) {\n this._flagUpdater.init(context, newFlags);\n await this._storeCache(context);\n }\n /**\n * Upserts a flag into the {@link FlagUpdater} and stores that to persistence if the upsert\n * was successful / accepted. An upsert may be rejected if the provided context is not\n * the active context.\n */\n async upsert(context, key, item) {\n if (this._flagUpdater.upsert(context, key, item)) {\n await this._storeCache(context);\n return true;\n }\n return false;\n }\n /**\n * Loads the flags from persistence for the provided context and gives those to the\n * {@link FlagUpdater} this {@link FlagPersistence} was constructed with.\n */\n async loadCached(context) {\n const storageKey = await namespaceForContextData(this._platform.crypto, this._environmentNamespace, context);\n let flagsJson = await this._platform.storage?.get(storageKey);\n if (flagsJson === null || flagsJson === undefined) {\n // Fallback: in version <10.3.1 flag data was stored under the canonical key, check\n // to see if data is present and migrate the data if present.\n flagsJson = await this._platform.storage?.get(context.canonicalKey);\n if (flagsJson === null || flagsJson === undefined) {\n // return false indicating cache did not load if flag json is still absent\n return false;\n }\n // migrate data from version <10.3.1 and cleanup data that was under canonical key\n await this._platform.storage?.set(storageKey, flagsJson);\n await this._platform.storage?.clear(context.canonicalKey);\n }\n try {\n const flags = JSON.parse(flagsJson);\n // mapping flags to item descriptors\n const descriptors = Object.entries(flags).reduce((acc, [key, flag]) => {\n acc[key] = { version: flag.version, flag };\n return acc;\n }, {});\n this._flagUpdater.initCached(context, descriptors);\n this._logger.debug('Loaded cached flag evaluations from persistent storage');\n return true;\n }\n catch (e) {\n this._logger.warn(`Could not load cached flag evaluations from persistent storage: ${e.message}`);\n return false;\n }\n }\n async _loadIndex() {\n if (this._contextIndex !== undefined) {\n return this._contextIndex;\n }\n const json = await this._platform.storage?.get(await this._indexKeyPromise);\n if (!json) {\n this._contextIndex = new ContextIndex();\n return this._contextIndex;\n }\n try {\n this._contextIndex = ContextIndex.fromJson(json);\n this._logger.debug('Loaded context index from persistent storage');\n }\n catch (e) {\n this._logger.warn(`Could not load index from persistent storage: ${e.message}`);\n this._contextIndex = new ContextIndex();\n }\n return this._contextIndex;\n }\n async _storeCache(context) {\n const index = await this._loadIndex();\n const storageKey = await namespaceForContextData(this._platform.crypto, this._environmentNamespace, context);\n index.notice(storageKey, this._timeStamper());\n const pruned = index.prune(this._maxCachedContexts);\n await Promise.all(pruned.map(async (it) => this._platform.storage?.clear(it.id)));\n // store index\n await this._platform.storage?.set(await this._indexKeyPromise, index.toJson());\n const allFlags = this._flagStore.getAll();\n // mapping item descriptors to flags\n const flags = Object.entries(allFlags).reduce((acc, [key, descriptor]) => {\n if (descriptor.flag !== null && descriptor.flag !== undefined) {\n acc[key] = descriptor.flag;\n }\n return acc;\n }, {});\n const jsonAll = JSON.stringify(flags);\n // store flag data\n await this._platform.storage?.set(storageKey, jsonAll);\n }\n}\n\n/**\n * In memory flag store.\n */\nclass DefaultFlagStore {\n constructor() {\n this._flags = {};\n }\n init(newFlags) {\n this._flags = Object.entries(newFlags).reduce((acc, [key, flag]) => {\n acc[key] = flag;\n return acc;\n }, {});\n }\n insertOrUpdate(key, update) {\n this._flags[key] = update;\n }\n get(key) {\n if (Object.prototype.hasOwnProperty.call(this._flags, key)) {\n return this._flags[key];\n }\n return undefined;\n }\n getAll() {\n return this._flags;\n }\n}\n\nfunction calculateChangedKeys(existingObject, newObject) {\n const changedKeys = [];\n // property deleted or updated\n Object.entries(existingObject).forEach(([k, f]) => {\n const subObject = newObject[k];\n if (!subObject || !fastDeepEqual(f, subObject)) {\n changedKeys.push(k);\n }\n });\n // property added\n Object.keys(newObject).forEach((k) => {\n if (!existingObject[k]) {\n changedKeys.push(k);\n }\n });\n return changedKeys;\n}\n\n/**\n * The flag updater handles logic required during the flag update process.\n * It handles versions checking to handle out of order flag updates and\n * also handles flag comparisons for change notification.\n */\nclass FlagUpdater {\n constructor(flagStore, logger) {\n this._changeCallbacks = new Array();\n this._flagStore = flagStore;\n this._logger = logger;\n }\n init(context, newFlags) {\n this._activeContextKey = context.canonicalKey;\n const oldFlags = this._flagStore.getAll();\n this._flagStore.init(newFlags);\n const changed = calculateChangedKeys(oldFlags, newFlags);\n if (changed.length > 0) {\n this._changeCallbacks.forEach((callback) => {\n try {\n callback(context, changed, 'init');\n }\n catch (err) {\n /* intentionally empty */\n }\n });\n }\n }\n initCached(context, newFlags) {\n if (this._activeContextKey === context.canonicalKey) {\n return;\n }\n this.init(context, newFlags);\n }\n upsert(context, key, item) {\n if (this._activeContextKey !== context.canonicalKey) {\n this._logger.warn('Received an update for an inactive context.');\n return false;\n }\n const currentValue = this._flagStore.get(key);\n if (currentValue !== undefined && currentValue.version >= item.version) {\n // this is an out of order update that can be ignored\n return false;\n }\n this._flagStore.insertOrUpdate(key, item);\n this._changeCallbacks.forEach((callback) => {\n try {\n callback(context, [key], 'patch');\n }\n catch (err) {\n /* intentionally empty */\n }\n });\n return true;\n }\n on(callback) {\n this._changeCallbacks.push(callback);\n }\n off(callback) {\n const index = this._changeCallbacks.indexOf(callback);\n if (index > -1) {\n this._changeCallbacks.splice(index, 1);\n }\n }\n}\n\nclass DefaultFlagManager {\n /**\n * @param platform implementation of various platform provided functionality\n * @param sdkKey that will be used to distinguish different environments\n * @param maxCachedContexts that specifies the max number of contexts that will be cached in persistence\n * @param logger used for logging various messages\n * @param timeStamper exists for testing purposes\n */\n constructor(platform, sdkKey, maxCachedContexts, logger, timeStamper = () => Date.now()) {\n this._flagStore = new DefaultFlagStore();\n this._flagUpdater = new FlagUpdater(this._flagStore, logger);\n this._flagPersistencePromise = this._initPersistence(platform, sdkKey, maxCachedContexts, logger, timeStamper);\n }\n async _initPersistence(platform, sdkKey, maxCachedContexts, logger, timeStamper = () => Date.now()) {\n const environmentNamespace = await namespaceForEnvironment(platform.crypto, sdkKey);\n return new FlagPersistence(platform, environmentNamespace, maxCachedContexts, this._flagStore, this._flagUpdater, logger, timeStamper);\n }\n get(key) {\n return this._flagStore.get(key);\n }\n getAll() {\n return this._flagStore.getAll();\n }\n setBootstrap(context, newFlags) {\n // Bypasses the persistence as we do not want to put these flags into any cache.\n // Generally speaking persistence likely *SHOULD* be disabled when using bootstrap.\n this._flagUpdater.init(context, newFlags);\n }\n async init(context, newFlags) {\n return (await this._flagPersistencePromise).init(context, newFlags);\n }\n async upsert(context, key, item) {\n return (await this._flagPersistencePromise).upsert(context, key, item);\n }\n async loadCached(context) {\n return (await this._flagPersistencePromise).loadCached(context);\n }\n on(callback) {\n this._flagUpdater.on(callback);\n }\n off(callback) {\n this._flagUpdater.off(callback);\n }\n}\n\nconst UNKNOWN_HOOK_NAME = 'unknown hook';\nconst BEFORE_EVALUATION_STAGE_NAME = 'beforeEvaluation';\nconst AFTER_EVALUATION_STAGE_NAME = 'afterEvaluation';\nfunction tryExecuteStage(logger, method, hookName, stage, def) {\n try {\n return stage();\n }\n catch (err) {\n logger?.error(`An error was encountered in \"${method}\" of the \"${hookName}\" hook: ${err}`);\n return def;\n }\n}\nfunction getHookName(logger, hook) {\n try {\n return hook.getMetadata().name || UNKNOWN_HOOK_NAME;\n }\n catch {\n logger.error(`Exception thrown getting metadata for hook. Unable to get hook name.`);\n return UNKNOWN_HOOK_NAME;\n }\n}\nfunction executeBeforeEvaluation(logger, hooks, hookContext) {\n return hooks.map((hook) => tryExecuteStage(logger, BEFORE_EVALUATION_STAGE_NAME, getHookName(logger, hook), () => hook?.beforeEvaluation?.(hookContext, {}) ?? {}, {}));\n}\nfunction executeAfterEvaluation(logger, hooks, hookContext, updatedData, result) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n const data = updatedData[hookIndex];\n tryExecuteStage(logger, AFTER_EVALUATION_STAGE_NAME, getHookName(logger, hook), () => hook?.afterEvaluation?.(hookContext, data, result) ?? {}, {});\n }\n}\nfunction executeBeforeIdentify(logger, hooks, hookContext) {\n return hooks.map((hook) => tryExecuteStage(logger, BEFORE_EVALUATION_STAGE_NAME, getHookName(logger, hook), () => hook?.beforeIdentify?.(hookContext, {}) ?? {}, {}));\n}\nfunction executeAfterIdentify(logger, hooks, hookContext, updatedData, result) {\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n const data = updatedData[hookIndex];\n tryExecuteStage(logger, AFTER_EVALUATION_STAGE_NAME, getHookName(logger, hook), () => hook?.afterIdentify?.(hookContext, data, result) ?? {}, {});\n }\n}\nclass HookRunner {\n constructor(_logger, initialHooks) {\n this._logger = _logger;\n this._hooks = [];\n this._hooks.push(...initialHooks);\n }\n withEvaluation(key, context, defaultValue, method) {\n if (this._hooks.length === 0) {\n return method();\n }\n const hooks = [...this._hooks];\n const hookContext = {\n flagKey: key,\n context,\n defaultValue,\n };\n const hookData = executeBeforeEvaluation(this._logger, hooks, hookContext);\n const result = method();\n executeAfterEvaluation(this._logger, hooks, hookContext, hookData, result);\n return result;\n }\n identify(context, timeout) {\n const hooks = [...this._hooks];\n const hookContext = {\n context,\n timeout,\n };\n const hookData = executeBeforeIdentify(this._logger, hooks, hookContext);\n return (result) => {\n executeAfterIdentify(this._logger, hooks, hookContext, hookData, result);\n };\n }\n addHook(hook) {\n this._hooks.push(hook);\n }\n}\n\nfunction getInspectorHook(inspectorManager) {\n return {\n getMetadata() {\n return {\n name: 'LaunchDarkly-Inspector-Adapter',\n };\n },\n afterEvaluation: (hookContext, data, detail) => {\n inspectorManager.onFlagUsed(hookContext.flagKey, detail, hookContext.context);\n return data;\n },\n afterIdentify(hookContext, data, _result) {\n inspectorManager.onIdentityChanged(hookContext.context);\n return data;\n },\n };\n}\n\nfunction invalidInspector(type, name) {\n return `an inspector: \"${name}\" of an invalid type (${type}) was configured`;\n}\nfunction inspectorMethodError(type, name) {\n return `an inspector: \"${name}\" of type: \"${type}\" generated an exception`;\n}\n\n/**\n * Wrap an inspector ensuring that calling its methods are safe.\n * @param inspector Inspector to wrap.\n */\nfunction createSafeInspector(inspector, logger) {\n let errorLogged = false;\n const wrapper = {\n method: (...args) => {\n try {\n // We are proxying arguments here to the underlying method. Typescript doesn't care\n // for this as it cannot validate the parameters are correct, but we are also the caller\n // in this case and will dispatch things with the correct arguments. The dispatch to this\n // will itself happen with a type guard.\n // @ts-ignore\n inspector.method(...args);\n }\n catch {\n // If something goes wrong in an inspector we want to log that something\n // went wrong. We don't want to flood the logs, so we only log something\n // the first time that something goes wrong.\n // We do not include the exception in the log, because we do not know what\n // kind of data it may contain.\n if (!errorLogged) {\n errorLogged = true;\n logger.warn(inspectorMethodError(wrapper.type, wrapper.name));\n }\n // Prevent errors.\n }\n },\n type: inspector.type,\n name: inspector.name,\n synchronous: inspector.synchronous,\n };\n return wrapper;\n}\n\nconst FLAG_USED_TYPE = 'flag-used';\nconst FLAG_DETAILS_CHANGED_TYPE = 'flag-details-changed';\nconst FLAG_DETAIL_CHANGED_TYPE = 'flag-detail-changed';\nconst IDENTITY_CHANGED_TYPE = 'client-identity-changed';\nconst VALID__TYPES = [\n FLAG_USED_TYPE,\n FLAG_DETAILS_CHANGED_TYPE,\n FLAG_DETAIL_CHANGED_TYPE,\n IDENTITY_CHANGED_TYPE,\n];\nfunction validateInspector(inspector, logger) {\n const valid = VALID__TYPES.includes(inspector.type) &&\n inspector.method &&\n typeof inspector.method === 'function';\n if (!valid) {\n logger.warn(invalidInspector(inspector.type, inspector.name));\n }\n return valid;\n}\n/**\n * Manages dispatching of inspection data to registered inspectors.\n */\nclass InspectorManager {\n constructor(inspectors, logger) {\n this._safeInspectors = [];\n const validInspectors = inspectors.filter((inspector) => validateInspector(inspector, logger));\n this._safeInspectors = validInspectors.map((inspector) => createSafeInspector(inspector, logger));\n }\n hasInspectors() {\n return this._safeInspectors.length !== 0;\n }\n /**\n * Notify registered inspectors of a flag being used.\n *\n * @param flagKey The key for the flag.\n * @param detail The LDEvaluationDetail for the flag.\n * @param context The LDContext for the flag.\n */\n onFlagUsed(flagKey, detail, context) {\n this._safeInspectors.forEach((inspector) => {\n if (inspector.type === FLAG_USED_TYPE) {\n inspector.method(flagKey, detail, context);\n }\n });\n }\n /**\n * Notify registered inspectors that the flags have been replaced.\n *\n * @param flags The current flags as a Record<string, LDEvaluationDetail>.\n */\n onFlagsChanged(flags) {\n this._safeInspectors.forEach((inspector) => {\n if (inspector.type === FLAG_DETAILS_CHANGED_TYPE) {\n inspector.method(flags);\n }\n });\n }\n /**\n * Notify registered inspectors that a flag value has changed.\n *\n * @param flagKey The key for the flag that changed.\n * @param flag An `LDEvaluationDetail` for the flag.\n */\n onFlagChanged(flagKey, flag) {\n this._safeInspectors.forEach((inspector) => {\n if (inspector.type === FLAG_DETAIL_CHANGED_TYPE) {\n inspector.method(flagKey, flag);\n }\n });\n }\n /**\n * Notify the registered inspectors that the context identity has changed.\n *\n * The notification itself will be dispatched asynchronously.\n *\n * @param context The `LDContext` which is now identified.\n */\n onIdentityChanged(context) {\n this._safeInspectors.forEach((inspector) => {\n if (inspector.type === IDENTITY_CHANGED_TYPE) {\n inspector.method(context);\n }\n });\n }\n}\n\n/**\n * Implementation Note: There should not be any default listeners for change events in a client\n * implementation. Default listeners mean a client cannot determine when there are actual\n * application developer provided listeners. If we require default listeners, then we should add\n * a system to allow listeners which have counts independent of the primary listener counts.\n */\nclass LDEmitter {\n constructor(_logger) {\n this._logger = _logger;\n this._listeners = new Map();\n }\n on(name, listener) {\n if (!this._listeners.has(name)) {\n this._listeners.set(name, [listener]);\n }\n else {\n this._listeners.get(name)?.push(listener);\n }\n }\n /**\n * Unsubscribe one or all events.\n *\n * @param name\n * @param listener Optional. If unspecified, all listeners for the event will be removed.\n */\n off(name, listener) {\n const existingListeners = this._listeners.get(name);\n if (!existingListeners) {\n return;\n }\n if (listener) {\n // remove from internal cache\n const updated = existingListeners.filter((fn) => fn !== listener);\n if (updated.length === 0) {\n this._listeners.delete(name);\n }\n else {\n this._listeners.set(name, updated);\n }\n return;\n }\n // listener was not specified, so remove them all for that event\n this._listeners.delete(name);\n }\n _invokeListener(listener, name, ...detail) {\n try {\n listener(...detail);\n }\n catch (err) {\n this._logger?.error(`Encountered error invoking handler for \"${name}\", detail: \"${err}\"`);\n }\n }\n emit(name, ...detail) {\n const listeners = this._listeners.get(name);\n listeners?.forEach((listener) => this._invokeListener(listener, name, ...detail));\n }\n eventNames() {\n return [...this._listeners.keys()];\n }\n listenerCount(name) {\n return this._listeners.get(name)?.length ?? 0;\n }\n}\n\nconst { ClientMessages, ErrorKinds } = internal;\nclass LDClientImpl {\n /**\n * Creates the client object synchronously. No async, no network calls.\n */\n constructor(sdkKey, autoEnvAttributes, platform, options, dataManagerFactory, internalOptions) {\n this.sdkKey = sdkKey;\n this.autoEnvAttributes = autoEnvAttributes;\n this.platform = platform;\n this._identifyTimeout = 5;\n this._highTimeoutThreshold = 15;\n this._eventFactoryDefault = new EventFactory(false);\n this._eventFactoryWithReasons = new EventFactory(true);\n this._eventSendingEnabled = false;\n if (!sdkKey) {\n throw new Error('You must configure the client with a client-side SDK key');\n }\n if (!platform.encoding) {\n throw new Error('Platform must implement Encoding because btoa is required.');\n }\n this._config = new ConfigurationImpl(options, internalOptions);\n this.logger = this._config.logger;\n this._baseHeaders = defaultHeaders(this.sdkKey, this.platform.info, this._config.tags, this._config.serviceEndpoints.includeAuthorizationHeader, this._config.userAgentHeaderName);\n this._flagManager = new DefaultFlagManager(this.platform, sdkKey, this._config.maxCachedContexts, this._config.logger);\n this._diagnosticsManager = createDiagnosticsManager(sdkKey, this._config, platform);\n this._eventProcessor = createEventProcessor(sdkKey, this._config, platform, this._baseHeaders, this._diagnosticsManager);\n this.emitter = new LDEmitter();\n this.emitter.on('error', (c, err) => {\n this.logger.error(`error: ${err}, context: ${JSON.stringify(c)}`);\n });\n this._flagManager.on((context, flagKeys, type) => {\n this._handleInspectionChanged(flagKeys, type);\n const ldContext = Context.toLDContext(context);\n this.emitter.emit('change', ldContext, flagKeys);\n flagKeys.forEach((it) => {\n this.emitter.emit(`change:${it}`, ldContext);\n });\n });\n this.dataManager = dataManagerFactory(this._flagManager, this._config, this._baseHeaders, this.emitter, this._diagnosticsManager);\n this._hookRunner = new HookRunner(this.logger, this._config.hooks);\n this._inspectorManager = new InspectorManager(this._config.inspectors, this.logger);\n if (this._inspectorManager.hasInspectors()) {\n this._hookRunner.addHook(getInspectorHook(this._inspectorManager));\n }\n }\n allFlags() {\n // extracting all flag values\n const result = Object.entries(this._flagManager.getAll()).reduce((acc, [key, descriptor]) => {\n if (descriptor.flag !== null && descriptor.flag !== undefined && !descriptor.flag.deleted) {\n acc[key] = descriptor.flag.value;\n }\n return acc;\n }, {});\n return result;\n }\n async close() {\n await this.flush();\n this._eventProcessor?.close();\n this._updateProcessor?.close();\n this.logger.debug('Closed event processor and data source.');\n }\n async flush() {\n try {\n await this._eventProcessor?.flush();\n this.logger.debug('Successfully flushed event processor.');\n }\n catch (e) {\n this.logger.error(`Error flushing event processor: ${e}.`);\n return { error: e, result: false };\n }\n return { result: true };\n }\n getContext() {\n // The LDContext returned here may have been modified by the SDK (for example: adding auto env attributes).\n // We are returning an LDContext here to maintain a consistent represetnation of context to the consuming\n // code. We are returned the unchecked context so that if a consumer identifies with an invalid context\n // and then calls getContext, they get back the same context they provided, without any assertion about\n // validity.\n return this._uncheckedContext ? clone(this._uncheckedContext) : undefined;\n }\n getInternalContext() {\n return this._checkedContext;\n }\n _createIdentifyPromise(timeout) {\n let res;\n let rej;\n const slow = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n const timed = timedPromise(timeout, 'identify');\n const raced = Promise.race([timed, slow]).catch((e) => {\n if (e.message.includes('timed out')) {\n this.logger.error(`identify error: ${e}`);\n }\n throw e;\n });\n return { identifyPromise: raced, identifyResolve: res, identifyReject: rej };\n }\n /**\n * Identifies a context to LaunchDarkly. See {@link LDClient.identify}.\n *\n * @param pristineContext The LDContext object to be identified.\n * @param identifyOptions Optional configuration. See {@link LDIdentifyOptions}.\n * @returns A Promise which resolves when the flag values for the specified\n * context are available. It rejects when:\n *\n * 1. The context is unspecified or has no key.\n *\n * 2. The identify timeout is exceeded. In client SDKs this defaults to 5s.\n * You can customize this timeout with {@link LDIdentifyOptions | identifyOptions}.\n *\n * 3. A network error is encountered during initialization.\n */\n async identify(pristineContext, identifyOptions) {\n if (identifyOptions?.timeout) {\n this._identifyTimeout = identifyOptions.timeout;\n }\n if (this._identifyTimeout > this._highTimeoutThreshold) {\n this.logger.warn('The identify function was called with a timeout greater than ' +\n `${this._highTimeoutThreshold} seconds. We recommend a timeout of less than ` +\n `${this._highTimeoutThreshold} seconds.`);\n }\n let context = await ensureKey(pristineContext, this.platform);\n if (this.autoEnvAttributes === AutoEnvAttributes.Enabled) {\n context = await addAutoEnv(context, this.platform, this._config);\n }\n const checkedContext = Context.fromLDContext(context);\n if (!checkedContext.valid) {\n const error = new Error('Context was unspecified or had no key');\n this.emitter.emit('error', context, error);\n return Promise.reject(error);\n }\n this._uncheckedContext = context;\n this._checkedContext = checkedContext;\n this._eventProcessor?.sendEvent(this._eventFactoryDefault.identifyEvent(this._checkedContext));\n const { identifyPromise, identifyResolve, identifyReject } = this._createIdentifyPromise(this._identifyTimeout);\n this.logger.debug(`Identifying ${JSON.stringify(this._checkedContext)}`);\n const afterIdentify = this._hookRunner.identify(context, identifyOptions?.timeout);\n await this.dataManager.identify(identifyResolve, identifyReject, checkedContext, identifyOptions);\n return identifyPromise.then((res) => {\n afterIdentify({ status: 'completed' });\n return res;\n }, (e) => {\n afterIdentify({ status: 'error' });\n throw e;\n });\n }\n on(eventName, listener) {\n this.emitter.on(eventName, listener);\n }\n off(eventName, listener) {\n this.emitter.off(eventName, listener);\n }\n track(key, data, metricValue) {\n if (!this._checkedContext || !this._checkedContext.valid) {\n this.logger.warn(ClientMessages.MissingContextKeyNoEvent);\n return;\n }\n // 0 is valid, so do not truthy check the metric value\n if (metricValue !== undefined && !TypeValidators.Number.is(metricValue)) {\n this.logger?.warn(ClientMessages.invalidMetricValue(typeof metricValue));\n }\n this._eventProcessor?.sendEvent(this._config.trackEventModifier(this._eventFactoryDefault.customEvent(key, this._checkedContext, data, metricValue)));\n }\n _variationInternal(flagKey, defaultValue, eventFactory, typeChecker) {\n if (!this._uncheckedContext) {\n this.logger.debug(ClientMessages.MissingContextKeyNoEvent);\n return createErrorEvaluationDetail(ErrorKinds.UserNotSpecified, defaultValue);\n }\n const evalContext = Context.fromLDContext(this._uncheckedContext);\n const foundItem = this._flagManager.get(flagKey);\n if (foundItem === undefined || foundItem.flag.deleted) {\n const defVal = defaultValue ?? null;\n const error = new LDClientError(`Unknown feature flag \"${flagKey}\"; returning default value ${defVal}.`);\n this.emitter.emit('error', this._uncheckedContext, error);\n this._eventProcessor?.sendEvent(this._eventFactoryDefault.unknownFlagEvent(flagKey, defVal, evalContext));\n return createErrorEvaluationDetail(ErrorKinds.FlagNotFound, defaultValue);\n }\n const { reason, value, variation, prerequisites } = foundItem.flag;\n if (typeChecker) {\n const [matched, type] = typeChecker(value);\n if (!matched) {\n this._eventProcessor?.sendEvent(eventFactory.evalEventClient(flagKey, defaultValue, // track default value on type errors\n defaultValue, foundItem.flag, evalContext, reason));\n const error = new LDClientError(`Wrong type \"${type}\" for feature flag \"${flagKey}\"; returning default value`);\n this.emitter.emit('error', this._uncheckedContext, error);\n return createErrorEvaluationDetail(ErrorKinds.WrongType, defaultValue);\n }\n }\n const successDetail = createSuccessEvaluationDetail(value, variation, reason);\n if (value === undefined || value === null) {\n this.logger.debug('Result value is null. Providing default value.');\n successDetail.value = defaultValue;\n }\n prerequisites?.forEach((prereqKey) => {\n this._variationInternal(prereqKey, undefined, this._eventFactoryDefault);\n });\n this._eventProcessor?.sendEvent(eventFactory.evalEventClient(flagKey, value, defaultValue, foundItem.flag, evalContext, reason));\n return successDetail;\n }\n variation(flagKey, defaultValue) {\n const { value } = this._hookRunner.withEvaluation(flagKey, this._uncheckedContext, defaultValue, () => this._variationInternal(flagKey, defaultValue, this._eventFactoryDefault));\n return value;\n }\n variationDetail(flagKey, defaultValue) {\n return this._hookRunner.withEvaluation(flagKey, this._uncheckedContext, defaultValue, () => this._variationInternal(flagKey, defaultValue, this._eventFactoryWithReasons));\n }\n _typedEval(key, defaultValue, eventFactory, typeChecker) {\n return this._hookRunner.withEvaluation(key, this._uncheckedContext, defaultValue, () => this._variationInternal(key, defaultValue, eventFactory, typeChecker));\n }\n boolVariation(key, defaultValue) {\n return this._typedEval(key, defaultValue, this._eventFactoryDefault, (value) => [\n TypeValidators.Boolean.is(value),\n TypeValidators.Boolean.getType(),\n ]).value;\n }\n jsonVariation(key, defaultValue) {\n return this.variation(key, defaultValue);\n }\n numberVariation(key, defaultValue) {\n return this._typedEval(key, defaultValue, this._eventFactoryDefault, (value) => [\n TypeValidators.Number.is(value),\n TypeValidators.Number.getType(),\n ]).value;\n }\n stringVariation(key, defaultValue) {\n return this._typedEval(key, defaultValue, this._eventFactoryDefault, (value) => [\n TypeValidators.String.is(value),\n TypeValidators.String.getType(),\n ]).value;\n }\n boolVariationDetail(key, defaultValue) {\n return this._typedEval(key, defaultValue, this._eventFactoryWithReasons, (value) => [\n TypeValidators.Boolean.is(value),\n TypeValidators.Boolean.getType(),\n ]);\n }\n numberVariationDetail(key, defaultValue) {\n return this._typedEval(key, defaultValue, this._eventFactoryWithReasons, (value) => [\n TypeValidators.Number.is(value),\n TypeValidators.Number.getType(),\n ]);\n }\n stringVariationDetail(key, defaultValue) {\n return this._typedEval(key, defaultValue, this._eventFactoryWithReasons, (value) => [\n TypeValidators.String.is(value),\n TypeValidators.String.getType(),\n ]);\n }\n jsonVariationDetail(key, defaultValue) {\n return this.variationDetail(key, defaultValue);\n }\n addHook(hook) {\n this._hookRunner.addHook(hook);\n }\n /**\n * Enable/Disable event sending.\n * @param enabled True to enable event processing, false to disable.\n * @param flush True to flush while disabling. Useful to flush on certain state transitions.\n */\n setEventSendingEnabled(enabled, flush) {\n if (this._eventSendingEnabled === enabled) {\n return;\n }\n this._eventSendingEnabled = enabled;\n if (enabled) {\n this.logger.debug('Starting event processor');\n this._eventProcessor?.start();\n }\n else if (flush) {\n this.logger?.debug('Flushing event processor before disabling.');\n // Disable and flush.\n this.flush().then(() => {\n // While waiting for the flush event sending could be re-enabled, in which case\n // we do not want to close the event processor.\n if (!this._eventSendingEnabled) {\n this.logger?.debug('Stopping event processor.');\n this._eventProcessor?.close();\n }\n });\n }\n else {\n // Just disabled.\n this.logger?.debug('Stopping event processor.');\n this._eventProcessor?.close();\n }\n }\n sendEvent(event) {\n this._eventProcessor?.sendEvent(event);\n }\n _handleInspectionChanged(flagKeys, type) {\n if (!this._inspectorManager.hasInspectors()) {\n return;\n }\n const details = {};\n flagKeys.forEach((flagKey) => {\n const item = this._flagManager.get(flagKey);\n if (item?.flag && !item.flag.deleted) {\n const { reason, value, variation } = item.flag;\n details[flagKey] = createSuccessEvaluationDetail(value, variation, reason);\n }\n });\n if (type === 'init') {\n this._inspectorManager.onFlagsChanged(details);\n }\n else if (type === 'patch') {\n Object.entries(details).forEach(([flagKey, detail]) => {\n this._inspectorManager.onFlagChanged(flagKey, detail);\n });\n }\n }\n}\n\nclass DataSourceEventHandler {\n constructor(_flagManager, _statusManager, _logger) {\n this._flagManager = _flagManager;\n this._statusManager = _statusManager;\n this._logger = _logger;\n }\n async handlePut(context, flags) {\n this._logger.debug(`Got PUT: ${Object.keys(flags)}`);\n // mapping flags to item descriptors\n const descriptors = Object.entries(flags).reduce((acc, [key, flag]) => {\n acc[key] = { version: flag.version, flag };\n return acc;\n }, {});\n await this._flagManager.init(context, descriptors);\n this._statusManager.requestStateUpdate(DataSourceState.Valid);\n }\n async handlePatch(context, patchFlag) {\n this._logger.debug(`Got PATCH ${JSON.stringify(patchFlag, null, 2)}`);\n this._flagManager.upsert(context, patchFlag.key, {\n version: patchFlag.version,\n flag: patchFlag,\n });\n }\n async handleDelete(context, deleteFlag) {\n this._logger.debug(`Got DELETE ${JSON.stringify(deleteFlag, null, 2)}`);\n this._flagManager.upsert(context, deleteFlag.key, {\n version: deleteFlag.version,\n flag: {\n ...deleteFlag,\n deleted: true,\n // props below are set to sensible defaults. they are irrelevant\n // because this flag has been deleted.\n flagVersion: 0,\n value: undefined,\n variation: 0,\n trackEvents: false,\n },\n });\n }\n handleStreamingError(error) {\n this._statusManager.reportError(error.kind, error.message, error.code, error.recoverable);\n }\n handlePollingError(error) {\n this._statusManager.reportError(error.kind, error.message, error.status, error.recoverable);\n }\n}\n\n/**\n * Tracks the current data source status and emits updates when the status changes.\n */\nclass DataSourceStatusManager {\n constructor(_emitter, timeStamper = () => Date.now()) {\n this._emitter = _emitter;\n this._state = DataSourceState.Closed;\n this._stateSinceMillis = timeStamper();\n this._timeStamper = timeStamper;\n }\n get status() {\n return {\n state: this._state,\n stateSince: this._stateSinceMillis,\n lastError: this._errorInfo,\n };\n }\n /**\n * Updates the state of the manager.\n *\n * @param requestedState to track\n * @param isError to indicate that the state update is a result of an error occurring.\n */\n _updateState(requestedState, isError = false) {\n const newState = requestedState === DataSourceState.Interrupted && this._state === DataSourceState.Initializing // don't go to interrupted from initializing (recoverable errors when initializing are not noteworthy)\n ? DataSourceState.Initializing\n : requestedState;\n const changedState = this._state !== newState;\n if (changedState) {\n this._state = newState;\n this._stateSinceMillis = this._timeStamper();\n }\n if (changedState || isError) {\n this._emitter.emit('dataSourceStatus', this.status);\n }\n }\n /**\n * Requests the manager move to the provided state. This request may be ignored\n * if the current state cannot transition to the requested state.\n * @param state that is requested\n */\n requestStateUpdate(state) {\n this._updateState(state);\n }\n /**\n * Reports a datasource error to this manager. Since the {@link DataSourceStatus} includes error\n * information, it is possible that that a {@link DataSourceStatus} update is emitted with\n * the same {@link DataSourceState}.\n *\n * @param kind of the error\n * @param message for the error\n * @param statusCode of the error if there was one\n * @param recoverable to indicate that the error is anticipated to be recoverable\n */\n reportError(kind, message, statusCode, recoverable = false) {\n const errorInfo = {\n kind,\n message,\n statusCode,\n time: this._timeStamper(),\n };\n this._errorInfo = errorInfo;\n this._updateState(recoverable ? DataSourceState.Interrupted : DataSourceState.Closed, true);\n }\n}\n\n/**\n * @internal\n */\nclass PollingProcessor {\n constructor(_requestor, _pollIntervalSeconds, _dataHandler, _errorHandler, _logger) {\n this._requestor = _requestor;\n this._pollIntervalSeconds = _pollIntervalSeconds;\n this._dataHandler = _dataHandler;\n this._errorHandler = _errorHandler;\n this._logger = _logger;\n this._stopped = false;\n }\n async _poll() {\n if (this._stopped) {\n return;\n }\n const reportJsonError = (data) => {\n this._logger?.error('Polling received invalid data');\n this._logger?.debug(`Invalid JSON follows: ${data}`);\n this._errorHandler?.(new LDPollingError(DataSourceErrorKind.InvalidData, 'Malformed JSON data in polling response'));\n };\n this._logger?.debug('Polling LaunchDarkly for feature flag updates');\n const startTime = Date.now();\n try {\n const res = await this._requestor.requestPayload();\n try {\n const flags = JSON.parse(res);\n try {\n this._dataHandler?.(flags);\n }\n catch (err) {\n this._logger?.error(`Exception from data handler: ${err}`);\n }\n }\n catch {\n reportJsonError(res);\n }\n }\n catch (err) {\n const requestError = err;\n if (requestError.status !== undefined) {\n if (!isHttpRecoverable(requestError.status)) {\n this._logger?.error(httpErrorMessage(err, 'polling request'));\n this._errorHandler?.(new LDPollingError(DataSourceErrorKind.ErrorResponse, requestError.message, requestError.status));\n return;\n }\n }\n this._logger?.error(httpErrorMessage(err, 'polling request', 'will retry'));\n }\n const elapsed = Date.now() - startTime;\n const sleepFor = Math.max(this._pollIntervalSeconds * 1000 - elapsed, 0);\n this._logger?.debug('Elapsed: %d ms, sleeping for %d ms', elapsed, sleepFor);\n this._timeoutHandle = setTimeout(() => {\n this._poll();\n }, sleepFor);\n }\n start() {\n this._poll();\n }\n stop() {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle);\n this._timeoutHandle = undefined;\n }\n this._stopped = true;\n }\n close() {\n this.stop();\n }\n}\n\nconst reportJsonError = (type, data, logger, errorHandler) => {\n logger?.error(`Stream received invalid data in \"${type}\" message`);\n logger?.debug(`Invalid JSON follows: ${data}`);\n errorHandler?.(new LDStreamingError(DataSourceErrorKind.InvalidData, 'Malformed JSON data in event stream'));\n};\nclass StreamingProcessor {\n constructor(_plainContextString, _dataSourceConfig, _listeners, _requests, encoding, _pollingRequestor, _diagnosticsManager, _errorHandler, _logger) {\n this._plainContextString = _plainContextString;\n this._dataSourceConfig = _dataSourceConfig;\n this._listeners = _listeners;\n this._requests = _requests;\n this._pollingRequestor = _pollingRequestor;\n this._diagnosticsManager = _diagnosticsManager;\n this._errorHandler = _errorHandler;\n this._logger = _logger;\n let path;\n if (_dataSourceConfig.useReport && !_requests.getEventSourceCapabilities().customMethod) {\n path = _dataSourceConfig.paths.pathPing(encoding, _plainContextString);\n }\n else {\n path = _dataSourceConfig.useReport\n ? _dataSourceConfig.paths.pathReport(encoding, _plainContextString)\n : _dataSourceConfig.paths.pathGet(encoding, _plainContextString);\n }\n const parameters = [\n ...(_dataSourceConfig.queryParameters ?? []),\n ];\n if (this._dataSourceConfig.withReasons) {\n parameters.push({ key: 'withReasons', value: 'true' });\n }\n this._requests = _requests;\n this._headers = { ..._dataSourceConfig.baseHeaders };\n this._logger = _logger;\n this._streamUri = getStreamingUri(_dataSourceConfig.serviceEndpoints, path, parameters);\n }\n _logConnectionStarted() {\n this._connectionAttemptStartTime = Date.now();\n }\n _logConnectionResult(success) {\n if (this._connectionAttemptStartTime && this._diagnosticsManager) {\n this._diagnosticsManager.recordStreamInit(this._connectionAttemptStartTime, !success, Date.now() - this._connectionAttemptStartTime);\n }\n this._connectionAttemptStartTime = undefined;\n }\n /**\n * This is a wrapper around the passed errorHandler which adds additional\n * diagnostics and logging logic.\n *\n * @param err The error to be logged and handled.\n * @return boolean whether to retry the connection.\n *\n * @private\n */\n _retryAndHandleError(err) {\n if (!shouldRetry(err)) {\n this._logConnectionResult(false);\n this._errorHandler?.(new LDStreamingError(DataSourceErrorKind.ErrorResponse, err.message, err.status, false));\n this._logger?.error(httpErrorMessage(err, 'streaming request'));\n return false;\n }\n this._logger?.warn(httpErrorMessage(err, 'streaming request', 'will retry'));\n this._logConnectionResult(false);\n this._logConnectionStarted();\n return true;\n }\n start() {\n this._logConnectionStarted();\n let methodAndBodyOverrides;\n if (this._dataSourceConfig.useReport) {\n // REPORT will include a body, so content type is required.\n this._headers['content-type'] = 'application/json';\n // orverrides default method with REPORT and adds body.\n methodAndBodyOverrides = { method: 'REPORT', body: this._plainContextString };\n }\n else {\n // no method or body override\n methodAndBodyOverrides = {};\n }\n // TLS is handled by the platform implementation.\n const eventSource = this._requests.createEventSource(this._streamUri, {\n headers: this._headers,\n ...methodAndBodyOverrides,\n errorFilter: (error) => this._retryAndHandleError(error),\n initialRetryDelayMillis: this._dataSourceConfig.initialRetryDelayMillis,\n readTimeoutMillis: 5 * 60 * 1000,\n retryResetIntervalMillis: 60 * 1000,\n });\n this._eventSource = eventSource;\n eventSource.onclose = () => {\n this._logger?.info('Closed LaunchDarkly stream connection');\n };\n eventSource.onerror = () => {\n // The work is done by `errorFilter`.\n };\n eventSource.onopen = () => {\n this._logger?.info('Opened LaunchDarkly stream connection');\n };\n eventSource.onretrying = (e) => {\n this._logger?.info(`Will retry stream connection in ${e.delayMillis} milliseconds`);\n };\n this._listeners.forEach(({ deserializeData, processJson }, eventName) => {\n eventSource.addEventListener(eventName, (event) => {\n this._logger?.debug(`Received ${eventName} event`);\n if (event?.data) {\n this._logConnectionResult(true);\n const { data } = event;\n const dataJson = deserializeData(data);\n if (!dataJson) {\n reportJsonError(eventName, data, this._logger, this._errorHandler);\n return;\n }\n processJson(dataJson);\n }\n else {\n this._errorHandler?.(new LDStreamingError(DataSourceErrorKind.InvalidData, 'Unexpected payload from event stream'));\n }\n });\n });\n // here we set up a listener that will poll when ping is received\n eventSource.addEventListener('ping', async () => {\n this._logger?.debug('Got PING, going to poll LaunchDarkly for feature flag updates');\n try {\n const res = await this._pollingRequestor.requestPayload();\n try {\n const payload = JSON.parse(res);\n try {\n // forward the payload on to the PUT listener\n this._listeners.get('put')?.processJson(payload);\n }\n catch (err) {\n this._logger?.error(`Exception from data handler: ${err}`);\n }\n }\n catch {\n this._logger?.error('Polling after ping received invalid data');\n this._logger?.debug(`Invalid JSON follows: ${res}`);\n this._errorHandler?.(new LDPollingError(DataSourceErrorKind.InvalidData, 'Malformed JSON data in ping polling response'));\n }\n }\n catch (err) {\n const requestError = err;\n this._errorHandler?.(new LDPollingError(DataSourceErrorKind.ErrorResponse, requestError.message, requestError.status));\n }\n });\n }\n stop() {\n this._eventSource?.close();\n this._eventSource = undefined;\n }\n close() {\n this.stop();\n }\n}\n\nclass BaseDataManager {\n constructor(platform, flagManager, credential, config, getPollingPaths, getStreamingPaths, baseHeaders, emitter, diagnosticsManager) {\n this.platform = platform;\n this.flagManager = flagManager;\n this.credential = credential;\n this.config = config;\n this.getPollingPaths = getPollingPaths;\n this.getStreamingPaths = getStreamingPaths;\n this.baseHeaders = baseHeaders;\n this.emitter = emitter;\n this.diagnosticsManager = diagnosticsManager;\n this.logger = config.logger;\n this.dataSourceStatusManager = new DataSourceStatusManager(emitter);\n this._dataSourceEventHandler = new DataSourceEventHandler(flagManager, this.dataSourceStatusManager, this.config.logger);\n }\n /**\n * Set additional connection parameters for requests polling/streaming.\n */\n setConnectionParams(connectionParams) {\n this._connectionParams = connectionParams;\n }\n createPollingProcessor(context, checkedContext, requestor, identifyResolve, identifyReject) {\n const processor = new PollingProcessor(requestor, this.config.pollInterval, async (flags) => {\n await this._dataSourceEventHandler.handlePut(checkedContext, flags);\n identifyResolve?.();\n }, (err) => {\n this.emitter.emit('error', context, err);\n this._dataSourceEventHandler.handlePollingError(err);\n identifyReject?.(err);\n }, this.logger);\n this.updateProcessor = this._decorateProcessorWithStatusReporting(processor, this.dataSourceStatusManager);\n }\n createStreamingProcessor(context, checkedContext, pollingRequestor, identifyResolve, identifyReject) {\n const processor = new StreamingProcessor(JSON.stringify(context), {\n credential: this.credential,\n serviceEndpoints: this.config.serviceEndpoints,\n paths: this.getStreamingPaths(),\n baseHeaders: this.baseHeaders,\n initialRetryDelayMillis: this.config.streamInitialReconnectDelay * 1000,\n withReasons: this.config.withReasons,\n useReport: this.config.useReport,\n queryParameters: this._connectionParams?.queryParameters,\n }, this.createStreamListeners(checkedContext, identifyResolve), this.platform.requests, this.platform.encoding, pollingRequestor, this.diagnosticsManager, (e) => {\n this.emitter.emit('error', context, e);\n this._dataSourceEventHandler.handleStreamingError(e);\n identifyReject?.(e);\n }, this.logger);\n this.updateProcessor = this._decorateProcessorWithStatusReporting(processor, this.dataSourceStatusManager);\n }\n createStreamListeners(context, identifyResolve) {\n const listeners = new Map();\n listeners.set('put', {\n deserializeData: JSON.parse,\n processJson: async (flags) => {\n await this._dataSourceEventHandler.handlePut(context, flags);\n identifyResolve?.();\n },\n });\n listeners.set('patch', {\n deserializeData: JSON.parse,\n processJson: async (patchFlag) => {\n this._dataSourceEventHandler.handlePatch(context, patchFlag);\n },\n });\n listeners.set('delete', {\n deserializeData: JSON.parse,\n processJson: async (deleteFlag) => {\n this._dataSourceEventHandler.handleDelete(context, deleteFlag);\n },\n });\n return listeners;\n }\n _decorateProcessorWithStatusReporting(processor, statusManager) {\n return {\n start: () => {\n // update status before starting processor to ensure potential errors are reported after initializing\n statusManager.requestStateUpdate(DataSourceState.Initializing);\n processor.start();\n },\n stop: () => {\n processor.stop();\n statusManager.requestStateUpdate(DataSourceState.Closed);\n },\n close: () => {\n processor.close();\n statusManager.requestStateUpdate(DataSourceState.Closed);\n },\n };\n }\n}\n\nexport { BaseDataManager, DataSourceState, LDClientImpl, Requestor, makeRequestor };\n//# sourceMappingURL=index.mjs.map\n",null,null,null,null,"export default function escapeStringRegexp(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\t// Escape characters with special meaning either inside or outside character sets.\n\t// Use a simple backslash escape when it’s always valid, and a `\\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.\n\treturn string\n\t\t.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&')\n\t\t.replace(/-/g, '\\\\x2d');\n}\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["unescape","ref","indexOf","replace","AttributeReference","constructor","refOrLiteral","literal","literalVal","this","_components","isValid","redactionName","startsWith","match","reference","isLiteral","slice","substring","split","map","component","getComponents","get","target","components","current","index","length","Object","prototype","hasOwnProperty","call","Array","isArray","getComponent","depth","isKind","compare","other","every","value","InvalidReference","Type","typeName","example","_typeName","typeOf","is","u","getType","TypeArray","val","NumberWithMinimum","min","super","StringMatchingRegex","expression","DATE_REGEX","TypeValidators","createTypeArray","numberWithMin","stringMatchingRegex","isSingleKind","context","String","kind","isMultiKind","isLegacyUser","undefined","Number","ObjectOrFactory","factoryOrInstance","typeOfFactory","StringArray","Boolean","Function","Date","test","Kind","NullableBoolean","DEFAULT_KIND","encodeKey","key","includes","validKind","validKey","processPrivateAttributes","privateAttributes","literals","privateAttribute","Context","valid","message","_isMulti","_isUser","_wasLegacy","_contexts","_contextForError","_getValueFromContext","anonymous","_contextForKind","_context","_fromMultiKindContext","kinds","keys","filter","kindsValid","contextsAreObjects","contexts","reduce","acc","singleContext","kindOrContext","_meta","values","part","created","_privateAttributeReferences","_fromSingleKindContext","kindValid","keyValid","privateAttributeReferences","_fromLegacyUser","user","singleKindContext","custom","name","ip","firstName","lastName","email","avatar","country","privateAttributeNames","legacyToSingleKind","fromLDContext","toLDContext","getContexts","result","forEach","kindAndContext","nestedContext","valueForKind","canonicalKey","sort","join","kindsAndKeys","entries","legacy","UserKind","protectedAttributes","str","legacyTopLevelCopyAttributes","ContextFilter","_allAttributesPrivate","_privateAttributes","redactAnonymousAttributes","_filterSingleKind","filteredMulti","single","_getAttributesToFilter","redactAllAttributes","k","attr","some","protectedAttr","cloned","excluded","references","stack","push","ptr","source","parent","visited","item","pop","redactRef","find","a","b","cloneWithRedactions","redactedAttributes","DataSourceErrorKind","AutoEnvAttributes","LDEventType","LDDeliveryStatus","LDPollingError","Error","status","recoverable","LDStreamingError","code","tryStringify","toString","JSON","stringify","error","TypeError","escapes","s","d","toNumber","i","parseInt","toInt","f","parseFloat","toFloat","j","o","O","c","format","args","formatString","shift","out","char","charAt","nextChar","LogPriority","debug","info","warn","none","LevelNames","BasicLogger","options","_logLevel","level","_name","_destination","destination","_formatter","formatter","_tryFormat","_tryWrite","msg","console","_log","prefix","loggerRequirements","SafeLogger","logger","fallback","validator","_logger","_fallback","createSafeLogger","basicLogger","OptionMessages","deprecated","oldName","newName","optionBelowMinimum","unknownOption","wrongOptionType","expectedType","actualType","wrongOptionTypeBoolean","invalidTagValue","tagValueTooLong","partialEndpoint","regexValidator","tagValidator","ApplicationTags","tags","application","tagKeys","flatMap","ClientContext","sdkKey","configuration","platform","basicConfiguration","offline","serviceEndpoints","canonicalizeUri","uri","canonicalizePath","path","ServiceEndpoints","streaming","polling","events","DEFAULT_EVENTS","analyticsEventPath","diagnosticEventPath","includeAuthorizationHeader","payloadFilterKey","getWithParams","parameters","getStreamingUri","endpoints","canonicalizedPath","combinedParameters","getEventsUri","LDUnexpectedResponseError","LDClientError","LDTimeoutError","isHttpRecoverable","clone","obj","parse","secondsToMillis","sec","Math","trunc","deepCompact","ignoreKeys","isEmptyObject","fastDeepEqual","Map","size","has","Set","ArrayBuffer","isView","RegExp","flags","valueOf","httpErrorMessage","err","retryMessage","desc","shouldRetry","base64UrlEncode","encoding","btoa","ErrorKinds","ErrorKinds$1","ClientMessages$1","invalidMetricValue","badType","ClientMessages","MissingContextKeyNoEvent","EventSender","clientContext","baseHeaders","crypto","requests","_defaultHeaders","_eventsUri","_diagnosticEventsUri","_requests","_crypto","_tryPostingEvents","payloadId","canRetry","tryRes","Succeeded","headers","resHeaders","fetch","body","method","keepalive","serverDate","serverTime","isHttpLocallyRecoverable","FailedAndMustShutDown","Failed","async","delayMillis","Promise","resolve","setTimeout","sleep","sendEventData","type","data","AnalyticsEvents","randomUUID","isFeature","SummaryCounter","count","defValue","version","variation","default","increment","EventSummarizer","_startDate","_endDate","_counters","_contextKinds","summarizeEvent","event","excludeFromSummaries","countKey","counterKey","counter","add","creationDate","getSummary","features","flagSummary","counters","contextKinds","counterOut","unknown","startDate","endDate","clearSummary","LDInvalidSDKKeyError","shouldSample","ratio","truncated","floor","random","InputCustomEvent","metricValue","samplingRatio","url","now","InputEvalEvent","withReasons","trackEvents","prereqOf","reason","debugEventsUntilDate","InputIdentifyEvent","DataSourceState","freeze","__proto__","DiagnosticsManager","_platform","_diagnosticInitConfig","_streamInits","_startTime","_dataSinceDate","_id","diagnosticId","sdkKeySuffix","createInitEvent","sdkData","platformData","id","sdk","osArch","os","arch","osName","osVersion","additional","recordStreamInit","timestamp","failed","durationMillis","createStatsEventAndReset","droppedEvents","deduplicatedUsers","eventsInLastBatch","currentTime","evt","dataSinceDate","streamInits","EventFactoryBase","_withReasons","evalEvent","e","flagKey","defaultVal","addExperimentData","prereqOfFlagKey","unknownFlagEvent","defVal","identifyEvent","customEvent","EventProcessor","_config","_contextDeduplicator","_diagnosticsManager","start","_summarizer","_queue","_lastKnownPastTime","_droppedEvents","_deduplicatedUsers","_exceededCapacity","_eventsInLastBatch","_shutdown","_flushUsersTimer","_capacity","eventsCapacity","_eventSender","_contextFilter","allAttributesPrivate","flushInterval","setInterval","flush","_flushTimer","initEvent","_postDiagnosticEvent","_diagnosticsTimer","statsEvent","diagnosticRecordingInterval","DiagnosticEvent","close","clearInterval","eventsToFlush","summary","sendEvent","inputEvent","migrationEvent","_enqueue","isFeatureEvent","addFullEvent","addDebugEvent","_shouldDebugEvent","isIdentifyEvent","isIdentify","shouldNotDeduplicate","processContext","_makeOutputEvent","contextKeys","selector","res","NullEventProcessor","StreamingProcessor","streamUriPath","_listeners","_errorHandler","_streamInitialReconnectDelay","_headers","_streamUri","_logConnectionStarted","_connectionAttemptStartTime","_logConnectionResult","success","_retryAndHandleError","ErrorResponse","eventSource","createEventSource","errorFilter","initialRetryDelayMillis","readTimeoutMillis","retryResetIntervalMillis","_eventSource","onclose","onerror","onopen","onretrying","deserializeData","processJson","eventName","addEventListener","dataJson","errorHandler","InvalidData","reportJsonError","Unknown","stop","LDRequestError","Requestor","_uri","_method","_body","requestPayload","isOk","text","makeRequestor","plainContextString","paths","baseQueryParams","useReport","secureModeHash","pathReport","pathGet","getPollingUri","validators","maxCachedContexts","baseUri","streamUri","eventsUri","capacity","streamInitialReconnectDelay","diagnosticOptOut","sendEvents","pollInterval","applicationInfo","wrapperName","wrapperVersion","hooks","inspectors","DEFAULT_POLLING","DEFAULT_STREAM","ConfigurationImpl","pristineOptions","internalOptions","sendLDHeaders","_validateTypesAndNames","userAgentHeaderName","trackEventModifier","errors","v","validatorType","digest","hasher","asyncDigest","getOrGenerateKey","storageKey","storage","generatedKey","set","hashAndBase64Encode","input","createHash","update","noop","concatNamespacesAndValues","parts","all","transform","namespaceForContextData","environmentNamespace","isLegacyUser$1","isSingleKind$1","isMultiKind$1","internal","addDeviceInfo","ld_device","device","family","ldDeviceNamespace","namespaceForGeneratedContextKey","envAttributesVersion","addAutoEnv","config","ld_application","app","versionName","addApplicationInfo","contextCommon","toMulti","ensureKeyCommon","namespaceForAnonymousGeneratedContextKey","ensureKey","ensureKeySingle","multiContext","singleContexts","ensureKeyMulti","ensureKeyLegacy","createDiagnosticsManager","clientSideID","customBaseURI","customStreamURI","customEventsURI","eventsFlushIntervalMillis","reconnectTimeMillis","diagnosticRecordingIntervalMillis","usingSecureMode","bootstrapMode","createDiagnosticsInitConfig","createErrorEvaluationDetail","errorKind","def","variationIndex","createSuccessEvaluationDetail","EventFactory","evalEventClient","flag","trackReason","flagVersion","ContextIndex","container","fromJson","json","contextIndex","toJson","notice","entry","it","prune","maxContexts","clampedMax","max","splice","FlagPersistence","_environmentNamespace","_maxCachedContexts","_flagStore","_flagUpdater","_timeStamper","_indexKeyPromise","namespaceForContextIndex","init","newFlags","_storeCache","upsert","loadCached","flagsJson","clear","descriptors","initCached","_loadIndex","_contextIndex","pruned","allFlags","getAll","descriptor","jsonAll","DefaultFlagStore","_flags","insertOrUpdate","calculateChangedKeys","existingObject","newObject","changedKeys","subObject","FlagUpdater","flagStore","_changeCallbacks","_activeContextKey","oldFlags","changed","callback","currentValue","on","off","DefaultFlagManager","timeStamper","_flagPersistencePromise","_initPersistence","namespaceForEnvironment","setBootstrap","UNKNOWN_HOOK_NAME","BEFORE_EVALUATION_STAGE_NAME","AFTER_EVALUATION_STAGE_NAME","tryExecuteStage","hookName","stage","getHookName","hook","getMetadata","HookRunner","initialHooks","_hooks","withEvaluation","defaultValue","hookContext","hookData","beforeEvaluation","executeBeforeEvaluation","updatedData","hookIndex","afterEvaluation","executeAfterEvaluation","identify","timeout","beforeIdentify","executeBeforeIdentify","afterIdentify","executeAfterIdentify","addHook","FLAG_USED_TYPE","FLAG_DETAILS_CHANGED_TYPE","FLAG_DETAIL_CHANGED_TYPE","IDENTITY_CHANGED_TYPE","VALID__TYPES","InspectorManager","_safeInspectors","validInspectors","inspector","validateInspector","errorLogged","wrapper","synchronous","createSafeInspector","hasInspectors","onFlagUsed","detail","onFlagsChanged","onFlagChanged","onIdentityChanged","LDEmitter","listener","existingListeners","updated","fn","delete","_invokeListener","emit","listeners","eventNames","listenerCount","LDClientImpl","autoEnvAttributes","dataManagerFactory","_identifyTimeout","_highTimeoutThreshold","_eventFactoryDefault","_eventFactoryWithReasons","_eventSendingEnabled","inspectorManager","_baseHeaders","userAgentBase","authorization","defaultHeaders","_flagManager","_eventProcessor","diagnosticsManager","createEventProcessor","emitter","flagKeys","_handleInspectionChanged","ldContext","dataManager","_hookRunner","_inspectorManager","_result","deleted","_updateProcessor","getContext","_uncheckedContext","getInternalContext","_checkedContext","_createIdentifyPromise","rej","slow","reject","timed","t","taskName","_res","identifyPromise","race","catch","identifyResolve","identifyReject","pristineContext","identifyOptions","Enabled","checkedContext","then","track","_variationInternal","eventFactory","typeChecker","UserNotSpecified","evalContext","foundItem","FlagNotFound","prerequisites","matched","WrongType","successDetail","prereqKey","variationDetail","_typedEval","boolVariation","jsonVariation","numberVariation","stringVariation","boolVariationDetail","numberVariationDetail","stringVariationDetail","jsonVariationDetail","setEventSendingEnabled","enabled","details","DataSourceEventHandler","_statusManager","handlePut","requestStateUpdate","Valid","handlePatch","patchFlag","handleDelete","deleteFlag","handleStreamingError","reportError","handlePollingError","DataSourceStatusManager","_emitter","_state","Closed","_stateSinceMillis","state","stateSince","lastError","_errorInfo","_updateState","requestedState","isError","newState","Interrupted","Initializing","changedState","statusCode","errorInfo","time","PollingProcessor","_requestor","_pollIntervalSeconds","_dataHandler","_stopped","_poll","startTime","requestError","elapsed","sleepFor","_timeoutHandle","clearTimeout","_plainContextString","_dataSourceConfig","_pollingRequestor","getEventSourceCapabilities","customMethod","pathPing","queryParameters","methodAndBodyOverrides","payload","BaseDataManager","flagManager","credential","getPollingPaths","getStreamingPaths","dataSourceStatusManager","_dataSourceEventHandler","setConnectionParams","connectionParams","_connectionParams","createPollingProcessor","requestor","processor","updateProcessor","_decorateProcessorWithStatusReporting","createStreamingProcessor","pollingRequestor","createStreamListeners","statusManager","isDocument","document","isWindow","window","addDocumentEventListener","removeEventListener","addWindowEventListener","getHref","location","href","BrowserDataManager","_browserConfig","_forcedStreaming","_automaticStreamingState","_debugLog","browserIdentifyOptions","hash","_secureModeHash","bootstrap","_finishIdentifyFromBootstrap","_finishIdentifyFromPoll","_updateStreamingState","putListener","_a","NetworkError","_b","metadataKey","metadata","ret","assign","readFlagsFromBootstrap","setForcedStreaming","setAutomaticStreamingState","shouldBeStreaming","_startDataSource","_stopDataSource","_setupConnection","rawContext","registerStateDetection","requestFlush","removeDocListener","visibilityState","removeWindowListener","escapeStringRegexp","string","findGoalsForClick","clickGoals","matches","goal","elements","querySelectorAll","elementIndex","parentNode","GoalTracker","goals","onEvent","goalsMatchingUrl","urls","matcher","search","canonicalUrl","pattern","matchesUrl","pageviewGoals","clickHandler","clickGoal","_cleanup","DefaultLocationWatcher","_previousLocation","checkUrl","currentLocation","_watcherHandle","removeListener","_cleanupListeners","GoalManager","baseUrl","_reportError","_reportGoal","locationWatcherFactory","cb","_goals","_isTracking","_url","_watcher","_createTracker","initialize","_fetchGoals","startTracking","_tracker","optDefaults","fetchGoals","eventUrlTransformer","BrowserHasher","_webcrypto","algorithm","_data","_algorithm","combinedData","encoded","TextEncoder","encode","digestedBuffer","subtle","fromCharCode","Uint8Array","padStart","timeLow","end","timeMid","timeHiAndVersion","clockSeqHiAndReserved","clockSeqLow","nodes","hex","bytes","range","strVal","fallbackUuidV4","getRandomValues","typedArray","getRandom128bit","formatDataAsUuidV4","BrowserCrypto","getCrypto","BrowserEncoding","binString","from","byte","fromCodePoint","bytesToBase64","BrowserInfo","Backoff","_retryResetIntervalMillis","_random","_retryCount","_initialRetryDelayMillis","_maxExponent","ceil","log2","_backoff","exponent","delay","_jitter","computedDelayMillis","timeStampMs","_activeSince","fail","DefaultBrowserEventSource","_errorFilter","_openConnection","_es","EventSource","_handleError","_c","_reconnectTimeoutHandle","_tryConnect","delayMs","BrowserRequests","eventSourceInitDict","readTimeout","PlatformStorage","localStorage","removeItem","getItem","setItem","BrowserPlatform","LocalStorage","BrowserClient","clientSideId","overridePlatform","customLogger","validatedBrowserOptions","opts","output","applyBrowserDefaults","validateOptions","baseOptions","filterToBaseOptions","_encoding","highTimeoutThreshold","_goalManager","transformedUrl","isClick","automaticBackgroundHandling","setStreaming","_updateAutomaticStreamingState","Disabled"],"mappings":"AAaA,SAASA,EAASC,GACd,OAAOA,EAAIC,QAAQ,K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