@configdirector/nuxt-sdk 0.1.1 → 0.2.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/README.md CHANGED
@@ -1,150 +1,12 @@
1
1
  # ConfigDirector Nuxt SDK
2
2
 
3
- ## Getting started
3
+ This is the Nuxt SDK for [ConfigDirector](https://www.configdirector.com).
4
4
 
5
- ### 1. Install
5
+ ## Documentation
6
6
 
7
- Install from NPM:
7
+ Refer to the [official documentation for the Nuxt SDK](https://docs.configdirector.com/sdks/meta/nuxt).
8
8
 
9
- ```bash
10
- npm install --save @configdirector/nuxt-sdk
11
- ```
12
-
13
- ### 2. Configure the Nuxt module
14
-
15
- The Nuxt SDK requires the client SDK key for evaluation in the browser, and the server SDK key for server side rendering (SSR) and for server routes.
16
-
17
- You can provide the keys in `nuxt.config.ts`:
18
-
19
- ```ts
20
- export default defineNuxtConfig({
21
- //...
22
- modules: ["@configdirector/nuxt-sdk"],
23
- runtimeConfig: {
24
- public: {
25
- configdirector: {
26
- clientSdkKey: "YOUR-CLIENT-SDK-KEY",
27
- },
28
- },
29
- configdirector: {
30
- serverSdkKey: "YOUR-SERVER-SDK-KEY", // This is a secret, do not commit to your source repository
31
- },
32
- },
33
- });
34
- ```
35
-
36
- Since the server SDK key is a secret value, the recommended approach is to provide it via an environment variable:
37
-
38
- ```bash
39
- export NUXT_CONFIGDIRECTOR_SERVER_SDK_KEY=YOUR-SERVER-SDK-KEY
40
- ```
41
-
42
- The client key can also be provided via an environment variable, which overrides the key provided in: `nuxt.config.ts`:
43
-
44
- ```bash
45
- export NUXT_PUBLIC_CONFIGDIRECTOR_CLIENT_SDK_KEY=YOUR-CLIENT-SDK-KEY
46
- ```
47
-
48
- ### 3. Retrieve config values
49
-
50
- Retrieve a config value with the `useConfigDirectorValue` composable:
51
-
52
- ```ts
53
- <script setup lang="ts">
54
- const { value } = useConfigDirectorValue<string>("my-config", "default value");
55
- </script>
56
-
57
- <template>
58
- <div>my-config is : {{ value }}</div>
59
- </template>
60
- ```
61
-
62
- The `value` returned is a ShallowRef that will update whenever the config value is updated in the ConfigDirector dashboard, or if it evaluates to a different value due to targeting rules (for example, if the user context is updated). Keep in mind that it is a ShallowRef when accessing it in scripts:
63
-
64
- ```ts
65
- <script setup lang="ts">
66
- const { value: myConfigValue } = useConfigDirectorValue<string>("my-config", "default value");
67
-
68
- const someOtherDerivedValue = computed(() => `Hello ${myConfigValue.value}`);
69
- </script>
70
-
71
- <template>
72
- <div>my-config is : {{ someOtherDerivedValue }}</div>
73
- </template>
74
- ```
75
-
76
-
77
- You can also determine if the client is still initializing, so rather than transition from the default value to the evaluated value, you can show a loading state until the client is ready and config values are evaluated:
78
-
79
- ```ts
80
- <script setup lang="ts">
81
- const { value, loading } = useConfigDirectorValue<string>("my-config", "default value");
82
- </script>
83
-
84
- <template>
85
- <div v-if="loading">Loading...</div>
86
- <div v-else>my-config is : {{ value }}</div>
87
- </template>
88
- ```
89
-
90
- Additionally, you can also use the `useConfigDirectorStatus` composable to retrieve just the status:
91
-
92
- ```ts
93
- <script setup lang="ts">
94
- const { loading } = useConfigDirectorStatus();
95
- </script>
96
-
97
- <template>
98
- <div v-if="loading">Loading...</div>
99
- <div v-else><SomeComponentThatUsesConfigValues /></div>
100
- </template>
101
- ```
102
-
103
- ### 4. Updating the user context
104
-
105
- Update the user context with the `useConfigDirectorContext` composable:
106
-
107
- ```ts
108
- <script setup lang="ts">
109
- const { context, updateContext } = useConfigDirectorContext();
110
- const { value } = useConfigDirectorValue<string>("my-config", "default value");
111
-
112
- const onUpdate = () => {
113
- updateContext({
114
- id: "54321",
115
- name: "Another User",
116
- });
117
- };
118
- </script>
119
-
120
- <template>
121
- <div>Current context: {{ context }}</div>
122
- <div>my-config is : {{ value }}</div>
123
- <button type="button" @click="onUpdate">Update Context</button>
124
- </template>
125
- ```
126
-
127
- ### 5. Retrieving config values in a server handler
128
-
129
- On the server side, there is a Nitro composable to retrieve the ConfigDirector client:
130
-
131
- ```ts
132
- export default defineEventHandler(async (_event) => {
133
- const client = useConfigDirectorClient();
134
- return client.getValue("my-config", "default value");
135
- });
136
- ```
137
-
138
- `getValue` also accepts an optional user context:
139
-
140
- ```ts
141
- export default defineEventHandler(async (_event) => {
142
- const client = useConfigDirectorClient();
143
- return client.getValue("my-config", "default value", { id: "some-user-id", name: "Example User" });
144
- });
145
- ```
146
-
147
- The server side evaluation is performed entirely by the SDK. Unlike the browser client which must retrieve new values when the user context is updated, the server evaluator can evaluate targeting rules locally (without additional network requests to ConfigDirector) for any user context.
9
+ There is also [a quickstart guide for ConfigDirector and any of our SDKs](https://docs.configdirector.com/getting-started/quickstart).
148
10
 
149
11
  ## Getting Help
150
12
 
package/dist/module.json CHANGED
@@ -4,5 +4,5 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.0.0"
6
6
  },
7
- "version": "0.1.1"
7
+ "version": "0.2.0"
8
8
  }
package/dist/module.mjs CHANGED
@@ -5,7 +5,7 @@ var module_default = defineNuxtModule({
5
5
  meta: {
6
6
  name: "@configdirector/nuxt-sdk",
7
7
  configKey: "configdirector",
8
- compatibility: { nuxt: ">=4.0.0" }
8
+ compatibility: { nuxt: ">=3.7.0" }
9
9
  },
10
10
  defaults: {},
11
11
  setup(options, nuxt) {
@@ -33,33 +33,35 @@ var module_default = defineNuxtModule({
33
33
  middleware: true,
34
34
  handler: resolver.resolve("./runtime/nitro/middleware")
35
35
  });
36
- addServerImports({
36
+ addServerImports([{
37
37
  name: "useConfigDirectorClient",
38
38
  as: "useConfigDirectorClient",
39
39
  from: resolver.resolve("./runtime/server/composables/useConfigDirectorClient")
40
- });
40
+ }]);
41
41
  addPlugin(resolver.resolve("./runtime/plugin.server"));
42
42
  addPlugin(resolver.resolve("./runtime/plugin.client"));
43
- addImports({
44
- name: "useConfigDirectorClient",
45
- as: "useConfigDirectorClient",
46
- from: resolver.resolve("./runtime/app/composables/useConfigDirectorClient")
47
- });
48
- addImports({
49
- name: "useConfigDirectorStatus",
50
- as: "useConfigDirectorStatus",
51
- from: resolver.resolve("./runtime/app/composables/useConfigDirectorStatus")
52
- });
53
- addImports({
54
- name: "useConfigDirectorContext",
55
- as: "useConfigDirectorContext",
56
- from: resolver.resolve("./runtime/app/composables/useConfigDirectorContext")
57
- });
58
- addImports({
59
- name: "useConfigDirectorValue",
60
- as: "useConfigDirectorValue",
61
- from: resolver.resolve("./runtime/app/composables/useConfigDirectorValue")
62
- });
43
+ addImports([
44
+ {
45
+ name: "useConfigDirectorClient",
46
+ as: "useConfigDirectorClient",
47
+ from: resolver.resolve("./runtime/app/composables/useConfigDirectorClient")
48
+ },
49
+ {
50
+ name: "useConfigDirectorStatus",
51
+ as: "useConfigDirectorStatus",
52
+ from: resolver.resolve("./runtime/app/composables/useConfigDirectorStatus")
53
+ },
54
+ {
55
+ name: "useConfigDirectorContext",
56
+ as: "useConfigDirectorContext",
57
+ from: resolver.resolve("./runtime/app/composables/useConfigDirectorContext")
58
+ },
59
+ {
60
+ name: "useConfigDirectorValue",
61
+ as: "useConfigDirectorValue",
62
+ from: resolver.resolve("./runtime/app/composables/useConfigDirectorValue")
63
+ }
64
+ ]);
63
65
  }
64
66
  });
65
67
  //#endregion
@@ -1,124 +1,6 @@
1
1
  import * as _$h3 from "h3";
2
+ import { ConfigDirectorClient } from "@configdirector/server-sdk";
2
3
 
3
- //#region ../js-server-sdk/dist/configdirector-server.d.cts
4
- //#region ../shared/src/types.d.ts
5
- type ConfigEnumLikeType = {
6
- [key: string]: string | number;
7
- };
8
- type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
9
- /**
10
- * The user's context to be sent to ConfigDirector. This context will be used for targeting
11
- * rules evaluation.
12
- */
13
- type ConfigDirectorContext = {
14
- /**
15
- * The user's identifier. This should be a value that uniquely identifies an application
16
- * user.
17
- * In the case of anonymous users, you could generate a UUID or alternatively not provide
18
- * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
19
- * value is used for segmenting users in percentage rollouts, and changes to the {@link id}
20
- * could result in the user being assigned to a different percentile.
21
- */
22
- id?: string;
23
- /**
24
- * The user's display name. This will be shown in the ConfigDirector dashboard and may be
25
- * used for targeting rules.
26
- */
27
- name?: string;
28
- /**
29
- * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
30
- * dashboard and may be used for targeting rules.
31
- */
32
- traits?: {
33
- [key: string]: unknown;
34
- };
35
- };
36
- /**
37
- * Metadata about your application. It is recommended you include these values when configuring
38
- * a ConfigDirector client so that you can use them in targeting rules.
39
- */
40
- type ClientEvents = {
41
- configsUpdated: {
42
- keys: string[];
43
- };
44
- clientReady: undefined;
45
- };
46
- type WatchHandler<T extends ConfigValueType> = (message: T) => void;
47
- /**
48
- * The ConfigDirector SDK client object.
49
- *
50
- * Applications should create a single instance of `ConfigDirectorClient`, and call
51
- * {@link initialize} during application initialization.
52
- */
53
- interface ConfigDirectorClient {
54
- /**
55
- * Initializes the connection to ConfigDirector to retrieve config definitions. Until
56
- * initialization is successful, all flags will return their default value provided to
57
- * {@link watch} or {@link getValue}.
58
- *
59
- * If the connection fails or is interrupted with a transient error (network error,
60
- * internal server error, etc) the client will continue to attempt to connect. However,
61
- * if the connection fails with a persistent error, like an invalid SDK key, the client will
62
- * not attempt to re-connect and an error will be logged to the console or the provided
63
- * logger.
64
- */
65
- initialize(): Promise<void>;
66
- /**
67
- * Returns whether or not the client is ready after calling {@link initialize}
68
- *
69
- * The definition of ready is that the connection to the server was successful, and config definitions
70
- * were received.
71
- */
72
- get isReady(): boolean;
73
- /**
74
- * Evaluates a config and returns its value based on the current context and targeting rules
75
- *
76
- * @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
77
- * @param configKey The config key to evaluate
78
- * @param defaultValue The default value to be returned if the config state is unavailable. For
79
- * example, if the client cannot connect to the server due to network conditions, or if getValue
80
- * is called before initialization is done.
81
- * @param context The user's context to be used for targeting rules evaluation (optional)
82
- */
83
- getValue<T extends ConfigValueType>(configKey: string, defaultValue: T, context?: ConfigDirectorContext): T;
84
- /**
85
- * Watches for changes to a a config evaluation value. Whenever the config value changes, the
86
- * provided callback function will be called with the new value. Changes can happen due to updates
87
- * to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
88
- *
89
- * @returns An 'unwatch' function that can be called to remove the subscriber
90
- *
91
- * @param configKey The config key to watch
92
- * @param defaultValue The default value to be referenced if the config state is unavailable
93
- * @param callback The callback function to be called whenever the config value is updated
94
- * @param context The user's context to be used for targeting rules evaluation (optional)
95
- */
96
- watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>, context?: ConfigDirectorContext): () => void;
97
- /**
98
- * Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
99
- * is provided.
100
- *
101
- * @param configKey The config key to remove subscribers from
102
- * @param callback The subscriber to be removed. If not provided, all subscribers are removed for
103
- * the given `configKey`.
104
- */
105
- unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
106
- /**
107
- * Removes all subscribers from all config keys
108
- */
109
- unwatchAll(): void;
110
- on<T extends keyof ClientEvents>(eventName: T, handler: (args: ClientEvents[T]) => void): void;
111
- off<T extends keyof ClientEvents>(eventName: T, handler?: (args: ClientEvents[T]) => void): void;
112
- /**
113
- * Disposes of the client. All connections are closed, and all event and config key subscribers
114
- * are removed.
115
- *
116
- * Intended to be called when your application shuts down
117
- */
118
- dispose(): void;
119
- } //#endregion
120
- //#region ../shared/src/logger.d.ts
121
- //#endregion
122
4
  //#region src/runtime/nitro/middleware.d.ts
