@configdirector/nextjs-sdk 1.6.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +41 -0
  2. package/dist/client/index.cjs +1 -5
  3. package/dist/client/index.d.cts +52 -216
  4. package/dist/client/index.d.cts.map +1 -1
  5. package/dist/client/index.d.mts +52 -216
  6. package/dist/client/index.d.mts.map +1 -1
  7. package/dist/client/index.mjs +1 -5
  8. package/dist/client/index.mjs.map +1 -1
  9. package/dist/client/installedTestClient-CrHwnJTr.mjs +7 -0
  10. package/dist/client/installedTestClient-CrHwnJTr.mjs.map +1 -0
  11. package/dist/client/installedTestClient-LbS5fHdP.cjs +6 -0
  12. package/dist/client/testing.cjs +2 -0
  13. package/dist/client/testing.d.cts +159 -0
  14. package/dist/client/testing.d.cts.map +1 -0
  15. package/dist/client/testing.d.mts +159 -0
  16. package/dist/client/testing.d.mts.map +1 -0
  17. package/dist/client/testing.mjs +3 -0
  18. package/dist/client/testing.mjs.map +1 -0
  19. package/dist/client/types-DA2VZKNX.d.mts +220 -0
  20. package/dist/client/types-DA2VZKNX.d.mts.map +1 -0
  21. package/dist/client/types-fL7X5zwg.d.cts +220 -0
  22. package/dist/client/types-fL7X5zwg.d.cts.map +1 -0
  23. package/dist/server/DefaultConfigDirectorClient-BhyVJv6Z.mjs +6 -0
  24. package/dist/server/DefaultConfigDirectorClient-BhyVJv6Z.mjs.map +1 -0
  25. package/dist/server/DefaultConfigDirectorClient-BngKzHat.cjs +5 -0
  26. package/dist/server/{errors-B1AJJTZ-.mjs → errors-BGpFuqOO.mjs} +1 -1
  27. package/dist/server/{errors-B1AJJTZ-.mjs.map → errors-BGpFuqOO.mjs.map} +1 -1
  28. package/dist/server/index.cjs +1 -1
  29. package/dist/server/index.d.cts +14 -288
  30. package/dist/server/index.d.cts.map +1 -1
  31. package/dist/server/index.d.mts +14 -288
  32. package/dist/server/index.d.mts.map +1 -1
  33. package/dist/server/index.mjs +1 -1
  34. package/dist/server/index.mjs.map +1 -1
  35. package/dist/server/testing.cjs +1 -0
  36. package/dist/server/testing.d.cts +119 -0
  37. package/dist/server/testing.d.cts.map +1 -0
  38. package/dist/server/testing.d.mts +119 -0
  39. package/dist/server/testing.d.mts.map +1 -0
  40. package/dist/server/testing.mjs +2 -0
  41. package/dist/server/testing.mjs.map +1 -0
  42. package/dist/server/types-DnzM2ukj.d.cts +292 -0
  43. package/dist/server/types-DnzM2ukj.d.cts.map +1 -0
  44. package/dist/server/types-qIeNbtNf.d.mts +292 -0
  45. package/dist/server/types-qIeNbtNf.d.mts.map +1 -0
  46. package/package.json +37 -2
  47. package/dist/server/DefaultConfigDirectorClient-CAMGE6h8.mjs +0 -6
  48. package/dist/server/DefaultConfigDirectorClient-CAMGE6h8.mjs.map +0 -1
  49. package/dist/server/DefaultConfigDirectorClient-DhSSj7ds.cjs +0 -5
  50. /package/dist/server/{errors-zhcEWVnY.cjs → errors-CCbuIqT8.cjs} +0 -0
