@configdirector/nuxt-sdk 1.6.1 → 1.8.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.
@@ -0,0 +1,352 @@
1
+ //#region ../js-client-core/src/Emitter.d.ts
2
+ type EventType = string | symbol;
3
+ type EventsRecord = Record<EventType, any>;
4
+ type Handler<TEventsRecord extends EventsRecord, TKey extends keyof TEventsRecord> = (payload: TEventsRecord[TKey]) => void;
5
+ interface EventProvider<TEventsRecord extends EventsRecord> {
6
+ on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>): void;
7
+ off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>): void;
8
+ clear(): void;
9
+ }
10
+ //#endregion
11
+ //#region ../shared/src/types.d.ts
12
+ type ConfigEnumLikeType = {
13
+ [key: string]: string | number;
14
+ };
15
+ type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
16
+ interface ConfigDirectorLogger {
17
+ debug(message: string, ...args: any): void;
18
+ info(message: string, ...args: any): void;
19
+ warn(message: string, ...args: any): void;
20
+ error(message: string, ...args: any): void;
21
+ }
22
+ type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
23
+ type ConfigEvaluation = {
24
+ key: string;
25
+ value: ConfigValueType;
26
+ valueId?: string;
27
+ isDefaultValue: boolean;
28
+ reason: EvaluationReason;
29
+ context?: ConfigDirectorContext;
30
+ };
31
+ /**
32
+ * The user's context to be sent to ConfigDirector. This context will be used for targeting
33
+ * rules evaluation.
34
+ */
35
+ type ConfigDirectorContext = {
36
+ /**
37
+ * The user's identifier. This should be a value that uniquely identifies an application
38
+ * user.
39
+ * In the case of anonymous users, you could generate a UUID or alternatively not provide
40
+ * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
41
+ * value is used for segmenting users in percentage rollouts, and changes to the {@link id}
42
+ * could result in the user being assigned to a different percentile.
43
+ */
44
+ id?: string;
45
+ /**
46
+ * The user's display name. This will be shown in the ConfigDirector dashboard and may be
47
+ * used for targeting rules.
48
+ */
49
+ name?: string;
50
+ /**
51
+ * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
52
+ * dashboard and may be used for targeting rules.
53
+ */
54
+ traits?: {
55
+ [key: string]: unknown;
56
+ };
57
+ /**
58
+ * Whether or not to treat the context as anonymous during evaluation. When `true`, the
59
+ * context values will be used for targeting rules evaluation but the context will not be
60
+ * persisted and will not appear in the dashboard.
61
+ *
62
+ * @default false
63
+ */
64
+ anonymous?: boolean;
65
+ };
66
+ //#endregion
67
+ //#region ../js-client-core/src/types.d.ts
68
+ type ClientConnectAction = "initialization" | "context update" | "network resume";
69
+ type ClientEvents = {
70
+ configsUpdated: {
71
+ keys: string[];
72
+ removedKeys: string[];
73
+ };
74
+ clientReady: {
75
+ action: ClientConnectAction;
76
+ };
77
+ contextUpdated: {
78
+ context: ConfigDirectorContext | undefined;
79
+ };
80
+ configEvaluated: {
81
+ evaluation: ConfigEvaluation;
82
+ };
83
+ connectionError: {
84
+ error: Error;
85
+ };
86
+ };
87
+ type WatchHandler<T extends ConfigValueType> = (message: T) => void;
88
+ /**
89
+ * The ConfigDirector SDK client object.
90
+ *
91
+ * Applications should create a single instance of `ConfigDirectorClient`, and call
92
+ * {@link initialize} during application initialization.
93
+ *
94
+ * After initialization, to update the user's context, so that targeting rules are evaluated
95
+ * with the updated context, call {@link updateContext}.
96
+ */
97
+ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
98
+ /**
99
+ * Initializes the connection to ConfigDirector to retrieve config evaluations. Until
100
+ * initialization is successful, all flags will return their default value provided to
101
+ * {@link watch} or {@link getValue}.
102
+ *
103
+ * If the connection fails or is interrupted with a transient error (network error,
104
+ * internal server error, etc) the client will continue to attempt to connect. However,
105
+ * if the connection fails with a persistent error, like an invalid SDK key, the client will
106
+ * not attempt to re-connect and an error will be logged to the console or the provided
107
+ * logger.
108
+ *
109
+ * @param context The current user's context to be used for evaluating targeting rules (optional).
110
+ */
111
+ initialize(context?: ConfigDirectorContext): Promise<void>;
112
+ /**
113
+ * Updates the user's context and re-evaluates all config and flag values based on the new context.
114
+ *
115
+ * @param context The current user's context to be used for evaluating targeting rules (required).
116
+ */
117
+ updateContext(context: ConfigDirectorContext): Promise<void>;
118
+ /**
119
+ * Returns the current context the client is configured with, or undefined if there is no context.
120
+ *
121
+ * Note that the value returned does not updated immediately after calling {@link updateContext}. Only
122
+ * once the underlying connection was successful or timed out, the current context is updated. This is
123
+ * because while the context update is in progress, configs are still evaluated on the previous context.
124
+ *
125
+ */
126
+ get context(): ConfigDirectorContext | undefined;
127
+ /**
128
+ * Returns whether or not the client is ready after calling {@link initialize} or {@link updateContext}
129
+ *
130
+ * The definition of ready is that the connection to the server was successful, and config state
131
+ * was received.
132
+ */
133
+ get isReady(): boolean;
134
+ /**
135
+ * Whether the client is trying to get its very first payload from the server. Upon client creation,
136
+ * it is `false`. It becomes `true` when `initialize` is called on a client that has never received a
137
+ * payload, stays `true` through timeouts and retries, and becomes `false` when the first payload
138
+ * arrives, when a fatal connection error stops the retries, or on `close`. `updateContext` and
139
+ * `resumeNetwork` never set it, and once a payload has been received it is never `true` again.
140
+ */
141
+ get isInitializing(): boolean;
142
+ /**
143
+ * Evaluates a config and returns its value based on the current context and targeting rules
144
+ *
145
+ * @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
146
+ * @param configKey The config key to evaluate
147
+ * @param defaultValue The default value to be returned if the config state is unavailable. For
148
+ * example, if the client cannot connect to the server due to network conditions, or if getValue
149
+ * is called before initialization is done.
150
+ */
151
+ getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
152
+ /**
153
+ * Watches for changes to a a config evaluation value. Whenever the config value changes, the
154
+ * provided callback function will be called with the new value. Changes can happen due to updates
155
+ * to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
156
+ *
157
+ * @returns An 'unwatch' function that can be called to remove the subscriber
158
+ *
159
+ * @param configKey The config key to watch
160
+ * @param defaultValue The default value to be referenced if the config state is unavailable
161
+ * @param callback The callback function to be called whenever the config value is updated
162
+ */
163
+ watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>): () => void;
164
+ /**
165
+ * Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
166
+ * is provided.
167
+ *
168
+ * @param configKey The config key to remove subscribers from
169
+ * @param callback The subscriber to be removed. If not provided, all subscribers are removed for
170
+ * the given `configKey`.
171
+ */
172
+ unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
173
+ /**
174
+ * Removes all subscribers from all config keys
175
+ */
176
+ unwatchAll(): void;
177
+ /**
178
+ * Pauses the network connection without clearing event handlers, watch handlers, or config
179
+ * state. Intended for mobile environments where the OS may kill background connections (e.g.
180
+ * when the app is backgrounded on iOS/Android).
181
+ *
182
+ * Call {@link resumeNetwork} to re-establish the connection.
183
+ */
184
+ pauseNetwork(): void;
185
+ /**
186
+ * Resumes a connection that was paused via {@link pauseNetwork}, using the last context that
187
+ * was provided to {@link initialize} or {@link updateContext}.
188
+ */
189
+ resumeNetwork(): Promise<void>;
190
+ /**
191
+ * Disposes of the client. All connections are closed, and all event and config key subscribers
192
+ * are removed.
193
+ *
194
+ * Intended to be called when your application shuts down
195
+ */
196
+ dispose(): void;
197
+ }
198
+ //#endregion
199
+ //#region ../shared/src/testing/values.d.ts
200
+ type TestJsonValue = boolean | number | string | null | TestJsonValue[] | {
201
+ [key: string]: TestJsonValue;
202
+ };
203
+ type TestValue = boolean | number | string | TestJsonValue[] | {
204
+ [key: string]: TestJsonValue;
205
+ };
206
+ type TestValues = Record<string, TestValue>;
207
+ //#endregion
208
+ //#region ../js-client-core/src/testing/TestClient.d.ts
209
+ /**
210
+ * Options for {@link createTestClient}. Every option is optional.
211
+ */
212
+ type TestClientOptions = {
213
+ /**
214
+ * The config values the test client serves once its client connects, keyed by config key. The
215
+ * config type follows from each value: a boolean, an integral number (`integer`), any other
216
+ * number (`float`), a string, or a plain object or array (`json`).
217
+ */
218
+ values?: TestValues;
219
+ /**
220
+ * The connection timeout of the SDK client, in milliseconds. It bounds how long a held
221
+ * `initialize` or `updateContext` waits. Defaults to the SDK's production timeout.
222
+ */
223
+ timeout?: number;
224
+ /**
225
+ * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.
226
+ */
227
+ logger?: ConfigDirectorLogger;
228
+ };
229
+ /**
230
+ * A real ConfigDirector client connected to an in-memory server that the test controls.
231
+ *
232
+ * The client under {@link TestClient.client} is the SDK's production client: value parsing, watchers,
233
+ * events, and readiness behave as they do against ConfigDirector. Only the network connection and
234
+ * telemetry are replaced, so no request is ever made and nothing is left running after the client is
235
+ * disposed.
236
+ */
237
+ interface TestClient {
238
+ /**
239
+ * The SDK client to hand to the code under test. It starts uninitialized, like a production
240
+ * client; `initialize` completes at once with the seeded values unless initialization is held.
241
+ */
242
+ readonly client: ConfigDirectorClient;
243
+ /**
244
+ * Stores `value` under `key` and, when the client is connected, delivers it as an update, so
245
+ * reads, watchers, and `configsUpdated` handlers see it.
246
+ */
247
+ setValue(key: string, value: TestValue): void;
248
+ /**
249
+ * Removes `key` and, when the client is connected, delivers a full update without it, so reads
250
+ * fall back to the in-code default value and watchers of `key` receive that default.
251
+ */
252
+ removeValue(key: string): void;
253
+ /**
254
+ * Replaces every stored value with `values`, disarms any armed hold or failure, and, when the
255
+ * client is connected, delivers the new values as a full update.
256
+ */
257
+ replaceValues(values: TestValues): void;
258
+ /**
259
+ * Makes the next `initialize` wait until {@link completeInitialization} or
260
+ * {@link failInitialization} is called, or until the client's timeout elapses.
261
+ */
262
+ holdInitialization(): void;
263
+ /**
264
+ * Delivers the stored values to a held `initialize`, so it completes with the client ready. When
265
+ * a hold is armed but no `initialize` has started, it disarms the hold instead.
266
+ */
267
+ completeInitialization(): void;
268
+ /**
269
+ * Fails a held `initialize` with an unrecoverable connection error, or arms the next `initialize`
270
+ * to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.
271
+ */
272
+ failInitialization(): void;
273
+ /**
274
+ * Makes the next `updateContext` wait until {@link completeContextUpdate} or
275
+ * {@link failContextUpdate} is called, or until the client's timeout elapses.
276
+ */
277
+ holdContextUpdate(): void;
278
+ /**
279
+ * Delivers the stored values to a held `updateContext`, or disarms an armed hold that no
280
+ * `updateContext` has picked up.
281
+ */
282
+ completeContextUpdate(): void;
283
+ /**
284
+ * Fails a held `updateContext` with an unrecoverable connection error, or arms the next
285
+ * `updateContext` to fail.
286
+ */
287
+ failContextUpdate(): void;
288
+ /**
289
+ * The context of every `initialize` and `updateContext` call, in call order. `initialize` without
290
+ * a context records an empty context. Resumes are not recorded.
291
+ */
292
+ readonly contextUpdates: ConfigDirectorContext[];
293
+ }
294
+ //#endregion
295
+ //#region ../js-client-core/src/testing/installTestClient.d.ts
296
+ /**
297
+ * Makes every `ConfigDirectorProvider` mounted without a `client` prop, and every client
298
+ * `withProvider` would build, use `testClient.client` instead of building a client, until the
299
+ * returned function uninstalls it. Construction props such as `sdkKey` are ignored while installed;
300
+ * `context` and `hooks` apply to the installed client as they do for a `client` prop. A provider
301
+ * reads the installed client when it is constructed, so install before rendering.
302
+ *
303
+ * Installing again replaces the installed test client. Each uninstall function restores the test
304
+ * client that was installed when it was created, so nested installs are uninstalled in reverse order.
305
+ *
306
+ * @param testClient The test client whose `client` providers should use
307
+ * @returns A function that uninstalls it
308
+ *
309
+ * @example
310
+ * let uninstallTestClient: () => void;
311
+ * beforeEach(() => {
312
+ * testClient = createTestClient({ values: { "new-checkout": true } });
313
+ * uninstallTestClient = installTestClient(testClient);
314
+ * });
315
+ * afterEach(() => uninstallTestClient());
316
+ */
317
+ declare const installTestClient: (testClient: TestClient) => (() => void);
318
+ //#endregion
319
+ //#region ../shared/src/errors.d.ts
320
+ declare class ConfigDirectorConnectionError extends Error {
321
+ readonly name: string;
322
+ readonly status?: number;
323
+ constructor(message: string, status?: number);
324
+ }
325
+ declare class ConfigDirectorValidationError extends Error {
326
+ readonly name: string;
327
+ constructor(message: string);
328
+ }
329
+ //#endregion
330
+ //#region src/testing.d.ts
331
+ /**
332
+ * Creates a {@link TestClient}: a real `ConfigDirectorClient` connected to an in-memory server
333
+ * that the test controls. No network connection is opened and no telemetry is sent. Hand it to the
334
+ * ConfigDirector Nuxt plugin with `installTestClient` before the Nuxt app is created.
335
+ *
336
+ * @param options {@link TestClientOptions}: the initial values, the client's timeout, and its logger
337
+ * @returns A {@link TestClient} whose `client` the plugin provides to the app
338
+ *
339
+ * @example
340
+ * import { createTestClient, installTestClient } from "@configdirector/nuxt-sdk/testing";
341
+ *
342
+ * const testClient = createTestClient({ values: { "new-checkout": true } });
343
+ * installTestClient(testClient);
344
+ *
345
+ * test("shows the new checkout when the flag is on", async () => {
346
+ * const component = await mountSuspended(Checkout);
347
+ * expect(component.text()).toContain("New checkout");
348
+ * });
349
+ */
350
+ declare const createTestClient: (options?: TestClientOptions) => TestClient;
351
+ //#endregion
352
+ export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type TestJsonValue, type TestValue, type TestValues, createTestClient, installTestClient };