123
5
  declare const _default: _$h3.EventHandler<_$h3.EventHandlerRequest, void>;
124
6
  declare module "h3" {
@@ -1,124 +1,6 @@
1
1
  import * as _$h3 from "h3";
2
+ import { ConfigDirectorClient } from "@configdirector/server-sdk";
2
3
 
3
- //#region ../js-server-sdk/dist/configdirector-server.d.cts
4
- //#region ../shared/src/types.d.ts
5
- type ConfigEnumLikeType = {
6
- [key: string]: string | number;
7
- };
8
- type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
9
- /**
10
- * The user's context to be sent to ConfigDirector. This context will be used for targeting
11
- * rules evaluation.
12
- */
13
- type ConfigDirectorContext = {
14
- /**
15
- * The user's identifier. This should be a value that uniquely identifies an application
16
- * user.
17
- * In the case of anonymous users, you could generate a UUID or alternatively not provide
18
- * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
19
- * value is used for segmenting users in percentage rollouts, and changes to the {@link id}
20
- * could result in the user being assigned to a different percentile.
21
- */
22
- id?: string;
23
- /**
24
- * The user's display name. This will be shown in the ConfigDirector dashboard and may be
25
- * used for targeting rules.
26
- */
27
- name?: string;
28
- /**
29
- * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
30
- * dashboard and may be used for targeting rules.
31
- */
32
- traits?: {
33
- [key: string]: unknown;
34
- };
35
- };
36
- /**
37
- * Metadata about your application. It is recommended you include these values when configuring
38
- * a ConfigDirector client so that you can use them in targeting rules.
39
- */
40
- type ClientEvents = {
41
- configsUpdated: {
42
- keys: string[];
43
- };
44
- clientReady: undefined;
45
- };
46
- type WatchHandler<T extends ConfigValueType> = (message: T) => void;
47
- /**
48
- * The ConfigDirector SDK client object.
49
- *
50
- * Applications should create a single instance of `ConfigDirectorClient`, and call
51
- * {@link initialize} during application initialization.
52
- */
53
- interface ConfigDirectorClient {
54
- /**
55
- * Initializes the connection to ConfigDirector to retrieve config definitions. Until
56
- * initialization is successful, all flags will return their default value provided to
57
- * {@link watch} or {@link getValue}.
58
- *
59
- * If the connection fails or is interrupted with a transient error (network error,
60
- * internal server error, etc) the client will continue to attempt to connect. However,
61
- * if the connection fails with a persistent error, like an invalid SDK key, the client will
62
- * not attempt to re-connect and an error will be logged to the console or the provided
63
- * logger.
64
- */
65
- initialize(): Promise<void>;
66
- /**
67
- * Returns whether or not the client is ready after calling {@link initialize}
68
- *
69
- * The definition of ready is that the connection to the server was successful, and config definitions
70
- * were received.
71
- */
72
- get isReady(): boolean;
73
- /**
74
- * Evaluates a config and returns its value based on the current context and targeting rules
75
- *
76
- * @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
77
- * @param configKey The config key to evaluate
78
- * @param defaultValue The default value to be returned if the config state is unavailable. For
79
- * example, if the client cannot connect to the server due to network conditions, or if getValue
80
- * is called before initialization is done.
81
- * @param context The user's context to be used for targeting rules evaluation (optional)
82
- */
83
- getValue<T extends ConfigValueType>(configKey: string, defaultValue: T, context?: ConfigDirectorContext): T;
84
- /**
85
- * Watches for changes to a a config evaluation value. Whenever the config value changes, the
86
- * provided callback function will be called with the new value. Changes can happen due to updates
87
- * to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
88
- *
89
- * @returns An 'unwatch' function that can be called to remove the subscriber
90
- *
91
- * @param configKey The config key to watch
92
- * @param defaultValue The default value to be referenced if the config state is unavailable
93
- * @param callback The callback function to be called whenever the config value is updated
94
- * @param context The user's context to be used for targeting rules evaluation (optional)
95
- */
96
- watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>, context?: ConfigDirectorContext): () => void;
97
- /**
98
- * Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
99
- * is provided.
100
- *
101
- * @param configKey The config key to remove subscribers from
102
- * @param callback The subscriber to be removed. If not provided, all subscribers are removed for
103
- * the given `configKey`.
104
- */
105
- unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
106
- /**
107
- * Removes all subscribers from all config keys
108
- */
109
- unwatchAll(): void;
110
- on<T extends keyof ClientEvents>(eventName: T, handler: (args: ClientEvents[T]) => void): void;
111
- off<T extends keyof ClientEvents>(eventName: T, handler?: (args: ClientEvents[T]) => void): void;
112
- /**
113
- * Disposes of the client. All connections are closed, and all event and config key subscribers
114
- * are removed.
115
- *
116
- * Intended to be called when your application shuts down
117
- */
118
- dispose(): void;
119
- } //#endregion
120
- //#region ../shared/src/logger.d.ts
121
- //#endregion
122
4
  //#region src/runtime/nitro/middleware.d.ts
