@configdirector/react-web-sdk 1.8.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/configdirector-react-client-testing.cjs +1 -1
- package/dist/configdirector-react-client-testing.d.cts +1 -1
- package/dist/configdirector-react-client-testing.d.mts +1 -1
- package/dist/configdirector-react-client-testing.mjs +1 -1
- package/dist/configdirector-react-client.cjs +1 -1
- package/dist/configdirector-react-client.d.cts +8 -2
- package/dist/configdirector-react-client.d.cts.map +1 -1
- package/dist/configdirector-react-client.d.mts +8 -2
- package/dist/configdirector-react-client.d.mts.map +1 -1
- package/dist/configdirector-react-client.mjs +1 -1
- package/dist/configdirector-react-client.mjs.map +1 -1
- package/dist/installedTestClient-CFTroBWf.cjs +5 -0
- package/dist/installedTestClient-DxB-5uP1.mjs +6 -0
- package/dist/installedTestClient-DxB-5uP1.mjs.map +1 -0
- package/dist/{types-DJSy0ELn.d.cts → types-CFBLmqUM.d.cts} +49 -6
- package/dist/types-CFBLmqUM.d.cts.map +1 -0
- package/dist/{types-BfakBTXM.d.mts → types-CrgXfAWw.d.mts} +49 -6
- package/dist/types-CrgXfAWw.d.mts.map +1 -0
- package/package.json +1 -1
- package/dist/installedTestClient-BXUl11xD.cjs +0 -5
- package/dist/installedTestClient-CqDdos7F.mjs +0 -6
- package/dist/installedTestClient-CqDdos7F.mjs.map +0 -1
- package/dist/types-BfakBTXM.d.mts.map +0 -1
- package/dist/types-DJSy0ELn.d.cts.map +0 -1
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var e=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))}},t=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},n=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}},i=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},a=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},o=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},s=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},c=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
+
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
3
|
+
`&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){this.onComment?.(this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
|
|
4
|
+
`)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent({...this.currentEvent,id:this.lastEventId,data:e}),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
|
|
5
|
+
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:/^\d+$/.test(e.value)&&this.onRetry?.(Number.parseInt(e.value,10));break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let l=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var u=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=l.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===l.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=l.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=l.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 a(`The server response did not have a body`);this._readyState=l.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new c({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 i(`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=l.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=l.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new s(`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 o(`${n} must be a function`);return e}};const d=e=>new u(e);var ee=class{constructor(t){this.options=t,this.eventEmitter=new e,this.connectionGeneration=0,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/sse/v1`,t.baseUrl)}async connect(e,t){let n=++this.connectionGeneration,r=await this.options.clientSession;if(n!==this.connectionGeneration)return this;this.eventSource&&this.close();let i=new Promise((t,n)=>{this.eventSource=d({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:r.instanceId,ephemeral:r.ephemeral}),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([i,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,n){let r=e??0;return new t(`${`Connection failed with status: ${e??`unknown`}.`}${n?` Error: ${n}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}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.connectionGeneration++,this.eventSource?.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const f=(e,t)=>{if(e.trim().length==0)throw new n(`Invalid config key. The key of a value cannot be empty.`);return p(e,t)},p=(e,t)=>{switch(typeof t){case`boolean`:return{type:`boolean`,value:t?`true`:`false`};case`number`:return m(e,t);case`string`:return{type:`string`,value:t};case`object`:if(t!==null)return g(e,t,``),{type:`json`,value:JSON.stringify(t)}}throw new n(`Invalid value for '${e}': ${y(t)}. Use a boolean, a number, a string, a plain object, or an array.`)},m=(e,t)=>{if(!Number.isFinite(t))throw new n(`Invalid value for '${e}': ${y(t)} is not a finite number.`);if(Number.isInteger(t)){if(!Number.isSafeInteger(t))throw new n(`Invalid value for '${e}': ${t} is not a safe integer, so the SDK could not read it back exactly.`);return{type:`integer`,value:String(t)}}return{type:`float`,value:h(t)}},h=e=>{let t=String(e),n=t.indexOf(`e-`);if(n<0)return t;let r=t.startsWith(`-`)?`-`:``,[i=``,a=``]=t.slice(r.length,n).split(`.`),o=Number(t.slice(n+2))-i.length;return`${r}0.${`0`.repeat(o)}${i}${a}`},g=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw _(e,n,`${y(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>g(e,t,`${n}[${r}]`));return}if(v(t)){for(let[r,i]of Object.entries(t))g(e,i,n?`${n}.${r}`:r);return}throw _(e,n,`${y(t)} cannot be encoded as JSON`)}},_=(e,t,r)=>new n(`Invalid value for '${e}'${t?` at '${t}'`:``}: ${r}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),v=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},y=e=>e===null?`null`:typeof e==`function`?`a function`:typeof e==`object`?`a ${e.constructor?.name??`object`} instance`:typeof e==`symbol`?`a symbol`:String(e),b=(e,t,n,r)=>{let i=f(t,n);return{id:e,key:t,type:i.type,value:i.value,valueId:r}},x={environmentId:`offline`,projectId:`offline`};var S=class{constructor(t){this.source=t,this.emitter=new e,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t)}async connect(){let e=C(this.source);return this.emitter.emit(`configSetReceived`,{...x,kind:`full`,configs:e}),this}clear(){this.emitter.clear()}close(){}dispose(){this.clear()}};const C=e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return te(e.values);case`rejected`:throw new r(e.message)}},te=e=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,b(`offline:${e}`,e,t,void 0)]))}catch(e){throw e instanceof n?new r(`The offline values could not be loaded. ${e.message}`):e}},ne=(e,t,r)=>{if(t?.mode===`offline`)return{kind:`stay-offline`,source:ie(t)};let i=t?.mode??`streaming`;if(!e||e.trim().length==0)throw new n(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`);return t?.values===void 0?{kind:`connect`,mode:i,clientSdkKey:e,baseUrl:re(t?.url,r)}:{kind:`stay-offline`,source:{kind:`rejected`,message:`The connection option 'values' applies only when the connection mode is 'offline', but the mode is '${i}'.`}}},re=(e,t)=>{if(!e)return`https://client-sdk-api.configdirector.com`;try{return t(e)}catch(t){throw new n(`Invalid base URL '${e}'. Parsing failed: ${t}`)}},ie=e=>e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values},w=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},T=e=>e===`number`||e===`bigint`,E=new Set([`boolean`,`integer`,`float`]),D=(e,t)=>{let n=e.value,r=w(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return N(n,t,r,e.valueId);if(typeof t==`string`)return E.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=O(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(T(typeof t)&&e.type===`integer`){let i=k(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(T(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=A(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`}},O=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},k=e=>{let t=j(e);return t==null?void 0:Math.trunc(t)},A=e=>j(e),j=e=>{if(!e||!M(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},M=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},N=(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 P(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`}}},P=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},F={off:-1,error:0,warn:1,info:2,debug:3},I=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,{...e,fractionalSecondDigits:3})}catch{return new Intl.DateTimeFormat(void 0,e)}};var L=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=I()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){F[this.level]>=F[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},R=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const z=(e,t)=>new L(e??`warn`,t??new R),B={updateContext:async()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>{},close:async()=>{}},V=(e,t)=>new URL(e,t?.toString()),H=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},U=()=>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)}),W=e=>{try{return e(globalThis)}catch{return}},G=()=>W(e=>e.navigator?.userAgent),K=()=>W(e=>e.location?.host),q=()=>{try{return globalThis.localStorage??void 0}catch{return}},J=`configdirector-sdk:instance-id`,Y=1e3,ae=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,X=(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=X(n,2166136261);return X(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},oe=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||!ae.test(n)?!1:i===Z(n,r)},se=async(e,t)=>{let n;try{n=await e.getItem(J)}catch(e){return t.debug(`[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one`,e),{outcome:`failed`}}if(typeof n!=`string`||n===``)return{outcome:`nothing usable`};let r;try{r=JSON.parse(n)}catch{return t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`),{outcome:`nothing usable`}}return oe(r)?{outcome:`stored`,instanceId:r.id}:(t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`})},ce=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:Z(t,r)};try{return await e.setItem(J,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},le=async(e,t,n,r)=>{let i=await se(e,r);switch(i.outcome){case`stored`:return{instanceId:i.instanceId};case`failed`:return{instanceId:t,ephemeral:!0};case`nothing usable`:break}return n.passed?{instanceId:t,ephemeral:!0}:await ce(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},ue=(e,t=q())=>{let n=U();if(!t)return e.debug(`[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id`),Promise.resolve({instanceId:n,ephemeral:!0});let r={passed:!1},i,a=new Promise(t=>{i=setTimeout(()=>{r.passed=!0,e.warn(`[ConfigDirectorClient] The instance id storage did not respond within ${Y}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},Y)});return Promise.race([le(t,n,r,e),a]).finally(()=>clearTimeout(i))};var de=class{constructor(){this.fatalError=!1}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 t(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new t(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new t(`Failed to parse the response from the server: ${e}`):new t(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,n){let r=e??0;return new t(`${`Connection failed with status: ${e??`unknown`}`}${(n?.trim()?.length??0)>0?` (${n})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,r)}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 fe=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 pe=class extends de{constructor(t){super(),this.options=t,this.eventEmitter=new e,this.connectionGeneration=0,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/polling/v1`,t.baseUrl),this.pollingIntervalSeconds=t.pollingInterval??60}async connect(e,t){let n=++this.connectionGeneration;this.clearPollingInterval();let r=await this.options.clientSession;if(n!==this.connectionGeneration)return this;try{await this.fetchConfigs(e,t,r)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e,t,r).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}close(){this.connectionGeneration++,super.close()}async fetchConfigs(e,t,n){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let r=await fe(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:n.instanceId,ephemeral:n.ephemeral,lastUpdateTimestamp:this.lastUpdateTimestamp})},this.logger);if(await this.handleNonOkResponse(r),r.status==200){let e=JSON.parse(await r.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 me=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,he=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!me(t))return!1;return!0},ge=e=>e==null||typeof e==`string`&&he(e),_e=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},ve=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},ye=e=>{let t=e?.kind;return ge(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:ve(_e(t),128)}},be=e=>e>=55296&&e<=56319,xe=e=>e>=56320&&e<=57343,Se=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<=127?t+=1:r<=2047?t+=2:be(r)&&n+1<e.length&&xe(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t},Ce=(e,t,n)=>{if(e.kind===`stay-offline`)return{kind:`no cache`,reason:`offline mode`};if(t?.enabled===!1)return{kind:`no cache`,reason:`turned off`};let r=t?.provider??n?.(e.clientSdkKey);return r?{kind:`cache`,provider:r,clientSdkKey:e.clientSdkKey}:{kind:`no cache`,reason:`no provider available`}},Q=(e,t)=>{let n=e?.kind??`user`;return e?.id==null?{contextKind:n,anonymousInstanceId:t}:{contextKind:n,contextId:e.id}},we=(e,t)=>e.contextKind===t.contextKind?`contextId`in e&&`contextId`in t?e.contextId===t.contextId:`anonymousInstanceId`in e&&`anonymousInstanceId`in t?e.anonymousInstanceId===t.anonymousInstanceId:!1:!1,Te=(e,t,n)=>n?`live values already arrived`:we(e.contextTag,t)?`adopt`:`context mismatch`,Ee=e=>{if(!e||typeof e!=`object`)return!1;let{contextKind:t,contextId:n,anonymousInstanceId:r}=e;return typeof t==`string`?typeof n==`string`||typeof r==`string`:!1},De=e=>!e||typeof e!=`object`||Array.isArray(e)?!1:Object.values(e).every(e=>e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.key==`string`),Oe=(e,t)=>{if(!t||typeof t!=`object`)return!1;let n=t;return n.formatVersion===1&&n.clientSdkKey===e&&Ee(n.contextTag)&&typeof n.environmentId==`string`&&typeof n.projectId==`string`&&De(n.configs)&&typeof n.receivedAt==`number`};var ke=class{constructor(e,t,n){this.provider=e,this.clientSdkKey=t,this.logger=n,this.warned=new Set,this.writing=!1}read(){return this.pendingRead??=this.readEntry(),this.pendingRead}replace(e){this.queuedCachedValues=e,this.writeQueued()}async readEntry(){let e;try{e=await this.provider.read()}catch(e){return this.warnOnce(`read failed`,`Could not read the values kept on the device, starting without them:`,e),{outcome:`failed`}}if(e==null||e===``)return{outcome:`nothing stored`};let t=this.parseEntry(e);return t?{outcome:`stored`,cachedValues:t}:(this.warnOnce(`unreadable`,`The values kept on the device could not be read and were removed, starting without them`),await this.removeEntry(),{outcome:`unreadable`})}parseEntry(e){try{let t=JSON.parse(e);return Oe(this.clientSdkKey,t)?t:void 0}catch{return}}async writeQueued(){if(!this.writing){this.writing=!0;try{for(;this.queuedCachedValues;){let e=this.queuedCachedValues;this.queuedCachedValues=void 0,await this.writeEntry(e)}}finally{this.writing=!1}}}async writeEntry(e){let t={formatVersion:1,clientSdkKey:this.clientSdkKey,...e},n=JSON.stringify(t),r=Se(n),i=this.provider.sizeLimit();if(r>i){this.warnOnce(`over the size limit`,`The values received (${r} bytes) exceed the caching provider's limit of ${i} bytes, so no values are kept on the device`),await this.removeEntry();return}try{await this.provider.write(n)}catch(e){this.warnOnce(`write failed`,`Could not keep the values on the device:`,e)}}async removeEntry(){try{await this.provider.remove()}catch(e){this.warnOnce(`remove failed`,`Could not remove the values kept on the device:`,e)}}warnOnce(e,t,...n){this.warned.has(e)||(this.warned.add(e),this.logger.warn(`[ConfigDirectorClient] ${t}`,...n))}},Ae=class t{static from(e,n,r,i,a){return typeof n==`object`?new t(e,void 0,r,n,a):new t(e,n,r,i,a)}constructor(t,n,r,i,a){this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.servingCachedValues=!1,this.cachedValuesAdoptionStarted=!1,this.logger=i?.logger??z(),this.clientSession=ue(this.logger,a?.instanceIdStorage),this.timeout=i?.connection?.timeout??3e3;let o=a?.urlFactory??V;this.connectionPlan=ne(n,i?.connection,o),this.cachedValuesStore=this.buildCachedValuesStore(Ce(this.connectionPlan,i?.caching,a?.platformCachingProvider)),this.telemetryClient=this.buildTelemetryClient(t,i),this.transport=a?.transport??this.buildTransport(r,i,o,a),this.transport.on(`configSetReceived`,e=>{this.hasReceivedConfigSet=!0,this.servingCachedValues=!1,this.readyResolve?.();let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs={...this.configSet.configs,...e.configs},this.keepValuesOnTheDevice(this.configSet);let n=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.initializing=!1,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`,i?.hooks?.clientReady),this.registerHandler(`configEvaluated`,i?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,i?.hooks?.configsUpdated),this.registerHandler(`contextUpdated`,i?.hooks?.contextUpdated),this.registerHandler(`connectionError`,i?.hooks?.connectionError),this.registerHandler(`cachedValuesLoaded`,i?.hooks?.cachedValuesLoaded)}buildCachedValuesStore(e){switch(e.kind){case`no cache`:this.logger.debug(`[ConfigDirectorClient] No values are kept on the device: ${e.reason}`);return;case`cache`:{let t=new ke(e.provider,e.clientSdkKey,this.logger);return t.read(),t}}}startCachedValuesAdoption(){let e=this.cachedValuesStore;!e||this.cachedValuesAdoptionStarted||(this.cachedValuesAdoptionStarted=!0,this.adoptCachedValues(e))}async adoptCachedValues(e){let t=await e.read();switch(t.outcome){case`nothing stored`:case`unreadable`:case`failed`:return;case`stored`:break}let{instanceId:n}=await this.clientSession,r=Q(this.submittedContext,n),i=Te(t.cachedValues,r,this.hasReceivedConfigSet);switch(i){case`adopt`:this.serveCachedValues(t.cachedValues);return;case`live values already arrived`:case`context mismatch`:this.logger.debug(`[ConfigDirectorClient] The values kept on the device were not adopted: ${i}`);return}}serveCachedValues(e){let{environmentId:t,projectId:n,configs:r}=e;this.configSet={environmentId:t,projectId:n,configs:r,kind:`full`},this.servingCachedValues=!0;let i=Object.keys(r);this.emit(`cachedValuesLoaded`,{}),this.emit(`configsUpdated`,{keys:i,removedKeys:[]}),this.updateWatchers(i),this.logger.debug(`[ConfigDirectorClient] Serving the values kept on the device until live values arrive:`,{keys:i})}keepValuesOnTheDevice(e){let t=this.cachedValuesStore;if(!t)return;let n=this.submittedContext,r=Date.now();this.clientSession.then(({instanceId:i})=>t.replace({contextTag:Q(n,i),environmentId:e.environmentId,projectId:e.projectId,configs:e.configs,receivedAt:r}))}servedReason(e){return this.servingCachedValues&&e===`found-match`?`cached`:e}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)}pollingIntervalFor(e,t){if(e!==`polling`)return;let n=H(t,{defaultSeconds:60,minimumSeconds:30});return n.warning&&this.logger.warn(`[ConfigDirectorClient] ${n.warning}`),n.seconds}buildTelemetryClient(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return B;case`connect`:return e({clientSdkKey:n.clientSdkKey,baseUrl:n.baseUrl,logger:this.logger,metadata:t?.metadata})}}buildTransport(e,t,n,r){let i=this.connectionPlan;switch(i.kind){case`stay-offline`:return new S(i.source);case`connect`:return new(this.getTransportConstructor(i.mode))({clientSession:this.clientSession,clientSdkKey:i.clientSdkKey,baseUrl:i.baseUrl,resolveUrl:n,metaContext:{...t?.metadata,sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:G(),host:K()},logger:this.logger,fetch:r?.fetch,connectionRetryDelay:r?.connectionRetryDelay??(e=>2**Math.min(e,9)*1e3),pollingInterval:this.pollingIntervalFor(i.mode,t?.connection?.pollingInterval)})}}getTransportConstructor(e){switch(e){case`polling`:return pe;case`streaming`:return ee}}async initialize(e){this.hasReceivedConfigSet||(this.initializing=!0),await this.submitContext(e,`initialization`)}async updateContext(e){switch(this.connectionPlan.kind){case`connect`:await this.submitContext(e,`context update`);return;case`stay-offline`:this.storeContext(this.admittedContextFor(e,`context update`));return}}storeContext(e){this.currentContext=e,this.emit(`contextUpdated`,{context:e})}async submitContext(e,t){await this.connectToTransport(this.admittedContextFor(e,t),t)}admittedContextFor(e,t){let n=ye(e);switch(n.outcome){case`admitted`:return n.context;case`ignored`:this.logger.error(`[ConfigDirectorClient] Ignored the context supplied for ${t} because its kind '${n.kindSample}' is invalid; continuing as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),this.telemetryClient.recordInvalidContext(n.kindSample);return}}get context(){return this.currentContext}async connectToTransport(e,t){this.submittedContext=e,t===`initialization`&&this.startCachedValuesAdoption();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,t),this.currentContext=e,this.telemetryClient.updateContext(e).catch(e=>this.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,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. ${this.timeoutWarningDetails()}`)}catch(e){if(e instanceof r)throw this.initializing=!1,e;this.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}timeoutWarningDetails(){switch(this.connectionPlan.kind){case`connect`:return`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`;case`stay-offline`:return`The offline values were not delivered, so configs return the default value.`}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.getValueFromConfigState(e,t,n.defaultValue);n.handler(r)})}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:w(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let r=D(t,n),i=this.servedReason(r.reason);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:i}),this.dispatchEvaluationEvent({key:e,value:r.parsedValue,valueId:r.parsedValueId??void 0,isDefaultValue:r.usedDefault,reason:i,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)}}validateDefaultValue(e){if(e==null)throw new n(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new n(`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(){switch(this.connectionPlan.kind){case`stay-offline`:return;case`connect`:this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1;return}}async resumeNetwork(){switch(this.connectionPlan.kind){case`stay-offline`:return;case`connect`:await this.connectToTransport(this.currentContext,`network resume`);return}}async close(){this.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(this.timeoutTimer),this.readyResolve?.(!0),this.telemetryClient.close().catch(e=>this.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,e)),this.transport.close(),this.ready=!1,this.initializing=!1}dispose(){this.clear(),this.close()}};const $=Symbol.for(`@configdirector/installed-test-client`),je=()=>globalThis[$];Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return 262144}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return`configdirector-sdk:cached-values:`}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return je}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return b}});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
function e(t){"@babel/helpers - typeof";return e=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},e(t)}function t(t,n){if(e(t)!=`object`||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,n||`default`);if(e(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(t)}function n(n){var r=t(n,`string`);return e(r)==`symbol`?r:r+``}function r(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){r(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var o=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))}},s=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},c=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},l=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}},u=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},d=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},f=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},p=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},m=class{constructor(e){var t;this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=(t=e.onEvent)==null?(()=>{}):t,this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
+
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
3
|
+
`&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){var t;(t=this.onComment)==null||t.call(this,this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
|
|
4
|
+
`)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent(a(a({},this.currentEvent),{},{id:this.lastEventId,data:e})),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
|
|
5
|
+
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:if(/^\d+$/.test(e.value)){var t;(t=this.onRetry)==null||t.call(this,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 h=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var g=class{constructor(e){var t,n;this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=h.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers=a({Accept:`text/event-stream`},e.headers);let r=e.body;this.body=typeof r==`function`?r:()=>r,this.requestOptions={method:(t=e.method)==null?`GET`:t,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=(n=e.fetch)==null?((e,t)=>fetch(e,t)):n,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===h.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=h.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=h.CONNECTING,this._fetch(this.url,a(a({},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){var t=this;let{body:n,status:r}=e;if(r===204){t.disconnected();return}if(r>=400){t.scheduleReconnect({status:r});return}if(!n)throw new d(`The server response did not have a body`);t._readyState=h.OPEN,t._onConnect(),t.reconnectAttempt=0;let i=new m({onEvent:e=>{typeof e.id==`string`&&(t.lastEventId=e.id),t._onMessage(e)},onComment:e=>t._onComment(e),onRetry:e=>t.serverReconnectionTime=e});await t.readResponseStream(n,i),t.scheduleReconnect({status:r,error:new u(`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=h.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return a(a({},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=h.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new p(`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 f(`${n} must be a function`);return e}};const _=e=>new g(e);var v=class{constructor(e){this.options=e,this.eventEmitter=new o,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){var n=this;let r=++n.connectionGeneration,i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;n.eventSource&&n.close();let a=new Promise((t,r)=>{n.eventSource=_({url:n.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:n.options.fetch,body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:i.instanceId,ephemeral:i.ephemeral}),onMessage:({data:e})=>{n.dispatchMessage(e)},onConnect:()=>{n.logger.debug(`[StreamingTransport] Connected`),t(n)},shouldReconnect:e=>{let t=!n.isStatusFatal(e.status);if(!t){let t=n.prepareFatalError(e.status,e.error);n.eventEmitter.emit(`connectionError`,t),r(t)}return t},calculateReconnectDelay:e=>{let t=n.options.connectionRetryDelay(e.attempt),r=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?n.logger.info(r):n.logger.warn(r),t},onError:e=>{n.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{n.logger.debug(`[StreamingTransport] Disconnected`)}}),n.eventSource.connect()});return clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,Promise.race([a,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(n),t)})]).finally(()=>clearTimeout(n.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==null?0:e;return new s(`${`Connection failed with status: ${e==null?`unknown`:e}.`}${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(){var e;this.connectionGeneration++,(e=this.eventSource)==null||e.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const ee=(e,t)=>{if(e.trim().length==0)throw new c(`Invalid config key. The key of a value cannot be empty.`);return te(e,t)},te=(e,t)=>{switch(typeof t){case`boolean`:return{type:`boolean`,value:t?`true`:`false`};case`number`:return y(e,t);case`string`:return{type:`string`,value:t};case`object`:if(t!==null)return x(e,t,``),{type:`json`,value:JSON.stringify(t)}}throw new c(`Invalid value for '${e}': ${w(t)}. Use a boolean, a number, a string, a plain object, or an array.`)},y=(e,t)=>{if(!Number.isFinite(t))throw new c(`Invalid value for '${e}': ${w(t)} is not a finite number.`);if(Number.isInteger(t)){if(!Number.isSafeInteger(t))throw new c(`Invalid value for '${e}': ${t} is not a safe integer, so the SDK could not read it back exactly.`);return{type:`integer`,value:String(t)}}return{type:`float`,value:b(t)}},b=e=>{let t=String(e),n=t.indexOf(`e-`);if(n<0)return t;let r=t.startsWith(`-`)?`-`:``,[i=``,a=``]=t.slice(r.length,n).split(`.`),o=Number(t.slice(n+2))-i.length;return`${r}0.${`0`.repeat(o)}${i}${a}`},x=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw S(e,n,`${w(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>x(e,t,`${n}[${r}]`));return}if(C(t)){for(let[r,i]of Object.entries(t))x(e,i,n?`${n}.${r}`:r);return}throw S(e,n,`${w(t)} cannot be encoded as JSON`)}},S=(e,t,n)=>new c(`Invalid value for '${e}'${t?` at '${t}'`:``}: ${n}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),C=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},w=e=>{if(e===null)return`null`;if(typeof e==`function`)return`a function`;if(typeof e==`object`){var t,n;return`a ${(t=(n=e.constructor)==null?void 0:n.name)==null?`object`:t} instance`}return typeof e==`symbol`?`a symbol`:String(e)},T=(e,t,n,r)=>{let i=ee(t,n);return{id:e,key:t,type:i.type,value:i.value,valueId:r}},E={environmentId:`offline`,projectId:`offline`};var D=class{constructor(e){this.source=e,this.emitter=new o,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t)}async connect(){var e=this;let t=ne(e.source);return e.emitter.emit(`configSetReceived`,a(a({},E),{},{kind:`full`,configs:t})),e}clear(){this.emitter.clear()}close(){}dispose(){this.clear()}};const ne=e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return re(e.values);case`rejected`:throw new l(e.message)}},re=e=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,T(`offline:${e}`,e,t,void 0)]))}catch(e){throw e instanceof c?new l(`The offline values could not be loaded. ${e.message}`):e}},ie=(e,t,n)=>{var r;if((t==null?void 0:t.mode)===`offline`)return{kind:`stay-offline`,source:oe(t)};let i=(r=t==null?void 0:t.mode)==null?`streaming`:r;if(!e||e.trim().length==0)throw new c(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`);return(t==null?void 0:t.values)===void 0?{kind:`connect`,mode:i,clientSdkKey:e,baseUrl:ae(t==null?void 0:t.url,n)}:{kind:`stay-offline`,source:{kind:`rejected`,message:`The connection option 'values' applies only when the connection mode is 'offline', but the mode is '${i}'.`}}},ae=(e,t)=>{if(!e)return`https://client-sdk-api.configdirector.com`;try{return t(e)}catch(t){throw new c(`Invalid base URL '${e}'. Parsing failed: ${t}`)}},oe=e=>e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values},O=e=>{let t=typeof e;if(t===`object`)try{var n,r;return(n=(r=e.constructor)==null?void 0:r.name)==null?t:n}catch(e){return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch(e){return t}return t},k=e=>e===`number`||e===`bigint`,se=new Set([`boolean`,`integer`,`float`]),ce=(e,t)=>{let n=e.value,r=O(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return P(n,t,r,e.valueId);if(typeof t==`string`)return se.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=le(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(k(typeof t)&&e.type===`integer`){let i=A(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(k(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=j(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`}},le=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},A=e=>{let t=M(e);return t==null?void 0:Math.trunc(t)},j=e=>M(e),M=e=>{if(!e||!N(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},N=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},P=(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 F(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(e){return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},F=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},I={off:-1,error:0,warn:1,info:2,debug:3},L=()=>{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,a(a({},e),{},{fractionalSecondDigits:3}))}catch(t){return new Intl.DateTimeFormat(void 0,e)}};var R=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=L()}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){if(I[this.level]>=I[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},z=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const B=(e,t)=>new R(e==null?`warn`:e,t==null?new z:t),V={updateContext:async()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>{},close:async()=>{}},H=(e,t)=>new URL(e,t==null?void 0:t.toString()),U=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},W=()=>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)}),G=e=>{try{return e(globalThis)}catch(e){return}},ue=()=>G(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),de=()=>G(e=>{var t;return(t=e.location)==null?void 0:t.host}),K=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},q=`configdirector-sdk:instance-id`,J=1e3,fe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Y=(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},X=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=Y(n,2166136261);return Y(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},pe=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||!fe.test(n)?!1:i===X(n,r)},me=async(e,t)=>{let n;try{n=await e.getItem(q)}catch(e){return t.debug(`[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one`,e),{outcome:`failed`}}if(typeof n!=`string`||n===``)return{outcome:`nothing usable`};let r;try{r=JSON.parse(n)}catch(e){return t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`),{outcome:`nothing usable`}}return pe(r)?{outcome:`stored`,instanceId:r.id}:(t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`})},he=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:X(t,r)};try{return await e.setItem(q,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},ge=async(e,t,n,r)=>{let i=await me(e,r);switch(i.outcome){case`stored`:return{instanceId:i.instanceId};case`failed`:return{instanceId:t,ephemeral:!0};case`nothing usable`:break}return n.passed?{instanceId:t,ephemeral:!0}:await he(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},_e=(e,t=K())=>{let n=W();if(!t)return e.debug(`[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id`),Promise.resolve({instanceId:n,ephemeral:!0});let r={passed:!1},i,a=new Promise(t=>{i=setTimeout(()=>{r.passed=!0,e.warn(`[ConfigDirectorClient] The instance id storage did not respond within ${J}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},J)});return Promise.race([ge(t,n,r,e),a]).finally(()=>clearTimeout(i))};var ve=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){var t=this;if(!e.ok)throw t.isStatusFatal(e.status)?(t.fatalError=!0,t.close(),t.prepareFatalResponseStatusError(e.status,await e.text())):new s(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new s(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new s(`Failed to parse the response from the server: ${e}`):new s(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){var n,r;let i=e==null?0:e;return new s(`${`Connection failed with status: ${e==null?`unknown`:e}`}${((n=t==null||(r=t.trim())==null?void 0:r.length)==null?0:n)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,i)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return(e==null?void 0:e.name)===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const ye=async(e,t,n,r)=>{let i=new AbortController,o=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(),a(a({},n),{},{signal:i.signal}));return clearTimeout(o),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(o),e}};var be=class extends ve{constructor(e){var t;super(),this.options=e,this.eventEmitter=new o,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=(t=e.pollingInterval)==null?60:t}async connect(e,t){var n=this;let r=++n.connectionGeneration;n.clearPollingInterval();let i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;try{await n.fetchConfigs(e,t,i)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t,i).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}close(){this.connectionGeneration++,super.close()}async fetchConfigs(e,t,n){var r=this;if(r.fatalError){r.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let i=await ye(t,r.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:r.options.metaContext,clientSdkKey:r.options.clientSdkKey,instanceId:n.instanceId,ephemeral:n.ephemeral,lastUpdateTimestamp:r.lastUpdateTimestamp})},r.logger);if(await r.handleNonOkResponse(i),i.status==200){let e=JSON.parse(await i.text());r.lastUpdateTimestamp=e.timestamp,r.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{r.handleFetchError(e)}catch(e){throw r.fatalError&&r.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 xe=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,Se=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!xe(t))return!1;return!0},Ce=e=>e==null||typeof e==`string`&&Se(e),we=e=>{if(typeof e==`string`)return e;try{return String(e)}catch(t){return Object.prototype.toString.call(e)}},Te=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},Ee=e=>{let t=e==null?void 0:e.kind;return Ce(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:Te(we(t),128)}},De=e=>e>=55296&&e<=56319,Oe=e=>e>=56320&&e<=57343,ke=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<=127?t+=1:r<=2047?t+=2:De(r)&&n+1<e.length&&Oe(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t},Z=`configdirector-sdk:cached-values:`,Ae=256*1024,je=(e,t,n)=>{var r;if(e.kind===`stay-offline`)return{kind:`no cache`,reason:`offline mode`};if((t==null?void 0:t.enabled)===!1)return{kind:`no cache`,reason:`turned off`};let i=(r=t==null?void 0:t.provider)==null?n==null?void 0:n(e.clientSdkKey):r;return i?{kind:`cache`,provider:i,clientSdkKey:e.clientSdkKey}:{kind:`no cache`,reason:`no provider available`}},Q=(e,t)=>{var n;let r=(n=e==null?void 0:e.kind)==null?`user`:n;return(e==null?void 0:e.id)==null?{contextKind:r,anonymousInstanceId:t}:{contextKind:r,contextId:e.id}},Me=(e,t)=>e.contextKind===t.contextKind?`contextId`in e&&`contextId`in t?e.contextId===t.contextId:`anonymousInstanceId`in e&&`anonymousInstanceId`in t?e.anonymousInstanceId===t.anonymousInstanceId:!1:!1,Ne=(e,t,n)=>n?`live values already arrived`:Me(e.contextTag,t)?`adopt`:`context mismatch`,Pe=e=>{if(!e||typeof e!=`object`)return!1;let{contextKind:t,contextId:n,anonymousInstanceId:r}=e;return typeof t==`string`?typeof n==`string`||typeof r==`string`:!1},Fe=e=>!e||typeof e!=`object`||Array.isArray(e)?!1:Object.values(e).every(e=>e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.key==`string`),Ie=(e,t)=>{if(!t||typeof t!=`object`)return!1;let n=t;return n.formatVersion===1&&n.clientSdkKey===e&&Pe(n.contextTag)&&typeof n.environmentId==`string`&&typeof n.projectId==`string`&&Fe(n.configs)&&typeof n.receivedAt==`number`};var Le=class{constructor(e,t,n){this.provider=e,this.clientSdkKey=t,this.logger=n,this.warned=new Set,this.writing=!1}read(){return this.pendingRead!=null||(this.pendingRead=this.readEntry()),this.pendingRead}replace(e){this.queuedCachedValues=e,this.writeQueued()}async readEntry(){var e=this;let t;try{t=await e.provider.read()}catch(t){return e.warnOnce(`read failed`,`Could not read the values kept on the device, starting without them:`,t),{outcome:`failed`}}if(t==null||t===``)return{outcome:`nothing stored`};let n=e.parseEntry(t);return n?{outcome:`stored`,cachedValues:n}:(e.warnOnce(`unreadable`,`The values kept on the device could not be read and were removed, starting without them`),await e.removeEntry(),{outcome:`unreadable`})}parseEntry(e){try{let t=JSON.parse(e);return Ie(this.clientSdkKey,t)?t:void 0}catch(e){return}}async writeQueued(){var e=this;if(!e.writing){e.writing=!0;try{for(;e.queuedCachedValues;){let t=e.queuedCachedValues;e.queuedCachedValues=void 0,await e.writeEntry(t)}}finally{e.writing=!1}}}async writeEntry(e){var t=this;let n=a({formatVersion:1,clientSdkKey:t.clientSdkKey},e),r=JSON.stringify(n),i=ke(r),o=t.provider.sizeLimit();if(i>o){t.warnOnce(`over the size limit`,`The values received (${i} bytes) exceed the caching provider's limit of ${o} bytes, so no values are kept on the device`),await t.removeEntry();return}try{await t.provider.write(r)}catch(e){t.warnOnce(`write failed`,`Could not keep the values on the device:`,e)}}async removeEntry(){var e=this;try{await e.provider.remove()}catch(t){e.warnOnce(`remove failed`,`Could not remove the values kept on the device:`,t)}}warnOnce(e,t,...n){this.warned.has(e)||(this.warned.add(e),this.logger.warn(`[ConfigDirectorClient] ${t}`,...n))}},Re=class e{static from(t,n,r,i,a){return typeof n==`object`?new e(t,void 0,r,n,a):new e(t,n,r,i,a)}constructor(e,t,n,r,i){var s,c,l,u,d,f,p,m,h,g,_;this.handlersMap=new Map,this.eventEmitter=new o,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.servingCachedValues=!1,this.cachedValuesAdoptionStarted=!1,this.logger=(s=r==null?void 0:r.logger)==null?B():s,this.clientSession=_e(this.logger,i==null?void 0:i.instanceIdStorage),this.timeout=(c=r==null||(l=r.connection)==null?void 0:l.timeout)==null?3e3:c;let v=(u=i==null?void 0:i.urlFactory)==null?H:u;this.connectionPlan=ie(t,r==null?void 0:r.connection,v),this.cachedValuesStore=this.buildCachedValuesStore(je(this.connectionPlan,r==null?void 0:r.caching,i==null?void 0:i.platformCachingProvider)),this.telemetryClient=this.buildTelemetryClient(e,r),this.transport=(d=i==null?void 0:i.transport)==null?this.buildTransport(n,r,v,i):d,this.transport.on(`configSetReceived`,e=>{var t;this.hasReceivedConfigSet=!0,this.servingCachedValues=!1,(t=this.readyResolve)==null||t.call(this);let n=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs=a(a({},this.configSet.configs),e.configs),this.keepValuesOnTheDevice(this.configSet);let r=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:r,removedKeys:n}),this.updateWatchers([...r,...n]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:r,removedKeys:n})}),this.transport.on(`connectionError`,e=>{this.initializing=!1,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==null||(f=r.hooks)==null?void 0:f.clientReady),this.registerHandler(`configEvaluated`,r==null||(p=r.hooks)==null?void 0:p.configEvaluated),this.registerHandler(`configsUpdated`,r==null||(m=r.hooks)==null?void 0:m.configsUpdated),this.registerHandler(`contextUpdated`,r==null||(h=r.hooks)==null?void 0:h.contextUpdated),this.registerHandler(`connectionError`,r==null||(g=r.hooks)==null?void 0:g.connectionError),this.registerHandler(`cachedValuesLoaded`,r==null||(_=r.hooks)==null?void 0:_.cachedValuesLoaded)}buildCachedValuesStore(e){switch(e.kind){case`no cache`:this.logger.debug(`[ConfigDirectorClient] No values are kept on the device: ${e.reason}`);return;case`cache`:{let t=new Le(e.provider,e.clientSdkKey,this.logger);return t.read(),t}}}startCachedValuesAdoption(){let e=this.cachedValuesStore;!e||this.cachedValuesAdoptionStarted||(this.cachedValuesAdoptionStarted=!0,this.adoptCachedValues(e))}async adoptCachedValues(e){var t=this;let n=await e.read();switch(n.outcome){case`nothing stored`:case`unreadable`:case`failed`:return;case`stored`:break}let{instanceId:r}=await t.clientSession,i=Q(t.submittedContext,r),a=Ne(n.cachedValues,i,t.hasReceivedConfigSet);switch(a){case`adopt`:t.serveCachedValues(n.cachedValues);return;case`live values already arrived`:case`context mismatch`:t.logger.debug(`[ConfigDirectorClient] The values kept on the device were not adopted: ${a}`);return}}serveCachedValues(e){let{environmentId:t,projectId:n,configs:r}=e;this.configSet={environmentId:t,projectId:n,configs:r,kind:`full`},this.servingCachedValues=!0;let i=Object.keys(r);this.emit(`cachedValuesLoaded`,{}),this.emit(`configsUpdated`,{keys:i,removedKeys:[]}),this.updateWatchers(i),this.logger.debug(`[ConfigDirectorClient] Serving the values kept on the device until live values arrive:`,{keys:i})}keepValuesOnTheDevice(e){let t=this.cachedValuesStore;if(!t)return;let n=this.submittedContext,r=Date.now();this.clientSession.then(({instanceId:i})=>t.replace({contextTag:Q(n,i),environmentId:e.environmentId,projectId:e.projectId,configs:e.configs,receivedAt:r}))}servedReason(e){return this.servingCachedValues&&e===`found-match`?`cached`:e}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)}pollingIntervalFor(e,t){if(e!==`polling`)return;let n=U(t,{defaultSeconds:60,minimumSeconds:30});return n.warning&&this.logger.warn(`[ConfigDirectorClient] ${n.warning}`),n.seconds}buildTelemetryClient(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return V;case`connect`:return e({clientSdkKey:n.clientSdkKey,baseUrl:n.baseUrl,logger:this.logger,metadata:t==null?void 0:t.metadata})}}buildTransport(e,t,n,r){let i=this.connectionPlan;switch(i.kind){case`stay-offline`:return new D(i.source);case`connect`:var o,s;return new(this.getTransportConstructor(i.mode))({clientSession:this.clientSession,clientSdkKey:i.clientSdkKey,baseUrl:i.baseUrl,resolveUrl:n,metaContext:a(a({},t==null?void 0:t.metadata),{},{sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:ue(),host:de()}),logger:this.logger,fetch:r==null?void 0:r.fetch,connectionRetryDelay:(o=r==null?void 0:r.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):o,pollingInterval:this.pollingIntervalFor(i.mode,t==null||(s=t.connection)==null?void 0:s.pollingInterval)})}}getTransportConstructor(e){switch(e){case`polling`:return be;case`streaming`:return v}}async initialize(e){var t=this;t.hasReceivedConfigSet||(t.initializing=!0),await t.submitContext(e,`initialization`)}async updateContext(e){var t=this;switch(t.connectionPlan.kind){case`connect`:await t.submitContext(e,`context update`);return;case`stay-offline`:t.storeContext(t.admittedContextFor(e,`context update`));return}}storeContext(e){this.currentContext=e,this.emit(`contextUpdated`,{context:e})}async submitContext(e,t){var n=this;await n.connectToTransport(n.admittedContextFor(e,t),t)}admittedContextFor(e,t){let n=Ee(e);switch(n.outcome){case`admitted`:return n.context;case`ignored`:this.logger.error(`[ConfigDirectorClient] Ignored the context supplied for ${t} because its kind '${n.kindSample}' is invalid; continuing as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),this.telemetryClient.recordInvalidContext(n.kindSample);return}}get context(){return this.currentContext}async connectToTransport(e,t){var n=this;n.submittedContext=e,t===`initialization`&&n.startCachedValuesAdoption();try{n.ready=!1,n.readyPromise=new Promise(e=>{n.readyResolve=e}).then(e=>{e||(n.ready=!0,n.initializing=!1,n.emit(`clientReady`,{action:t}),n.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let r=new Date().getTime();await n.transport.connect(e==null?{}:e,n.timeout,t),n.currentContext=e,n.telemetryClient.updateContext(e).catch(e=>n.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,e)),n.emit(`contextUpdated`,{context:e});let i=new Date().getTime()-r,a=n.timeout-i;clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,a>0&&await Promise.race([n.readyPromise,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(),a)})]).finally(()=>clearTimeout(n.timeoutTimer)),n.ready||n.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${n.timeout}ms. ${n.timeoutWarningDetails()}`)}catch(e){if(e instanceof l)throw n.initializing=!1,e;n.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}timeoutWarningDetails(){switch(this.connectionPlan.kind){case`connect`:return`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`;case`stay-offline`:return`The offline values were not delivered, so configs return the default value.`}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){var t,n;let r=(t=this.configSet)==null?void 0:t.configs[e];(n=this.handlersMap.get(e))==null||n.forEach(t=>{let n=this.getValueFromConfigState(e,r,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==null||n.splice(e,1))}else n.splice(0)}getValue(e,t){var n;this.validateDefaultValue(t);let r=(n=this.configSet)==null?void 0:n.configs[e];return this.getValueFromConfigState(e,r,t)}getValueFromConfigState(e,t,n){var r,i;if(!t){var a;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:(a=this.currentContext)==null?void 0:a.id,key:e,defaultValue:n,requestedType:O(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let o=ce(t,n),s=this.servedReason(o.reason);return this.telemetryClient.evaluatedConfig({contextId:(r=this.currentContext)==null?void 0:r.id,type:t.type,key:e,defaultValue:n,requestedType:o.requestedType,evaluatedValue:o.parsedValue,evaluatedValueId:o.parsedValueId,usedDefault:o.usedDefault,evaluationReason:s}),this.dispatchEvaluationEvent({key:e,value:o.parsedValue,valueId:(i=o.parsedValueId)==null?void 0:i,isDefaultValue:o.usedDefault,reason:s,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${o.parsedValue}'`),o.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)}}validateDefaultValue(e){if(e==null)throw new c(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new c(`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(){switch(this.connectionPlan.kind){case`stay-offline`:return;case`connect`:this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1;return}}async resumeNetwork(){var e=this;switch(e.connectionPlan.kind){case`stay-offline`:return;case`connect`:await e.connectToTransport(e.currentContext,`network resume`);return}}async close(){var e=this,t;e.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(e.timeoutTimer),(t=e.readyResolve)==null||t.call(e,!0),e.telemetryClient.close().catch(t=>e.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,t)),e.transport.close(),e.ready=!1,e.initializing=!1}dispose(){this.clear(),this.close()}};const $=Symbol.for(`@configdirector/installed-test-client`),ze=()=>globalThis[$];export{Ae as a,V as c,s as d,c as f,Z as i,B as l,a as m,ze as n,K as o,o as p,Re as r,H as s,$ as t,T as u};
|
|
6
|
+
//# sourceMappingURL=installedTestClient-DxB-5uP1.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"installedTestClient-DxB-5uP1.mjs","names":["this","this","this","this","this","this","this"],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/errors.ts","../../eventsource/src/errors.ts","../../eventsource/src/EventSourceParser.ts","../../eventsource/src/types.ts","../../eventsource/src/EventSourceClient.ts","../../eventsource/src/index.ts","../../js-client-core/src/StreamingTransport.ts","../../shared/src/native-values.ts","../../js-client-core/src/native-values.ts","../../js-client-core/src/OfflineTransport.ts","../../shared/src/constants.ts","../../js-client-core/src/connection-plan.ts","../../shared/src/value-parser.ts","../../shared/src/logger.ts","../../js-client-core/src/logger.ts","../../js-client-core/src/telemetry/discarding.ts","../../shared/src/url.ts","../../shared/src/transport/pollingInterval.ts","../../shared/src/instance-id.ts","../../js-client-core/src/browser-globals.ts","../../js-client-core/src/client-session.ts","../../shared/src/transport/AbstractPollingTransport.ts","../../shared/src/fetchWithTimeout.ts","../../js-client-core/src/PollingTransport.ts","../../shared/src/context-kind.ts","../../shared/src/utf8-byte-length.ts","../../js-client-core/src/cached-values.ts","../../js-client-core/src/DefaultConfigDirectorClient.ts","../../js-client-core/src/installedTestClient.ts"],"sourcesContent":["type EventType = string | symbol;\ntype EventsRecord = Record<EventType, any>;\n\ntype Handler<TEventsRecord extends EventsRecord, TKey extends keyof TEventsRecord> = (\n payload: TEventsRecord[TKey],\n) => void;\n\nexport interface EventProvider<TEventsRecord extends EventsRecord> {\n on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>): void;\n off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>): void;\n clear(): void;\n}\n\nexport class Emitter<TEventsRecord extends EventsRecord> implements EventProvider<TEventsRecord> {\n private handlerMap: Map<keyof TEventsRecord, Array<(payload: any) => void>> = new Map();\n\n on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>) {\n const handlers = this.handlerMap.get(name);\n if (handlers) {\n handlers.push(handler);\n } else {\n this.handlerMap.set(name, [handler]);\n }\n }\n\n once<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n function onceHandler(payload: TEventsRecord[keyof TEventsRecord]) {\n self.off(name, onceHandler);\n handler.apply(self, payload);\n }\n this.on(name, onceHandler);\n }\n\n off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>) {\n const handlers = this.handlerMap.get(name);\n if (!handlers) {\n return;\n }\n\n if (handler) {\n const listenerIndex = handlers.indexOf(handler);\n if (listenerIndex >= 0) {\n handlers.splice(listenerIndex, 1);\n }\n } else {\n this.handlerMap.set(name, []);\n }\n }\n\n clear() {\n this.handlerMap.clear();\n }\n\n emit<TName extends keyof TEventsRecord>(name: TName, payload: TEventsRecord[TName]) {\n const handlers = this.handlerMap.get(name);\n if (!handlers) {\n return;\n }\n\n handlers.slice().map((h) => h(payload));\n }\n}\n","export class ConfigDirectorConnectionError extends Error {\n public override readonly name: string = \"ConfigDirectorConnectionError\";\n public readonly status?: number;\n\n constructor(message: string, status?: number) {\n super(message);\n this.status = status;\n\n Object.setPrototypeOf(this, ConfigDirectorConnectionError.prototype);\n }\n}\n\nexport class ConfigDirectorValidationError extends Error {\n public override readonly name: string = \"ConfigDirectorValidationError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ConfigDirectorValidationError.prototype);\n }\n}\n\nexport class ConfigDirectorInitializationError extends Error {\n public override readonly name: string = \"ConfigDirectorInitializationError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ConfigDirectorInitializationError.prototype);\n }\n}\n","export class StreamClosedError extends Error {\n public override readonly name: string = \"StreamClosedError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, StreamClosedError.prototype);\n }\n}\n\nexport class MissingResponseBodyError extends Error {\n public override readonly name: string = \"MissingResponseBodyError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, MissingResponseBodyError.prototype);\n }\n}\n\nexport class InvalidOptionError extends Error {\n public override readonly name: string = \"InvalidOptionError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, InvalidOptionError.prototype);\n }\n}\n\nexport class ValueOutOfRangeError extends Error {\n public override readonly name: string = \"ValueOutOfRangeError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ValueOutOfRangeError.prototype);\n }\n}\n","import {\n type EventSourceParserOptions,\n type EventSourceMessageHandler,\n type EventSourceCommentHandler,\n type EventParserRetryCallback,\n} from \"./types\";\n\ntype ParsedField = {\n field: string;\n value: string;\n};\n\nexport class EventSourceParser {\n private isFirstChunk = true;\n private bufferedInput = \"\";\n private currentEvent: { type?: string; data: string } = { data: \"\" };\n private lastEventId: string | undefined;\n private onEvent: EventSourceMessageHandler;\n private onRetry: EventParserRetryCallback | undefined;\n private onComment: EventSourceCommentHandler | undefined;\n\n constructor(options: EventSourceParserOptions) {\n this.currentEvent = { data: \"\" };\n this.onEvent = options.onEvent ?? (() => {});\n this.onRetry = options.onRetry;\n this.onComment = options.onComment;\n }\n\n public parse(chunk: string): void {\n let input = chunk;\n\n if (this.isFirstChunk) {\n this.isFirstChunk = false;\n if (input.startsWith(\"\\uFEFF\")) {\n input = input.slice(1);\n } else if (input.startsWith(\"\\xEF\\xBB\\xBF\")) {\n input = input.slice(3);\n }\n }\n\n const lines = this.scanLines(this.bufferedInput + input);\n for (const line of lines) {\n this.dispatchLine(line);\n }\n }\n\n // Per the SSE spec, any data still buffered when the stream ends is discarded —\n // an event requires a terminating empty line to be dispatched.\n public finish(): void {\n this.bufferedInput = \"\";\n }\n\n /**\n * Scans `text` character by character to extract complete lines, recognizing\n * CR, LF, and CRLF as line terminators per the SSE spec. Any unterminated\n * trailing text is buffered and prepended to the next chunk.\n */\n private scanLines(text: string): string[] {\n const lines: string[] = [];\n let lineStart = 0;\n let i = 0;\n\n while (i < text.length) {\n const ch = text[i];\n if (ch === \"\\r\" || ch === \"\\n\") {\n lines.push(text.slice(lineStart, i));\n // Consume CRLF as a single terminator rather than two separate lines.\n if (ch === \"\\r\" && text[i + 1] === \"\\n\") {\n i++;\n }\n i++;\n lineStart = i;\n } else {\n i++;\n }\n }\n\n this.bufferedInput = text.slice(lineStart);\n return lines;\n }\n\n private dispatchLine(line: string): void {\n if (line.startsWith(\":\")) {\n this.onComment?.(this.extractValue(line, 1));\n return;\n }\n\n if (line === \"\") {\n this.emitEvent();\n return;\n }\n\n this.applyField(this.parseField(line));\n }\n\n private emitEvent(): void {\n const data = this.currentEvent.data.endsWith(\"\\n\")\n ? this.currentEvent.data.slice(0, -1)\n : this.currentEvent.data;\n\n if (data !== \"\") {\n this.onEvent({ ...this.currentEvent, id: this.lastEventId, data });\n }\n\n this.currentEvent = { data: \"\" };\n }\n\n private applyField(parsed: ParsedField): void {\n switch (parsed.field) {\n case \"event\":\n this.currentEvent.type = parsed.value;\n break;\n case \"data\":\n this.currentEvent.data += parsed.value + \"\\n\";\n break;\n case \"id\":\n // Spec: ignore id values that contain a null character.\n if (!parsed.value.includes(\"\\0\")) {\n this.lastEventId = parsed.value;\n }\n break;\n case \"retry\":\n if (/^\\d+$/.test(parsed.value)) {\n this.onRetry?.(Number.parseInt(parsed.value, 10));\n }\n break;\n default:\n break;\n }\n }\n\n private parseField(line: string): ParsedField {\n const colon = line.indexOf(\":\");\n if (colon === -1) {\n return { field: line, value: \"\" };\n }\n return { field: line.slice(0, colon), value: this.extractValue(line, colon + 1) };\n }\n\n /** Returns the value portion of a line, stripping a single leading space per spec. */\n private extractValue(line: string, from: number): string {\n return line[from] === \" \" ? line.slice(from + 1) : line.slice(from);\n }\n}\n","export type ReconnectionState = {\n attempt: number;\n serverReconnectionTime: number;\n status?: number | undefined;\n error?: Error | undefined;\n};\n\nexport enum ReadyState {\n OPEN = \"open\",\n CLOSED = \"closed\",\n CONNECTING = \"connecting\",\n}\n\nexport type EventSourceClientOptions = {\n url: { toString(): string } | string;\n method?: string;\n headers?: Record<string, string>;\n body?: string | (() => string);\n mode?: \"cors\" | \"no-cors\" | \"same-origin\";\n credentials?: \"include\" | \"omit\" | \"same-origin\";\n redirect?: \"error\" | \"follow\";\n referrer?: string;\n referrerPolicy?: ReferrerPolicy;\n lastEventId?: string;\n fetch?: (url: string, init: RequestInit) => Promise<Response>;\n onError?: (error: Error) => void;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onMessage?: EventSourceMessageHandler;\n onComment?: EventSourceCommentHandler;\n shouldReconnect?: (state: ReconnectionState) => boolean;\n calculateReconnectDelay?: (state: ReconnectionState) => number;\n};\n\nexport type EventSourceMessage = {\n id?: string | undefined;\n type?: string;\n data: string;\n};\n\nexport type EventSourceMessageHandler = (message: EventSourceMessage) => void;\nexport type EventSourceCommentHandler = (comment: string) => void;\n\nexport type EventParserRetryCallback = (retry: number) => void;\n\nexport type EventSourceParserOptions = {\n onEvent?: EventSourceMessageHandler;\n onRetry?: EventParserRetryCallback;\n onComment?: EventSourceCommentHandler;\n};\n","import {\n InvalidOptionError,\n MissingResponseBodyError,\n StreamClosedError,\n ValueOutOfRangeError,\n} from \"./errors\";\nimport { EventSourceParser } from \"./EventSourceParser\";\nimport {\n type EventSourceClientOptions,\n type EventSourceCommentHandler,\n type EventSourceMessageHandler,\n type ReconnectionState,\n ReadyState,\n} from \"./types\";\n\nexport class EventSourceClient {\n private readonly DEFAULT_SHOULD_RECONNECT = () => true;\n private readonly DEFAULT_CALCULATE_RECONNECT_DELAY = () => this.serverReconnectionTime;\n private readonly url: string;\n private readonly headers?: Record<string, string>;\n private readonly body: () => string | undefined;\n private readonly requestOptions;\n private lastEventId?: string;\n private reconnectAttempt: number = 0;\n private abortController: AbortController = new AbortController();\n private reconnectTimeout: ReturnType<typeof setTimeout> | undefined;\n private _readyState: ReadyState = ReadyState.CLOSED;\n private serverReconnectionTime: number = 2_000;\n private _fetch: (url: string, init: RequestInit) => Promise<Response>;\n private _onError: (error: Error) => void;\n private _onMessage: EventSourceMessageHandler;\n private _onComment: EventSourceCommentHandler;\n private _onConnect: () => void;\n private _onDisconnect: () => void;\n private _shouldReconnect: (state: ReconnectionState) => boolean;\n private _calculateReconnectDelay: (state: ReconnectionState) => number;\n\n constructor(options: EventSourceClientOptions) {\n this.url = options.url.toString();\n this.lastEventId = options.lastEventId;\n this.headers = {\n Accept: \"text/event-stream\",\n ...options.headers,\n };\n const body = options.body;\n this.body = typeof body === \"function\" ? body : () => body;\n this.requestOptions = {\n method: options.method ?? \"GET\",\n mode: options.mode,\n credentials: options.credentials,\n redirect: options.redirect,\n referrer: options.referrer,\n referrerPolicy: options.referrerPolicy,\n };\n this._fetch = options.fetch ?? ((url, init) => fetch(url, init));\n this._onError = this.resolveCallback(options.onError, () => {}, \"onError\");\n this._onConnect = this.resolveCallback(options.onConnect, () => {}, \"onConnect\");\n this._onDisconnect = this.resolveCallback(options.onDisconnect, () => {}, \"onDisconnect\");\n this._onMessage = this.resolveCallback(options.onMessage, () => {}, \"onMessage\");\n this._onComment = this.resolveCallback(options.onComment, () => {}, \"onComment\");\n this._shouldReconnect = this.resolveCallback(\n options.shouldReconnect,\n this.DEFAULT_SHOULD_RECONNECT,\n \"shouldReconnect\",\n );\n this._calculateReconnectDelay = this.resolveCallback(\n options.calculateReconnectDelay,\n this.DEFAULT_CALCULATE_RECONNECT_DELAY,\n \"calculateReconnectDelay\",\n );\n }\n\n public set onError(value: (error: Error) => void) {\n this._onError = this.resolveCallback(value, () => {}, \"onError\");\n }\n\n public set onMessage(value: EventSourceMessageHandler) {\n this._onMessage = this.resolveCallback(value, () => {}, \"onMessage\");\n }\n\n public set onComment(value: EventSourceCommentHandler) {\n this._onComment = this.resolveCallback(value, () => {}, \"onComment\");\n }\n\n public set onConnect(value: () => void) {\n this._onConnect = this.resolveCallback(value, () => {}, \"onConnect\");\n }\n\n public set onDisconnect(value: () => void) {\n this._onDisconnect = this.resolveCallback(value, () => {}, \"onDisconnect\");\n }\n\n public set shouldReconnect(value: (state: ReconnectionState) => boolean) {\n this._shouldReconnect = this.resolveCallback(value, this.DEFAULT_SHOULD_RECONNECT, \"shouldReconnect\");\n }\n\n public set calculateReconnectDelay(value: (state: ReconnectionState) => number) {\n this._calculateReconnectDelay = this.resolveCallback(\n value,\n this.DEFAULT_CALCULATE_RECONNECT_DELAY,\n \"shouldReconnect\",\n );\n }\n\n public get readyState(): ReadyState {\n return this._readyState;\n }\n\n public connect() {\n if (this._readyState !== ReadyState.CLOSED) {\n return;\n }\n\n this.reconnectAttempt = 0;\n this.initiateConnection();\n }\n\n public close() {\n clearTimeout(this.reconnectTimeout);\n this._readyState = ReadyState.CLOSED;\n this.abortController.abort();\n }\n\n private initiateConnection() {\n this.abortController = new AbortController();\n this._readyState = ReadyState.CONNECTING;\n\n this._fetch(this.url, {\n ...this.requestOptions,\n body: this.body(),\n headers: this.buildRequestHeaders(),\n signal: this.abortController.signal,\n cache: \"no-store\",\n })\n .then((response) => this.handleFetchResponse(response))\n .catch((error: Error) => {\n if (error.name === \"AbortError\" || this.abortController.signal.aborted) {\n this.close();\n return;\n }\n\n this._onError(error);\n this.scheduleReconnect({ error });\n });\n }\n\n private async handleFetchResponse(response: Response) {\n const { body, status } = response;\n\n if (status === 204) {\n this.disconnected();\n return;\n }\n\n if (status >= 400) {\n this.scheduleReconnect({ status });\n return;\n }\n\n if (!body) {\n throw new MissingResponseBodyError(\"The server response did not have a body\");\n }\n\n this._readyState = ReadyState.OPEN;\n this._onConnect();\n this.reconnectAttempt = 0;\n\n const parser = new EventSourceParser({\n onEvent: (event) => {\n if (typeof event.id === \"string\") {\n this.lastEventId = event.id;\n }\n this._onMessage(event);\n },\n onComment: (comment) => this._onComment(comment),\n onRetry: (retryDelay) => (this.serverReconnectionTime = retryDelay),\n });\n\n await this.readResponseStream(body, parser);\n\n this.scheduleReconnect({\n status,\n error: new StreamClosedError(\"The server response stream was closed\"),\n });\n }\n\n private async readResponseStream(body: ReadableStream<Uint8Array>, parser: EventSourceParser) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n\n let done = false;\n while (!done) {\n const result = await reader.read();\n if (result.value) {\n parser.parse(decoder.decode(result.value, { stream: true }));\n }\n done = result.done;\n }\n\n parser.finish();\n }\n\n private disconnected() {\n clearTimeout(this.reconnectTimeout);\n this._readyState = ReadyState.CLOSED;\n this._onDisconnect();\n }\n\n private buildRequestHeaders(): Record<string, string> {\n const lastEventIdHeader = this.lastEventId ? { \"Last-Event-ID\": this.lastEventId } : undefined;\n return {\n ...this.headers,\n ...lastEventIdHeader,\n };\n }\n\n private scheduleReconnect(state: { status?: number; error?: Error }) {\n if (this.abortController.signal.aborted) {\n return;\n }\n\n clearTimeout(this.reconnectTimeout);\n this.reconnectAttempt += 1;\n\n const reconnectionState: ReconnectionState = {\n attempt: this.reconnectAttempt,\n status: state.status,\n error: state.error,\n serverReconnectionTime: this.serverReconnectionTime,\n };\n\n if (!this._shouldReconnect(reconnectionState)) {\n this.disconnected();\n return;\n }\n\n this._readyState = ReadyState.CONNECTING;\n let delay = this._calculateReconnectDelay(reconnectionState);\n\n if (!Number.isFinite(delay) || delay < 1 || delay > 1_000 * 60 * 60) {\n this._onError(\n new ValueOutOfRangeError(\n `The calculated reconnect delay is out of range: ${delay}. Defaulting to ${this.serverReconnectionTime}`,\n ),\n );\n delay = this.serverReconnectionTime;\n }\n\n this.reconnectTimeout = setTimeout(() => this.initiateConnection(), delay);\n }\n\n private resolveCallback<T extends (...args: any[]) => any>(\n provided: unknown,\n fallback: T,\n optionName: string,\n ): T {\n if (provided == null) return fallback;\n if (typeof provided !== \"function\") {\n throw new InvalidOptionError(`${optionName} must be a function`);\n }\n return provided as T;\n }\n}\n","import { EventSourceClient } from \"./EventSourceClient\";\nimport { type EventSourceClientOptions } from \"./types\";\n\nexport const createEventSourceClient = (options: EventSourceClientOptions) => {\n return new EventSourceClient(options);\n};\n","import type {\n ConfigDirectorContext,\n ConfigDirectorLogger,\n Transport,\n TransportEvents,\n TransportOptions,\n} from \"./types\";\nimport { Emitter } from \"./Emitter\";\nimport { ConfigDirectorConnectionError } from \"./errors\";\nimport { createEventSourceClient } from \"@eventsource/index\";\nimport type { EventSourceClient } from \"@eventsource/EventSourceClient\";\nimport type { UrlLike } from \"@shared/url\";\n\nexport class StreamingTransport implements Transport {\n private logger: ConfigDirectorLogger;\n private eventSource: EventSourceClient | undefined;\n private eventEmitter = new Emitter<TransportEvents>();\n private url: UrlLike;\n private timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n private connectionGeneration = 0;\n\n constructor(private readonly options: TransportOptions) {\n this.options = options;\n this.logger = options.logger;\n this.url = options.resolveUrl(\"client/sse/v1\", options.baseUrl);\n }\n\n public async connect(context: ConfigDirectorContext, timeout: number): Promise<this> {\n const generation = ++this.connectionGeneration;\n const clientSession = await this.options.clientSession;\n if (generation !== this.connectionGeneration) {\n return this;\n }\n\n if (this.eventSource) {\n this.close();\n }\n\n const eventSourcePromise = new Promise<this>((resolve, reject) => {\n this.eventSource = createEventSourceClient({\n url: this.url,\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n fetch: this.options.fetch,\n body: JSON.stringify({\n givenContext: context,\n metaContext: this.options.metaContext,\n clientSdkKey: this.options.clientSdkKey,\n instanceId: clientSession.instanceId,\n ephemeral: clientSession.ephemeral,\n }),\n\n onMessage: ({ data }) => {\n this.dispatchMessage(data);\n },\n onConnect: () => {\n this.logger.debug(\"[StreamingTransport] Connected\");\n resolve(this);\n },\n shouldReconnect: (state) => {\n const reconnect = !this.isStatusFatal(state.status);\n if (!reconnect) {\n const error = this.prepareFatalError(state.status, state.error);\n this.eventEmitter.emit(\"connectionError\", error);\n reject(error);\n }\n return reconnect;\n },\n calculateReconnectDelay: (state) => {\n const delay = this.options.connectionRetryDelay(state.attempt);\n const logMessage = `[StreamingTransport] Scheduling reconnect attempt #${state.attempt} in ${delay}ms.`;\n if (state.attempt <= 5) {\n this.logger.info(logMessage);\n } else {\n this.logger.warn(logMessage);\n }\n return delay;\n },\n onError: (error) => {\n this.logger.debug(\"[StreamingTransport] Error: \", error);\n },\n onDisconnect: () => {\n this.logger.debug(\"[StreamingTransport] Disconnected\");\n },\n });\n this.eventSource.connect();\n });\n\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n return Promise.race([\n eventSourcePromise,\n new Promise<this>((resolve) => {\n this.timeoutTimer = setTimeout(() => resolve(this), timeout);\n }),\n ]).finally(() => clearTimeout(this.timeoutTimer));\n }\n\n private dispatchMessage(data: string) {\n try {\n const json = JSON.parse(data);\n this.eventEmitter.emit(\"configSetReceived\", json);\n } catch (error) {\n this.logger.error(\"[StreamingTransport] Error parsing and dispatching config data update: \", error);\n }\n }\n\n private prepareFatalError(\n responseStatus: number | undefined,\n error: Error | undefined,\n ): ConfigDirectorConnectionError {\n const status = responseStatus ?? 0;\n const headline = `Connection failed with status: ${responseStatus ?? \"unknown\"}.`;\n const errorLine = error ? ` Error: ${error}` : \"\";\n const message = `${headline}${errorLine}. This is an unrecoverable error, will not attempt to reconnect.`;\n return new ConfigDirectorConnectionError(message, status);\n }\n\n private isStatusFatal(status: number | undefined): boolean {\n return !!status && status >= 400 && status < 500 && status != 429;\n }\n\n public on<TName extends keyof TransportEvents>(\n name: TName,\n handler: (payload: TransportEvents[TName]) => void,\n ): void {\n this.eventEmitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(\n name: TName,\n handler?: ((payload: TransportEvents[TName]) => void) | undefined,\n ): void {\n this.eventEmitter.off(name, handler);\n }\n\n public clear(): void {\n this.eventEmitter.clear();\n }\n\n public close() {\n this.connectionGeneration++;\n this.eventSource?.close();\n clearTimeout(this.timeoutTimer);\n }\n\n public dispose(): void {\n this.close();\n this.clear();\n }\n}\n","import type { ConfigType } from \"./types\";\nimport { ConfigDirectorValidationError } from \"./errors\";\n\nexport type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | { [key: string]: NativeJsonValue };\n\nexport type NativeValue = boolean | number | string | NativeJsonValue[] | { [key: string]: NativeJsonValue };\n\nexport type NativeValues = Record<string, NativeValue>;\n\nexport type EncodedNativeValue = { type: ConfigType; value: string };\n\nexport const encodeNativeValue = (key: string, value: NativeValue): EncodedNativeValue => {\n if (key.trim().length == 0) {\n throw new ConfigDirectorValidationError(\"Invalid config key. The key of a value cannot be empty.\");\n }\n return encode(key, value);\n};\n\nconst decoders: { [T in ConfigType]: (value: string) => NativeValue } = {\n boolean: (value) => value === \"true\",\n integer: Number,\n float: Number,\n string: (value) => value,\n enum: (value) => value,\n url: (value) => value,\n custom: (value) => value,\n json: (value) => JSON.parse(value),\n};\n\nexport const decodeNativeValue = (type: ConfigType, value: string): NativeValue => decoders[type](value);\n\nconst encode = (key: string, value: NativeValue): EncodedNativeValue => {\n switch (typeof value) {\n case \"boolean\":\n return { type: \"boolean\", value: value ? \"true\" : \"false\" };\n case \"number\":\n return encodeNumber(key, value);\n case \"string\":\n return { type: \"string\", value };\n case \"object\":\n if (value !== null) {\n assertJsonContents(key, value, \"\");\n return { type: \"json\", value: JSON.stringify(value) };\n }\n }\n throw new ConfigDirectorValidationError(\n `Invalid value for '${key}': ${describe(value)}. Use a boolean, a number, a string, a plain object, or an array.`,\n );\n};\n\nconst encodeNumber = (key: string, value: number): EncodedNativeValue => {\n if (!Number.isFinite(value)) {\n throw new ConfigDirectorValidationError(`Invalid value for '${key}': ${describe(value)} is not a finite number.`);\n }\n if (Number.isInteger(value)) {\n if (!Number.isSafeInteger(value)) {\n throw new ConfigDirectorValidationError(\n `Invalid value for '${key}': ${value} is not a safe integer, so the SDK could not read it back exactly.`,\n );\n }\n return { type: \"integer\", value: String(value) };\n }\n return { type: \"float\", value: toPlainDecimal(value) };\n};\n\nconst toPlainDecimal = (value: number): string => {\n const text = String(value);\n const exponentIndex = text.indexOf(\"e-\");\n if (exponentIndex < 0) {\n return text;\n }\n const sign = text.startsWith(\"-\") ? \"-\" : \"\";\n const [integerDigits = \"\", fractionDigits = \"\"] = text.slice(sign.length, exponentIndex).split(\".\");\n const leadingZeros = Number(text.slice(exponentIndex + 2)) - integerDigits.length;\n return `${sign}0.${\"0\".repeat(leadingZeros)}${integerDigits}${fractionDigits}`;\n};\n\nconst assertJsonContents = (key: string, value: unknown, path: string): void => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return;\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw invalidJsonContents(key, path, `${describe(value)} is not a finite number`);\n }\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) => assertJsonContents(key, item, `${path}[${index}]`));\n return;\n }\n if (isPlainObject(value)) {\n for (const [property, item] of Object.entries(value)) {\n assertJsonContents(key, item, path ? `${path}.${property}` : property);\n }\n return;\n }\n throw invalidJsonContents(key, path, `${describe(value)} cannot be encoded as JSON`);\n};\n\nconst invalidJsonContents = (key: string, path: string, problem: string) =>\n new ConfigDirectorValidationError(\n `Invalid value for '${key}'${path ? ` at '${path}'` : \"\"}: ${problem}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`,\n );\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n\nconst describe = (value: unknown): string => {\n if (value === null) {\n return \"null\";\n }\n if (typeof value === \"function\") {\n return \"a function\";\n }\n if (typeof value === \"object\") {\n return `a ${value.constructor?.name ?? \"object\"} instance`;\n }\n if (typeof value === \"symbol\") {\n return \"a symbol\";\n }\n return String(value);\n};\n","import type { ConfigState } from \"./types\";\nimport { encodeNativeValue, type NativeValue } from \"@shared/native-values\";\n\nexport const nativeValueConfigState = (\n id: string,\n key: string,\n value: NativeValue,\n valueId: string | undefined,\n): ConfigState => {\n const encoded = encodeNativeValue(key, value);\n return { id, key, type: encoded.type, value: encoded.value, valueId };\n};\n","import { Emitter } from \"./Emitter\";\nimport { ConfigDirectorInitializationError, ConfigDirectorValidationError } from \"./errors\";\nimport type { ConfigStateMap, OfflineValues, Transport, TransportEvents } from \"./types\";\nimport type { OfflineSource } from \"./connection-plan\";\nimport { nativeValueConfigState } from \"./native-values\";\n\nconst OFFLINE_ENVIRONMENT = { environmentId: \"offline\", projectId: \"offline\" };\n\nexport class OfflineTransport implements Transport {\n private readonly emitter = new Emitter<TransportEvents>();\n\n constructor(private readonly source: OfflineSource) {}\n\n public async connect(): Promise<this> {\n const configs = loadOfflineConfigs(this.source);\n this.emitter.emit(\"configSetReceived\", { ...OFFLINE_ENVIRONMENT, kind: \"full\", configs });\n return this;\n }\n\n public on: Transport[\"on\"] = (name, handler) => this.emitter.on(name, handler);\n\n public off: Transport[\"off\"] = (name, handler) => this.emitter.off(name, handler);\n\n public clear() {\n this.emitter.clear();\n }\n\n public close() {}\n\n public dispose() {\n this.clear();\n }\n}\n\nconst loadOfflineConfigs = (source: OfflineSource): ConfigStateMap => {\n switch (source.kind) {\n case \"in-code-defaults\":\n return {};\n case \"values\":\n return encodeOfflineValues(source.values);\n case \"rejected\":\n throw new ConfigDirectorInitializationError(source.message);\n }\n};\n\nconst encodeOfflineValues = (values: OfflineValues): ConfigStateMap => {\n try {\n return Object.fromEntries(\n Object.entries(values).map(([key, value]) => [key, nativeValueConfigState(`offline:${key}`, key, value, undefined)]),\n );\n } catch (error) {\n if (error instanceof ConfigDirectorValidationError) {\n throw new ConfigDirectorInitializationError(`The offline values could not be loaded. ${error.message}`);\n }\n throw error;\n }\n};\n","export const CLIENT_BASE_URL = \"https://client-sdk-api.configdirector.com\";\nexport const CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS = 60;\nexport const CLIENT_MIN_POLLING_INTERVAL_SECONDS = 30;\nexport const SERVER_DEFAULT_POLLING_INTERVAL_SECONDS = 300;\nexport const SERVER_MIN_POLLING_INTERVAL_SECONDS = 60;\n","import { ConfigDirectorValidationError } from \"./errors\";\nimport { CLIENT_BASE_URL } from \"@shared/constants\";\nimport type { UrlFactory, UrlLike } from \"@shared/url\";\nimport type { ConnectionOptions, OfflineValues } from \"./types\";\n\nexport type LiveConnectionMode = \"streaming\" | \"polling\";\n\nexport type OfflineSource =\n | { kind: \"in-code-defaults\" }\n | { kind: \"values\"; values: OfflineValues }\n | { kind: \"rejected\"; message: string };\n\nexport type ConnectionPlan =\n | { kind: \"connect\"; mode: LiveConnectionMode; clientSdkKey: string; baseUrl: UrlLike }\n | { kind: \"stay-offline\"; source: OfflineSource };\n\nexport const planConnection = (\n clientSdkKey: string | undefined,\n connection: ConnectionOptions | undefined,\n urlFactory: UrlFactory,\n): ConnectionPlan => {\n if (connection?.mode === \"offline\") {\n return { kind: \"stay-offline\", source: offlineSourceOf(connection) };\n }\n const mode = connection?.mode ?? \"streaming\";\n if (!clientSdkKey || clientSdkKey.trim().length == 0) {\n throw new ConfigDirectorValidationError(\n \"No client SDK key was provided, the client cannot be instantiated without a valid client SDK key\",\n );\n }\n if (connection?.values !== undefined) {\n return {\n kind: \"stay-offline\",\n source: {\n kind: \"rejected\",\n message: `The connection option 'values' applies only when the connection mode is 'offline', but the mode is '${mode}'.`,\n },\n };\n }\n return { kind: \"connect\", mode, clientSdkKey, baseUrl: baseUrlOf(connection?.url, urlFactory) };\n};\n\nconst baseUrlOf = (url: string | undefined, urlFactory: UrlFactory): UrlLike => {\n if (!url) {\n return CLIENT_BASE_URL;\n }\n try {\n return urlFactory(url);\n } catch (error) {\n throw new ConfigDirectorValidationError(`Invalid base URL '${url}'. Parsing failed: ${error}`);\n }\n};\n\nconst offlineSourceOf = (connection: ConnectionOptions): OfflineSource => {\n if (connection.values !== undefined) {\n return { kind: \"values\", values: connection.values };\n }\n return { kind: \"in-code-defaults\" };\n};\n","import type { ConfigState, ConfigType, ConfigValueType, EvaluationReason } from \"./types\";\n\ntype NativeType = \"string\" | \"number\" | \"bigint\" | \"boolean\" | \"symbol\" | \"undefined\" | \"object\" | \"function\";\n\ntype ParseResult<T extends ConfigValueType> = {\n parsedValue: T;\n parsedValueId: string | null | undefined;\n requestedType: NativeType | string;\n usedDefault: boolean;\n reason: EvaluationReason;\n};\n\nexport const getRequestedType = <T extends ConfigValueType>(defaultValue: T): string => {\n const baseType = typeof defaultValue;\n if (baseType === \"object\") {\n try {\n return (defaultValue as object).constructor?.name ?? baseType;\n } catch {\n return baseType;\n }\n } else if (baseType === \"function\") {\n try {\n const functionName = (defaultValue as any).name;\n return functionName ? `function: ${functionName}` : baseType;\n } catch {\n return baseType;\n }\n }\n return baseType;\n};\n\nconst isNumericNativeType = (requestedType: NativeType): boolean => {\n return requestedType === \"number\" || requestedType === \"bigint\";\n};\n\nconst configTypesNotReadableAsString: ReadonlySet<ConfigType> = new Set<ConfigType>([\"boolean\", \"integer\", \"float\"]);\n\nexport const parseConfigValue = <T extends ConfigValueType>(\n configState: ConfigState,\n defaultValue: T,\n): ParseResult<T> => {\n const value = configState.value;\n const requestedType = getRequestedType(defaultValue);\n\n if (value == null || value === \"\") {\n return {\n parsedValue: defaultValue as T,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"value-missing\",\n };\n }\n\n if (configState.type === \"json\") {\n return parseJson(value, defaultValue, requestedType, configState.valueId);\n }\n\n if (typeof defaultValue === \"string\") {\n if (configTypesNotReadableAsString.has(configState.type)) {\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"type-mismatch\",\n };\n }\n return {\n parsedValue: value as T,\n parsedValueId: configState.valueId,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n }\n\n if (\n typeof defaultValue === \"boolean\" &&\n (configState.type === \"boolean\" || configState.type === \"string\" || configState.type === \"enum\")\n ) {\n const boolValue = parseConfigBoolean(value);\n const hasBoolean = typeof boolValue === \"boolean\";\n return {\n parsedValue: (hasBoolean ? boolValue : defaultValue) as T,\n parsedValueId: hasBoolean ? configState.valueId : undefined,\n requestedType,\n usedDefault: !hasBoolean,\n reason: hasBoolean ? \"found-match\" : \"invalid-boolean\",\n };\n }\n\n if (isNumericNativeType(typeof defaultValue) && configState.type === \"integer\") {\n const numValue = parseConfigInteger(value);\n const hasNumber = typeof numValue === \"number\";\n return {\n parsedValue: (hasNumber ? numValue : defaultValue) as T,\n parsedValueId: hasNumber ? configState.valueId : undefined,\n requestedType,\n usedDefault: !hasNumber,\n reason: hasNumber ? \"found-match\" : \"invalid-number\",\n };\n }\n if (\n isNumericNativeType(typeof defaultValue) &&\n (configState.type === \"float\" || configState.type === \"enum\" || configState.type === \"string\")\n ) {\n const numValue = parseConfigFloat(value);\n const hasNumber = typeof numValue === \"number\";\n return {\n parsedValue: (hasNumber ? numValue : defaultValue) as T,\n parsedValueId: hasNumber ? configState.valueId : undefined,\n requestedType,\n usedDefault: !hasNumber,\n reason: hasNumber ? \"found-match\" : \"invalid-number\",\n };\n }\n\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"type-mismatch\",\n };\n};\n\nconst parseConfigBoolean = (value: string): boolean | undefined => {\n if (!value) {\n return;\n }\n const lowerValue = value.toLowerCase();\n if (lowerValue != \"true\" && lowerValue != \"false\") {\n return;\n }\n return lowerValue === \"true\";\n};\n\nconst parseConfigInteger = (value: string): number | undefined => {\n const num = parseStrictNumber(value);\n return num == null ? undefined : Math.trunc(num);\n};\n\nconst parseConfigFloat = (value: string): number | undefined => {\n return parseStrictNumber(value);\n};\n\nconst parseStrictNumber = (value: string): number | undefined => {\n if (!value || !isDecimalCharacters(value)) {\n return;\n }\n const num = Number(value);\n if (isNaN(num) || !isFinite(num)) {\n return;\n }\n return num;\n};\n\nconst isDecimalCharacters = (value: string): boolean => {\n for (const character of value) {\n const isDigit = character >= \"0\" && character <= \"9\";\n if (!isDigit && !\"+-.eE\".includes(character)) {\n return false;\n }\n }\n return true;\n};\n\nconst parseJson = <T extends ConfigValueType>(\n jsonString: string,\n defaultValue: T,\n requestedType: string,\n valueId: string | null | undefined,\n): ParseResult<T> => {\n if (typeof defaultValue === \"string\") {\n return {\n parsedValue: jsonString as T,\n parsedValueId: valueId,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n }\n\n try {\n const parsed = JSON.parse(jsonString);\n if (!isJsonTypeCompatible(parsed, defaultValue)) {\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"type-mismatch\",\n };\n }\n return {\n parsedValue: parsed,\n parsedValueId: valueId,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n } catch {\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"invalid-json\",\n };\n }\n};\n\nconst isJsonTypeCompatible = (parsed: unknown, defaultValue: ConfigValueType): boolean => {\n if (parsed === null) {\n return false;\n }\n const defaultType = typeof defaultValue;\n if (defaultType === \"bigint\") {\n return typeof parsed === \"number\";\n }\n return typeof parsed === defaultType;\n};\n","import type { ConfigDirectorLogger, ConfigDirectorLogMessageDecorator, ConfigDirectorLoggingLevel } from \"./types\";\n\nconst LEVELS: Record<ConfigDirectorLoggingLevel, number> = {\n off: -1,\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nconst buildDateFormatter = () => {\n const baseOptions: Intl.DateTimeFormatOptions = {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n timeZoneName: \"short\",\n };\n\n try {\n return new Intl.DateTimeFormat(\n undefined,\n { ...baseOptions, fractionalSecondDigits: 3 } as Intl.DateTimeFormatOptions,\n );\n } catch {\n return new Intl.DateTimeFormat(undefined, baseOptions);\n }\n};\n\nexport class DefaultConsoleLogger implements ConfigDirectorLogger {\n private readonly dateFormatter;\n\n constructor(private readonly level: ConfigDirectorLoggingLevel, private readonly decorator: ConfigDirectorLogMessageDecorator) {\n this.level = level;\n this.decorator = decorator;\n this.dateFormatter = buildDateFormatter();\n }\n\n debug(message: string, ...args: any): void {\n this.log(console.debug, \"debug\", message, ...args);\n }\n\n info(message: string, ...args: any): void {\n this.log(console.info, \"info\", message, ...args);\n }\n\n warn(message: string, ...args: any): void {\n this.log(console.warn, \"warn\", message, ...args);\n }\n\n error(message: string, ...args: any): void {\n this.log(console.error, \"error\", message, ...args);\n }\n\n protected log(loggerFunction: (...args: any) => void, level: ConfigDirectorLoggingLevel, message: string, ...args: any) {\n if (LEVELS[this.level] >= LEVELS[level]) {\n loggerFunction(`[${this.dateFormatter.format(new Date())}] ${this.decorator?.decorateMessage(message)}`, ...args);\n }\n }\n}\n","import { type ConfigDirectorLogMessageDecorator, type ConfigDirectorLoggingLevel } from \"./types\";\nimport { DefaultConsoleLogger } from \"../../shared/src/logger\";\nexport { DefaultConsoleLogger } from \"../../shared/src/logger\";\n\nclass LogMessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:js-client-sdk] ${message}`;\n }\n}\n\nexport const createDefaultLogger = (\n level?: ConfigDirectorLoggingLevel,\n messageDecorator?: ConfigDirectorLogMessageDecorator,\n) => {\n return new DefaultConsoleLogger(level ?? \"warn\", messageDecorator ?? new LogMessageDecorator());\n};\n","import type { TelemetryClient } from \"./types\";\n\nexport const discardingTelemetryClient: TelemetryClient = {\n updateContext: async () => {},\n evaluatedConfig: () => {},\n recordInvalidContext: () => {},\n close: async () => {},\n};\n","import { ConfigDirectorValidationError } from \"./errors\";\n\nexport interface UrlLike {\n toString(): string;\n}\n\nexport type UrlFactory = (input: string, base?: UrlLike) => UrlLike;\n\nexport const defaultUrlFactory: UrlFactory = (input, base) => new URL(input, base?.toString());\n\nexport const parseUrl = (url: string | undefined): URL | undefined => {\n if (!url) {\n return;\n }\n\n try {\n return new URL(url);\n } catch (error) {\n throw new ConfigDirectorValidationError(`Invalid URL '${url}'. Parsing failed: ${error}`);\n }\n};\n","export type PollingIntervalDefaults = {\n defaultSeconds: number;\n minimumSeconds: number;\n};\n\nexport type ResolvedPollingInterval = {\n seconds: number;\n warning: string | undefined;\n};\n\nexport const resolvePollingInterval = (\n configuredSeconds: number | undefined,\n defaults: PollingIntervalDefaults,\n): ResolvedPollingInterval => {\n if (configuredSeconds === undefined) {\n return { seconds: defaults.defaultSeconds, warning: undefined };\n }\n if (configuredSeconds >= defaults.minimumSeconds) {\n return { seconds: configuredSeconds, warning: undefined };\n }\n return {\n seconds: defaults.minimumSeconds,\n warning: `pollingInterval of ${configuredSeconds} seconds is below the minimum of ${defaults.minimumSeconds} seconds. Using ${defaults.minimumSeconds} seconds.`,\n };\n};\n","// React Native's Hermes engine does not expose a global `crypto`, unlike browsers and Node 19+.\nexport const generateInstanceId = (): string => {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (placeholder) => {\n const random = (Math.random() * 16) | 0;\n const value = placeholder === \"x\" ? random : (random & 0x3) | 0x8;\n return value.toString(16);\n });\n};\n","type BrowserGlobals = {\n navigator?: { userAgent?: string };\n location?: { host?: string };\n localStorage?: Storage;\n};\n\nconst read = (readValue: (globals: BrowserGlobals) => string | undefined): string | undefined => {\n try {\n return readValue(globalThis as BrowserGlobals);\n } catch {\n return undefined;\n }\n};\n\nexport const readUserAgent = (): string | undefined => read((globals) => globals.navigator?.userAgent);\n\nexport const readHost = (): string | undefined => read((globals) => globals.location?.host);\n\nexport const localStorageIfAvailable = (): Storage | undefined => {\n try {\n return (globalThis as BrowserGlobals).localStorage ?? undefined;\n } catch {\n return undefined;\n }\n};\n","import { generateInstanceId } from \"@shared/instance-id\";\nimport { localStorageIfAvailable } from \"./browser-globals\";\nimport type { ClientSession, ConfigDirectorLogger, InstanceIdStorage } from \"./types\";\n\nconst STORAGE_KEY = \"configdirector-sdk:instance-id\";\nconst RECORD_VERSION = 1;\nconst STORAGE_DEADLINE_MS = 1_000;\nconst CHECKSUM_SALT = \"configdirector.instanceId.v1\";\nconst UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\n\ntype StoredInstanceId = {\n v: number;\n id: string;\n createdAt: number;\n checksum: string;\n};\n\ntype StorageRead =\n | { outcome: \"stored\"; instanceId: string }\n | { outcome: \"nothing usable\" }\n | { outcome: \"failed\" };\n\ntype Deadline = { passed: boolean };\n\nconst fnv1a = (input: string, offsetBasis: number): number => {\n let hash = offsetBasis;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n};\n\nconst checksumFor = (id: string, createdAt: number): string => {\n const payload = `${CHECKSUM_SALT}|${id}|${createdAt}`;\n const low = fnv1a(payload, 0x811c9dc5);\n const high = fnv1a(`${low}|${payload}`, 0x01000193);\n return high.toString(16).padStart(8, \"0\") + low.toString(16).padStart(8, \"0\");\n};\n\nconst isUsableRecord = (record: unknown): record is StoredInstanceId => {\n if (!record || typeof record !== \"object\") {\n return false;\n }\n\n const { v, id, createdAt, checksum } = record as Partial<StoredInstanceId>;\n if (v !== RECORD_VERSION || typeof id !== \"string\" || typeof checksum !== \"string\") {\n return false;\n }\n\n if (typeof createdAt !== \"number\" || !Number.isInteger(createdAt) || createdAt <= 0) {\n return false;\n }\n\n if (!UUID_V4_PATTERN.test(id)) {\n return false;\n }\n\n return checksum === checksumFor(id, createdAt);\n};\n\nconst readStoredInstanceId = async (\n storage: InstanceIdStorage,\n logger: ConfigDirectorLogger,\n): Promise<StorageRead> => {\n let raw: unknown;\n try {\n raw = await storage.getItem(STORAGE_KEY);\n } catch (error) {\n logger.debug(\n \"[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one\",\n error,\n );\n return { outcome: \"failed\" };\n }\n\n if (typeof raw !== \"string\" || raw === \"\") {\n return { outcome: \"nothing usable\" };\n }\n\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n logger.debug(\"[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one\");\n return { outcome: \"nothing usable\" };\n }\n\n if (!isUsableRecord(record)) {\n logger.debug(\"[ConfigDirectorClient] The stored instance id failed validation, generating a new one\");\n return { outcome: \"nothing usable\" };\n }\n\n return { outcome: \"stored\", instanceId: record.id };\n};\n\nconst persistInstanceId = async (\n storage: InstanceIdStorage,\n id: string,\n logger: ConfigDirectorLogger,\n): Promise<boolean> => {\n const createdAt = Date.now();\n const record: StoredInstanceId = { v: RECORD_VERSION, id, createdAt, checksum: checksumFor(id, createdAt) };\n try {\n await storage.setItem(STORAGE_KEY, JSON.stringify(record));\n return true;\n } catch (error) {\n logger.debug(\n \"[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one\",\n error,\n );\n return false;\n }\n};\n\nconst settleFromStorage = async (\n storage: InstanceIdStorage,\n provisionalId: string,\n deadline: Deadline,\n logger: ConfigDirectorLogger,\n): Promise<ClientSession> => {\n const read = await readStoredInstanceId(storage, logger);\n switch (read.outcome) {\n case \"stored\":\n return { instanceId: read.instanceId };\n case \"failed\":\n return { instanceId: provisionalId, ephemeral: true };\n case \"nothing usable\":\n break;\n }\n\n if (deadline.passed) {\n return { instanceId: provisionalId, ephemeral: true };\n }\n\n const persisted = await persistInstanceId(storage, provisionalId, logger);\n return persisted ? { instanceId: provisionalId } : { instanceId: provisionalId, ephemeral: true };\n};\n\nexport const resolveClientSession = (\n logger: ConfigDirectorLogger,\n storage: InstanceIdStorage | undefined = localStorageIfAvailable(),\n): Promise<ClientSession> => {\n const provisionalId = generateInstanceId();\n if (!storage) {\n logger.debug(\n \"[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id\",\n );\n return Promise.resolve({ instanceId: provisionalId, ephemeral: true });\n }\n\n const deadline: Deadline = { passed: false };\n let deadlineTimer: ReturnType<typeof setTimeout> | undefined;\n const fallbackAtDeadline = new Promise<ClientSession>((resolve) => {\n deadlineTimer = setTimeout(() => {\n deadline.passed = true;\n logger.warn(\n `[ConfigDirectorClient] The instance id storage did not respond within ${STORAGE_DEADLINE_MS}ms, using an ephemeral instance id`,\n );\n resolve({ instanceId: provisionalId, ephemeral: true });\n }, STORAGE_DEADLINE_MS);\n });\n\n return Promise.race([\n settleFromStorage(storage, provisionalId, deadline, logger),\n fallbackAtDeadline,\n ]).finally(() => clearTimeout(deadlineTimer));\n};\n","import { ConfigDirectorConnectionError } from \"../errors\";\n\nexport abstract class AbstractPollingTransport {\n protected fatalError = false;\n protected pollingInterval: ReturnType<typeof setInterval> | undefined;\n protected abstract pollingIntervalSeconds: number;\n\n protected clearPollingInterval() {\n clearInterval(this.pollingInterval);\n }\n\n protected schedulePollingInterval(callback: () => void) {\n clearInterval(this.pollingInterval);\n if (this.pollingIntervalSeconds <= 0) {\n return;\n }\n this.pollingInterval = setInterval(callback, this.pollingIntervalSeconds * 1_000);\n }\n\n protected async handleNonOkResponse(response: Response) {\n if (!response.ok) {\n if (this.isStatusFatal(response.status)) {\n this.fatalError = true;\n this.close();\n throw this.prepareFatalResponseStatusError(response.status, await response.text());\n } else {\n throw new ConfigDirectorConnectionError(\n `Connection failed with status: ${response.status}`,\n response.status,\n );\n }\n }\n }\n\n protected handleFetchError(fetchError: unknown) {\n if (this.isFetchErrorFatal(fetchError)) {\n this.fatalError = true;\n this.close();\n throw new ConfigDirectorConnectionError(\n `Connection failed with fatal error: ${fetchError}. This is an unrecoverable error, retry attempts will be ignored.`,\n );\n } else if (fetchError instanceof SyntaxError) {\n throw new ConfigDirectorConnectionError(`Failed to parse the response from the server: ${fetchError}`);\n } else {\n throw new ConfigDirectorConnectionError(`Connection failed with error: ${fetchError}.`);\n }\n }\n\n protected prepareFatalResponseStatusError(\n responseStatus: number,\n errorBody: string | undefined,\n ): ConfigDirectorConnectionError {\n const status = responseStatus ?? 0;\n const headline = `Connection failed with status: ${responseStatus ?? \"unknown\"}`;\n const serverBody = (errorBody?.trim()?.length ?? 0) > 0 ? ` (${errorBody})` : \"\";\n const message = `${headline}${serverBody}. This is an unrecoverable error, retry attempts will be ignored.`;\n return new ConfigDirectorConnectionError(message, status);\n }\n\n protected isStatusFatal(status: number | undefined): boolean {\n return !!status && status >= 400 && status < 500 && status != 429;\n }\n\n protected isFetchErrorFatal(fetchError: unknown): boolean {\n return (fetchError as any)?.name === \"NotAllowedError\";\n }\n\n public get isConnected(): boolean {\n return this.pollingInterval !== undefined;\n }\n\n public close() {\n clearInterval(this.pollingInterval);\n this.pollingInterval = undefined;\n }\n\n public abstract clear(): void;\n\n public dispose(): void {\n this.close();\n this.clear();\n }\n}\n","import { type ConfigDirectorLogger } from \"./types\";\nimport type { UrlLike } from \"./url\";\n\nexport const fetchWithTimeout = async (\n timeout: number,\n resource: string | UrlLike | Request,\n options: RequestInit | undefined,\n logger: ConfigDirectorLogger,\n) => {\n const abortController = new AbortController();\n const abortTimeoutId = setTimeout(() => {\n logger.debug(\"[fetchWithTimeout] Reached timeout, aborting request\");\n abortController.abort();\n }, timeout);\n\n try {\n const response = await fetch(typeof resource === \"string\" || resource instanceof Request ? resource : resource.toString(), {\n ...options,\n signal: abortController.signal,\n });\n clearTimeout(abortTimeoutId);\n return response;\n } catch (error) {\n logger.warn(\"[fetchWithTimeout] Fetch error: \", error);\n clearTimeout(abortTimeoutId);\n throw error;\n }\n};\n","import type {\n ClientSession,\n ConfigDirectorContext,\n ConfigDirectorLogger,\n Transport,\n TransportEvents,\n TransportOptions,\n} from \"./types\";\nimport { Emitter } from \"./Emitter\";\nimport { AbstractPollingTransport } from \"@shared/transport/AbstractPollingTransport\";\nimport { fetchWithTimeout } from \"@shared/fetchWithTimeout\";\nimport type { UrlLike } from \"@shared/url\";\nimport { CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS } from \"@shared/constants\";\n\nexport class PollingTransport extends AbstractPollingTransport implements Transport {\n protected pollingIntervalSeconds: number;\n private logger: ConfigDirectorLogger;\n private eventEmitter = new Emitter<TransportEvents>();\n private url: UrlLike;\n private lastUpdateTimestamp: string | undefined;\n private connectionGeneration = 0;\n\n constructor(private readonly options: TransportOptions) {\n super();\n this.options = options;\n this.logger = options.logger;\n this.url = options.resolveUrl(\"client/polling/v1\", options.baseUrl);\n this.pollingIntervalSeconds = options.pollingInterval ?? CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS;\n }\n\n public async connect(context: ConfigDirectorContext, timeout: number): Promise<this> {\n const generation = ++this.connectionGeneration;\n this.clearPollingInterval();\n const clientSession = await this.options.clientSession;\n if (generation !== this.connectionGeneration) {\n return this;\n }\n\n try {\n await this.fetchConfigs(context, timeout, clientSession);\n } finally {\n // A transient failure on the first fetch must not leave the client without a\n // connection, so polling is scheduled either way. An unrecoverable failure has\n // already closed the transport and must not be retried.\n if (!this.fatalError) {\n this.schedulePollingInterval(() => {\n void this.fetchConfigs(context, timeout, clientSession).catch((error) => {\n this.logger.error(\"[PollingTransport] Error during polling:\", error);\n });\n });\n }\n }\n\n return this;\n }\n\n public override close() {\n this.connectionGeneration++;\n super.close();\n }\n\n private async fetchConfigs(context: ConfigDirectorContext, timeout: number, clientSession: ClientSession) {\n if (this.fatalError) {\n this.logger.warn(\n \"[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.\",\n );\n return;\n }\n\n try {\n const response = await fetchWithTimeout(\n timeout,\n this.url,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n givenContext: context,\n metaContext: this.options.metaContext,\n clientSdkKey: this.options.clientSdkKey,\n instanceId: clientSession.instanceId,\n ephemeral: clientSession.ephemeral,\n lastUpdateTimestamp: this.lastUpdateTimestamp,\n }),\n },\n this.logger,\n );\n\n await this.handleNonOkResponse(response);\n\n if (response.status == 200) {\n const json = JSON.parse(await response.text());\n this.lastUpdateTimestamp = json.timestamp;\n this.eventEmitter.emit(\"configSetReceived\", json);\n }\n } catch (fetchError) {\n try {\n this.handleFetchError(fetchError);\n } catch (handledError) {\n if (this.fatalError) {\n this.eventEmitter.emit(\"connectionError\", handledError as Error);\n }\n throw handledError;\n }\n }\n }\n\n public on<TName extends keyof TransportEvents>(\n name: TName,\n handler: (payload: TransportEvents[TName]) => void,\n ): void {\n this.eventEmitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(\n name: TName,\n handler?: ((payload: TransportEvents[TName]) => void) | undefined,\n ): void {\n this.eventEmitter.off(name, handler);\n }\n\n public clear(): void {\n this.eventEmitter.clear();\n }\n}\n","import type { ConfigDirectorContext } from \"./types\";\n\nconst CONTEXT_KIND_MAXIMUM_LENGTH = 64;\nconst KIND_SAMPLE_MAXIMUM_CHARACTERS = 128;\n\ntype ContextAdmission =\n | { outcome: \"admitted\"; context: ConfigDirectorContext | undefined }\n | { outcome: \"ignored\"; kindSample: string };\n\nconst isContextKindCharacter = (character: string): boolean =>\n (character >= \"a\" && character <= \"z\") ||\n (character >= \"0\" && character <= \"9\") ||\n character === \"-\" ||\n character === \"_\";\n\nconst isValidContextKind = (kind: string): boolean => {\n if (kind.length < 1 || kind.length > CONTEXT_KIND_MAXIMUM_LENGTH) {\n return false;\n }\n for (const character of kind) {\n if (!isContextKindCharacter(character)) {\n return false;\n }\n }\n return true;\n};\n\nconst isAcceptedKind = (kind: unknown): boolean =>\n kind === undefined || kind === null || (typeof kind === \"string\" && isValidContextKind(kind));\n\nconst stringFormOf = (kind: unknown): string => {\n if (typeof kind === \"string\") {\n return kind;\n }\n try {\n return String(kind);\n } catch {\n return Object.prototype.toString.call(kind);\n }\n};\n\nconst firstCharactersOf = (text: string, maximumCharacters: number): string => {\n let sample = \"\";\n let characterCount = 0;\n for (const character of text) {\n if (characterCount === maximumCharacters) {\n break;\n }\n sample += character;\n characterCount += 1;\n }\n return sample;\n};\n\nexport const admittedContextOrNone = (\n context: ConfigDirectorContext | undefined,\n): ConfigDirectorContext | undefined => {\n const admission = admitContext(context);\n return admission.outcome === \"admitted\" ? admission.context : undefined;\n};\n\nexport const admitContext = (context: ConfigDirectorContext | undefined): ContextAdmission => {\n const kind: unknown = context?.kind;\n if (isAcceptedKind(kind)) {\n return { outcome: \"admitted\", context };\n }\n return {\n outcome: \"ignored\",\n kindSample: firstCharactersOf(stringFormOf(kind), KIND_SAMPLE_MAXIMUM_CHARACTERS),\n };\n};\n","const isHighSurrogate = (codeUnit: number): boolean => codeUnit >= 0xd800 && codeUnit <= 0xdbff;\n\nconst isLowSurrogate = (codeUnit: number): boolean => codeUnit >= 0xdc00 && codeUnit <= 0xdfff;\n\nexport const utf8ByteLength = (text: string): number => {\n let bytes = 0;\n for (let i = 0; i < text.length; i++) {\n const codeUnit = text.charCodeAt(i);\n if (codeUnit <= 0x7f) {\n bytes += 1;\n } else if (codeUnit <= 0x7ff) {\n bytes += 2;\n } else if (isHighSurrogate(codeUnit) && i + 1 < text.length && isLowSurrogate(text.charCodeAt(i + 1))) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n};\n","import type { CachingOptions, CachingProvider, ConfigDirectorContext, ConfigDirectorLogger, ConfigStateMap } from \"./types\";\nimport type { ConnectionPlan } from \"./connection-plan\";\nimport { utf8ByteLength } from \"@shared/utf8-byte-length\";\n\nconst ENTRY_FORMAT_VERSION = 1;\nconst DEFAULT_CONTEXT_KIND = \"user\";\n\nexport const CACHED_VALUES_STORAGE_KEY_PREFIX = \"configdirector-sdk:cached-values:\";\nexport const DEFAULT_CACHING_SIZE_LIMIT_BYTES = 256 * 1024;\n\nexport type ContextTag =\n | { contextKind: string; contextId: string }\n | { contextKind: string; anonymousInstanceId: string };\n\nexport type CachedValues = {\n contextTag: ContextTag;\n environmentId: string;\n projectId: string;\n configs: ConfigStateMap;\n receivedAt: number;\n};\n\ntype CachedValuesEntry = CachedValues & {\n formatVersion: typeof ENTRY_FORMAT_VERSION;\n clientSdkKey: string;\n};\n\nexport type CachedValuesRead =\n | { outcome: \"stored\"; cachedValues: CachedValues }\n | { outcome: \"nothing stored\" }\n | { outcome: \"unreadable\" }\n | { outcome: \"failed\" };\n\nexport type CachingPlan =\n | { kind: \"cache\"; provider: CachingProvider; clientSdkKey: string }\n | { kind: \"no cache\"; reason: \"offline mode\" | \"turned off\" | \"no provider available\" };\n\nexport type CachedValuesAdoption = \"adopt\" | \"live values already arrived\" | \"context mismatch\";\n\nexport const planCaching = (\n connectionPlan: ConnectionPlan,\n caching: CachingOptions | undefined,\n platformProvider: ((clientSdkKey: string) => CachingProvider | undefined) | undefined,\n): CachingPlan => {\n if (connectionPlan.kind === \"stay-offline\") {\n return { kind: \"no cache\", reason: \"offline mode\" };\n }\n if (caching?.enabled === false) {\n return { kind: \"no cache\", reason: \"turned off\" };\n }\n const provider = caching?.provider ?? platformProvider?.(connectionPlan.clientSdkKey);\n if (!provider) {\n return { kind: \"no cache\", reason: \"no provider available\" };\n }\n return { kind: \"cache\", provider, clientSdkKey: connectionPlan.clientSdkKey };\n};\n\nexport const contextTagFor = (context: ConfigDirectorContext | undefined, instanceId: string): ContextTag => {\n const contextKind = context?.kind ?? DEFAULT_CONTEXT_KIND;\n if (context?.id != null) {\n return { contextKind, contextId: context.id };\n }\n return { contextKind, anonymousInstanceId: instanceId };\n};\n\nconst sameContextTag = (stored: ContextTag, launch: ContextTag): boolean => {\n if (stored.contextKind !== launch.contextKind) {\n return false;\n }\n if (\"contextId\" in stored && \"contextId\" in launch) {\n return stored.contextId === launch.contextId;\n }\n if (\"anonymousInstanceId\" in stored && \"anonymousInstanceId\" in launch) {\n return stored.anonymousInstanceId === launch.anonymousInstanceId;\n }\n return false;\n};\n\nexport const decideCachedValuesAdoption = (\n cachedValues: CachedValues,\n launchContextTag: ContextTag,\n hasReceivedLiveValues: boolean,\n): CachedValuesAdoption => {\n if (hasReceivedLiveValues) {\n return \"live values already arrived\";\n }\n if (!sameContextTag(cachedValues.contextTag, launchContextTag)) {\n return \"context mismatch\";\n }\n return \"adopt\";\n};\n\nconst isContextTag = (candidate: unknown): candidate is ContextTag => {\n if (!candidate || typeof candidate !== \"object\") {\n return false;\n }\n const { contextKind, contextId, anonymousInstanceId } = candidate as Record<string, unknown>;\n if (typeof contextKind !== \"string\") {\n return false;\n }\n return typeof contextId === \"string\" || typeof anonymousInstanceId === \"string\";\n};\n\nconst isConfigStateMap = (candidate: unknown): candidate is ConfigStateMap => {\n if (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) {\n return false;\n }\n return Object.values(candidate).every(\n (config) =>\n config && typeof config === \"object\" && typeof config.id === \"string\" && typeof config.key === \"string\",\n );\n};\n\nconst isEntryFor = (clientSdkKey: string, candidate: unknown): candidate is CachedValuesEntry => {\n if (!candidate || typeof candidate !== \"object\") {\n return false;\n }\n const entry = candidate as Partial<CachedValuesEntry>;\n return (\n entry.formatVersion === ENTRY_FORMAT_VERSION &&\n entry.clientSdkKey === clientSdkKey &&\n isContextTag(entry.contextTag) &&\n typeof entry.environmentId === \"string\" &&\n typeof entry.projectId === \"string\" &&\n isConfigStateMap(entry.configs) &&\n typeof entry.receivedAt === \"number\"\n );\n};\n\ntype Warning = \"read failed\" | \"unreadable\" | \"over the size limit\" | \"write failed\" | \"remove failed\";\n\nexport class CachedValuesStore {\n private readonly warned = new Set<Warning>();\n private pendingRead: Promise<CachedValuesRead> | undefined;\n private queuedCachedValues: CachedValues | undefined;\n private writing = false;\n\n constructor(\n private readonly provider: CachingProvider,\n private readonly clientSdkKey: string,\n private readonly logger: ConfigDirectorLogger,\n ) {}\n\n public read(): Promise<CachedValuesRead> {\n this.pendingRead ??= this.readEntry();\n return this.pendingRead;\n }\n\n public replace(cachedValues: CachedValues) {\n this.queuedCachedValues = cachedValues;\n void this.writeQueued();\n }\n\n private async readEntry(): Promise<CachedValuesRead> {\n let raw: string | null | undefined;\n try {\n raw = await this.provider.read();\n } catch (error) {\n this.warnOnce(\"read failed\", \"Could not read the values kept on the device, starting without them:\", error);\n return { outcome: \"failed\" };\n }\n if (raw == null || raw === \"\") {\n return { outcome: \"nothing stored\" };\n }\n\n const entry = this.parseEntry(raw);\n if (!entry) {\n this.warnOnce(\"unreadable\", \"The values kept on the device could not be read and were removed, starting without them\");\n await this.removeEntry();\n return { outcome: \"unreadable\" };\n }\n return { outcome: \"stored\", cachedValues: entry };\n }\n\n private parseEntry(raw: string): CachedValuesEntry | undefined {\n try {\n const candidate: unknown = JSON.parse(raw);\n return isEntryFor(this.clientSdkKey, candidate) ? candidate : undefined;\n } catch {\n return undefined;\n }\n }\n\n private async writeQueued() {\n if (this.writing) {\n return;\n }\n this.writing = true;\n try {\n while (this.queuedCachedValues) {\n const cachedValues = this.queuedCachedValues;\n this.queuedCachedValues = undefined;\n await this.writeEntry(cachedValues);\n }\n } finally {\n this.writing = false;\n }\n }\n\n private async writeEntry(cachedValues: CachedValues) {\n const entry: CachedValuesEntry = {\n formatVersion: ENTRY_FORMAT_VERSION,\n clientSdkKey: this.clientSdkKey,\n ...cachedValues,\n };\n const serialized = JSON.stringify(entry);\n const size = utf8ByteLength(serialized);\n const limit = this.provider.sizeLimit();\n if (size > limit) {\n this.warnOnce(\n \"over the size limit\",\n `The values received (${size} bytes) exceed the caching provider's limit of ${limit} bytes, so no values are kept on the device`,\n );\n await this.removeEntry();\n return;\n }\n try {\n await this.provider.write(serialized);\n } catch (error) {\n this.warnOnce(\"write failed\", \"Could not keep the values on the device:\", error);\n }\n }\n\n private async removeEntry() {\n try {\n await this.provider.remove();\n } catch (error) {\n this.warnOnce(\"remove failed\", \"Could not remove the values kept on the device:\", error);\n }\n }\n\n private warnOnce(warning: Warning, message: string, ...details: unknown[]) {\n if (this.warned.has(warning)) {\n return;\n }\n this.warned.add(warning);\n this.logger.warn(`[ConfigDirectorClient] ${message}`, ...details);\n }\n}\n","import { Emitter } from \"./Emitter\";\nimport { StreamingTransport } from \"./StreamingTransport\";\nimport { OfflineTransport } from \"./OfflineTransport\";\nimport { planConnection, type ConnectionPlan, type LiveConnectionMode } from \"./connection-plan\";\nimport { getRequestedType, parseConfigValue } from \"../../shared/src/value-parser\";\nimport type {\n ConfigSet,\n ConfigState,\n ConfigDirectorContext,\n ConfigDirectorClientOptions,\n ConfigDirectorClient,\n ClientEvents,\n WatchHandler,\n ConfigValueType,\n ConfigDirectorLogger,\n Transport,\n ClientConnectAction,\n IdentifyingSdkOptions,\n InternalClientOptions,\n ConfigEvaluation,\n HookHandler,\n ClientSession,\n OfflineClientOptions,\n EvaluationReason,\n} from \"./types\";\nimport { createDefaultLogger } from \"./logger\";\nimport { ConfigDirectorInitializationError, ConfigDirectorValidationError } from \"./errors\";\nimport type { LiveTelemetryClientFactory, TelemetryClient } from \"./telemetry\";\nimport { discardingTelemetryClient } from \"./telemetry/discarding\";\nimport { defaultUrlFactory } from \"@shared/url\";\nimport type { UrlFactory } from \"@shared/url\";\nimport { CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS, CLIENT_MIN_POLLING_INTERVAL_SECONDS } from \"@shared/constants\";\nimport { resolvePollingInterval } from \"@shared/transport/pollingInterval\";\nimport { resolveClientSession } from \"./client-session\";\nimport { PollingTransport } from \"./PollingTransport\";\nimport { readHost, readUserAgent } from \"./browser-globals\";\nimport { admitContext } from \"@shared/context-kind\";\nimport {\n CachedValuesStore,\n contextTagFor,\n decideCachedValuesAdoption,\n planCaching,\n type CachedValues,\n type CachingPlan,\n} from \"./cached-values\";\nconst MAX_EXPONENTIAL_DELAY = 9; // 2^9 = 512 seconds, to cap it to under 10min\n\ntype ContextSubmission = Exclude<ClientConnectAction, \"network resume\">;\n\ntype WatchHandlerWithOptions<T extends ConfigValueType> = {\n handler: WatchHandler<T>;\n defaultValue: T;\n requestedType: string;\n};\n\nexport class DefaultConfigDirectorClient implements ConfigDirectorClient {\n private logger: ConfigDirectorLogger;\n private telemetryClient: TelemetryClient;\n private configSet: ConfigSet | undefined;\n private handlersMap: Map<string, WatchHandlerWithOptions<any>[]> = new Map();\n private transport: Transport;\n private eventEmitter = new Emitter<ClientEvents>();\n private timeout: number;\n private timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n private ready = false;\n private initializing = false;\n private hasReceivedConfigSet = false;\n private readyPromise: Promise<void> | undefined;\n private readyResolve: ((cancelled?: boolean) => void) | undefined;\n private currentContext?: ConfigDirectorContext;\n private submittedContext?: ConfigDirectorContext;\n private readonly connectionPlan: ConnectionPlan;\n private clientSession: Promise<ClientSession>;\n private readonly cachedValuesStore: CachedValuesStore | undefined;\n private servingCachedValues = false;\n private cachedValuesAdoptionStarted = false;\n\n public static from(\n liveTelemetryClient: LiveTelemetryClientFactory,\n clientSdkKeyOrOptions: string | OfflineClientOptions | undefined,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions: ConfigDirectorClientOptions | undefined,\n internalClientOptions?: InternalClientOptions,\n ): DefaultConfigDirectorClient {\n if (typeof clientSdkKeyOrOptions === \"object\") {\n return new DefaultConfigDirectorClient(\n liveTelemetryClient,\n undefined,\n sdkOptions,\n clientSdkKeyOrOptions,\n internalClientOptions,\n );\n }\n return new DefaultConfigDirectorClient(\n liveTelemetryClient,\n clientSdkKeyOrOptions,\n sdkOptions,\n clientOptions,\n internalClientOptions,\n );\n }\n\n constructor(\n liveTelemetryClient: LiveTelemetryClientFactory,\n clientSdkKey: string | undefined,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n internalClientOptions?: InternalClientOptions,\n ) {\n this.logger = clientOptions?.logger ?? createDefaultLogger();\n this.clientSession = resolveClientSession(this.logger, internalClientOptions?.instanceIdStorage);\n this.timeout = clientOptions?.connection?.timeout ?? 3_000;\n const urlFactory: UrlFactory = internalClientOptions?.urlFactory ?? defaultUrlFactory;\n this.connectionPlan = planConnection(clientSdkKey, clientOptions?.connection, urlFactory);\n this.cachedValuesStore = this.buildCachedValuesStore(\n planCaching(this.connectionPlan, clientOptions?.caching, internalClientOptions?.platformCachingProvider),\n );\n this.telemetryClient = this.buildTelemetryClient(liveTelemetryClient, clientOptions);\n this.transport =\n internalClientOptions?.transport ?? this.buildTransport(sdkOptions, clientOptions, urlFactory, internalClientOptions);\n\n this.transport.on(\"configSetReceived\", (configSet: ConfigSet) => {\n this.hasReceivedConfigSet = true;\n this.servingCachedValues = false;\n this.readyResolve?.();\n const removedKeys = this.findKeysRemovedBy(configSet);\n if (!this.configSet || configSet.kind == \"full\") {\n this.configSet = configSet;\n } else {\n this.configSet.configs = {\n ...this.configSet.configs,\n ...configSet.configs,\n };\n }\n this.keepValuesOnTheDevice(this.configSet);\n const keys = Object.keys(configSet.configs);\n this.emit(\"configsUpdated\", { keys, removedKeys });\n this.updateWatchers([...keys, ...removedKeys]);\n this.logger.debug(\"[ConfigDirectorClient] ConfigSet updated from server:\", { keys, removedKeys });\n });\n\n this.transport.on(\"connectionError\", (error: Error) => {\n this.initializing = false;\n this.logger.error(\n \"[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.\",\n error,\n );\n this.emit(\"connectionError\", { error });\n });\n\n this.registerHandler(\"clientReady\", clientOptions?.hooks?.clientReady);\n this.registerHandler(\"configEvaluated\", clientOptions?.hooks?.configEvaluated);\n this.registerHandler(\"configsUpdated\", clientOptions?.hooks?.configsUpdated);\n this.registerHandler(\"contextUpdated\", clientOptions?.hooks?.contextUpdated);\n this.registerHandler(\"connectionError\", clientOptions?.hooks?.connectionError);\n this.registerHandler(\"cachedValuesLoaded\", clientOptions?.hooks?.cachedValuesLoaded);\n }\n\n private buildCachedValuesStore(cachingPlan: CachingPlan): CachedValuesStore | undefined {\n switch (cachingPlan.kind) {\n case \"no cache\":\n this.logger.debug(`[ConfigDirectorClient] No values are kept on the device: ${cachingPlan.reason}`);\n return undefined;\n case \"cache\": {\n const store = new CachedValuesStore(cachingPlan.provider, cachingPlan.clientSdkKey, this.logger);\n void store.read();\n return store;\n }\n }\n }\n\n private startCachedValuesAdoption() {\n const store = this.cachedValuesStore;\n if (!store || this.cachedValuesAdoptionStarted) {\n return;\n }\n this.cachedValuesAdoptionStarted = true;\n void this.adoptCachedValues(store);\n }\n\n private async adoptCachedValues(store: CachedValuesStore) {\n const read = await store.read();\n switch (read.outcome) {\n case \"nothing stored\":\n case \"unreadable\":\n case \"failed\":\n return;\n case \"stored\":\n break;\n }\n const { instanceId } = await this.clientSession;\n const launchContextTag = contextTagFor(this.submittedContext, instanceId);\n const adoption = decideCachedValuesAdoption(read.cachedValues, launchContextTag, this.hasReceivedConfigSet);\n switch (adoption) {\n case \"adopt\":\n this.serveCachedValues(read.cachedValues);\n return;\n case \"live values already arrived\":\n case \"context mismatch\":\n this.logger.debug(`[ConfigDirectorClient] The values kept on the device were not adopted: ${adoption}`);\n return;\n }\n }\n\n private serveCachedValues(cachedValues: CachedValues) {\n const { environmentId, projectId, configs } = cachedValues;\n this.configSet = { environmentId, projectId, configs, kind: \"full\" };\n this.servingCachedValues = true;\n const keys = Object.keys(configs);\n this.emit(\"cachedValuesLoaded\", {});\n this.emit(\"configsUpdated\", { keys, removedKeys: [] });\n this.updateWatchers(keys);\n this.logger.debug(\"[ConfigDirectorClient] Serving the values kept on the device until live values arrive:\", { keys });\n }\n\n private keepValuesOnTheDevice(configSet: ConfigSet) {\n const store = this.cachedValuesStore;\n if (!store) {\n return;\n }\n const context = this.submittedContext;\n const receivedAt = Date.now();\n void this.clientSession.then(({ instanceId }) =>\n store.replace({\n contextTag: contextTagFor(context, instanceId),\n environmentId: configSet.environmentId,\n projectId: configSet.projectId,\n configs: configSet.configs,\n receivedAt,\n }),\n );\n }\n\n private servedReason(reason: EvaluationReason): EvaluationReason {\n return this.servingCachedValues && reason === \"found-match\" ? \"cached\" : reason;\n }\n\n private registerHandler<T extends keyof ClientEvents>(\n event: T,\n handler: HookHandler<T> | HookHandler<T>[] | undefined,\n ) {\n if (!handler) {\n return;\n }\n\n const handlers = Array.isArray(handler) ? handler : [handler];\n for (const h of handlers) {\n if (typeof h === \"function\") {\n this.on(event, h);\n }\n }\n }\n\n private pollingIntervalFor(mode: LiveConnectionMode, configuredSeconds: number | undefined): number | undefined {\n if (mode !== \"polling\") {\n return undefined;\n }\n const resolved = resolvePollingInterval(configuredSeconds, {\n defaultSeconds: CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS,\n minimumSeconds: CLIENT_MIN_POLLING_INTERVAL_SECONDS,\n });\n if (resolved.warning) {\n this.logger.warn(`[ConfigDirectorClient] ${resolved.warning}`);\n }\n return resolved.seconds;\n }\n\n private buildTelemetryClient(\n liveTelemetryClient: LiveTelemetryClientFactory,\n clientOptions: ConfigDirectorClientOptions | undefined,\n ): TelemetryClient {\n const plan = this.connectionPlan;\n switch (plan.kind) {\n case \"stay-offline\":\n return discardingTelemetryClient;\n case \"connect\":\n return liveTelemetryClient({\n clientSdkKey: plan.clientSdkKey,\n baseUrl: plan.baseUrl,\n logger: this.logger,\n metadata: clientOptions?.metadata,\n });\n }\n }\n\n private buildTransport(\n sdkOptions: IdentifyingSdkOptions,\n clientOptions: ConfigDirectorClientOptions | undefined,\n urlFactory: UrlFactory,\n internalClientOptions: InternalClientOptions | undefined,\n ): Transport {\n const plan = this.connectionPlan;\n switch (plan.kind) {\n case \"stay-offline\":\n return new OfflineTransport(plan.source);\n case \"connect\": {\n const transportConstructor = this.getTransportConstructor(plan.mode);\n return new transportConstructor({\n clientSession: this.clientSession,\n clientSdkKey: plan.clientSdkKey,\n baseUrl: plan.baseUrl,\n resolveUrl: urlFactory,\n metaContext: {\n ...clientOptions?.metadata,\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n userAgent: readUserAgent(),\n host: readHost(),\n },\n logger: this.logger,\n fetch: internalClientOptions?.fetch,\n connectionRetryDelay:\n internalClientOptions?.connectionRetryDelay ??\n ((attempt: number) => {\n const seconds = Math.pow(2, Math.min(attempt, MAX_EXPONENTIAL_DELAY));\n return seconds * 1_000;\n }),\n pollingInterval: this.pollingIntervalFor(plan.mode, clientOptions?.connection?.pollingInterval),\n });\n }\n }\n }\n\n private getTransportConstructor(mode: LiveConnectionMode) {\n switch (mode) {\n case \"polling\":\n return PollingTransport;\n case \"streaming\":\n return StreamingTransport;\n }\n }\n\n public async initialize(context?: ConfigDirectorContext) {\n if (!this.hasReceivedConfigSet) {\n this.initializing = true;\n }\n await this.submitContext(context, \"initialization\");\n }\n\n public async updateContext(context: ConfigDirectorContext) {\n switch (this.connectionPlan.kind) {\n case \"connect\":\n await this.submitContext(context, \"context update\");\n return;\n case \"stay-offline\":\n this.storeContext(this.admittedContextFor(context, \"context update\"));\n return;\n }\n }\n\n private storeContext(context: ConfigDirectorContext | undefined) {\n this.currentContext = context;\n this.emit(\"contextUpdated\", { context });\n }\n\n private async submitContext(context: ConfigDirectorContext | undefined, submission: ContextSubmission) {\n await this.connectToTransport(this.admittedContextFor(context, submission), submission);\n }\n\n private admittedContextFor(\n suppliedContext: ConfigDirectorContext | undefined,\n submission: ContextSubmission,\n ): ConfigDirectorContext | undefined {\n const admission = admitContext(suppliedContext);\n switch (admission.outcome) {\n case \"admitted\":\n return admission.context;\n case \"ignored\":\n this.logger.error(\n `[ConfigDirectorClient] Ignored the context supplied for ${submission} because its kind '${admission.kindSample}' is invalid; continuing as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`,\n );\n this.telemetryClient.recordInvalidContext(admission.kindSample);\n return undefined;\n }\n }\n\n public get context(): ConfigDirectorContext | undefined {\n return this.currentContext;\n }\n\n private async connectToTransport(context: ConfigDirectorContext | undefined, caller: ClientConnectAction) {\n this.submittedContext = context;\n if (caller === \"initialization\") {\n this.startCachedValuesAdoption();\n }\n try {\n this.ready = false;\n this.readyPromise = new Promise<boolean | undefined>((resolve) => {\n this.readyResolve = resolve;\n }).then((cancelled) => {\n if (cancelled) {\n return;\n }\n this.ready = true;\n this.initializing = false;\n this.emit(\"clientReady\", { action: caller });\n this.logger.debug(\"[ConfigDirectorClient] Received initial payload from the server, client is ready\");\n });\n const startTime = new Date().getTime();\n await this.transport.connect(context ?? {}, this.timeout, caller);\n this.currentContext = context;\n this.telemetryClient\n .updateContext(context)\n .catch((error) =>\n this.logger.warn(\"[ConfigDirectorClient] Telemetry could not update the context: \", error),\n );\n this.emit(\"contextUpdated\", { context });\n\n const elapsedTime = new Date().getTime() - startTime;\n const remainingTimeout = this.timeout - elapsedTime;\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n if (remainingTimeout > 0) {\n await Promise.race([\n this.readyPromise,\n new Promise<void>((resolve) => {\n this.timeoutTimer = setTimeout(() => resolve(), remainingTimeout);\n }),\n ]).finally(() => clearTimeout(this.timeoutTimer));\n }\n\n if (!this.ready) {\n this.logger.warn(\n `[ConfigDirectorClient] Timed out waiting for ${caller} after ${this.timeout}ms. ${this.timeoutWarningDetails()}`,\n );\n }\n } catch (error) {\n if (error instanceof ConfigDirectorInitializationError) {\n this.initializing = false;\n throw error;\n }\n this.logger.error(`[ConfigDirectorClient] An error occurred during ${caller}: `, error);\n }\n }\n\n private timeoutWarningDetails(): string {\n switch (this.connectionPlan.kind) {\n case \"connect\":\n return \"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.\";\n case \"stay-offline\":\n return \"The offline values were not delivered, so configs return the default value.\";\n }\n }\n\n private findKeysRemovedBy(configSet: ConfigSet): string[] {\n if (!this.configSet || configSet.kind != \"full\") {\n return [];\n }\n return Object.keys(this.configSet.configs).filter((key) => !Object.prototype.hasOwnProperty.call(configSet.configs, key));\n }\n\n private updateWatchers(configKeys: string[]) {\n configKeys.forEach((configKey) => this.updateWatchersForConfig(configKey));\n }\n\n private updateWatchersForConfig(configKey: string) {\n const configState = this.configSet?.configs[configKey];\n this.handlersMap.get(configKey)?.forEach((h) => {\n const value = this.getValueFromConfigState(configKey, configState, h.defaultValue);\n h.handler(value);\n });\n }\n\n public watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>) {\n this.validateDefaultValue(defaultValue);\n\n const handlers = this.handlersMap.get(configKey);\n const handlerWithOptions = { handler: callback, defaultValue, requestedType: typeof defaultValue };\n if (handlers) {\n handlers.push(handlerWithOptions);\n } else {\n this.handlersMap.set(configKey, [handlerWithOptions]);\n }\n\n return () => this.unwatch(configKey, callback);\n }\n\n public unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>) {\n const handlers = this.handlersMap.get(configKey);\n if (!handlers) {\n return;\n }\n\n if (callback) {\n const index = handlers.findIndex((h) => h.handler == callback);\n if (index >= 0) {\n handlers?.splice(index, 1);\n }\n } else {\n handlers.splice(0);\n }\n }\n\n public getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T {\n this.validateDefaultValue(defaultValue);\n\n const configState = this.configSet?.configs[configKey];\n return this.getValueFromConfigState(configKey, configState, defaultValue);\n }\n\n private getValueFromConfigState<T extends ConfigValueType>(\n configKey: string,\n configState: ConfigState | undefined,\n defaultValue: T,\n ): T {\n if (!configState) {\n this.logger.debug(\n `[ConfigDirectorClient] No config state found for '${configKey}', returning default value '${defaultValue}'`,\n );\n const reason = this.isReady ? \"config-state-missing\" : \"client-not-ready\";\n this.telemetryClient.evaluatedConfig({\n contextId: this.currentContext?.id,\n key: configKey,\n defaultValue: defaultValue,\n requestedType: getRequestedType(defaultValue),\n evaluatedValue: defaultValue,\n usedDefault: true,\n evaluationReason: reason,\n });\n this.dispatchEvaluationEvent({\n key: configKey,\n value: defaultValue,\n isDefaultValue: true,\n reason,\n context: this.context,\n });\n return defaultValue;\n }\n\n const parseResult = parseConfigValue<T>(configState, defaultValue);\n const reason = this.servedReason(parseResult.reason);\n this.telemetryClient.evaluatedConfig({\n contextId: this.currentContext?.id,\n type: configState.type,\n key: configKey,\n defaultValue: defaultValue,\n requestedType: parseResult.requestedType,\n evaluatedValue: parseResult.parsedValue,\n evaluatedValueId: parseResult.parsedValueId,\n usedDefault: parseResult.usedDefault,\n evaluationReason: reason,\n });\n this.dispatchEvaluationEvent({\n key: configKey,\n value: parseResult.parsedValue,\n valueId: parseResult.parsedValueId ?? undefined,\n isDefaultValue: parseResult.usedDefault,\n reason,\n context: this.context,\n });\n this.logger.debug(`[ConfigDirectorClient] Evaluated '${configKey}' to '${parseResult.parsedValue}'`);\n return parseResult.parsedValue;\n }\n\n private dispatchEvaluationEvent(event: ConfigEvaluation) {\n setTimeout(() => this.emit(\"configEvaluated\", { evaluation: event }), 0);\n }\n\n private emit<TName extends keyof ClientEvents>(name: TName, payload: ClientEvents[TName]) {\n try {\n this.eventEmitter.emit(name, payload);\n } catch (error) {\n this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${name}'`, error);\n }\n }\n\n private validateDefaultValue<T extends ConfigValueType>(defaultValue: T) {\n if (defaultValue === undefined || defaultValue === null) {\n throw new ConfigDirectorValidationError(\n \"Invalid default value. The default value for a config must be defined and non-null.\",\n );\n }\n\n if (typeof defaultValue === \"function\") {\n throw new ConfigDirectorValidationError(\n \"Invalid default value. The default value for a config cannot be a function.\",\n );\n }\n }\n\n public get isReady(): boolean {\n return this.ready;\n }\n\n public get isInitializing(): boolean {\n return this.initializing;\n }\n\n public on<T extends keyof ClientEvents>(eventName: T, handler: (event: ClientEvents[T]) => void): void {\n this.eventEmitter.on(eventName, handler);\n }\n\n public off<T extends keyof ClientEvents>(eventName: T, handler?: (payload: ClientEvents[T]) => void) {\n this.eventEmitter.off(eventName, handler);\n }\n\n public clear() {\n this.logger.debug(\"[ConfigDirectorClient] clear() has been called, removing all observers\");\n this.eventEmitter.clear();\n this.handlersMap.clear();\n }\n\n public unwatchAll() {\n this.handlersMap.clear();\n }\n\n public pauseNetwork(): void {\n switch (this.connectionPlan.kind) {\n case \"stay-offline\":\n return;\n case \"connect\":\n this.logger.debug(\"[ConfigDirectorClient] pauseNetwork() called, pausing transport connection\");\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n this.transport.close();\n this.ready = false;\n return;\n }\n }\n\n public async resumeNetwork(): Promise<void> {\n switch (this.connectionPlan.kind) {\n case \"stay-offline\":\n return;\n case \"connect\":\n await this.connectToTransport(this.currentContext, \"network resume\");\n return;\n }\n }\n\n public async close() {\n this.logger.debug(\"[ConfigDirectorClient] close() has been called, closing connection to server\");\n clearTimeout(this.timeoutTimer);\n this.readyResolve?.(true);\n this.telemetryClient\n .close()\n .catch((error) => this.logger.warn(\"[ConfigDirectorClient] Telemetry could not close: \", error));\n this.transport.close();\n this.ready = false;\n this.initializing = false;\n }\n\n public dispose() {\n this.clear();\n this.close();\n }\n}\n","import type { ConfigDirectorClient } from \"./types\";\n\nexport const INSTALLED_TEST_CLIENT_SLOT = Symbol.for(\"@configdirector/installed-test-client\");\n\nexport type InstalledTestClientSlot = { [INSTALLED_TEST_CLIENT_SLOT]?: ConfigDirectorClient };\n\nexport const readInstalledTestClient = (): ConfigDirectorClient | undefined =>\n (globalThis as InstalledTestClientSlot)[INSTALLED_TEST_CLIENT_SLOT];\n"],"mappings":"6uCAaA,IAAa,EAAb,KAAiG,eAC/F,KAAQ,WAAsE,IAAI,IAElF,GAAsC,EAAa,EAAwC,CACzF,IAAM,EAAW,KAAK,WAAW,IAAI,EAAK,CACtC,EACF,EAAS,KAAK,EAAQ,CAEtB,KAAK,WAAW,IAAI,EAAM,CAAC,EAAQ,CAAC,CAIxC,KAAwC,EAAa,EAAwC,CAE3F,IAAM,EAAO,KACb,SAAS,EAAY,EAA6C,CAChE,EAAK,IAAI,EAAM,EAAY,CAC3B,EAAQ,MAAM,EAAM,EAAQ,CAE9B,KAAK,GAAG,EAAM,EAAY,CAG5B,IAAuC,EAAa,EAAyC,CAC3F,IAAM,EAAW,KAA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ACpB,KAAK,UAAU,OAAO,CACtB,KAAK,MAAQ,GACb,QAIN,MAAa,eAA+B,YAC1C,OAAQA,EAAK,eAAe,KAA5B,CACE,IAAK,eACH,OACF,IAAK,UACH,MAAMA,EAAK,mBAAmBA,EAAK,eAAgB,iBAAiB,CACpE,QAIN,MAAa,OAAQ,cACnB,EAAK,OAAO,MAAM,+EAA+E,CACjG,aAAaA,EAAK,aAAa,EAC/B,EAAA,EAAK,eAAA,MAAA,EAAA,KAAA,EAAe,GAAK,CACzB,EAAK,gBACF,OAAO,CACP,MAAO,GAAUA,EAAK,OAAO,KAAK,qDAAsD,EAAM,CAAC,CAClG,EAAK,UAAU,OAAO,CACtB,EAAK,MAAQ,GACb,EAAK,aAAe,GAGtB,SAAiB,CACf,KAAK,OAAO,CACZ,KAAK,OAAO,GCloBhB,MAAa,EAA6B,OAAO,IAAI,wCAAwC,CAIhF,OACV,WAAuC"}
|
|
@@ -20,7 +20,7 @@ interface ConfigDirectorLogger {
|
|
|
20
20
|
warn(message: string, ...args: any): void;
|
|
21
21
|
error(message: string, ...args: any): void;
|
|
22
22
|
}
|
|
23
|
-
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
|
|
23
|
+
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
|
|
24
24
|
type ConfigEvaluation = {
|
|
25
25
|
key: string;
|
|
26
26
|
value: ConfigValueType;
|
|
@@ -39,9 +39,11 @@ type ConfigDirectorContext = {
|
|
|
39
39
|
* The context's identifier. This should be a value that uniquely identifies the user or other
|
|
40
40
|
* entity among contexts of the same {@link kind}.
|
|
41
41
|
* In the case of anonymous users, you could generate a UUID or alternatively not provide
|
|
42
|
-
* the {@link id}
|
|
43
|
-
*
|
|
44
|
-
*
|
|
42
|
+
* the {@link id}. In a client SDK, ConfigDirector then derives an identifier from an ID the SDK
|
|
43
|
+
* stores for the app install or the website, so it stays the same until the app is uninstalled
|
|
44
|
+
* or the site's data is cleared. However, keep in mind that this value is used for segmenting
|
|
45
|
+
* contexts in percentage rollouts, and changes to the {@link id} could result in the context
|
|
46
|
+
* being assigned to a different percentile.
|
|
45
47
|
*/
|
|
46
48
|
id?: string;
|
|
47
49
|
/**
|
|
@@ -89,6 +91,45 @@ type NativeValue = boolean | number | string | NativeJsonValue[] | {
|
|
|
89
91
|
type NativeValues = Record<string, NativeValue>;
|
|
90
92
|
//#endregion
|
|
91
93
|
//#region ../js-client-core/src/types.d.ts
|
|
94
|
+
/**
|
|
95
|
+
* A store for the values the client keeps on the device between launches. One provider instance
|
|
96
|
+
* serves one client: the provider decides where the entry lives, and the SDK owns the entry's
|
|
97
|
+
* format, which may change between SDK versions.
|
|
98
|
+
*/
|
|
99
|
+
type CachingProvider = {
|
|
100
|
+
/**
|
|
101
|
+
* Returns the stored entry, or `null` or `undefined` when nothing is stored.
|
|
102
|
+
*/
|
|
103
|
+
read(): string | null | undefined | Promise<string | null | undefined>;
|
|
104
|
+
/**
|
|
105
|
+
* Replaces the stored entry. The SDK never writes an entry larger than {@link sizeLimit}.
|
|
106
|
+
*/
|
|
107
|
+
write(value: string): void | Promise<void>;
|
|
108
|
+
/**
|
|
109
|
+
* Removes the stored entry.
|
|
110
|
+
*/
|
|
111
|
+
remove(): void | Promise<void>;
|
|
112
|
+
/**
|
|
113
|
+
* The largest entry, in UTF-8 bytes, the provider accepts. When the values received from
|
|
114
|
+
* ConfigDirector exceed it, the SDK removes the stored entry and keeps nothing on the device.
|
|
115
|
+
*/
|
|
116
|
+
sizeLimit(): number;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Options for the values the client keeps on the device, served on the next launch of the same
|
|
120
|
+
* context until live values arrive. Ignored in `offline` mode.
|
|
121
|
+
*/
|
|
122
|
+
type CachingOptions = {
|
|
123
|
+
/**
|
|
124
|
+
* Whether to keep the last values received on the device. Defaults to `true`.
|
|
125
|
+
*/
|
|
126
|
+
enabled?: boolean;
|
|
127
|
+
/**
|
|
128
|
+
* The store for the values. Defaults to the platform's own store: `localStorage` in the
|
|
129
|
+
* browser, AsyncStorage on React Native.
|
|
130
|
+
*/
|
|
131
|
+
provider?: CachingProvider;
|
|
132
|
+
};
|
|
92
133
|
/**
|
|
93
134
|
* One value an offline client serves for a config key. The config type follows from the value: a
|
|
94
135
|
* boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
|
|
@@ -106,6 +147,7 @@ type ClientHooks = {
|
|
|
106
147
|
contextUpdated?: HookHandler<"contextUpdated"> | HookHandler<"contextUpdated">[];
|
|
107
148
|
configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
|
|
108
149
|
connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
|
|
150
|
+
cachedValuesLoaded?: HookHandler<"cachedValuesLoaded"> | HookHandler<"cachedValuesLoaded">[];
|
|
109
151
|
};
|
|
110
152
|
type ClientConnectAction = "initialization" | "context update" | "network resume";
|
|
111
153
|
type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
|
|
@@ -126,6 +168,7 @@ type ClientEvents = {
|
|
|
126
168
|
connectionError: {
|
|
127
169
|
error: Error;
|
|
128
170
|
};
|
|
171
|
+
cachedValuesLoaded: Record<string, never>;
|
|
129
172
|
};
|
|
130
173
|
type WatchHandler<T extends ConfigValueType> = (message: T) => void;
|
|
131
174
|
/**
|
|
@@ -247,5 +290,5 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
|
|
|
247
290
|
dispose(): void;
|
|
248
291
|
}
|
|
249
292
|
//#endregion
|
|
250
|
-
export {
|
|
251
|
-
//# sourceMappingURL=types-
|
|
293
|
+
export { OfflineValue as a, NativeValue as c, ConfigDirectorLogger as d, ConfigDirectorLoggingLevel as f, ConfigDirectorClient as i, NativeValues as l, ConnectionMode as m, CachingProvider as n, OfflineValues as o, ConfigValueType as p, ClientHooks as r, NativeJsonValue as s, CachingOptions as t, ConfigDirectorContext as u };
|
|
294
|
+
//# sourceMappingURL=types-CFBLmqUM.d.cts.map
|