@configdirector/nextjs-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/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +21 -40
- package/dist/client/index.d.cts.map +1 -1
- package/dist/client/index.d.mts +21 -40
- package/dist/client/index.d.mts.map +1 -1
- package/dist/client/index.mjs +1 -1
- package/dist/client/index.mjs.map +1 -1
- package/dist/server/DefaultConfigDirectorClient-BZA1xhE9.cjs +5 -0
- package/dist/server/DefaultConfigDirectorClient-Dw-ZzO94.mjs +6 -0
- package/dist/server/DefaultConfigDirectorClient-Dw-ZzO94.mjs.map +1 -0
- package/dist/server/errors-B1AJJTZ-.mjs +2 -0
- package/dist/server/errors-B1AJJTZ-.mjs.map +1 -0
- package/dist/server/errors-zhcEWVnY.cjs +1 -0
- package/dist/server/index.cjs +1 -5
- package/dist/server/index.d.cts +135 -44
- package/dist/server/index.d.cts.map +1 -1
- package/dist/server/index.d.mts +135 -44
- package/dist/server/index.d.mts.map +1 -1
- package/dist/server/index.mjs +1 -5
- package/dist/server/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/server/index.d.mts
CHANGED
|
@@ -1,8 +1,19 @@
|
|
|
1
|
+
import * as _$react_jsx_runtime0 from "react/jsx-runtime";
|
|
2
|
+
import { PropsWithChildren } from "react";
|
|
3
|
+
|
|
1
4
|
//#region ../shared/src/types.d.ts
|
|
5
|
+
declare const ConfigTypeList: readonly ["custom", "boolean", "string", "integer", "float", "enum", "url", "json"];
|
|
6
|
+
type ConfigType = (typeof ConfigTypeList)[number];
|
|
2
7
|
type ConfigEnumLikeType = {
|
|
3
8
|
[key: string]: string | number;
|
|
4
9
|
};
|
|
5
10
|
type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
|
|
11
|
+
type ConfigState = {
|
|
12
|
+
id: string;
|
|
13
|
+
key: string;
|
|
14
|
+
type: ConfigType;
|
|
15
|
+
value: string | undefined | null;
|
|
16
|
+
};
|
|
6
17
|
type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
|
|
7
18
|
interface ConfigDirectorLogger {
|
|
8
19
|
debug(message: string, ...args: any): void;
|
|
@@ -211,6 +222,17 @@ interface ConfigDirectorClient {
|
|
|
211
222
|
* Removes all subscribers from all config keys
|
|
212
223
|
*/
|
|
213
224
|
unwatchAll(): void;
|
|
225
|
+
/**
|
|
226
|
+
* Returns the evaluated {@link ConfigState} for every known config key, or only the keys
|
|
227
|
+
* listed in `configKeys` when provided.
|
|
228
|
+
*
|
|
229
|
+
* Intended for SSR hydration — does NOT record telemetry events. Returns an empty object
|
|
230
|
+
* when the client is not yet ready.
|
|
231
|
+
*/
|
|
232
|
+
getAllConfigs(options?: {
|
|
233
|
+
context?: ConfigDirectorContext;
|
|
234
|
+
configKeys?: string[];
|
|
235
|
+
}): Record<string, ConfigState>;
|
|
214
236
|
on<T extends keyof ClientEvents>(eventName: T, handler: (args: ClientEvents[T]) => void): void;
|
|
215
237
|
off<T extends keyof ClientEvents>(eventName: T, handler?: (args: ClientEvents[T]) => void): void;
|
|
216
238
|
/**
|
|
@@ -225,6 +247,10 @@ interface ConfigDirectorClient {
|
|
|
225
247
|
//#region src/server/singleton.d.ts
|
|
226
248
|
declare global {
|
|
227
249
|
var __configDirectorServerClient: ConfigDirectorClient | undefined;
|
|
250
|
+
var __configDirectorAppMeta: {
|
|
251
|
+
appName?: string;
|
|
252
|
+
appVersion?: string;
|
|
253
|
+
} | undefined;
|
|
228
254
|
}
|
|
229
255
|
type RegisterOptions = {
|
|
230
256
|
/**
|
|
@@ -240,61 +266,38 @@ type RegisterOptions = {
|
|
|
240
266
|
* ```ts
|
|
241
267
|
* // instrumentation.ts
|
|
242
268
|
* export async function register() {
|
|
243
|
-
*
|
|
244
|
-
*
|
|
245
|
-
* await register({ serverSdkKey: process.env.CONFIGDIRECTOR_SERVER_KEY! });
|
|
246
|
-
* }
|
|
269
|
+
* const { register } = await import("@configdirector/nextjs-sdk/server");
|
|
270
|
+
* await register({ serverSdkKey: process.env.CONFIGDIRECTOR_SERVER_KEY! });
|
|
247
271
|
* }
|
|
248
272
|
* ```
|
|
249
273
|
*/
|
|
250
274
|
declare function register(options: RegisterOptions): Promise<void>;
|
|
275
|
+
declare function getAppMeta(): {
|
|
276
|
+
appName?: string;
|
|
277
|
+
appVersion?: string;
|
|
278
|
+
};
|
|
251
279
|
declare function getServerSingleton(): ConfigDirectorClient;
|
|
252
280
|
//#endregion
|
|
253
|
-
//#region src/server/
|
|
254
|
-
|
|
255
|
-
|
|
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;
|
|
281
|
+
//#region src/server/ssr.d.ts
|
|
282
|
+
type GenerateSsrConfigSetOptions = {
|
|
283
|
+
/** User context for targeting rule evaluation. */context?: ConfigDirectorContext;
|
|
267
284
|
/**
|
|
268
|
-
*
|
|
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.
|
|
285
|
+
* Restrict the returned config set to these keys. When omitted, all known configs are
|
|
286
|
+
* returned. Useful when you want to pre-evaluate only a specific subset of flags.
|
|
273
287
|
*/
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
unwatchAll(): void;
|
|
277
|
-
}
|
|
288
|
+
configKeys?: string[];
|
|
289
|
+
};
|
|
278
290
|
/**
|
|
279
|
-
*
|
|
280
|
-
*
|
|
291
|
+
* Evaluates configs server-side and returns a map of {@link ConfigState} objects keyed by
|
|
292
|
+
* config key, suitable for passing as `initialConfigs` to `ConfigDirectorProvider`.
|
|
281
293
|
*
|
|
282
|
-
*
|
|
294
|
+
* Returns an empty object when the server SDK isn't initialized yet (e.g. during
|
|
295
|
+
* `next build` static analysis without a live connection).
|
|
283
296
|
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
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
|
-
* ```
|
|
297
|
+
* In most cases you don't need this directly — use the `ConfigDirectorProvider` exported
|
|
298
|
+
* from `@configdirector/nextjs-sdk/server`, which calls this automatically.
|
|
296
299
|
*/
|
|
297
|
-
declare function
|
|
300
|
+
declare function generateSsrConfigSet(options?: GenerateSsrConfigSetOptions): Record<string, ConfigState>;
|
|
298
301
|
//#endregion
|
|
299
302
|
//#region ../shared/src/logger.d.ts
|
|
300
303
|
declare class DefaultConsoleLogger implements ConfigDirectorLogger {
|
|
@@ -309,8 +312,96 @@ declare class DefaultConsoleLogger implements ConfigDirectorLogger {
|
|
|
309
312
|
protected log(loggerFunction: (...args: any) => void, level: ConfigDirectorLoggingLevel, message: string, ...args: any): void;
|
|
310
313
|
}
|
|
311
314
|
//#endregion
|
|
315
|
+
//#region src/client/types.d.ts
|
|
316
|
+
type ConfigDirectorProviderOptions = {
|
|
317
|
+
/**
|
|
318
|
+
* Your ConfigDirector Client SDK key. This is a public value safe for the browser.
|
|
319
|
+
*/
|
|
320
|
+
sdkKey: string;
|
|
321
|
+
appName?: string;
|
|
322
|
+
appVersion?: string;
|
|
323
|
+
/**
|
|
324
|
+
* Override the ConfigDirector client API base URL. Primarily useful for testing or proxying.
|
|
325
|
+
*/
|
|
326
|
+
url?: string;
|
|
327
|
+
/**
|
|
328
|
+
* Initialization timeout in milliseconds. Defaults to 3000.
|
|
329
|
+
*/
|
|
330
|
+
timeout?: number;
|
|
331
|
+
/**
|
|
332
|
+
* Initial user context to evaluate targeting rules against.
|
|
333
|
+
*/
|
|
334
|
+
context?: ConfigDirectorContext;
|
|
335
|
+
/**
|
|
336
|
+
* Log level for the console logger. Defaults to "warn".
|
|
337
|
+
*/
|
|
338
|
+
logLevel?: ConfigDirectorLoggingLevel;
|
|
339
|
+
/**
|
|
340
|
+
* Pre-evaluated config states from the server, used to hydrate client components correctly
|
|
341
|
+
* during SSR. Obtain these via {@link generateSsrConfigSet} or by using the
|
|
342
|
+
* `ConfigDirectorProvider` exported from `@configdirector/nextjs-sdk/server`, which
|
|
343
|
+
* populates this automatically.
|
|
344
|
+
*
|
|
345
|
+
* When the browser client is not yet ready (during SSR and the initial client render before
|
|
346
|
+
* initialization completes), hooks will return values from this map rather than the default
|
|
347
|
+
* value, avoiding a flash of wrong content on hydration.
|
|
348
|
+
*/
|
|
349
|
+
initialConfigs?: Record<string, ConfigState>;
|
|
350
|
+
};
|
|
351
|
+
//#endregion
|
|
352
|
+
//#region src/server/ConfigDirectorProvider.d.ts
|
|
353
|
+
/**
|
|
354
|
+
* Props for {@link ConfigDirectorProvider}. Identical to the client provider options
|
|
355
|
+
* except `initialConfigs` is omitted — SSR-evaluated values are injected automatically.
|
|
356
|
+
*/
|
|
357
|
+
type ConfigDirectorProviderProps = Omit<ConfigDirectorProviderOptions, "initialConfigs"> & {
|
|
358
|
+
/**
|
|
359
|
+
* Restrict SSR pre-evaluation to these config keys. When omitted, all known configs are
|
|
360
|
+
* pre-evaluated. Useful when you have a large config set and only need a subset hydrated
|
|
361
|
+
* on this layout.
|
|
362
|
+
*/
|
|
363
|
+
configKeys?: string[];
|
|
364
|
+
};
|
|
365
|
+
/**
|
|
366
|
+
* React Server Component wrapper around the ConfigDirector client provider.
|
|
367
|
+
*
|
|
368
|
+
* Place this in your root layout. It pre-evaluates all configs on the server using the
|
|
369
|
+
* provided context and passes them to the client provider, preventing any flash of wrong
|
|
370
|
+
* content on hydration.
|
|
371
|
+
*
|
|
372
|
+
* Requires Next.js 13+ (App Router) and React 18+.
|
|
373
|
+
*
|
|
374
|
+
* @example
|
|
375
|
+
* ```tsx
|
|
376
|
+
* // app/layout.tsx
|
|
377
|
+
* import { ConfigDirectorProvider } from "@configdirector/nextjs-sdk/server";
|
|
378
|
+
* import { cookies } from "next/headers";
|
|
379
|
+
*
|
|
380
|
+
* export default async function RootLayout({ children }) {
|
|
381
|
+
* const userId = (await cookies()).get("userId")?.value;
|
|
382
|
+
* return (
|
|
383
|
+
* <html>
|
|
384
|
+
* <body>
|
|
385
|
+
* <ConfigDirectorProvider
|
|
386
|
+
* sdkKey={process.env.NEXT_PUBLIC_CONFIGDIRECTOR_CLIENT_KEY!}
|
|
387
|
+
* context={{ userId }}
|
|
388
|
+
* >
|
|
389
|
+
* {children}
|
|
390
|
+
* </ConfigDirectorProvider>
|
|
391
|
+
* </body>
|
|
392
|
+
* </html>
|
|
393
|
+
* );
|
|
394
|
+
* }
|
|
395
|
+
* ```
|
|
396
|
+
*/
|
|
397
|
+
declare function ConfigDirectorProvider({
|
|
398
|
+
children,
|
|
399
|
+
configKeys,
|
|
400
|
+
...props
|
|
401
|
+
}: PropsWithChildren<ConfigDirectorProviderProps>): Promise<_$react_jsx_runtime0.JSX.Element>;
|
|
402
|
+
//#endregion
|
|
312
403
|
//#region src/server/logger.d.ts
|
|
313
404
|
declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel, messageDecorator?: ConfigDirectorLogMessageDecorator) => DefaultConsoleLogger;
|
|
314
405
|
//#endregion
|
|
315
|
-
export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, type ConfigDirectorLogger, type ConfigDirectorMetaContext, type ConfigValueType, type ConnectionMode, type
|
|
406
|
+
export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, type ConfigDirectorLogger, type ConfigDirectorMetaContext, ConfigDirectorProvider, type ConfigDirectorProviderProps, type ConfigValueType, type ConnectionMode, type GenerateSsrConfigSetOptions, type RegisterOptions, createConsoleLogger, generateSsrConfigSet, getAppMeta, getServerSingleton, register };
|
|
316
407
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +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/
|
|
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/ssr.ts","../../../shared/src/logger.ts","../../src/client/types.ts","../../src/server/ConfigDirectorProvider.tsx","../../src/server/logger.ts"],"mappings":";;;;cAAa,cAAA;AAAA,KAUD,UAAA,WAAqB,cAAA;AAAA,KAErB,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAEvD,WAAA;EACV,EAAA;EACA,GAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;AAAA;AAAA,KAQU,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;;;;;KAgBN,qBAAA;EArCV;;;AAQF;;;;;EAsCE,EAAA;EApCmC;;;;EA0CnC,IAAA;EAzC0B;;;;EA+C1B,MAAA;IAAA,CAAY,GAAA;EAAA;AAAA;;;;;KAOF,yBAAA;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AAA,GAAU,qBAAA;ELfV;;;EKmBA,QAAA,GAAW,0BAAA;ELlBN;AAQP;;;;;AAEA;;;;EKmBE,cAAA,GAAiB,MAAA,SAAe,WAAA;AAAA;;;;;ALjDlC;;KMUY,2BAAA,GAA8B,IAAA,CAAK,6BAAA;ENDrC;;AACV;;;EMME,UAAA;AAAA;ANJF;;;;;AAEA;;;;;AAEA;;;;;;;;;;;AAYA;;;;;AAEA;;;;;;AAlBA,iBMuCsB,sBAAA,CAAA;EACpB,QAAA;EACA,UAAA;EAAA,GACG;AAAA,GACF,iBAAA,CAAkB,2BAAA,IAA4B,OAAA,CAAA,oBAAA,CAAA,GAAA,CAAA,OAAA;;;cCvCpC,mBAAA,GACX,KAAA,EAAO,0BAAA,EACP,gBAAA,GAAmB,iCAAA,KAAiC,oBAAA"}
|
package/dist/server/index.mjs
CHANGED
|
@@ -1,6 +1,2 @@
|
|
|
1
|
-
import e,
|
|
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.1`},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};
|
|
1
|
+
import{i as e,n as t}from"./errors-B1AJJTZ-.mjs";import{ConfigDirectorProvider as n}from"@configdirector/nextjs-sdk/client";import{jsx as r}from"react/jsx-runtime";var i=class{decorateMessage(e){return`[ConfigDirector:nextjs-sdk] ${e}`}};const a=(t,n)=>new e(t??`warn`,n??new i),o=(t,n)=>new e(t,n??new i);async function s(e){if(process.env.NEXT_RUNTIME===`nodejs`){if(!e.serverSdkKey){let e=`The ConfigDirector serverSdkKey must be provided to register(). You can pass it via process.env.CONFIGDIRECTOR_SERVER_KEY.`;throw a().error(e),new t(e)}if(!globalThis.__configDirectorServerClient){let{DefaultConfigDirectorClient:t}=await import(`./DefaultConfigDirectorClient-Dw-ZzO94.mjs`),{serverSdkKey:n,...r}=e;globalThis.__configDirectorAppMeta={appName:e.metadata?.appName,appVersion:e.metadata?.appVersion};let i=new t(n,{sdkName:`nextjs-sdk`,sdkVersion:`0.2.0`},r);globalThis.__configDirectorServerClient=i,await i.initialize()}}}function c(){return globalThis.__configDirectorAppMeta??{}}function l(){if(!globalThis.__configDirectorServerClient)throw new t(`[ConfigDirector] Server client not initialized. Make sure to call register() in your instrumentation.ts file before using the SDK.`);return globalThis.__configDirectorServerClient}const u=a();function d(e){try{return l().getAllConfigs(e)}catch(e){return u.error(`Error retrieving SSR config set:`,e),{}}}async function f({children:e,configKeys:t,...i}){let a=d({context:i.context,configKeys:t}),o=c();return r(n,{...i,appName:i.appName??o.appName,appVersion:i.appVersion??o.appVersion,initialConfigs:a,children:e})}export{f as ConfigDirectorProvider,o as createConsoleLogger,d as generateSsrConfigSet,c as getAppMeta,l as getServerSingleton,s as register};
|
|
6
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["EventEmitter","EventEmitter","LogMessageDecorator","createDefaultLogger","createDefaultLogger"],"sources":["../../../shared/src/errors.ts","../../../eventsource/src/errors.ts","../../../eventsource/src/EventSourceParser.ts","../../../eventsource/src/types.ts","../../../eventsource/src/EventSourceClient.ts","../../../eventsource/src/index.ts","../../../js-server-sdk/src/StreamingTransport.ts","../../../shared/src/transport/AbstractPollingTransport.ts","../../../shared/src/fetchWithTimeout.ts","../../../js-server-sdk/src/PollingTransport.ts","../../../js-server-sdk/src/OneTimeTransport.ts","../../../config-evaluator/src/text-comparison.ts","../../../config-evaluator/src/numeric-comparison.ts","../../../config-evaluator/src/date-comparison.ts","../../../config-evaluator/src/semver-comparison.ts","../../../config-evaluator/src/array-comparison.ts","../../../config-evaluator/src/ConditionEvaluator.ts","../../../config-evaluator/src/percent-hashing.ts","../../../config-evaluator/src/ConfigEvaluator.ts","../../../shared/src/value-parser.ts","../../../shared/src/logger.ts","../../../js-server-sdk/src/logger.ts","../../../shared/src/url.ts","../../../shared/src/telemetry/utils.ts","../../../js-server-sdk/src/telemetry/ServerEventReporter.ts","../../../shared/src/telemetry/EventAggregator.ts","../../../shared/src/telemetry/EventQueue.ts","../../../shared/src/telemetry/TelemetryEventCollector.ts","../../../shared/src/LimitedMap.ts","../../../js-server-sdk/src/telemetry/ServerTelemetryEventCollector.ts","../../../js-server-sdk/src/DefaultConfigDirectorClient.ts","../../src/server/logger.ts","../../src/server/singleton.ts","../../src/server/SsrClient.ts"],"sourcesContent":["export class ConfigDirectorConnectionError extends Error {\n public override readonly name: string = \"ConfigDirectorConnectionError\";\n public readonly status?: number;\n\n constructor(message: string, status?: number) {\n super(message);\n this.status = status;\n\n Object.setPrototypeOf(this, ConfigDirectorConnectionError.prototype);\n }\n}\n\nexport class ConfigDirectorValidationError extends Error {\n public override readonly name: string = \"ConfigDirectorValidationError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ConfigDirectorValidationError.prototype);\n }\n}\n\nexport class ConfigDirectorInitializationError extends Error {\n public override readonly name: string = \"ConfigDirectorInitializationError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ConfigDirectorInitializationError.prototype);\n }\n}\n","export class StreamClosedError extends Error {\n public override readonly name: string = \"StreamClosedError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, StreamClosedError.prototype);\n }\n}\n\nexport class MissingResponseBodyError extends Error {\n public override readonly name: string = \"MissingResponseBodyError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, MissingResponseBodyError.prototype);\n }\n}\n\nexport class InvalidOptionError extends Error {\n public override readonly name: string = \"InvalidOptionError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, InvalidOptionError.prototype);\n }\n}\n\nexport class ValueOutOfRangeError extends Error {\n public override readonly name: string = \"ValueOutOfRangeError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ValueOutOfRangeError.prototype);\n }\n}\n","import {\n type EventSourceParserOptions,\n type EventSourceMessageHandler,\n type EventSourceCommentHandler,\n type EventParserRetryCallback,\n} from \"./types\";\n\ntype ParsedField = {\n field: string;\n value: string;\n};\n\nexport class EventSourceParser {\n private isFirstChunk = true;\n private bufferedInput = \"\";\n private currentEvent: { type?: string; data: string } = { data: \"\" };\n private lastEventId: string | undefined;\n private onEvent: EventSourceMessageHandler;\n private onRetry: EventParserRetryCallback | undefined;\n private onComment: EventSourceCommentHandler | undefined;\n\n constructor(options: EventSourceParserOptions) {\n this.currentEvent = { data: \"\" };\n this.onEvent = options.onEvent ?? (() => {});\n this.onRetry = options.onRetry;\n this.onComment = options.onComment;\n }\n\n public parse(chunk: string): void {\n let input = chunk;\n\n if (this.isFirstChunk) {\n this.isFirstChunk = false;\n if (input.startsWith(\"\\uFEFF\")) {\n input = input.slice(1);\n } else if (input.startsWith(\"\\xEF\\xBB\\xBF\")) {\n input = input.slice(3);\n }\n }\n\n const lines = this.scanLines(this.bufferedInput + input);\n for (const line of lines) {\n this.dispatchLine(line);\n }\n }\n\n // Per the SSE spec, any data still buffered when the stream ends is discarded —\n // an event requires a terminating empty line to be dispatched.\n public finish(): void {\n this.bufferedInput = \"\";\n }\n\n /**\n * Scans `text` character by character to extract complete lines, recognizing\n * CR, LF, and CRLF as line terminators per the SSE spec. Any unterminated\n * trailing text is buffered and prepended to the next chunk.\n */\n private scanLines(text: string): string[] {\n const lines: string[] = [];\n let lineStart = 0;\n let i = 0;\n\n while (i < text.length) {\n const ch = text[i];\n if (ch === \"\\r\" || ch === \"\\n\") {\n lines.push(text.slice(lineStart, i));\n // Consume CRLF as a single terminator rather than two separate lines.\n if (ch === \"\\r\" && text[i + 1] === \"\\n\") {\n i++;\n }\n i++;\n lineStart = i;\n } else {\n i++;\n }\n }\n\n this.bufferedInput = text.slice(lineStart);\n return lines;\n }\n\n private dispatchLine(line: string): void {\n if (line.startsWith(\":\")) {\n this.onComment?.(this.extractValue(line, 1));\n return;\n }\n\n if (line === \"\") {\n this.emitEvent();\n return;\n }\n\n this.applyField(this.parseField(line));\n }\n\n private emitEvent(): void {\n const data = this.currentEvent.data.endsWith(\"\\n\")\n ? this.currentEvent.data.slice(0, -1)\n : this.currentEvent.data;\n\n if (data !== \"\") {\n this.onEvent({ ...this.currentEvent, id: this.lastEventId, data });\n }\n\n this.currentEvent = { data: \"\" };\n }\n\n private applyField(parsed: ParsedField): void {\n switch (parsed.field) {\n case \"event\":\n this.currentEvent.type = parsed.value;\n break;\n case \"data\":\n this.currentEvent.data += parsed.value + \"\\n\";\n break;\n case \"id\":\n // Spec: ignore id values that contain a null character.\n if (!parsed.value.includes(\"\\0\")) {\n this.lastEventId = parsed.value;\n }\n break;\n case \"retry\":\n if (/^\\d+$/.test(parsed.value)) {\n this.onRetry?.(Number.parseInt(parsed.value, 10));\n }\n break;\n default:\n break;\n }\n }\n\n private parseField(line: string): ParsedField {\n const colon = line.indexOf(\":\");\n if (colon === -1) {\n return { field: line, value: \"\" };\n }\n return { field: line.slice(0, colon), value: this.extractValue(line, colon + 1) };\n }\n\n /** Returns the value portion of a line, stripping a single leading space per spec. */\n private extractValue(line: string, from: number): string {\n return line[from] === \" \" ? line.slice(from + 1) : line.slice(from);\n }\n}\n","export type ReconnectionState = {\n attempt: number;\n serverReconnectionTime: number;\n status?: number | undefined;\n error?: Error | undefined;\n};\n\nexport enum ReadyState {\n OPEN = \"open\",\n CLOSED = \"closed\",\n CONNECTING = \"connecting\",\n}\n\nexport type EventSourceClientOptions = {\n url: { toString(): string } | string;\n method?: string;\n headers?: Record<string, string>;\n body?: any;\n mode?: \"cors\" | \"no-cors\" | \"same-origin\";\n credentials?: \"include\" | \"omit\" | \"same-origin\";\n redirect?: \"error\" | \"follow\";\n referrer?: string;\n referrerPolicy?: ReferrerPolicy;\n lastEventId?: string;\n fetch?: (url: string, init: RequestInit) => Promise<Response>;\n onError?: (error: Error) => void;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onMessage?: EventSourceMessageHandler;\n onComment?: EventSourceCommentHandler;\n shouldReconnect?: (state: ReconnectionState) => boolean;\n calculateReconnectDelay?: (state: ReconnectionState) => number;\n};\n\nexport type EventSourceMessage = {\n id?: string | undefined;\n type?: string;\n data: string;\n};\n\nexport type EventSourceMessageHandler = (message: EventSourceMessage) => void;\nexport type EventSourceCommentHandler = (comment: string) => void;\n\nexport type EventParserRetryCallback = (retry: number) => void;\n\nexport type EventSourceParserOptions = {\n onEvent?: EventSourceMessageHandler;\n onRetry?: EventParserRetryCallback;\n onComment?: EventSourceCommentHandler;\n};\n","import {\n InvalidOptionError,\n MissingResponseBodyError,\n StreamClosedError,\n ValueOutOfRangeError,\n} from \"./errors\";\nimport { EventSourceParser } from \"./EventSourceParser\";\nimport {\n type EventSourceClientOptions,\n type EventSourceCommentHandler,\n type EventSourceMessageHandler,\n type ReconnectionState,\n ReadyState,\n} from \"./types\";\n\nexport class EventSourceClient {\n private readonly DEFAULT_SHOULD_RECONNECT = () => true;\n private readonly DEFAULT_CALCULATE_RECONNECT_DELAY = () => this.serverReconnectionTime;\n private readonly url: string;\n private readonly headers?: Record<string, string>;\n private readonly requestOptions;\n private lastEventId?: string;\n private reconnectAttempt: number = 0;\n private abortController: AbortController = new AbortController();\n private reconnectTimeout: ReturnType<typeof setTimeout> | undefined;\n private _readyState: ReadyState = ReadyState.CLOSED;\n private serverReconnectionTime: number = 2_000;\n private _fetch: (url: string, init: RequestInit) => Promise<Response>;\n private _onError: (error: Error) => void;\n private _onMessage: EventSourceMessageHandler;\n private _onComment: EventSourceCommentHandler;\n private _onConnect: () => void;\n private _onDisconnect: () => void;\n private _shouldReconnect: (state: ReconnectionState) => boolean;\n private _calculateReconnectDelay: (state: ReconnectionState) => number;\n\n constructor(options: EventSourceClientOptions) {\n this.url = options.url.toString();\n this.lastEventId = options.lastEventId;\n this.headers = {\n Accept: \"text/event-stream\",\n ...options.headers,\n };\n this.requestOptions = {\n body: options.body,\n method: options.method ?? \"GET\",\n mode: options.mode,\n credentials: options.credentials,\n redirect: options.redirect,\n referrer: options.referrer,\n referrerPolicy: options.referrerPolicy,\n };\n this._fetch = options.fetch ?? ((url, init) => fetch(url, init));\n this._onError = this.resolveCallback(options.onError, () => {}, \"onError\");\n this._onConnect = this.resolveCallback(options.onConnect, () => {}, \"onConnect\");\n this._onDisconnect = this.resolveCallback(options.onDisconnect, () => {}, \"onDisconnect\");\n this._onMessage = this.resolveCallback(options.onMessage, () => {}, \"onMessage\");\n this._onComment = this.resolveCallback(options.onComment, () => {}, \"onComment\");\n this._shouldReconnect = this.resolveCallback(\n options.shouldReconnect,\n this.DEFAULT_SHOULD_RECONNECT,\n \"shouldReconnect\",\n );\n this._calculateReconnectDelay = this.resolveCallback(\n options.calculateReconnectDelay,\n this.DEFAULT_CALCULATE_RECONNECT_DELAY,\n \"calculateReconnectDelay\",\n );\n }\n\n public set onError(value: (error: Error) => void) {\n this._onError = this.resolveCallback(value, () => {}, \"onError\");\n }\n\n public set onMessage(value: EventSourceMessageHandler) {\n this._onMessage = this.resolveCallback(value, () => {}, \"onMessage\");\n }\n\n public set onComment(value: EventSourceCommentHandler) {\n this._onComment = this.resolveCallback(value, () => {}, \"onComment\");\n }\n\n public set onConnect(value: () => void) {\n this._onConnect = this.resolveCallback(value, () => {}, \"onConnect\");\n }\n\n public set onDisconnect(value: () => void) {\n this._onDisconnect = this.resolveCallback(value, () => {}, \"onDisconnect\");\n }\n\n public set shouldReconnect(value: (state: ReconnectionState) => boolean) {\n this._shouldReconnect = this.resolveCallback(value, this.DEFAULT_SHOULD_RECONNECT, \"shouldReconnect\");\n }\n\n public set calculateReconnectDelay(value: (state: ReconnectionState) => number) {\n this._calculateReconnectDelay = this.resolveCallback(\n value,\n this.DEFAULT_CALCULATE_RECONNECT_DELAY,\n \"shouldReconnect\",\n );\n }\n\n public get readyState(): ReadyState {\n return this._readyState;\n }\n\n public connect() {\n if (this._readyState !== ReadyState.CLOSED) {\n return;\n }\n\n this.reconnectAttempt = 0;\n this.initiateConnection();\n }\n\n public close() {\n clearTimeout(this.reconnectTimeout);\n this._readyState = ReadyState.CLOSED;\n this.abortController.abort();\n }\n\n private initiateConnection() {\n this.abortController = new AbortController();\n this._readyState = ReadyState.CONNECTING;\n\n this._fetch(this.url, {\n ...this.requestOptions,\n headers: this.buildRequestHeaders(),\n signal: this.abortController.signal,\n cache: \"no-store\",\n })\n .then((response) => this.handleFetchResponse(response))\n .catch((error: Error) => {\n if (error.name === \"AbortError\" || this.abortController.signal.aborted) {\n this.close();\n return;\n }\n\n this._onError(error);\n this.scheduleReconnect({ error });\n });\n }\n\n private async handleFetchResponse(response: Response) {\n const { body, status } = response;\n\n if (status === 204) {\n this.disconnected();\n return;\n }\n\n if (status >= 400) {\n this.scheduleReconnect({ status });\n return;\n }\n\n if (!body) {\n throw new MissingResponseBodyError(\"The server response did not have a body\");\n }\n\n this._readyState = ReadyState.OPEN;\n this._onConnect();\n this.reconnectAttempt = 0;\n\n const parser = new EventSourceParser({\n onEvent: (event) => {\n if (typeof event.id === \"string\") {\n this.lastEventId = event.id;\n }\n this._onMessage(event);\n },\n onComment: (comment) => this._onComment(comment),\n onRetry: (retryDelay) => (this.serverReconnectionTime = retryDelay),\n });\n\n await this.readResponseStream(body, parser);\n\n this.scheduleReconnect({\n status,\n error: new StreamClosedError(\"The server response stream was closed\"),\n });\n }\n\n private async readResponseStream(body: ReadableStream<Uint8Array>, parser: EventSourceParser) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n\n let done = false;\n while (!done) {\n const result = await reader.read();\n if (result.value) {\n parser.parse(decoder.decode(result.value, { stream: true }));\n }\n done = result.done;\n }\n\n parser.finish();\n }\n\n private disconnected() {\n clearTimeout(this.reconnectTimeout);\n this._readyState = ReadyState.CLOSED;\n this._onDisconnect();\n }\n\n private buildRequestHeaders(): Record<string, string> {\n const lastEventIdHeader = this.lastEventId ? { \"Last-Event-ID\": this.lastEventId } : undefined;\n return {\n ...this.headers,\n ...lastEventIdHeader,\n };\n }\n\n private scheduleReconnect(state: { status?: number; error?: Error }) {\n if (this.abortController.signal.aborted) {\n return;\n }\n\n clearTimeout(this.reconnectTimeout);\n this.reconnectAttempt += 1;\n\n const reconnectionState: ReconnectionState = {\n attempt: this.reconnectAttempt,\n status: state.status,\n error: state.error,\n serverReconnectionTime: this.serverReconnectionTime,\n };\n\n if (!this._shouldReconnect(reconnectionState)) {\n this.disconnected();\n return;\n }\n\n this._readyState = ReadyState.CONNECTING;\n let delay = this._calculateReconnectDelay(reconnectionState);\n\n if (!Number.isFinite(delay) || delay < 1 || delay > 1_000 * 60 * 60) {\n this._onError(\n new ValueOutOfRangeError(\n `The calculated reconnect delay is out of range: ${delay}. Defaulting to ${this.serverReconnectionTime}`,\n ),\n );\n delay = this.serverReconnectionTime;\n }\n\n this.reconnectTimeout = setTimeout(() => this.initiateConnection(), delay);\n }\n\n private resolveCallback<T extends (...args: any[]) => any>(\n provided: unknown,\n fallback: T,\n optionName: string,\n ): T {\n if (provided == null) return fallback;\n if (typeof provided !== \"function\") {\n throw new InvalidOptionError(`${optionName} must be a function`);\n }\n return provided as T;\n }\n}\n","import { EventSourceClient } from \"./EventSourceClient\";\nimport { type EventSourceClientOptions } from \"./types\";\n\nexport const createEventSourceClient = (options: EventSourceClientOptions) => {\n return new EventSourceClient(options);\n};\n","import type {\n ConfigBundle,\n ConfigDirectorLogger,\n Transport,\n TransportEvents,\n TransportOptions,\n} from \"./types\";\nimport { ConfigDirectorConnectionError } from \"@shared/errors\";\nimport { EventEmitter } from \"node:events\";\nimport { createEventSourceClient } from \"@eventsource/index\";\nimport type { EventSourceClient } from \"@eventsource/EventSourceClient\";\n\nconst MAX_EXPONENTIAL_DELAY = 9; // 2^9 = 512 seconds, to cap it to under 10min\n\nexport class StreamingTransport implements Transport {\n private logger: ConfigDirectorLogger;\n private eventSource: EventSourceClient | undefined;\n private eventEmitter = new EventEmitter();\n private url: URL;\n\n constructor(private readonly options: TransportOptions) {\n this.options = options;\n this.logger = options.logger;\n this.url = new URL(\"server/sse/v1\", options.baseUrl);\n }\n\n public async connect(timeout: number): Promise<this> {\n if (this.eventSource) {\n this.close();\n }\n\n const eventSourcePromise = new Promise<this>((resolve, reject) => {\n this.eventSource = createEventSourceClient({\n url: this.url,\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n metaContext: this.options.metaContext,\n serverSdkKey: this.options.serverSdkKey,\n }),\n\n onMessage: ({ data }) => {\n this.dispatchMessage(data);\n },\n onConnect: () => {\n this.logger.debug(\"[EventSourceTransport] Connected\");\n resolve(this);\n },\n shouldReconnect: (state) => {\n const reconnect = !this.isStatusFatal(state.status);\n if (!reconnect) {\n reject(this.prepareFatalError(state.status, state.error));\n }\n return reconnect;\n },\n calculateReconnectDelay: (state) => {\n const seconds = Math.pow(2, Math.min(state.attempt, MAX_EXPONENTIAL_DELAY));\n const delay = seconds * 1_000;\n this.logger.warn(`[EventSourceTransport] Scheduling reconnect in ${delay}ms.`);\n return delay;\n },\n onDisconnect: () => {\n this.logger.debug(\"[EventSourceTransport] Disconnected\");\n },\n });\n this.eventSource.connect();\n });\n return Promise.race([\n eventSourcePromise,\n new Promise<this>((resolve) => {\n setTimeout(() => resolve(this), timeout);\n }),\n ]);\n }\n\n private dispatchMessage(data: string) {\n try {\n const json = JSON.parse(data);\n this.eventEmitter.emit(\"configBundleReceived\", json as ConfigBundle);\n } catch (error) {\n this.logger.error(\"[EventSourceTransport] Error parsing and dispatching config data update: \", error);\n }\n }\n\n private prepareFatalError(\n responseStatus: number | undefined,\n error: Error | undefined,\n ): ConfigDirectorConnectionError {\n const status = responseStatus ?? 0;\n const headline = `Connection failed with status: ${responseStatus ?? \"unknown\"}.`;\n const errorLine = error ? ` Error: ${error}.` : \"\";\n const message = `${headline}${errorLine} This is an unrecoverable error, will not attempt to reconnect.`;\n return new ConfigDirectorConnectionError(message, status);\n }\n\n private isStatusFatal(status: number | undefined): boolean {\n return !!status && status >= 400 && status < 500;\n }\n\n public get isConnected(): boolean {\n return this.eventSource?.readyState == \"open\";\n }\n\n public on<TName extends keyof TransportEvents>(\n name: TName,\n handler: (payload: TransportEvents[TName]) => void,\n ): void {\n this.eventEmitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(\n name: TName,\n handler?: ((payload: TransportEvents[TName]) => void) | undefined,\n ): void {\n if (handler) {\n this.eventEmitter.off(name, handler);\n } else {\n this.eventEmitter.removeAllListeners(name);\n }\n }\n\n public clear(): void {\n this.eventEmitter.removeAllListeners();\n }\n\n public close() {\n this.eventSource?.close();\n }\n\n public dispose(): void {\n this.close();\n this.clear();\n }\n}\n","import { ConfigDirectorConnectionError } from \"../errors\";\n\nexport abstract class AbstractPollingTransport {\n protected fatalError = false;\n protected pollingInterval: ReturnType<typeof setInterval> | undefined;\n protected pollingIntervalSeconds: number = 60;\n\n protected clearPollingInterval() {\n clearInterval(this.pollingInterval);\n }\n\n protected schedulePollingInterval(callback: () => void) {\n clearInterval(this.pollingInterval);\n if (this.pollingIntervalSeconds <= 0) {\n return;\n }\n this.pollingInterval = setInterval(callback, this.pollingIntervalSeconds * 1_000);\n }\n\n protected async handleNonOkResponse(response: Response) {\n if (!response.ok) {\n if (this.isStatusFatal(response.status)) {\n this.fatalError = true;\n throw this.prepareFatalResponseStatusError(response.status, await response.text());\n } else {\n throw new ConfigDirectorConnectionError(\n `Connection failed with status: ${response.status}`,\n response.status,\n );\n }\n }\n }\n\n protected handleFetchError(fetchError: unknown) {\n if (this.isFetchErrorFatal(fetchError)) {\n this.fatalError = true;\n this.close();\n throw new ConfigDirectorConnectionError(\n `Connection failed with fatal error: ${fetchError}. This is an unrecoverable error, retry attempts will be ignored.`,\n );\n } else if (fetchError instanceof SyntaxError) {\n throw new ConfigDirectorConnectionError(`Failed to parse the response from the server: ${fetchError}`);\n } else {\n throw new ConfigDirectorConnectionError(`Connection failed with error: ${fetchError}.`);\n }\n }\n\n protected prepareFatalResponseStatusError(\n responseStatus: number,\n errorBody: string | undefined,\n ): ConfigDirectorConnectionError {\n const status = responseStatus ?? 0;\n const headline = `Connection failed with status: ${responseStatus ?? \"unknown\"}`;\n const serverBody = (errorBody?.trim()?.length ?? 0) > 0 ? ` (${errorBody})` : \"\";\n const message = `${headline}${serverBody}. This is an unrecoverable error, retry attempts will be ignored.`;\n return new ConfigDirectorConnectionError(message, status);\n }\n\n protected isStatusFatal(status: number | undefined): boolean {\n return !!status && status >= 400 && status < 500;\n }\n\n protected isFetchErrorFatal(fetchError: unknown): boolean {\n if ((fetchError as any)?.name === \"NotAllowedError\") {\n return true;\n } else if (fetchError instanceof TypeError) {\n return true;\n }\n return false;\n }\n\n public get isConnected(): boolean {\n return this.pollingInterval !== undefined;\n }\n\n public close() {\n clearInterval(this.pollingInterval);\n this.pollingInterval = undefined;\n }\n\n public abstract clear(): void;\n\n public dispose(): void {\n this.close();\n this.clear();\n }\n}\n","import { type ConfigDirectorLogger } from \"./types\";\nimport type { UrlLike } from \"./url\";\n\nexport const fetchWithTimeout = async (\n timeout: number,\n resource: string | UrlLike | Request,\n options: RequestInit | undefined,\n logger: ConfigDirectorLogger,\n) => {\n const abortController = new AbortController();\n const abortTimeoutId = setTimeout(() => {\n logger.debug(\"[fetchWithTimeout] Reached timeout, aborting request\");\n abortController.abort();\n }, timeout);\n\n try {\n const response = await fetch(typeof resource === \"string\" || resource instanceof Request ? resource : resource.toString(), {\n ...options,\n signal: abortController.signal,\n });\n clearTimeout(abortTimeoutId);\n return response;\n } catch (error) {\n logger.warn(\"[fetchWithTimeout] Fetch error: \", error);\n clearTimeout(abortTimeoutId);\n throw error;\n }\n};\n","import type {\n ConfigDirectorLogger,\n Transport,\n TransportEvents,\n TransportOptions,\n} from \"./types\";\nimport { AbstractPollingTransport } from \"@shared/transport/AbstractPollingTransport\";\nimport { EventEmitter } from \"node:events\";\nimport { fetchWithTimeout } from \"@shared/fetchWithTimeout\";\n\nexport class PollingTransport extends AbstractPollingTransport implements Transport {\n private logger: ConfigDirectorLogger;\n private eventEmitter = new EventEmitter();\n private url: URL;\n private lastUpdateTimestamp: string | undefined;\n\n constructor(private readonly options: TransportOptions) {\n super();\n this.options = options;\n this.logger = options.logger;\n this.url = new URL(\"server/polling/v1\", options.baseUrl);\n this.pollingIntervalSeconds = options.pollingInterval ?? 60;\n }\n\n public async connect(timeout: number): Promise<this> {\n this.clearPollingInterval();\n\n await this.fetchConfigs(timeout);\n\n this.schedulePollingInterval(() => {\n void this.fetchConfigs(timeout).catch((error) => {\n this.logger.error(\"[PollingTransport] Error during polling:\", error);\n });\n });\n\n return this;\n }\n\n private async fetchConfigs(timeout: number) {\n if (this.fatalError) {\n this.logger.warn(\n \"[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.\",\n );\n return;\n }\n\n try {\n const response = await fetchWithTimeout(\n timeout,\n this.url,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n metaContext: this.options.metaContext,\n serverSdkKey: this.options.serverSdkKey,\n lastUpdateTimestamp: this.lastUpdateTimestamp,\n }),\n },\n this.logger,\n );\n\n await this.handleNonOkResponse(response);\n\n if (response.status === 200) {\n const json = JSON.parse(await response.text());\n this.lastUpdateTimestamp = json.timestamp;\n this.eventEmitter.emit(\"configBundleReceived\", json);\n }\n } catch (fetchError) {\n this.handleFetchError(fetchError);\n }\n }\n\n public on<TName extends keyof TransportEvents>(\n name: TName,\n handler: (payload: TransportEvents[TName]) => void,\n ): void {\n this.eventEmitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(\n name: TName,\n handler?: ((payload: TransportEvents[TName]) => void) | undefined,\n ): void {\n if (handler) {\n this.eventEmitter.off(name, handler);\n } else {\n this.eventEmitter.removeAllListeners(name);\n }\n }\n\n public clear(): void {\n this.eventEmitter.removeAllListeners();\n }\n}\n","import type { TransportOptions } from \"./types\";\nimport { PollingTransport } from \"./PollingTransport\";\n\nexport class OneTimeTransport extends PollingTransport {\n constructor(options: TransportOptions) {\n super(options);\n this.pollingIntervalSeconds = 0;\n }\n}\n","import type { Operator } from \"./types\";\n\nexport const compareText = (value: string | null | undefined, operator: Operator, targetValues: string[]) => {\n switch (operator.toLowerCase()) {\n case \"=\":\n case \"equals\":\n return value == targetValues[0];\n case \"!=\":\n case \"does not equal\":\n return value != targetValues[0];\n case \"is one of\":\n return targetValues.includes(value as any);\n case \"is not one of\":\n return !targetValues.includes(value as any);\n case \"starts with any of\":\n return targetValues.findIndex((v) => value?.startsWith(v)) >= 0;\n case \"does not start with any of\":\n return targetValues.findIndex((v) => value?.startsWith(v)) < 0;\n case \"ends with any of\":\n return targetValues.findIndex((v) => value?.endsWith(v)) >= 0;\n case \"does not end with any of\":\n return targetValues.findIndex((v) => value?.endsWith(v)) < 0;\n case \"matches regex\":\n return matchesRegex(targetValues[0], value);\n case \"does not match regex\":\n return !matchesRegex(targetValues[0], value);\n default:\n return false;\n }\n};\n\nconst matchesRegex = (regexString: string, value: string | null | undefined) => {\n try {\n return new RegExp(regexString).test(value as any);\n } catch {\n return false;\n }\n};\n","import type { Operator } from \"./types\";\n\nexport const compareNumeric = (\n givenValue: number | bigint | string | boolean | null | undefined,\n operator: Operator,\n targetValues: string[],\n) => {\n if (typeof givenValue == \"boolean\") {\n return false;\n }\n const lowercaseOperator = operator.toLowerCase();\n if (givenValue == null) {\n return lowercaseOperator == \"!=\" || lowercaseOperator == \"does not equal\";\n }\n\n const { value, target } = parseValueAndTarget(givenValue, targetValues[0]);\n\n switch (lowercaseOperator) {\n case \"=\":\n case \"equals\":\n return value == target;\n case \"!=\":\n case \"does not equal\":\n return value != target;\n case \"<\":\n return value < target;\n case \"<=\":\n return value <= target;\n case \">\":\n return value > target;\n case \">=\":\n return value >= target;\n default:\n return false;\n }\n};\n\nconst parseValueAndTarget = (value: number | bigint | string, targetValue: string) => {\n if (typeof value == \"number\") {\n return { value, target: parseAsNumber(targetValue) };\n } else if (typeof value == \"bigint\") {\n return { value, target: BigInt(targetValue) };\n } else {\n return { value: parseAsNumber(value), target: parseAsNumber(targetValue) };\n }\n};\n\nconst parseAsNumber = (value: number | bigint | string): number => {\n const n = Number.parseFloat(value.toString());\n if (isNaN(n) || !isFinite(n)) {\n throw new TypeError(`Invalid numeric value: ${value}`);\n }\n return n;\n};\n","import type { Operator } from \"./types\";\n\nexport const compareDate = (value: string | null | undefined, operator: Operator, targetValues: string[]) => {\n if (value == null) {\n return false;\n }\n\n try {\n const dateValue = new Date(value);\n const dateTarget = new Date(targetValues[0]);\n switch (operator) {\n case \"is after\":\n return dateValue > dateTarget;\n case \"is before\":\n return dateValue < dateTarget;\n default:\n return false;\n }\n } catch {\n return false;\n }\n};\n","import type { Operator } from \"./types\";\nimport * as semver from \"semver\";\n\nexport const compareSemver = (value: string | null | undefined, operator: Operator, targetValues: string[]) => {\n const lowercaseOperator = operator.toLowerCase();\n if (value == null || value.trim().length == 0) {\n return lowercaseOperator == \"is not one of\";\n }\n\n const semverValue = semver.coerce(value) ?? value;\n const semverTargets = targetValues.map((v) => semver.coerce(v) ?? v);\n try {\n switch (lowercaseOperator) {\n case \"=\":\n return safeEquals(semverValue, semverTargets[0]);\n case \"<\":\n return semver.lt(semverValue, semverTargets[0]);\n case \"<=\":\n return semver.lte(semverValue, semverTargets[0]);\n case \">\":\n return semver.gt(semverValue, semverTargets[0]);\n case \">=\":\n return semver.gte(semverValue, semverTargets[0]);\n case \"is one of\":\n return semverTargets.findIndex((v) => safeEquals(semverValue, v)) >= 0;\n case \"is not one of\":\n return semverTargets.findIndex((v) => safeEquals(semverValue, v)) < 0;\n default:\n return false;\n }\n } catch {\n return false;\n }\n};\n\nconst safeEquals = (v1: string | semver.SemVer, v2: string | semver.SemVer): boolean => {\n try {\n return semver.eq(v1, v2);\n } catch {\n return false;\n }\n};\n","import type { Operator } from \"./types\";\n\nexport const compareArray = (givenValue: any, operator: Operator, targetValues: string[]) => {\n const lowercaseOperator = operator.toLowerCase();\n if (!Array.isArray(givenValue)) {\n return lowercaseOperator == \"does not contain any of\";\n }\n\n switch (lowercaseOperator) {\n case \"contains any of\":\n return givenValue.some((v) => targetValues.includes(v));\n case \"does not contain any of\":\n return !givenValue.some((v) => targetValues.includes(v));\n default:\n return false;\n }\n};\n","import type { Condition, EvaluationContext } from \"./types\";\nimport { findByPointer } from \"@jsonjoy.com/json-pointer\";\nimport { compareText } from \"./text-comparison\";\nimport { compareNumeric } from \"./numeric-comparison\";\nimport { compareDate } from \"./date-comparison\";\nimport { compareSemver } from \"./semver-comparison\";\nimport { compareArray } from \"./array-comparison\";\n\nexport class ConditionEvaluator {\n public evaluate(condition: Condition, context?: EvaluationContext): boolean {\n if (!this.isConditionValidForComparison(condition)) {\n return false;\n }\n\n switch (condition.attribute) {\n case \"identifier\":\n return this.compare(context?.context?.id, condition);\n case \"name\":\n return this.compare(context?.context?.name, condition);\n case \"appName\":\n return this.compare(context?.metadata?.appName, condition);\n case \"appVersion\":\n return this.compare(context?.metadata?.appVersion, condition);\n case \"traits\":\n if (condition.trait) {\n const value = this.findTraitValue(context?.context?.traits, condition.trait);\n return this.compare(value, condition);\n }\n }\n\n return false;\n }\n\n private compare(\n value: any,\n condition: Condition,\n ): boolean {\n switch (condition.targetType) {\n case \"text\":\n return compareText(value?.toString(), condition.operator, condition.targetValues);\n case \"number\":\n return compareNumeric(value, condition.operator, condition.targetValues);\n case \"datetime\":\n return compareDate(value?.toString(), condition.operator, condition.targetValues);\n case \"semver\":\n return compareSemver(value?.toString(), condition.operator, condition.targetValues);\n case \"array\":\n return compareArray(value, condition.operator, condition.targetValues);\n }\n return false;\n }\n\n private findTraitValue(traits: Record<string, unknown> | undefined, path: string) {\n try {\n const reference = findByPointer(path, traits);\n return reference.val;\n } catch {\n return undefined;\n }\n }\n\n private isConditionValidForComparison(condition: Condition): boolean {\n return Array.isArray(condition.targetValues) && condition.targetValues.length > 0;\n }\n}\n","import { rapidhash } from \"rapidhash-js\";\n\nconst SEED = 0x397832987n;\n\nexport const assignPercentage = (data: {configId: string, contextIdentifier: string}): number => {\n const value = `${data.contextIdentifier}-${data.configId}`;\n\n return Number(rapidhash(value, { seed: SEED }) % 1_000n) / 10.0;\n};\n","import { ConditionEvaluator } from \"./ConditionEvaluator\";\nimport { assignPercentage } from \"./percent-hashing\";\nimport type {\n ConditionalRule,\n Config,\n EvaluationContext,\n ConfigState,\n Percentage,\n PercentageRule,\n Rule,\n Condition,\n ConfigDirectorLogger,\n} from \"./types\";\n\ntype RuleSuccess = {\n success: true;\n value: string;\n};\n\ntype RuleFailure = {\n success: false;\n};\n\ntype RuleEvaluationResult = RuleSuccess | RuleFailure;\n\nexport class ConfigEvaluator {\n private readonly conditionEvaluator = new ConditionEvaluator();\n\n constructor(private readonly logger: ConfigDirectorLogger) {\n if (!logger || !logger.warn || !logger.error || !logger.info) {\n throw new TypeError(\"The provided logger is not a valid 'ConfigDirectorLogger'\");\n }\n\n this.logger = logger;\n }\n\n public evaluate(config: Config, context?: EvaluationContext): ConfigState {\n return {\n id: config.id,\n key: config.key,\n type: config.type,\n value: this.getConfigValue(config, context),\n };\n }\n\n private getConfigValue(config: Config, context?: EvaluationContext) {\n const rules = [...(config.target?.rules ?? [])].sort(\n (a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER),\n );\n for (const rule of rules) {\n const result = this.evaluateRule(rule, config, context);\n if (result.success) {\n return result.value;\n }\n }\n return config.target?.defaultValue;\n }\n\n private evaluateRule(rule: Rule, config: Config, context?: EvaluationContext): RuleEvaluationResult {\n try {\n if (rule.type == \"percentage\") {\n return this.evaluatePercentageRule(rule, config, context);\n } else if (rule.type == \"conditional\") {\n return this.evaluateConditionalRule(rule, config, context);\n }\n } catch (error) {\n this.logger.warn(`There was an error while evaluating a targeting rule '${rule?.id}' for '${config?.key}'. The rule will be disregarded.`, {\n error,\n configKey: config?.key,\n ruleId: rule?.id,\n });\n }\n\n return { success: false };\n }\n\n private evaluatePercentageRule(\n rule: PercentageRule,\n config: Config,\n context?: EvaluationContext,\n ): RuleEvaluationResult {\n return this.evaluatePercentage(rule.percentages ?? [], config, context);\n }\n\n private evaluatePercentage(\n percentages: Percentage[],\n config: Config,\n context?: EvaluationContext,\n ): RuleEvaluationResult {\n const assignedPercentage = assignPercentage({\n configId: config.id,\n contextIdentifier: context?.context?.id ?? crypto.randomUUID(),\n });\n let index = 0;\n let sum = 0.0;\n let bucket: Percentage | undefined = undefined;\n while (!bucket && index < percentages.length) {\n if (assignedPercentage <= percentages[index].percentage + sum) {\n bucket = percentages[index];\n }\n\n sum += percentages[index].percentage;\n index += 1;\n }\n\n if (bucket?.value != null) {\n return { success: true, value: bucket.value.toString() };\n }\n return { success: false };\n }\n\n private evaluateConditionalRule(\n rule: ConditionalRule,\n config: Config,\n context?: EvaluationContext,\n ): RuleEvaluationResult {\n const conditions = rule.conditions ?? [];\n let index = 0;\n let condition: Condition | undefined = undefined;\n while (!condition && index < conditions.length) {\n if (this.conditionEvaluator.evaluate(conditions[index], context)) {\n condition = conditions[index];\n }\n index += 1;\n }\n\n if (condition && rule.target == \"value\" && rule.value != null) {\n return { success: true, value: rule.value.toString() };\n } else if (condition && rule.target == \"percentage\") {\n return this.evaluatePercentage(rule.percentages ?? [], config, context);\n }\n return { success: false };\n }\n}\n","import type { ConfigState, ConfigValueType, EvaluationReason } from \"./types\";\n\ntype NativeType =\n | \"string\"\n | \"number\"\n | \"bigint\"\n | \"boolean\"\n | \"symbol\"\n | \"undefined\"\n | \"object\"\n | \"function\";\n\ntype ParseResult<T extends ConfigValueType> = {\n parsedValue: T;\n requestedType: NativeType | string;\n usedDefault: boolean;\n reason: EvaluationReason;\n};\n\nexport const getRequestedType = <T extends ConfigValueType>(defaultValue: T): string => {\n const baseType = typeof defaultValue;\n if (baseType === \"object\") {\n try {\n return (defaultValue as object).constructor?.name ?? baseType;\n } catch {\n return baseType;\n }\n } else if (baseType === \"function\") {\n try {\n const functionName = (defaultValue as any).name;\n return functionName ? `function: ${functionName}` : baseType;\n } catch {\n return baseType;\n }\n }\n return baseType;\n};\n\nconst isNumericNativeType = (requestedType: NativeType): boolean => {\n return requestedType === \"number\" || requestedType === \"bigint\";\n};\n\nexport const parseConfigValue = <T extends ConfigValueType>(\n configState: ConfigState,\n defaultValue: T,\n): ParseResult<T> => {\n const value = configState.value;\n const requestedType = getRequestedType(defaultValue);\n\n if (!value) {\n return {\n parsedValue: defaultValue as T,\n requestedType,\n usedDefault: true,\n reason: \"value-missing\",\n };\n }\n\n if (typeof defaultValue === \"string\") {\n return {\n parsedValue: value as T,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n }\n\n if (typeof defaultValue === \"boolean\" && configState.type === \"boolean\") {\n const boolValue = parseConfigBoolean(value);\n const hasBoolean = typeof boolValue === \"boolean\";\n return {\n parsedValue: (hasBoolean ? boolValue : defaultValue) as T,\n requestedType,\n usedDefault: !hasBoolean,\n reason: hasBoolean ? \"found-match\" : \"invalid-boolean\",\n };\n }\n\n if (isNumericNativeType(typeof defaultValue) && configState.type === \"integer\") {\n const numValue = parseConfigInteger(value);\n const hasNumber = typeof numValue === \"number\";\n return {\n parsedValue: (hasNumber ? numValue : defaultValue) as T,\n requestedType,\n usedDefault: !hasNumber,\n reason: hasNumber ? \"found-match\" : \"invalid-number\",\n };\n }\n if (isNumericNativeType(typeof defaultValue) && (configState.type === \"float\" || configState.type === \"enum\" )) {\n const numValue = parseConfigFloat(value);\n const hasNumber = typeof numValue === \"number\";\n return {\n parsedValue: (hasNumber ? numValue : defaultValue) as T,\n requestedType,\n usedDefault: !hasNumber,\n reason: hasNumber ? \"found-match\" : \"invalid-number\",\n };\n }\n\n return {\n parsedValue: value as T,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n};\n\nconst parseConfigBoolean = (value: string): boolean | undefined => {\n if (!value) {\n return;\n }\n const lowerValue = value.toLowerCase();\n if (lowerValue != \"true\" && lowerValue != \"false\") {\n return;\n }\n return lowerValue === \"true\";\n};\n\nconst parseConfigInteger = (value: string): number | undefined => {\n if (!value) {\n return;\n }\n const num = Number.parseInt(value);\n if (isNaN(num) || !isFinite(num)) {\n return;\n }\n return num;\n};\n\nconst parseConfigFloat = (value: string): number | undefined => {\n if (!value) {\n return;\n }\n const num = Number.parseFloat(value);\n if (isNaN(num) || !isFinite(num)) {\n return;\n }\n return num;\n};\n","import type { ConfigDirectorLogger, ConfigDirectorLogMessageDecorator, ConfigDirectorLoggingLevel } from \"./types\";\n\nconst LEVELS: Record<ConfigDirectorLoggingLevel, number> = {\n off: -1,\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nconst buildDateFormatter = () => {\n const baseOptions: Intl.DateTimeFormatOptions = {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n timeZoneName: \"short\",\n };\n\n try {\n return new Intl.DateTimeFormat(\n undefined,\n { ...baseOptions, fractionalSecondDigits: 3 } as Intl.DateTimeFormatOptions,\n );\n } catch {\n return new Intl.DateTimeFormat(undefined, baseOptions);\n }\n};\n\nexport class DefaultConsoleLogger implements ConfigDirectorLogger {\n private readonly dateFormatter;\n\n constructor(private readonly level: ConfigDirectorLoggingLevel, private readonly decorator: ConfigDirectorLogMessageDecorator) {\n this.level = level;\n this.decorator = decorator;\n this.dateFormatter = buildDateFormatter();\n }\n\n debug(message: string, ...args: any): void {\n this.log(console.debug, \"debug\", message, ...args);\n }\n\n info(message: string, ...args: any): void {\n this.log(console.info, \"info\", message, ...args);\n }\n\n warn(message: string, ...args: any): void {\n this.log(console.warn, \"warn\", message, ...args);\n }\n\n error(message: string, ...args: any): void {\n this.log(console.error, \"error\", message, ...args);\n }\n\n protected log(loggerFunction: (...args: any) => void, level: ConfigDirectorLoggingLevel, message: string, ...args: any) {\n if (LEVELS[this.level] >= LEVELS[level]) {\n loggerFunction(`[${this.dateFormatter.format(new Date())}] ${this.decorator?.decorateMessage(message)}`, ...args);\n }\n }\n}\n","import { DefaultConsoleLogger } from \"@shared/logger\";\nimport type { ConfigDirectorLoggingLevel, ConfigDirectorLogMessageDecorator } from \"@shared/types\";\n\nclass LogMessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:js-server-sdk] ${message}`;\n }\n}\n\nexport const createDefaultLogger = (\n level?: ConfigDirectorLoggingLevel,\n messageDecorator?: ConfigDirectorLogMessageDecorator,\n) => {\n return new DefaultConsoleLogger(level ?? \"warn\", messageDecorator ?? new LogMessageDecorator());\n};\n","import { ConfigDirectorValidationError } from \"./errors\";\n\nexport interface UrlLike {\n toString(): string;\n}\n\nexport type UrlFactory = (input: string, base?: UrlLike) => UrlLike;\n\nexport const defaultUrlFactory: UrlFactory = (input, base) => new URL(input, base?.toString());\n\nexport const parseUrl = (url: string | undefined): URL | undefined => {\n if (!url) {\n return;\n }\n\n try {\n return new URL(url);\n } catch (error) {\n throw new ConfigDirectorValidationError(`Invalid URL '${url}'. Parsing failed: ${error}`);\n }\n};\n","import type { ConfigType, ConfigValueType } from \"../types\";\nimport { type DroppedEvents } from \"./types\";\n\nconst CONFIG_VALUE_MAX_LENGTH = 500;\n\nexport const sanitizeValue = <TV extends ConfigValueType>(value: TV, type?: ConfigType): string => {\n if (type === \"json\") {\n try {\n const json = JSON.stringify(value);\n return djb2Hash(json);\n } catch {\n return value.toString().slice(0, CONFIG_VALUE_MAX_LENGTH);\n }\n }\n\n return value.toString().slice(0, CONFIG_VALUE_MAX_LENGTH);\n};\n\nexport const djb2Hash = (data: string): string => {\n const hash = djb2(new TextEncoder().encode(data));\n return hash.toString(16).padStart(8, \"0\");\n};\n\nconst djb2 = (bytes: Uint8Array): number => {\n let hash = 5381;\n for (let i = 0; i < bytes.length; i++) {\n hash = (hash << 5) + hash + (bytes[i] ?? 0);\n hash = hash >>> 0;\n }\n return hash;\n};\n\nexport const isEventListEmpty = <T extends Record<string | symbol, any[]>>(eventList: T): boolean => {\n const keys = Object.keys(eventList);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((eventList[key]?.length ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isDroppedEventsEmpty = (droppedEvents?: DroppedEvents): boolean => {\n if (!droppedEvents) {\n return true;\n }\n const keys = Object.keys(droppedEvents);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((droppedEvents[key] ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n","import { isDroppedEventsEmpty, isEventListEmpty } from \"@shared/telemetry/utils\";\nimport type { ConfigDirectorLogger } from \"../types\";\nimport type { EventReport, EventReporter, EventReporterPayload, ReporterResponse } from \"./types\";\nimport { fetchWithTimeout } from \"@shared/fetchWithTimeout\";\nimport {type UrlLike } from \"@shared/url\";\n\nexport type EventReporterOptions = {\n sdkKey: string;\n logger: ConfigDirectorLogger;\n baseUrl: UrlLike;\n};\n\nexport class ServerEventReporter implements EventReporter {\n private readonly sdkKey: string;\n private readonly logger: ConfigDirectorLogger;\n private readonly url: URL;\n private executeRequests = true;\n\n constructor(options: EventReporterOptions) {\n this.sdkKey = options.sdkKey;\n this.logger = options.logger;\n this.url = new URL(\"server/telemetry/v1\", options.baseUrl.toString());\n }\n\n public async report({\n discreteEvents,\n aggregatedEvents,\n droppedEvents,\n }: EventReporterPayload): Promise<ReporterResponse> {\n if (!this.executeRequests) {\n return { success: false, fatalError: true };\n }\n\n const eventReport: EventReport = {\n serverSdkKey: this.sdkKey,\n discreteEvents,\n aggregatedEvents,\n droppedEvents,\n };\n if (this.isReportEmpty(eventReport)) {\n return { success: true, fatalError: false };\n }\n\n const response = await this.sendReport(eventReport);\n if (response.fatalError) {\n this.executeRequests = false;\n }\n return response;\n }\n\n private isReportEmpty(eventReport: EventReport) {\n return (\n isEventListEmpty(eventReport.discreteEvents) &&\n isEventListEmpty(eventReport.aggregatedEvents) &&\n isDroppedEventsEmpty(eventReport.droppedEvents)\n );\n }\n\n private async sendReport(eventReport: EventReport): Promise<ReporterResponse> {\n try {\n const response = await fetchWithTimeout(\n 5_000,\n this.url,\n {\n method: \"POST\",\n body: JSON.stringify(eventReport),\n },\n this.logger,\n );\n\n const isFatalError = this.isStatusFatal(response.status);\n if (isFatalError) {\n this.logger.warn(\n `[EventReporter] Received a fatal status response (${response.status}) from the telemetry endpoint. No more telemetry data will be sent.`,\n );\n }\n return { success: response.ok, fatalError: isFatalError };\n } catch (error) {\n this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${error}`, { error });\n return { success: false, fatalError: false };\n }\n }\n\n private isStatusFatal(status: number | undefined): boolean {\n return !!status && status >= 400 && status < 500;\n }\n}\n","import type { AggregatedEvent, EventQueueSnapshot, ReportableEvent } from \"./types\";\n\nexport class EventAggregator {\n public aggregate<T extends ReportableEvent>(snapshot: EventQueueSnapshot<T>): AggregatedEvent<T>[] {\n if (snapshot.events.length == 0) {\n return [];\n }\n\n const map = new Map<string, { event: T; count: number }>();\n for (const event of snapshot.events) {\n const serializedEvent = JSON.stringify(event);\n const count = map.get(serializedEvent)?.count || 0;\n map.set(serializedEvent, { event, count: count + 1 });\n }\n return Array.from(map).map(([, v]) => {\n return {\n startTime: snapshot.startTime,\n endTime: snapshot.endTime,\n count: v.count,\n event: v.event,\n };\n });\n }\n}\n","import type { EventQueueSnapshot, ReportableEvent } from \"./types\";\n\nexport class EventQueue<T extends ReportableEvent> {\n private readonly limit: number;\n private startTime?: Date;\n private _events: T[] = [];\n private _droppedEventCount = 0;\n\n constructor(limit?: number) {\n this.limit = limit ?? 1_000;\n }\n\n public get events(): T[] {\n return this._events;\n }\n\n public get reachedLimit(): boolean {\n return this._events.length >= this.limit;\n }\n\n public get droppedEventCount(): number {\n return this._droppedEventCount;\n }\n\n public push(...newEvents: T[]) {\n if (!this.startTime) {\n this.startTime = new Date();\n }\n\n const newEventsCountToDrop = Math.max(0, newEvents.length - this.limit);\n const eventsToPush = newEvents.slice(newEventsCountToDrop, newEvents.length);\n this._droppedEventCount += newEventsCountToDrop;\n if (this._events.length + eventsToPush.length > this.limit) {\n const eventCountToDrop = this._events.length + eventsToPush.length - this.limit;\n this._events.splice(0, eventCountToDrop);\n this._droppedEventCount += eventCountToDrop;\n }\n return this._events.push(...eventsToPush);\n }\n\n public takeSnapshot(): EventQueueSnapshot<T> {\n const endTime = new Date();\n const startTime = this.startTime ?? endTime;\n const eventsSnapshot = this._events.splice(0);\n const droppedCount = this._droppedEventCount;\n this.startTime = undefined;\n this._droppedEventCount = 0;\n return {\n startTime,\n endTime,\n events: eventsSnapshot,\n droppedCount,\n };\n }\n\n public clear() {\n this._events = [];\n this.startTime = undefined;\n this._droppedEventCount = 0;\n }\n}\n","import type { ConfigDirectorContext, ConfigDirectorLogger, ConfigType, ConfigValueType } from \"../types\";\nimport { EventAggregator } from \"./EventAggregator\";\nimport { EventQueue } from \"./EventQueue\";\nimport { sanitizeValue } from \"./utils\";\nimport type { EventReporter, ReportableEvent, ReporterResponse } from \"./types\";\nimport type { UrlFactory, UrlLike } from \"../url\";\n\nexport type TelemetryEventCollectorOptions = {\n sdkKey: string;\n logger: ConfigDirectorLogger;\n baseUrl: UrlLike;\n urlFactory: UrlFactory;\n flushIntervalDelay?: number;\n initialFlushIntervalDelay?: number;\n evaluationQueueLimit?: number;\n};\n\nexport abstract class TelemetryEventCollector<T extends ReportableEvent> {\n protected readonly logger: ConfigDirectorLogger;\n protected abstract readonly reporter: EventReporter | undefined;\n protected readonly evaluationEventQueue: EventQueue<T>;\n protected readonly aggregator: EventAggregator = new EventAggregator();\n protected flushIntervalDelay: number;\n protected flushTimeout: ReturnType<typeof setTimeout>;\n protected collectEvents = true;\n protected abstract _context?: ConfigDirectorContext;\n\n constructor(options: TelemetryEventCollectorOptions) {\n this.logger = options.logger;\n this.evaluationEventQueue = new EventQueue(options.evaluationQueueLimit ?? 1_000);\n this.flushIntervalDelay = options.flushIntervalDelay ?? 30_000;\n const initialDelay = options.initialFlushIntervalDelay ?? 5_000;\n this.flushTimeout = setTimeout(() => this.flushAndScheduleNext(), initialDelay);\n }\n\n protected sanitizeValue<TV extends ConfigValueType>(value: TV, type?: ConfigType): string {\n return sanitizeValue(value, type);\n }\n\n protected async flushAndScheduleNext() {\n const response = await this.flush();\n if (response.fatalError) {\n this.collectEvents = false;\n this.close();\n this.logger.warn(\n \"[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.\",\n );\n } else {\n this.flushTimeout = setTimeout(() => this.flushAndScheduleNext(), this.flushIntervalDelay);\n }\n }\n\n protected async flush(): Promise<ReporterResponse> {\n if (!this.reporter) {\n return { success: false, fatalError: false };\n }\n const evaluationSnapshot = this.evaluationEventQueue.takeSnapshot();\n const response = await this.reporter?.report({\n context: this._context,\n discreteEvents: {},\n aggregatedEvents: {\n evaluatedConfig: this.aggregator.aggregate(evaluationSnapshot),\n },\n droppedEvents: {\n evaluatedConfig: evaluationSnapshot.droppedCount,\n },\n });\n return response;\n }\n\n protected cancelScheduledFlush() {\n clearTimeout(this.flushTimeout);\n }\n\n public async close() {\n this.collectEvents = false;\n clearTimeout(this.flushTimeout);\n await this.flush();\n this.evaluationEventQueue.clear();\n }\n\n public dispose() {\n this.close();\n }\n}\n","export class LimitedMap<K, V> extends Map<K, V> {\n private readonly limit: number;\n private _droppedCount: number = 0;\n\n constructor(limit: number, entries?: [K, V][]) {\n super(entries);\n this.limit = limit;\n this.enforceLimit();\n }\n\n public override set(key: K, value: V): this {\n super.set(key, value);\n this.enforceLimit();\n return this;\n }\n\n public get droppedCount(): number {\n return this._droppedCount;\n }\n\n public clearAndReset() {\n this.clear();\n this._droppedCount = 0;\n }\n\n private enforceLimit() {\n while (this.size > this.limit) {\n const oldestKey = this.keys().next().value;\n if (oldestKey !== undefined) {\n this.delete(oldestKey);\n this._droppedCount += 1;\n }\n }\n }\n}\n","import type { ConfigDirectorContext, ConfigValueType } from \"../types\";\nimport { ServerEventReporter } from \"./ServerEventReporter\";\nimport type { EvaluatedConfigEvent } from \"./telemetry-events\";\nimport type { EvaluatedConfig, EventReporter, ReporterResponse, ServerTelemetryEventCollectorOptions } from \"./types\";\nimport { TelemetryEventCollector } from \"@shared/telemetry/TelemetryEventCollector\";\nimport { LimitedMap } from \"@shared/LimitedMap\";\n\nconst DEFAULT_CONTEXTS_LIMIT = 1_000;\n\nexport class ServerTelemetryEventCollector extends TelemetryEventCollector<EvaluatedConfigEvent<string>> {\n protected readonly reporter: EventReporter;\n protected _context?: ConfigDirectorContext;\n private readonly contexts: LimitedMap<string, ConfigDirectorContext>;\n\n constructor(options: ServerTelemetryEventCollectorOptions) {\n super(options);\n this.reporter = new ServerEventReporter(options);\n this.contexts = new LimitedMap(options.contextLimit ?? DEFAULT_CONTEXTS_LIMIT);\n }\n\n public evaluatedConfig<T extends ConfigValueType>(payload: EvaluatedConfig<T>): void {\n if (!this.collectEvents) {\n return;\n }\n if (payload.context?.id) {\n this.contexts.set(payload.context.id, payload.context);\n }\n const event = {\n ...payload.evaluation,\n contextId: payload.context?.id,\n };\n\n this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(event));\n }\n\n private sanitizeEvaluatedConfigEvent<T extends ConfigValueType>(\n event: EvaluatedConfigEvent<T>,\n ): EvaluatedConfigEvent<string> {\n return {\n ...event,\n defaultValue: this.sanitizeValue(event.defaultValue, event.type),\n evaluatedValue: this.sanitizeValue(event.evaluatedValue, event.type),\n };\n }\n\n private snapshotContexts() {\n const contexts = Array.from(this.contexts.values());\n const droppedCount = this.contexts.droppedCount;\n this.contexts.clearAndReset();\n return { contexts, droppedCount };\n }\n\n protected override async flush(): Promise<ReporterResponse> {\n if (!this.reporter) {\n return { success: false, fatalError: false };\n }\n const evaluationSnapshot = this.evaluationEventQueue.takeSnapshot();\n const contextsSnapshot = this.snapshotContexts();\n const response = await this.reporter?.report({\n context: this._context,\n discreteEvents: {\n capturedContexts: contextsSnapshot.contexts,\n },\n aggregatedEvents: {\n evaluatedConfig: this.aggregator.aggregate(evaluationSnapshot),\n },\n droppedEvents: {\n evaluatedConfig: evaluationSnapshot.droppedCount,\n capturedContexts: contextsSnapshot.droppedCount,\n },\n });\n return response;\n }\n}\n","import { StreamingTransport } from \"./StreamingTransport\";\nimport { OneTimeTransport } from \"./OneTimeTransport\";\nimport { PollingTransport } from \"./PollingTransport\";\nimport { ConfigEvaluator } from \"@config-evaluator/ConfigEvaluator\";\nimport { getRequestedType, parseConfigValue } from \"@shared/value-parser\";\nimport type {\n ConfigDirectorContext,\n ConfigDirectorClientOptions,\n ConfigDirectorClient,\n ClientEvents,\n WatchHandler,\n ConfigValueType,\n ConfigDirectorLogger,\n Transport,\n IdentifyingSdkOptions,\n ConfigBundle,\n ConfigDefinition,\n ConnectionMode,\n} from \"./types\";\nimport { createDefaultLogger } from \"./logger\";\nimport { ConfigDirectorValidationError } from \"@shared/errors\";\nimport EventEmitter from \"node:events\";\nimport type { ConfigDirectorMetaContext } from \"@shared/types\";\nimport { defaultUrlFactory } from \"@shared/url\";\nimport { ServerTelemetryEventCollector } from \"./telemetry\";\n\nconst defaultBaseUrl = new URL(\"https://server-sdk-api.configdirector.com\");\nconst DEFAULT_FLUSH_INTERVAL = 30_000;\nconst DEFAULT_EVENT_QUEUE_LIMIT = 5_000;\n\ntype WatchHandlerWithOptions<T extends ConfigValueType> = {\n handler: WatchHandler<T>;\n defaultValue: T;\n requestedType: string;\n context?: ConfigDirectorContext;\n};\n\nexport class DefaultConfigDirectorClient implements ConfigDirectorClient {\n private logger: ConfigDirectorLogger;\n private usageEventCollector: ServerTelemetryEventCollector;\n private configSet: ConfigBundle | undefined;\n private handlersMap: Map<string, WatchHandlerWithOptions<any>[]> = new Map();\n private transport: Transport;\n private eventEmitter = new EventEmitter();\n private timeout: number;\n private ready = false;\n private readyPromise: Promise<void> | undefined;\n private readyResolve: (() => void) | undefined;\n private connectionMode: ConnectionMode;\n private configEvaluator: ConfigEvaluator;\n private metaContext: ConfigDirectorMetaContext;\n\n constructor(\n serverSdkKey: string,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n ) {\n this.logger = clientOptions?.logger ?? createDefaultLogger();\n this.timeout = clientOptions?.connection?.timeout ?? 3_000;\n this.metaContext = clientOptions?.metadata ?? {};\n this.configEvaluator = new ConfigEvaluator(this.logger);\n const baseUrl = this.parseUrl(clientOptions?.connection?.url) ?? defaultBaseUrl;\n this.connectionMode = clientOptions?.connection?.mode ?? \"streaming\";\n const transportConstructor = this.getTransportConstructor(this.connectionMode);\n const queueLimit = clientOptions?.telemetry?.eventQueueLimit ?? DEFAULT_EVENT_QUEUE_LIMIT;\n this.usageEventCollector = new ServerTelemetryEventCollector({\n sdkKey: serverSdkKey,\n logger: this.logger,\n baseUrl,\n flushIntervalDelay: clientOptions?.telemetry?.flushInterval ?? DEFAULT_FLUSH_INTERVAL,\n evaluationQueueLimit: Math.ceil(queueLimit * 0.7),\n contextLimit: Math.floor(queueLimit * 0.3),\n urlFactory: defaultUrlFactory,\n });\n this.transport = new transportConstructor({\n serverSdkKey,\n baseUrl,\n metaContext: {\n ...clientOptions?.metadata,\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n },\n logger: this.logger,\n pollingInterval: clientOptions?.connection?.pollingInterval,\n });\n\n this.transport.on(\"configBundleReceived\", (configBundle: ConfigBundle) => {\n this.readyResolve?.();\n const configKeys = Object.keys(configBundle.configs);\n if (!this.configSet || configBundle.kind == \"full\") {\n this.configSet = configBundle;\n this.eventEmitter.emit(\"configsUpdated\", { keys: configKeys });\n this.updateWatchers(configBundle.configs);\n } else {\n this.configSet.configs = {\n ...this.configSet.configs,\n ...configBundle.configs,\n };\n this.eventEmitter.emit(\"configsUpdated\", { keys: configKeys });\n this.updateWatchers(configBundle.configs);\n }\n this.logger.debug(\n `[ConfigDirectorClient] ConfigSet updated from server with ${configKeys.length} key(s)`,\n { keys: configKeys },\n );\n });\n }\n\n public async initialize() {\n try {\n this.ready = false;\n this.readyPromise = new Promise<void>((resolve) => {\n this.readyResolve = resolve;\n }).then(() => {\n this.ready = true;\n this.eventEmitter.emit(\"clientReady\");\n this.logger.debug(\"[ConfigDirectorClient] Received initial payload from the server, client is ready\");\n });\n const startTime = new Date().getTime();\n await this.transport.connect(this.timeout);\n const elapsedTime = new Date().getTime() - startTime;\n const remainingTimeout = this.timeout - elapsedTime;\n if (remainingTimeout > 0) {\n await Promise.race([\n this.readyPromise,\n new Promise<void>((resolve) => {\n setTimeout(() => resolve(), remainingTimeout);\n }),\n ]);\n }\n if (!this.ready) {\n const warningDetails = this.connectionMode === \"streaming\"\n ? \"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.\"\n : \"Since the client was configured without streaming, configs may not update and always return the default value.\";\n this.logger.warn(\n `[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${warningDetails}`,\n );\n }\n } catch (error) {\n this.logger.error(\"[ConfigDirectorClient] An error occurred during initialization: \", error);\n }\n }\n\n private getTransportConstructor(mode: ConnectionMode) {\n switch (mode) {\n case \"one-time\":\n return OneTimeTransport;\n case \"polling\":\n return PollingTransport;\n default:\n return StreamingTransport;\n }\n }\n\n private updateWatchers(configsMap: Record<string, ConfigDefinition>) {\n Object.values(configsMap).forEach((v) => this.updateWatchersForConfig(v as ConfigDefinition));\n }\n\n private updateWatchersForConfig(configDefinition: ConfigDefinition) {\n this.handlersMap.get(configDefinition.key)?.forEach((h) => {\n const value = this.getValueFromConfigDefinition(\n configDefinition.key,\n configDefinition,\n h.defaultValue,\n h.context,\n );\n h.handler(value);\n });\n }\n\n public watch<T extends ConfigValueType>(\n configKey: string,\n defaultValue: T,\n callback: WatchHandler<T>,\n context?: ConfigDirectorContext,\n ) {\n this.validateDefaultValue(defaultValue);\n\n const handlers = this.handlersMap.get(configKey);\n const handlerWithOptions = {\n handler: callback,\n defaultValue,\n requestedType: typeof defaultValue,\n context,\n };\n if (handlers) {\n handlers.push(handlerWithOptions);\n } else {\n this.handlersMap.set(configKey, [handlerWithOptions]);\n }\n\n return () => this.unwatch(configKey, callback);\n }\n\n public unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>) {\n const handlers = this.handlersMap.get(configKey);\n if (!handlers) {\n return;\n }\n\n if (callback) {\n const index = handlers.findIndex((h) => h.handler == callback);\n if (index >= 0) {\n handlers?.splice(index, 1);\n }\n } else {\n handlers.splice(0);\n }\n }\n\n public getValue<T extends ConfigValueType>(\n configKey: string,\n defaultValue: T,\n context?: ConfigDirectorContext,\n ): T {\n this.validateDefaultValue(defaultValue);\n\n const configDefinition = this.configSet?.configs[configKey];\n return this.getValueFromConfigDefinition(configKey, configDefinition, defaultValue, context);\n }\n\n private getValueFromConfigDefinition<T extends ConfigValueType>(\n configKey: string,\n configDefinition: ConfigDefinition | undefined,\n defaultValue: T,\n context?: ConfigDirectorContext,\n ): T {\n if (configDefinition) {\n const configState = this.configEvaluator.evaluate(configDefinition, {\n context,\n metadata: this.metaContext,\n });\n const parseResult = parseConfigValue<T>(configState, defaultValue);\n this.usageEventCollector.evaluatedConfig({\n context,\n evaluation: {\n key: configKey,\n defaultValue: defaultValue,\n requestedType: parseResult.requestedType,\n evaluatedValue: parseResult.parsedValue,\n usedDefault: parseResult.usedDefault,\n evaluationReason: parseResult.reason,\n },\n });\n this.logger.debug(`[ConfigDirectorClient] Evaluated '${configKey}' to '${parseResult.parsedValue}'`);\n return parseResult.parsedValue;\n } else {\n this.logger.debug(\n `[ConfigDirectorClient] No config state found for '${configKey}', returning default value '${defaultValue}'`,\n );\n this.usageEventCollector.evaluatedConfig({\n context,\n evaluation: {\n key: configKey,\n defaultValue: defaultValue,\n requestedType: getRequestedType(defaultValue),\n evaluatedValue: defaultValue,\n usedDefault: true,\n evaluationReason: \"config-state-missing\",\n },\n });\n return defaultValue;\n }\n }\n\n private parseUrl(url: string | undefined): URL | undefined {\n if (!url) {\n return;\n }\n\n try {\n return new URL(url);\n } catch (error) {\n throw new ConfigDirectorValidationError(`Invalid base URL '${url}'. Parsing failed: ${error}`);\n }\n }\n\n private validateDefaultValue<T extends ConfigValueType>(defaultValue: T) {\n if (defaultValue === undefined || defaultValue === null) {\n throw new ConfigDirectorValidationError(\n \"Invalid default value. The default value for a config must be defined and non-null.\",\n );\n }\n\n if (typeof defaultValue === \"function\") {\n throw new ConfigDirectorValidationError(\n \"Invalid default value. The default value for a config cannot be a function.\",\n );\n }\n }\n\n public get isReady(): boolean {\n return this.ready;\n }\n\n public on<T extends keyof ClientEvents>(eventName: T, handler: (args: ClientEvents[T]) => void): void {\n this.eventEmitter.on(eventName, handler);\n }\n\n public off<T extends keyof ClientEvents>(eventName: T, handler?: (args: ClientEvents[T]) => void) {\n if (handler) {\n this.eventEmitter.off(eventName, handler);\n } else {\n this.eventEmitter.removeAllListeners(eventName);\n }\n }\n\n public removeAllObservers() {\n this.logger.debug(\"[ConfigDirectorClient] removeAllObservers() has been called, removing all observers\");\n this.eventEmitter.removeAllListeners();\n this.handlersMap.clear();\n }\n\n public unwatchAll() {\n this.handlersMap.clear();\n }\n\n public closeConnection() {\n this.logger.debug(\n \"[ConfigDirectorClient] closeConnection() has been called, closing connection to server\",\n );\n this.transport.close();\n this.ready = false;\n }\n\n public dispose() {\n this.removeAllObservers();\n this.closeConnection();\n }\n}\n","import { DefaultConsoleLogger } from \"@shared/logger\";\nimport type { ConfigDirectorLoggingLevel, ConfigDirectorLogMessageDecorator } from \"@shared/types\";\n\nclass LogMessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:nextjs-sdk] ${message}`;\n }\n}\n\nexport const createDefaultLogger = (\n level?: ConfigDirectorLoggingLevel,\n messageDecorator?: ConfigDirectorLogMessageDecorator,\n) => {\n return new DefaultConsoleLogger(level ?? \"warn\", messageDecorator ?? new LogMessageDecorator());\n};\n\nexport const createConsoleLogger = (\n level: ConfigDirectorLoggingLevel,\n messageDecorator?: ConfigDirectorLogMessageDecorator,\n) => {\n return new DefaultConsoleLogger(level, messageDecorator ?? new LogMessageDecorator());\n};\n","import { DefaultConfigDirectorClient } from \"@js-server-sdk/DefaultConfigDirectorClient\";\nimport type { ConfigDirectorClient, ConfigDirectorClientOptions } from \"@js-server-sdk/types\";\nimport { createDefaultLogger } from \"./logger\";\nimport { ConfigDirectorInitializationError } from \"@shared/errors\";\n\ndeclare global {\n var __configDirectorServerClient: ConfigDirectorClient | undefined;\n}\n\nexport type RegisterOptions = {\n /**\n * Your ConfigDirector Server SDK key. This is a secret value — do not commit it to source\n * control. Provide it via an environment variable (e.g. process.env.CONFIGDIRECTOR_SERVER_KEY).\n */\n serverSdkKey: string;\n} & ConfigDirectorClientOptions;\n\n/**\n * Initializes the ConfigDirector server SDK singleton. Call this from your Next.js\n * `instrumentation.ts` file so it runs once when the server starts:\n *\n * ```ts\n * // instrumentation.ts\n * export async function register() {\n * if (process.env.NEXT_RUNTIME === \"nodejs\") {\n * const { register } = await import(\"@configdirector/nextjs-sdk/server\");\n * await register({ serverSdkKey: process.env.CONFIGDIRECTOR_SERVER_KEY! });\n * }\n * }\n * ```\n */\nexport async function register(options: RegisterOptions): Promise<void> {\n if (!options.serverSdkKey) {\n const message =\n \"The ConfigDirector serverSdkKey must be provided to register(). You can pass it via process.env.CONFIGDIRECTOR_SERVER_KEY.\";\n createDefaultLogger().error(message);\n throw new ConfigDirectorInitializationError(message);\n }\n\n if (!globalThis.__configDirectorServerClient) {\n const { serverSdkKey, ...clientOptions } = options;\n const client = new DefaultConfigDirectorClient(\n serverSdkKey,\n { sdkName: \"nextjs-sdk\", sdkVersion: \"__VERSION__\" },\n clientOptions,\n );\n globalThis.__configDirectorServerClient = client;\n await client.initialize();\n }\n}\n\nexport function getServerSingleton(): ConfigDirectorClient {\n if (!globalThis.__configDirectorServerClient) {\n throw new ConfigDirectorInitializationError(\n \"[ConfigDirector] Server client not initialized. Make sure to call register() in your instrumentation.ts file before using the SDK.\",\n );\n }\n return globalThis.__configDirectorServerClient;\n}\n","import type { ConfigDirectorContext, ConfigValueType, WatchHandler } from \"@js-server-sdk/types\";\nimport { getServerSingleton } from \"./singleton\";\n\n/**\n * A thin wrapper around the server SDK singleton that binds a per-request user context to every\n * evaluation, making it behave like the browser client (no context arg on getValue/watch) from\n * the perspective of calling code.\n *\n * Create one per request via {@link createSsrClient}. The underlying server SDK singleton is\n * shared and long-lived; the SsrClient is lightweight and request-scoped.\n */\nexport class SsrClient {\n constructor(private readonly context: ConfigDirectorContext | undefined) {}\n\n get isReady(): boolean {\n return getServerSingleton().isReady;\n }\n\n getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T {\n return getServerSingleton().getValue(configKey, defaultValue, this.context);\n }\n\n /**\n * Synchronously evaluates the config and calls the callback once, then returns a no-op unwatch.\n *\n * In a Server Component there is no component lifecycle to subscribe to, so live-watching is not\n * meaningful. Use getValue() directly in Server Components; watch() is here for symmetry with the\n * browser client interface.\n */\n watch<T extends ConfigValueType>(\n configKey: string,\n defaultValue: T,\n callback: WatchHandler<T>,\n ): () => void {\n callback(this.getValue(configKey, defaultValue));\n return () => {};\n }\n\n unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void {\n getServerSingleton().unwatch(configKey, callback);\n }\n\n unwatchAll(): void {\n getServerSingleton().unwatchAll();\n }\n}\n\n/**\n * Creates a request-scoped {@link SsrClient} that evaluates configs against the shared server\n * SDK singleton using the provided user context.\n *\n * Call this in Server Components or Route Handlers:\n *\n * ```ts\n * // app/dashboard/page.tsx (Server Component)\n * import { createSsrClient } from \"@configdirector/nextjs-sdk/server\";\n * import { cookies } from \"next/headers\";\n *\n * export default async function DashboardPage() {\n * const userId = (await cookies()).get(\"userId\")?.value;\n * const client = createSsrClient({ userId });\n * const showNewDashboard = client.getValue(\"new-dashboard\", false);\n * // ...\n * }\n * ```\n */\nexport function createSsrClient(context?: ConfigDirectorContext): SsrClient {\n return new SsrClient(context);\n}\n"],"mappings":"0KAAA,IAAa,EAAb,MAAa,UAAsC,KAAM,CAIvD,YAAY,EAAiB,EAAiB,CAC5C,MAAM,EAAQ,CAJhB,KAAyB,KAAe,gCAKtC,KAAK,OAAS,EAEd,OAAO,eAAe,KAAM,EAA8B,UAAU,GAI3D,EAAb,MAAa,UAAsC,KAAM,CAGvD,YAAY,EAAiB,CAC3B,MAAM,EAAQ,CAHhB,KAAyB,KAAe,gCAKtC,OAAO,eAAe,KAAM,EAA8B,UAAU,GAI3D,EAAb,MAAa,UAA0C,KAAM,CAG3D,YAAY,EAAiB,CAC3B,MAAM,EAAQ,CAHhB,KAAyB,KAAe,oCAKtC,OAAO,eAAe,KAAM,EAAkC,UAAU,GC5B/D,EAAb,MAAa,UAA0B,KAAM,CAG3C,YAAY,EAAiB,CAC3B,MAAM,EAAQ,CAHhB,KAAyB,KAAe,oBAKtC,OAAO,eAAe,KAAM,EAAkB,UAAU,GAI/C,EAAb,MAAa,UAAiC,KAAM,CAGlD,YAAY,EAAiB,CAC3B,MAAM,EAAQ,CAHhB,KAAyB,KAAe,2BAKtC,OAAO,eAAe,KAAM,EAAyB,UAAU,GAItD,GAAb,MAAa,UAA2B,KAAM,CAG5C,YAAY,EAAiB,CAC3B,MAAM,EAAQ,CAHhB,KAAyB,KAAe,qBAKtC,OAAO,eAAe,KAAM,EAAmB,UAAU,GAIhD,GAAb,MAAa,UAA6B,KAAM,CAG9C,YAAY,EAAiB,CAC3B,MAAM,EAAQ,CAHhB,KAAyB,KAAe,uBAKtC,OAAO,eAAe,KAAM,EAAqB,UAAU,GCxBlD,EAAb,KAA+B,CAS7B,YAAY,EAAmC,CAR/C,KAAQ,aAAe,GACvB,KAAQ,cAAgB,GACxB,KAA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,EAAU,EAAQ"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["ClientProvider"],"sources":["../../src/server/logger.ts","../../src/server/singleton.ts","../../src/server/ssr.ts","../../src/server/ConfigDirectorProvider.tsx"],"sourcesContent":["import { DefaultConsoleLogger } from \"@shared/logger\";\nimport type { ConfigDirectorLoggingLevel, ConfigDirectorLogMessageDecorator } from \"@shared/types\";\n\nclass LogMessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:nextjs-sdk] ${message}`;\n }\n}\n\nexport const createDefaultLogger = (\n level?: ConfigDirectorLoggingLevel,\n messageDecorator?: ConfigDirectorLogMessageDecorator,\n) => {\n return new DefaultConsoleLogger(level ?? \"warn\", messageDecorator ?? new LogMessageDecorator());\n};\n\nexport const createConsoleLogger = (\n level: ConfigDirectorLoggingLevel,\n messageDecorator?: ConfigDirectorLogMessageDecorator,\n) => {\n return new DefaultConsoleLogger(level, messageDecorator ?? new LogMessageDecorator());\n};\n","import type { ConfigDirectorClient, ConfigDirectorClientOptions } from \"@js-server-sdk/types\";\nimport { createDefaultLogger } from \"./logger\";\nimport { ConfigDirectorInitializationError } from \"@shared/errors\";\n\ndeclare global {\n var __configDirectorServerClient: ConfigDirectorClient | undefined;\n var __configDirectorAppMeta: { appName?: string; appVersion?: string } | undefined;\n}\n\nexport type RegisterOptions = {\n /**\n * Your ConfigDirector Server SDK key. This is a secret value — do not commit it to source\n * control. Provide it via an environment variable (e.g. process.env.CONFIGDIRECTOR_SERVER_KEY).\n */\n serverSdkKey: string;\n} & ConfigDirectorClientOptions;\n\n/**\n * Initializes the ConfigDirector server SDK singleton. Call this from your Next.js\n * `instrumentation.ts` file so it runs once when the server starts:\n *\n * ```ts\n * // instrumentation.ts\n * export async function register() {\n * const { register } = await import(\"@configdirector/nextjs-sdk/server\");\n * await register({ serverSdkKey: process.env.CONFIGDIRECTOR_SERVER_KEY! });\n * }\n * ```\n */\nexport async function register(options: RegisterOptions): Promise<void> {\n if (process.env[\"NEXT_RUNTIME\"] !== \"nodejs\") {\n return;\n }\n\n if (!options.serverSdkKey) {\n const message =\n \"The ConfigDirector serverSdkKey must be provided to register(). You can pass it via process.env.CONFIGDIRECTOR_SERVER_KEY.\";\n createDefaultLogger().error(message);\n throw new ConfigDirectorInitializationError(message);\n }\n\n if (!globalThis.__configDirectorServerClient) {\n const { DefaultConfigDirectorClient } = await import(\"@js-server-sdk/DefaultConfigDirectorClient\");\n const { serverSdkKey, ...clientOptions } = options;\n globalThis.__configDirectorAppMeta = {\n appName: options.metadata?.appName,\n appVersion: options.metadata?.appVersion,\n };\n const client = new DefaultConfigDirectorClient(\n serverSdkKey,\n { sdkName: \"nextjs-sdk\", sdkVersion: \"__VERSION__\" },\n clientOptions,\n );\n globalThis.__configDirectorServerClient = client;\n await client.initialize();\n }\n}\n\nexport function getAppMeta(): { appName?: string; appVersion?: string } {\n return globalThis.__configDirectorAppMeta ?? {};\n}\n\nexport function getServerSingleton(): ConfigDirectorClient {\n if (!globalThis.__configDirectorServerClient) {\n throw new ConfigDirectorInitializationError(\n \"[ConfigDirector] Server client not initialized. Make sure to call register() in your instrumentation.ts file before using the SDK.\",\n );\n }\n return globalThis.__configDirectorServerClient;\n}\n","import type { ConfigDirectorContext, ConfigState } from \"@js-server-sdk/types\";\nimport { getServerSingleton } from \"./singleton\";\nimport { createDefaultLogger } from \"./logger\";\n\nconst logger = createDefaultLogger();\n\nexport type GenerateSsrConfigSetOptions = {\n /** User context for targeting rule evaluation. */\n context?: ConfigDirectorContext;\n /**\n * Restrict the returned config set to these keys. When omitted, all known configs are\n * returned. Useful when you want to pre-evaluate only a specific subset of flags.\n */\n configKeys?: string[];\n};\n\n/**\n * Evaluates configs server-side and returns a map of {@link ConfigState} objects keyed by\n * config key, suitable for passing as `initialConfigs` to `ConfigDirectorProvider`.\n *\n * Returns an empty object when the server SDK isn't initialized yet (e.g. during\n * `next build` static analysis without a live connection).\n *\n * In most cases you don't need this directly — use the `ConfigDirectorProvider` exported\n * from `@configdirector/nextjs-sdk/server`, which calls this automatically.\n */\nexport function generateSsrConfigSet(options?: GenerateSsrConfigSetOptions): Record<string, ConfigState> {\n try {\n return getServerSingleton().getAllConfigs(options);\n } catch (error) {\n logger.error(\"Error retrieving SSR config set:\", error);\n return {};\n }\n}\n","import type { PropsWithChildren } from \"react\";\nimport { ConfigDirectorProvider as ClientProvider } from \"@configdirector/nextjs-sdk/client\";\nimport type { ConfigDirectorProviderOptions } from \"../client/types\";\nimport { generateSsrConfigSet } from \"./ssr\";\nimport { getAppMeta } from \"./singleton\";\n\n/**\n * Props for {@link ConfigDirectorProvider}. Identical to the client provider options\n * except `initialConfigs` is omitted — SSR-evaluated values are injected automatically.\n */\nexport type ConfigDirectorProviderProps = Omit<ConfigDirectorProviderOptions, \"initialConfigs\"> & {\n /**\n * Restrict SSR pre-evaluation to these config keys. When omitted, all known configs are\n * pre-evaluated. Useful when you have a large config set and only need a subset hydrated\n * on this layout.\n */\n configKeys?: string[];\n};\n\n/**\n * React Server Component wrapper around the ConfigDirector client provider.\n *\n * Place this in your root layout. It pre-evaluates all configs on the server using the\n * provided context and passes them to the client provider, preventing any flash of wrong\n * content on hydration.\n *\n * Requires Next.js 13+ (App Router) and React 18+.\n *\n * @example\n * ```tsx\n * // app/layout.tsx\n * import { ConfigDirectorProvider } from \"@configdirector/nextjs-sdk/server\";\n * import { cookies } from \"next/headers\";\n *\n * export default async function RootLayout({ children }) {\n * const userId = (await cookies()).get(\"userId\")?.value;\n * return (\n * <html>\n * <body>\n * <ConfigDirectorProvider\n * sdkKey={process.env.NEXT_PUBLIC_CONFIGDIRECTOR_CLIENT_KEY!}\n * context={{ userId }}\n * >\n * {children}\n * </ConfigDirectorProvider>\n * </body>\n * </html>\n * );\n * }\n * ```\n */\nexport async function ConfigDirectorProvider({\n children,\n configKeys,\n ...props\n}: PropsWithChildren<ConfigDirectorProviderProps>) {\n const initialConfigs = generateSsrConfigSet({ context: props.context, configKeys });\n const appMeta = getAppMeta();\n return (\n <ClientProvider\n {...props}\n appName={props.appName ?? appMeta.appName}\n appVersion={props.appVersion ?? appMeta.appVersion}\n initialConfigs={initialConfigs}>\n {children}\n </ClientProvider>\n );\n}\n"],"mappings":"oKAGA,IAAM,EAAN,KAAuE,CACrE,gBAAgB,EAAyB,CACvC,MAAO,+BAA+B,MAI1C,MAAa,GACX,EACA,IAEO,IAAI,EAAqB,GAAS,OAAQ,GAAoB,IAAI,EAAsB,CAGpF,GACX,EACA,IAEO,IAAI,EAAqB,EAAO,GAAoB,IAAI,EAAsB,CCSvF,eAAsB,EAAS,EAAyC,CAClE,WAAQ,IAAI,eAAoB,SAIpC,IAAI,CAAC,EAAQ,aAAc,CACzB,IAAM,EACJ,6HAEF,MADA,GAAqB,CAAC,MAAM,EAAQ,CAC9B,IAAI,EAAkC,EAAQ,CAGtD,GAAI,CAAC,WAAW,6BAA8B,CAC5C,GAAM,CAAE,+BAAgC,MAAM,OAAO,8CAC/C,CAAE,eAAc,GAAG,GAAkB,EAC3C,WAAW,wBAA0B,CACnC,QAAS,EAAQ,UAAU,QAC3B,WAAY,EAAQ,UAAU,WAC/B,CACD,IAAM,EAAS,IAAI,EACjB,EACA,CAAE,QAAS,aAAc,WAAY,QAAe,CACpD,EACD,CACD,WAAW,6BAA+B,EAC1C,MAAM,EAAO,YAAY,GAI7B,SAAgB,GAAwD,CACtE,OAAO,WAAW,yBAA2B,EAAE,CAGjD,SAAgB,GAA2C,CACzD,GAAI,CAAC,WAAW,6BACd,MAAM,IAAI,EACR,qIACD,CAEH,OAAO,WAAW,6BChEpB,MAAM,EAAS,GAAqB,CAsBpC,SAAgB,EAAqB,EAAoE,CACvG,GAAI,CACF,OAAO,GAAoB,CAAC,cAAc,EAAQ,OAC3C,EAAO,CAEd,OADA,EAAO,MAAM,mCAAoC,EAAM,CAChD,EAAE,ECoBb,eAAsB,EAAuB,CAC3C,WACA,aACA,GAAG,GAC8C,CACjD,IAAM,EAAiB,EAAqB,CAAE,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