123
5
  declare const _default: _$h3.EventHandler<_$h3.EventHandlerRequest, void>;
124
6
  declare module "h3" {
@@ -440,6 +440,148 @@ var StreamingTransport = class {
440
440
  }
441
441
  };
442
442
  //#endregion
443
+ //#region ../shared/src/transport/AbstractPollingTransport.ts
444
+ var AbstractPollingTransport = class {
445
+ fatalError = false;
446
+ pollingInterval;
447
+ pollingIntervalSeconds = 60;
448
+ clearPollingInterval() {
449
+ clearInterval(this.pollingInterval);
450
+ }
451
+ schedulePollingInterval(callback) {
452
+ clearInterval(this.pollingInterval);
453
+ if (this.pollingIntervalSeconds <= 0) return;
454
+ this.pollingInterval = setInterval(callback, this.pollingIntervalSeconds * 1e3);
455
+ }
456
+ async handleNonOkResponse(response) {
457
+ if (!response.ok) if (this.isStatusFatal(response.status)) {
458
+ this.fatalError = true;
459
+ throw this.prepareFatalResponseStatusError(response.status, await response.text());
460
+ } else throw new ConfigDirectorConnectionError(`Connection failed with status: ${response.status}`, response.status);
461
+ }
462
+ handleFetchError(fetchError) {
463
+ if (this.isFetchErrorFatal(fetchError)) {
464
+ this.fatalError = true;
465
+ this.close();
466
+ throw new ConfigDirectorConnectionError(`Connection failed with fatal error: ${fetchError}. This is an unrecoverable error, retry attempts will be ignored.`);
467
+ } else if (fetchError instanceof SyntaxError) throw new ConfigDirectorConnectionError(`Failed to parse the response from the server: ${fetchError}`);
468
+ else throw new ConfigDirectorConnectionError(`Connection failed with error: ${fetchError}.`);
469
+ }
470
+ prepareFatalResponseStatusError(responseStatus, errorBody) {
471
+ const status = responseStatus ?? 0;
472
+ return new ConfigDirectorConnectionError(`${`Connection failed with status: ${responseStatus ?? "unknown"}`}${(errorBody?.trim()?.length ?? 0) > 0 ? ` (${errorBody})` : ""}. This is an unrecoverable error, retry attempts will be ignored.`, status);
473
+ }
474
+ isStatusFatal(status) {
475
+ return !!status && status >= 400 && status < 500;
476
+ }
477
+ isFetchErrorFatal(fetchError) {
478
+ if (fetchError?.name === "NotAllowedError") return true;
479
+ else if (fetchError instanceof TypeError) return true;
480
+ return false;
481
+ }
482
+ get isConnected() {
483
+ return this.pollingInterval !== void 0;
484
+ }
485
+ close() {
486
+ clearInterval(this.pollingInterval);
487
+ this.pollingInterval = void 0;
488
+ }
489
+ dispose() {
490
+ this.close();
491
+ this.clear();
492
+ }
493
+ };
494
+ //#endregion
495
+ //#region ../shared/src/fetchWithTimeout.ts
496
+ const fetchWithTimeout = async (timeout, resource, options, logger) => {
497
+ const abortController = new AbortController();
498
+ const abortTimeoutId = setTimeout(() => {
499
+ logger.debug("[fetchWithTimeout] Reached timeout, aborting request");
500
+ abortController.abort();
501
+ }, timeout);
502
+ try {
503
+ const response = await fetch(typeof resource === "string" || resource instanceof Request ? resource : resource.toString(), {
504
+ ...options,
505
+ signal: abortController.signal
506
+ });
507
+ clearTimeout(abortTimeoutId);
508
+ return response;
509
+ } catch (error) {
510
+ logger.warn("[fetchWithTimeout] Fetch error: ", error);
511
+ clearTimeout(abortTimeoutId);
512
+ throw error;
513
+ }
514
+ };
515
+ //#endregion
516
+ //#region ../js-server-sdk/src/PollingTransport.ts
517
+ var PollingTransport = class extends AbstractPollingTransport {
518
+ logger;
519
+ eventEmitter = new EventEmitter$1();
520
+ url;
521
+ lastUpdateTimestamp;
522
+ constructor(options) {
523
+ super();
524
+ this.options = options;
525
+ this.options = options;
526
+ this.logger = options.logger;
527
+ this.url = new URL("server/polling/v1", options.baseUrl);
528
+ this.pollingIntervalSeconds = options.pollingInterval ?? 60;
529
+ }
530
+ async connect(timeout) {
531
+ this.clearPollingInterval();
532
+ await this.fetchConfigs(timeout);
533
+ this.schedulePollingInterval(() => {
534
+ this.fetchConfigs(timeout).catch((error) => {
535
+ this.logger.error("[PollingTransport] Error during polling:", error);
536
+ });
537
+ });
538
+ return this;
539
+ }
540
+ async fetchConfigs(timeout) {
541
+ if (this.fatalError) {
542
+ this.logger.warn("[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.");
543
+ return;
544
+ }
545
+ try {
546
+ const response = await fetchWithTimeout(timeout, this.url, {
547
+ method: "POST",
548
+ headers: { "Content-Type": "application/json" },
549
+ body: JSON.stringify({
550
+ metaContext: this.options.metaContext,
551
+ serverSdkKey: this.options.serverSdkKey,
552
+ lastUpdateTimestamp: this.lastUpdateTimestamp
553
+ })
554
+ }, this.logger);
555
+ await this.handleNonOkResponse(response);
556
+ if (response.status === 200) {
557
+ const json = JSON.parse(await response.text());
558
+ this.lastUpdateTimestamp = json.timestamp;
559
+ this.eventEmitter.emit("configBundleReceived", json);
560
+ }
561
+ } catch (fetchError) {
562
+ this.handleFetchError(fetchError);
563
+ }
564
+ }
565
+ on(name, handler) {
566
+ this.eventEmitter.on(name, handler);
567
+ }
568
+ off(name, handler) {
569
+ if (handler) this.eventEmitter.off(name, handler);
570
+ else this.eventEmitter.removeAllListeners(name);
571
+ }
572
+ clear() {
573
+ this.eventEmitter.removeAllListeners();
574
+ }
575
+ };
576
+ //#endregion
577
+ //#region ../js-server-sdk/src/OneTimeTransport.ts
578
+ var OneTimeTransport = class extends PollingTransport {
579
+ constructor(options) {
580
+ super(options);
581
+ this.pollingIntervalSeconds = 0;
582
+ }
583
+ };
584
+ //#endregion
443
585
  //#region ../config-evaluator/src/text-comparison.ts