@@ -0,0 +1,119 @@
1
+ import { a as ConfigDirectorLogger, t as ConfigDirectorClient } from "./types-qIeNbtNf.mjs";
2
+
3
+ //#region ../shared/src/errors.d.ts
4
+ declare class ConfigDirectorConnectionError extends Error {
5
+ readonly name: string;
6
+ readonly status?: number;
7
+ constructor(message: string, status?: number);
8
+ }
9
+ declare class ConfigDirectorValidationError extends Error {
10
+ readonly name: string;
11
+ constructor(message: string);
12
+ }
13
+ //#endregion
14
+ //#region ../shared/src/testing/values.d.ts
15
+ type TestJsonValue = boolean | number | string | null | TestJsonValue[] | {
16
+ [key: string]: TestJsonValue;
17
+ };
18
+ type TestValue = boolean | number | string | TestJsonValue[] | {
19
+ [key: string]: TestJsonValue;
20
+ };
21
+ type TestValues = Record<string, TestValue>;
22
+ //#endregion
23
+ //#region ../js-server-sdk/src/testing/TestClient.d.ts
24
+ /**
25
+ * Options for {@link createTestClient}. Every option is optional.
26
+ */
27
+ type TestClientOptions = {
28
+ /**
29
+ * The config values the test client serves once its client connects, keyed by config key. The
30
+ * config type follows from each value: a boolean, an integral number (`integer`), any other
31
+ * number (`float`), a string, or a plain object or array (`json`). Every context receives the
32
+ * same value.
33
+ */
34
+ values?: TestValues;
35
+ /**
36
+ * The connection timeout of the SDK client, in milliseconds. It bounds how long a held
37
+ * `initialize` waits. Defaults to the SDK's production timeout.
38
+ */
39
+ timeout?: number;
40
+ /**
41
+ * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.
42
+ */
43
+ logger?: ConfigDirectorLogger;
44
+ };
45
+ /**
46
+ * A real ConfigDirector client connected to an in-memory server that the test controls.
47
+ *
48
+ * The client under {@link TestClient.client} is the SDK's production client: value parsing,
49
+ * targeting evaluation, watchers, events, and readiness behave as they do against ConfigDirector.
50
+ * Only the network connection and telemetry are replaced, so no request is ever made and nothing
51
+ * is left running after the client is disposed.
52
+ */
53
+ interface TestClient {
54
+ /**
55
+ * The SDK client to hand to the code under test. It starts uninitialized, like a production
56
+ * client; `initialize` completes at once with the seeded values unless initialization is held.
57
+ */
58
+ readonly client: ConfigDirectorClient;
59
+ /**
60
+ * Stores `value` under `key` and, when the client is connected, delivers it as an update, so
61
+ * reads, watchers, and `configsUpdated` handlers see it.
62
+ */
63
+ setValue(key: string, value: TestValue): void;
64
+ /**
65
+ * Removes `key` and, when the client is connected, delivers a full update without it, so reads
66
+ * fall back to the in-code default value and watchers of `key` receive that default.
67
+ */
68
+ removeValue(key: string): void;
69
+ /**
70
+ * Replaces every stored value with `values`, disarms any armed hold or failure, and, when the
71
+ * client is connected, delivers the new values as a full update.
72
+ */
73
+ replaceValues(values: TestValues): void;
74
+ /**
75
+ * Makes the next `initialize` wait until {@link completeInitialization} or
76
+ * {@link failInitialization} is called, or until the client's timeout elapses.
77
+ */
78
+ holdInitialization(): void;
79
+ /**
80
+ * Delivers the stored values to a held `initialize`, so it completes with the client ready. When
81
+ * a hold is armed but no `initialize` has started, it disarms the hold instead.
82
+ */
83
+ completeInitialization(): void;
84
+ /**
85
+ * Fails a held `initialize` with an unrecoverable connection error, or arms the next `initialize`
86
+ * to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.
87
+ */
88
+ failInitialization(): void;
89
+ }
90
+ //#endregion
91
+ //#region src/server/testing.d.ts
92
+ /**
93
+ * Creates a {@link TestClient}: a real server `ConfigDirectorClient` connected to an in-memory
94
+ * server that the test controls. No network connection is opened and no telemetry is sent. Put it
95
+ * where `register()` would put the server singleton with {@link installServerTestClient}.
96
+ *
97
+ * @param options {@link TestClientOptions}: the initial values, the client's timeout, and its logger
98
+ * @returns A {@link TestClient} whose `client` is passed to the code under test
99
+ *
100
+ * @example
101
+ * import { createTestClient, installServerTestClient } from "@configdirector/nextjs-sdk/server/testing";
102
+ *
103
+ * const testClient = createTestClient({ values: { "new-checkout": true } });
104
+ * const uninstall = installServerTestClient(testClient);
105
+ * await testClient.client.initialize();
106
+ */
107
+ declare const createTestClient: (options?: TestClientOptions) => TestClient;
108
+ /**
109
+ * Puts `testClient.client` where `register()` puts the server singleton, so `getConfigClient()`,
110
+ * `generateSsrConfigSet()`, and the server `ConfigDirectorProvider` serve its values. It does not
111
+ * initialize the client: call `await testClient.client.initialize()`, as `register()` would.
112
+ *
113
+ * @param testClient The server test client whose `client` to install
114
+ * @returns A function that restores the client installed before
115
+ */
116
+ declare const installServerTestClient: (testClient: TestClient) => (() => void);
117
+ //#endregion
118
+ export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type TestJsonValue, type TestValue, type TestValues, createTestClient, installServerTestClient };
119
+ //# sourceMappingURL=testing.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.mts","names":[],"sources":["../../../shared/src/errors.ts","../../../shared/src/testing/values.ts","../../../js-server-sdk/src/testing/TestClient.ts","../../src/server/testing.ts"],"mappings":";;;cAAa,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;EAAA,SACT,MAAA;cAEJ,OAAA,UAAiB,MAAA;AAAA;AAAA,cAQlB,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;cAEb,OAAA;AAAA;;;KCZF,aAAA,sCAAmD,aAAA;EAAA,CAAqB,GAAA,WAAc,aAAA;AAAA;AAAA,KAEtF,SAAA,+BAAwC,aAAA;EAAA,CAAqB,GAAA,WAAc,aAAA;AAAA;AAAA,KAE3E,UAAA,GAAa,MAAA,SAAe,SAAA;;;;ADPxC;;KEYY,iBAAA;EFZ4C;;;;;;EEmBtD,MAAA,GAAS,UAAA;EFfmC;;AAQ9C;;EEYE,OAAA;EFZsD;;;EEgBtD,MAAA,GAAS,oBAAA;AAAA;;;;;;ADzBX;;;UCoCiB,UAAA;EDpC8C;;;;EAAA,SCyCpD,MAAA,EAAQ,oBAAA;EDvCP;;;;EC6CV,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,SAAA;ED7C0C;;;;ECmDvE,WAAA,CAAY,GAAA;EDjDQ;;;;ECuDpB,aAAA,CAAc,MAAA,EAAQ,UAAA;;;AAlDxB;;EAwDE,kBAAA;EAxC6B;;;;EA8C7B,sBAAA;EA9CS;;;AAWX;EAyCE,kBAAA;AAAA;;;;;;;;;;;;;;AFpEF;;;;cGUa,gBAAA,GAAoB,OAAA,GAAU,iBAAA,KAAoB,UAAA;;;;;;;;;cAYlD,uBAAA,GAA2B,UAAA,EAAY,UAAA"}
@@ -0,0 +1,2 @@
1
+ import{r as e,t}from"./DefaultConfigDirectorClient-BhyVJv6Z.mjs";import{r as n,t as r}from"./errors-BGpFuqOO.mjs";import i from"node:events";const a=(e,t)=>{if(e.trim().length==0)throw new n(`Invalid config key. The key of a test value cannot be empty.`);return o(e,t)},o=(e,t)=>{switch(typeof t){case`boolean`:return{type:`boolean`,value:t?`true`:`false`};case`number`:return s(e,t);case`string`:return{type:`string`,value:t};case`object`:if(t!==null)return l(e,t,``),{type:`json`,value:JSON.stringify(t)}}throw new n(`Invalid test value for '${e}': ${f(t)}. Use a boolean, a number, a string, a plain object, or an array.`)},s=(e,t)=>{if(!Number.isFinite(t))throw new n(`Invalid test value for '${e}': ${f(t)} is not a finite number.`);if(Number.isInteger(t)){if(!Number.isSafeInteger(t))throw new n(`Invalid test value for '${e}': ${t} is not a safe integer, so the SDK could not read it back exactly.`);return{type:`integer`,value:String(t)}}return{type:`float`,value:c(t)}},c=e=>{let t=String(e),n=t.indexOf(`e-`);if(n<0)return t;let r=t.startsWith(`-`)?`-`:``,[i=``,a=``]=t.slice(r.length,n).split(`.`),o=Number(t.slice(n+2))-i.length;return`${r}0.${`0`.repeat(o)}${i}${a}`},l=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw u(e,n,`${f(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>l(e,t,`${n}[${r}]`));return}if(d(t)){for(let[r,i]of Object.entries(t))l(e,i,n?`${n}.${r}`:r);return}throw u(e,n,`${f(t)} cannot be encoded as JSON`)}},u=(e,t,r)=>new n(`Invalid test value for '${e}'${t?` at '${t}'`:``}: ${r}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),d=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},f=e=>e===null?`null`:typeof e==`function`?`a function`:typeof e==`object`?`a ${e.constructor?.name??`object`} instance`:typeof e==`symbol`?`a symbol`:String(e),p=(e,t)=>{let n=a(e,t);return{id:`test-config:${e}`,key:e,type:n.type,variations:[{name:null,value:n.value}],target:{defaultValue:n.value,rules:[]}}},m={environmentId:`test-environment`,projectId:`test-project`};var h=class{constructor(e,t){this.logger=e,this.emitter=new i,this.configs=new Map,this.pendingDeliveries=[],this.armed=`nothing`,this.connected=!1,this.delivering=!1,this.encodeAll(t).forEach((e,t)=>this.configs.set(t,e))}setValue(e,t){let n=p(e,t);this.configs.set(e,n),this.deliverIfConnected({...m,kind:`delta`,configs:{[e]:n}})}removeValue(e){this.configs.delete(e),this.deliverIfConnected(this.fullUpdate())}replaceValues(e){let t=this.encodeAll(e);this.configs.clear(),t.forEach((e,t)=>this.configs.set(t,e)),this.armed=`nothing`,this.deliverIfConnected(this.fullUpdate())}hold(){this.armed=`hold`}complete(){this.pendingHold?this.pendingHold.complete():this.armed===`hold`&&(this.armed=`nothing`)}fail(){this.pendingHold?this.pendingHold.fail():this.armed=`failure`}connect(e){this.endAttempt();let t=this.armed;switch(this.armed=`nothing`,t){case`failure`:return this.failNow();case`hold`:return this.holdNow(e);default:return this.connectNow(),Promise.resolve(this)}}get isConnected(){return this.connected}on(e,t){this.emitter.on(e,t)}off(e,t){t?this.emitter.off(e,t):this.emitter.removeAllListeners(e)}close(){this.endAttempt()}dispose(){this.close(),this.emitter.removeAllListeners()}endAttempt(){this.connected=!1,this.pendingHold?.end()}connectNow(){this.connected=!0,this.deliver(this.fullUpdate())}holdNow(e){return new Promise((t,n)=>{let r=setTimeout(()=>this.pendingHold?.end(),e),i=()=>{clearTimeout(r),this.pendingHold=void 0};this.pendingHold={end:()=>{i(),t(this)},complete:()=>{i(),this.connectNow(),t(this)},fail:()=>{i();let e=this.fatalError();this.emitter.emit(`connectionError`,e),n(e)}}})}failNow(){let e=this.fatalError();return this.emitter.emit(`connectionError`,e),Promise.reject(e)}fatalError(){return new r(`Connection failed with status: 401. Error: the test client failed this initialization. This is an unrecoverable error, will not attempt to reconnect.`,401)}deliverIfConnected(e){this.connected&&this.deliver(e)}deliver(e){if(this.pendingDeliveries.push(e),!this.delivering){this.delivering=!0;try{let e=this.pendingDeliveries.shift();for(;e;)this.emitCaught(e),e=this.pendingDeliveries.shift()}finally{this.delivering=!1}}}emitCaught(e){try{this.emitter.emit(`configBundleReceived`,e)}catch(e){this.logger.error(`[InMemoryConnection] Error dispatching a config update from the test client: `,e)}}fullUpdate(){return{...m,kind:`full`,configs:Object.fromEntries(this.configs)}}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,p(n,r));return t}};const g={start:()=>{},evaluatedConfig:()=>{},close:async()=>{}};var _=class{constructor(e,t){this.client=e,this.connection=t}setValue(e,t){this.connection.setValue(e,t)}removeValue(e){this.connection.removeValue(e)}replaceValues(e){this.connection.replaceValues(e)}holdInitialization(){this.connection.hold()}completeInitialization(){this.connection.complete()}failInitialization(){this.connection.fail()}};const v=(n,r)=>{let i=r?.logger??e(),a=new h(i,r?.values??{});return new _(new t(`test-client`,n,{logger:i,connection:{timeout:r?.timeout}},{transport:a,telemetry:g}),a)},y=e=>v({sdkName:`nextjs-sdk`,sdkVersion:`1.8.0`},e),b=e=>{let t=globalThis.__configDirectorServerClient;return globalThis.__configDirectorServerClient=e.client,()=>{globalThis.__configDirectorServerClient=t}};export{r as ConfigDirectorConnectionError,n as ConfigDirectorValidationError,y as createTestClient,b as installServerTestClient};
2
+ //# sourceMappingURL=testing.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.mjs","names":["encodeTestValue","encodeShared","createTestClient"],"sources":["../../../shared/src/testing/values.ts","../../../js-server-sdk/src/testing/values.ts","../../../js-server-sdk/src/testing/InMemoryConnection.ts","../../../js-server-sdk/src/testing/TestClient.ts","../../src/server/testing.ts"],"sourcesContent":["import type { ConfigType } from \"../types\";\nimport { ConfigDirectorValidationError } from \"../errors\";\n\nexport type TestJsonValue = boolean | number | string | null | TestJsonValue[] | { [key: string]: TestJsonValue };\n\nexport type TestValue = boolean | number | string | TestJsonValue[] | { [key: string]: TestJsonValue };\n\nexport type TestValues = Record<string, TestValue>;\n\nexport type EncodedTestValue = { type: ConfigType; value: string };\n\nexport const encodeTestValue = (key: string, value: TestValue): EncodedTestValue => {\n if (key.trim().length == 0) {\n throw new ConfigDirectorValidationError(\"Invalid config key. The key of a test value cannot be empty.\");\n }\n return encode(key, value);\n};\n\nconst encode = (key: string, value: TestValue): EncodedTestValue => {\n switch (typeof value) {\n case \"boolean\":\n return { type: \"boolean\", value: value ? \"true\" : \"false\" };\n case \"number\":\n return encodeNumber(key, value);\n case \"string\":\n return { type: \"string\", value };\n case \"object\":\n if (value !== null) {\n assertJsonContents(key, value, \"\");\n return { type: \"json\", value: JSON.stringify(value) };\n }\n }\n throw new ConfigDirectorValidationError(\n `Invalid test value for '${key}': ${describe(value)}. Use a boolean, a number, a string, a plain object, or an array.`,\n );\n};\n\nconst encodeNumber = (key: string, value: number): EncodedTestValue => {\n if (!Number.isFinite(value)) {\n throw new ConfigDirectorValidationError(`Invalid test value for '${key}': ${describe(value)} is not a finite number.`);\n }\n if (Number.isInteger(value)) {\n if (!Number.isSafeInteger(value)) {\n throw new ConfigDirectorValidationError(\n `Invalid test value for '${key}': ${value} is not a safe integer, so the SDK could not read it back exactly.`,\n );\n }\n return { type: \"integer\", value: String(value) };\n }\n return { type: \"float\", value: toPlainDecimal(value) };\n};\n\nconst toPlainDecimal = (value: number): string => {\n const text = String(value);\n const exponentIndex = text.indexOf(\"e-\");\n if (exponentIndex < 0) {\n return text;\n }\n const sign = text.startsWith(\"-\") ? \"-\" : \"\";\n const [integerDigits = \"\", fractionDigits = \"\"] = text.slice(sign.length, exponentIndex).split(\".\");\n const leadingZeros = Number(text.slice(exponentIndex + 2)) - integerDigits.length;\n return `${sign}0.${\"0\".repeat(leadingZeros)}${integerDigits}${fractionDigits}`;\n};\n\nconst assertJsonContents = (key: string, value: unknown, path: string): void => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return;\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw invalidJsonContents(key, path, `${describe(value)} is not a finite number`);\n }\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) => assertJsonContents(key, item, `${path}[${index}]`));\n return;\n }\n if (isPlainObject(value)) {\n for (const [property, item] of Object.entries(value)) {\n assertJsonContents(key, item, path ? `${path}.${property}` : property);\n }\n return;\n }\n throw invalidJsonContents(key, path, `${describe(value)} cannot be encoded as JSON`);\n};\n\nconst invalidJsonContents = (key: string, path: string, problem: string) =>\n new ConfigDirectorValidationError(\n `Invalid test value for '${key}'${path ? ` at '${path}'` : \"\"}: ${problem}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`,\n );\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n\nconst describe = (value: unknown): string => {\n if (value === null) {\n return \"null\";\n }\n if (typeof value === \"function\") {\n return \"a function\";\n }\n if (typeof value === \"object\") {\n return `a ${value.constructor?.name ?? \"object\"} instance`;\n }\n if (typeof value === \"symbol\") {\n return \"a symbol\";\n }\n return String(value);\n};\n","import type { ConfigDefinition } from \"../types\";\nimport { encodeTestValue as encodeShared } from \"@shared/testing/values\";\nimport type { TestValue } from \"@shared/testing/values\";\n\nexport type { TestJsonValue, TestValue, TestValues } from \"@shared/testing/values\";\n\nexport const encodeTestValue = (key: string, value: TestValue): ConfigDefinition => {\n const encoded = encodeShared(key, value);\n return {\n id: `test-config:${key}`,\n key,\n type: encoded.type,\n variations: [{ name: null, value: encoded.value }],\n target: { defaultValue: encoded.value, rules: [] },\n };\n};\n","import EventEmitter from \"node:events\";\nimport type { ConfigBundle, ConfigDefinition, ConfigDirectorLogger, Transport, TransportEvents } from \"../types\";\nimport { ConfigDirectorConnectionError } from \"@shared/errors\";\nimport { encodeTestValue, type TestValue, type TestValues } from \"./values\";\n\ntype Armed = \"nothing\" | \"hold\" | \"failure\";\n\ntype PendingHold = {\n end: () => void;\n complete: () => void;\n fail: () => void;\n};\n\nconst TEST_ENVIRONMENT = { environmentId: \"test-environment\", projectId: \"test-project\" };\n\nexport class InMemoryConnection implements Transport {\n private readonly emitter = new EventEmitter();\n private readonly configs = new Map<string, ConfigDefinition>();\n private readonly pendingDeliveries: ConfigBundle[] = [];\n private armed: Armed = \"nothing\";\n private pendingHold: PendingHold | undefined;\n private connected = false;\n private delivering = false;\n\n constructor(\n private readonly logger: ConfigDirectorLogger,\n values: TestValues,\n ) {\n this.encodeAll(values).forEach((definition, key) => this.configs.set(key, definition));\n }\n\n public setValue(key: string, value: TestValue) {\n const definition = encodeTestValue(key, value);\n this.configs.set(key, definition);\n this.deliverIfConnected({ ...TEST_ENVIRONMENT, kind: \"delta\", configs: { [key]: definition } });\n }\n\n public removeValue(key: string) {\n this.configs.delete(key);\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public replaceValues(values: TestValues) {\n const encoded = this.encodeAll(values);\n this.configs.clear();\n encoded.forEach((definition, key) => this.configs.set(key, definition));\n this.armed = \"nothing\";\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public hold() {\n this.armed = \"hold\";\n }\n\n public complete() {\n if (this.pendingHold) {\n this.pendingHold.complete();\n } else if (this.armed === \"hold\") {\n this.armed = \"nothing\";\n }\n }\n\n public fail() {\n if (this.pendingHold) {\n this.pendingHold.fail();\n } else {\n this.armed = \"failure\";\n }\n }\n\n public connect(timeout: number): Promise<this> {\n this.endAttempt();\n const armed = this.armed;\n this.armed = \"nothing\";\n switch (armed) {\n case \"failure\":\n return this.failNow();\n case \"hold\":\n return this.holdNow(timeout);\n default:\n this.connectNow();\n return Promise.resolve(this);\n }\n }\n\n public get isConnected(): boolean {\n return this.connected;\n }\n\n public on<TName extends keyof TransportEvents>(name: TName, handler: (payload: TransportEvents[TName]) => void) {\n this.emitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(name: TName, handler?: (payload: TransportEvents[TName]) => void) {\n if (handler) {\n this.emitter.off(name, handler);\n } else {\n this.emitter.removeAllListeners(name);\n }\n }\n\n public close() {\n this.endAttempt();\n }\n\n public dispose() {\n this.close();\n this.emitter.removeAllListeners();\n }\n\n private endAttempt() {\n this.connected = false;\n this.pendingHold?.end();\n }\n\n private connectNow() {\n this.connected = true;\n this.deliver(this.fullUpdate());\n }\n\n private holdNow(timeout: number): Promise<this> {\n return new Promise<this>((resolve, reject) => {\n const timer = setTimeout(() => this.pendingHold?.end(), timeout);\n const release = () => {\n clearTimeout(timer);\n this.pendingHold = undefined;\n };\n this.pendingHold = {\n end: () => {\n release();\n resolve(this);\n },\n complete: () => {\n release();\n this.connectNow();\n resolve(this);\n },\n fail: () => {\n release();\n const error = this.fatalError();\n this.emitter.emit(\"connectionError\", error);\n reject(error);\n },\n };\n });\n }\n\n private failNow(): Promise<this> {\n const error = this.fatalError();\n this.emitter.emit(\"connectionError\", error);\n return Promise.reject(error);\n }\n\n private fatalError() {\n return new ConfigDirectorConnectionError(\n \"Connection failed with status: 401. Error: the test client failed this initialization. This is an unrecoverable error, will not attempt to reconnect.\",\n 401,\n );\n }\n\n private deliverIfConnected(configBundle: ConfigBundle) {\n if (this.connected) {\n this.deliver(configBundle);\n }\n }\n\n private deliver(configBundle: ConfigBundle) {\n this.pendingDeliveries.push(configBundle);\n if (this.delivering) {\n return;\n }\n this.delivering = true;\n try {\n let next = this.pendingDeliveries.shift();\n while (next) {\n this.emitCaught(next);\n next = this.pendingDeliveries.shift();\n }\n } finally {\n this.delivering = false;\n }\n }\n\n private emitCaught(configBundle: ConfigBundle) {\n try {\n this.emitter.emit(\"configBundleReceived\", configBundle);\n } catch (error) {\n this.logger.error(\"[InMemoryConnection] Error dispatching a config update from the test client: \", error);\n }\n }\n\n private fullUpdate(): ConfigBundle {\n return { ...TEST_ENVIRONMENT, kind: \"full\", configs: Object.fromEntries(this.configs) };\n }\n\n private encodeAll(values: TestValues): Map<string, ConfigDefinition> {\n const encoded = new Map<string, ConfigDefinition>();\n for (const [key, value] of Object.entries(values)) {\n encoded.set(key, encodeTestValue(key, value));\n }\n return encoded;\n }\n}\n","import { DefaultConfigDirectorClient } from \"../DefaultConfigDirectorClient\";\nimport { createDefaultLogger } from \"../logger\";\nimport type { ConfigDirectorClient, ConfigDirectorLogger, IdentifyingSdkOptions } from \"../types\";\nimport type { ServerTelemetryClient } from \"../telemetry\";\nimport { InMemoryConnection } from \"./InMemoryConnection\";\nimport type { TestValue, TestValues } from \"./values\";\n\nconst TEST_CLIENT_SDK_KEY = \"test-client\";\n\n/**\n * Options for {@link createTestClient}. Every option is optional.\n */\nexport type TestClientOptions = {\n /**\n * The config values the test client serves once its client connects, keyed by config key. The\n * config type follows from each value: a boolean, an integral number (`integer`), any other\n * number (`float`), a string, or a plain object or array (`json`). Every context receives the\n * same value.\n */\n values?: TestValues;\n /**\n * The connection timeout of the SDK client, in milliseconds. It bounds how long a held\n * `initialize` waits. Defaults to the SDK's production timeout.\n */\n timeout?: number;\n /**\n * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.\n */\n logger?: ConfigDirectorLogger;\n};\n\n/**\n * A real ConfigDirector client connected to an in-memory server that the test controls.\n *\n * The client under {@link TestClient.client} is the SDK's production client: value parsing,\n * targeting evaluation, watchers, events, and readiness behave as they do against ConfigDirector.\n * Only the network connection and telemetry are replaced, so no request is ever made and nothing\n * is left running after the client is disposed.\n */\nexport interface TestClient {\n /**\n * The SDK client to hand to the code under test. It starts uninitialized, like a production\n * client; `initialize` completes at once with the seeded values unless initialization is held.\n */\n readonly client: ConfigDirectorClient;\n\n /**\n * Stores `value` under `key` and, when the client is connected, delivers it as an update, so\n * reads, watchers, and `configsUpdated` handlers see it.\n */\n setValue(key: string, value: TestValue): void;\n\n /**\n * Removes `key` and, when the client is connected, delivers a full update without it, so reads\n * fall back to the in-code default value and watchers of `key` receive that default.\n */\n removeValue(key: string): void;\n\n /**\n * Replaces every stored value with `values`, disarms any armed hold or failure, and, when the\n * client is connected, delivers the new values as a full update.\n */\n replaceValues(values: TestValues): void;\n\n /**\n * Makes the next `initialize` wait until {@link completeInitialization} or\n * {@link failInitialization} is called, or until the client's timeout elapses.\n */\n holdInitialization(): void;\n\n /**\n * Delivers the stored values to a held `initialize`, so it completes with the client ready. When\n * a hold is armed but no `initialize` has started, it disarms the hold instead.\n */\n completeInitialization(): void;\n\n /**\n * Fails a held `initialize` with an unrecoverable connection error, or arms the next `initialize`\n * to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.\n */\n failInitialization(): void;\n}\n\nconst noopTelemetryClient: ServerTelemetryClient = {\n start: () => {},\n evaluatedConfig: () => {},\n close: async () => {},\n};\n\nclass InMemoryTestClient implements TestClient {\n constructor(\n public readonly client: ConfigDirectorClient,\n private readonly connection: InMemoryConnection,\n ) {}\n\n public setValue(key: string, value: TestValue) {\n this.connection.setValue(key, value);\n }\n\n public removeValue(key: string) {\n this.connection.removeValue(key);\n }\n\n public replaceValues(values: TestValues) {\n this.connection.replaceValues(values);\n }\n\n public holdInitialization() {\n this.connection.hold();\n }\n\n public completeInitialization() {\n this.connection.complete();\n }\n\n public failInitialization() {\n this.connection.fail();\n }\n}\n\nexport const createTestClient = (sdkOptions: IdentifyingSdkOptions, options?: TestClientOptions): TestClient => {\n const logger = options?.logger ?? createDefaultLogger();\n const connection = new InMemoryConnection(logger, options?.values ?? {});\n const client = new DefaultConfigDirectorClient(\n TEST_CLIENT_SDK_KEY,\n sdkOptions,\n { logger, connection: { timeout: options?.timeout } },\n { transport: connection, telemetry: noopTelemetryClient },\n );\n return new InMemoryTestClient(client, connection);\n};\n","import { createTestClient as createServerTestClient } from \"@js-server-sdk/testing/TestClient\";\nimport type { TestClient, TestClientOptions } from \"@js-server-sdk/testing/TestClient\";\n\nexport type { TestClient, TestClientOptions } from \"@js-server-sdk/testing/TestClient\";\nexport type { TestValue, TestValues, TestJsonValue } from \"@js-server-sdk/testing/values\";\nexport { ConfigDirectorConnectionError, ConfigDirectorValidationError } from \"@shared/errors\";\n\n/**\n * Creates a {@link TestClient}: a real server `ConfigDirectorClient` connected to an in-memory\n * server that the test controls. No network connection is opened and no telemetry is sent. Put it\n * where `register()` would put the server singleton with {@link installServerTestClient}.\n *\n * @param options {@link TestClientOptions}: the initial values, the client's timeout, and its logger\n * @returns A {@link TestClient} whose `client` is passed to the code under test\n *\n * @example\n * import { createTestClient, installServerTestClient } from \"@configdirector/nextjs-sdk/server/testing\";\n *\n * const testClient = createTestClient({ values: { \"new-checkout\": true } });\n * const uninstall = installServerTestClient(testClient);\n * await testClient.client.initialize();\n */\nexport const createTestClient = (options?: TestClientOptions): TestClient => {\n return createServerTestClient({ sdkName: \"nextjs-sdk\", sdkVersion: \"__VERSION__\" }, options);\n};\n\n/**\n * Puts `testClient.client` where `register()` puts the server singleton, so `getConfigClient()`,\n * `generateSsrConfigSet()`, and the server `ConfigDirectorProvider` serve its values. It does not\n * initialize the client: call `await testClient.client.initialize()`, as `register()` would.\n *\n * @param testClient The server test client whose `client` to install\n * @returns A function that restores the client installed before\n */\nexport const installServerTestClient = (testClient: TestClient): (() => void) => {\n const previous = globalThis.__configDirectorServerClient;\n globalThis.__configDirectorServerClient = testClient.client;\n return () => {\n globalThis.__configDirectorServerClient = previous;\n };\n};\n"],"mappings":"6IAWA,MAAaA,GAAmB,EAAa,IAAuC,CAClF,GAAI,EAAI,MAAM,CAAC,QAAU,EACvB,MAAM,IAAI,EAA8B,+DAA+D,CAEzG,OAAO,EAAO,EAAK,EAAM,EAGrB,GAAU,EAAa,IAAuC,CAClE,OAAQ,OAAO,EAAf,CACE,IAAK,UACH,MAAO,CAAE,KAAM,UAAW,MAAO,EAAQ,OAAS,QAAS,CAC7D,IAAK,SACH,OAAO,EAAa,EAAK,EAAM,CACjC,IAAK,SACH,MAAO,CAAE,KAAM,SAAU,QAAO,CAClC,IAAK,SACH,GAAI,IAAU,KAEZ,OADA,EAAmB,EAAK,EAAO,GAAG,CAC3B,CAAE,KAAM,OAAQ,MAAO,KAAK,UAAU,EAAM,CAAE,CAG3D,MAAM,IAAI,EACR,2BAA2B,EAAI,KAAK,EAAS,EAAM,CAAC,mEACrD,EAGG,GAAgB,EAAa,IAAoC,CACrE,GAAI,CAAC,OAAO,SAAS,EAAM,CACzB,MAAM,IAAI,EAA8B,2BAA2B,EAAI,KAAK,EAAS,EAAM,CAAC,0BAA0B,CAExH,GAAI,OAAO,UAAU,EAAM,CAAE,CAC3B,GAAI,CAAC,OAAO,cAAc,EAAM,CAC9B,MAAM,IAAI,EACR,2BAA2B,EAAI,KAAK,EAAM,oE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B,CACvC,KAAK,WAAW,cAAc,EAAO,CAGvC,oBAA4B,CAC1B,KAAK,WAAW,MAAM,CAGxB,wBAAgC,CAC9B,KAAK,WAAW,UAAU,CAG5B,oBAA4B,CAC1B,KAAK,WAAW,MAAM,GAI1B,MAAaC,GAAoB,EAAmC,IAA4C,CAC9G,IAAM,EAAS,GAAS,QAAU,GAAqB,CACjD,EAAa,IAAI,EAAmB,EAAQ,GAAS,QAAU,EAAE,CAAC,CAOxE,OAAO,IAAI,EANI,IAAI,EACjB,cACA,EACA,CAAE,SAAQ,WAAY,CAAE,QAAS,GAAS,QAAS,CAAE,CACrD,CAAE,UAAW,EAAY,UAAW,EAAqB,CAC1D,CACqC,EAAW,EC3GtC,EAAoB,GACxB,EAAuB,CAAE,QAAS,aAAc,WAAY,QAAe,CAAE,EAAQ,CAWjF,EAA2B,GAAyC,CAC/E,IAAM,EAAW,WAAW,6BAE5B,MADA,YAAW,6BAA+B,EAAW,WACxC,CACX,WAAW,6BAA+B"}
@@ -0,0 +1,292 @@
1
+ //#region ../shared/src/types.d.ts
2
+ declare const ConfigTypeList: readonly ["custom", "boolean", "string", "integer", "float", "enum", "url", "json"];
3
+ type ConfigType = (typeof ConfigTypeList)[number];
4
+ type ConfigEnumLikeType = {
5
+ [key: string]: string | number;
6
+ };
7
+ type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
8
+ type ConfigState = {
9
+ id: string;
10
+ key: string;
11
+ type: ConfigType;
12
+ value: string | undefined | null;
13
+ valueId?: string | undefined | null;
14
+ };
15
+ type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
16
+ interface ConfigDirectorLogger {
17
+ debug(message: string, ...args: any): void;
18
+ info(message: string, ...args: any): void;
19
+ warn(message: string, ...args: any): void;
20
+ error(message: string, ...args: any): void;
21
+ }
22
+ interface ConfigDirectorLogMessageDecorator {
23
+ decorateMessage(message: string): string;
24
+ }
25
+ type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
26
+ type ConfigEvaluation = {
27
+ key: string;
28
+ value: ConfigValueType;
29
+ valueId?: string;
30
+ isDefaultValue: boolean;
31
+ reason: EvaluationReason;
32
+ context?: ConfigDirectorContext;
33
+ };
34
+ /**
35
+ * The user's context to be sent to ConfigDirector. This context will be used for targeting
36
+ * rules evaluation.
37
+ */
38
+ type ConfigDirectorContext = {
39
+ /**
40
+ * The user's identifier. This should be a value that uniquely identifies an application
41
+ * user.
42
+ * In the case of anonymous users, you could generate a UUID or alternatively not provide
43
+ * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
44
+ * value is used for segmenting users in percentage rollouts, and changes to the {@link id}
45
+ * could result in the user being assigned to a different percentile.
46
+ */
47
+ id?: string;
48
+ /**
49
+ * The user's display name. This will be shown in the ConfigDirector dashboard and may be
50
+ * used for targeting rules.
51
+ */
52
+ name?: string;
53
+ /**
54
+ * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
55
+ * dashboard and may be used for targeting rules.
56
+ */
57
+ traits?: {
58
+ [key: string]: unknown;
59
+ };
60
+ /**
61
+ * Whether or not to treat the context as anonymous during evaluation. When `true`, the
62
+ * context values will be used for targeting rules evaluation but the context will not be
63
+ * persisted and will not appear in the dashboard.
64
+ *
65
+ * @default false
66
+ */
67
+ anonymous?: boolean;
68
+ };
69
+ /**
70
+ * Metadata about your application. It is recommended you include these values when configuring
71
+ * a ConfigDirector client so that you can use them in targeting rules.
72
+ */
73
+ type ConfigDirectorMetaContext = {
74
+ appVersion?: string;
75
+ appName?: string;
76
+ };
77
+ type ConnectionMode = "streaming" | "polling";
78
+ //#endregion
79
+ //#region ../js-server-sdk/src/types.d.ts
80
+ /**
81
+ * Configuration options for the {@link ConfigDirectorClient}
82
+ */
83
+ type ConfigDirectorClientOptions = {
84
+ /**
85
+ * Application metadata that remains constant through the lifetime of the connection
86
+ */
87
+ metadata?: ConfigDirectorMetaContext;
88
+ /**
89
+ * Connection options
90
+ */
91
+ connection?: {
92
+ /**
93
+ * The connection mode to be used, one of `streaming` (default) or `polling`.
94
+ * If set to `streaming`, the connection will remain open and receive updates whenever
95
+ * config state is updated on the ConfigDirector dashboard.
96
+ * When set to `polling`, there will be an initial request to retrieve config state during
97
+ * initialization, and additional requests on a `pollingInterval`.
98
+ *
99
+ * Defaults to `streaming`
100
+ */
101
+ mode?: ConnectionMode;
102
+ /**
103
+ * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
104
+ * effect when the `mode` is set to `streaming`.
105
+ *
106
+ * Defaults to 300 seconds (5 minutes). The minimum is 60 seconds. A value below the minimum is
107
+ * raised to the minimum and a warning is logged.
108
+ */
109
+ pollingInterval?: number;
110
+ /**
111
+ * The timeout, in milliseconds, to be used in initialization and when updating the context.
112
+ * If streaming is enabled, the operation (initialization or context update) may still succeed
113
+ * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
114
+ * If streaming is disabled, if the operation times out, it will not be retried.
115
+ *
116
+ * Defaults to 3,000 milliseconds (3 seconds)
117
+ */
118
+ timeout?: number;
119
+ /**
120
+ * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
121
+ * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
122
+ * a proxy for the client SDK.
123
+ */
124
+ url?: string;
125
+ };
126
+ /**
127
+ * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
128
+ * logger set to 'warn' level.
129
+ *
130
+ * The log level of the default logger can be adjusted by creating a default logger with the desired
131
+ * level and providing it in this property:
132
+ * @example
133
+ * import { createClient, createConsoleLogger } from "@configdirector/server-sdk";
134
+ * const client = createClient(
135
+ * "YOUR-SERVER-SDK-KEY",
136
+ * { logger: createConsoleLogger("debug") },
137
+ * );
138
+ */
139
+ logger?: ConfigDirectorLogger;
140
+ /**
141
+ * Telemetry tunning. It is unlikely these settings need to be adjusted. However, in cases where
142
+ * your application has a large number of evaluations per second, you can adjust these settings
143
+ * to tune the memory footprint and frequency of telemetry requests.
144
+ * Keep in mind that ConfigDirector relies on these telemetry events to provide insights and features
145
+ * related to the configs being used.
146
+ */
147
+ telemetry?: {
148
+ /**
149
+ * The size limit of telemetry event queues. If the size limit is reached before the events are
150
+ * flushed to the network, older events will be dropped.
151
+ *
152
+ * ConfigDirector keeps a count of dropped events. If the number of dropped events is higher than
153
+ * 50% of the total events, ConfigDirector will issue a notification alert in the dashboard.
154
+ *
155
+ * A number between 100 and 100,000. Defaults to 5,000.
156
+ */
157
+ eventQueueLimit?: number;
158
+ /**
159
+ * How often events are flushed and sent over the network in milliseconds.
160
+ *
161
+ * Decrease this number if your application consistently captures a large number of events in short
162
+ * periods of time in order to reduce memory footprint from a large event queue.
163
+ *
164
+ * Defaults to 30,000 milliseconds (30 seconds)
165
+ */
166
+ flushInterval?: number;
167
+ };
168
+ /**
169
+ * Handlers for hooks/events emitted by the client. Each hook accepts either a single event handler or
170
+ * an array of event handlers.
171
+ *
172
+ * @example
173
+ * import { createClient, createConsoleLogger } from "@configdirector/server-sdk";
174
+ * const client = createClient(
175
+ * "YOUR-SERVER-SDK-KEY",
176
+ * {
177
+ * hooks: {
178
+ * configEvaluated: (event) => { console.log(event.evaluation); }
179
+ * },
180
+ * },
181
+ * );
182
+ */
183
+ hooks?: ClientHooks;
184
+ };
185
+ type ClientEvents = {
186
+ configsUpdated: {
187
+ keys: string[];
188
+ removedKeys: string[];
189
+ };
190
+ clientReady: undefined;
191
+ configEvaluated: {
192
+ evaluation: ConfigEvaluation;
193
+ };
194
+ connectionError: {
195
+ error: Error;
196
+ };
197
+ };
198
+ type ClientHooks = {
199
+ clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
200
+ configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
201
+ configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
202
+ connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
203
+ };
204
+ type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
205
+ type WatchHandler<T extends ConfigValueType> = (message: T) => void;
206
+ /**
207
+ * The ConfigDirector SDK client object.
208
+ *
209
+ * Applications should create a single instance of `ConfigDirectorClient`, and call
210
+ * {@link initialize} during application initialization.
211
+ */
212
+ interface ConfigDirectorClient {
213
+ /**
214
+ * Initializes the connection to ConfigDirector to retrieve config definitions. Until
215
+ * initialization is successful, all flags will return their default value provided to
216
+ * {@link watch} or {@link getValue}.
217
+ *
218
+ * If the connection fails or is interrupted with a transient error (network error,
219
+ * internal server error, etc) the client will continue to attempt to connect. However,
220
+ * if the connection fails with a persistent error, like an invalid SDK key, the client will
221
+ * not attempt to re-connect and an error will be logged to the console or the provided
222
+ * logger.
223
+ */
224
+ initialize(): Promise<void>;
225
+ /**
226
+ * Returns whether or not the client is ready after calling {@link initialize}
227
+ *
228
+ * The definition of ready is that the connection to the server was successful, and config definitions
229
+ * were received.
230
+ */
231
+ get isReady(): boolean;
232
+ /**
233
+ * Evaluates a config and returns its value based on the current context and targeting rules
234
+ *
235
+ * @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
236
+ * @param configKey The config key to evaluate
237
+ * @param defaultValue The default value to be returned if the config state is unavailable. For
238
+ * example, if the client cannot connect to the server due to network conditions, or if getValue
239
+ * is called before initialization is done.
240
+ * @param context The user's context to be used for targeting rules evaluation (optional)
241
+ */
242
+ getValue<T extends ConfigValueType>(configKey: string, defaultValue: T, context?: ConfigDirectorContext): T;
243
+ /**
244
+ * Watches for changes to a a config evaluation value. Whenever the config value changes, the
245
+ * provided callback function will be called with the new value. Changes can happen due to updates
246
+ * to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
247
+ *
248
+ * @returns An 'unwatch' function that can be called to remove the subscriber
249
+ *
250
+ * @param configKey The config key to watch
251
+ * @param defaultValue The default value to be referenced if the config state is unavailable
252
+ * @param callback The callback function to be called whenever the config value is updated
253
+ * @param context The user's context to be used for targeting rules evaluation (optional)
254
+ */
255
+ watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>, context?: ConfigDirectorContext): () => void;
256
+ /**
257
+ * Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
258
+ * is provided.
259
+ *
260
+ * @param configKey The config key to remove subscribers from
261
+ * @param callback The subscriber to be removed. If not provided, all subscribers are removed for
262
+ * the given `configKey`.
263
+ */
264
+ unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
265
+ /**
266
+ * Removes all subscribers from all config keys
267
+ */
268
+ unwatchAll(): void;
269
+ /**
270
+ * Returns the evaluated {@link ConfigState} for every known config key, or only the keys
271
+ * listed in `configKeys` when provided.
272
+ *
273
+ * Intended for SSR hydration — does NOT record telemetry events. Returns an empty object
274
+ * when the client is not yet ready.
275
+ */
276
+ getAllConfigs(options?: {
277
+ context?: ConfigDirectorContext;
278
+ configKeys?: string[];
279
+ }): Record<string, ConfigState>;
280
+ on<T extends keyof ClientEvents>(eventName: T, handler: (args: ClientEvents[T]) => void): void;
281
+ off<T extends keyof ClientEvents>(eventName: T, handler?: (args: ClientEvents[T]) => void): void;
282
+ /**
283
+ * Disposes of the client. All connections are closed, and all event and config key subscribers
284
+ * are removed.
285
+ *
286
+ * Intended to be called when your application shuts down
287
+ */
288
+ dispose(): void;
289
+ }
290
+ //#endregion
291
+ export { ConfigDirectorLogger as a, ConfigEvaluation as c, ConnectionMode as d, ConfigDirectorLogMessageDecorator as i, ConfigState as l, ConfigDirectorClientOptions as n, ConfigDirectorLoggingLevel as o, ConfigDirectorContext as r, ConfigDirectorMetaContext as s, ConfigDirectorClient as t, ConfigValueType as u };
292
+ //# sourceMappingURL=types-DnzM2ukj.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-DnzM2ukj.d.cts","names":[],"sources":["../../../shared/src/types.ts","../../../js-server-sdk/src/types.ts"],"mappings":";cAAa,cAAA;AAAA,KAUD,UAAA,WAAqB,cAAA;AAAA,KAErB,kBAAA;EAAA,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