@configdirector/nextjs-sdk 0.1.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,316 @@
1
+ //#region ../shared/src/types.d.ts
2
+ type ConfigEnumLikeType = {
3
+ [key: string]: string | number;
4
+ };
5
+ type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
6
+ type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
7
+ interface ConfigDirectorLogger {
8
+ debug(message: string, ...args: any): void;
9
+ info(message: string, ...args: any): void;
10
+ warn(message: string, ...args: any): void;
11
+ error(message: string, ...args: any): void;
12
+ }
13
+ interface ConfigDirectorLogMessageDecorator {
14
+ decorateMessage(message: string): string;
15
+ }
16
+ /**
17
+ * The user's context to be sent to ConfigDirector. This context will be used for targeting
18
+ * rules evaluation.
19
+ */
20
+ type ConfigDirectorContext = {
21
+ /**
22
+ * The user's identifier. This should be a value that uniquely identifies an application
23
+ * user.
24
+ * In the case of anonymous users, you could generate a UUID or alternatively not provide
25
+ * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
26
+ * value is used for segmenting users in percentage rollouts, and changes to the {@link id}
27
+ * could result in the user being assigned to a different percentile.
28
+ */
29
+ id?: string;
30
+ /**
31
+ * The user's display name. This will be shown in the ConfigDirector dashboard and may be
32
+ * used for targeting rules.
33
+ */
34
+ name?: string;
35
+ /**
36
+ * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
37
+ * dashboard and may be used for targeting rules.
38
+ */
39
+ traits?: {
40
+ [key: string]: unknown;
41
+ };
42
+ };
43
+ /**
44
+ * Metadata about your application. It is recommended you include these values when configuring
45
+ * a ConfigDirector client so that you can use them in targeting rules.
46
+ */
47
+ type ConfigDirectorMetaContext = {
48
+ appVersion?: string;
49
+ appName?: string;
50
+ };
51
+ type ConnectionMode = "streaming" | "polling" | "one-time";
52
+ //#endregion
53
+ //#region ../js-server-sdk/src/types.d.ts
54
+ /**
55
+ * Configuration options for the {@link ConfigDirectorClient}
56
+ */
57
+ type ConfigDirectorClientOptions = {
58
+ /**
59
+ * Application metadata that remains constant through the lifetime of the connection
60
+ */
61
+ metadata?: ConfigDirectorMetaContext;
62
+ /**
63
+ * Connection options
64
+ */
65
+ connection?: {
66
+ /**
67
+ * The connection mode to be used, one of `streaming` (default), `polling`, or `one-time`.
68
+ * If set to `streaming`, the connection will remain open and receive updates whenever
69
+ * config state is updated on the ConfigDirector dashboard.
70
+ * When set to `polling`, there will be an initial request to retrieve config state during
71
+ * initialization, and additional requests on a `pollingInterval`.
72
+ * The `one-time` connection mode will only retrieve config state during initialization. It
73
+ * will not poll for regular updates.
74
+ *
75
+ * Defaults to `streaming`
76
+ */
77
+ mode?: ConnectionMode;
78
+ /**
79
+ * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
80
+ * effect when the `mode` is set to `streaming` or `one-time`.
81
+ *
82
+ * Defaults to 60 seconds
83
+ */
84
+ pollingInterval?: number;
85
+ /**
86
+ * The timeout, in milliseconds, to be used in initialization and when updating the context.
87
+ * If streaming is enabled, the operation (initialization or context update) may still succeed
88
+ * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
89
+ * If streaming is disabled, if the operation times out, it will not be retried.
90
+ *
91
+ * Defaults to 3,000 milliseconds (3 seconds)
92
+ */
93
+ timeout?: number;
94
+ /**
95
+ * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
96
+ * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
97
+ * a proxy for the client SDK.
98
+ */
99
+ url?: string;
100
+ };
101
+ /**
102
+ * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
103
+ * logger set to 'warn' level.
104
+ *
105
+ * The log level of the default logger can be adjusted by creating a default logger with the desired
106
+ * level and providing it in this property:
107
+ * @example
108
+ * import { createClient, createConsoleLogger } from "@configdirector/server-sdk";
109
+ * const client = createClient(
110
+ * "YOUR-SERVER-SDK-KEY",
111
+ * { logger: createConsoleLogger("debug") },
112
+ * );
113
+ */
114
+ logger?: ConfigDirectorLogger;
115
+ /**
116
+ * Telemetry tunning. It is unlikely these settings need to be adjusted. However, in cases where
117
+ * your application has a large number of evaluations per second, you can adjust these settings
118
+ * to tune the memory footprint and frequency of telemetry requests.
119
+ * Keep in mind that ConfigDirector relies on these telemetry events to provide insights and features
120
+ * related to the configs being used.
121
+ */
122
+ telemetry?: {
123
+ /**
124
+ * The size limit of telemetry event queues. If the size limit is reached before the events are
125
+ * flushed to the network, older events will be dropped.
126
+ *
127
+ * ConfigDirector keeps a count of dropped events. If the number of dropped events is higher than
128
+ * 50% of the total events, ConfigDirector will issue a notification alert in the dashboard.
129
+ *
130
+ * A number between 100 and 100,000. Defaults to 5,000.
131
+ */
132
+ eventQueueLimit?: number;
133
+ /**
134
+ * How often events are flushed and sent over the network in milliseconds.
135
+ *
136
+ * Decrease this number if your application consistently captures a large number of events in short
137
+ * periods of time in order to reduce memory footprint from a large event queue.
138
+ *
139
+ * Defaults to 30,000 milliseconds (30 seconds)
140
+ */
141
+ flushInterval?: number;
142
+ };
143
+ };
144
+ type ClientEvents = {
145
+ configsUpdated: {
146
+ keys: string[];
147
+ };
148
+ clientReady: undefined;
149
+ };
150
+ type WatchHandler<T extends ConfigValueType> = (message: T) => void;
151
+ /**
152
+ * The ConfigDirector SDK client object.
153
+ *
154
+ * Applications should create a single instance of `ConfigDirectorClient`, and call
155
+ * {@link initialize} during application initialization.
156
+ */
157
+ interface ConfigDirectorClient {
158
+ /**
159
+ * Initializes the connection to ConfigDirector to retrieve config definitions. Until
160
+ * initialization is successful, all flags will return their default value provided to
161
+ * {@link watch} or {@link getValue}.
162
+ *
163
+ * If the connection fails or is interrupted with a transient error (network error,
164
+ * internal server error, etc) the client will continue to attempt to connect. However,
165
+ * if the connection fails with a persistent error, like an invalid SDK key, the client will
166
+ * not attempt to re-connect and an error will be logged to the console or the provided
167
+ * logger.
168
+ */
169
+ initialize(): Promise<void>;
170
+ /**
171
+ * Returns whether or not the client is ready after calling {@link initialize}
172
+ *
173
+ * The definition of ready is that the connection to the server was successful, and config definitions
174
+ * were received.
175
+ */
176
+ get isReady(): boolean;
177
+ /**
178
+ * Evaluates a config and returns its value based on the current context and targeting rules
179
+ *
180
+ * @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
181
+ * @param configKey The config key to evaluate
182
+ * @param defaultValue The default value to be returned if the config state is unavailable. For
183
+ * example, if the client cannot connect to the server due to network conditions, or if getValue
184
+ * is called before initialization is done.
185
+ * @param context The user's context to be used for targeting rules evaluation (optional)
186
+ */
187
+ getValue<T extends ConfigValueType>(configKey: string, defaultValue: T, context?: ConfigDirectorContext): T;
188
+ /**
189
+ * Watches for changes to a a config evaluation value. Whenever the config value changes, the
190
+ * provided callback function will be called with the new value. Changes can happen due to updates
191
+ * to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
192
+ *
193
+ * @returns An 'unwatch' function that can be called to remove the subscriber
194
+ *
195
+ * @param configKey The config key to watch
196
+ * @param defaultValue The default value to be referenced if the config state is unavailable
197
+ * @param callback The callback function to be called whenever the config value is updated
198
+ * @param context The user's context to be used for targeting rules evaluation (optional)
199
+ */
200
+ watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>, context?: ConfigDirectorContext): () => void;
201
+ /**
202
+ * Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
203
+ * is provided.
204
+ *
205
+ * @param configKey The config key to remove subscribers from
206
+ * @param callback The subscriber to be removed. If not provided, all subscribers are removed for
207
+ * the given `configKey`.
208
+ */
209
+ unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
210
+ /**
211
+ * Removes all subscribers from all config keys
212
+ */
213
+ unwatchAll(): void;
214
+ on<T extends keyof ClientEvents>(eventName: T, handler: (args: ClientEvents[T]) => void): void;
215
+ off<T extends keyof ClientEvents>(eventName: T, handler?: (args: ClientEvents[T]) => void): void;
216
+ /**
217
+ * Disposes of the client. All connections are closed, and all event and config key subscribers
218
+ * are removed.
219
+ *
220
+ * Intended to be called when your application shuts down
221
+ */
222
+ dispose(): void;
223
+ }
224
+ //#endregion
225
+ //#region src/server/singleton.d.ts
226
+ declare global {
227
+ var __configDirectorServerClient: ConfigDirectorClient | undefined;
228
+ }
229
+ type RegisterOptions = {
230
+ /**
231
+ * Your ConfigDirector Server SDK key. This is a secret value — do not commit it to source
232
+ * control. Provide it via an environment variable (e.g. process.env.CONFIGDIRECTOR_SERVER_KEY).
233
+ */
234
+ serverSdkKey: string;
235
+ } & ConfigDirectorClientOptions;
236
+ /**
237
+ * Initializes the ConfigDirector server SDK singleton. Call this from your Next.js
238
+ * `instrumentation.ts` file so it runs once when the server starts:
239
+ *
240
+ * ```ts
241
+ * // instrumentation.ts
242
+ * export async function register() {
243
+ * if (process.env.NEXT_RUNTIME === "nodejs") {
244
+ * const { register } = await import("@configdirector/nextjs-sdk/server");
245
+ * await register({ serverSdkKey: process.env.CONFIGDIRECTOR_SERVER_KEY! });
246
+ * }
247
+ * }
248
+ * ```
249
+ */
250
+ declare function register(options: RegisterOptions): Promise<void>;
251
+ declare function getServerSingleton(): ConfigDirectorClient;
252
+ //#endregion
253
+ //#region src/server/SsrClient.d.ts
254
+ /**
255
+ * A thin wrapper around the server SDK singleton that binds a per-request user context to every
256
+ * evaluation, making it behave like the browser client (no context arg on getValue/watch) from
257
+ * the perspective of calling code.
258
+ *
259
+ * Create one per request via {@link createSsrClient}. The underlying server SDK singleton is
260
+ * shared and long-lived; the SsrClient is lightweight and request-scoped.
261
+ */
262
+ declare class SsrClient {
263
+ private readonly context;
264
+ constructor(context: ConfigDirectorContext | undefined);
265
+ get isReady(): boolean;
266
+ getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
267
+ /**
268
+ * Synchronously evaluates the config and calls the callback once, then returns a no-op unwatch.
269
+ *
270
+ * In a Server Component there is no component lifecycle to subscribe to, so live-watching is not
271
+ * meaningful. Use getValue() directly in Server Components; watch() is here for symmetry with the
272
+ * browser client interface.
273
+ */
274
+ watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>): () => void;
275
+ unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
276
+ unwatchAll(): void;
277
+ }
278
+ /**
279
+ * Creates a request-scoped {@link SsrClient} that evaluates configs against the shared server
280
+ * SDK singleton using the provided user context.
281
+ *
282
+ * Call this in Server Components or Route Handlers:
283
+ *
284
+ * ```ts
285
+ * // app/dashboard/page.tsx (Server Component)
286
+ * import { createSsrClient } from "@configdirector/nextjs-sdk/server";
287
+ * import { cookies } from "next/headers";
288
+ *
289
+ * export default async function DashboardPage() {
290
+ * const userId = (await cookies()).get("userId")?.value;
291
+ * const client = createSsrClient({ userId });
292
+ * const showNewDashboard = client.getValue("new-dashboard", false);
293
+ * // ...
294
+ * }
295
+ * ```
296
+ */
297
+ declare function createSsrClient(context?: ConfigDirectorContext): SsrClient;
298
+ //#endregion
299
+ //#region ../shared/src/logger.d.ts
300
+ declare class DefaultConsoleLogger implements ConfigDirectorLogger {
301
+ private readonly level;
302
+ private readonly decorator;
303
+ private readonly dateFormatter;
304
+ constructor(level: ConfigDirectorLoggingLevel, decorator: ConfigDirectorLogMessageDecorator);
305
+ debug(message: string, ...args: any): void;
306
+ info(message: string, ...args: any): void;
307
+ warn(message: string, ...args: any): void;
308
+ error(message: string, ...args: any): void;
309
+ protected log(loggerFunction: (...args: any) => void, level: ConfigDirectorLoggingLevel, message: string, ...args: any): void;
310
+ }
311
+ //#endregion
312
+ //#region src/server/logger.d.ts
313
+ declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel, messageDecorator?: ConfigDirectorLogMessageDecorator) => DefaultConsoleLogger;
314
+ //#endregion
315
+ export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, type ConfigDirectorLogger, type ConfigDirectorMetaContext, type ConfigValueType, type ConnectionMode, type RegisterOptions, SsrClient, createConsoleLogger, createSsrClient, getServerSingleton, register };
316
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../shared/src/types.ts","../../../js-server-sdk/src/types.ts","../../src/server/singleton.ts","../../src/server/SsrClient.ts","../../../shared/src/logger.ts","../../src/server/logger.ts"],"mappings":"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"}
@@ -0,0 +1,6 @@
1
+ import e,{EventEmitter as t}from"node:events";import{findByPointer as n}from"@jsonjoy.com/json-pointer";import*as r from"semver";import{rapidhash as i}from"rapidhash-js";var a=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},o=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},s=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}},c=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},l=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},ee=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},te=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},u=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
2
+ `?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
3
+ `&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){this.onComment?.(this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
4
+ `)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent({...this.currentEvent,id:this.lastEventId,data:e}),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
5
+ `;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:/^\d+$/.test(e.value)&&this.onRetry?.(Number.parseInt(e.value,10));break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let d=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var f=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=d.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers},this.requestOptions={body:e.body,method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===d.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=d.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=d.CONNECTING,this._fetch(this.url,{...this.requestOptions,headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`}).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new l(`The server response did not have a body`);this._readyState=d.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new u({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new c(`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=d.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...this.headers,...e}}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=d.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new te(`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 ee(`${n} must be a function`);return e}};const p=e=>new f(e);var m=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=new URL(`server/sse/v1`,e.baseUrl)}async connect(e){this.eventSource&&this.close();let t=new Promise((e,t)=>{this.eventSource=p({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey}),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[EventSourceTransport] Connected`),e(this)},shouldReconnect:e=>{let n=!this.isStatusFatal(e.status);return n||t(this.prepareFatalError(e.status,e.error)),n},calculateReconnectDelay:e=>{let t=2**Math.min(e.attempt,9)*1e3;return this.logger.warn(`[EventSourceTransport] Scheduling reconnect in ${t}ms.`),t},onDisconnect:()=>{this.logger.debug(`[EventSourceTransport] Disconnected`)}}),this.eventSource.connect()});return Promise.race([t,new Promise(t=>{setTimeout(()=>t(this),e)})])}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configBundleReceived`,t)}catch(e){this.logger.error(`[EventSourceTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let n=e??0;return new a(`${`Connection failed with status: ${e??`unknown`}.`}${t?` Error: ${t}.`:``} This is an unrecoverable error, will not attempt to reconnect.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500}get isConnected(){return this.eventSource?.readyState==`open`}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}close(){this.eventSource?.close()}dispose(){this.close(),this.clear()}},h=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){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.prepareFatalResponseStatusError(e.status,await e.text())):new a(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new a(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new a(`Failed to parse the response from the server: ${e}`):new a(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new a(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500}isFetchErrorFatal(e){return e?.name===`NotAllowedError`?!0:e instanceof TypeError}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const g=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var _=class extends h{constructor(e){super(),this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=new URL(`server/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??60}async connect(e){return this.clearPollingInterval(),await this.fetchConfigs(e),this.schedulePollingInterval(()=>{this.fetchConfigs(e).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})}),this}async fetchConfigs(e){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let t=await g(e,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,lastUpdateTimestamp:this.lastUpdateTimestamp})},this.logger);if(await this.handleNonOkResponse(t),t.status===200){let e=JSON.parse(await t.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configBundleReceived`,e)}}catch(e){this.handleFetchError(e)}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}},ne=class extends _{constructor(e){super(e),this.pollingIntervalSeconds=0}};const re=(e,t,n)=>{switch(t.toLowerCase()){case`=`:case`equals`:return e==n[0];case`!=`:case`does not equal`:return e!=n[0];case`is one of`:return n.includes(e);case`is not one of`:return!n.includes(e);case`starts with any of`:return n.findIndex(t=>e?.startsWith(t))>=0;case`does not start with any of`:return n.findIndex(t=>e?.startsWith(t))<0;case`ends with any of`:return n.findIndex(t=>e?.endsWith(t))>=0;case`does not end with any of`:return n.findIndex(t=>e?.endsWith(t))<0;case`matches regex`:return v(n[0],e);case`does not match regex`:return!v(n[0],e);default:return!1}},v=(e,t)=>{try{return new RegExp(e).test(t)}catch{return!1}},y=(e,t,n)=>{if(typeof e==`boolean`)return!1;let r=t.toLowerCase();if(e==null)return r==`!=`||r==`does not equal`;let{value:i,target:a}=b(e,n[0]);switch(r){case`=`:case`equals`:return i==a;case`!=`:case`does not equal`:return i!=a;case`<`:return i<a;case`<=`:return i<=a;case`>`:return i>a;case`>=`:return i>=a;default:return!1}},b=(e,t)=>typeof e==`number`?{value:e,target:x(t)}:typeof e==`bigint`?{value:e,target:BigInt(t)}:{value:x(e),target:x(t)},x=e=>{let t=Number.parseFloat(e.toString());if(isNaN(t)||!isFinite(t))throw TypeError(`Invalid numeric value: ${e}`);return t},S=(e,t,n)=>{if(e==null)return!1;try{let r=new Date(e),i=new Date(n[0]);switch(t){case`is after`:return r>i;case`is before`:return r<i;default:return!1}}catch{return!1}},C=(e,t,n)=>{let i=t.toLowerCase();if(e==null||e.trim().length==0)return i==`is not one of`;let a=r.coerce(e)??e,o=n.map(e=>r.coerce(e)??e);try{switch(i){case`=`:return w(a,o[0]);case`<`:return r.lt(a,o[0]);case`<=`:return r.lte(a,o[0]);case`>`:return r.gt(a,o[0]);case`>=`:return r.gte(a,o[0]);case`is one of`:return o.findIndex(e=>w(a,e))>=0;case`is not one of`:return o.findIndex(e=>w(a,e))<0;default:return!1}}catch{return!1}},w=(e,t)=>{try{return r.eq(e,t)}catch{return!1}},T=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r==`does not contain any of`;switch(r){case`contains any of`:return e.some(e=>n.includes(e));case`does not contain any of`:return!e.some(e=>n.includes(e));default:return!1}};var E=class{evaluate(e,t){if(!this.isConditionValidForComparison(e))return!1;switch(e.attribute){case`identifier`:return this.compare(t?.context?.id,e);case`name`:return this.compare(t?.context?.name,e);case`appName`:return this.compare(t?.metadata?.appName,e);case`appVersion`:return this.compare(t?.metadata?.appVersion,e);case`traits`:if(e.trait){let n=this.findTraitValue(t?.context?.traits,e.trait);return this.compare(n,e)}}return!1}compare(e,t){switch(t.targetType){case`text`:return re(e?.toString(),t.operator,t.targetValues);case`number`:return y(e,t.operator,t.targetValues);case`datetime`:return S(e?.toString(),t.operator,t.targetValues);case`semver`:return C(e?.toString(),t.operator,t.targetValues);case`array`:return T(e,t.operator,t.targetValues)}return!1}findTraitValue(e,t){try{return n(t,e).val}catch{return}}isConditionValidForComparison(e){return Array.isArray(e.targetValues)&&e.targetValues.length>0}};const D=e=>{let t=`${e.contextIdentifier}-${e.configId}`;return Number(i(t,{seed:15426857351n})%1000n)/10};var O=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new E,!e||!e.warn||!e.error||!e.info)throw TypeError(`The provided logger is not a valid 'ConfigDirectorLogger'`);this.logger=e}evaluate(e,t){return{id:e.id,key:e.key,type:e.type,value:this.getConfigValue(e,t)}}getConfigValue(e,t){let n=[...e.target?.rules??[]].sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1));for(let r of n){let n=this.evaluateRule(r,e,t);if(n.success)return n.value}return e.target?.defaultValue}evaluateRule(e,t,n){try{if(e.type==`percentage`)return this.evaluatePercentageRule(e,t,n);if(e.type==`conditional`)return this.evaluateConditionalRule(e,t,n)}catch(n){this.logger.warn(`There was an error while evaluating a targeting rule '${e?.id}' for '${t?.key}'. The rule will be disregarded.`,{error:n,configKey:t?.key,ruleId:e?.id})}return{success:!1}}evaluatePercentageRule(e,t,n){return this.evaluatePercentage(e.percentages??[],t,n)}evaluatePercentage(e,t,n){let r=D({configId:t.id,contextIdentifier:n?.context?.id??crypto.randomUUID()}),i=0,a=0,o;for(;!o&&i<e.length;)r<=e[i].percentage+a&&(o=e[i]),a+=e[i].percentage,i+=1;return o?.value==null?{success:!1}:{success:!0,value:o.value.toString()}}evaluateConditionalRule(e,t,n){let r=e.conditions??[],i=0,a;for(;!a&&i<r.length;)this.conditionEvaluator.evaluate(r[i],n)&&(a=r[i]),i+=1;return a&&e.target==`value`&&e.value!=null?{success:!0,value:e.value.toString()}:a&&e.target==`percentage`?this.evaluatePercentage(e.percentages??[],t,n):{success:!1}}};const k=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},A=e=>e===`number`||e===`bigint`,j=(e,t)=>{let n=e.value,r=k(t);if(!n)return{parsedValue:t,requestedType:r,usedDefault:!0,reason:`value-missing`};if(typeof t==`string`)return{parsedValue:n,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&e.type===`boolean`){let e=M(n),i=typeof e==`boolean`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-boolean`}}if(A(typeof t)&&e.type===`integer`){let e=N(n),i=typeof e==`number`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-number`}}if(A(typeof t)&&(e.type===`float`||e.type===`enum`)){let e=P(n),i=typeof e==`number`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-number`}}return{parsedValue:n,requestedType:r,usedDefault:!1,reason:`found-match`}},M=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},N=e=>{if(!e)return;let t=Number.parseInt(e);if(!(isNaN(t)||!isFinite(t)))return t},P=e=>{if(!e)return;let t=Number.parseFloat(e);if(!(isNaN(t)||!isFinite(t)))return t},F={off:-1,error:0,warn:1,info:2,debug:3},I=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,{...e,fractionalSecondDigits:3})}catch{return new Intl.DateTimeFormat(void 0,e)}};var L=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=I()}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){F[this.level]>=F[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},R=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const ie=(e,t)=>new L(e??`warn`,t??new R),z=(e,t)=>new URL(e,t?.toString()),B=(e,t)=>{if(t===`json`)try{return V(JSON.stringify(e))}catch{return e.toString().slice(0,500)}return e.toString().slice(0,500)},V=e=>H(new TextEncoder().encode(e)).toString(16).padStart(8,`0`),H=e=>{let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+(e[n]??0),t>>>=0;return t},U=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},W=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};var G=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.url=new URL(`server/telemetry/v1`,e.baseUrl.toString())}async report({discreteEvents:e,aggregatedEvents:t,droppedEvents:n}){if(!this.executeRequests)return{success:!1,fatalError:!0};let r={serverSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:t,droppedEvents:n};if(this.isReportEmpty(r))return{success:!0,fatalError:!1};let i=await this.sendReport(r);return i.fatalError&&(this.executeRequests=!1),i}isReportEmpty(e){return U(e.discreteEvents)&&U(e.aggregatedEvents)&&W(e.droppedEvents)}async sendReport(e){try{let t=await g(5e3,this.url,{method:`POST`,body:JSON.stringify(e)},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){return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:!1}}}isStatusFatal(e){return!!e&&e>=400&&e<500}},K=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}))}},q=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||(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}},J=class{constructor(e){this.aggregator=new K,this.collectEvents=!0,this.logger=e.logger,this.evaluationEventQueue=new q(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4;let t=e.initialFlushIntervalDelay??5e3;this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),t)}sanitizeValue(e,t){return B(e,t)}async flushAndScheduleNext(){(await this.flush()).fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay)}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=this.evaluationEventQueue.takeSnapshot();return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout),await this.flush(),this.evaluationEventQueue.clear()}dispose(){this.close()}},Y=class extends Map{constructor(e,t){super(t),this._droppedCount=0,this.limit=e,this.enforceLimit()}set(e,t){return super.set(e,t),this.enforceLimit(),this}get droppedCount(){return this._droppedCount}clearAndReset(){this.clear(),this._droppedCount=0}enforceLimit(){for(;this.size>this.limit;){let e=this.keys().next().value;e!==void 0&&(this.delete(e),this._droppedCount+=1)}}},ae=class extends J{constructor(e){super(e),this.reporter=new G(e),this.contexts=new Y(e.contextLimit??1e3)}evaluatedConfig(e){if(!this.collectEvents)return;e.context?.id&&this.contexts.set(e.context.id,e.context);let t={...e.evaluation,contextId:e.context?.id};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:this.sanitizeValue(e.defaultValue,e.type),evaluatedValue:this.sanitizeValue(e.evaluatedValue,e.type)}}snapshotContexts(){let e=Array.from(this.contexts.values()),t=this.contexts.droppedCount;return this.contexts.clearAndReset(),{contexts:e,droppedCount:t}}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=this.evaluationEventQueue.takeSnapshot(),t=this.snapshotContexts();return await this.reporter?.report({context:this._context,discreteEvents:{capturedContexts:t.contexts},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const oe=new URL(`https://server-sdk-api.configdirector.com`);var se=class{constructor(t,n,r){this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.logger=r?.logger??ie(),this.timeout=r?.connection?.timeout??3e3,this.metaContext=r?.metadata??{},this.configEvaluator=new O(this.logger);let i=this.parseUrl(r?.connection?.url)??oe;this.connectionMode=r?.connection?.mode??`streaming`;let a=this.getTransportConstructor(this.connectionMode),o=r?.telemetry?.eventQueueLimit??5e3;this.usageEventCollector=new ae({sdkKey:t,logger:this.logger,baseUrl:i,flushIntervalDelay:r?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(o*.7),contextLimit:Math.floor(o*.3),urlFactory:z}),this.transport=new a({serverSdkKey:t,baseUrl:i,metaContext:{...r?.metadata,sdkName:n.sdkName,sdkVersion:n.sdkVersion},logger:this.logger,pollingInterval:r?.connection?.pollingInterval}),this.transport.on(`configBundleReceived`,e=>{this.readyResolve?.();let t=Object.keys(e.configs);!this.configSet||e.kind==`full`?(this.configSet=e,this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)):(this.configSet.configs={...this.configSet.configs,...e.configs},this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server with ${t.length} key(s)`,{keys:t})})}async initialize(){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(()=>{this.ready=!0,this.eventEmitter.emit(`clientReady`),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`)});let e=new Date().getTime();await this.transport.connect(this.timeout);let t=new Date().getTime()-e,n=this.timeout-t;if(n>0&&await Promise.race([this.readyPromise,new Promise(e=>{setTimeout(()=>e(),n)})]),!this.ready){let e=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.`;this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${e}`)}}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}getTransportConstructor(e){switch(e){case`one-time`:return ne;case`polling`:return _;default:return m}}updateWatchers(e){Object.values(e).forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){this.handlersMap.get(e.key)?.forEach(t=>{let n=this.getValueFromConfigDefinition(e.key,e,t.defaultValue,t.context);t.handler(n)})}watch(e,t,n,r){this.validateDefaultValue(t);let i=this.handlersMap.get(e),a={handler:n,defaultValue:t,requestedType:typeof t,context:r};return i?i.push(a):this.handlersMap.set(e,[a]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t,n){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.getValueFromConfigDefinition(e,r,t,n)}getValueFromConfigDefinition(e,t,n,r){if(t){let i=j(this.configEvaluator.evaluate(t,{context:r,metadata:this.metaContext}),n);return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,defaultValue:n,requestedType:i.requestedType,evaluatedValue:i.parsedValue,usedDefault:i.usedDefault,evaluationReason:i.reason}}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${i.parsedValue}'`),i.parsedValue}else return this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`),this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,defaultValue:n,requestedType:k(n),evaluatedValue:n,usedDefault:!0,evaluationReason:`config-state-missing`}}),n}parseUrl(e){if(e)try{return new URL(e)}catch(t){throw new o(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateDefaultValue(e){if(e==null)throw new o(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new o(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}removeAllObservers(){this.logger.debug(`[ConfigDirectorClient] removeAllObservers() has been called, removing all observers`),this.eventEmitter.removeAllListeners(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}dispose(){this.removeAllObservers(),this.closeConnection()}},X=class{decorateMessage(e){return`[ConfigDirector:nextjs-sdk] ${e}`}};const ce=(e,t)=>new L(e??`warn`,t??new X),Z=(e,t)=>new L(e,t??new X);async function le(e){if(!e.serverSdkKey){let e=`The ConfigDirector serverSdkKey must be provided to register(). You can pass it via process.env.CONFIGDIRECTOR_SERVER_KEY.`;throw ce().error(e),new s(e)}if(!globalThis.__configDirectorServerClient){let{serverSdkKey:t,...n}=e,r=new se(t,{sdkName:`nextjs-sdk`,sdkVersion:`0.1.0`},n);globalThis.__configDirectorServerClient=r,await r.initialize()}}function Q(){if(!globalThis.__configDirectorServerClient)throw new s(`[ConfigDirector] Server client not initialized. Make sure to call register() in your instrumentation.ts file before using the SDK.`);return globalThis.__configDirectorServerClient}var $=class{constructor(e){this.context=e}get isReady(){return Q().isReady}getValue(e,t){return Q().getValue(e,t,this.context)}watch(e,t,n){return n(this.getValue(e,t)),()=>{}}unwatch(e,t){Q().unwatch(e,t)}unwatchAll(){Q().unwatchAll()}};function ue(e){return new $(e)}export{$ as SsrClient,Z as createConsoleLogger,ue as createSsrClient,Q as getServerSingleton,le as register};
6
+ //# sourceMappingURL=index.mjs.map