444
586
  const compareText = (value, operator, targetValues) => {
445
587
  switch (operator.toLowerCase()) {
@@ -872,27 +1014,6 @@ const isDroppedEventsEmpty = (droppedEvents) => {
872
1014
  return true;
873
1015
  };
874
1016
  //#endregion
875
- //#region ../shared/src/fetchWithTimeout.ts
876
- const fetchWithTimeout = async (timeout, resource, options, logger) => {
877
- const abortController = new AbortController();
878
- const abortTimeoutId = setTimeout(() => {
879
- logger.debug("[fetchWithTimeout] Reached timeout, aborting request");
880
- abortController.abort();
881
- }, timeout);
882
- try {
883
- const response = await fetch(typeof resource === "string" || resource instanceof Request ? resource : resource.toString(), {
884
- ...options,
885
- signal: abortController.signal
886
- });
887
- clearTimeout(abortTimeoutId);
888
- return response;
889
- } catch (error) {
890
- logger.warn("[fetchWithTimeout] Fetch error: ", error);
891
- clearTimeout(abortTimeoutId);
892
- throw error;
893
- }
894
- };
895
- //#endregion
896
1017
  //#region ../js-server-sdk/src/telemetry/ServerEventReporter.ts
897
1018
  var ServerEventReporter = class {
898
1019
  sdkKey;
@@ -1180,7 +1301,7 @@ var DefaultConfigDirectorClient = class {
1180
1301
  ready = false;
1181
1302
  readyPromise;
1182
1303
  readyResolve;
1183
- streaming;
1304
+ connectionMode;
1184
1305
  configEvaluator;
1185
1306
  metaContext;
1186
1307
  constructor(serverSdkKey, sdkOptions, clientOptions) {
@@ -1189,8 +1310,8 @@ var DefaultConfigDirectorClient = class {
1189
1310
  this.metaContext = clientOptions?.metadata ?? {};
1190
1311
  this.configEvaluator = new ConfigEvaluator(this.logger);
1191
1312
  const baseUrl = this.parseUrl(clientOptions?.connection?.url) ?? defaultBaseUrl;
1192
- this.streaming = clientOptions?.connection?.streaming === false ? false : true;
1193
- const transportConstructor = StreamingTransport;
1313
+ this.connectionMode = clientOptions?.connection?.mode ?? "streaming";
1314
+ const transportConstructor = this.getTransportConstructor(this.connectionMode);
1194
1315
  const queueLimit = clientOptions?.telemetry?.eventQueueLimit ?? DEFAULT_EVENT_QUEUE_LIMIT;
1195
1316
  this.usageEventCollector = new ServerTelemetryEventCollector({
1196
1317
  sdkKey: serverSdkKey,
@@ -1209,7 +1330,8 @@ var DefaultConfigDirectorClient = class {
1209
1330
  sdkName: sdkOptions.sdkName,
1210
1331
  sdkVersion: sdkOptions.sdkVersion
1211
1332
  },
1212
- logger: this.logger
1333
+ logger: this.logger,
1334
+ pollingInterval: clientOptions?.connection?.pollingInterval
1213
1335
  });
1214
1336
  this.transport.on("configBundleReceived", (configBundle) => {
1215
1337
  this.readyResolve?.();
@@ -1247,13 +1369,20 @@ var DefaultConfigDirectorClient = class {
1247
1369
  setTimeout(() => resolve(), remainingTimeout);
1248
1370
  })]);
1249
1371
  if (!this.ready) {
1250
- const warningDetails = this.streaming ? "The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds." : "Since the client was configured without streaming, configs may not update and always return the default value.";
1372
+ const warningDetails = this.connectionMode === "streaming" ? "The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds." : "Since the client was configured without streaming, configs may not update and always return the default value.";
1251
1373
  this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${warningDetails}`);
1252
1374
  }
1253
1375
  } catch (error) {
1254
1376
  this.logger.error("[ConfigDirectorClient] An error occurred during initialization: ", error);
1255
1377
  }
1256
1378
  }
1379
+ getTransportConstructor(mode) {
1380
+ switch (mode) {
1381
+ case "one-time": return OneTimeTransport;
1382
+ case "polling": return PollingTransport;
1383
+ default: return StreamingTransport;
1384
+ }
1385
+ }
1257
1386
  updateWatchers(configsMap) {
1258
1387
  Object.values(configsMap).forEach((v) => this.updateWatchersForConfig(v));
1259
1388
  }
@@ -1385,7 +1514,7 @@ var plugin_default = defineNitroPlugin((nitroApp) => {
1385
1514
  const { serverSdkKey, baseUrl } = runtimeConfig.configdirector;
1386
1515
  const client = new DefaultConfigDirectorClient(serverSdkKey, {
1387
1516
  sdkName: "nuxt-sdk",
1388
- sdkVersion: "0.1.1"
1517
+ sdkVersion: "0.2.0"
1389
1518
  }, {
1390
1519
  logger,
1391
1520
  ...baseUrl ? { connection: { url: baseUrl } } : {}
@@ -60,13 +60,6 @@ var ConfigDirectorInitializationError = class ConfigDirectorInitializationError
60
60
  }
61
61
  };
62
62
  //#endregion
63
- //#region ../js-client-core/src/errors.ts
64
- const isFetchErrorFatal = (fetchError) => {
65
- if (fetchError?.name === "NotAllowedError") return true;
66
- else if (fetchError instanceof TypeError) return true;
67
- return false;
68
- };
69
- //#endregion
70
63
  //#region ../eventsource/src/errors.ts
71
64
  var StreamClosedError = class StreamClosedError extends Error {
72
65
  name = "StreamClosedError";
@@ -635,6 +628,58 @@ const createDefaultLogger$1 = (level, messageDecorator) => {
635
628
  return new DefaultConsoleLogger(level ?? "warn", messageDecorator ?? new LogMessageDecorator());
636
629
  };
637
630
  //#endregion
631
+ //#region ../shared/src/transport/AbstractPollingTransport.ts
632
+ var AbstractPollingTransport = class {
633
+ fatalError = false;
634
+ pollingInterval;
635
+ pollingIntervalSeconds = 60;
636
+ clearPollingInterval() {
637
+ clearInterval(this.pollingInterval);
638
+ }
639
+ schedulePollingInterval(callback) {
640
+ clearInterval(this.pollingInterval);
641
+ if (this.pollingIntervalSeconds <= 0) return;
642
+ this.pollingInterval = setInterval(callback, this.pollingIntervalSeconds * 1e3);
643
+ }
644
+ async handleNonOkResponse(response) {
645
+ if (!response.ok) if (this.isStatusFatal(response.status)) {
646
+ this.fatalError = true;
647
+ throw this.prepareFatalResponseStatusError(response.status, await response.text());
648
+ } else throw new ConfigDirectorConnectionError(`Connection failed with status: ${response.status}`, response.status);
649
+ }
650
+ handleFetchError(fetchError) {
651
+ if (this.isFetchErrorFatal(fetchError)) {
652
+ this.fatalError = true;
653
+ this.close();
654
+ throw new ConfigDirectorConnectionError(`Connection failed with fatal error: ${fetchError}. This is an unrecoverable error, retry attempts will be ignored.`);
655
+ } else if (fetchError instanceof SyntaxError) throw new ConfigDirectorConnectionError(`Failed to parse the response from the server: ${fetchError}`);
656
+ else throw new ConfigDirectorConnectionError(`Connection failed with error: ${fetchError}.`);
657
+ }
658
+ prepareFatalResponseStatusError(responseStatus, errorBody) {
659
+ const status = responseStatus ?? 0;
660
+ return new ConfigDirectorConnectionError(`${`Connection failed with status: ${responseStatus ?? "unknown"}`}${(errorBody?.trim()?.length ?? 0) > 0 ? ` (${errorBody})` : ""}. This is an unrecoverable error, retry attempts will be ignored.`, status);
661
+ }
662
+ isStatusFatal(status) {
663
+ return !!status && status >= 400 && status < 500;
664
+ }
665
+ isFetchErrorFatal(fetchError) {
666
+ if (fetchError?.name === "NotAllowedError") return true;
667
+ else if (fetchError instanceof TypeError) return true;
668
+ return false;
669
+ }
670
+ get isConnected() {
671
+ return this.pollingInterval !== void 0;
672
+ }
673
+ close() {
674
+ clearInterval(this.pollingInterval);
675
+ this.pollingInterval = void 0;
676
+ }
677
+ dispose() {
678
+ this.close();
679
+ this.clear();
680
+ }
681
+ };
682
+ //#endregion
638
683
  //#region ../shared/src/fetchWithTimeout.ts
639
684
  const fetchWithTimeout = async (timeout, resource, options, logger) => {
640
685
  const abortController = new AbortController();
@@ -656,22 +701,34 @@ const fetchWithTimeout = async (timeout, resource, options, logger) => {
656
701
  }
657
702
  };
658
703
  //#endregion
659
- //#region ../js-client-core/src/PullTransport.ts
660
- var PullTransport = class {
704
+ //#region ../js-client-core/src/PollingTransport.ts
705
+ var PollingTransport = class extends AbstractPollingTransport {
661
706
  logger;
662
707
  eventEmitter = new Emitter();
663
708
  url;
664
- fatalError = false;
709
+ lastUpdateTimestamp;
665
710
  constructor(options) {
711
+ super();
666
712
  this.options = options;
667
713
  this.options = options;
668
714
  this.logger = options.logger;
669
- this.url = options.resolveUrl("client/pull/v1", options.baseUrl);
715
+ this.url = options.resolveUrl("client/polling/v1", options.baseUrl);
716
+ this.pollingIntervalSeconds = options.pollingInterval ?? 60;
670
717
  }
671
718
  async connect(context, timeout) {
719
+ this.clearPollingInterval();
720
+ await this.fetchConfigs(context, timeout);
721
+ this.schedulePollingInterval(() => {
722
+ this.fetchConfigs(context, timeout).catch((error) => {
723
+ this.logger.error("[PollingTransport] Error during polling:", error);
724
+ });
725
+ });
726
+ return this;
727
+ }
728
+ async fetchConfigs(context, timeout) {
672
729
  if (this.fatalError) {
673
- this.logger.warn("[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.");
674
- return this;
730
+ this.logger.warn("[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.");
731
+ return;
675
732
  }
676
733
  try {
677
734
  const response = await fetchWithTimeout(timeout, this.url, {
@@ -680,31 +737,20 @@ var PullTransport = class {
680
737
  body: JSON.stringify({
681
738
  givenContext: context,
682
739
  metaContext: this.options.metaContext,
683
- clientSdkKey: this.options.clientSdkKey
740
+ clientSdkKey: this.options.clientSdkKey,
741
+ lastUpdateTimestamp: this.lastUpdateTimestamp
684
742
  })
685
743
  }, this.logger);
686
- if (!response.ok) if (this.isStatusFatal(response.status)) {
687
- this.fatalError = true;
688
- throw this.prepareFatalResponseStatusError(response.status, await response.text());
689
- } else throw new ConfigDirectorConnectionError(`Connection failed with status: ${response.status}`, response.status);
690
- const json = JSON.parse(await response.text());
691
- this.eventEmitter.emit("configSetReceived", json);
692
- return this;
744
+ await this.handleNonOkResponse(response);
745
+ if (response.status == 200) {
746
+ const json = JSON.parse(await response.text());
747
+ this.lastUpdateTimestamp = json.timestamp;
748
+ this.eventEmitter.emit("configSetReceived", json);
749
+ }
693
750
  } catch (fetchError) {
694
- if (isFetchErrorFatal(fetchError)) {
695
- this.fatalError = true;
696
- throw new ConfigDirectorConnectionError(`Connection failed with fatal error: ${fetchError}. This is an unrecoverable error, retry attempts will be ignored.`);
697
- } else if (fetchError instanceof SyntaxError) throw new ConfigDirectorConnectionError(`Failed to parse the response from the server: ${fetchError}`);
698
- else throw new ConfigDirectorConnectionError(`Connection failed with error: ${fetchError}.`);
751
+ this.handleFetchError(fetchError);
699
752
  }
700
753
  }
701
- prepareFatalResponseStatusError(responseStatus, errorBody) {
702
- const status = responseStatus ?? 0;
703
- return new ConfigDirectorConnectionError(`${`Connection failed with status: ${responseStatus ?? "unknown"}`}${(errorBody?.trim()?.length ?? 0) > 0 ? ` (${errorBody})` : ""}. This is an unrecoverable error, retry attempts will be ignored.`, status);
704
- }
705
- isStatusFatal(status) {
706
- return !!status && status >= 400 && status < 500;
707
- }
708
754
  on(name, handler) {
709
755
  this.eventEmitter.on(name, handler);
710
756
  }
@@ -714,10 +760,13 @@ var PullTransport = class {
714
760
  clear() {
715
761
  this.eventEmitter.clear();
716
762
  }
717
- close() {}
718
- dispose() {
719
- this.close();
720
- this.clear();
763
+ };
764
+ //#endregion
765
+ //#region ../js-client-core/src/OneTimeTransport.ts
766
+ var OneTimeTransport = class extends PollingTransport {
767
+ constructor(options) {
768
+ super(options);
769
+ this.pollingIntervalSeconds = 0;
721
770
  }
722
771
  };
723
772
  //#endregion
@@ -748,14 +797,14 @@ var DefaultConfigDirectorClient = class {
748
797
  readyPromise;
749
798
  readyResolve;
750
799
  currentContext;
751
- streaming;
800
+ connectionMode;
752
801
  constructor(telemetryClient, clientSdkKey, sdkOptions, clientOptions, internalClientOptions) {
753
802
  this.logger = clientOptions?.logger ?? createDefaultLogger$1();
754
803
  this.timeout = clientOptions?.connection?.timeout ?? 3e3;
755
804
  const urlFactory = internalClientOptions?.urlFactory ?? defaultUrlFactory;
756
805
  const baseUrl = this.parseUrl(clientOptions?.connection?.url, urlFactory) ?? "https://client-sdk-api.configdirector.com";
757
- this.streaming = clientOptions?.connection?.streaming === false ? false : true;
758
- const transportConstructor = this.streaming ? StreamingTransport : PullTransport;
806
+ this.connectionMode = clientOptions?.connection?.mode ?? "streaming";
807
+ const transportConstructor = this.getTransportConstructor(this.connectionMode);
759
808
  this.telemetryClient = telemetryClient;
760
809
  this.transport = new transportConstructor({
761
810
  clientSdkKey,
@@ -771,7 +820,8 @@ var DefaultConfigDirectorClient = class {
771
820
  fetch: internalClientOptions?.fetch,
772
821
  connectionRetryDelay: internalClientOptions?.connectionRetryDelay ?? ((attempt) => {
773
822
  return Math.pow(2, Math.min(attempt, MAX_EXPONENTIAL_DELAY)) * 1e3;
774
- })
823
+ }),
824
+ pollingInterval: clientOptions?.connection?.pollingInterval
775
825
  });
776
826
  this.transport.on("configSetReceived", (configSet) => {
777
827
  this.readyResolve?.();
@@ -791,6 +841,13 @@ var DefaultConfigDirectorClient = class {
791
841
  this.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:", { keys: configKeys });
792
842
  });
793
843
  }
844
+ getTransportConstructor(connectionMode) {
845
+ switch (connectionMode) {
846
+ case "one-time": return OneTimeTransport;
847
+ case "polling": return PollingTransport;
848
+ default: return StreamingTransport;
849
+ }
850
+ }
794
851
  async initialize(context) {
795
852
  this.initializing = true;
796
853
  await this.connectToTransport(context, "initialization");
@@ -824,10 +881,7 @@ var DefaultConfigDirectorClient = class {
824
881
  if (remainingTimeout > 0) await Promise.race([this.readyPromise, new Promise((resolve) => {
825
882
  this.timeoutTimer = setTimeout(() => resolve(), remainingTimeout);
826
883
  })]).finally(() => clearTimeout(this.timeoutTimer));
827
- if (!this.ready) {
828
- const warningDetails = this.streaming ? "The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds." : "Since the client was configured without streaming, configs may not update and always return the default value.";
829
- this.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${caller} after ${this.timeout}ms. ${warningDetails}`);
830
- }
884
+ if (!this.ready) this.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${caller} 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.`);
831
885
  } catch (error) {
832
886
  this.logger.error(`[ConfigDirectorClient] An error occurred during ${caller}: `, error);
833
887
  }
@@ -1130,7 +1184,7 @@ var plugin_client_default = defineNuxtPlugin((nuxtApp) => {
1130
1184
  const { clientSdkKey, appName, appVersion, baseUrl } = runtimeConfig.public.configdirector;
1131
1185
  const client = createBrowserClient(clientSdkKey, {
1132
1186
  sdkName: "nuxt-sdk",
1133
- sdkVersion: "0.1.1"
1187
+ sdkVersion: "0.2.0"
1134
1188
  }, {
1135
1189
  metadata: {
1136
1190
  appName,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@configdirector/nuxt-sdk",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Nuxt SDK for ConfigDirector. ConfigDirector is a remote configuration and feature flag service.",
5
5
  "license": "MIT",
6
6
  "author": "ConfigDirector",
@@ -18,7 +18,7 @@
18
18
  "homepage": "https://www.configdirector.com",
19
19
  "repository": {
20
20
  "type": "git",
21
- "url": "https://github.com/ConfigDirector/js-sdks"
21
+ "url": "git+https://github.com/ConfigDirector/js-sdks.git"
22
22
  },
23
23
  "type": "module",
24
24
  "exports": {
@@ -41,7 +41,7 @@
41
41
  "scripts": {
42
42
  "build": "nuxt prepare && tsdown",
43
43
  "prepack": "nuxt prepare && tsdown",
44
- "release": "yarn lint && yarn ci:test && yarn build && npm publish --access public",
44
+ "release": "nuxt prepare && yarn lint && yarn ci:test && yarn build && npm publish --access public",
45
45
  "lint": "eslint .",
46
46
  "ci:test": "vitest run",
47
47
  "test": "vitest watch",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@jsonjoy.com/json-pointer": "^18.1.0",
52
- "@nuxt/kit": "^4.4.2",
52
+ "@nuxt/kit": "^3.7.0 || ^4.0.0",
53
53
  "consola": "^3.4.2",
54
54
  "defu": "^6.1.7",
55
55
  "rapidhash-js": "^3.0.0",
@@ -63,7 +63,7 @@
63
63
  "@types/node": "latest",
64
64
  "changelogen": "^0.6.2",
65
65
  "eslint": "^10.2.1",
66
- "nuxt": "^4.4.2",
66
+ "nuxt": "^4.4.6",
67
67
  "playwright": "^1.52.0",
68
68
  "rimraf": "^6.1.3",
69
69
  "tsdown": "^0.21.7",