@configdirector/nextjs-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +13 -0
- package/dist/client/index.cjs +6 -0
- package/dist/client/index.d.cts +324 -0
- package/dist/client/index.d.cts.map +1 -0
- package/dist/client/index.d.mts +324 -0
- package/dist/client/index.d.mts.map +1 -0
- package/dist/client/index.mjs +7 -0
- package/dist/client/index.mjs.map +1 -0
- package/dist/server/index.cjs +5 -0
- package/dist/server/index.d.cts +316 -0
- package/dist/server/index.d.cts.map +1 -0
- package/dist/server/index.d.mts +316 -0
- package/dist/server/index.d.mts.map +1 -0
- package/dist/server/index.mjs +6 -0
- package/dist/server/index.mjs.map +1 -0
- package/package.json +91 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ConfigDirector
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is furnished
|
|
10
|
+
to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# ConfigDirector Next.js SDK
|
|
2
|
+
|
|
3
|
+
This is the Next.js SDK for [ConfigDirector](https://www.configdirector.com).
|
|
4
|
+
|
|
5
|
+
## Documentation
|
|
6
|
+
|
|
7
|
+
Refer to the [official documentation for the Next.js SDK](https://docs.configdirector.com/sdks/meta/nextjs).
|
|
8
|
+
|
|
9
|
+
There is also [a quickstart guide for ConfigDirector and any of our SDKs](https://docs.configdirector.com/getting-started/quickstart).
|
|
10
|
+
|
|
11
|
+
## Getting Help
|
|
12
|
+
|
|
13
|
+
Reach out to us via https://www.configdirector.com/support
|
|
@@ -0,0 +1,6 @@
|
|
|
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)}},g=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},_=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 v=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var y=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=v.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers},this.requestOptions={body:e.body,method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===v.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=v.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=v.CONNECTING,this._fetch(this.url,{...this.requestOptions,headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`}).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new m(`The server response did not have a body`);this._readyState=v.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new _({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=v.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=v.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new g(`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 b=e=>new y(e);var x=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=b({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}),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[EventSourceTransport] Connected`),t(this)},shouldReconnect:e=>{let t=!this.isStatusFatal(e.status);return t||n(this.prepareFatalError(e.status,e.error)),t},calculateReconnectDelay:e=>{let t=this.options.connectionRetryDelay(e.attempt);return this.logger.warn(`[EventSourceTransport] Scheduling reconnect in ${t}ms.`),t},onError:e=>{this.logger.debug(`[EventSourceTransport] Error: `,e)},onDisconnect:()=>{this.logger.debug(`[EventSourceTransport] 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(`[EventSourceTransport] 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}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 S=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},C=e=>e===`number`||e===`bigint`,w=(e,t)=>{let n=e.value,r=S(t);if(!n)return{parsedValue:t,requestedType:r,usedDefault:!0,reason:`value-missing`};if(typeof t==`string`)return{parsedValue:n,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&e.type===`boolean`){let e=T(n),i=typeof e==`boolean`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-boolean`}}if(C(typeof t)&&e.type===`integer`){let e=E(n),i=typeof e==`number`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-number`}}if(C(typeof t)&&(e.type===`float`||e.type===`enum`)){let e=D(n),i=typeof e==`number`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-number`}}return{parsedValue:n,requestedType:r,usedDefault:!1,reason:`found-match`}},T=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},E=e=>{if(!e)return;let t=Number.parseInt(e);if(!(isNaN(t)||!isFinite(t)))return t},D=e=>{if(!e)return;let t=Number.parseFloat(e);if(!(isNaN(t)||!isFinite(t)))return t},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);var N=class{constructor(){this.fatalError=!1,this.pollingIntervalSeconds=60}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.prepareFatalResponseStatusError(e.status,await e.text())):new 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}isFetchErrorFatal(e){return e?.name===`NotAllowedError`?!0:e instanceof TypeError}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const P=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 F=class extends N{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),this.pollingIntervalSeconds=e.pollingInterval??60}async connect(e,t){return this.clearPollingInterval(),await this.fetchConfigs(e,t),this.schedulePollingInterval(()=>{this.fetchConfigs(e,t).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})}),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 P(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,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){this.handleFetchError(e)}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}},I=class extends F{constructor(e){super(e),this.pollingIntervalSeconds=0}};const L=(e,t)=>new URL(e,t?.toString()),R=e=>{if(e)try{return new URL(e)}catch(t){throw new f(`Invalid URL '${e}'. Parsing failed: ${t}`)}};var z=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.timeout=r?.connection?.timeout??3e3;let a=i?.urlFactory??L,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({clientSdkKey:t,baseUrl:o,resolveUrl:a,metaContext:{...r?.metadata,sdkName:n.sdkName,sdkVersion:n.sdkVersion,userAgent:navigator?.userAgent},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.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)):(this.configSet.configs={...this.configSet.configs,...e.configs},this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:t})})}getTransportConstructor(e){switch(e){case`one-time`:return I;case`polling`:return F;default:return x}}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(()=>{this.ready=!0,this.initializing=!1,this.eventEmitter.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.eventEmitter.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)return this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`),this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:S(n),evaluatedValue:n,usedDefault:!0,evaluationReason:`config-state-missing`}),n;let r=w(t,n);return this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:r.requestedType,evaluatedValue:r.parsedValue,usedDefault:r.usedDefault,evaluationReason:r.reason}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),r.parsedValue}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new f(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}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?.(),this.telemetryClient.close(),this.transport.close(),this.ready=!1}dispose(){this.clear(),this.close()}};const B=(e,t)=>{if(t===`json`)try{return V(JSON.stringify(e))}catch{return e.toString().slice(0,500)}return e.toString().slice(0,500)},V=e=>H(new TextEncoder().encode(e)).toString(16).padStart(8,`0`),H=e=>{let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+(e[n]??0),t>>>=0;return t};var U=class{constructor(e){this.logger=e.logger;let t={type:`Initialize`,payload:{sdkKey:e.sdkKey,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=(e,n)=>{if(n===`json`)try{return t(JSON.stringify(e))}catch{return e.toString().slice(0,500)}return e.toString().slice(0,500)},t=e=>n(new TextEncoder().encode(e)).toString(16).padStart(8,`0`),n=e=>{let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+(e[n]??0),t>>>=0;return t},r=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},i=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},a=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}},o=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var s=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,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,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 r(e.discreteEvents)&&r(e.aggregatedEvents)&&i(e.droppedEvents)}async sendReport(e){try{let t=await a(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=o(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}},c=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}))}},l=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}},u=class{constructor(e){this.aggregator=new c,this.collectEvents=!0,this.logger=e.logger,this.evaluationEventQueue=new l(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4;let t=e.initialFlushIntervalDelay??5e3;this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),t)}sanitizeValue(t,n){return e(t,n)}async flushAndScheduleNext(){(await this.flush()).fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay)}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=this.evaluationEventQueue.takeSnapshot();return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout),await this.flush(),this.evaluationEventQueue.clear()}dispose(){this.close()}},d=class extends u{constructor(e){super(e),this.reporter=new s(e)}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()}};let f=(e,t)=>new URL(e,t?.toString()),p,m=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),h=e=>{try{self.postMessage(e)}catch{self.postMessage(m(e.payload.level,e.payload.message))}},g={debug:function(e,...t){h(m(`debug`,e,t))},info:function(e,...t){h(m(`info`,e,t))},warn:function(e,...t){h(m(`warn`,e,t))},error:function(e,...t){h(m(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!p){g.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(g.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:p=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,logger:g});break;case`EvaluatedConfigEvent`:p?.evaluatedConfig(t.payload);break;case`UpdateContext`:p?.updateContext(t.payload.context);break;case`Flush`:p?.forceFlush();break;case`Close`:(p?.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:B(e.defaultValue,e.type),evaluatedValue:B(e.evaluatedValue,e.type)}}handleWorkerEvent(e){if(e.type===`Closed`){this.closeResolve?.();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.warn(n,...r);break}}flush(){this.worker.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){return document.removeEventListener(`visibilitychange`,this.visibilityHandler),this.closePromise=new Promise(e=>{this.closeResolve=e,this.worker.postMessage({type:`Close`})}),this.closePromise}};const W=(e,t,n)=>{let r=n?.logger??M();return new z(new U({sdkKey:e,logger:r,baseUrl:R(n?.connection?.url)??`https://client-sdk-api.configdirector.com`,urlFactory:L}),e,t,{...n,logger:r})},G=c.default.createContext({status:`loading`});var K=class{decorateMessage(e){return`[ConfigDirector:nextjs-sdk] ${e}`}};const q=e=>M(e,new K);var J=class extends c.Component{constructor(e){super(e),this.state={status:`loading`}}buildClient(){return W(this.props.sdkKey,{sdkName:`nextjs-sdk`,sdkVersion:`0.1.0`},{connection:{url:this.props.url,timeout:this.props.timeout},metadata:{appName:this.props.appName,appVersion:this.props.appVersion},logger:this.props.logger??q(`warn`)})}async componentDidMount(){let e=this.buildClient();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),e.isReady||this.setState({status:`default`})}async componentDidUpdate(e){if(e.context!==this.props.context){let{client:e}=this.state;if(!e)return;this.setState({status:`loading`}),await e.updateContext(this.props.context??{}),e.isReady||this.setState({status:`default`})}}componentWillUnmount(){this.state.client?.dispose()}render(){return(0,l.jsx)(G.Provider,{value:{...this.state,initialConfigs:this.props.initialConfigs},children:this.props.children})}},Y=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorNextContextError`,Object.setPrototypeOf(this,e.prototype)}};const X=()=>new Y(`The ConfigDirector client was not found in the React context. Make sure the component using this hook is inside a <ConfigDirectorProvider>.`),Z=(e,t)=>{let n=(0,c.useContext)(G);if(!n)throw X();return{value:n.client?.isReady?n.client.getValue(e,t):n.initialConfigs?.[e]??t,readyStatus:n.status,loading:n.status===`loading`}},Q=()=>{let e=(0,c.useContext)(G);if(!e)throw X();return{updateContext:async t=>{await e.client?.updateContext(t)}}},$=()=>{let e=(0,c.useContext)(G);if(!e?.client)throw X();return{client:e.client}},ee=()=>{let e=(0,c.useContext)(G);if(!e)throw X();return{readyStatus:e.status,loading:e.status===`loading`}};exports.ConfigDirectorNextContextError=Y,exports.ConfigDirectorProvider=J,exports.createConsoleLogger=q,exports.useClient=$,exports.useConfigDirectorStatus=ee,exports.useConfigValue=Z,exports.useContext=Q;
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
|
|
2
|
+
import * as _$react_jsx_runtime0 from "react/jsx-runtime";
|
|
3
|
+
import { Component, PropsWithChildren } from "react";
|
|
4
|
+
|
|
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
|
+
type ConfigEnumLikeType = {
|
|
17
|
+
[key: string]: string | number;
|
|
18
|
+
};
|
|
19
|
+
type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
|
|
20
|
+
type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
|
|
21
|
+
interface ConfigDirectorLogger {
|
|
22
|
+
debug(message: string, ...args: any): void;
|
|
23
|
+
info(message: string, ...args: any): void;
|
|
24
|
+
warn(message: string, ...args: any): void;
|
|
25
|
+
error(message: string, ...args: any): void;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The user's context to be sent to ConfigDirector. This context will be used for targeting
|
|
29
|
+
* rules evaluation.
|
|
30
|
+
*/
|
|
31
|
+
type ConfigDirectorContext = {
|
|
32
|
+
/**
|
|
33
|
+
* The user's identifier. This should be a value that uniquely identifies an application
|
|
34
|
+
* user.
|
|
35
|
+
* In the case of anonymous users, you could generate a UUID or alternatively not provide
|
|
36
|
+
* the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
|
|
37
|
+
* value is used for segmenting users in percentage rollouts, and changes to the {@link id}
|
|
38
|
+
* could result in the user being assigned to a different percentile.
|
|
39
|
+
*/
|
|
40
|
+
id?: string;
|
|
41
|
+
/**
|
|
42
|
+
* The user's display name. This will be shown in the ConfigDirector dashboard and may be
|
|
43
|
+
* used for targeting rules.
|
|
44
|
+
*/
|
|
45
|
+
name?: string;
|
|
46
|
+
/**
|
|
47
|
+
* Any arbitrary traits for the current user. They will be shown in the ConfigDirector
|
|
48
|
+
* dashboard and may be used for targeting rules.
|
|
49
|
+
*/
|
|
50
|
+
traits?: {
|
|
51
|
+
[key: string]: unknown;
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region ../js-client-core/src/types.d.ts
|
|
56
|
+
type ClientConnectAction = "initialization" | "context update" | "network resume";
|
|
57
|
+
type ClientEvents = {
|
|
58
|
+
configsUpdated: {
|
|
59
|
+
keys: string[];
|
|
60
|
+
};
|
|
61
|
+
clientReady: {
|
|
62
|
+
action: ClientConnectAction;
|
|
63
|
+
};
|
|
64
|
+
contextUpdated: {
|
|
65
|
+
context: ConfigDirectorContext | undefined;
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
type WatchHandler<T extends ConfigValueType> = (message: T) => void;
|
|
69
|
+
/**
|
|
70
|
+
* The ConfigDirector SDK client object.
|
|
71
|
+
*
|
|
72
|
+
* Applications should create a single instance of `ConfigDirectorClient`, and call
|
|
73
|
+
* {@link initialize} during application initialization.
|
|
74
|
+
*
|
|
75
|
+
* After initialization, to update the user's context, so that targeting rules are evaluated
|
|
76
|
+
* with the updated context, call {@link updateContext}.
|
|
77
|
+
*/
|
|
78
|
+
interface ConfigDirectorClient extends EventProvider<ClientEvents> {
|
|
79
|
+
/**
|
|
80
|
+
* Initializes the connection to ConfigDirector to retrieve config evaluations. Until
|
|
81
|
+
* initialization is successful, all flags will return their default value provided to
|
|
82
|
+
* {@link watch} or {@link getValue}.
|
|
83
|
+
*
|
|
84
|
+
* If the connection fails or is interrupted with a transient error (network error,
|
|
85
|
+
* internal server error, etc) the client will continue to attempt to connect. However,
|
|
86
|
+
* if the connection fails with a persistent error, like an invalid SDK key, the client will
|
|
87
|
+
* not attempt to re-connect and an error will be logged to the console or the provided
|
|
88
|
+
* logger.
|
|
89
|
+
*
|
|
90
|
+
* @param context The current user's context to be used for evaluating targeting rules (optional).
|
|
91
|
+
*/
|
|
92
|
+
initialize(context?: ConfigDirectorContext): Promise<void>;
|
|
93
|
+
/**
|
|
94
|
+
* Updates the user's context and re-evaluates all config and flag values based on the new context.
|
|
95
|
+
*
|
|
96
|
+
* @param context The current user's context to be used for evaluating targeting rules (required).
|
|
97
|
+
*/
|
|
98
|
+
updateContext(context: ConfigDirectorContext): Promise<void>;
|
|
99
|
+
/**
|
|
100
|
+
* Returns the current context the client is configured with, or undefined if there is no context.
|
|
101
|
+
*
|
|
102
|
+
* Note that the value returned does not updated immediately after calling {@link updateContext}. Only
|
|
103
|
+
* once the underlying connection was successful or timed out, the current context is updated. This is
|
|
104
|
+
* because while the context update is in progress, configs are still evaluated on the previous context.
|
|
105
|
+
*
|
|
106
|
+
*/
|
|
107
|
+
get context(): ConfigDirectorContext | undefined;
|
|
108
|
+
/**
|
|
109
|
+
* Returns whether or not the client is ready after calling {@link initialize} or {@link updateContext}
|
|
110
|
+
*
|
|
111
|
+
* The definition of ready is that the connection to the server was successful, and config state
|
|
112
|
+
* was received.
|
|
113
|
+
*/
|
|
114
|
+
get isReady(): boolean;
|
|
115
|
+
/**
|
|
116
|
+
* Returns whether or not the client is currently initializing. Upon client creation, it is `false`.
|
|
117
|
+
* It is `true` after calling `initialize` and becomes `false` again once initialization is completed.
|
|
118
|
+
*/
|
|
119
|
+
get isInitializing(): boolean;
|
|
120
|
+
/**
|
|
121
|
+
* Evaluates a config and returns its value based on the current context and targeting rules
|
|
122
|
+
*
|
|
123
|
+
* @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
|
|
124
|
+
* @param configKey The config key to evaluate
|
|
125
|
+
* @param defaultValue The default value to be returned if the config state is unavailable. For
|
|
126
|
+
* example, if the client cannot connect to the server due to network conditions, or if getValue
|
|
127
|
+
* is called before initialization is done.
|
|
128
|
+
*/
|
|
129
|
+
getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
|
|
130
|
+
/**
|
|
131
|
+
* Watches for changes to a a config evaluation value. Whenever the config value changes, the
|
|
132
|
+
* provided callback function will be called with the new value. Changes can happen due to updates
|
|
133
|
+
* to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
|
|
134
|
+
*
|
|
135
|
+
* @returns An 'unwatch' function that can be called to remove the subscriber
|
|
136
|
+
*
|
|
137
|
+
* @param configKey The config key to watch
|
|
138
|
+
* @param defaultValue The default value to be referenced if the config state is unavailable
|
|
139
|
+
* @param callback The callback function to be called whenever the config value is updated
|
|
140
|
+
*/
|
|
141
|
+
watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>): () => void;
|
|
142
|
+
/**
|
|
143
|
+
* Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
|
|
144
|
+
* is provided.
|
|
145
|
+
*
|
|
146
|
+
* @param configKey The config key to remove subscribers from
|
|
147
|
+
* @param callback The subscriber to be removed. If not provided, all subscribers are removed for
|
|
148
|
+
* the given `configKey`.
|
|
149
|
+
*/
|
|
150
|
+
unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
|
|
151
|
+
/**
|
|
152
|
+
* Removes all subscribers from all config keys
|
|
153
|
+
*/
|
|
154
|
+
unwatchAll(): void;
|
|
155
|
+
/**
|
|
156
|
+
* Pauses the network connection without clearing event handlers, watch handlers, or config
|
|
157
|
+
* state. Intended for mobile environments where the OS may kill background connections (e.g.
|
|
158
|
+
* when the app is backgrounded on iOS/Android).
|
|
159
|
+
*
|
|
160
|
+
* Call {@link resumeNetwork} to re-establish the connection.
|
|
161
|
+
*/
|
|
162
|
+
pauseNetwork(): void;
|
|
163
|
+
/**
|
|
164
|
+
* Resumes a connection that was paused via {@link pauseNetwork}, using the last context that
|
|
165
|
+
* was provided to {@link initialize} or {@link updateContext}.
|
|
166
|
+
*/
|
|
167
|
+
resumeNetwork(): Promise<void>;
|
|
168
|
+
/**
|
|
169
|
+
* Disposes of the client. All connections are closed, and all event and config key subscribers
|
|
170
|
+
* are removed.
|
|
171
|
+
*
|
|
172
|
+
* Intended to be called when your application shuts down
|
|
173
|
+
*/
|
|
174
|
+
dispose(): void;
|
|
175
|
+
}
|
|
176
|
+
//#endregion
|
|
177
|
+
//#region src/client/types.d.ts
|
|
178
|
+
type ClientStatus = "loading" | "ready" | "default";
|
|
179
|
+
interface ConfigDirectorContextData {
|
|
180
|
+
client?: ConfigDirectorClient;
|
|
181
|
+
updatedAt?: Date;
|
|
182
|
+
status: ClientStatus;
|
|
183
|
+
initialConfigs?: Record<string, unknown>;
|
|
184
|
+
}
|
|
185
|
+
type ConfigDirectorProviderState = Omit<ConfigDirectorContextData, "initialConfigs">;
|
|
186
|
+
type ConfigDirectorProviderOptions = {
|
|
187
|
+
/**
|
|
188
|
+
* Your ConfigDirector Client SDK key. This is a public value safe for the browser.
|
|
189
|
+
*/
|
|
190
|
+
sdkKey: string;
|
|
191
|
+
appName?: string;
|
|
192
|
+
appVersion?: string;
|
|
193
|
+
/**
|
|
194
|
+
* Override the ConfigDirector client API base URL. Primarily useful for testing or proxying.
|
|
195
|
+
*/
|
|
196
|
+
url?: string;
|
|
197
|
+
/**
|
|
198
|
+
* Initialization timeout in milliseconds. Defaults to 3000.
|
|
199
|
+
*/
|
|
200
|
+
timeout?: number;
|
|
201
|
+
/**
|
|
202
|
+
* Initial user context to evaluate targeting rules against.
|
|
203
|
+
*/
|
|
204
|
+
context?: ConfigDirectorContext;
|
|
205
|
+
/**
|
|
206
|
+
* A logger instance created with {@link createConsoleLogger}.
|
|
207
|
+
*/
|
|
208
|
+
logger?: ConfigDirectorLogger;
|
|
209
|
+
/**
|
|
210
|
+
* Pre-evaluated config values from the server, used to hydrate client components correctly
|
|
211
|
+
* during SSR. Obtain these by calling {@link createSsrClient} in your Server Component
|
|
212
|
+
* layout and passing the results here.
|
|
213
|
+
*
|
|
214
|
+
* When the browser client is not yet ready (during SSR and the initial client render before
|
|
215
|
+
* initialization completes), hooks will return values from this map rather than the default
|
|
216
|
+
* value, avoiding a flash of wrong content on hydration.
|
|
217
|
+
*/
|
|
218
|
+
initialConfigs?: Record<string, unknown>;
|
|
219
|
+
};
|
|
220
|
+
//#endregion
|
|
221
|
+
//#region src/client/ConfigDirectorProvider.d.ts
|
|
222
|
+
/**
|
|
223
|
+
* Initializes the ConfigDirector browser client and provides it to all descendant hooks.
|
|
224
|
+
*
|
|
225
|
+
* Place this in your root layout, wrapping your application. Pass server-evaluated
|
|
226
|
+
* `initialConfigs` to ensure Client Components render the correct values during SSR and before
|
|
227
|
+
* the browser client finishes initializing, preventing a flash of wrong content on hydration:
|
|
228
|
+
*
|
|
229
|
+
* ```tsx
|
|
230
|
+
* // app/layout.tsx
|
|
231
|
+
* import { createSsrClient } from "@configdirector/nextjs-sdk/server";
|
|
232
|
+
* import { ConfigDirectorProvider } from "@configdirector/nextjs-sdk/client";
|
|
233
|
+
* import { cookies } from "next/headers";
|
|
234
|
+
*
|
|
235
|
+
* export default async function RootLayout({ children }) {
|
|
236
|
+
* const userId = (await cookies()).get("userId")?.value;
|
|
237
|
+
* const ssrClient = createSsrClient({ userId });
|
|
238
|
+
*
|
|
239
|
+
* return (
|
|
240
|
+
* <html>
|
|
241
|
+
* <body>
|
|
242
|
+
* <ConfigDirectorProvider
|
|
243
|
+
* sdkKey={process.env.NEXT_PUBLIC_CONFIGDIRECTOR_CLIENT_KEY!}
|
|
244
|
+
* context={{ userId }}
|
|
245
|
+
* initialConfigs={{
|
|
246
|
+
* "new-dashboard": ssrClient.getValue("new-dashboard", false),
|
|
247
|
+
* "theme": ssrClient.getValue("theme", "light"),
|
|
248
|
+
* }}
|
|
249
|
+
* >
|
|
250
|
+
* {children}
|
|
251
|
+
* </ConfigDirectorProvider>
|
|
252
|
+
* </body>
|
|
253
|
+
* </html>
|
|
254
|
+
* );
|
|
255
|
+
* }
|
|
256
|
+
* ```
|
|
257
|
+
*/
|
|
258
|
+
declare class ConfigDirectorProvider extends Component<PropsWithChildren<ConfigDirectorProviderOptions>, ConfigDirectorProviderState> {
|
|
259
|
+
constructor(props: PropsWithChildren<ConfigDirectorProviderOptions>);
|
|
260
|
+
private buildClient;
|
|
261
|
+
componentDidMount(): Promise<void>;
|
|
262
|
+
componentDidUpdate(prevProps: PropsWithChildren<ConfigDirectorProviderOptions>): Promise<void>;
|
|
263
|
+
componentWillUnmount(): void;
|
|
264
|
+
render(): _$react_jsx_runtime0.JSX.Element;
|
|
265
|
+
}
|
|
266
|
+
//#endregion
|
|
267
|
+
//#region src/client/hooks.d.ts
|
|
268
|
+
/**
|
|
269
|
+
* Returns the evaluated value of a config key.
|
|
270
|
+
*
|
|
271
|
+
* During SSR and before the browser client finishes initializing, returns the value from
|
|
272
|
+
* `initialConfigs` (if provided to the provider) to avoid a flash of wrong content on hydration.
|
|
273
|
+
* Once the browser client is ready, returns live-evaluated values and re-renders whenever configs
|
|
274
|
+
* change.
|
|
275
|
+
*
|
|
276
|
+
* Must be used inside a `<ConfigDirectorProvider>`.
|
|
277
|
+
*/
|
|
278
|
+
declare const useConfigValue: <T extends ConfigValueType>(key: string, defaultValue: T) => {
|
|
279
|
+
value: T;
|
|
280
|
+
readyStatus: ClientStatus;
|
|
281
|
+
loading: boolean;
|
|
282
|
+
};
|
|
283
|
+
/**
|
|
284
|
+
* Returns an `updateContext` function to update the user context on the browser client.
|
|
285
|
+
* Triggers re-evaluation of all watched config values.
|
|
286
|
+
*
|
|
287
|
+
* Must be used inside a `<ConfigDirectorProvider>`.
|
|
288
|
+
*/
|
|
289
|
+
declare const useContext: () => {
|
|
290
|
+
updateContext: (context: ConfigDirectorContext) => Promise<void>;
|
|
291
|
+
};
|
|
292
|
+
/**
|
|
293
|
+
* Returns the raw browser client for advanced use cases.
|
|
294
|
+
*
|
|
295
|
+
* Must be used inside a `<ConfigDirectorProvider>`.
|
|
296
|
+
*/
|
|
297
|
+
declare const useClient: () => {
|
|
298
|
+
client: ConfigDirectorClient;
|
|
299
|
+
};
|
|
300
|
+
/**
|
|
301
|
+
* Returns the current connection status of the browser client.
|
|
302
|
+
*
|
|
303
|
+
* - `"loading"` — client is initializing
|
|
304
|
+
* - `"ready"` — client received configs from the server
|
|
305
|
+
* - `"default"` — initialization timed out; hooks return default or initial values
|
|
306
|
+
*
|
|
307
|
+
* Must be used inside a `<ConfigDirectorProvider>`.
|
|
308
|
+
*/
|
|
309
|
+
declare const useConfigDirectorStatus: () => {
|
|
310
|
+
readyStatus: ClientStatus;
|
|
311
|
+
loading: boolean;
|
|
312
|
+
};
|
|
313
|
+
//#endregion
|
|
314
|
+
//#region src/client/logger.d.ts
|
|
315
|
+
declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel) => ConfigDirectorLogger;
|
|
316
|
+
//#endregion
|
|
317
|
+
//#region src/client/errors.d.ts
|
|
318
|
+
declare class ConfigDirectorNextContextError extends Error {
|
|
319
|
+
readonly name: string;
|
|
320
|
+
constructor(message: string);
|
|
321
|
+
}
|
|
322
|
+
//#endregion
|
|
323
|
+
export { type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, type ConfigDirectorLogger, ConfigDirectorNextContextError, ConfigDirectorProvider, type ConfigDirectorProviderOptions, type ConfigValueType, createConsoleLogger, useClient, useConfigDirectorStatus, useConfigValue, useContext };
|
|
324
|
+
//# sourceMappingURL=index.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../js-client-core/src/Emitter.ts","../../../shared/src/types.ts","../../../js-client-core/src/types.ts","../../src/client/types.ts","../../src/client/ConfigDirectorProvider.tsx","../../src/client/hooks.tsx","../../src/client/logger.ts","../../src/client/errors.ts"],"mappings":"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"}
|