@configdirector/vue-sdk 1.7.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/DefaultConfigDirectorClient-BSBC3rBa.cjs +5 -0
- package/dist/DefaultConfigDirectorClient-CgL72BvL.mjs +6 -0
- package/dist/DefaultConfigDirectorClient-CgL72BvL.mjs.map +1 -0
- package/dist/configdirector-vue-client-testing.cjs +1 -1
- package/dist/configdirector-vue-client-testing.d.cts +5 -14
- package/dist/configdirector-vue-client-testing.d.cts.map +1 -1
- package/dist/configdirector-vue-client-testing.d.mts +5 -14
- package/dist/configdirector-vue-client-testing.d.mts.map +1 -1
- package/dist/configdirector-vue-client-testing.mjs +1 -1
- package/dist/configdirector-vue-client-testing.mjs.map +1 -1
- package/dist/configdirector-vue-client.cjs +1 -1
- package/dist/configdirector-vue-client.d.cts +24 -6
- package/dist/configdirector-vue-client.d.cts.map +1 -1
- package/dist/configdirector-vue-client.d.mts +24 -6
- package/dist/configdirector-vue-client.d.mts.map +1 -1
- package/dist/configdirector-vue-client.mjs +1 -1
- package/dist/configdirector-vue-client.mjs.map +1 -1
- package/dist/{types-CXaEh4ok.d.mts → types-CFBLmqUM.d.cts} +70 -7
- package/dist/types-CFBLmqUM.d.cts.map +1 -0
- package/dist/{types-BOj-1-h2.d.cts → types-CrgXfAWw.d.mts} +70 -7
- package/dist/types-CrgXfAWw.d.mts.map +1 -0
- package/package.json +1 -1
- package/dist/DefaultConfigDirectorClient-B0E4jg9y.cjs +0 -5
- package/dist/DefaultConfigDirectorClient-B4x3i04O.mjs +0 -6
- package/dist/DefaultConfigDirectorClient-B4x3i04O.mjs.map +0 -1
- package/dist/types-BOj-1-h2.d.cts.map +0 -1
- package/dist/types-CXaEh4ok.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-vue-client.mjs","names":["createJsSdkLogger"],"sources":["../../shared/src/telemetry/utils.ts","../../shared/src/telemetry/InvalidContextSubmissions.ts","../../js-browser-client/src/telemetry/WebWorkerTelemetryClient.ts","../../shared/src/base62-encoder.ts","../../shared/src/value-id.ts","../../js-browser-client/src/telemetry/value-id-generator.ts","../../js-browser-client/src/BrowserConfigDirectorClient.ts","../src/logger.ts","../src/client.ts","../src/plugin.ts","../src/composables/util.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts"],"sourcesContent":["import type { ConfigType, ConfigValueType } from \"../types\";\nimport type { ValueIdGenerator, DroppedEvents } from \"./types\";\n\nconst CONFIG_VALUE_MAX_LENGTH = 500;\n\nexport type TelemetryValue = {\n value?: string;\n valueId?: string;\n type?: ConfigType;\n};\n\nexport type TelemetryEvaluationValue<TV extends ConfigValueType> = {\n value: TV;\n valueId?: string | null | undefined;\n type?: ConfigType;\n};\n\nexport const compactTelemetryValue = async (\n tv: TelemetryValue,\n valueIdGenerator: ValueIdGenerator,\n): Promise<TelemetryValue> => {\n if (tv.valueId) {\n return { valueId: tv.valueId };\n }\n if (tv.value) {\n if (tv.value.length <= CONFIG_VALUE_MAX_LENGTH && tv.type != \"json\") {\n return { value: tv.value };\n }\n\n return { valueId: await valueIdGenerator(tv.value) };\n }\n\n return tv;\n};\n\nexport const mapToTelemetryValue = <TV extends ConfigValueType>(\n ev: TelemetryEvaluationValue<TV>,\n): TelemetryValue => {\n if (ev.type === \"json\" || (ev.type == null && typeof ev.value === \"object\")) {\n if (ev.valueId) {\n return { valueId: ev.valueId, type: \"json\" };\n }\n try {\n const json = JSON.stringify(ev.value);\n return { value: json, type: \"json\" };\n } catch {\n return { value: ev.value.toString(), type: \"json\" };\n }\n }\n\n const stringValue = ev.value?.toString();\n if (stringValue && stringValue.length <= CONFIG_VALUE_MAX_LENGTH) {\n return { value: stringValue };\n }\n\n return ev.valueId ? { valueId: ev.valueId } : { value: stringValue };\n};\n\nexport const djb2Hash = (data: string): string => {\n const hash = djb2(new TextEncoder().encode(data));\n return hash.toString(16).padStart(8, \"0\");\n};\n\nconst djb2 = (bytes: Uint8Array): number => {\n let hash = 5381;\n for (let i = 0; i < bytes.length; i++) {\n hash = (hash << 5) + hash + (bytes[i] ?? 0);\n hash = hash >>> 0;\n }\n return hash;\n};\n\nexport const isEventListEmpty = <T extends Record<string | symbol, any[]>>(eventList: T): boolean => {\n const keys = Object.keys(eventList);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((eventList[key]?.length ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isDroppedEventsEmpty = (droppedEvents?: DroppedEvents): boolean => {\n if (!droppedEvents) {\n return true;\n }\n const keys = Object.keys(droppedEvents);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((droppedEvents[key] ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n","import type { InvalidContextEvent } from \"./telemetry-events\";\nimport type { AggregatedEvent } from \"./types\";\n\nexport const DISTINCT_KIND_SAMPLE_LIMIT = 20;\n\nexport type InvalidContextRecording =\n | \"new-kind-sample\"\n | \"known-kind-sample\"\n | \"first-beyond-sample-limit\"\n | \"beyond-sample-limit\";\n\nexport class InvalidContextSubmissions {\n private readonly countsByKindSample = new Map<string, number>();\n private countBeyondSampleLimit = 0;\n private startTime: Date | undefined;\n\n public record(kindSample: string): InvalidContextRecording {\n this.startTime ??= new Date();\n return this.add(kindSample, 1);\n }\n\n public absorb(entries: AggregatedEvent<InvalidContextEvent>[]): void {\n for (const entry of entries) {\n if (this.startTime === undefined || entry.startTime < this.startTime) {\n this.startTime = entry.startTime;\n }\n this.add(entry.event.kindSample, entry.count);\n }\n }\n\n private add(kindSample: string | undefined, count: number): InvalidContextRecording {\n if (kindSample !== undefined) {\n const knownCount = this.countsByKindSample.get(kindSample);\n if (knownCount !== undefined) {\n this.countsByKindSample.set(kindSample, knownCount + count);\n return \"known-kind-sample\";\n }\n if (this.countsByKindSample.size < DISTINCT_KIND_SAMPLE_LIMIT) {\n this.countsByKindSample.set(kindSample, count);\n return \"new-kind-sample\";\n }\n }\n const firstBeyondSampleLimit = this.countBeyondSampleLimit === 0;\n this.countBeyondSampleLimit += count;\n return firstBeyondSampleLimit ? \"first-beyond-sample-limit\" : \"beyond-sample-limit\";\n }\n\n public takeSnapshot(): AggregatedEvent<InvalidContextEvent>[] {\n const endTime = new Date();\n const startTime = this.startTime ?? endTime;\n const entryOf = (count: number, kindSample?: string): AggregatedEvent<InvalidContextEvent> => ({\n startTime,\n endTime,\n count,\n event: { reason: \"invalid-context-kind\", kindSample },\n });\n const sampledEntries = Array.from(this.countsByKindSample, ([kindSample, count]) =>\n entryOf(count, kindSample),\n );\n const entries =\n this.countBeyondSampleLimit > 0\n ? [...sampledEntries, entryOf(this.countBeyondSampleLimit)]\n : sampledEntries;\n this.clear();\n return entries;\n }\n\n private clear() {\n this.countsByKindSample.clear();\n this.countBeyondSampleLimit = 0;\n this.startTime = undefined;\n }\n}\n","import { type TelemetryEventCollectorOptions } from \"@shared/telemetry/TelemetryEventCollector\";\nimport type { ConfigDirectorContext, ConfigDirectorLogger, ConfigValueType } from \"@js-client-core/types\";\nimport type { TelemetryClient, EvaluatedConfigEvent } from \"@js-client-core/telemetry\";\nimport type {\n TelemetryCloseEvent,\n TelemetryEvaluatedConfigEvent,\n TelemetryFlushEvent,\n TelemetryInitializeEvent,\n TelemetryInvalidContextSubmissionsEvent,\n TelemetryUpdateContextEvent,\n TelemetryWorkerResponseEvent,\n} from \"./types\";\nimport type { TelemetryValue } from \"@shared/telemetry/utils\";\nimport { mapToTelemetryValue } from \"@shared/telemetry/utils\";\nimport { InvalidContextSubmissions } from \"@shared/telemetry/InvalidContextSubmissions\";\n\nconst DEFAULT_WORKER_CLOSE_TIMEOUT = 6_000;\n\nexport type WebWorkerTelemetryClientOptions = TelemetryEventCollectorOptions & {\n workerCloseTimeout?: number;\n};\n\nexport class WebWorkerTelemetryClient implements TelemetryClient {\n private readonly logger: ConfigDirectorLogger;\n private readonly initializeMessage: TelemetryInitializeEvent;\n private worker: Worker | undefined;\n private turnedOff = false;\n private readonly pendingEvaluations: TelemetryEvaluatedConfigEvent[] = [];\n private readonly pendingEvaluationLimit: number;\n private readonly pendingInvalidContextSubmissions = new InvalidContextSubmissions();\n private closePromise: Promise<void> | undefined;\n private closeResolve: (() => void) | undefined;\n private closeTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly workerCloseTimeout: number;\n private readonly visibilityHandler: () => void;\n\n constructor(options: WebWorkerTelemetryClientOptions) {\n this.logger = options.logger;\n this.workerCloseTimeout = options.workerCloseTimeout ?? DEFAULT_WORKER_CLOSE_TIMEOUT;\n this.pendingEvaluationLimit = options.evaluationQueueLimit ?? 1_000;\n\n this.initializeMessage = {\n type: \"Initialize\",\n payload: {\n sdkKey: options.sdkKey,\n sdkIdentity: options.sdkIdentity,\n metaContext: options.metaContext,\n baseUrl: options.baseUrl.toString(),\n evaluationQueueLimit: this.pendingEvaluationLimit,\n initialFlushIntervalDelay: options.initialFlushIntervalDelay ?? 5_000,\n flushIntervalDelay: options.flushIntervalDelay ?? 30_000,\n },\n };\n\n this.visibilityHandler = () => {\n if (document.visibilityState === \"hidden\") {\n this.flush();\n }\n };\n }\n\n private createWorkerOrTurnOff(): Worker | undefined {\n if (typeof Worker === \"undefined\") {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.\",\n );\n return undefined;\n }\n try {\n return new Worker(new URL(\"./worker.ts\", import.meta.url), { type: \"module\" });\n } catch (error) {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: \",\n error,\n );\n return undefined;\n }\n }\n\n private turnOff(warning: string, ...details: unknown[]) {\n this.turnedOff = true;\n this.pendingEvaluations.length = 0;\n this.logger.warn(warning, ...details);\n }\n\n private startWorker(): Worker | undefined {\n if (this.worker || this.turnedOff) {\n return this.worker;\n }\n const worker = this.createWorkerOrTurnOff();\n if (!worker) {\n return undefined;\n }\n worker.onmessage = (message: MessageEvent<TelemetryWorkerResponseEvent>) => {\n this.handleWorkerEvent(message.data);\n };\n worker.postMessage(this.initializeMessage);\n this.worker = worker;\n\n try {\n document.addEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[TelemetryEventCollector] Could not configure 'visibilitychange' listener: \", error);\n }\n\n for (const evaluation of this.pendingEvaluations) {\n worker.postMessage(evaluation);\n }\n this.pendingEvaluations.length = 0;\n this.forwardInvalidContextSubmissions(worker);\n return worker;\n }\n\n private forwardInvalidContextSubmissions(worker: Worker | undefined) {\n if (!worker) {\n return;\n }\n const entries = this.pendingInvalidContextSubmissions.takeSnapshot();\n if (entries.length === 0) {\n return;\n }\n const submissionsMessage: TelemetryInvalidContextSubmissionsEvent = {\n type: \"InvalidContextSubmissions\",\n payload: { entries },\n };\n worker.postMessage(submissionsMessage);\n }\n\n public async updateContext(value: ConfigDirectorContext | undefined) {\n if (this.closePromise) {\n return;\n }\n const updateContextMessage: TelemetryUpdateContextEvent = {\n type: \"UpdateContext\",\n payload: {\n context: value,\n },\n };\n this.startWorker()?.postMessage(updateContextMessage);\n }\n\n public evaluatedConfig<T extends ConfigValueType>(event: EvaluatedConfigEvent<T>): void {\n if (this.turnedOff) {\n return;\n }\n const evaluatedConfigMessage: TelemetryEvaluatedConfigEvent = {\n type: \"EvaluatedConfigEvent\",\n payload: this.sanitizeEvaluatedConfigEvent(event),\n };\n if (this.worker) {\n this.worker.postMessage(evaluatedConfigMessage);\n return;\n }\n if (this.pendingEvaluations.length >= this.pendingEvaluationLimit) {\n this.pendingEvaluations.shift();\n }\n this.pendingEvaluations.push(evaluatedConfigMessage);\n }\n\n public recordInvalidContext(kindSample: string): void {\n this.pendingInvalidContextSubmissions.record(kindSample);\n this.forwardInvalidContextSubmissions(this.worker);\n }\n\n private sanitizeEvaluatedConfigEvent<T extends ConfigValueType>(\n event: EvaluatedConfigEvent<T>,\n ): EvaluatedConfigEvent<TelemetryValue> {\n return {\n ...event,\n defaultValue: mapToTelemetryValue({ value: event.defaultValue, type: event.type }),\n evaluatedValue: mapToTelemetryValue({\n value: event.evaluatedValue,\n valueId: event.evaluatedValueId,\n type: event.type,\n }),\n };\n }\n\n private handleWorkerEvent(event: TelemetryWorkerResponseEvent) {\n if (event.type === \"Closed\") {\n this.finishClose();\n return;\n }\n if (!event.payload?.level || !event.payload?.message) {\n return;\n }\n const { level, message, args } = event.payload;\n\n switch (level) {\n case \"debug\":\n this.logger.debug(message, ...args);\n break;\n case \"info\":\n this.logger.info(message, ...args);\n break;\n case \"warn\":\n this.logger.warn(message, ...args);\n break;\n case \"error\":\n this.logger.error(message, ...args);\n break;\n }\n }\n\n private flush() {\n const flushMessage: TelemetryFlushEvent = {\n type: \"Flush\",\n };\n this.worker?.postMessage(flushMessage);\n }\n\n public close(): Promise<void> {\n if (this.closePromise) {\n return this.closePromise;\n }\n\n return this.performClose();\n }\n\n private performClose(): Promise<void> {\n const worker = this.worker;\n if (!worker) {\n this.pendingEvaluations.length = 0;\n this.closePromise = Promise.resolve();\n return this.closePromise;\n }\n try {\n document.removeEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: \", error);\n }\n this.closePromise = new Promise<void>((resolve) => {\n this.closeResolve = resolve;\n this.closeTimer = setTimeout(() => {\n this.logger.warn(\n \"[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.\",\n );\n this.finishClose();\n }, this.workerCloseTimeout);\n const closeMessage: TelemetryCloseEvent = { type: \"Close\" };\n worker.postMessage(closeMessage);\n });\n return this.closePromise;\n }\n\n private finishClose() {\n clearTimeout(this.closeTimer);\n this.closeTimer = undefined;\n this.worker?.terminate();\n this.closeResolve?.();\n }\n}\n","const BASE62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nexport const toBase62 = (buf: Uint8Array, length: number): string => {\n const ZERO = BigInt(0);\n const BASE = BigInt(62);\n const hex = Array.from(buf)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n let n = BigInt(\"0x\" + hex);\n let result = \"\";\n while (n > ZERO) {\n result = BASE62[Number(n % BASE)] + result;\n n /= BASE;\n }\n return result.padStart(length, \"0\");\n};\n","export const DIGEST_BYTES = 16;\nexport const BASE62_LENGTH = Math.ceil((DIGEST_BYTES * 8) / Math.log2(62));\n","import { toBase62 } from \"@shared/base62-encoder\";\nimport { DIGEST_BYTES, BASE62_LENGTH } from \"@shared/value-id\";\n\nconst encoder = new TextEncoder();\n\nexport const generateValueId = async (\n v: string | number | boolean | null | undefined,\n): Promise<string | undefined> => {\n if (typeof crypto === \"undefined\" || crypto.subtle == null) {\n return undefined;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encoder.encode(v?.toString() ?? \"\"));\n return toBase62(new Uint8Array(hashBuffer, 0, DIGEST_BYTES), BASE62_LENGTH);\n};\n","import {\n type ConfigDirectorClientOptions,\n type ConfigDirectorClient,\n type IdentifyingSdkOptions,\n createDefaultLogger,\n} from \"@js-client-core/index\";\nimport { WebWorkerTelemetryClient } from \"./telemetry/WebWorkerTelemetryClient\";\nimport { DefaultConfigDirectorClient } from \"@js-client-core/DefaultConfigDirectorClient\";\nimport { defaultUrlFactory, parseUrl } from \"@shared/url\";\nimport { CLIENT_BASE_URL } from \"@shared/constants\";\nimport { generateValueId } from \"./telemetry/value-id-generator\";\n\nexport const createBrowserClient = (\n clientSdkKey: string,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n const logger = clientOptions?.logger ?? createDefaultLogger();\n const baseUrl = parseUrl(clientOptions?.connection?.url) ?? CLIENT_BASE_URL;\n const telemetryClient = new WebWorkerTelemetryClient({\n sdkKey: clientSdkKey,\n sdkIdentity: {\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n },\n metaContext: {\n appName: clientOptions?.metadata?.appName,\n appVersion: clientOptions?.metadata?.appVersion,\n },\n logger: logger,\n baseUrl,\n urlFactory: defaultUrlFactory,\n valueIdGenerator: generateValueId,\n });\n\n return new DefaultConfigDirectorClient(telemetryClient, clientSdkKey, sdkOptions, {\n ...clientOptions,\n logger,\n });\n};\n","import type {\n ConfigDirectorLogMessageDecorator,\n ConfigDirectorLogger} from \"@js-browser-client/index\";\nimport {\n type ConfigDirectorLoggingLevel,\n createDefaultLogger as createJsSdkLogger,\n} from \"@js-browser-client/index\";\n\nclass MessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:vue-sdk] ${message}`;\n }\n}\n\nexport const createConsoleLogger = (level: ConfigDirectorLoggingLevel): ConfigDirectorLogger => {\n return createJsSdkLogger(level, new MessageDecorator());\n};\n","import type { ConfigDirectorClient, ConfigDirectorClientOptions } from \"@js-browser-client/index\";\nimport { createBrowserClient } from \"@js-browser-client/index\";\nimport type { ConfigDirectorPluginOptions } from \"./types\";\nimport { createConsoleLogger } from \"./logger\";\n\nexport const createClient = (\n clientSdkKey: string,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return createBrowserClient(clientSdkKey, { sdkName: \"vue-sdk\", sdkVersion: \"__VERSION__\" }, clientOptions);\n};\n\nexport const createClientFromPluginOptions = (options: ConfigDirectorPluginOptions): ConfigDirectorClient => {\n return createClient(options.sdkKey, {\n connection: {\n url: options.url,\n timeout: options.timeout,\n mode: options.mode,\n pollingInterval: options.pollingInterval,\n },\n metadata: { appName: options.appName, appVersion: options.appVersion },\n logger: options.logger ?? createConsoleLogger(\"warn\"),\n hooks: options.hooks,\n });\n};\n\nexport const initializeClient = async (\n options: ConfigDirectorPluginOptions,\n): Promise<ConfigDirectorClient> => {\n const client = createClientFromPluginOptions(options);\n await client.initialize(options.context);\n return client;\n};\n","import { readonly, ref, type InjectionKey, type Ref, type App } from \"vue\";\nimport type { ClientStatus, ConfigDirectorPluginOptions } from \"./types\";\nimport { createClientFromPluginOptions } from \"./client\";\nimport type { ConfigDirectorClient, ConfigDirectorContext } from \"@js-client-core/types\";\nimport { ConfigDirectorInitializationError } from \"@shared/errors\";\n\nexport const ConfigDirectorClientKey: InjectionKey<ConfigDirectorClient> = Symbol(\"ConfigDirector.Client\");\nexport const ConfigDirectorStatusKey: InjectionKey<Readonly<Ref<ClientStatus>>> = Symbol(\n \"ConfigDirector.ClientStatus\",\n);\nexport const ConfigDirectorContextKey: InjectionKey<Readonly<Ref<ConfigDirectorContext | undefined>>> =\n Symbol(\"ConfigDirector.Context\");\n\nexport const ConfigDirectorPlugin = {\n install: (app: App, optionsOrClient: ConfigDirectorPluginOptions | ConfigDirectorClient) => {\n const getClient = () => {\n if (isClientObject(optionsOrClient)) {\n return optionsOrClient as ConfigDirectorClient;\n } else if (isOptionsObject(optionsOrClient)) {\n return createClientFromPluginOptions(optionsOrClient as ConfigDirectorPluginOptions);\n } else {\n throw new ConfigDirectorInitializationError(\n \"The plugin options must be either an initialized ConfigDirectorClient, or a ConfigDirectorPluginOptions object with a valid client 'sdkKey'\",\n );\n }\n };\n\n const client = getClient();\n\n const status = ref<ClientStatus>(client.isReady ? \"ready\" : \"loading\");\n const readonlyStatus = readonly(status);\n client.on(\"clientReady\", () => (status.value = \"ready\"));\n\n const context = ref<ConfigDirectorContext | undefined>(optionsOrClient.context);\n const readonlyContext = readonly(context);\n client.on(\"contextUpdated\", ({ context: newContext }) => (context.value = newContext));\n\n if (!client.isReady && !client.isInitializing) {\n client.initialize(optionsOrClient.context).then(() => {\n if (!client.isReady) {\n // The client timed-out initialization and it is serving default values\n status.value = \"default\";\n }\n });\n }\n\n app.provide(ConfigDirectorClientKey, client);\n app.provide(ConfigDirectorStatusKey, readonlyStatus);\n app.provide(ConfigDirectorContextKey, readonlyContext);\n },\n};\n\nconst isClientObject = (options: ConfigDirectorPluginOptions | ConfigDirectorClient): options is ConfigDirectorClient => {\n const candidate = options as Partial<ConfigDirectorClient>;\n return (\n typeof candidate.initialize === \"function\" &&\n typeof candidate.getValue === \"function\" &&\n typeof candidate.watch === \"function\" &&\n typeof candidate.on === \"function\"\n );\n};\n\nconst isOptionsObject = (options: ConfigDirectorPluginOptions | ConfigDirectorClient) => {\n return typeof (options as ConfigDirectorPluginOptions).sdkKey === \"string\";\n};\n","import type { InjectionKey } from \"vue\";\nimport { inject } from \"vue\";\nimport { ConfigDirectorInitializationError } from \"@shared/errors\";\n\nexport const injectOrThrow = <T>(key: InjectionKey<T>): T => {\n const injected = inject(key);\n if (injected === undefined) {\n throw new ConfigDirectorInitializationError(\n `Could not inject ${key.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`,\n );\n }\n return injected;\n};\n","import type { ConfigDirectorClient } from \"@js-browser-client/index\";\nimport { ConfigDirectorClientKey } from \"../plugin\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useClient = (): { client: ConfigDirectorClient } => {\n const client = injectOrThrow(ConfigDirectorClientKey);\n return { client };\n};\n","import type { Ref } from \"vue\";\nimport { computed } from \"vue\";\nimport type { ClientStatus } from \"../types\";\nimport { injectOrThrow } from \"./util\";\nimport { ConfigDirectorStatusKey } from \"../plugin\";\n\nexport const useClientStatus = (): {\n readyStatus: Readonly<Ref<ClientStatus>>;\n loading: Readonly<Ref<boolean>>;\n} => {\n const readyStatus = injectOrThrow(ConfigDirectorStatusKey);\n const loading = computed(() => readyStatus.value === \"loading\");\n return { readyStatus, loading };\n};\n","import { shallowRef, onBeforeUnmount } from \"vue\";\nimport type { Ref, ShallowRef } from \"vue\";\nimport type { ConfigValueType } from \"@js-client-core/types\";\nimport type { ClientStatus } from \"../types\";\nimport { useClient } from \"./useClient\";\nimport { useClientStatus } from \"./useClientStatus\";\n\nexport const useConfigValue = <T extends ConfigValueType>(\n configKey: string,\n defaultValue: T,\n): { value: ShallowRef<T>; readyStatus: Readonly<Ref<ClientStatus>>; loading: Readonly<Ref<boolean>> } => {\n const { client } = useClient();\n const { readyStatus, loading } = useClientStatus();\n const configValue = shallowRef(client.getValue<T>(configKey, defaultValue)) as ShallowRef<T>;\n\n const watcher = (newValue: T) => (configValue.value = newValue);\n client.watch(configKey, defaultValue, watcher);\n\n onBeforeUnmount(() => client.unwatch(configKey, watcher));\n\n return { value: configValue, readyStatus, loading };\n};\n","import type { ConfigDirectorContext } from \"@js-browser-client/index\";\nimport { toRaw } from \"vue\";\nimport { ConfigDirectorContextKey } from \"../plugin\";\nimport { useClient } from \"./useClient\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useContext = () => {\n const { client } = useClient();\n const currentContext = injectOrThrow(ConfigDirectorContextKey);\n\n const updateContext = async (context: ConfigDirectorContext) => {\n const rawContext = toRaw(context);\n const oldContextJson = JSON.stringify(client.context);\n const newContextJson = JSON.stringify(rawContext);\n if (oldContextJson != newContextJson) {\n await client.updateContext(rawContext);\n }\n };\n\n return {\n context: currentContext,\n updateContext,\n };\n};\n"],"mappings":"2NAGA,MAgCa,EACX,GACmB,OACnB,GAAI,EAAG,OAAS,QAAW,EAAG,MAAQ,MAAQ,OAAO,EAAG,OAAU,SAAW,CAC3E,GAAI,EAAG,QACL,MAAO,CAAE,QAAS,EAAG,QAAS,KAAM,OAAQ,CAE9C,GAAI,CAEF,MAAO,CAAE,MADI,KAAK,UAAU,EAAG,MAAM,CACf,KAAM,OAAQ,SAC9B,CACN,MAAO,CAAE,MAAO,EAAG,MAAM,UAAU,CAAE,KAAM,OAAQ,EAIvD,IAAM,GAAA,EAAc,EAAG,QAAA,KAAA,IAAA,GAAA,EAAO,UAAU,CAKxC,OAJI,GAAe,EAAY,QAAU,IAChC,CAAE,MAAO,EAAa,CAGxB,EAAG,QAAU,CAAE,QAAS,EAAG,QAAS,CAAG,CAAE,MAAO,EAAa,EC5CtE,IAAa,EAAb,KAAuC,eACrC,KAAiB,mBAAqB,IAAI,IAC1C,KAAQ,uBAAyB,EAGjC,OAAc,EAA6C,CAEzD,OADA,KAAK,WA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B,GAChB,OAAQ,EAAwC,QAAW,SC3DvD,EAAoB,GAA4B,CAC3D,IAAM,EAAW,EAAO,EAAI,CAC7B,GAAI,IAAa,IAAA,GACd,MAAM,IAAI,EACR,oBAAoB,EAAI,YAAY,8EACrC,CAEH,OAAO,GCPI,OAEJ,CAAE,OADM,EAAc,EAAwB,CACpC,ECAN,MAGR,CACH,IAAM,EAAc,EAAc,EAAwB,CAE1D,MAAO,CAAE,cAAa,QADN,MAAe,EAAY,QAAU,UAAU,CAChC,ECLpB,GACX,EACA,IACwG,CACxG,GAAM,CAAE,UAAW,GAAW,CACxB,CAAE,cAAa,WAAY,GAAiB,CAC5C,EAAc,EAAW,EAAO,SAAY,EAAW,EAAa,CAAC,CAErE,EAAW,GAAiB,EAAY,MAAQ,EAKtD,OAJA,EAAO,MAAM,EAAW,EAAc,EAAQ,CAE9C,MAAsB,EAAO,QAAQ,EAAW,EAAQ,CAAC,CAElD,CAAE,MAAO,EAAa,cAAa,UAAS,ECdxC,MAAmB,CAC9B,GAAM,CAAE,UAAW,GAAW,CAY9B,MAAO,CACL,QAZqB,EAAc,EAAyB,CAa5D,cAXoB,KAAO,IAAmC,CAC9D,IAAM,EAAa,EAAM,EAAQ,CACV,KAAK,UAAU,EAAO,QAAQ,EAC9B,KAAK,UAAU,EAAW,EAE/C,MAAM,EAAO,cAAc,EAAW,EAOzC"}
|
|
1
|
+
{"version":3,"file":"configdirector-vue-client.mjs","names":["createJsSdkLogger"],"sources":["../../shared/src/telemetry/utils.ts","../../shared/src/telemetry/InvalidContextSubmissions.ts","../../js-browser-client/src/telemetry/WebWorkerTelemetryClient.ts","../../shared/src/base62-encoder.ts","../../shared/src/value-id.ts","../../js-browser-client/src/telemetry/value-id-generator.ts","../../js-browser-client/src/local-storage-caching-provider.ts","../../js-browser-client/src/BrowserConfigDirectorClient.ts","../src/logger.ts","../src/client.ts","../src/plugin.ts","../src/composables/util.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts"],"sourcesContent":["import type { ConfigType, ConfigValueType } from \"../types\";\nimport type { ValueIdGenerator, DroppedEvents } from \"./types\";\n\nconst CONFIG_VALUE_MAX_LENGTH = 500;\n\nexport type TelemetryValue = {\n value?: string;\n valueId?: string;\n type?: ConfigType;\n};\n\nexport type TelemetryEvaluationValue<TV extends ConfigValueType> = {\n value: TV;\n valueId?: string | null | undefined;\n type?: ConfigType;\n};\n\nexport const compactTelemetryValue = async (\n tv: TelemetryValue,\n valueIdGenerator: ValueIdGenerator,\n): Promise<TelemetryValue> => {\n if (tv.valueId) {\n return { valueId: tv.valueId };\n }\n if (tv.value) {\n if (tv.value.length <= CONFIG_VALUE_MAX_LENGTH && tv.type != \"json\") {\n return { value: tv.value };\n }\n\n return { valueId: await valueIdGenerator(tv.value) };\n }\n\n return tv;\n};\n\nexport const mapToTelemetryValue = <TV extends ConfigValueType>(\n ev: TelemetryEvaluationValue<TV>,\n): TelemetryValue => {\n if (ev.type === \"json\" || (ev.type == null && typeof ev.value === \"object\")) {\n if (ev.valueId) {\n return { valueId: ev.valueId, type: \"json\" };\n }\n try {\n const json = JSON.stringify(ev.value);\n return { value: json, type: \"json\" };\n } catch {\n return { value: ev.value.toString(), type: \"json\" };\n }\n }\n\n const stringValue = ev.value?.toString();\n if (stringValue && stringValue.length <= CONFIG_VALUE_MAX_LENGTH) {\n return { value: stringValue };\n }\n\n return ev.valueId ? { valueId: ev.valueId } : { value: stringValue };\n};\n\nexport const djb2Hash = (data: string): string => {\n const hash = djb2(new TextEncoder().encode(data));\n return hash.toString(16).padStart(8, \"0\");\n};\n\nconst djb2 = (bytes: Uint8Array): number => {\n let hash = 5381;\n for (let i = 0; i < bytes.length; i++) {\n hash = (hash << 5) + hash + (bytes[i] ?? 0);\n hash = hash >>> 0;\n }\n return hash;\n};\n\nexport const isEventListEmpty = <T extends Record<string | symbol, any[]>>(eventList: T): boolean => {\n const keys = Object.keys(eventList);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((eventList[key]?.length ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isDroppedEventsEmpty = (droppedEvents?: DroppedEvents): boolean => {\n if (!droppedEvents) {\n return true;\n }\n const keys = Object.keys(droppedEvents);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((droppedEvents[key] ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n","import type { InvalidContextEvent } from \"./telemetry-events\";\nimport type { AggregatedEvent } from \"./types\";\n\nexport const DISTINCT_KIND_SAMPLE_LIMIT = 20;\n\nexport type InvalidContextRecording =\n | \"new-kind-sample\"\n | \"known-kind-sample\"\n | \"first-beyond-sample-limit\"\n | \"beyond-sample-limit\";\n\nexport class InvalidContextSubmissions {\n private readonly countsByKindSample = new Map<string, number>();\n private countBeyondSampleLimit = 0;\n private startTime: Date | undefined;\n\n public record(kindSample: string): InvalidContextRecording {\n this.startTime ??= new Date();\n return this.add(kindSample, 1);\n }\n\n public absorb(entries: AggregatedEvent<InvalidContextEvent>[]): void {\n for (const entry of entries) {\n if (this.startTime === undefined || entry.startTime < this.startTime) {\n this.startTime = entry.startTime;\n }\n this.add(entry.event.kindSample, entry.count);\n }\n }\n\n private add(kindSample: string | undefined, count: number): InvalidContextRecording {\n if (kindSample !== undefined) {\n const knownCount = this.countsByKindSample.get(kindSample);\n if (knownCount !== undefined) {\n this.countsByKindSample.set(kindSample, knownCount + count);\n return \"known-kind-sample\";\n }\n if (this.countsByKindSample.size < DISTINCT_KIND_SAMPLE_LIMIT) {\n this.countsByKindSample.set(kindSample, count);\n return \"new-kind-sample\";\n }\n }\n const firstBeyondSampleLimit = this.countBeyondSampleLimit === 0;\n this.countBeyondSampleLimit += count;\n return firstBeyondSampleLimit ? \"first-beyond-sample-limit\" : \"beyond-sample-limit\";\n }\n\n public takeSnapshot(): AggregatedEvent<InvalidContextEvent>[] {\n const endTime = new Date();\n const startTime = this.startTime ?? endTime;\n const entryOf = (count: number, kindSample?: string): AggregatedEvent<InvalidContextEvent> => ({\n startTime,\n endTime,\n count,\n event: { reason: \"invalid-context-kind\", kindSample },\n });\n const sampledEntries = Array.from(this.countsByKindSample, ([kindSample, count]) =>\n entryOf(count, kindSample),\n );\n const entries =\n this.countBeyondSampleLimit > 0\n ? [...sampledEntries, entryOf(this.countBeyondSampleLimit)]\n : sampledEntries;\n this.clear();\n return entries;\n }\n\n private clear() {\n this.countsByKindSample.clear();\n this.countBeyondSampleLimit = 0;\n this.startTime = undefined;\n }\n}\n","import { type TelemetryEventCollectorOptions } from \"@shared/telemetry/TelemetryEventCollector\";\nimport type { ConfigDirectorContext, ConfigDirectorLogger, ConfigValueType } from \"@js-client-core/types\";\nimport type { TelemetryClient, EvaluatedConfigEvent } from \"@js-client-core/telemetry\";\nimport type {\n TelemetryCloseEvent,\n TelemetryEvaluatedConfigEvent,\n TelemetryFlushEvent,\n TelemetryInitializeEvent,\n TelemetryInvalidContextSubmissionsEvent,\n TelemetryUpdateContextEvent,\n TelemetryWorkerResponseEvent,\n} from \"./types\";\nimport type { TelemetryValue } from \"@shared/telemetry/utils\";\nimport { mapToTelemetryValue } from \"@shared/telemetry/utils\";\nimport { InvalidContextSubmissions } from \"@shared/telemetry/InvalidContextSubmissions\";\n\nconst DEFAULT_WORKER_CLOSE_TIMEOUT = 6_000;\n\nexport type WebWorkerTelemetryClientOptions = TelemetryEventCollectorOptions & {\n workerCloseTimeout?: number;\n};\n\nexport class WebWorkerTelemetryClient implements TelemetryClient {\n private readonly logger: ConfigDirectorLogger;\n private readonly initializeMessage: TelemetryInitializeEvent;\n private worker: Worker | undefined;\n private turnedOff = false;\n private readonly pendingEvaluations: TelemetryEvaluatedConfigEvent[] = [];\n private readonly pendingEvaluationLimit: number;\n private readonly pendingInvalidContextSubmissions = new InvalidContextSubmissions();\n private closePromise: Promise<void> | undefined;\n private closeResolve: (() => void) | undefined;\n private closeTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly workerCloseTimeout: number;\n private readonly visibilityHandler: () => void;\n\n constructor(options: WebWorkerTelemetryClientOptions) {\n this.logger = options.logger;\n this.workerCloseTimeout = options.workerCloseTimeout ?? DEFAULT_WORKER_CLOSE_TIMEOUT;\n this.pendingEvaluationLimit = options.evaluationQueueLimit ?? 1_000;\n\n this.initializeMessage = {\n type: \"Initialize\",\n payload: {\n sdkKey: options.sdkKey,\n sdkIdentity: options.sdkIdentity,\n metaContext: options.metaContext,\n baseUrl: options.baseUrl.toString(),\n evaluationQueueLimit: this.pendingEvaluationLimit,\n initialFlushIntervalDelay: options.initialFlushIntervalDelay ?? 5_000,\n flushIntervalDelay: options.flushIntervalDelay ?? 30_000,\n },\n };\n\n this.visibilityHandler = () => {\n if (document.visibilityState === \"hidden\") {\n this.flush();\n }\n };\n }\n\n private createWorkerOrTurnOff(): Worker | undefined {\n if (typeof Worker === \"undefined\") {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.\",\n );\n return undefined;\n }\n try {\n return new Worker(new URL(\"./worker.ts\", import.meta.url), { type: \"module\" });\n } catch (error) {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: \",\n error,\n );\n return undefined;\n }\n }\n\n private turnOff(warning: string, ...details: unknown[]) {\n this.turnedOff = true;\n this.pendingEvaluations.length = 0;\n this.logger.warn(warning, ...details);\n }\n\n private startWorker(): Worker | undefined {\n if (this.worker || this.turnedOff) {\n return this.worker;\n }\n const worker = this.createWorkerOrTurnOff();\n if (!worker) {\n return undefined;\n }\n worker.onmessage = (message: MessageEvent<TelemetryWorkerResponseEvent>) => {\n this.handleWorkerEvent(message.data);\n };\n worker.postMessage(this.initializeMessage);\n this.worker = worker;\n\n try {\n document.addEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[TelemetryEventCollector] Could not configure 'visibilitychange' listener: \", error);\n }\n\n for (const evaluation of this.pendingEvaluations) {\n worker.postMessage(evaluation);\n }\n this.pendingEvaluations.length = 0;\n this.forwardInvalidContextSubmissions(worker);\n return worker;\n }\n\n private forwardInvalidContextSubmissions(worker: Worker | undefined) {\n if (!worker) {\n return;\n }\n const entries = this.pendingInvalidContextSubmissions.takeSnapshot();\n if (entries.length === 0) {\n return;\n }\n const submissionsMessage: TelemetryInvalidContextSubmissionsEvent = {\n type: \"InvalidContextSubmissions\",\n payload: { entries },\n };\n worker.postMessage(submissionsMessage);\n }\n\n public async updateContext(value: ConfigDirectorContext | undefined) {\n if (this.closePromise) {\n return;\n }\n const updateContextMessage: TelemetryUpdateContextEvent = {\n type: \"UpdateContext\",\n payload: {\n context: value,\n },\n };\n this.startWorker()?.postMessage(updateContextMessage);\n }\n\n public evaluatedConfig<T extends ConfigValueType>(event: EvaluatedConfigEvent<T>): void {\n if (this.turnedOff) {\n return;\n }\n const evaluatedConfigMessage: TelemetryEvaluatedConfigEvent = {\n type: \"EvaluatedConfigEvent\",\n payload: this.sanitizeEvaluatedConfigEvent(event),\n };\n if (this.worker) {\n this.worker.postMessage(evaluatedConfigMessage);\n return;\n }\n if (this.pendingEvaluations.length >= this.pendingEvaluationLimit) {\n this.pendingEvaluations.shift();\n }\n this.pendingEvaluations.push(evaluatedConfigMessage);\n }\n\n public recordInvalidContext(kindSample: string): void {\n this.pendingInvalidContextSubmissions.record(kindSample);\n this.forwardInvalidContextSubmissions(this.worker);\n }\n\n private sanitizeEvaluatedConfigEvent<T extends ConfigValueType>(\n event: EvaluatedConfigEvent<T>,\n ): EvaluatedConfigEvent<TelemetryValue> {\n return {\n ...event,\n defaultValue: mapToTelemetryValue({ value: event.defaultValue, type: event.type }),\n evaluatedValue: mapToTelemetryValue({\n value: event.evaluatedValue,\n valueId: event.evaluatedValueId,\n type: event.type,\n }),\n };\n }\n\n private handleWorkerEvent(event: TelemetryWorkerResponseEvent) {\n if (event.type === \"Closed\") {\n this.finishClose();\n return;\n }\n if (!event.payload?.level || !event.payload?.message) {\n return;\n }\n const { level, message, args } = event.payload;\n\n switch (level) {\n case \"debug\":\n this.logger.debug(message, ...args);\n break;\n case \"info\":\n this.logger.info(message, ...args);\n break;\n case \"warn\":\n this.logger.warn(message, ...args);\n break;\n case \"error\":\n this.logger.error(message, ...args);\n break;\n }\n }\n\n private flush() {\n const flushMessage: TelemetryFlushEvent = {\n type: \"Flush\",\n };\n this.worker?.postMessage(flushMessage);\n }\n\n public close(): Promise<void> {\n if (this.closePromise) {\n return this.closePromise;\n }\n\n return this.performClose();\n }\n\n private performClose(): Promise<void> {\n const worker = this.worker;\n if (!worker) {\n this.pendingEvaluations.length = 0;\n this.closePromise = Promise.resolve();\n return this.closePromise;\n }\n try {\n document.removeEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: \", error);\n }\n this.closePromise = new Promise<void>((resolve) => {\n this.closeResolve = resolve;\n this.closeTimer = setTimeout(() => {\n this.logger.warn(\n \"[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.\",\n );\n this.finishClose();\n }, this.workerCloseTimeout);\n const closeMessage: TelemetryCloseEvent = { type: \"Close\" };\n worker.postMessage(closeMessage);\n });\n return this.closePromise;\n }\n\n private finishClose() {\n clearTimeout(this.closeTimer);\n this.closeTimer = undefined;\n this.worker?.terminate();\n this.closeResolve?.();\n }\n}\n","const BASE62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nexport const toBase62 = (buf: Uint8Array, length: number): string => {\n const ZERO = BigInt(0);\n const BASE = BigInt(62);\n const hex = Array.from(buf)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n let n = BigInt(\"0x\" + hex);\n let result = \"\";\n while (n > ZERO) {\n result = BASE62[Number(n % BASE)] + result;\n n /= BASE;\n }\n return result.padStart(length, \"0\");\n};\n","export const DIGEST_BYTES = 16;\nexport const BASE62_LENGTH = Math.ceil((DIGEST_BYTES * 8) / Math.log2(62));\n","import { toBase62 } from \"@shared/base62-encoder\";\nimport { DIGEST_BYTES, BASE62_LENGTH } from \"@shared/value-id\";\n\nconst encoder = new TextEncoder();\n\nexport const generateValueId = async (\n v: string | number | boolean | null | undefined,\n): Promise<string | undefined> => {\n if (typeof crypto === \"undefined\" || crypto.subtle == null) {\n return undefined;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encoder.encode(v?.toString() ?? \"\"));\n return toBase62(new Uint8Array(hashBuffer, 0, DIGEST_BYTES), BASE62_LENGTH);\n};\n","import type { CachingProvider } from \"@js-client-core/index\";\nimport { CACHED_VALUES_STORAGE_KEY_PREFIX, DEFAULT_CACHING_SIZE_LIMIT_BYTES } from \"@js-client-core/cached-values\";\nimport { localStorageIfAvailable } from \"@js-client-core/browser-globals\";\n\nconst toHex = (bytes: Uint8Array): string =>\n Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\nconst storageKeyFor = async (clientSdkKey: string): Promise<string> => {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(clientSdkKey));\n return CACHED_VALUES_STORAGE_KEY_PREFIX + toHex(new Uint8Array(digest));\n};\n\nconst subtleCryptoAvailable = (): boolean => typeof crypto !== \"undefined\" && crypto.subtle != null;\n\nexport const localStorageCachingProvider = (clientSdkKey: string): CachingProvider | undefined => {\n const storage = localStorageIfAvailable();\n if (!storage || !subtleCryptoAvailable()) {\n return undefined;\n }\n const storageKey = storageKeyFor(clientSdkKey);\n return {\n read: async () => storage.getItem(await storageKey),\n write: async (value) => storage.setItem(await storageKey, value),\n remove: async () => storage.removeItem(await storageKey),\n sizeLimit: () => DEFAULT_CACHING_SIZE_LIMIT_BYTES,\n };\n};\n","import {\n type ConfigDirectorClientOptions,\n type ConfigDirectorClient,\n type IdentifyingSdkOptions,\n type OfflineClientOptions,\n} from \"@js-client-core/index\";\nimport { WebWorkerTelemetryClient } from \"./telemetry/WebWorkerTelemetryClient\";\nimport { DefaultConfigDirectorClient } from \"@js-client-core/DefaultConfigDirectorClient\";\nimport { defaultUrlFactory } from \"@shared/url\";\nimport { generateValueId } from \"./telemetry/value-id-generator\";\nimport { localStorageCachingProvider } from \"./local-storage-caching-provider\";\n\n/**\n * Creates a browser client. With a client SDK key it connects to ConfigDirector; with\n * {@link OfflineClientOptions} alone it runs in `offline` mode and serves `connection.values`. An\n * absent key with `clientOptions` is the same as the options alone when their mode is `offline`,\n * and fails like a missing key otherwise.\n */\nexport const createBrowserClient = (\n clientSdkKeyOrOptions: string | OfflineClientOptions | undefined,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return DefaultConfigDirectorClient.from(\n ({ clientSdkKey, baseUrl, logger, metadata }) =>\n new WebWorkerTelemetryClient({\n sdkKey: clientSdkKey,\n sdkIdentity: {\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n },\n metaContext: {\n appName: metadata?.appName,\n appVersion: metadata?.appVersion,\n },\n logger,\n baseUrl,\n urlFactory: defaultUrlFactory,\n valueIdGenerator: generateValueId,\n }),\n clientSdkKeyOrOptions,\n sdkOptions,\n clientOptions,\n { platformCachingProvider: localStorageCachingProvider },\n );\n};\n","import type {\n ConfigDirectorLogMessageDecorator,\n ConfigDirectorLogger} from \"@js-browser-client/index\";\nimport {\n type ConfigDirectorLoggingLevel,\n createDefaultLogger as createJsSdkLogger,\n} from \"@js-browser-client/index\";\n\nclass MessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:vue-sdk] ${message}`;\n }\n}\n\nexport const createConsoleLogger = (level: ConfigDirectorLoggingLevel): ConfigDirectorLogger => {\n return createJsSdkLogger(level, new MessageDecorator());\n};\n","import type { ConfigDirectorClient, ConfigDirectorClientOptions } from \"@js-browser-client/index\";\nimport { createBrowserClient } from \"@js-browser-client/index\";\nimport type { ConfigDirectorPluginOptions } from \"./types\";\nimport { createConsoleLogger } from \"./logger\";\n\nconst createClient = (\n clientSdkKey: string | undefined,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return createBrowserClient(clientSdkKey, { sdkName: \"vue-sdk\", sdkVersion: \"__VERSION__\" }, clientOptions);\n};\n\nexport const createClientFromPluginOptions = (options: ConfigDirectorPluginOptions): ConfigDirectorClient => {\n return createClient(options.sdkKey, {\n connection: {\n url: options.url,\n timeout: options.timeout,\n mode: options.mode,\n pollingInterval: options.pollingInterval,\n values: options.values,\n },\n metadata: { appName: options.appName, appVersion: options.appVersion },\n logger: options.logger ?? createConsoleLogger(\"warn\"),\n hooks: options.hooks,\n caching: options.caching,\n });\n};\n\nexport const initializeClient = async (\n options: ConfigDirectorPluginOptions,\n): Promise<ConfigDirectorClient> => {\n const client = createClientFromPluginOptions(options);\n await client.initialize(options.context);\n return client;\n};\n","import { readonly, ref, type InjectionKey, type Ref, type App } from \"vue\";\nimport type { ClientStatus, ConfigDirectorPluginOptions } from \"./types\";\nimport { createClientFromPluginOptions } from \"./client\";\nimport type { ConfigDirectorClient, ConfigDirectorContext } from \"@js-client-core/types\";\n\nexport const ConfigDirectorClientKey: InjectionKey<ConfigDirectorClient> = Symbol(\"ConfigDirector.Client\");\nexport const ConfigDirectorStatusKey: InjectionKey<Readonly<Ref<ClientStatus>>> = Symbol(\n \"ConfigDirector.ClientStatus\",\n);\nexport const ConfigDirectorContextKey: InjectionKey<Readonly<Ref<ConfigDirectorContext | undefined>>> =\n Symbol(\"ConfigDirector.Context\");\n\nexport const ConfigDirectorPlugin = {\n install: (app: App, optionsOrClient: ConfigDirectorPluginOptions | ConfigDirectorClient) => {\n const client = isClientObject(optionsOrClient)\n ? optionsOrClient\n : createClientFromPluginOptions(optionsOrClient);\n\n const status = ref<ClientStatus>(client.isReady ? \"ready\" : \"loading\");\n const readonlyStatus = readonly(status);\n client.on(\"clientReady\", () => (status.value = \"ready\"));\n\n const context = ref<ConfigDirectorContext | undefined>(optionsOrClient.context);\n const readonlyContext = readonly(context);\n client.on(\"contextUpdated\", ({ context: newContext }) => (context.value = newContext));\n\n if (!client.isReady && !client.isInitializing) {\n client.initialize(optionsOrClient.context).then(() => {\n if (!client.isReady) {\n // The client timed-out initialization and it is serving default values\n status.value = \"default\";\n }\n });\n }\n\n app.provide(ConfigDirectorClientKey, client);\n app.provide(ConfigDirectorStatusKey, readonlyStatus);\n app.provide(ConfigDirectorContextKey, readonlyContext);\n },\n};\n\nconst isClientObject = (options: ConfigDirectorPluginOptions | ConfigDirectorClient): options is ConfigDirectorClient => {\n const candidate = options as Partial<ConfigDirectorClient>;\n return (\n typeof candidate.initialize === \"function\" &&\n typeof candidate.getValue === \"function\" &&\n typeof candidate.watch === \"function\" &&\n typeof candidate.on === \"function\"\n );\n};\n","import type { InjectionKey } from \"vue\";\nimport { inject } from \"vue\";\nimport { ConfigDirectorInitializationError } from \"@shared/errors\";\n\nexport const injectOrThrow = <T>(key: InjectionKey<T>): T => {\n const injected = inject(key);\n if (injected === undefined) {\n throw new ConfigDirectorInitializationError(\n `Could not inject ${key.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`,\n );\n }\n return injected;\n};\n","import type { ConfigDirectorClient } from \"@js-browser-client/index\";\nimport { ConfigDirectorClientKey } from \"../plugin\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useClient = (): { client: ConfigDirectorClient } => {\n const client = injectOrThrow(ConfigDirectorClientKey);\n return { client };\n};\n","import type { Ref } from \"vue\";\nimport { computed } from \"vue\";\nimport type { ClientStatus } from \"../types\";\nimport { injectOrThrow } from \"./util\";\nimport { ConfigDirectorStatusKey } from \"../plugin\";\n\nexport const useClientStatus = (): {\n readyStatus: Readonly<Ref<ClientStatus>>;\n loading: Readonly<Ref<boolean>>;\n} => {\n const readyStatus = injectOrThrow(ConfigDirectorStatusKey);\n const loading = computed(() => readyStatus.value === \"loading\");\n return { readyStatus, loading };\n};\n","import { shallowRef, onBeforeUnmount } from \"vue\";\nimport type { Ref, ShallowRef } from \"vue\";\nimport type { ConfigValueType } from \"@js-client-core/types\";\nimport type { ClientStatus } from \"../types\";\nimport { useClient } from \"./useClient\";\nimport { useClientStatus } from \"./useClientStatus\";\n\nexport const useConfigValue = <T extends ConfigValueType>(\n configKey: string,\n defaultValue: T,\n): { value: ShallowRef<T>; readyStatus: Readonly<Ref<ClientStatus>>; loading: Readonly<Ref<boolean>> } => {\n const { client } = useClient();\n const { readyStatus, loading } = useClientStatus();\n const configValue = shallowRef(client.getValue<T>(configKey, defaultValue)) as ShallowRef<T>;\n\n const watcher = (newValue: T) => (configValue.value = newValue);\n client.watch(configKey, defaultValue, watcher);\n\n onBeforeUnmount(() => client.unwatch(configKey, watcher));\n\n return { value: configValue, readyStatus, loading };\n};\n","import type { ConfigDirectorContext } from \"@js-browser-client/index\";\nimport { toRaw } from \"vue\";\nimport { ConfigDirectorContextKey } from \"../plugin\";\nimport { useClient } from \"./useClient\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useContext = () => {\n const { client } = useClient();\n const currentContext = injectOrThrow(ConfigDirectorContextKey);\n\n const updateContext = async (context: ConfigDirectorContext) => {\n const rawContext = toRaw(context);\n const oldContextJson = JSON.stringify(client.context);\n const newContextJson = JSON.stringify(rawContext);\n if (oldContextJson != newContextJson) {\n await client.updateContext(rawContext);\n }\n };\n\n return {\n context: currentContext,\n updateContext,\n };\n};\n"],"mappings":"6NAGA,MAgCa,EACX,GACmB,OACnB,GAAI,EAAG,OAAS,QAAW,EAAG,MAAQ,MAAQ,OAAO,EAAG,OAAU,SAAW,CAC3E,GAAI,EAAG,QACL,MAAO,CAAE,QAAS,EAAG,QAAS,KAAM,OAAQ,CAE9C,GAAI,CAEF,MAAO,CAAE,MADI,KAAK,UAAU,EAAG,MAAM,CACf,KAAM,OAAQ,SAC9B,CACN,MAAO,CAAE,MAAO,EAAG,MAAM,UAAU,CAAE,KAAM,OAAQ,EAIvD,IAAM,GAAA,EAAc,EAAG,QA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,EAAyB,CAa5D,cAXoB,KAAO,IAAmC,CAC9D,IAAM,EAAa,EAAM,EAAQ,CACV,KAAK,UAAU,EAAO,QAAQ,EAC9B,KAAK,UAAU,EAAW,EAE/C,MAAM,EAAO,cAAc,EAAW,EAOzC"}
|
|
@@ -20,7 +20,7 @@ interface ConfigDirectorLogger {
|
|
|
20
20
|
warn(message: string, ...args: any): void;
|
|
21
21
|
error(message: string, ...args: any): void;
|
|
22
22
|
}
|
|
23
|
-
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
|
|
23
|
+
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
|
|
24
24
|
type ConfigEvaluation = {
|
|
25
25
|
key: string;
|
|
26
26
|
value: ConfigValueType;
|
|
@@ -39,9 +39,11 @@ type ConfigDirectorContext = {
|
|
|
39
39
|
* The context's identifier. This should be a value that uniquely identifies the user or other
|
|
40
40
|
* entity among contexts of the same {@link kind}.
|
|
41
41
|
* In the case of anonymous users, you could generate a UUID or alternatively not provide
|
|
42
|
-
* the {@link id}
|
|
43
|
-
*
|
|
44
|
-
*
|
|
42
|
+
* the {@link id}. In a client SDK, ConfigDirector then derives an identifier from an ID the SDK
|
|
43
|
+
* stores for the app install or the website, so it stays the same until the app is uninstalled
|
|
44
|
+
* or the site's data is cleared. However, keep in mind that this value is used for segmenting
|
|
45
|
+
* contexts in percentage rollouts, and changes to the {@link id} could result in the context
|
|
46
|
+
* being assigned to a different percentile.
|
|
45
47
|
*/
|
|
46
48
|
id?: string;
|
|
47
49
|
/**
|
|
@@ -77,15 +79,75 @@ type ConfigDirectorContext = {
|
|
|
77
79
|
*/
|
|
78
80
|
anonymous?: boolean;
|
|
79
81
|
};
|
|
80
|
-
type ConnectionMode = "streaming" | "polling";
|
|
82
|
+
type ConnectionMode = "streaming" | "polling" | "offline";
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region ../shared/src/native-values.d.ts
|
|
85
|
+
type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
|
|
86
|
+
[key: string]: NativeJsonValue;
|
|
87
|
+
};
|
|
88
|
+
type NativeValue = boolean | number | string | NativeJsonValue[] | {
|
|
89
|
+
[key: string]: NativeJsonValue;
|
|
90
|
+
};
|
|
91
|
+
type NativeValues = Record<string, NativeValue>;
|
|
81
92
|
//#endregion
|
|
82
93
|
//#region ../js-client-core/src/types.d.ts
|
|
94
|
+
/**
|
|
95
|
+
* A store for the values the client keeps on the device between launches. One provider instance
|
|
96
|
+
* serves one client: the provider decides where the entry lives, and the SDK owns the entry's
|
|
97
|
+
* format, which may change between SDK versions.
|
|
98
|
+
*/
|
|
99
|
+
type CachingProvider = {
|
|
100
|
+
/**
|
|
101
|
+
* Returns the stored entry, or `null` or `undefined` when nothing is stored.
|
|
102
|
+
*/
|
|
103
|
+
read(): string | null | undefined | Promise<string | null | undefined>;
|
|
104
|
+
/**
|
|
105
|
+
* Replaces the stored entry. The SDK never writes an entry larger than {@link sizeLimit}.
|
|
106
|
+
*/
|
|
107
|
+
write(value: string): void | Promise<void>;
|
|
108
|
+
/**
|
|
109
|
+
* Removes the stored entry.
|
|
110
|
+
*/
|
|
111
|
+
remove(): void | Promise<void>;
|
|
112
|
+
/**
|
|
113
|
+
* The largest entry, in UTF-8 bytes, the provider accepts. When the values received from
|
|
114
|
+
* ConfigDirector exceed it, the SDK removes the stored entry and keeps nothing on the device.
|
|
115
|
+
*/
|
|
116
|
+
sizeLimit(): number;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Options for the values the client keeps on the device, served on the next launch of the same
|
|
120
|
+
* context until live values arrive. Ignored in `offline` mode.
|
|
121
|
+
*/
|
|
122
|
+
type CachingOptions = {
|
|
123
|
+
/**
|
|
124
|
+
* Whether to keep the last values received on the device. Defaults to `true`.
|
|
125
|
+
*/
|
|
126
|
+
enabled?: boolean;
|
|
127
|
+
/**
|
|
128
|
+
* The store for the values. Defaults to the platform's own store: `localStorage` in the
|
|
129
|
+
* browser, AsyncStorage on React Native.
|
|
130
|
+
*/
|
|
131
|
+
provider?: CachingProvider;
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* One value an offline client serves for a config key. The config type follows from the value: a
|
|
135
|
+
* boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
|
|
136
|
+
* or array (`json`).
|
|
137
|
+
*/
|
|
138
|
+
type OfflineValue = NativeValue;
|
|
139
|
+
/**
|
|
140
|
+
* The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
|
|
141
|
+
* value's config type is decided. Every context receives the same value.
|
|
142
|
+
*/
|
|
143
|
+
type OfflineValues = NativeValues;
|
|
83
144
|
type ClientHooks = {
|
|
84
145
|
clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
|
|
85
146
|
configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
|
|
86
147
|
contextUpdated?: HookHandler<"contextUpdated"> | HookHandler<"contextUpdated">[];
|
|
87
148
|
configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
|
|
88
149
|
connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
|
|
150
|
+
cachedValuesLoaded?: HookHandler<"cachedValuesLoaded"> | HookHandler<"cachedValuesLoaded">[];
|
|
89
151
|
};
|
|
90
152
|
type ClientConnectAction = "initialization" | "context update" | "network resume";
|
|
91
153
|
type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
|
|
@@ -106,6 +168,7 @@ type ClientEvents = {
|
|
|
106
168
|
connectionError: {
|
|
107
169
|
error: Error;
|
|
108
170
|
};
|
|
171
|
+
cachedValuesLoaded: Record<string, never>;
|
|
109
172
|
};
|
|
110
173
|
type WatchHandler<T extends ConfigValueType> = (message: T) => void;
|
|
111
174
|
/**
|
|
@@ -227,5 +290,5 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
|
|
|
227
290
|
dispose(): void;
|
|
228
291
|
}
|
|
229
292
|
//#endregion
|
|
230
|
-
export {
|
|
231
|
-
//# sourceMappingURL=types-
|
|
293
|
+
export { OfflineValue as a, NativeValue as c, ConfigDirectorLogger as d, ConfigDirectorLoggingLevel as f, ConfigDirectorClient as i, NativeValues as l, ConnectionMode as m, CachingProvider as n, OfflineValues as o, ConfigValueType as p, ClientHooks as r, NativeJsonValue as s, CachingOptions as t, ConfigDirectorContext as u };
|
|
294
|
+
//# sourceMappingURL=types-CFBLmqUM.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-CFBLmqUM.d.cts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts"],"mappings":";KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAevD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,KAOhB,gBAAA;AAAA,KAWA,gBA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
|
|
23
|
-
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
|
|
23
|
+
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
|
|
24
24
|
type ConfigEvaluation = {
|
|
25
25
|
key: string;
|
|
26
26
|
value: ConfigValueType;
|
|
@@ -39,9 +39,11 @@ type ConfigDirectorContext = {
|
|
|
39
39
|
* The context's identifier. This should be a value that uniquely identifies the user or other
|
|
40
40
|
* entity among contexts of the same {@link kind}.
|
|
41
41
|
* In the case of anonymous users, you could generate a UUID or alternatively not provide
|
|
42
|
-
* the {@link id}
|
|
43
|
-
*
|
|
44
|
-
*
|
|
42
|
+
* the {@link id}. In a client SDK, ConfigDirector then derives an identifier from an ID the SDK
|
|
43
|
+
* stores for the app install or the website, so it stays the same until the app is uninstalled
|
|
44
|
+
* or the site's data is cleared. However, keep in mind that this value is used for segmenting
|
|
45
|
+
* contexts in percentage rollouts, and changes to the {@link id} could result in the context
|
|
46
|
+
* being assigned to a different percentile.
|
|
45
47
|
*/
|
|
46
48
|
id?: string;
|
|
47
49
|
/**
|
|
@@ -77,15 +79,75 @@ type ConfigDirectorContext = {
|
|
|
77
79
|
*/
|
|
78
80
|
anonymous?: boolean;
|
|
79
81
|
};
|
|
80
|
-
type ConnectionMode = "streaming" | "polling";
|
|
82
|
+
type ConnectionMode = "streaming" | "polling" | "offline";
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region ../shared/src/native-values.d.ts
|
|
85
|
+
type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
|
|
86
|
+
[key: string]: NativeJsonValue;
|
|
87
|
+
};
|
|
88
|
+
type NativeValue = boolean | number | string | NativeJsonValue[] | {
|
|
89
|
+
[key: string]: NativeJsonValue;
|
|
90
|
+
};
|
|
91
|
+
type NativeValues = Record<string, NativeValue>;
|
|
81
92
|
//#endregion
|
|
82
93
|
//#region ../js-client-core/src/types.d.ts
|
|
94
|
+
/**
|
|
95
|
+
* A store for the values the client keeps on the device between launches. One provider instance
|
|
96
|
+
* serves one client: the provider decides where the entry lives, and the SDK owns the entry's
|
|
97
|
+
* format, which may change between SDK versions.
|
|
98
|
+
*/
|
|
99
|
+
type CachingProvider = {
|
|
100
|
+
/**
|
|
101
|
+
* Returns the stored entry, or `null` or `undefined` when nothing is stored.
|
|
102
|
+
*/
|
|
103
|
+
read(): string | null | undefined | Promise<string | null | undefined>;
|
|
104
|
+
/**
|
|
105
|
+
* Replaces the stored entry. The SDK never writes an entry larger than {@link sizeLimit}.
|
|
106
|
+
*/
|
|
107
|
+
write(value: string): void | Promise<void>;
|
|
108
|
+
/**
|
|
109
|
+
* Removes the stored entry.
|
|
110
|
+
*/
|
|
111
|
+
remove(): void | Promise<void>;
|
|
112
|
+
/**
|
|
113
|
+
* The largest entry, in UTF-8 bytes, the provider accepts. When the values received from
|
|
114
|
+
* ConfigDirector exceed it, the SDK removes the stored entry and keeps nothing on the device.
|
|
115
|
+
*/
|
|
116
|
+
sizeLimit(): number;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Options for the values the client keeps on the device, served on the next launch of the same
|
|
120
|
+
* context until live values arrive. Ignored in `offline` mode.
|
|
121
|
+
*/
|
|
122
|
+
type CachingOptions = {
|
|
123
|
+
/**
|
|
124
|
+
* Whether to keep the last values received on the device. Defaults to `true`.
|
|
125
|
+
*/
|
|
126
|
+
enabled?: boolean;
|
|
127
|
+
/**
|
|
128
|
+
* The store for the values. Defaults to the platform's own store: `localStorage` in the
|
|
129
|
+
* browser, AsyncStorage on React Native.
|
|
130
|
+
*/
|
|
131
|
+
provider?: CachingProvider;
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* One value an offline client serves for a config key. The config type follows from the value: a
|
|
135
|
+
* boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
|
|
136
|
+
* or array (`json`).
|
|
137
|
+
*/
|
|
138
|
+
type OfflineValue = NativeValue;
|
|
139
|
+
/**
|
|
140
|
+
* The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
|
|
141
|
+
* value's config type is decided. Every context receives the same value.
|
|
142
|
+
*/
|
|
143
|
+
type OfflineValues = NativeValues;
|
|
83
144
|
type ClientHooks = {
|
|
84
145
|
clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
|
|
85
146
|
configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
|
|
86
147
|
contextUpdated?: HookHandler<"contextUpdated"> | HookHandler<"contextUpdated">[];
|
|
87
148
|
configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
|
|
88
149
|
connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
|
|
150
|
+
cachedValuesLoaded?: HookHandler<"cachedValuesLoaded"> | HookHandler<"cachedValuesLoaded">[];
|
|
89
151
|
};
|
|
90
152
|
type ClientConnectAction = "initialization" | "context update" | "network resume";
|
|
91
153
|
type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
|
|
@@ -106,6 +168,7 @@ type ClientEvents = {
|
|
|
106
168
|
connectionError: {
|
|
107
169
|
error: Error;
|
|
108
170
|
};
|
|
171
|
+
cachedValuesLoaded: Record<string, never>;
|
|
109
172
|
};
|
|
110
173
|
type WatchHandler<T extends ConfigValueType> = (message: T) => void;
|
|
111
174
|
/**
|
|
@@ -227,5 +290,5 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
|
|
|
227
290
|
dispose(): void;
|
|
228
291
|
}
|
|
229
292
|
//#endregion
|
|
230
|
-
export {
|
|
231
|
-
//# sourceMappingURL=types-
|
|
293
|
+
export { OfflineValue as a, NativeValue as c, ConfigDirectorLogger as d, ConfigDirectorLoggingLevel as f, ConfigDirectorClient as i, NativeValues as l, ConnectionMode as m, CachingProvider as n, OfflineValues as o, ConfigValueType as p, ClientHooks as r, NativeJsonValue as s, CachingOptions as t, ConfigDirectorContext as u };
|
|
294
|
+
//# sourceMappingURL=types-CrgXfAWw.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-CrgXfAWw.d.mts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts"],"mappings":";KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAevD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,KAOhB,gBAAA;AAAA,KAWA,gBAAA;EACV,GAAA;EACA,KAAA,EAAO,eAAA;EACP,OAAA;EACA,cAAA;EACA,MAAA,EAAQ,gBAAA;EACR,OAAA,GAAU,qBAAA;AAAA;;;;;;KAOA,qBAAA;ED5DoD;;;;;;;;;;ECuE9D,EAAA;EDxEoE;;;;;;;;;;;ECqFpE,IAAA;EDnFA;;;;ECyFA,IAAA;;AAvFF;;;EA6FE,MAAA;IAAA,CAAY,GAAA;EAAA;EA3Fa;;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WAAuB,eAAA,KAAoB,OAAA,EAAS,CAAA;;;;;;;;;;UAW/C,oBAAA,SAA6B,aAAA,CAAc,YAAA;EAhCf;;;;;;;;;;;;;;;;EAiD3C,UAAA,CAAW,OAAA,GAAU,qBAAA,GAAwB,OAAA;EA5CuB;AAGtE;;;;;AAEA;;;EAkDE,aAAA,CAAc,OAAA,EAAS,qBAAA,GAAwB,OAAA;EAlDsB;;;;;;;;;EAAA,IA6DjE,OAAA,IAAW,qBAAA;EA7D0E;AAE3F;;;;;EAF2F,IAqErF,OAAA;EA9DsB;;;;;;;EAAA,IAuEtB,cAAA;EA1EW;;;;;;;;;EAqFf,QAAA,WAAmB,eAAA,EAAiB,SAAA,UAAmB,YAAA,EAAc,CAAA,GAAI,CAAA;EAlF/C;;;;;AAI5B;;;;;;EA2FE,KAAA,WAAgB,eAAA,EAAiB,SAAA,UAAmB,YAAA,EAAc,CAAA,EAAG,QAAA,EAAU,YAAA,CAAa,CAAA;EA3FvC;;;AAWvD;;;;;EA0FE,OAAA,WAAkB,eAAA,EAAiB,SAAA,UAAmB,QAAA,GAAW,YAAA,CAAa,CAAA;EA9DvD;;;EAmEvB,UAAA;EA5BqE;;;;;;;EAqCrE,YAAA;EAdiE;;;;EAoBjE,aAAA,IAAiB,OAAA;EA9G2B;;;;;;EAsH5C,OAAA;AAAA"}
|
package/package.json
CHANGED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
var e=class{constructor(){this.handlerMap=new Map}on(e,t){let n=this.handlerMap.get(e);n?n.push(t):this.handlerMap.set(e,[t])}once(e,t){let n=this;function r(i){n.off(e,r),t.apply(n,i)}this.on(e,r)}off(e,t){let n=this.handlerMap.get(e);if(n)if(t){let e=n.indexOf(t);e>=0&&n.splice(e,1)}else this.handlerMap.set(e,[])}clear(){this.handlerMap.clear()}emit(e,t){let n=this.handlerMap.get(e);n&&n.slice().map(e=>e(t))}},t=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},n=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}},i=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},a=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},o=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},s=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},c=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
-
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
3
|
-
`&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){this.onComment?.(this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
|
|
4
|
-
`)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent({...this.currentEvent,id:this.lastEventId,data:e}),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
|
|
5
|
-
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:/^\d+$/.test(e.value)&&this.onRetry?.(Number.parseInt(e.value,10));break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let l=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var u=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=l.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===l.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=l.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=l.CONNECTING,this._fetch(this.url,{...this.requestOptions,body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`}).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new a(`The server response did not have a body`);this._readyState=l.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new c({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new i(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=l.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...this.headers,...e}}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=l.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new s(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new o(`${n} must be a function`);return e}};const d=e=>new u(e);var f=class{constructor(t){this.options=t,this.eventEmitter=new e,this.connectionGeneration=0,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/sse/v1`,t.baseUrl)}async connect(e,t){let n=++this.connectionGeneration,r=await this.options.clientSession;if(n!==this.connectionGeneration)return this;this.eventSource&&this.close();let i=new Promise((t,n)=>{this.eventSource=d({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:this.options.fetch,body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:r.instanceId,ephemeral:r.ephemeral}),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),t(this)},shouldReconnect:e=>{let t=!this.isStatusFatal(e.status);if(!t){let t=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,t),n(t)}return t},calculateReconnectDelay:e=>{let t=this.options.connectionRetryDelay(e.attempt),n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onError:e=>{this.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});return clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,Promise.race([i,new Promise(e=>{this.timeoutTimer=setTimeout(()=>e(this),t)})]).finally(()=>clearTimeout(this.timeoutTimer))}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,n){let r=e??0;return new t(`${`Connection failed with status: ${e??`unknown`}.`}${n?` Error: ${n}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){this.connectionGeneration++,this.eventSource?.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const p=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},m=e=>e===`number`||e===`bigint`,h=new Set([`boolean`,`integer`,`float`]),g=(e,t)=>{let n=e.value,r=p(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return x(n,t,r,e.valueId);if(typeof t==`string`)return h.has(e.type)?{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}:{parsedValue:n,parsedValueId:e.valueId,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&(e.type===`boolean`||e.type===`string`||e.type===`enum`)){let i=_(n),a=typeof i==`boolean`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-boolean`}}if(m(typeof t)&&e.type===`integer`){let i=v(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(m(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=ee(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},_=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},v=e=>{let t=y(e);return t==null?void 0:Math.trunc(t)},ee=e=>y(e),y=e=>{if(!e||!b(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},b=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},x=(e,t,n,r)=>{if(typeof t==`string`)return{parsedValue:e,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`};try{let i=JSON.parse(e);return S(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch{return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},S=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},C={off:-1,error:0,warn:1,info:2,debug:3},w=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,{...e,fractionalSecondDigits:3})}catch{return new Intl.DateTimeFormat(void 0,e)}};var T=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=w()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){C[this.level]>=C[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},E=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const D=(e,t)=>new T(e??`warn`,t??new E),O=(e,t)=>new URL(e,t?.toString()),k=e=>{if(e)try{return new URL(e)}catch(t){throw new n(`Invalid URL '${e}'. Parsing failed: ${t}`)}},A=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},j=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),M=`configdirector-sdk:instance-id`,N=1e3,P=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,F=(e,t)=>{let n=t;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0},I=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=F(n,2166136261);return F(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},L=()=>{try{return globalThis.localStorage??void 0}catch{return}},R=e=>{if(!e||typeof e!=`object`)return!1;let{v:t,id:n,createdAt:r,checksum:i}=e;return t!==1||typeof n!=`string`||typeof i!=`string`||typeof r!=`number`||!Number.isInteger(r)||r<=0||!P.test(n)?!1:i===I(n,r)},z=async(e,t)=>{let n;try{n=await e.getItem(M)}catch(e){return t.debug(`[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one`,e),{outcome:`failed`}}if(typeof n!=`string`||n===``)return{outcome:`nothing usable`};let r;try{r=JSON.parse(n)}catch{return t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`),{outcome:`nothing usable`}}if(!R(r))return t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`};let i=Date.now()-r.createdAt;return i<0||i>=216e5?(t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`),{outcome:`nothing usable`}):{outcome:`stored`,instanceId:r.id}},B=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:I(t,r)};try{return await e.setItem(M,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},V=async(e,t,n,r)=>{let i=await z(e,r);switch(i.outcome){case`stored`:return{instanceId:i.instanceId};case`failed`:return{instanceId:t,ephemeral:!0};case`nothing usable`:break}return n.passed?{instanceId:t,ephemeral:!0}:await B(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},H=(e,t=L())=>{let n=j();if(!t)return e.debug(`[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id`),Promise.resolve({instanceId:n,ephemeral:!0});let r={passed:!1},i,a=new Promise(t=>{i=setTimeout(()=>{r.passed=!0,e.warn(`[ConfigDirectorClient] The instance id storage did not respond within ${N}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},N)});return Promise.race([V(t,n,r,e),a]).finally(()=>clearTimeout(i))};var U=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.close(),this.prepareFatalResponseStatusError(e.status,await e.text())):new t(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new t(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new t(`Failed to parse the response from the server: ${e}`):new t(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,n){let r=e??0;return new t(`${`Connection failed with status: ${e??`unknown`}`}${(n?.trim()?.length??0)>0?` (${n})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return e?.name===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const W=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var G=class extends U{constructor(t){super(),this.options=t,this.eventEmitter=new e,this.connectionGeneration=0,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/polling/v1`,t.baseUrl),this.pollingIntervalSeconds=t.pollingInterval??60}async connect(e,t){let n=++this.connectionGeneration;this.clearPollingInterval();let r=await this.options.clientSession;if(n!==this.connectionGeneration)return this;try{await this.fetchConfigs(e,t,r)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e,t,r).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}close(){this.connectionGeneration++,super.close()}async fetchConfigs(e,t,n){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let r=await W(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:n.instanceId,ephemeral:n.ephemeral,lastUpdateTimestamp:this.lastUpdateTimestamp})},this.logger);if(await this.handleNonOkResponse(r),r.status==200){let e=JSON.parse(await r.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{this.handleFetchError(e)}catch(e){throw this.fatalError&&this.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}};const K=e=>{try{return e(globalThis)}catch{return}},q=()=>K(e=>e.navigator?.userAgent),J=()=>K(e=>e.location?.host),Y=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,X=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!Y(t))return!1;return!0},Z=e=>e==null||typeof e==`string`&&X(e),Q=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},$=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},te=e=>{let t=e?.kind;return Z(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:$(Q(t),128)}};var ne=class{constructor(t,n,r,i,a){this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=i?.logger??D(),this.clientSession=H(this.logger,a?.instanceIdStorage),this.timeout=i?.connection?.timeout??3e3,this.validateSdkKeyPresence(n);let o=a?.urlFactory??O,s=this.parseUrl(i?.connection?.url,o)??`https://client-sdk-api.configdirector.com`;this.connectionMode=i?.connection?.mode??`streaming`,this.telemetryClient=t,this.transport=a?.transport??this.buildTransport(n,r,s,o,i,a),this.transport.on(`configSetReceived`,e=>{this.hasReceivedConfigSet=!0,this.readyResolve?.();let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs={...this.configSet.configs,...e.configs};let n=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.initializing=!1,this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,i?.hooks?.clientReady),this.registerHandler(`configEvaluated`,i?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,i?.hooks?.configsUpdated),this.registerHandler(`contextUpdated`,i?.hooks?.contextUpdated),this.registerHandler(`connectionError`,i?.hooks?.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=A(e,{defaultSeconds:60,minimumSeconds:30});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTransport(e,t,n,r,i,a){return new(this.getTransportConstructor(this.connectionMode))({clientSession:this.clientSession,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:{...i?.metadata,sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:q(),host:J()},logger:this.logger,fetch:a?.fetch,connectionRetryDelay:a?.connectionRetryDelay??(e=>2**Math.min(e,9)*1e3),pollingInterval:this.resolvePollingIntervalForMode(i?.connection?.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return G;default:return f}}async initialize(e){this.hasReceivedConfigSet||(this.initializing=!0),await this.submitContext(e,`initialization`)}async updateContext(e){await this.submitContext(e,`context update`)}async submitContext(e,t){await this.connectToTransport(this.contextToConnectWith(e,t),t)}contextToConnectWith(e,t){let n=te(e);switch(n.outcome){case`admitted`:return n.context;case`ignored`:this.logger.error(`[ConfigDirectorClient] Ignored the context supplied for ${t} because its kind '${n.kindSample}' is invalid; connecting as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),this.telemetryClient.recordInvalidContext(n.kindSample);return}}get context(){return this.currentContext}async connectToTransport(e,t){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.initializing=!1,this.emit(`clientReady`,{action:t}),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let n=new Date().getTime();await this.transport.connect(e??{},this.timeout,t),this.currentContext=e,this.telemetryClient.updateContext(e).catch(e=>this.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,e)),this.emit(`contextUpdated`,{context:e});let r=new Date().getTime()-n,i=this.timeout-r;clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,i>0&&await Promise.race([this.readyPromise,new Promise(e=>{this.timeoutTimer=setTimeout(()=>e(),i)})]).finally(()=>clearTimeout(this.timeoutTimer)),this.ready||this.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${this.timeout}ms. The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`)}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.getValueFromConfigState(e,t,n.defaultValue);n.handler(r)})}watch(e,t,n){this.validateDefaultValue(t);let r=this.handlersMap.get(e),i={handler:n,defaultValue:t,requestedType:typeof t};return r?r.push(i):this.handlersMap.set(e,[i]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t){this.validateDefaultValue(t);let n=this.configSet?.configs[e];return this.getValueFromConfigState(e,n,t)}getValueFromConfigState(e,t,n){if(!t){this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:p(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let r=g(t,n);return this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,type:t.type,key:e,defaultValue:n,requestedType:r.requestedType,evaluatedValue:r.parsedValue,evaluatedValueId:r.parsedValueId,usedDefault:r.usedDefault,evaluationReason:r.reason}),this.dispatchEvaluationEvent({key:e,value:r.parsedValue,valueId:r.parsedValueId??void 0,isDefaultValue:r.usedDefault,reason:r.reason,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),r.parsedValue}dispatchEvaluationEvent(e){setTimeout(()=>this.emit(`configEvaluated`,{evaluation:e}),0)}emit(e,t){try{this.eventEmitter.emit(e,t)}catch(t){this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${e}'`,t)}}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new n(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new n(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new n(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new n(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}get isInitializing(){return this.initializing}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}pauseNetwork(){this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1}async resumeNetwork(){await this.connectToTransport(this.currentContext,`network resume`)}async close(){this.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(this.timeoutTimer),this.readyResolve?.(!0),this.telemetryClient.close().catch(e=>this.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,e)),this.transport.close(),this.ready=!1,this.initializing=!1}dispose(){this.clear(),this.close()}};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return`https://client-sdk-api.configdirector.com`}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return ne}});
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
var e=class{constructor(){this.handlerMap=new Map}on(e,t){let n=this.handlerMap.get(e);n?n.push(t):this.handlerMap.set(e,[t])}once(e,t){let n=this;function r(i){n.off(e,r),t.apply(n,i)}this.on(e,r)}off(e,t){let n=this.handlerMap.get(e);if(n)if(t){let e=n.indexOf(t);e>=0&&n.splice(e,1)}else this.handlerMap.set(e,[])}clear(){this.handlerMap.clear()}emit(e,t){let n=this.handlerMap.get(e);n&&n.slice().map(e=>e(t))}},t=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},n=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}},i=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},a=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},o=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},s=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}};function c(e){"@babel/helpers - typeof";return c=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},c(e)}function l(e,t){if(c(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(c(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function u(e){var t=l(e,`string`);return c(t)==`symbol`?t:t+``}function d(e,t,n){return(t=u(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function p(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?f(Object(n),!0).forEach(function(t){d(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var m=class{constructor(e){var t;this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=(t=e.onEvent)==null?(()=>{}):t,this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
-
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
3
|
-
`&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){var t;(t=this.onComment)==null||t.call(this,this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
|
|
4
|
-
`)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent(p(p({},this.currentEvent),{},{id:this.lastEventId,data:e})),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
|
|
5
|
-
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:if(/^\d+$/.test(e.value)){var t;(t=this.onRetry)==null||t.call(this,Number.parseInt(e.value,10))}break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let h=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var g=class{constructor(e){var t,n;this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=h.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers=p({Accept:`text/event-stream`},e.headers);let r=e.body;this.body=typeof r==`function`?r:()=>r,this.requestOptions={method:(t=e.method)==null?`GET`:t,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=(n=e.fetch)==null?((e,t)=>fetch(e,t)):n,this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===h.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=h.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=h.CONNECTING,this._fetch(this.url,p(p({},this.requestOptions),{},{body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`})).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){var t=this;let{body:n,status:r}=e;if(r===204){t.disconnected();return}if(r>=400){t.scheduleReconnect({status:r});return}if(!n)throw new a(`The server response did not have a body`);t._readyState=h.OPEN,t._onConnect(),t.reconnectAttempt=0;let o=new m({onEvent:e=>{typeof e.id==`string`&&(t.lastEventId=e.id),t._onMessage(e)},onComment:e=>t._onComment(e),onRetry:e=>t.serverReconnectionTime=e});await t.readResponseStream(n,o),t.scheduleReconnect({status:r,error:new i(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=h.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return p(p({},this.headers),e)}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=h.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new s(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new o(`${n} must be a function`);return e}};const _=e=>new g(e);var v=class{constructor(t){this.options=t,this.eventEmitter=new e,this.connectionGeneration=0,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/sse/v1`,t.baseUrl)}async connect(e,t){var n=this;let r=++n.connectionGeneration,i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;n.eventSource&&n.close();let a=new Promise((t,r)=>{n.eventSource=_({url:n.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:n.options.fetch,body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:i.instanceId,ephemeral:i.ephemeral}),onMessage:({data:e})=>{n.dispatchMessage(e)},onConnect:()=>{n.logger.debug(`[StreamingTransport] Connected`),t(n)},shouldReconnect:e=>{let t=!n.isStatusFatal(e.status);if(!t){let t=n.prepareFatalError(e.status,e.error);n.eventEmitter.emit(`connectionError`,t),r(t)}return t},calculateReconnectDelay:e=>{let t=n.options.connectionRetryDelay(e.attempt),r=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?n.logger.info(r):n.logger.warn(r),t},onError:e=>{n.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{n.logger.debug(`[StreamingTransport] Disconnected`)}}),n.eventSource.connect()});return clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,Promise.race([a,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(n),t)})]).finally(()=>clearTimeout(n.timeoutTimer))}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,n){let r=e==null?0:e;return new t(`${`Connection failed with status: ${e==null?`unknown`:e}.`}${n?` Error: ${n}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){var e;this.connectionGeneration++,(e=this.eventSource)==null||e.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const y=e=>{let t=typeof e;if(t===`object`)try{var n,r;return(n=(r=e.constructor)==null?void 0:r.name)==null?t:n}catch(e){return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch(e){return t}return t},b=e=>e===`number`||e===`bigint`,x=new Set([`boolean`,`integer`,`float`]),S=(e,t)=>{let n=e.value,r=y(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return O(n,t,r,e.valueId);if(typeof t==`string`)return x.has(e.type)?{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}:{parsedValue:n,parsedValueId:e.valueId,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&(e.type===`boolean`||e.type===`string`||e.type===`enum`)){let i=C(n),a=typeof i==`boolean`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-boolean`}}if(b(typeof t)&&e.type===`integer`){let i=w(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(b(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=T(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},C=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},w=e=>{let t=E(e);return t==null?void 0:Math.trunc(t)},T=e=>E(e),E=e=>{if(!e||!D(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},D=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},O=(e,t,n,r)=>{if(typeof t==`string`)return{parsedValue:e,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`};try{let i=JSON.parse(e);return k(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch(e){return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},k=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},A={off:-1,error:0,warn:1,info:2,debug:3},j=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,p(p({},e),{},{fractionalSecondDigits:3}))}catch(t){return new Intl.DateTimeFormat(void 0,e)}};var ee=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=j()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){if(A[this.level]>=A[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},te=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const M=(e,t)=>new ee(e==null?`warn`:e,t==null?new te:t),N=(e,t)=>new URL(e,t==null?void 0:t.toString()),P=e=>{if(e)try{return new URL(e)}catch(t){throw new n(`Invalid URL '${e}'. Parsing failed: ${t}`)}},F=`https://client-sdk-api.configdirector.com`,I=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},L=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),R=`configdirector-sdk:instance-id`,z=1e3,B=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,V=(e,t)=>{let n=t;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0},H=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=V(n,2166136261);return V(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},U=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},W=e=>{if(!e||typeof e!=`object`)return!1;let{v:t,id:n,createdAt:r,checksum:i}=e;return t!==1||typeof n!=`string`||typeof i!=`string`||typeof r!=`number`||!Number.isInteger(r)||r<=0||!B.test(n)?!1:i===H(n,r)},G=async(e,t)=>{let n;try{n=await e.getItem(R)}catch(e){return t.debug(`[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one`,e),{outcome:`failed`}}if(typeof n!=`string`||n===``)return{outcome:`nothing usable`};let r;try{r=JSON.parse(n)}catch(e){return t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`),{outcome:`nothing usable`}}if(!W(r))return t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`};let i=Date.now()-r.createdAt;return i<0||i>=216e5?(t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`),{outcome:`nothing usable`}):{outcome:`stored`,instanceId:r.id}},K=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:H(t,r)};try{return await e.setItem(R,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},q=async(e,t,n,r)=>{let i=await G(e,r);switch(i.outcome){case`stored`:return{instanceId:i.instanceId};case`failed`:return{instanceId:t,ephemeral:!0};case`nothing usable`:break}return n.passed?{instanceId:t,ephemeral:!0}:await K(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},J=(e,t=U())=>{let n=L();if(!t)return e.debug(`[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id`),Promise.resolve({instanceId:n,ephemeral:!0});let r={passed:!1},i,a=new Promise(t=>{i=setTimeout(()=>{r.passed=!0,e.warn(`[ConfigDirectorClient] The instance id storage did not respond within ${z}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},z)});return Promise.race([q(t,n,r,e),a]).finally(()=>clearTimeout(i))};var Y=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){var n=this;if(!e.ok)throw n.isStatusFatal(e.status)?(n.fatalError=!0,n.close(),n.prepareFatalResponseStatusError(e.status,await e.text())):new t(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new t(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new t(`Failed to parse the response from the server: ${e}`):new t(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,n){var r,i;let a=e==null?0:e;return new t(`${`Connection failed with status: ${e==null?`unknown`:e}`}${((r=n==null||(i=n.trim())==null?void 0:i.length)==null?0:r)>0?` (${n})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,a)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return(e==null?void 0:e.name)===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const X=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),p(p({},n),{},{signal:i.signal}));return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var Z=class extends Y{constructor(t){var n;super(),this.options=t,this.eventEmitter=new e,this.connectionGeneration=0,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/polling/v1`,t.baseUrl),this.pollingIntervalSeconds=(n=t.pollingInterval)==null?60:n}async connect(e,t){var n=this;let r=++n.connectionGeneration;n.clearPollingInterval();let i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;try{await n.fetchConfigs(e,t,i)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t,i).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}close(){this.connectionGeneration++,super.close()}async fetchConfigs(e,t,n){var r=this;if(r.fatalError){r.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let i=await X(t,r.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:r.options.metaContext,clientSdkKey:r.options.clientSdkKey,instanceId:n.instanceId,ephemeral:n.ephemeral,lastUpdateTimestamp:r.lastUpdateTimestamp})},r.logger);if(await r.handleNonOkResponse(i),i.status==200){let e=JSON.parse(await i.text());r.lastUpdateTimestamp=e.timestamp,r.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{r.handleFetchError(e)}catch(e){throw r.fatalError&&r.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}};const Q=e=>{try{return e(globalThis)}catch(e){return}},ne=()=>Q(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),re=()=>Q(e=>{var t;return(t=e.location)==null?void 0:t.host}),ie=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,ae=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!ie(t))return!1;return!0},oe=e=>e==null||typeof e==`string`&&ae(e),$=e=>{if(typeof e==`string`)return e;try{return String(e)}catch(t){return Object.prototype.toString.call(e)}},se=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},ce=e=>{let t=e==null?void 0:e.kind;return oe(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:se($(t),128)}};var le=class{constructor(t,n,r,i,a){var o,s,c,l,u,d,f,m,h,g,_,v,y,b;this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=(o=i==null?void 0:i.logger)==null?M():o,this.clientSession=J(this.logger,a==null?void 0:a.instanceIdStorage),this.timeout=(s=i==null||(c=i.connection)==null?void 0:c.timeout)==null?3e3:s,this.validateSdkKeyPresence(n);let x=(l=a==null?void 0:a.urlFactory)==null?N:l,S=(u=this.parseUrl(i==null||(d=i.connection)==null?void 0:d.url,x))==null?F:u;this.connectionMode=(f=i==null||(m=i.connection)==null?void 0:m.mode)==null?`streaming`:f,this.telemetryClient=t,this.transport=(h=a==null?void 0:a.transport)==null?this.buildTransport(n,r,S,x,i,a):h,this.transport.on(`configSetReceived`,e=>{var t;this.hasReceivedConfigSet=!0,(t=this.readyResolve)==null||t.call(this);let n=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs=p(p({},this.configSet.configs),e.configs);let r=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:r,removedKeys:n}),this.updateWatchers([...r,...n]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:r,removedKeys:n})}),this.transport.on(`connectionError`,e=>{this.initializing=!1,this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,i==null||(g=i.hooks)==null?void 0:g.clientReady),this.registerHandler(`configEvaluated`,i==null||(_=i.hooks)==null?void 0:_.configEvaluated),this.registerHandler(`configsUpdated`,i==null||(v=i.hooks)==null?void 0:v.configsUpdated),this.registerHandler(`contextUpdated`,i==null||(y=i.hooks)==null?void 0:y.contextUpdated),this.registerHandler(`connectionError`,i==null||(b=i.hooks)==null?void 0:b.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=I(e,{defaultSeconds:60,minimumSeconds:30});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTransport(e,t,n,r,i,a){var o,s;return new(this.getTransportConstructor(this.connectionMode))({clientSession:this.clientSession,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:p(p({},i==null?void 0:i.metadata),{},{sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:ne(),host:re()}),logger:this.logger,fetch:a==null?void 0:a.fetch,connectionRetryDelay:(o=a==null?void 0:a.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):o,pollingInterval:this.resolvePollingIntervalForMode(i==null||(s=i.connection)==null?void 0:s.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return Z;default:return v}}async initialize(e){var t=this;t.hasReceivedConfigSet||(t.initializing=!0),await t.submitContext(e,`initialization`)}async updateContext(e){await this.submitContext(e,`context update`)}async submitContext(e,t){var n=this;await n.connectToTransport(n.contextToConnectWith(e,t),t)}contextToConnectWith(e,t){let n=ce(e);switch(n.outcome){case`admitted`:return n.context;case`ignored`:this.logger.error(`[ConfigDirectorClient] Ignored the context supplied for ${t} because its kind '${n.kindSample}' is invalid; connecting as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),this.telemetryClient.recordInvalidContext(n.kindSample);return}}get context(){return this.currentContext}async connectToTransport(e,t){var n=this;try{n.ready=!1,n.readyPromise=new Promise(e=>{n.readyResolve=e}).then(e=>{e||(n.ready=!0,n.initializing=!1,n.emit(`clientReady`,{action:t}),n.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let r=new Date().getTime();await n.transport.connect(e==null?{}:e,n.timeout,t),n.currentContext=e,n.telemetryClient.updateContext(e).catch(e=>n.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,e)),n.emit(`contextUpdated`,{context:e});let i=new Date().getTime()-r,a=n.timeout-i;clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,a>0&&await Promise.race([n.readyPromise,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(),a)})]).finally(()=>clearTimeout(n.timeoutTimer)),n.ready||n.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${n.timeout}ms. The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`)}catch(e){n.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){var t,n;let r=(t=this.configSet)==null?void 0:t.configs[e];(n=this.handlersMap.get(e))==null||n.forEach(t=>{let n=this.getValueFromConfigState(e,r,t.defaultValue);t.handler(n)})}watch(e,t,n){this.validateDefaultValue(t);let r=this.handlersMap.get(e),i={handler:n,defaultValue:t,requestedType:typeof t};return r?r.push(i):this.handlersMap.set(e,[i]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&(n==null||n.splice(e,1))}else n.splice(0)}getValue(e,t){var n;this.validateDefaultValue(t);let r=(n=this.configSet)==null?void 0:n.configs[e];return this.getValueFromConfigState(e,r,t)}getValueFromConfigState(e,t,n){var r,i;if(!t){var a;this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.telemetryClient.evaluatedConfig({contextId:(a=this.currentContext)==null?void 0:a.id,key:e,defaultValue:n,requestedType:y(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let o=S(t,n);return this.telemetryClient.evaluatedConfig({contextId:(r=this.currentContext)==null?void 0:r.id,type:t.type,key:e,defaultValue:n,requestedType:o.requestedType,evaluatedValue:o.parsedValue,evaluatedValueId:o.parsedValueId,usedDefault:o.usedDefault,evaluationReason:o.reason}),this.dispatchEvaluationEvent({key:e,value:o.parsedValue,valueId:(i=o.parsedValueId)==null?void 0:i,isDefaultValue:o.usedDefault,reason:o.reason,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${o.parsedValue}'`),o.parsedValue}dispatchEvaluationEvent(e){setTimeout(()=>this.emit(`configEvaluated`,{evaluation:e}),0)}emit(e,t){try{this.eventEmitter.emit(e,t)}catch(t){this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${e}'`,t)}}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new n(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new n(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new n(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new n(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}get isInitializing(){return this.initializing}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}pauseNetwork(){this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1}async resumeNetwork(){var e=this;await e.connectToTransport(e.currentContext,`network resume`)}async close(){var e=this,t;e.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(e.timeoutTimer),(t=e.readyResolve)==null||t.call(e,!0),e.telemetryClient.close().catch(t=>e.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,t)),e.transport.close(),e.ready=!1,e.initializing=!1}dispose(){this.clear(),this.close()}};export{M as a,r as c,P as i,n as l,F as n,p as o,N as r,t as s,le as t,e as u};
|
|
6
|
-
//# sourceMappingURL=DefaultConfigDirectorClient-B4x3i04O.mjs.map
|