@configdirector/vue-sdk 1.5.1 → 1.6.1
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/README.md +27 -0
- package/dist/DefaultConfigDirectorClient-Ci14OJI0.mjs +6 -0
- package/dist/DefaultConfigDirectorClient-Ci14OJI0.mjs.map +1 -0
- package/dist/DefaultConfigDirectorClient-DJLwj6p6.cjs +5 -0
- package/dist/configdirector-vue-client-testing.cjs +1 -0
- package/dist/configdirector-vue-client-testing.d.cts +130 -0
- package/dist/configdirector-vue-client-testing.d.cts.map +1 -0
- package/dist/configdirector-vue-client-testing.d.mts +130 -0
- package/dist/configdirector-vue-client-testing.d.mts.map +1 -0
- package/dist/configdirector-vue-client-testing.mjs +2 -0
- package/dist/configdirector-vue-client-testing.mjs.map +1 -0
- package/dist/configdirector-vue-client.cjs +1 -5
- package/dist/configdirector-vue-client.d.cts +17 -204
- package/dist/configdirector-vue-client.d.cts.map +1 -1
- package/dist/configdirector-vue-client.d.mts +17 -204
- package/dist/configdirector-vue-client.d.mts.map +1 -1
- package/dist/configdirector-vue-client.mjs +1 -5
- package/dist/configdirector-vue-client.mjs.map +1 -1
- package/dist/types-3Pw7bIUn.d.cts +210 -0
- package/dist/types-3Pw7bIUn.d.cts.map +1 -0
- package/dist/types-CU9VmelO.d.mts +210 -0
- package/dist/types-CU9VmelO.d.mts.map +1 -0
- package/package.json +19 -2
|
@@ -1,209 +1,7 @@
|
|
|
1
|
+
import { a as ConfigDirectorLoggingLevel, i as ConfigDirectorLogger, n as ConfigDirectorClient, o as ConfigValueType, r as ConfigDirectorContext, s as ConnectionMode, t as ClientHooks } from "./types-CU9VmelO.mjs";
|
|
1
2
|
import * as _$vue from "vue";
|
|
2
3
|
import { App, Ref, ShallowRef } from "vue";
|
|
3
4
|
|
|
4
|
-
//#region ../js-client-core/src/Emitter.d.ts
|
|
5
|
-
type EventType = string | symbol;
|
|
6
|
-
type EventsRecord = Record<EventType, any>;
|
|
7
|
-
type Handler<TEventsRecord extends EventsRecord, TKey extends keyof TEventsRecord> = (payload: TEventsRecord[TKey]) => void;
|
|
8
|
-
interface EventProvider<TEventsRecord extends EventsRecord> {
|
|
9
|
-
on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>): void;
|
|
10
|
-
off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>): void;
|
|
11
|
-
clear(): void;
|
|
12
|
-
}
|
|
13
|
-
//#endregion
|
|
14
|
-
//#region ../shared/src/types.d.ts
|
|
15
|
-
type ConfigEnumLikeType = {
|
|
16
|
-
[key: string]: string | number;
|
|
17
|
-
};
|
|
18
|
-
type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
|
|
19
|
-
type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
|
|
20
|
-
interface ConfigDirectorLogger {
|
|
21
|
-
debug(message: string, ...args: any): void;
|
|
22
|
-
info(message: string, ...args: any): void;
|
|
23
|
-
warn(message: string, ...args: any): void;
|
|
24
|
-
error(message: string, ...args: any): void;
|
|
25
|
-
}
|
|
26
|
-
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
|
|
27
|
-
type ConfigEvaluation = {
|
|
28
|
-
key: string;
|
|
29
|
-
value: ConfigValueType;
|
|
30
|
-
valueId?: string;
|
|
31
|
-
isDefaultValue: boolean;
|
|
32
|
-
reason: EvaluationReason;
|
|
33
|
-
context?: ConfigDirectorContext;
|
|
34
|
-
};
|
|
35
|
-
/**
|
|
36
|
-
* The user's context to be sent to ConfigDirector. This context will be used for targeting
|
|
37
|
-
* rules evaluation.
|
|
38
|
-
*/
|
|
39
|
-
type ConfigDirectorContext = {
|
|
40
|
-
/**
|
|
41
|
-
* The user's identifier. This should be a value that uniquely identifies an application
|
|
42
|
-
* user.
|
|
43
|
-
* In the case of anonymous users, you could generate a UUID or alternatively not provide
|
|
44
|
-
* the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
|
|
45
|
-
* value is used for segmenting users in percentage rollouts, and changes to the {@link id}
|
|
46
|
-
* could result in the user being assigned to a different percentile.
|
|
47
|
-
*/
|
|
48
|
-
id?: string;
|
|
49
|
-
/**
|
|
50
|
-
* The user's display name. This will be shown in the ConfigDirector dashboard and may be
|
|
51
|
-
* used for targeting rules.
|
|
52
|
-
*/
|
|
53
|
-
name?: string;
|
|
54
|
-
/**
|
|
55
|
-
* Any arbitrary traits for the current user. They will be shown in the ConfigDirector
|
|
56
|
-
* dashboard and may be used for targeting rules.
|
|
57
|
-
*/
|
|
58
|
-
traits?: {
|
|
59
|
-
[key: string]: unknown;
|
|
60
|
-
};
|
|
61
|
-
/**
|
|
62
|
-
* Whether or not to treat the context as anonymous during evaluation. When `true`, the
|
|
63
|
-
* context values will be used for targeting rules evaluation but the context will not be
|
|
64
|
-
* persisted and will not appear in the dashboard.
|
|
65
|
-
*
|
|
66
|
-
* @default false
|
|
67
|
-
*/
|
|
68
|
-
anonymous?: boolean;
|
|
69
|
-
};
|
|
70
|
-
//#endregion
|
|
71
|
-
//#region ../js-client-core/src/types.d.ts
|
|
72
|
-
type ClientHooks = {
|
|
73
|
-
clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
|
|
74
|
-
configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
|
|
75
|
-
contextUpdated?: HookHandler<"contextUpdated"> | HookHandler<"contextUpdated">[];
|
|
76
|
-
configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
|
|
77
|
-
connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
|
|
78
|
-
};
|
|
79
|
-
type ClientConnectAction = "initialization" | "context update" | "network resume";
|
|
80
|
-
type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
|
|
81
|
-
type ClientEvents = {
|
|
82
|
-
configsUpdated: {
|
|
83
|
-
keys: string[];
|
|
84
|
-
};
|
|
85
|
-
clientReady: {
|
|
86
|
-
action: ClientConnectAction;
|
|
87
|
-
};
|
|
88
|
-
contextUpdated: {
|
|
89
|
-
context: ConfigDirectorContext | undefined;
|
|
90
|
-
};
|
|
91
|
-
configEvaluated: {
|
|
92
|
-
evaluation: ConfigEvaluation;
|
|
93
|
-
};
|
|
94
|
-
connectionError: {
|
|
95
|
-
error: Error;
|
|
96
|
-
};
|
|
97
|
-
};
|
|
98
|
-
type WatchHandler<T extends ConfigValueType> = (message: T) => void;
|
|
99
|
-
/**
|
|
100
|
-
* The ConfigDirector SDK client object.
|
|
101
|
-
*
|
|
102
|
-
* Applications should create a single instance of `ConfigDirectorClient`, and call
|
|
103
|
-
* {@link initialize} during application initialization.
|
|
104
|
-
*
|
|
105
|
-
* After initialization, to update the user's context, so that targeting rules are evaluated
|
|
106
|
-
* with the updated context, call {@link updateContext}.
|
|
107
|
-
*/
|
|
108
|
-
interface ConfigDirectorClient extends EventProvider<ClientEvents> {
|
|
109
|
-
/**
|
|
110
|
-
* Initializes the connection to ConfigDirector to retrieve config evaluations. Until
|
|
111
|
-
* initialization is successful, all flags will return their default value provided to
|
|
112
|
-
* {@link watch} or {@link getValue}.
|
|
113
|
-
*
|
|
114
|
-
* If the connection fails or is interrupted with a transient error (network error,
|
|
115
|
-
* internal server error, etc) the client will continue to attempt to connect. However,
|
|
116
|
-
* if the connection fails with a persistent error, like an invalid SDK key, the client will
|
|
117
|
-
* not attempt to re-connect and an error will be logged to the console or the provided
|
|
118
|
-
* logger.
|
|
119
|
-
*
|
|
120
|
-
* @param context The current user's context to be used for evaluating targeting rules (optional).
|
|
121
|
-
*/
|
|
122
|
-
initialize(context?: ConfigDirectorContext): Promise<void>;
|
|
123
|
-
/**
|
|
124
|
-
* Updates the user's context and re-evaluates all config and flag values based on the new context.
|
|
125
|
-
*
|
|
126
|
-
* @param context The current user's context to be used for evaluating targeting rules (required).
|
|
127
|
-
*/
|
|
128
|
-
updateContext(context: ConfigDirectorContext): Promise<void>;
|
|
129
|
-
/**
|
|
130
|
-
* Returns the current context the client is configured with, or undefined if there is no context.
|
|
131
|
-
*
|
|
132
|
-
* Note that the value returned does not updated immediately after calling {@link updateContext}. Only
|
|
133
|
-
* once the underlying connection was successful or timed out, the current context is updated. This is
|
|
134
|
-
* because while the context update is in progress, configs are still evaluated on the previous context.
|
|
135
|
-
*
|
|
136
|
-
*/
|
|
137
|
-
get context(): ConfigDirectorContext | undefined;
|
|
138
|
-
/**
|
|
139
|
-
* Returns whether or not the client is ready after calling {@link initialize} or {@link updateContext}
|
|
140
|
-
*
|
|
141
|
-
* The definition of ready is that the connection to the server was successful, and config state
|
|
142
|
-
* was received.
|
|
143
|
-
*/
|
|
144
|
-
get isReady(): boolean;
|
|
145
|
-
/**
|
|
146
|
-
* Returns whether or not the client is currently initializing. Upon client creation, it is `false`.
|
|
147
|
-
* It is `true` after calling `initialize` and becomes `false` again once initialization is completed.
|
|
148
|
-
*/
|
|
149
|
-
get isInitializing(): boolean;
|
|
150
|
-
/**
|
|
151
|
-
* Evaluates a config and returns its value based on the current context and targeting rules
|
|
152
|
-
*
|
|
153
|
-
* @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
|
|
154
|
-
* @param configKey The config key to evaluate
|
|
155
|
-
* @param defaultValue The default value to be returned if the config state is unavailable. For
|
|
156
|
-
* example, if the client cannot connect to the server due to network conditions, or if getValue
|
|
157
|
-
* is called before initialization is done.
|
|
158
|
-
*/
|
|
159
|
-
getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
|
|
160
|
-
/**
|
|
161
|
-
* Watches for changes to a a config evaluation value. Whenever the config value changes, the
|
|
162
|
-
* provided callback function will be called with the new value. Changes can happen due to updates
|
|
163
|
-
* to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
|
|
164
|
-
*
|
|
165
|
-
* @returns An 'unwatch' function that can be called to remove the subscriber
|
|
166
|
-
*
|
|
167
|
-
* @param configKey The config key to watch
|
|
168
|
-
* @param defaultValue The default value to be referenced if the config state is unavailable
|
|
169
|
-
* @param callback The callback function to be called whenever the config value is updated
|
|
170
|
-
*/
|
|
171
|
-
watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>): () => void;
|
|
172
|
-
/**
|
|
173
|
-
* Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
|
|
174
|
-
* is provided.
|
|
175
|
-
*
|
|
176
|
-
* @param configKey The config key to remove subscribers from
|
|
177
|
-
* @param callback The subscriber to be removed. If not provided, all subscribers are removed for
|
|
178
|
-
* the given `configKey`.
|
|
179
|
-
*/
|
|
180
|
-
unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
|
|
181
|
-
/**
|
|
182
|
-
* Removes all subscribers from all config keys
|
|
183
|
-
*/
|
|
184
|
-
unwatchAll(): void;
|
|
185
|
-
/**
|
|
186
|
-
* Pauses the network connection without clearing event handlers, watch handlers, or config
|
|
187
|
-
* state. Intended for mobile environments where the OS may kill background connections (e.g.
|
|
188
|
-
* when the app is backgrounded on iOS/Android).
|
|
189
|
-
*
|
|
190
|
-
* Call {@link resumeNetwork} to re-establish the connection.
|
|
191
|
-
*/
|
|
192
|
-
pauseNetwork(): void;
|
|
193
|
-
/**
|
|
194
|
-
* Resumes a connection that was paused via {@link pauseNetwork}, using the last context that
|
|
195
|
-
* was provided to {@link initialize} or {@link updateContext}.
|
|
196
|
-
*/
|
|
197
|
-
resumeNetwork(): Promise<void>;
|
|
198
|
-
/**
|
|
199
|
-
* Disposes of the client. All connections are closed, and all event and config key subscribers
|
|
200
|
-
* are removed.
|
|
201
|
-
*
|
|
202
|
-
* Intended to be called when your application shuts down
|
|
203
|
-
*/
|
|
204
|
-
dispose(): void;
|
|
205
|
-
}
|
|
206
|
-
//#endregion
|
|
207
5
|
//#region src/logger.d.ts
|
|
208
6
|
declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel) => ConfigDirectorLogger;
|
|
209
7
|
//#endregion
|
|
@@ -215,6 +13,21 @@ type ConfigDirectorPluginOptions = {
|
|
|
215
13
|
appVersion?: string;
|
|
216
14
|
url?: string;
|
|
217
15
|
timeout?: number;
|
|
16
|
+
/**
|
|
17
|
+
* The connection mode, one of `streaming` or `polling`. In `streaming` mode the connection stays
|
|
18
|
+
* open and receives config updates as they happen. In `polling` mode configs are fetched once during
|
|
19
|
+
* initialization and then again on every `pollingInterval`.
|
|
20
|
+
*
|
|
21
|
+
* Defaults to `streaming`.
|
|
22
|
+
*/
|
|
23
|
+
mode?: ConnectionMode;
|
|
24
|
+
/**
|
|
25
|
+
* The polling interval in seconds when `mode` is `polling`. Has no effect in `streaming` mode.
|
|
26
|
+
*
|
|
27
|
+
* Defaults to 60 seconds. A value below the minimum of 30 seconds is raised to 30 seconds and a
|
|
28
|
+
* warning is logged.
|
|
29
|
+
*/
|
|
30
|
+
pollingInterval?: number;
|
|
218
31
|
context?: ConfigDirectorContext;
|
|
219
32
|
logger?: ConfigDirectorLogger;
|
|
220
33
|
hooks?: ClientHooks;
|
|
@@ -252,5 +65,5 @@ declare const useContext: () => {
|
|
|
252
65
|
//#region src/client.d.ts
|
|
253
66
|
declare const initializeClient: (options: ConfigDirectorPluginOptions) => Promise<ConfigDirectorClient>;
|
|
254
67
|
//#endregion
|
|
255
|
-
export { ConfigDirectorPlugin, createConsoleLogger, initializeClient, useClient, useClientStatus, useConfigValue, useContext };
|
|
68
|
+
export { type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorPlugin, type ConfigDirectorPluginOptions, type ConnectionMode, createConsoleLogger, initializeClient, useClient, useClientStatus, useConfigValue, useContext };
|
|
256
69
|
//# sourceMappingURL=configdirector-vue-client.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-vue-client.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"configdirector-vue-client.d.mts","names":[],"sources":["../src/logger.ts","../src/types.ts","../src/plugin.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts","../src/client.ts"],"mappings":";;;;;cAca,mBAAA,GAAuB,KAAA,EAAO,0BAAA,KAA6B,oBAAA;;;KCP5D,YAAA;AAAA,KAEA,2BAAA;EACV,MAAA;EACA,OAAA;EACA,UAAA;EACA,GAAA;EACA,OAAA;EDED;;;;;;;ECMC,IAAA,GAAO,cAAA;;AAfT;;;;;EAsBE,eAAA;EACA,OAAA,GAAU,qBAAA;EACV,MAAA,GAAS,oBAAA;EACT,KAAA,GAAQ,WAAA;AAAA;;;cCnBG,oBAAA;iBACI,GAAA,EAAG,eAAA,EAAmB,2BAAA,GAA8B,oBAAA;AAAA;;;cCVxD,SAAA;EAAkB,MAAA,EAAQ,oBAAA;AAAA;;;cCE1B,eAAA;EACX,WAAA,EAAa,QAAA,CAAS,GAAA,CAAI,YAAA;EAC1B,OAAA,EAAS,QAAA,CAAS,GAAA;AAAA;;;cCDP,cAAA,aAA4B,eAAA,EACvC,SAAA,UACA,YAAA,EAAc,CAAA;EACX,KAAA,EAAO,UAAA,CAAW,CAAA;EAAI,WAAA,EAAa,QAAA,CAAS,GAAA,CAAI,YAAA;EAAgB,OAAA,EAAS,QAAA,CAAS,GAAA;AAAA;;;cCJ1E,UAAA;;2BAI2B,qBAAA,KAAqB,OAAA;AAAA;;;cCgBhD,gBAAA,GACX,OAAA,EAAS,2BAAA,KACR,OAAA,CAAQ,oBAAA"}
|
|
@@ -1,6 +1,2 @@
|
|
|
1
|
-
import{computed as e,inject as t,onBeforeUnmount as n,readonly as r,ref as i,shallowRef as a,toRaw as o}from"vue";var s=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))}},c=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},l=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},u=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}},d=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},f=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},p=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},m=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}};function h(e){"@babel/helpers - typeof";return h=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},h(e)}function g(e,t){if(h(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(h(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function _(e){var t=g(e,`string`);return h(t)==`symbol`?t:t+``}function v(e,t,n){return(t=_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function y(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 b(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?y(Object(n),!0).forEach(function(t){v(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):y(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var x=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(b(b({},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 S=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var C=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=S.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers=b({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===S.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=S.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=S.CONNECTING,this._fetch(this.url,b(b({},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 f(`The server response did not have a body`);t._readyState=S.OPEN,t._onConnect(),t.reconnectAttempt=0;let i=new x({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,i),t.scheduleReconnect({status:r,error:new d(`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=S.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return b(b({},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=S.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new m(`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 p(`${n} must be a function`);return e}};const w=e=>new C(e);var ee=class{constructor(e){this.options=e,this.eventEmitter=new s,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){var n=this;n.eventSource&&n.close();let r=new Promise((t,r)=>{n.eventSource=w({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:n.options.instanceId}),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([r,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,t){let n=e==null?0:e;return new c(`${`Connection failed with status: ${e==null?`unknown`:e}.`}${t?` Error: ${t}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,n)}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;(e=this.eventSource)==null||e.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const T=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},E=e=>e===`number`||e===`bigint`,te=new Set([`boolean`,`integer`,`float`]),ne=(e,t)=>{let n=e.value,r=T(t);if(n==null)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return oe(n,t,r,e.valueId);if(typeof t==`string`)return te.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=D(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(E(typeof t)&&e.type===`integer`){let i=re(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(E(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=ie(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`}},D=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},re=e=>{let t=O(e);return t==null?void 0:Math.trunc(t)},ie=e=>O(e),O=e=>{if(!e||!ae(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},ae=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},oe=(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 se(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`}}},se=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},k={off:-1,error:0,warn:1,info:2,debug:3},ce=()=>{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,b(b({},e),{},{fractionalSecondDigits:3}))}catch(t){return new Intl.DateTimeFormat(void 0,e)}};var le=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=ce()}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(k[this.level]>=k[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},ue=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const A=(e,t)=>new le(e==null?`warn`:e,t==null?new ue:t),j=(e,t)=>new URL(e,t==null?void 0:t.toString()),de=e=>{if(e)try{return new URL(e)}catch(t){throw new l(`Invalid URL '${e}'. Parsing failed: ${t}`)}},M=`https://client-sdk-api.configdirector.com`,N=()=>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)}),P=`configdirector-sdk:instance-id`,fe=/^[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{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){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||!fe.test(n)?!1:i===I(n,r)},z=(e,t)=>{let n;try{n=e.getItem(P)}catch(e){t==null||t.debug(`[ConfigDirectorClient] Could not read the stored instance id, generating a new one`,e);return}if(!n)return;let r;try{r=JSON.parse(n)}catch(e){t==null||t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`);return}if(!R(r)){t==null||t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`);return}let i=Date.now()-r.createdAt;if(i<0||i>=216e5){t==null||t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`);return}return r.id},B=(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:I(t,r)};try{e.setItem(P,JSON.stringify(i))}catch(e){n==null||n.debug(`[ConfigDirectorClient] Could not persist the instance id`,e)}},V=e=>{let t=L();if(!t)return N();let n=z(t,e);if(n)return n;let r=N();return B(t,r,e),r};var pe=class{constructor(){this.fatalError=!1,this.pollingIntervalSeconds=60}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){var t=this;if(!e.ok)throw t.isStatusFatal(e.status)?(t.fatalError=!0,t.close(),t.prepareFatalResponseStatusError(e.status,await e.text())):new c(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new c(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new c(`Failed to parse the response from the server: ${e}`):new c(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){var n,r;let i=e==null?0:e;return new c(`${`Connection failed with status: ${e==null?`unknown`:e}`}${((n=t==null||(r=t.trim())==null?void 0:r.length)==null?0:n)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,i)}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 me=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(),b(b({},n),{},{signal:i.signal}));return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var he=class extends pe{constructor(e){var t;super(),this.options=e,this.eventEmitter=new s,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/polling/v1`,e.baseUrl);let n=(t=e.pollingInterval)==null?300:t;n<60&&this.logger.warn(`[PollingTransport] pollingInterval of ${n} seconds is below the minimum of 60 seconds. Using 60 seconds.`),this.pollingIntervalSeconds=Math.max(n,60)}async connect(e,t){var n=this;n.clearPollingInterval();try{await n.fetchConfigs(e,t)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}async fetchConfigs(e,t){var n=this;if(n.fatalError){n.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let r=await me(t,n.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:n.options.instanceId,lastUpdateTimestamp:n.lastUpdateTimestamp})},n.logger);if(await n.handleNonOkResponse(r),r.status==200){let e=JSON.parse(await r.text());n.lastUpdateTimestamp=e.timestamp,n.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{n.handleFetchError(e)}catch(e){throw n.fatalError&&n.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 H=e=>{try{return e(globalThis)}catch(e){return}},ge=()=>H(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),_e=()=>H(e=>{var t;return(t=e.location)==null?void 0:t.host});var U=class{constructor(e,t,n,r,i){var a,o,c,l,u,d,f,p,m,h,g,_,v,y,x;this.handlersMap=new Map,this.eventEmitter=new s,this.ready=!1,this.initializing=!1,this.logger=(a=r==null?void 0:r.logger)==null?A():a,this.instanceId=V(this.logger),this.timeout=(o=r==null||(c=r.connection)==null?void 0:c.timeout)==null?3e3:o,this.validateSdkKeyPresence(t);let S=(l=i==null?void 0:i.urlFactory)==null?j:l,C=(u=this.parseUrl(r==null||(d=r.connection)==null?void 0:d.url,S))==null?M:u;this.connectionMode=(f=r==null||(p=r.connection)==null?void 0:p.mode)==null?`streaming`:f;let w=this.getTransportConstructor(this.connectionMode);this.telemetryClient=e,this.transport=new w({instanceId:this.instanceId,clientSdkKey:t,baseUrl:C,resolveUrl:S,metaContext:b(b({},r==null?void 0:r.metadata),{},{sdkName:n.sdkName,sdkVersion:n.sdkVersion,userAgent:ge(),host:_e()}),logger:this.logger,fetch:i==null?void 0:i.fetch,connectionRetryDelay:(m=i==null?void 0:i.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):m,pollingInterval:r==null||(h=r.connection)==null?void 0:h.pollingInterval}),this.transport.on(`configSetReceived`,e=>{var t;(t=this.readyResolve)==null||t.call(this);let n=Object.keys(e.configs);!this.configSet||e.kind==`full`?(this.configSet=e,this.emit(`configsUpdated`,{keys:n}),this.updateWatchers(e.configs)):(this.configSet.configs=b(b({},this.configSet.configs),e.configs),this.emit(`configsUpdated`,{keys:n}),this.updateWatchers(e.configs)),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:n})}),this.transport.on(`connectionError`,e=>{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`,r==null||(g=r.hooks)==null?void 0:g.clientReady),this.registerHandler(`configEvaluated`,r==null||(_=r.hooks)==null?void 0:_.configEvaluated),this.registerHandler(`configsUpdated`,r==null||(v=r.hooks)==null?void 0:v.configsUpdated),this.registerHandler(`contextUpdated`,r==null||(y=r.hooks)==null?void 0:y.contextUpdated),this.registerHandler(`connectionError`,r==null||(x=r.hooks)==null?void 0:x.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)}getTransportConstructor(e){switch(e){case`polling`:return he;default:return ee}}async initialize(e){var t=this;t.initializing=!0,await t.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}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),n.currentContext=e,n.telemetryClient.updateContext(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)}}updateWatchers(e){Object.values(e).forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){var t;(t=this.handlersMap.get(e.key))==null||t.forEach(t=>{let n=this.getValueFromConfigState(e.key,e,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:T(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let o=ne(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 l(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new l(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new l(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new l(`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(),e.transport.close(),e.ready=!1,e.initializing=!1}dispose(){this.clear(),this.close()}};const W=e=>{var t;if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var G=class{constructor(e){var t,n,r,i;this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t;let a={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:(n=e.evaluationQueueLimit)==null?1e3:n,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}};this.worker=new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=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}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4;let t=e.initialFlushIntervalDelay??5e3;this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),t)}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class extends c{constructor(e){super(e),this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let d=(e,t)=>new URL(e,t?.toString()),f=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},p=Math.ceil(128/Math.log2(62)),m=new TextEncoder,h=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,m.encode(e?.toString()??``));return f(new Uint8Array(t,0,16),p)},g,_=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),v=e=>{try{self.postMessage(e)}catch{self.postMessage(_(e.payload.level,e.payload.message))}},y={debug:function(e,...t){v(_(`debug`,e,t))},info:function(e,...t){v(_(`info`,e,t))},warn:function(e,...t){v(_(`warn`,e,t))},error:function(e,...t){v(_(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!g){y.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(y.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(g){y.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}g=new u({...t.payload,baseUrl:d(t.payload.baseUrl),urlFactory:d,valueIdGenerator:h,logger:y});break;case`EvaluatedConfigEvent`:g?.evaluatedConfig(t.payload);break;case`UpdateContext`:g?.updateContext(t.payload.context);break;case`Flush`:g?.forceFlush();break;case`Close`:(g?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`}))),this.worker.onmessage=e=>{this.handleWorkerEvent(e.data)},this.worker.postMessage(a),this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()};try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}}async updateContext(e){var t=this;let n={type:`UpdateContext`,payload:{context:e}};t.worker.postMessage(n)}evaluatedConfig(e){let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};this.worker.postMessage(t)}sanitizeEvaluatedConfigEvent(e){return b(b({},e),{},{defaultValue:W({value:e.defaultValue,type:e.type}),evaluatedValue:W({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){this.worker.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(e=>{this.closeResolve=e,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),this.worker.postMessage({type:`Close`})}),this.closePromise}finishClose(){var e;clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker.terminate(),(e=this.closeResolve)==null||e.call(this)}};const ve=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},ye=Math.ceil(128/Math.log2(62)),be=new TextEncoder,xe=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,be.encode((t=e==null?void 0:e.toString())==null?``:t));return ve(new Uint8Array(n,0,16),ye)},Se=(e,t,n)=>{var r,i,a,o,s;let c=(r=n==null?void 0:n.logger)==null?A():r,l=(i=de(n==null||(a=n.connection)==null?void 0:a.url))==null?M:i;return new U(new G({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:n==null||(o=n.metadata)==null?void 0:o.appName,appVersion:n==null||(s=n.metadata)==null?void 0:s.appVersion},logger:c,baseUrl:l,urlFactory:j,valueIdGenerator:xe}),e,t,b(b({},n),{},{logger:c}))};var Ce=class{decorateMessage(e){return`[ConfigDirector:vue-sdk] ${e}`}};const K=e=>A(e,new Ce),we=(e,t)=>Se(e,{sdkName:`vue-sdk`,sdkVersion:`1.5.1`},t),q=e=>{var t;return we(e.sdkKey,{connection:{url:e.url,timeout:e.timeout},metadata:{appName:e.appName,appVersion:e.appVersion},logger:(t=e.logger)==null?K(`warn`):t,hooks:e.hooks})},Te=async e=>{let t=q(e);return await t.initialize(e.context),t},J=Symbol(`ConfigDirector.Client`),Y=Symbol(`ConfigDirector.ClientStatus`),X=Symbol(`ConfigDirector.Context`),Ee={install:(e,t)=>{let n=(()=>{if(De(t))return t;if(Oe(t))return q(t);throw new u(`The plugin options must be either an initialized ConfigDirectorClient, or a ConfigDirectorPluginOptions object with a valid client 'sdkKey'`)})(),a=i(n.isReady?`ready`:`loading`),o=r(a);n.on(`clientReady`,()=>a.value=`ready`);let s=i(t.context),c=r(s);n.on(`contextUpdated`,({context:e})=>s.value=e),!n.isReady&&!n.isInitializing&&n.initialize(t.context).then(()=>{n.isReady||(a.value=`default`)}),e.provide(J,n),e.provide(Y,o),e.provide(X,c)}},De=e=>e instanceof U,Oe=e=>typeof e.sdkKey==`string`,Z=e=>{let n=t(e);if(n===void 0)throw new u(`Could not inject ${e.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`);return n},Q=()=>({client:Z(J)}),$=()=>{let t=Z(Y);return{readyStatus:t,loading:e(()=>t.value===`loading`)}},ke=(e,t)=>{let{client:r}=Q(),{readyStatus:i,loading:o}=$(),s=a(r.getValue(e,t)),c=e=>s.value=e;return r.watch(e,t,c),n(()=>r.unwatch(e,c)),{value:s,readyStatus:i,loading:o}},Ae=()=>{let{client:e}=Q();return{context:Z(X),updateContext:async t=>{let n=o(t);JSON.stringify(e.context)!=JSON.stringify(n)&&await e.updateContext(n)}}};export{Ee as ConfigDirectorPlugin,K as createConsoleLogger,Te as initializeClient,Q as useClient,$ as useClientStatus,ke as useConfigValue,Ae as useContext};
|
|
1
|
+
import{a as e,c as t,i as n,n as r,o as i,r as a,t as o}from"./DefaultConfigDirectorClient-Ci14OJI0.mjs";import{computed as s,inject as c,onBeforeUnmount as l,readonly as u,ref as d,shallowRef as f,toRaw as p}from"vue";const m=e=>{var t;if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var h=class{constructor(e){var t,n,r,i;this.turnedOff=!1,this.pendingEvaluations=[],this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t,this.pendingEvaluationLimit=(n=e.evaluationQueueLimit)==null?1e3:n,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{return new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=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}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class extends c{constructor(e){super(e),this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let d=(e,t)=>new URL(e,t?.toString()),f=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},p=Math.ceil(128/Math.log2(62)),m=new TextEncoder,h=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,m.encode(e?.toString()??``));return f(new Uint8Array(t,0,16),p)},g,_=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),v=e=>{try{self.postMessage(e)}catch{self.postMessage(_(e.payload.level,e.payload.message))}},y={debug:function(e,...t){v(_(`debug`,e,t))},info:function(e,...t){v(_(`info`,e,t))},warn:function(e,...t){v(_(`warn`,e,t))},error:function(e,...t){v(_(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!g){y.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(y.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(g){y.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}g=new u({...t.payload,baseUrl:d(t.payload.baseUrl),urlFactory:d,valueIdGenerator:h,logger:y}),g.start();break;case`EvaluatedConfigEvent`:g?.evaluatedConfig(t.payload);break;case`UpdateContext`:g?.updateContext(t.payload.context);break;case`Flush`:g?.forceFlush();break;case`Close`:(g?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,e}}async updateContext(e){var t=this,n;if(t.closePromise)return;let r={type:`UpdateContext`,payload:{context:e}};(n=t.startWorker())==null||n.postMessage(r)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}sanitizeEvaluatedConfigEvent(e){return i(i({},e),{},{defaultValue:m({value:e.defaultValue,type:e.type}),evaluatedValue:m({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){var e;(e=this.worker)==null||e.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){var e,t;clearTimeout(this.closeTimer),this.closeTimer=void 0,(e=this.worker)==null||e.terminate(),(t=this.closeResolve)==null||t.call(this)}};const g=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},_=Math.ceil(128/Math.log2(62)),v=new TextEncoder,y=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,v.encode((t=e==null?void 0:e.toString())==null?``:t));return g(new Uint8Array(n,0,16),_)},b=(t,s,c)=>{var l,u,d,f,p;let m=(l=c==null?void 0:c.logger)==null?e():l,g=(u=n(c==null||(d=c.connection)==null?void 0:d.url))==null?r:u;return new o(new h({sdkKey:t,sdkIdentity:{sdkName:s.sdkName,sdkVersion:s.sdkVersion},metaContext:{appName:c==null||(f=c.metadata)==null?void 0:f.appName,appVersion:c==null||(p=c.metadata)==null?void 0:p.appVersion},logger:m,baseUrl:g,urlFactory:a,valueIdGenerator:y}),t,s,i(i({},c),{},{logger:m}))};var x=class{decorateMessage(e){return`[ConfigDirector:vue-sdk] ${e}`}};const S=t=>e(t,new x),C=(e,t)=>b(e,{sdkName:`vue-sdk`,sdkVersion:`1.6.1`},t),w=e=>{var t;return C(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval},metadata:{appName:e.appName,appVersion:e.appVersion},logger:(t=e.logger)==null?S(`warn`):t,hooks:e.hooks})},T=async e=>{let t=w(e);return await t.initialize(e.context),t},E=Symbol(`ConfigDirector.Client`),D=Symbol(`ConfigDirector.ClientStatus`),O=Symbol(`ConfigDirector.Context`),k={install:(e,n)=>{let r=(()=>{if(A(n))return n;if(j(n))return w(n);throw new t(`The plugin options must be either an initialized ConfigDirectorClient, or a ConfigDirectorPluginOptions object with a valid client 'sdkKey'`)})(),i=d(r.isReady?`ready`:`loading`),a=u(i);r.on(`clientReady`,()=>i.value=`ready`);let o=d(n.context),s=u(o);r.on(`contextUpdated`,({context:e})=>o.value=e),!r.isReady&&!r.isInitializing&&r.initialize(n.context).then(()=>{r.isReady||(i.value=`default`)}),e.provide(E,r),e.provide(D,a),e.provide(O,s)}},A=e=>{let t=e;return typeof t.initialize==`function`&&typeof t.getValue==`function`&&typeof t.watch==`function`&&typeof t.on==`function`},j=e=>typeof e.sdkKey==`string`,M=e=>{let n=c(e);if(n===void 0)throw new t(`Could not inject ${e.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`);return n},N=()=>({client:M(E)}),P=()=>{let e=M(D);return{readyStatus:e,loading:s(()=>e.value===`loading`)}},F=(e,t)=>{let{client:n}=N(),{readyStatus:r,loading:i}=P(),a=f(n.getValue(e,t)),o=e=>a.value=e;return n.watch(e,t,o),l(()=>n.unwatch(e,o)),{value:a,readyStatus:r,loading:i}},I=()=>{let{client:e}=N();return{context:M(O),updateContext:async t=>{let n=p(t);JSON.stringify(e.context)!=JSON.stringify(n)&&await e.updateContext(n)}}};export{k as ConfigDirectorPlugin,S as createConsoleLogger,T as initializeClient,N as useClient,P as useClientStatus,F as useConfigValue,I as useContext};
|
|
6
2
|
//# sourceMappingURL=configdirector-vue-client.mjs.map
|