@configdirector/nextjs-sdk 1.7.0 → 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.
- package/README.md +41 -0
- package/dist/client/index.cjs +1 -5
- package/dist/client/index.d.cts +52 -216
- package/dist/client/index.d.cts.map +1 -1
- package/dist/client/index.d.mts +52 -216
- package/dist/client/index.d.mts.map +1 -1
- package/dist/client/index.mjs +1 -5
- package/dist/client/index.mjs.map +1 -1
- package/dist/client/installedTestClient-CrHwnJTr.mjs +7 -0
- package/dist/client/installedTestClient-CrHwnJTr.mjs.map +1 -0
- package/dist/client/installedTestClient-LbS5fHdP.cjs +6 -0
- package/dist/client/testing.cjs +2 -0
- package/dist/client/testing.d.cts +159 -0
- package/dist/client/testing.d.cts.map +1 -0
- package/dist/client/testing.d.mts +159 -0
- package/dist/client/testing.d.mts.map +1 -0
- package/dist/client/testing.mjs +3 -0
- package/dist/client/testing.mjs.map +1 -0
- package/dist/client/types-DA2VZKNX.d.mts +220 -0
- package/dist/client/types-DA2VZKNX.d.mts.map +1 -0
- package/dist/client/types-fL7X5zwg.d.cts +220 -0
- package/dist/client/types-fL7X5zwg.d.cts.map +1 -0
- package/dist/server/DefaultConfigDirectorClient-BhyVJv6Z.mjs +6 -0
- package/dist/server/DefaultConfigDirectorClient-BhyVJv6Z.mjs.map +1 -0
- package/dist/server/DefaultConfigDirectorClient-BngKzHat.cjs +5 -0
- package/dist/server/{errors-B1AJJTZ-.mjs → errors-BGpFuqOO.mjs} +1 -1
- package/dist/server/{errors-B1AJJTZ-.mjs.map → errors-BGpFuqOO.mjs.map} +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +14 -288
- package/dist/server/index.d.cts.map +1 -1
- package/dist/server/index.d.mts +14 -288
- package/dist/server/index.d.mts.map +1 -1
- package/dist/server/index.mjs +1 -1
- package/dist/server/index.mjs.map +1 -1
- package/dist/server/testing.cjs +1 -0
- package/dist/server/testing.d.cts +119 -0
- package/dist/server/testing.d.cts.map +1 -0
- package/dist/server/testing.d.mts +119 -0
- package/dist/server/testing.d.mts.map +1 -0
- package/dist/server/testing.mjs +2 -0
- package/dist/server/testing.mjs.map +1 -0
- package/dist/server/types-DnzM2ukj.d.cts +292 -0
- package/dist/server/types-DnzM2ukj.d.cts.map +1 -0
- package/dist/server/types-qIeNbtNf.d.mts +292 -0
- package/dist/server/types-qIeNbtNf.d.mts.map +1 -0
- package/package.json +37 -2
- package/dist/server/DefaultConfigDirectorClient-C3kQeXox.cjs +0 -5
- package/dist/server/DefaultConfigDirectorClient-D7A_CT1K.mjs +0 -6
- package/dist/server/DefaultConfigDirectorClient-D7A_CT1K.mjs.map +0 -1
- /package/dist/server/{errors-zhcEWVnY.cjs → errors-CCbuIqT8.cjs} +0 -0
package/README.md
CHANGED
|
@@ -30,6 +30,47 @@ const { value: darkMode } = useConfigValue("dark-mode", false);
|
|
|
30
30
|
|
|
31
31
|
Full details are in the [official documentation](https://docs.configdirector.com/sdks/meta/nextjs).
|
|
32
32
|
|
|
33
|
+
## Test your code
|
|
34
|
+
|
|
35
|
+
The `/client/testing` and `/server/testing` entry points create real clients connected to an in-memory
|
|
36
|
+
server that your test controls, so components and server code run against the production SDK without
|
|
37
|
+
opening a network connection or sending telemetry.
|
|
38
|
+
|
|
39
|
+
```tsx
|
|
40
|
+
// Client Components: render the production provider with its client prop, or install the test client
|
|
41
|
+
import { act, render, screen } from "@testing-library/react";
|
|
42
|
+
import { ConfigDirectorProvider } from "@configdirector/nextjs-sdk/client";
|
|
43
|
+
import { createTestClient, installTestClient } from "@configdirector/nextjs-sdk/client/testing";
|
|
44
|
+
|
|
45
|
+
const testClient = createTestClient({ values: { "dark-mode": true } });
|
|
46
|
+
render(
|
|
47
|
+
<ConfigDirectorProvider client={testClient.client}>
|
|
48
|
+
<Page />
|
|
49
|
+
</ConfigDirectorProvider>,
|
|
50
|
+
);
|
|
51
|
+
act(() => testClient.setValue("dark-mode", false));
|
|
52
|
+
|
|
53
|
+
const uninstall = installTestClient(testClient);
|
|
54
|
+
render(<AppWithItsOwnProvider />);
|
|
55
|
+
uninstall();
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
// Server code: install a server test client where register() would have put the singleton
|
|
60
|
+
import { createTestClient, installServerTestClient } from "@configdirector/nextjs-sdk/server/testing";
|
|
61
|
+
import { getConfigClient } from "@configdirector/nextjs-sdk/server";
|
|
62
|
+
|
|
63
|
+
const serverTestClient = createTestClient({ values: { "dark-mode": true } });
|
|
64
|
+
const uninstall = installServerTestClient(serverTestClient);
|
|
65
|
+
await serverTestClient.client.initialize();
|
|
66
|
+
getConfigClient().getValue("dark-mode", false, { id: "user-1" }); // true
|
|
67
|
+
uninstall();
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
A provider given a client reports it on the first render, never disposes it, removes its handlers when
|
|
71
|
+
it unmounts, and does not initialize a client that is ready or initializing. `installServerTestClient`
|
|
72
|
+
does not initialize the client; the test calls `initialize`, as `register()` would.
|
|
73
|
+
|
|
33
74
|
## Documentation
|
|
34
75
|
|
|
35
76
|
Refer to the [official documentation for the Next.js SDK](https://docs.configdirector.com/sdks/meta/nextjs).
|
package/dist/client/index.cjs
CHANGED
|
@@ -1,6 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`react`);c=s(c);let l=require(`react/jsx-runtime`);var u=class{constructor(){this.handlerMap=new Map}on(e,t){let n=this.handlerMap.get(e);n?n.push(t):this.handlerMap.set(e,[t])}once(e,t){let n=this;function r(i){n.off(e,r),t.apply(n,i)}this.on(e,r)}off(e,t){let n=this.handlerMap.get(e);if(n)if(t){let e=n.indexOf(t);e>=0&&n.splice(e,1)}else this.handlerMap.set(e,[])}clear(){this.handlerMap.clear()}emit(e,t){let n=this.handlerMap.get(e);n&&n.slice().map(e=>e(t))}},d=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},f=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},p=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},m=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},h=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},ee=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},te=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
3
|
-
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
4
|
-
`&&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(`
|
|
5
|
-
`)?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+`
|
|
6
|
-
`;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 g=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var _=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=g.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={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===g.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=g.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=g.CONNECTING,this._fetch(this.url,{...this.requestOptions,body:this.body(),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 m(`The server response did not have a body`);this._readyState=g.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new te({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 p(`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=g.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=g.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new ee(`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 h(`${n} must be a function`);return e}};const v=e=>new _(e);var y=class{constructor(e){this.options=e,this.eventEmitter=new u,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){this.eventSource&&this.close();let n=new Promise((t,n)=>{this.eventSource=v({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:this.options.fetch,body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:this.options.instanceId}),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),t(this)},shouldReconnect:e=>{let t=!this.isStatusFatal(e.status);if(!t){let t=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,t),n(t)}return t},calculateReconnectDelay:e=>{let t=this.options.connectionRetryDelay(e.attempt),n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onError:e=>{this.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});return clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,Promise.race([n,new Promise(e=>{this.timeoutTimer=setTimeout(()=>e(this),t)})]).finally(()=>clearTimeout(this.timeoutTimer))}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let n=e??0;return new d(`${`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&&e!=429}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){this.eventSource?.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const b=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},x=e=>e===`number`||e===`bigint`,S=new Set([`boolean`,`integer`,`float`]),C=(e,t)=>{let n=e.value,r=b(t);if(n==null)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return re(n,t,r,e.valueId);if(typeof t==`string`)return S.has(e.type)?{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}:{parsedValue:n,parsedValueId:e.valueId,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&(e.type===`boolean`||e.type===`string`||e.type===`enum`)){let i=w(n),a=typeof i==`boolean`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-boolean`}}if(x(typeof t)&&e.type===`integer`){let i=T(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(x(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=E(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},w=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},T=e=>{let t=D(e);return t==null?void 0:Math.trunc(t)},E=e=>D(e),D=e=>{if(!e||!ne(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},ne=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},re=(e,t,n,r)=>{if(typeof t==`string`)return{parsedValue:e,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`};try{let i=JSON.parse(e);return ie(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch{return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},ie=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},O={off:-1,error:0,warn:1,info:2,debug:3},k=()=>{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 A=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=k()}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){O[this.level]>=O[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},j=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const M=(e,t)=>new A(e??`warn`,t??new j),N=(e,t)=>new URL(e,t?.toString()),P=e=>{if(e)try{return new URL(e)}catch(t){throw new f(`Invalid URL '${e}'. Parsing failed: ${t}`)}},F=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),I=`configdirector-sdk:instance-id`,L=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,R=(e,t)=>{let n=t;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0},z=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=R(n,2166136261);return R(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},B=()=>{try{return globalThis.localStorage??void 0}catch{return}},V=e=>{if(!e||typeof e!=`object`)return!1;let{v:t,id:n,createdAt:r,checksum:i}=e;return t!==1||typeof n!=`string`||typeof i!=`string`||typeof r!=`number`||!Number.isInteger(r)||r<=0||!L.test(n)?!1:i===z(n,r)},H=(e,t)=>{let n;try{n=e.getItem(I)}catch(e){t?.debug(`[ConfigDirectorClient] Could not read the stored instance id, generating a new one`,e);return}if(!n)return;let r;try{r=JSON.parse(n)}catch{t?.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`);return}if(!V(r)){t?.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`);return}let i=Date.now()-r.createdAt;if(i<0||i>=216e5){t?.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`);return}return r.id},U=(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:z(t,r)};try{e.setItem(I,JSON.stringify(i))}catch(e){n?.debug(`[ConfigDirectorClient] Could not persist the instance id`,e)}},W=e=>{let t=B();if(!t)return F();let n=H(t,e);if(n)return n;let r=F();return U(t,r,e),r};var G=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.close(),this.prepareFatalResponseStatusError(e.status,await e.text())):new d(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new d(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new d(`Failed to parse the response from the server: ${e}`):new d(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new d(`${`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&&e!=429}isFetchErrorFatal(e){return e?.name===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const K=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 ae=class extends G{constructor(e){super(),this.options=e,this.eventEmitter=new u,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/polling/v1`,e.baseUrl);let t=e.pollingInterval??300;t<60&&this.logger.warn(`[PollingTransport] pollingInterval of ${t} seconds is below the minimum of 60 seconds. Using 60 seconds.`),this.pollingIntervalSeconds=Math.max(t,60)}async connect(e,t){this.clearPollingInterval();try{await this.fetchConfigs(e,t)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e,t).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}async fetchConfigs(e,t){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let n=await K(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:this.options.instanceId,lastUpdateTimestamp:this.lastUpdateTimestamp})},this.logger);if(await this.handleNonOkResponse(n),n.status==200){let e=JSON.parse(await n.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{this.handleFetchError(e)}catch(e){throw this.fatalError&&this.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}};const q=e=>{try{return e(globalThis)}catch{return}},J=()=>q(e=>e.navigator?.userAgent),oe=()=>q(e=>e.location?.host);var se=class{constructor(e,t,n,r,i){this.handlersMap=new Map,this.eventEmitter=new u,this.ready=!1,this.initializing=!1,this.logger=r?.logger??M(),this.instanceId=W(this.logger),this.timeout=r?.connection?.timeout??3e3,this.validateSdkKeyPresence(t);let a=i?.urlFactory??N,o=this.parseUrl(r?.connection?.url,a)??`https://client-sdk-api.configdirector.com`;this.connectionMode=r?.connection?.mode??`streaming`;let s=this.getTransportConstructor(this.connectionMode);this.telemetryClient=e,this.transport=new s({instanceId:this.instanceId,clientSdkKey:t,baseUrl:o,resolveUrl:a,metaContext:{...r?.metadata,sdkName:n.sdkName,sdkVersion:n.sdkVersion,userAgent:J(),host:oe()},logger:this.logger,fetch:i?.fetch,connectionRetryDelay:i?.connectionRetryDelay??(e=>2**Math.min(e,9)*1e3),pollingInterval:r?.connection?.pollingInterval}),this.transport.on(`configSetReceived`,e=>{this.readyResolve?.();let t=Object.keys(e.configs);!this.configSet||e.kind==`full`?(this.configSet=e,this.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)):(this.configSet.configs={...this.configSet.configs,...e.configs},this.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:t})}),this.transport.on(`connectionError`,e=>{this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,r?.hooks?.clientReady),this.registerHandler(`configEvaluated`,r?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,r?.hooks?.configsUpdated),this.registerHandler(`contextUpdated`,r?.hooks?.contextUpdated),this.registerHandler(`connectionError`,r?.hooks?.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}getTransportConstructor(e){switch(e){case`polling`:return ae;default:return y}}async initialize(e){this.initializing=!0,await this.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}get context(){return this.currentContext}async connectToTransport(e,t){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.initializing=!1,this.emit(`clientReady`,{action:t}),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let n=new Date().getTime();await this.transport.connect(e??{},this.timeout),this.currentContext=e,this.telemetryClient.updateContext(e),this.emit(`contextUpdated`,{context:e});let r=new Date().getTime()-n,i=this.timeout-r;clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,i>0&&await Promise.race([this.readyPromise,new Promise(e=>{this.timeoutTimer=setTimeout(()=>e(),i)})]).finally(()=>clearTimeout(this.timeoutTimer)),this.ready||this.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${this.timeout}ms. The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`)}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}updateWatchers(e){Object.values(e).forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){this.handlersMap.get(e.key)?.forEach(t=>{let n=this.getValueFromConfigState(e.key,e,t.defaultValue);t.handler(n)})}watch(e,t,n){this.validateDefaultValue(t);let r=this.handlersMap.get(e),i={handler:n,defaultValue:t,requestedType:typeof t};return r?r.push(i):this.handlersMap.set(e,[i]),()=>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){this.validateDefaultValue(t);let n=this.configSet?.configs[e];return this.getValueFromConfigState(e,n,t)}getValueFromConfigState(e,t,n){if(!t){this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:b(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let r=C(t,n);return this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,type:t.type,key:e,defaultValue:n,requestedType:r.requestedType,evaluatedValue:r.parsedValue,evaluatedValueId:r.parsedValueId,usedDefault:r.usedDefault,evaluationReason:r.reason}),this.dispatchEvaluationEvent({key:e,value:r.parsedValue,valueId:r.parsedValueId??void 0,isDefaultValue:r.usedDefault,reason:r.reason,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),r.parsedValue}dispatchEvaluationEvent(e){setTimeout(()=>this.emit(`configEvaluated`,{evaluation:e}),0)}emit(e,t){try{this.eventEmitter.emit(e,t)}catch(t){this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${e}'`,t)}}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new f(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new f(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new f(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new f(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}get isInitializing(){return this.initializing}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}pauseNetwork(){this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1}async resumeNetwork(){await this.connectToTransport(this.currentContext,`network resume`)}async close(){this.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(this.timeoutTimer),this.readyResolve?.(!0),this.telemetryClient.close(),this.transport.close(),this.ready=!1,this.initializing=!1}dispose(){this.clear(),this.close()}};const Y=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}};var ce=class{constructor(e){this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3;let t={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:e.evaluationQueueLimit??1e3,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}};this.worker=new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=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},n=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},r=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}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},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){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=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}))}},s=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||=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}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4;let t=e.initialFlushIntervalDelay??5e3;this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),t)}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class extends c{constructor(e){super(e),this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let d=(e,t)=>new URL(e,t?.toString()),f=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},p=Math.ceil(128/Math.log2(62)),m=new TextEncoder,h=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,m.encode(e?.toString()??``));return f(new Uint8Array(t,0,16),p)},g,_=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),v=e=>{try{self.postMessage(e)}catch{self.postMessage(_(e.payload.level,e.payload.message))}},y={debug:function(e,...t){v(_(`debug`,e,t))},info:function(e,...t){v(_(`info`,e,t))},warn:function(e,...t){v(_(`warn`,e,t))},error:function(e,...t){v(_(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!g){y.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(y.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(g){y.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}g=new u({...t.payload,baseUrl:d(t.payload.baseUrl),urlFactory:d,valueIdGenerator:h,logger:y});break;case`EvaluatedConfigEvent`:g?.evaluatedConfig(t.payload);break;case`UpdateContext`:g?.updateContext(t.payload.context);break;case`Flush`:g?.forceFlush();break;case`Close`:(g?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`}))),this.worker.onmessage=e=>{this.handleWorkerEvent(e.data)},this.worker.postMessage(t),this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()};try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}}async updateContext(e){let t={type:`UpdateContext`,payload:{context:e}};this.worker.postMessage(t)}evaluatedConfig(e){let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};this.worker.postMessage(t)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:Y({value:e.defaultValue,type:e.type}),evaluatedValue:Y({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(e=>{this.closeResolve=e,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),this.worker.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker.terminate(),this.closeResolve?.()}};const le=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},ue=Math.ceil(128/Math.log2(62)),de=new TextEncoder,fe=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,de.encode(e?.toString()??``));return le(new Uint8Array(t,0,16),ue)},pe=(e,t,n)=>{let r=n?.logger??M(),i=P(n?.connection?.url)??`https://client-sdk-api.configdirector.com`;return new se(new ce({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:n?.metadata?.appName,appVersion:n?.metadata?.appVersion},logger:r,baseUrl:i,urlFactory:N,valueIdGenerator:fe}),e,t,{...n,logger:r})},X=c.default.createContext({status:`loading`});var me=class{decorateMessage(e){return`[ConfigDirector:nextjs-sdk] ${e}`}};const Z=e=>M(e,new me);var he=class extends c.Component{constructor(e){super(e),this.state={status:`loading`}}buildClient(){return pe(this.props.sdkKey,{sdkName:`nextjs-sdk`,sdkVersion:`1.7.0`},{connection:{url:this.props.url,timeout:this.props.timeout},metadata:{appName:this.props.appName,appVersion:this.props.appVersion},logger:Z(this.props.logLevel??`warn`),hooks:this.props.hooks})}async componentDidMount(){let e=this.buildClient();this.client=e,e.on(`configsUpdated`,()=>{this.setState({updatedAt:new Date})}),e.on(`clientReady`,()=>{this.setState({status:`ready`})}),this.setState({client:e}),await e.initialize(this.props.context),this.client===e&&!e.isReady&&this.setState({status:`default`})}async componentDidUpdate(e){if(e.context!==this.props.context){let e=this.client;if(!e)return;this.setState({status:`loading`}),await e.updateContext(this.props.context??{}),this.client===e&&!e.isReady&&this.setState({status:`default`})}}componentWillUnmount(){this.client?.dispose(),this.client=void 0}render(){return(0,l.jsx)(X.Provider,{value:{...this.state,initialConfigs:this.props.initialConfigs},children:this.props.children})}},Q=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorNextContextError`,Object.setPrototypeOf(this,e.prototype)}};const $=()=>new Q(`The ConfigDirector client was not found in the React context. Make sure the component using this hook is inside a <ConfigDirectorProvider>.`),ge=(e,t)=>{let n=(0,c.useContext)(X);if(!n)throw $();let r=n.initialConfigs?.[e];return{value:n.client?.isReady?n.client.getValue(e,t):r?C(r,t).parsedValue:t,readyStatus:n.status,loading:n.status===`loading`}},_e=()=>{let e=(0,c.useContext)(X);if(!e)throw $();return{updateContext:async t=>{await e.client?.updateContext(t)}}},ve=()=>{let e=(0,c.useContext)(X);if(!e?.client)throw $();return{client:e.client}},ye=()=>{let e=(0,c.useContext)(X);if(!e)throw $();return{readyStatus:e.status,loading:e.status===`loading`}};exports.ConfigDirectorNextContextError=Q,exports.ConfigDirectorProvider=he,exports.createConsoleLogger=Z,exports.useClient=ve,exports.useConfigDirectorStatus=ye,exports.useConfigValue=ge,exports.useContext=_e;
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require(`./installedTestClient-LbS5fHdP.cjs`);let l=require(`react`);l=s(l);let u=require(`react/jsx-runtime`);const d=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}};var f=class{constructor(e){this.pendingEvaluations=[],this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}startWorker(){if(this.worker)return this.worker;let e=new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=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},n=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},r=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}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},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){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=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}))}},s=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||=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}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class extends c{constructor(e){super(e),this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let d=(e,t)=>new URL(e,t?.toString()),f=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},p=Math.ceil(128/Math.log2(62)),m=new TextEncoder,h=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,m.encode(e?.toString()??``));return f(new Uint8Array(t,0,16),p)},g,_=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),v=e=>{try{self.postMessage(e)}catch{self.postMessage(_(e.payload.level,e.payload.message))}},y={debug:function(e,...t){v(_(`debug`,e,t))},info:function(e,...t){v(_(`info`,e,t))},warn:function(e,...t){v(_(`warn`,e,t))},error:function(e,...t){v(_(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!g){y.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(y.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(g){y.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}g=new u({...t.payload,baseUrl:d(t.payload.baseUrl),urlFactory:d,valueIdGenerator:h,logger:y}),g.start();break;case`EvaluatedConfigEvent`:g?.evaluatedConfig(t.payload);break;case`UpdateContext`:g?.updateContext(t.payload.context);break;case`Flush`:g?.forceFlush();break;case`Close`:(g?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})));e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,e}async updateContext(e){if(this.closePromise)return;let t={type:`UpdateContext`,payload:{context:e}};this.startWorker().postMessage(t)}evaluatedConfig(e){let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:d({value:e.defaultValue,type:e.type}),evaluatedValue:d({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}};const p=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},m=Math.ceil(128/Math.log2(62)),h=new TextEncoder,g=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,h.encode(e?.toString()??``));return p(new Uint8Array(t,0,16),m)},_=(e,t,n)=>{let r=n?.logger??c.s(),i=c.o(n?.connection?.url)??`https://client-sdk-api.configdirector.com`;return new c.r(new f({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:n?.metadata?.appName,appVersion:n?.metadata?.appVersion},logger:r,baseUrl:i,urlFactory:c.a,valueIdGenerator:g}),e,t,{...n,logger:r})};var v=class{constructor(e){this.client=e,this.registrations=[]}on(e,t){this.client.on(e,t),this.registrations.push({event:e,handler:t})}registerHooks(e){for(let[t,n]of Object.entries(e??{})){let e=Array.isArray(n)?n:[n];for(let n of e)typeof n==`function`&&this.on(t,n)}}removeAll(){for(let{event:e,handler:t}of this.registrations)this.client.off(e,t);this.registrations=[]}};const y=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>y(e,t[n]));if(!b(e)||!b(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&y(e[n],t[n]))},b=e=>{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},x=(e,t)=>e.isInitializing?`none`:e.isReady?t!==void 0&&!y(t,e.context)?`updateContext`:`none`:`initialize`,S=l.default.createContext({status:`loading`});var C=class{decorateMessage(e){return`[ConfigDirector:nextjs-sdk] ${e}`}};const w=e=>c.s(e,new C),T=e=>`client`in e&&e.client!==void 0;var E=class extends l.Component{constructor(e){super(e);let t=T(e)?e.client:c.n();this.ownsClient=t===void 0,this.client=t,this.state=t?{client:t,status:t.isReady?`ready`:`loading`}:{status:`loading`}}buildClient(){let e=this.props;return _(e.sdkKey,{sdkName:`nextjs-sdk`,sdkVersion:`1.8.0`},{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval},metadata:{appName:e.appName,appVersion:e.appVersion},logger:w(e.logLevel??`warn`),hooks:e.hooks})}async componentDidMount(){let e=this.client;this.ownsClient&&(e=this.buildClient(),this.client=e,this.setState({client:e})),e&&(this.handlers=new v(e),this.handlers.on(`configsUpdated`,()=>{this.setState({updatedAt:new Date})}),this.handlers.on(`clientReady`,()=>{this.setState({status:`ready`})}),this.ownsClient||this.handlers.registerHooks(this.props.hooks),await this.connect(e,this.props.context))}async connect(e,t){switch(x(e,t)){case`initialize`:await e.initialize(t);break;case`updateContext`:this.setState({status:`loading`}),await e.updateContext(t);break;case`none`:return}this.client===e&&!e.isReady&&this.setState({status:`default`})}async componentDidUpdate(e){if(T(e)&&T(this.props)&&e.client!==this.props.client&&w(`warn`).warn(`The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.`),!y(e.context,this.props.context)){let e=this.client;if(!e)return;this.setState({status:`loading`}),await e.updateContext(this.props.context??{}),this.client===e&&!e.isReady&&this.setState({status:`default`})}}componentWillUnmount(){this.handlers?.removeAll(),this.handlers=void 0,this.ownsClient&&this.client?.dispose(),this.client=void 0}render(){return(0,u.jsx)(S.Provider,{value:{...this.state,initialConfigs:this.props.initialConfigs},children:this.props.children})}},D=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorNextContextError`,Object.setPrototypeOf(this,e.prototype)}};const O=()=>new D(`The ConfigDirector client was not found in the React context. Make sure the component using this hook is inside a <ConfigDirectorProvider>.`),k=(e,t)=>{let n=(0,l.useContext)(S);if(!n)throw O();let r=n.initialConfigs?.[e];return{value:n.client?.isReady?n.client.getValue(e,t):r?c.c(r,t).parsedValue:t,readyStatus:n.status,loading:n.status===`loading`}},A=()=>{let e=(0,l.useContext)(S);if(!e)throw O();return{updateContext:async t=>{await e.client?.updateContext(t)}}},j=()=>{let e=(0,l.useContext)(S);if(!e?.client)throw O();return{client:e.client}},M=()=>{let e=(0,l.useContext)(S);if(!e)throw O();return{readyStatus:e.status,loading:e.status===`loading`}};exports.ConfigDirectorNextContextError=D,exports.ConfigDirectorProvider=E,exports.createConsoleLogger=w,exports.useClient=j,exports.useConfigDirectorStatus=M,exports.useConfigValue=k,exports.useContext=A;
|
package/dist/client/index.d.cts
CHANGED
|
@@ -1,219 +1,8 @@
|
|
|
1
1
|
|
|
2
|
+
import { a as ConfigDirectorLoggingLevel, c as ConnectionMode, i as ConfigDirectorLogger, n as ConfigDirectorClient, o as ConfigState, r as ConfigDirectorContext, s as ConfigValueType, t as ClientHooks } from "./types-fL7X5zwg.cjs";
|
|
2
3
|
import * as _$react_jsx_runtime0 from "react/jsx-runtime";
|
|
3
4
|
import { Component, PropsWithChildren } from "react";
|
|
4
5
|
|
|
5
|
-
//#region ../js-client-core/src/Emitter.d.ts
|
|
6
|
-
type EventType = string | symbol;
|
|
7
|
-
type EventsRecord = Record<EventType, any>;
|
|
8
|
-
type Handler<TEventsRecord extends EventsRecord, TKey extends keyof TEventsRecord> = (payload: TEventsRecord[TKey]) => void;
|
|
9
|
-
interface EventProvider<TEventsRecord extends EventsRecord> {
|
|
10
|
-
on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>): void;
|
|
11
|
-
off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>): void;
|
|
12
|
-
clear(): void;
|
|
13
|
-
}
|
|
14
|
-
//#endregion
|
|
15
|
-
//#region ../shared/src/types.d.ts
|
|
16
|
-
declare const ConfigTypeList: readonly ["custom", "boolean", "string", "integer", "float", "enum", "url", "json"];
|
|
17
|
-
type ConfigType = (typeof ConfigTypeList)[number];
|
|
18
|
-
type ConfigEnumLikeType = {
|
|
19
|
-
[key: string]: string | number;
|
|
20
|
-
};
|
|
21
|
-
type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
|
|
22
|
-
type ConfigState = {
|
|
23
|
-
id: string;
|
|
24
|
-
key: string;
|
|
25
|
-
type: ConfigType;
|
|
26
|
-
value: string | undefined | null;
|
|
27
|
-
valueId?: string | undefined | null;
|
|
28
|
-
};
|
|
29
|
-
type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
|
|
30
|
-
interface ConfigDirectorLogger {
|
|
31
|
-
debug(message: string, ...args: any): void;
|
|
32
|
-
info(message: string, ...args: any): void;
|
|
33
|
-
warn(message: string, ...args: any): void;
|
|
34
|
-
error(message: string, ...args: any): void;
|
|
35
|
-
}
|
|
36
|
-
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
|
|
37
|
-
type ConfigEvaluation = {
|
|
38
|
-
key: string;
|
|
39
|
-
value: ConfigValueType;
|
|
40
|
-
valueId?: string;
|
|
41
|
-
isDefaultValue: boolean;
|
|
42
|
-
reason: EvaluationReason;
|
|
43
|
-
context?: ConfigDirectorContext;
|
|
44
|
-
};
|
|
45
|
-
/**
|
|
46
|
-
* The user's context to be sent to ConfigDirector. This context will be used for targeting
|
|
47
|
-
* rules evaluation.
|
|
48
|
-
*/
|
|
49
|
-
type ConfigDirectorContext = {
|
|
50
|
-
/**
|
|
51
|
-
* The user's identifier. This should be a value that uniquely identifies an application
|
|
52
|
-
* user.
|
|
53
|
-
* In the case of anonymous users, you could generate a UUID or alternatively not provide
|
|
54
|
-
* the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
|
|
55
|
-
* value is used for segmenting users in percentage rollouts, and changes to the {@link id}
|
|
56
|
-
* could result in the user being assigned to a different percentile.
|
|
57
|
-
*/
|
|
58
|
-
id?: string;
|
|
59
|
-
/**
|
|
60
|
-
* The user's display name. This will be shown in the ConfigDirector dashboard and may be
|
|
61
|
-
* used for targeting rules.
|
|
62
|
-
*/
|
|
63
|
-
name?: string;
|
|
64
|
-
/**
|
|
65
|
-
* Any arbitrary traits for the current user. They will be shown in the ConfigDirector
|
|
66
|
-
* dashboard and may be used for targeting rules.
|
|
67
|
-
*/
|
|
68
|
-
traits?: {
|
|
69
|
-
[key: string]: unknown;
|
|
70
|
-
};
|
|
71
|
-
/**
|
|
72
|
-
* Whether or not to treat the context as anonymous during evaluation. When `true`, the
|
|
73
|
-
* context values will be used for targeting rules evaluation but the context will not be
|
|
74
|
-
* persisted and will not appear in the dashboard.
|
|
75
|
-
*
|
|
76
|
-
* @default false
|
|
77
|
-
*/
|
|
78
|
-
anonymous?: boolean;
|
|
79
|
-
};
|
|
80
|
-
//#endregion
|
|
81
|
-
//#region ../js-client-core/src/types.d.ts
|
|
82
|
-
type ClientHooks = {
|
|
83
|
-
clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
|
|
84
|
-
configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
|
|
85
|
-
contextUpdated?: HookHandler<"contextUpdated"> | HookHandler<"contextUpdated">[];
|
|
86
|
-
configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
|
|
87
|
-
connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
|
|
88
|
-
};
|
|
89
|
-
type ClientConnectAction = "initialization" | "context update" | "network resume";
|
|
90
|
-
type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
|
|
91
|
-
type ClientEvents = {
|
|
92
|
-
configsUpdated: {
|
|
93
|
-
keys: string[];
|
|
94
|
-
};
|
|
95
|
-
clientReady: {
|
|
96
|
-
action: ClientConnectAction;
|
|
97
|
-
};
|
|
98
|
-
contextUpdated: {
|
|
99
|
-
context: ConfigDirectorContext | undefined;
|
|
100
|
-
};
|
|
101
|
-
configEvaluated: {
|
|
102
|
-
evaluation: ConfigEvaluation;
|
|
103
|
-
};
|
|
104
|
-
connectionError: {
|
|
105
|
-
error: Error;
|
|
106
|
-
};
|
|
107
|
-
};
|
|
108
|
-
type WatchHandler<T extends ConfigValueType> = (message: T) => void;
|
|
109
|
-
/**
|
|
110
|
-
* The ConfigDirector SDK client object.
|
|
111
|
-
*
|
|
112
|
-
* Applications should create a single instance of `ConfigDirectorClient`, and call
|
|
113
|
-
* {@link initialize} during application initialization.
|
|
114
|
-
*
|
|
115
|
-
* After initialization, to update the user's context, so that targeting rules are evaluated
|
|
116
|
-
* with the updated context, call {@link updateContext}.
|
|
117
|
-
*/
|
|
118
|
-
interface ConfigDirectorClient extends EventProvider<ClientEvents> {
|
|
119
|
-
/**
|
|
120
|
-
* Initializes the connection to ConfigDirector to retrieve config evaluations. Until
|
|
121
|
-
* initialization is successful, all flags will return their default value provided to
|
|
122
|
-
* {@link watch} or {@link getValue}.
|
|
123
|
-
*
|
|
124
|
-
* If the connection fails or is interrupted with a transient error (network error,
|
|
125
|
-
* internal server error, etc) the client will continue to attempt to connect. However,
|
|
126
|
-
* if the connection fails with a persistent error, like an invalid SDK key, the client will
|
|
127
|
-
* not attempt to re-connect and an error will be logged to the console or the provided
|
|
128
|
-
* logger.
|
|
129
|
-
*
|
|
130
|
-
* @param context The current user's context to be used for evaluating targeting rules (optional).
|
|
131
|
-
*/
|
|
132
|
-
initialize(context?: ConfigDirectorContext): Promise<void>;
|
|
133
|
-
/**
|
|
134
|
-
* Updates the user's context and re-evaluates all config and flag values based on the new context.
|
|
135
|
-
*
|
|
136
|
-
* @param context The current user's context to be used for evaluating targeting rules (required).
|
|
137
|
-
*/
|
|
138
|
-
updateContext(context: ConfigDirectorContext): Promise<void>;
|
|
139
|
-
/**
|
|
140
|
-
* Returns the current context the client is configured with, or undefined if there is no context.
|
|
141
|
-
*
|
|
142
|
-
* Note that the value returned does not updated immediately after calling {@link updateContext}. Only
|
|
143
|
-
* once the underlying connection was successful or timed out, the current context is updated. This is
|
|
144
|
-
* because while the context update is in progress, configs are still evaluated on the previous context.
|
|
145
|
-
*
|
|
146
|
-
*/
|
|
147
|
-
get context(): ConfigDirectorContext | undefined;
|
|
148
|
-
/**
|
|
149
|
-
* Returns whether or not the client is ready after calling {@link initialize} or {@link updateContext}
|
|
150
|
-
*
|
|
151
|
-
* The definition of ready is that the connection to the server was successful, and config state
|
|
152
|
-
* was received.
|
|
153
|
-
*/
|
|
154
|
-
get isReady(): boolean;
|
|
155
|
-
/**
|
|
156
|
-
* Returns whether or not the client is currently initializing. Upon client creation, it is `false`.
|
|
157
|
-
* It is `true` after calling `initialize` and becomes `false` again once initialization is completed.
|
|
158
|
-
*/
|
|
159
|
-
get isInitializing(): boolean;
|
|
160
|
-
/**
|
|
161
|
-
* Evaluates a config and returns its value based on the current context and targeting rules
|
|
162
|
-
*
|
|
163
|
-
* @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
|
|
164
|
-
* @param configKey The config key to evaluate
|
|
165
|
-
* @param defaultValue The default value to be returned if the config state is unavailable. For
|
|
166
|
-
* example, if the client cannot connect to the server due to network conditions, or if getValue
|
|
167
|
-
* is called before initialization is done.
|
|
168
|
-
*/
|
|
169
|
-
getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
|
|
170
|
-
/**
|
|
171
|
-
* Watches for changes to a a config evaluation value. Whenever the config value changes, the
|
|
172
|
-
* provided callback function will be called with the new value. Changes can happen due to updates
|
|
173
|
-
* to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
|
|
174
|
-
*
|
|
175
|
-
* @returns An 'unwatch' function that can be called to remove the subscriber
|
|
176
|
-
*
|
|
177
|
-
* @param configKey The config key to watch
|
|
178
|
-
* @param defaultValue The default value to be referenced if the config state is unavailable
|
|
179
|
-
* @param callback The callback function to be called whenever the config value is updated
|
|
180
|
-
*/
|
|
181
|
-
watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>): () => void;
|
|
182
|
-
/**
|
|
183
|
-
* Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
|
|
184
|
-
* is provided.
|
|
185
|
-
*
|
|
186
|
-
* @param configKey The config key to remove subscribers from
|
|
187
|
-
* @param callback The subscriber to be removed. If not provided, all subscribers are removed for
|
|
188
|
-
* the given `configKey`.
|
|
189
|
-
*/
|
|
190
|
-
unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
|
|
191
|
-
/**
|
|
192
|
-
* Removes all subscribers from all config keys
|
|
193
|
-
*/
|
|
194
|
-
unwatchAll(): void;
|
|
195
|
-
/**
|
|
196
|
-
* Pauses the network connection without clearing event handlers, watch handlers, or config
|
|
197
|
-
* state. Intended for mobile environments where the OS may kill background connections (e.g.
|
|
198
|
-
* when the app is backgrounded on iOS/Android).
|
|
199
|
-
*
|
|
200
|
-
* Call {@link resumeNetwork} to re-establish the connection.
|
|
201
|
-
*/
|
|
202
|
-
pauseNetwork(): void;
|
|
203
|
-
/**
|
|
204
|
-
* Resumes a connection that was paused via {@link pauseNetwork}, using the last context that
|
|
205
|
-
* was provided to {@link initialize} or {@link updateContext}.
|
|
206
|
-
*/
|
|
207
|
-
resumeNetwork(): Promise<void>;
|
|
208
|
-
/**
|
|
209
|
-
* Disposes of the client. All connections are closed, and all event and config key subscribers
|
|
210
|
-
* are removed.
|
|
211
|
-
*
|
|
212
|
-
* Intended to be called when your application shuts down
|
|
213
|
-
*/
|
|
214
|
-
dispose(): void;
|
|
215
|
-
}
|
|
216
|
-
//#endregion
|
|
217
6
|
//#region src/client/types.d.ts
|
|
218
7
|
type ClientStatus = "loading" | "ready" | "default";
|
|
219
8
|
interface ConfigDirectorContextData {
|
|
@@ -238,6 +27,18 @@ type ConfigDirectorProviderOptions = {
|
|
|
238
27
|
* Initialization timeout in milliseconds. Defaults to 3000.
|
|
239
28
|
*/
|
|
240
29
|
timeout?: number;
|
|
30
|
+
/**
|
|
31
|
+
* The connection mode, one of `streaming` or `polling`. In `streaming` mode the connection stays
|
|
32
|
+
* open and receives config updates as they happen. In `polling` mode configs are fetched once during
|
|
33
|
+
* initialization and then again on every `pollingInterval`. Defaults to `streaming`.
|
|
34
|
+
*/
|
|
35
|
+
mode?: ConnectionMode;
|
|
36
|
+
/**
|
|
37
|
+
* The polling interval in seconds when `mode` is `polling`. Has no effect in `streaming` mode.
|
|
38
|
+
* Defaults to 60 seconds. A value below the minimum of 30 seconds is raised to 30 seconds and a
|
|
39
|
+
* warning is logged.
|
|
40
|
+
*/
|
|
41
|
+
pollingInterval?: number;
|
|
241
42
|
/**
|
|
242
43
|
* Initial user context to evaluate targeting rules against.
|
|
243
44
|
*/
|
|
@@ -259,6 +60,34 @@ type ConfigDirectorProviderOptions = {
|
|
|
259
60
|
*/
|
|
260
61
|
initialConfigs?: Record<string, ConfigState>;
|
|
261
62
|
};
|
|
63
|
+
/**
|
|
64
|
+
* Props of a client `ConfigDirectorProvider` given an existing client instead of the options to
|
|
65
|
+
* build one, for example a test client's `client`.
|
|
66
|
+
*/
|
|
67
|
+
type ConfigDirectorClientProviderClientProps = {
|
|
68
|
+
/**
|
|
69
|
+
* The client to provide. The provider never disposes it. If the client is not ready and not
|
|
70
|
+
* initializing, the provider initializes it with `context`; if it is ready and `context` is given
|
|
71
|
+
* and differs from the client's context, the provider updates the context; otherwise it leaves the
|
|
72
|
+
* client as it is and reports ready as soon as the client is.
|
|
73
|
+
*/
|
|
74
|
+
client: ConfigDirectorClient;
|
|
75
|
+
context?: ConfigDirectorContext;
|
|
76
|
+
/**
|
|
77
|
+
* Event handlers registered on the client while the provider is mounted, and removed when it
|
|
78
|
+
* unmounts.
|
|
79
|
+
*/
|
|
80
|
+
hooks?: ClientHooks;
|
|
81
|
+
/**
|
|
82
|
+
* Pre-evaluated config states shown by the hooks until the client is ready.
|
|
83
|
+
*/
|
|
84
|
+
initialConfigs?: Record<string, ConfigState>;
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* Props of the client `ConfigDirectorProvider`: either the options to build a client from, or an
|
|
88
|
+
* existing client.
|
|
89
|
+
*/
|
|
90
|
+
type ConfigDirectorClientProviderProps = ConfigDirectorProviderOptions | ConfigDirectorClientProviderClientProps;
|
|
262
91
|
//#endregion
|
|
263
92
|
//#region src/client/ConfigDirectorProvider.d.ts
|
|
264
93
|
/**
|
|
@@ -272,13 +101,20 @@ type ConfigDirectorProviderOptions = {
|
|
|
272
101
|
* This component itself is a Client Component, so if you use it directly (rather than through
|
|
273
102
|
* the server provider) any `sdkKey` sourced from `process.env` must use the `NEXT_PUBLIC_`
|
|
274
103
|
* prefix — Next.js only exposes prefixed variables to code that runs in the browser.
|
|
104
|
+
*
|
|
105
|
+
* Given a `client` prop, or while a test client is installed from
|
|
106
|
+
* `@configdirector/nextjs-sdk/client/testing`, the provider provides that client from its first
|
|
107
|
+
* render instead of building one, and never disposes it.
|
|
275
108
|
*/
|
|
276
|
-
declare class ConfigDirectorProvider extends Component<PropsWithChildren<
|
|
109
|
+
declare class ConfigDirectorProvider extends Component<PropsWithChildren<ConfigDirectorClientProviderProps>, ConfigDirectorProviderState> {
|
|
277
110
|
private client;
|
|
278
|
-
|
|
111
|
+
private readonly ownsClient;
|
|
112
|
+
private handlers;
|
|
113
|
+
constructor(props: PropsWithChildren<ConfigDirectorClientProviderProps>);
|
|
279
114
|
private buildClient;
|
|
280
115
|
componentDidMount(): Promise<void>;
|
|
281
|
-
|
|
116
|
+
private connect;
|
|
117
|
+
componentDidUpdate(prevProps: PropsWithChildren<ConfigDirectorClientProviderProps>): Promise<void>;
|
|
282
118
|
componentWillUnmount(): void;
|
|
283
119
|
render(): _$react_jsx_runtime0.JSX.Element;
|
|
284
120
|
}
|
|
@@ -339,5 +175,5 @@ declare class ConfigDirectorNextContextError extends Error {
|
|
|
339
175
|
constructor(message: string);
|
|
340
176
|
}
|
|
341
177
|
//#endregion
|
|
342
|
-
export { type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, ConfigDirectorNextContextError, ConfigDirectorProvider, type ConfigDirectorProviderOptions, type ConfigValueType, createConsoleLogger, useClient, useConfigDirectorStatus, useConfigValue, useContext };
|
|
178
|
+
export { type ClientStatus, type ConfigDirectorClient, type ConfigDirectorClientProviderClientProps, type ConfigDirectorClientProviderProps, type ConfigDirectorContext, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, ConfigDirectorNextContextError, ConfigDirectorProvider, type ConfigDirectorProviderOptions, type ConfigValueType, type ConnectionMode, createConsoleLogger, useClient, useConfigDirectorStatus, useConfigValue, useContext };
|
|
343
179
|
//# sourceMappingURL=index.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/client/types.ts","../../src/client/ConfigDirectorProvider.tsx","../../src/client/hooks.tsx","../../src/client/logger.ts","../../src/client/errors.ts"],"mappings":";;;;;;KAWY,YAAA;AAAA,UAEK,yBAAA;EACf,MAAA,GAAS,oBAAA;EACT,SAAA,GAAY,IAAA;EACZ,MAAA,EAAQ,YAAA;EACR,cAAA,GAAiB,MAAA,SAAe,WAAA;AAAA;AAAA,KAGtB,2BAAA,GAA8B,IAAA,CAAK,yBAAA;AAAA,KAEnC,6BAAA;;;;EAIV,MAAA;EACA,OAAA;EACA,UAAA;EAXuB;;;EAevB,GAAA;EAjBA;;;EAqBA,OAAA;EAnBA;;;;;EAyBA,IAAA,GAAO,cAAA;EAtB8B;;;;AAEvC;EA0BE,eAAA;;;;EAIA,OAAA,GAAU,qBAAA;EAMF;;;EAFR,QAAA,GAAW,0BAAA;EAEX,KAAA,GAAQ,WAAA;EAhCR;;;;;;;;;;EA2CA,cAAA,GAAiB,MAAA,SAAe,WAAA;AAAA;;;;;KAOtB,uCAAA;EAPiC;;AAO7C;;;;EAOE,MAAA,EAAQ,oBAAA;EACR,OAAA,GAAU,qBAAA;EASsB;;;;EAJhC,KAAA,GAAQ,WAAA;EANA;;;EAUR,cAAA,GAAiB,MAAA,SAAe,WAAA;AAAA;;;;;KAOtB,iCAAA,GAAoC,6BAAA,GAAgC,uCAAA;;;;;;AAzFhF;;;;;AAEA;;;;;;;;cCsBa,sBAAA,SAA+B,SAAA,CAC1C,iBAAA,CAAkB,iCAAA,GAClB,2BAAA;EAAA,QAEQ,MAAA;EAAA,iBACS,UAAA;EAAA,QACT,QAAA;cAEI,KAAA,EAAO,iBAAA,CAAkB,iCAAA;EAAA,QAU7B,WAAA;EAmBO,iBAAA,CAAA,GAAqB,OAAA;EAAA,QAwBtB,OAAA;EAiBC,kBAAA,CACb,SAAA,EAAW,iBAAA,CAAkB,iCAAA,IAC5B,OAAA;EAiBM,oBAAA,CAAA;EASA,MAAA,CAAA,GAAM,oBAAA,CAAA,GAAA,CAAA,OAAA;AAAA;;;;;;ADlIjB;;;;;AAEA;;cEYa,cAAA,aAA4B,eAAA,EACvC,GAAA,UACA,YAAA,EAAc,CAAA;EACX,KAAA,EAAO,CAAA;EAAG,WAAA,EAAa,YAAA;EAAc,OAAA;AAAA;;;;;;;cA2B7B,UAAA;EAAmB,aAAA,GAAgB,OAAA,EAAS,qBAAA,KAA0B,OAAA;AAAA;;;;;;cAiBtE,SAAA;UAIZ,oBAAA;AAAA;;;AFtDD;;;;;;;cEiEa,uBAAA;EAAgC,WAAA,EAAa,YAAA;EAAc,OAAA;AAAA;;;cC1E3D,mBAAA,GAAuB,KAAA,EAAO,0BAAA,KAA6B,oBAAA;;;cCb3D,8BAAA,SAAuC,KAAA;EAAA,SACzB,IAAA;cAEb,OAAA;AAAA"}
|