@configdirector/openfeature-web-provider 1.10.0 → 1.11.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.
@@ -1,5 +1,5 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@openfeature/web-sdk`);var 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)}};const i=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}};var a=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},o=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new a,this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.clientSession=e.clientSession,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{return new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl),this.clientSession=e.clientSession}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let{instanceId:i}=await this.clientSession,a={clientSdkKey:this.sdkKey,instanceId:i,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(a))return{success:!0,fatalError:!1};let o=await this.sendReport(a);return o.fatalError&&(this.executeRequests=!1),o}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},d=class extends c{constructor(e){super(e),this.invalidContextSubmissions=new u,this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}recordInvalidContext(e){this.invalidContextSubmissions.record(e)}absorbInvalidContextSubmissions(e){this.invalidContextSubmissions.absorb(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let f=(e,t)=>new URL(e,t?.toString()),p=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},m=Math.ceil(128/Math.log2(62)),h=new TextEncoder,g=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,h.encode(e?.toString()??``));return p(new Uint8Array(t,0,16),m)},_,v,y=new Promise(e=>{v=e}),b=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),x=e=>{try{self.postMessage(e)}catch{self.postMessage(b(e.payload.level,e.payload.message))}},S={debug:function(e,...t){x(b(`debug`,e,t))},info:function(e,...t){x(b(`info`,e,t))},warn:function(e,...t){x(b(`warn`,e,t))},error:function(e,...t){x(b(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){S.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(S.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){S.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:S,clientSession:y}),_.start();break;case`ClientSession`:v(t.payload);break;case`EvaluatedConfigEvent`:_?.evaluatedConfig(t.payload);break;case`InvalidContextSubmissions`:_?.absorbInvalidContextSubmissions(t.payload.entries);break;case`UpdateContext`:_?.updateContext(t.payload.context);break;case`Flush`:_?.forceFlush();break;case`Close`:(_?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.forwardClientSession(e),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,this.forwardInvalidContextSubmissions(e),e}}forwardClientSession(e){this.clientSession.then(t=>{let n={type:`ClientSession`,payload:t};e.postMessage(n)})}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}async updateContext(e){if(this.closePromise)return;let t={type:`UpdateContext`,payload:{context:e}};this.startWorker()?.postMessage(t)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:i({value:e.defaultValue,type:e.type}),evaluatedValue:i({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}},s=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))}},c=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},ee=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},te=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},ne=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},l=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===`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@openfeature/web-sdk`);var 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)}};const i=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}};var a=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}};const o=e=>e>=55296&&e<=56319,s=e=>e>=56320&&e<=57343,c=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:o(r)&&n+1<e.length&&s(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t},ee=e=>{let t=e?.anonymous?void 0:e?.id;return t===void 0?{}:{contextKind:e?.kind??`user`,contextIdentifier:t}},l=1024,te={"name-outside-the-character-limit":`[ConfigDirectorClient] A tracked event was not reported because its name does not have 1 to 150 characters.`,"value-not-a-finite-number":`[ConfigDirectorClient] A tracked event was reported without its value because the value is not a finite number.`,"details-not-reportable":`[ConfigDirectorClient] A tracked event was reported without its details because they are not an object, have more than 20 top-level keys, are larger than ${l} bytes as JSON, or cannot be written as JSON.`,"batch-already-full":`[ConfigDirectorClient] A tracked event was not reported because 1000 tracked events are already waiting for the next telemetry batch.`},ne=(e,t)=>{for(let n of t)e.warn(`${te[n]} Further tracked events like it are not logged until the next telemetry batch is sent.`)},u=e=>e!=null,d=e=>typeof e==`object`&&!!e&&!Array.isArray(e),f=e=>typeof e==`string`&&e.length>=1&&e.length<=300&&Array.from(e).length<=150,p=e=>u(e)?typeof e==`number`&&Number.isFinite(e)?{status:`reportable`,fields:{value:e}}:{status:`left-out`,warning:`value-not-a-finite-number`}:{status:`not-given`},m=e=>{if(d(e))try{let t=JSON.stringify(e);if(typeof t!=`string`||c(t)>l)return;let n=JSON.parse(t);return d(n)&&Object.keys(n).length<=20?n:void 0}catch{return}},h=e=>{if(!u(e))return{status:`not-given`};let t=m(e);return t===void 0?{status:`left-out`,warning:`details-not-reportable`}:{status:`reportable`,fields:{details:t}}},g=e=>e.status===`reportable`?e.fields:void 0,re=(...e)=>e.flatMap(e=>e.status===`left-out`?[e.warning]:[]),ie=e=>{if(!f(e.name))return{outcome:`dropped`,warnings:[`name-outside-the-character-limit`]};let t=p(e.options?.value),n=h(e.options?.details);return{outcome:`admitted`,entry:{name:e.name,...ee(e.context),...g(t),...g(n),happenedAt:e.happenedAt.toISOString()},warnings:re(t,n)}};var ae=class{constructor(){this.entries=[],this.warningsRaisedThisBatch=new Set}add(e){return this.warningsOfKeeping(e).filter(e=>this.isFirstThisBatch(e))}absorb(e){this.entries.push(...e)}takeBatch(){let e=this.entries;return this.clear(),e}clear(){this.entries=[],this.warningsRaisedThisBatch.clear()}warningsOfKeeping(e){switch(e.outcome){case`dropped`:return e.warnings;case`admitted`:return this.entries.length>=1e3?[`batch-already-full`]:(this.entries.push(e.entry),e.warnings)}}isFirstThisBatch(e){return this.warningsRaisedThisBatch.has(e)?!1:(this.warningsRaisedThisBatch.add(e),!0)}},oe=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new a,this.pendingTrackedEvents=new ae,this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.clientSession=e.clientSession,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{return new Worker(URL.createObjectURL(new Blob(['(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError,a=e=>e>=55296&&e<=56319,o=e=>e>=56320&&e<=57343,s=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:a(r)&&n+1<e.length&&o(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t};var c=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl),this.clientSession=e.clientSession}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let{instanceId:i}=await this.clientSession,a={clientSdkKey:this.sdkKey,instanceId:i,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(a))return{success:!0,fatalError:!1};let o=await this.sendReport(a);return o.fatalError&&(this.executeRequests=!1),o}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=JSON.stringify(e),n=await r(5e3,this.url,{method:`POST`,body:t,keepalive:s(t)<=32768},this.logger),i=this.isStatusFatal(n.status);return i&&this.logger.warn(`[EventReporter] Received a fatal status response (${n.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:n.ok,fatalError:i}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},l=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},u=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}};let d={"name-outside-the-character-limit":`[ConfigDirectorClient] A tracked event was not reported because its name does not have 1 to 150 characters.`,"value-not-a-finite-number":`[ConfigDirectorClient] A tracked event was reported without its value because the value is not a finite number.`,"details-not-reportable":`[ConfigDirectorClient] A tracked event was reported without its details because they are not an object, have more than 20 top-level keys, are larger than 1024 bytes as JSON, or cannot be written as JSON.`,"batch-already-full":`[ConfigDirectorClient] A tracked event was not reported because 1000 tracked events are already waiting for the next telemetry batch.`},f=(e,t)=>{for(let n of t)e.warn(`${d[n]} Further tracked events like it are not logged until the next telemetry batch is sent.`)};var p=class{constructor(){this.entries=[],this.warningsRaisedThisBatch=new Set}add(e){return this.warningsOfKeeping(e).filter(e=>this.isFirstThisBatch(e))}absorb(e){this.entries.push(...e)}takeBatch(){let e=this.entries;return this.clear(),e}clear(){this.entries=[],this.warningsRaisedThisBatch.clear()}warningsOfKeeping(e){switch(e.outcome){case`dropped`:return e.warnings;case`admitted`:return this.entries.length>=1e3?[`batch-already-full`]:(this.entries.push(e.entry),e.warnings)}}isFirstThisBatch(e){return this.warningsRaisedThisBatch.has(e)?!1:(this.warningsRaisedThisBatch.add(e),!0)}},m=class{constructor(e){this.aggregator=new l,this.trackedEventQueue=new p,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new u(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}trackedEvent(e){this.collectEvents&&f(this.logger,this.trackedEventQueue.add(e))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear(),this.trackedEventQueue.clear()}dispose(){this.close()}},h=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},g=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},_=class extends m{constructor(e){super(e),this.invalidContextSubmissions=new g,this.reporter=new c(e),this.evaluationEventSnapshotPreprocessor=new h(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}recordInvalidContext(e){this.invalidContextSubmissions.record(e)}absorbInvalidContextSubmissions(e){this.invalidContextSubmissions.absorb(e)}absorbTrackedEventEntries(e){this.trackedEventQueue.absorb(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{trackedEvents:this.trackedEventQueue.takeBatch()},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let v=(e,t)=>new URL(e,t?.toString()),y=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},b=Math.ceil(128/Math.log2(62)),x=new TextEncoder,S=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,x.encode(e?.toString()??``));return y(new Uint8Array(t,0,16),b)},C,w,T=new Promise(e=>{w=e}),E=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),D=e=>{try{self.postMessage(e)}catch{self.postMessage(E(e.payload.level,e.payload.message))}},O={debug:function(e,...t){D(E(`debug`,e,t))},info:function(e,...t){D(E(`info`,e,t))},warn:function(e,...t){D(E(`warn`,e,t))},error:function(e,...t){D(E(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!C){O.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(O.debug(`[TelemetryWorker] Received \'${t.type}\' event:`,t),t.type){case`Initialize`:if(C){O.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}C=new _({...t.payload,baseUrl:v(t.payload.baseUrl),urlFactory:v,valueIdGenerator:S,logger:O,clientSession:T}),C.start();break;case`ClientSession`:w(t.payload);break;case`EvaluatedConfigEvent`:C?.evaluatedConfig(t.payload);break;case`InvalidContextSubmissions`:C?.absorbInvalidContextSubmissions(t.payload.entries);break;case`TrackedEvent`:C?.trackedEvent(t.payload);break;case`TrackedEventEntries`:C?.absorbTrackedEventEntries(t.payload.entries);break;case`UpdateContext`:C?.updateContext(t.payload.context);break;case`Flush`:C?.forceFlush();break;case`Close`:(C?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();'],{type:`application/javascript`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.pendingTrackedEvents.clear(),this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.forwardClientSession(e),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,this.forwardInvalidContextSubmissions(e),this.forwardPendingTrackedEvents(e),e}}forwardPendingTrackedEvents(e){let t=this.pendingTrackedEvents.takeBatch();if(t.length===0)return;let n={type:`TrackedEventEntries`,payload:{entries:t}};e.postMessage(n)}forwardClientSession(e){this.clientSession.then(t=>{let n={type:`ClientSession`,payload:t};e.postMessage(n)})}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}async updateContext(e){if(this.closePromise)return;let t={type:`UpdateContext`,payload:{context:e}};this.startWorker()?.postMessage(t)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}trackedEvent(e){if(!(this.turnedOff||this.closePromise)){if(this.worker){let t={type:`TrackedEvent`,payload:e};this.worker.postMessage(t);return}ne(this.logger,this.pendingTrackedEvents.add(e))}}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:i({value:e.defaultValue,type:e.type}),evaluatedValue:i({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.pendingTrackedEvents.clear(),this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}},_=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))}},se=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},ce=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},le=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},ue=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},de=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
2
  `?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
3
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
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 u=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var d=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=u.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===u.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=u.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=u.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 ee(`The server response did not have a body`);this._readyState=u.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new l({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new c(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=u.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=u.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new ne(`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 te(`${n} must be a function`);return e}};const f=e=>new d(e);var p=class{constructor(e){this.options=e,this.eventEmitter=new s,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.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=f({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 m=(e,t)=>{if(e.trim().length==0)throw new n(`Invalid config key. The key of a value cannot be empty.`);return h(e,t)},h=(e,t)=>{switch(typeof t){case`boolean`:return{type:`boolean`,value:t?`true`:`false`};case`number`:return re(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}': ${v(t)}. Use a boolean, a number, a string, a plain object, or an array.`)},re=(e,t)=>{if(!Number.isFinite(t))throw new n(`Invalid value for '${e}': ${v(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:ie(t)}},ie=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,`${v(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>g(e,t,`${n}[${r}]`));return}if(ae(t)){for(let[r,i]of Object.entries(t))g(e,i,n?`${n}.${r}`:r);return}throw _(e,n,`${v(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.`),ae=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},v=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),oe=(e,t,n,r)=>{let i=m(t,n);return{id:e,key:t,type:i.type,value:i.value,valueId:r}},se={environmentId:`offline`,projectId:`offline`};var ce=class{constructor(e){this.source=e,this.emitter=new s,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t)}async connect(){let e=le(this.source);return this.emitter.emit(`configSetReceived`,{...se,kind:`full`,configs:e}),this}clear(){this.emitter.clear()}close(){}dispose(){this.clear()}};const le=e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return ue(e.values);case`rejected`:throw new r(e.message)}},ue=e=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,oe(`offline:${e}`,e,t,void 0)]))}catch(e){throw e instanceof n?new r(`The offline values could not be loaded. ${e.message}`):e}},y=(e,t,r)=>{if(t?.mode===`offline`)return{kind:`stay-offline`,source:x(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:b(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}'.`}}},b=(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}`)}},x=e=>e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values},S=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},C=e=>e===`number`||e===`bigint`,w=new Set([`boolean`,`integer`,`float`]),T=(e,t)=>{let n=e.value,r=S(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return j(n,t,r,e.valueId);if(typeof t==`string`)return w.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=E(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(C(typeof t)&&e.type===`integer`){let i=D(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(C(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=O(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`}},E=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},D=e=>{let t=k(e);return t==null?void 0:Math.trunc(t)},O=e=>k(e),k=e=>{if(!e||!A(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},A=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},j=(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 M(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`}}},M=(e,t)=>e===null?!1:N(e)===N(t),N=e=>{if(Array.isArray(e))return`array`;let t=typeof e;return t===`bigint`?`number`:t},P={off:-1,error:0,warn:1,info:2,debug:3},F=()=>{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 I=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=F()}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){P[this.level]>=P[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},L=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const R=(e,t)=>new I(e??`warn`,t??new L),z={updateContext:async()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>{},close:async()=>{}},B=(e,t)=>new URL(e,t?.toString()),V=(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.`},H=()=>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)}),U=e=>{try{return e(globalThis)}catch{return}},de=()=>U(e=>e.navigator?.userAgent),fe=()=>U(e=>e.location?.host),W=()=>{try{return globalThis.localStorage??void 0}catch{return}},G=`configdirector-sdk:instance-id`,K=1e3,pe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,q=(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},J=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=q(n,2166136261);return q(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},me=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||!pe.test(n)?!1:i===J(n,r)},he=async(e,t)=>{let n;try{n=await e.getItem(G)}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 me(r)?{outcome:`stored`,instanceId:r.id}:(t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`})},ge=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:J(t,r)};try{return await e.setItem(G,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},_e=async(e,t,n,r)=>{let i=await he(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 ge(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},ve=(e,t=W())=>{let n=H();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 ${K}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},K)});return Promise.race([_e(t,n,r,e),a]).finally(()=>clearTimeout(i))};var ye=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 be=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 xe=class extends ye{constructor(e){super(),this.options=e,this.eventEmitter=new s,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??60}async connect(e,t){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 be(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 Se=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,Ce=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!Se(t))return!1;return!0},we=e=>e==null||typeof e==`string`&&Ce(e),Te=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},Ee=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},De=e=>{let t=e?.kind;return we(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:Ee(Te(t),128)}},Oe=e=>e>=55296&&e<=56319,ke=e=>e>=56320&&e<=57343,Ae=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:Oe(r)&&n+1<e.length&&ke(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t},je=(e,t,n,r)=>{if(e.kind===`stay-offline`)return{kind:`no cache`,reason:`offline mode`};if(t?.enabled===!1)return{kind:`no cache`,reason:`turned off`};if(!n)return{kind:`no cache`,reason:`no SHA-256 available`};let i=n(e.clientSdkKey),a=t?.provider??r?.(i);return a?{kind:`cache`,provider:a,clientSdkKeyDigest:i}:{kind:`no cache`,reason:`no provider available`}},Y=(e,t)=>{let n=e?.kind??`user`;return e?.id==null?{contextKind:n,anonymousInstanceId:t}:{contextKind:n,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===2&&n.clientSdkKeyDigest===e&&Pe(n.contextTag)&&typeof n.environmentId==`string`&&typeof n.projectId==`string`&&Fe(n.configs)&&typeof n.receivedAt==`number`},Le=e=>!!e&&typeof e==`object`&&e.formatVersion===1,Re=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{outcome:`unreadable`}}return Ie(t,n)?{outcome:`stored`,cachedValues:n}:Le(n)?{outcome:`first format`}:{outcome:`unreadable`}};var ze=class{constructor(e,t,n){this.provider=e,this.clientSdkKeyDigest=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=Re(e,await this.clientSdkKeyDigest);switch(t.outcome){case`stored`:return t;case`first format`:return await this.removeEntry(),t;case`unreadable`:return this.warnOnce(`unreadable`,`The values kept on the device could not be read and were removed, starting without them`),await this.removeEntry(),t}}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:2,clientSdkKeyDigest:await this.clientSdkKeyDigest,...e},n=JSON.stringify(t),r=Ae(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))}},Be=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){this.handlersMap=new Map,this.eventEmitter=new s,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.servingCachedValues=!1,this.cachedValuesAdoptionStarted=!1,this.logger=r?.logger??R(),this.clientSession=ve(this.logger,i?.instanceIdStorage),this.timeout=r?.connection?.timeout??3e3;let a=i?.urlFactory??B;this.connectionPlan=y(t,r?.connection,a),this.cachedValuesStore=this.buildCachedValuesStore(je(this.connectionPlan,r?.caching,i?.sha256HexDigest,i?.platformCachingProvider)),this.telemetryClient=this.buildTelemetryClient(e,r),this.transport=i?.transport??this.buildTransport(n,r,a,i),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`,r?.hooks?.clientReady),this.registerHandler(`configEvaluated`,r?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,r?.hooks?.configsUpdated),this.registerHandler(`contextUpdated`,r?.hooks?.contextUpdated),this.registerHandler(`connectionError`,r?.hooks?.connectionError),this.registerHandler(`cachedValuesLoaded`,r?.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 ze(e.provider,e.clientSdkKeyDigest,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`first format`:case`unreadable`:case`failed`:return;case`stored`:break}let{instanceId:n}=await this.clientSession,r=Y(this.submittedContext,n),i=Ne(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:Y(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=V(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 z;case`connect`:return e({clientSdkKey:n.clientSdkKey,baseUrl:n.baseUrl,logger:this.logger,metadata:t?.metadata,clientSession:this.clientSession})}}buildTransport(e,t,n,r){let i=this.connectionPlan;switch(i.kind){case`stay-offline`:return new ce(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:de(),host:fe()},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 xe;case`streaming`:return p}}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=De(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.evaluationOf(e,t,n.defaultValue).value;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){return this.evaluate(e,t).value}evaluate(e,t){this.validateDefaultValue(t);let n=this.configSet?.configs[e];return this.evaluationOf(e,n,t)}evaluationOf(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`;this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:S(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t});let r={key:e,value:n,isDefaultValue:!0,reason:t,context:this.context};return this.dispatchEvaluationEvent(r),r}let r=T(t,n),i=this.servedReason(r.reason);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});let a={key:e,value:r.parsedValue,valueId:r.parsedValueId??void 0,isDefaultValue:r.usedDefault,reason:i,context:this.context};return this.dispatchEvaluationEvent(a),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),a}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 Ve=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},He=Math.ceil(128/Math.log2(62)),Ue=new TextEncoder,We=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,Ue.encode(e?.toString()??``));return Ve(new Uint8Array(t,0,16),He)},X=e=>{let t=W();if(!t)return;let n=e.then(e=>`configdirector-sdk:cached-values:`+e);return{read:async()=>t.getItem(await n),write:async e=>t.setItem(await n,e),remove:async()=>t.removeItem(await n),sizeLimit:()=>262144}},Ge=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),Ke=()=>{if(!(typeof crypto>`u`||crypto.subtle==null))return async e=>{let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Ge(new Uint8Array(t))}},qe=(e,t,n)=>Be.from(({clientSdkKey:e,baseUrl:n,logger:r,metadata:i,clientSession:a})=>new o({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:i?.appName,appVersion:i?.appVersion},logger:r,baseUrl:n,urlFactory:B,valueIdGenerator:We,clientSession:a}),e,t,n,{sha256HexDigest:Ke(),platformCachingProvider:X}),Z=(t,n,r)=>({value:t,reason:e.StandardResolutionReasons.ERROR,errorCode:n,errorMessage:r}),Q=t=>Z(t.value,e.ErrorCode.TYPE_MISMATCH,`The value of '${t.key}' cannot be read as the requested type (${t.reason}).`),Je={"found-match":t=>({value:t.value,variant:t.valueId,reason:e.StandardResolutionReasons.TARGETING_MATCH}),cached:t=>({value:t.value,variant:t.valueId,reason:e.StandardResolutionReasons.CACHED}),"value-missing":t=>({value:t.value,reason:e.StandardResolutionReasons.DEFAULT}),"config-state-missing":t=>Z(t.value,e.ErrorCode.FLAG_NOT_FOUND,`No config with the key '${t.key}' was found.`),"client-not-ready":t=>Z(t.value,e.ErrorCode.PROVIDER_NOT_READY,`ConfigDirector has not delivered config state yet.`),"type-mismatch":Q,"invalid-number":Q,"invalid-json":Q,"invalid-boolean":Q},$=e=>Je[e.reason](e),Ye={sdkName:`js-openfeature-web-provider`,sdkVersion:`1.10.0`},Xe=(e,t)=>e&&t?`stale`:`as the SDK recorded it`;var Ze=class{constructor(t,n){this.awaitingRecovery=!1,this.servingCachedValues=!1,this.metadata={name:`ConfigDirectorProvider`},this.runsOn=`client`,this.events=new e.OpenFeatureEventEmitter,this.client=qe(t,Ye,n),this.client.on(`clientReady`,()=>{this.servingCachedValues=!1,this.awaitingRecovery&&(this.awaitingRecovery=!1,this.events.emit(e.ProviderEvents.Ready))}),this.client.on(`cachedValuesLoaded`,()=>{this.servingCachedValues=!0,this.reportStatusOnceTheSdkRecordedTheOutcome()}),this.client.on(`configsUpdated`,({keys:t,removedKeys:n})=>{this.events.emit(e.ProviderEvents.ConfigurationChanged,{flagsChanged:[...t,...n]})})}async initialize(e){this.awaitingRecovery=!1,await this.client.initialize(this.mapContext(e)),this.requireReady(`ConfigDirector did not become ready during initialization. Flags resolve to their default values until the connection succeeds.`)}async onContextChange(e,t){this.awaitingRecovery=!1,await this.client.updateContext(this.mapContext(t)),this.requireReady(`ConfigDirector did not become ready after the context changed. Flags resolve against the previous context until the connection succeeds.`)}resolveBooleanEvaluation(e,t){return $(this.client.evaluate(e,t))}resolveStringEvaluation(e,t){return $(this.client.evaluate(e,t))}resolveNumberEvaluation(e,t){return $(this.client.evaluate(e,t))}resolveObjectEvaluation(e,t){return $(this.client.evaluate(e,t))}onClose(){return this.client.dispose(),Promise.resolve()}requireReady(t){if(!this.client.isReady)throw this.awaitingRecovery=!0,this.reportStatusOnceTheSdkRecordedTheOutcome(),new e.ProviderNotReadyError(t)}reportStatusOnceTheSdkRecordedTheOutcome(){setTimeout(()=>{switch(Xe(this.servingCachedValues,this.awaitingRecovery)){case`stale`:this.events.emit(e.ProviderEvents.Stale);return;case`as the SDK recorded it`:return}},0)}mapContext(e){if(!e)return{};let t=(e.targetingKey??e.id)?.toString(),n=e.kind,r=e.name?.toString(),i=e?.traits||{},a=typeof i==`object`&&Object.keys(i).length>0,o=e.anonymous;return{id:t,kind:n,name:r,traits:a?i:void 0,anonymous:typeof o==`boolean`?o:void 0}}};exports.ConfigDirectorInitializationError=r,exports.ConfigDirectorProvider=Ze;
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 v=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var fe=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=v.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};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===v.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=v.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=v.CONNECTING,this._fetch(this.url,{...this.requestOptions,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 ce(`The server response did not have a body`);this._readyState=v.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new de({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 se(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=v.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...this.headers,...e}}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=v.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new ue(`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 le(`${n} must be a function`);return e}};const pe=e=>new fe(e);var me=class{constructor(e){this.options=e,this.eventEmitter=new _,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.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=pe({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 he=(e,t)=>{if(e.trim().length==0)throw new n(`Invalid config key. The key of a value cannot be empty.`);return ge(e,t)},ge=(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 n(`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 n(`Invalid value for '${e}': ${w(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: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,r)=>new n(`Invalid value for '${e}'${t?` at '${t}'`:``}: ${r}. 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=>e===null?`null`:typeof e==`function`?`a function`:typeof e==`object`?`a ${e.constructor?.name??`object`} instance`:typeof e==`symbol`?`a symbol`:String(e),T=(e,t,n,r)=>{let i=he(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 _,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t)}async connect(){let e=O(this.source);return this.emitter.emit(`configSetReceived`,{...E,kind:`full`,configs:e}),this}clear(){this.emitter.clear()}close(){}dispose(){this.clear()}};const O=e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return k(e.values);case`rejected`:throw new r(e.message)}},k=e=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,T(`offline:${e}`,e,t,void 0)]))}catch(e){throw e instanceof n?new r(`The offline values could not be loaded. ${e.message}`):e}},A=(e,t,r)=>{if(t?.mode===`offline`)return{kind:`stay-offline`,source:M(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:j(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}'.`}}},j=(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}`)}},M=e=>e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values},N={variation:void 0,ruleId:void 0,shareId:void 0},P=e=>{let t=e.variation;if(t!=null)return t.name?{id:t.id,name:t.name}:{id:t.id}},F=e=>({variation:P(e),ruleId:e.ruleId??void 0,shareId:e.shareId??void 0}),I=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},L=e=>e===`number`||e===`bigint`,_e=new Set([`boolean`,`integer`,`float`]),ve=(e,t)=>{let n=ye(e,t);return{...n,...n.usedDefault?N:F(e)}},ye=(e,t)=>{let n=e.value,r=I(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return we(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=be(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(L(typeof t)&&e.type===`integer`){let i=xe(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(L(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=Se(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`}},be=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},xe=e=>{let t=R(e);return t==null?void 0:Math.trunc(t)},Se=e=>R(e),R=e=>{if(!e||!Ce(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},Ce=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},we=(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 Te(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`}}},Te=(e,t)=>e===null?!1:z(e)===z(t),z=e=>{if(Array.isArray(e))return`array`;let t=typeof e;return t===`bigint`?`number`:t},B={off:-1,error:0,warn:1,info:2,debug:3},Ee=()=>{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 De=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=Ee()}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){B[this.level]>=B[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},Oe=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const ke=(e,t)=>new De(e??`warn`,t??new Oe),Ae={updateContext:async()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>{},trackedEvent:()=>{},close:async()=>{}},V=(e,t)=>new URL(e,t?.toString()),je=(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.`},Me=()=>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)}),H=e=>{try{return e(globalThis)}catch{return}},Ne=()=>H(e=>e.navigator?.userAgent),Pe=()=>H(e=>e.location?.host),U=()=>{try{return globalThis.localStorage??void 0}catch{return}},W=`configdirector-sdk:instance-id`,G=1e3,Fe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,K=(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},q=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=K(n,2166136261);return K(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},Ie=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===q(n,r)},Le=async(e,t)=>{let n;try{n=await e.getItem(W)}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 Ie(r)?{outcome:`stored`,instanceId:r.id}:(t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`})},Re=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:q(t,r)};try{return await e.setItem(W,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},ze=async(e,t,n,r)=>{let i=await Le(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 Re(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},Be=(e,t=U())=>{let n=Me();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 ${G}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},G)});return Promise.race([ze(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){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 He=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 Ue=class extends Ve{constructor(e){super(),this.options=e,this.eventEmitter=new _,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??60}async connect(e,t){this.endCurrentConnection();let n=this.connectionGeneration,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.endCurrentConnection(),super.close()}endCurrentConnection(){this.connectionGeneration++,this.clearPollingInterval(),this.lastUpdateTimestamp=void 0}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 He(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 We=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,Ge=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!We(t))return!1;return!0},Ke=e=>e==null||typeof e==`string`&&Ge(e),qe=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},Je=(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 Ke(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:Je(qe(t),128)}},Xe=(e,t,n,r)=>{if(e.kind===`stay-offline`)return{kind:`no cache`,reason:`offline mode`};if(t?.enabled===!1)return{kind:`no cache`,reason:`turned off`};if(!n)return{kind:`no cache`,reason:`no SHA-256 available`};let i=n(e.clientSdkKey),a=t?.provider??r?.(i);return a?{kind:`cache`,provider:a,clientSdkKeyDigest:i}:{kind:`no cache`,reason:`no provider available`}},J=(e,t)=>{let n=e?.kind??`user`;return e?.id==null?{contextKind:n,anonymousInstanceId:t}:{contextKind:n,contextId:e.id}},Ze=(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,Qe=(e,t,n)=>n?`live values already arrived`:Ze(e.contextTag,t)?`adopt`:`context mismatch`,$e=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},et=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`),tt=(e,t)=>{if(!t||typeof t!=`object`)return!1;let n=t;return n.formatVersion===2&&n.clientSdkKeyDigest===e&&$e(n.contextTag)&&typeof n.environmentId==`string`&&typeof n.projectId==`string`&&et(n.configs)&&typeof n.receivedAt==`number`},nt=e=>!!e&&typeof e==`object`&&e.formatVersion===1,rt=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{outcome:`unreadable`}}return tt(t,n)?{outcome:`stored`,cachedValues:n}:nt(n)?{outcome:`first format`}:{outcome:`unreadable`}};var it=class{constructor(e,t,n){this.provider=e,this.clientSdkKeyDigest=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=rt(e,await this.clientSdkKeyDigest);switch(t.outcome){case`stored`:return t;case`first format`:return await this.removeEntry(),t;case`unreadable`:return this.warnOnce(`unreadable`,`The values kept on the device could not be read and were removed, starting without them`),await this.removeEntry(),t}}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:2,clientSdkKeyDigest:await this.clientSdkKeyDigest,...e},n=JSON.stringify(t),r=c(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))}},at=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){this.handlersMap=new Map,this.eventEmitter=new _,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.servingCachedValues=!1,this.cachedValuesAdoptionStarted=!1,this.logger=r?.logger??ke(),this.clientSession=Be(this.logger,i?.instanceIdStorage),this.timeout=r?.connection?.timeout??3e3;let a=i?.urlFactory??V;this.connectionPlan=A(t,r?.connection,a),this.cachedValuesStore=this.buildCachedValuesStore(Xe(this.connectionPlan,r?.caching,i?.sha256HexDigest,i?.platformCachingProvider)),this.telemetryClient=this.buildTelemetryClient(e,r),this.transport=i?.transport??this.buildTransport(n,r,a,i),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`,r?.hooks?.clientReady),this.registerHandler(`configEvaluated`,r?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,r?.hooks?.configsUpdated),this.registerHandler(`contextUpdated`,r?.hooks?.contextUpdated),this.registerHandler(`connectionError`,r?.hooks?.connectionError),this.registerHandler(`cachedValuesLoaded`,r?.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 it(e.provider,e.clientSdkKeyDigest,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`first format`:case`unreadable`:case`failed`:return;case`stored`:break}let{instanceId:n}=await this.clientSession,r=J(this.submittedContext,n),i=Qe(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:J(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=je(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 Ae;case`connect`:return e({clientSdkKey:n.clientSdkKey,baseUrl:n.baseUrl,logger:this.logger,metadata:t?.metadata,clientSession:this.clientSession})}}buildTransport(e,t,n,r){let i=this.connectionPlan;switch(i.kind){case`stay-offline`:return new D(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:Ne(),host:Pe()},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 Ue;case`streaming`:return me}}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.evaluationOf(e,t,n.defaultValue).value;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){return this.evaluate(e,t).value}evaluate(e,t){this.validateDefaultValue(t);let n=this.configSet?.configs[e];return this.evaluationOf(e,n,t)}evaluationOf(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`;this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:I(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t});let r={key:e,value:n,isDefaultValue:!0,reason:t,context:this.context};return this.dispatchEvaluationEvent(r),r}let r=ve(t,n),i=this.servedReason(r.reason);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,ruleId:r.ruleId,shareId:r.shareId,variationId:r.variation?.id});let a={key:e,value:r.parsedValue,valueId:r.parsedValueId??void 0,variation:r.variation,isDefaultValue:r.usedDefault,reason:i,context:this.context};return this.dispatchEvaluationEvent(a),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),a}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()}track(e,t){try{let n=this.currentContext;this.telemetryClient.trackedEvent(ie({name:e,context:n,options:t,happenedAt:new Date}),n)}catch(e){this.logger.warn(`[ConfigDirectorClient] A tracked event was not reported because it could not be read: `,e)}}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 Y=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},ot=Math.ceil(128/Math.log2(62)),st=new TextEncoder,ct=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,st.encode(e?.toString()??``));return Y(new Uint8Array(t,0,16),ot)},lt=e=>{let t=U();if(!t)return;let n=e.then(e=>`configdirector-sdk:cached-values:`+e);return{read:async()=>t.getItem(await n),write:async e=>t.setItem(await n,e),remove:async()=>t.removeItem(await n),sizeLimit:()=>262144}},ut=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),dt=()=>{if(!(typeof crypto>`u`||crypto.subtle==null))return async e=>{let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return ut(new Uint8Array(t))}},ft=(e,t,n)=>at.from(({clientSdkKey:e,baseUrl:n,logger:r,metadata:i,clientSession:a})=>new oe({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:i?.appName,appVersion:i?.appVersion},logger:r,baseUrl:n,urlFactory:V,valueIdGenerator:ct,clientSession:a}),e,t,n,{sha256HexDigest:dt(),platformCachingProvider:lt}),X=(t,n,r)=>({value:t,reason:e.StandardResolutionReasons.ERROR,errorCode:n,errorMessage:r}),Z=t=>X(t.value,e.ErrorCode.TYPE_MISMATCH,`The value of '${t.key}' cannot be read as the requested type (${t.reason}).`),Q=e=>e.variation?.name??e.valueId,pt={"found-match":t=>({value:t.value,variant:Q(t),reason:e.StandardResolutionReasons.TARGETING_MATCH}),"rollout-skipped-no-identifier":t=>({value:t.value,variant:Q(t),reason:e.StandardResolutionReasons.DEFAULT}),cached:t=>({value:t.value,variant:Q(t),reason:e.StandardResolutionReasons.CACHED}),"value-missing":t=>({value:t.value,reason:e.StandardResolutionReasons.DEFAULT}),"config-state-missing":t=>X(t.value,e.ErrorCode.FLAG_NOT_FOUND,`No config with the key '${t.key}' was found.`),"client-not-ready":t=>X(t.value,e.ErrorCode.PROVIDER_NOT_READY,`ConfigDirector has not delivered config state yet.`),"type-mismatch":Z,"invalid-number":Z,"invalid-json":Z,"invalid-boolean":Z},$=e=>pt[e.reason](e),mt={sdkName:`js-openfeature-web-provider`,sdkVersion:`1.11.0`},ht=(e,t)=>e&&t?`stale`:`as the SDK recorded it`;var gt=class{constructor(t,n){this.awaitingRecovery=!1,this.servingCachedValues=!1,this.metadata={name:`ConfigDirectorProvider`},this.runsOn=`client`,this.events=new e.OpenFeatureEventEmitter,this.client=ft(t,mt,n),this.client.on(`clientReady`,()=>{this.servingCachedValues=!1,this.awaitingRecovery&&(this.awaitingRecovery=!1,this.events.emit(e.ProviderEvents.Ready))}),this.client.on(`cachedValuesLoaded`,()=>{this.servingCachedValues=!0,this.reportStatusOnceTheSdkRecordedTheOutcome()}),this.client.on(`configsUpdated`,({keys:t,removedKeys:n})=>{this.events.emit(e.ProviderEvents.ConfigurationChanged,{flagsChanged:[...t,...n]})})}async initialize(e){this.awaitingRecovery=!1,await this.client.initialize(this.mapContext(e)),this.requireReady(`ConfigDirector did not become ready during initialization. Flags resolve to their default values until the connection succeeds.`)}async onContextChange(e,t){this.awaitingRecovery=!1,await this.client.updateContext(this.mapContext(t)),this.requireReady(`ConfigDirector did not become ready after the context changed. Flags resolve against the previous context until the connection succeeds.`)}resolveBooleanEvaluation(e,t){return $(this.client.evaluate(e,t))}resolveStringEvaluation(e,t){return $(this.client.evaluate(e,t))}resolveNumberEvaluation(e,t){return $(this.client.evaluate(e,t))}resolveObjectEvaluation(e,t){return $(this.client.evaluate(e,t))}track(e,t,n){let{value:r,...i}=n??{},a=Object.keys(i).length>0;this.client.track(e,{value:r,details:a?i:void 0})}onClose(){return this.client.dispose(),Promise.resolve()}requireReady(t){if(!this.client.isReady)throw this.awaitingRecovery=!0,this.reportStatusOnceTheSdkRecordedTheOutcome(),new e.ProviderNotReadyError(t)}reportStatusOnceTheSdkRecordedTheOutcome(){setTimeout(()=>{switch(ht(this.servingCachedValues,this.awaitingRecovery)){case`stale`:this.events.emit(e.ProviderEvents.Stale);return;case`as the SDK recorded it`:return}},0)}mapContext(e){if(!e)return{};let t=(e.targetingKey??e.id)?.toString(),n=e.kind,r=e.name?.toString(),i=e?.traits||{},a=typeof i==`object`&&Object.keys(i).length>0,o=e.anonymous;return{id:t,kind:n,name:r,traits:a?i:void 0,anonymous:typeof o==`boolean`?o:void 0}}};exports.ConfigDirectorInitializationError=r,exports.ConfigDirectorProvider=gt;
@@ -27,24 +27,63 @@ interface ConfigDirectorLogMessageDecorator {
27
27
  }
28
28
  /**
29
29
  * Why an evaluation returned the value it did. `found-match` returns a value from ConfigDirector,
30
- * and `cached` a value kept on the device while a client SDK waits for live values. `value-missing`
30
+ * and `cached` a value kept on the device while a client SDK waits for live values.
31
+ * `rollout-skipped-no-identifier` returns the default targeting rule value: a server SDK skipped a
32
+ * percentage rollout because the context has no `id` to place it in a share. `value-missing`
31
33
  * returns the in-code default value because the config has no value. Every other reason returns the
32
34
  * in-code default value because of an error: the config does not exist (`config-state-missing`), no
33
35
  * values have arrived yet (`client-not-ready`), or the value cannot be read as the type of the in-code
34
36
  * default value.
35
37
  */
36
- type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
38
+ type EvaluationReason = "found-match" | "rollout-skipped-no-identifier" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
39
+ /**
40
+ * One of the values a config can serve, such as the control or a treatment of an experiment.
41
+ */
42
+ type Variation = {
43
+ /** The ID ConfigDirector assigned to the variation, which stays the same when it is renamed. */id: string; /** The variation's name, when it has one. */
44
+ name?: string;
45
+ };
37
46
  /**
38
47
  * One evaluation of a config: the value it returned, why, and the context it was evaluated for.
39
48
  */
40
49
  type ConfigEvaluation<T extends ConfigValueType = ConfigValueType> = {
41
50
  /** The config key that was evaluated. */key: string; /** The value returned, which is the in-code default value when {@link isDefaultValue} is `true`. */
42
51
  value: T; /** The ID ConfigDirector assigned to the value returned, when ConfigDirector sent one with it. */
43
- valueId?: string; /** Whether the evaluation returned the in-code default value. */
52
+ valueId?: string;
53
+ /**
54
+ * The variation that was served. It is `undefined` when the config has no variations or the
55
+ * in-code default value is returned.
56
+ */
57
+ variation?: Variation; /** Whether the evaluation returned the in-code default value. */
44
58
  isDefaultValue: boolean; /** Why the evaluation returned this value. */
45
59
  reason: EvaluationReason; /** The context the config was evaluated for, if any. */
46
60
  context?: ConfigDirectorContext;
47
61
  };
62
+ /**
63
+ * A value in the details of a tracked event: a string, a number, a boolean, or an array or object
64
+ * of such values.
65
+ */
66
+ type TrackedEventDetailValue = string | number | boolean | TrackedEventDetailValue[] | {
67
+ [key: string]: TrackedEventDetailValue;
68
+ };
69
+ /**
70
+ * Details of a tracked event, such as the plan a customer chose. Details with more than 20
71
+ * top-level keys, or larger than 1 KB as JSON, are left out and the event is still reported.
72
+ */
73
+ type TrackedEventDetails = {
74
+ [key: string]: TrackedEventDetailValue;
75
+ };
76
+ /**
77
+ * What a tracked event carries besides its name.
78
+ */
79
+ type TrackOptions = {
80
+ /**
81
+ * A number the event measures, such as an amount of money, a count or a duration. A value that
82
+ * is not a finite number is left out and the event is still reported.
83
+ */
84
+ value?: number; /** Details of the event. */
85
+ details?: TrackedEventDetails;
86
+ };
48
87
  /**
49
88
  * The context to be sent to ConfigDirector: the user or other entity, such as a device or an
50
89
  * organization, that configs are evaluated for. This context will be used for targeting rules
@@ -373,8 +412,8 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
373
412
  getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
374
413
  /**
375
414
  * Evaluates a config as {@link getValue} does and returns the evaluation: the value, the reason it
376
- * was served and its value ID. Like every read, it fires `configEvaluated` and is counted in
377
- * telemetry.
415
+ * was served, its value ID and its variation. Like every read, it fires `configEvaluated` and is
416
+ * counted in telemetry.
378
417
  *
379
418
  * @returns The evaluation, whose `value` is what {@link getValue} returns
380
419
  * @param configKey The config key to evaluate
@@ -406,6 +445,20 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
406
445
  * Removes all subscribers from all config keys
407
446
  */
408
447
  unwatchAll(): void;
448
+ /**
449
+ * Reports to ConfigDirector that something happened for the current context, such as a completed
450
+ * checkout, so it can be counted. The event is sent with the next telemetry batch. `track` never
451
+ * throws, and does nothing in `offline` mode.
452
+ *
453
+ * An event counts for an experiment only when the current context has an `id`, the one the
454
+ * experiment's config was evaluated for. Before the client has a context, or for a context
455
+ * without an `id`, the event is still reported.
456
+ *
457
+ * @param eventName The name of the event, 1 to 150 characters. An event with any other name is
458
+ * not reported and a warning is logged.
459
+ * @param options The event's {@link TrackOptions.value} and {@link TrackOptions.details} (optional)
460
+ */
461
+ track(eventName: string, options?: TrackOptions): void;
409
462
  /**
410
463
  * Pauses the network connection without clearing event handlers, watch handlers, or config
411
464
  * state. Intended for mobile environments where the OS may kill background connections (e.g.
@@ -435,6 +488,9 @@ declare class ConfigDirectorInitializationError extends Error {
435
488
  }
436
489
  //#endregion
437
490
  //#region src/ConfigDirectorProvider.d.ts
491
+ type TrackingEventDetails = {
492
+ value?: number;
493
+ } & Record<string, unknown>;
438
494
  declare class ConfigDirectorProvider implements Provider {
439
495
  private readonly client;
440
496
  private awaitingRecovery;
@@ -457,6 +513,7 @@ declare class ConfigDirectorProvider implements Provider {
457
513
  resolveStringEvaluation(flagKey: string, defaultValue: string): ResolutionDetails<string>;
458
514
  resolveNumberEvaluation(flagKey: string, defaultValue: number): ResolutionDetails<number>;
459
515
  resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T): ResolutionDetails<T>;
516
+ track(trackingEventName: string, _context: EvaluationContext, trackingEventDetails: TrackingEventDetails): void;
460
517
  onClose?(): Promise<void>;
461
518
  private requireReady;
462
519
  private reportStatusOnceTheSdkRecordedTheOutcome;
@@ -1 +1 @@
1
- {"version":3,"file":"configdirector-openfeature-web-provider.d.cts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts","../../shared/src/errors.ts","../src/ConfigDirectorProvider.ts"],"mappings":";;;KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAevD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;;;;;ADnClB;;;;KC8CY,gBAAA;;;;KAcA,gBAAA,WAA2B,eAAA,GAAkB,eAAA;ED1D/B,yCC4DxB,GAAA,UD5DsE;EC8DtE,KAAA,EAAO,CAAA,ED9DuD;ECgE9D,OAAA,WDhEqE;ECkErE,cAAA,WDpEmD;ECsEnD,MAAA,EAAQ,gBAAA,EDrEL;ECuEH,OAAA,GAAU,qBAAA;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;EAMlG,OAAA,CAAA,CAAA,GAAY,OAAA;EAAA,QAKJ,YAAA;EAAA,QASA,wCAAA;EAAA,QAYA,UAAA;AAAA"}
1
+ {"version":3,"file":"configdirector-openfeature-web-provider.d.cts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts","../../shared/src/errors.ts","../src/ConfigDirectorProvider.ts"],"mappings":";;;KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAkBvD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;;;;;;;;;;;KAaN,gBAAA;;;;KAeA,SAAA;EDlEyC,gGCoEnD,EAAA,UDnEG;ECqEH,IAAA;AAAA;;;;KAMU,gBAAA,WAA2B,eAAA,GAAkB,eAAA;ED3EJ,yCC6EnD,GAAA,UD5EI;EC8EJ,KAAA,EAAO,CAAA,ED9EsC;ECgF7C,OAAA;EDhF8D;;;;ECqF9D,SAAA,GAAY,S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K6C/C,aAAA,EAAe,oBAAA;EAoB5B,UAAA,CAAW,OAAA,EAAS,iBAAA,GAAiB,OAAA;EASrC,eAAA,CAAA,CAAiB,WAAA,EAAa,iBAAA,EAAmB,UAAA,EAAY,iBAAA,GAAoB,OAAA;EASvF,wBAAA,CAAyB,OAAA,UAAiB,YAAA,YAAwB,iBAAA;EAIlE,uBAAA,CAAwB,OAAA,UAAiB,YAAA,WAAuB,iBAAA;EAIhE,uBAAA,CAAwB,OAAA,UAAiB,YAAA,WAAuB,iBAAA;EAIhE,uBAAA,WAAkC,SAAA,CAAA,CAAW,OAAA,UAAiB,YAAA,EAAc,CAAA,GAAI,iBAAA,CAAkB,CAAA;EAMlG,KAAA,CAAM,iBAAA,UAA2B,QAAA,EAAU,iBAAA,EAAmB,oBAAA,EAAsB,oBAAA;EASpF,OAAA,CAAA,CAAA,GAAY,OAAA;EAAA,QAKJ,YAAA;EAAA,QASA,wCAAA;EAAA,QAYA,UAAA;AAAA"}
@@ -27,24 +27,63 @@ interface ConfigDirectorLogMessageDecorator {
27
27
  }
28
28
  /**
29
29
  * Why an evaluation returned the value it did. `found-match` returns a value from ConfigDirector,
30
- * and `cached` a value kept on the device while a client SDK waits for live values. `value-missing`
30
+ * and `cached` a value kept on the device while a client SDK waits for live values.
31
+ * `rollout-skipped-no-identifier` returns the default targeting rule value: a server SDK skipped a
32
+ * percentage rollout because the context has no `id` to place it in a share. `value-missing`
31
33
  * returns the in-code default value because the config has no value. Every other reason returns the
32
34
  * in-code default value because of an error: the config does not exist (`config-state-missing`), no
33
35
  * values have arrived yet (`client-not-ready`), or the value cannot be read as the type of the in-code
34
36
  * default value.
35
37
  */
36
- type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
38
+ type EvaluationReason = "found-match" | "rollout-skipped-no-identifier" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
39
+ /**
40
+ * One of the values a config can serve, such as the control or a treatment of an experiment.
41
+ */
42
+ type Variation = {
43
+ /** The ID ConfigDirector assigned to the variation, which stays the same when it is renamed. */id: string; /** The variation's name, when it has one. */
44
+ name?: string;
45
+ };
37
46
  /**
38
47
  * One evaluation of a config: the value it returned, why, and the context it was evaluated for.
39
48
  */
40
49
  type ConfigEvaluation<T extends ConfigValueType = ConfigValueType> = {
41
50
  /** The config key that was evaluated. */key: string; /** The value returned, which is the in-code default value when {@link isDefaultValue} is `true`. */
42
51
  value: T; /** The ID ConfigDirector assigned to the value returned, when ConfigDirector sent one with it. */
43
- valueId?: string; /** Whether the evaluation returned the in-code default value. */
52
+ valueId?: string;
53
+ /**
54
+ * The variation that was served. It is `undefined` when the config has no variations or the
55
+ * in-code default value is returned.
56
+ */
57
+ variation?: Variation; /** Whether the evaluation returned the in-code default value. */
44
58
  isDefaultValue: boolean; /** Why the evaluation returned this value. */
45
59
  reason: EvaluationReason; /** The context the config was evaluated for, if any. */
46
60
  context?: ConfigDirectorContext;
47
61
  };
62
+ /**
63
+ * A value in the details of a tracked event: a string, a number, a boolean, or an array or object
64
+ * of such values.
65
+ */
66
+ type TrackedEventDetailValue = string | number | boolean | TrackedEventDetailValue[] | {
67
+ [key: string]: TrackedEventDetailValue;
68
+ };
69
+ /**
70
+ * Details of a tracked event, such as the plan a customer chose. Details with more than 20
71
+ * top-level keys, or larger than 1 KB as JSON, are left out and the event is still reported.
72
+ */
73
+ type TrackedEventDetails = {
74
+ [key: string]: TrackedEventDetailValue;
75
+ };
76
+ /**
77
+ * What a tracked event carries besides its name.
78
+ */
79
+ type TrackOptions = {
80
+ /**
81
+ * A number the event measures, such as an amount of money, a count or a duration. A value that
82
+ * is not a finite number is left out and the event is still reported.
83
+ */
84
+ value?: number; /** Details of the event. */
85
+ details?: TrackedEventDetails;
86
+ };
48
87
  /**
49
88
  * The context to be sent to ConfigDirector: the user or other entity, such as a device or an
50
89
  * organization, that configs are evaluated for. This context will be used for targeting rules
@@ -373,8 +412,8 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
373
412
  getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
374
413
  /**
375
414
  * Evaluates a config as {@link getValue} does and returns the evaluation: the value, the reason it
376
- * was served and its value ID. Like every read, it fires `configEvaluated` and is counted in
377
- * telemetry.
415
+ * was served, its value ID and its variation. Like every read, it fires `configEvaluated` and is
416
+ * counted in telemetry.
378
417
  *
379
418
  * @returns The evaluation, whose `value` is what {@link getValue} returns
380
419
  * @param configKey The config key to evaluate
@@ -406,6 +445,20 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
406
445
  * Removes all subscribers from all config keys
407
446
  */
408
447
  unwatchAll(): void;
448
+ /**
449
+ * Reports to ConfigDirector that something happened for the current context, such as a completed
450
+ * checkout, so it can be counted. The event is sent with the next telemetry batch. `track` never
451
+ * throws, and does nothing in `offline` mode.
452
+ *
453
+ * An event counts for an experiment only when the current context has an `id`, the one the
454
+ * experiment's config was evaluated for. Before the client has a context, or for a context
455
+ * without an `id`, the event is still reported.
456
+ *
457
+ * @param eventName The name of the event, 1 to 150 characters. An event with any other name is
458
+ * not reported and a warning is logged.
459
+ * @param options The event's {@link TrackOptions.value} and {@link TrackOptions.details} (optional)
460
+ */
461
+ track(eventName: string, options?: TrackOptions): void;
409
462
  /**
410
463
  * Pauses the network connection without clearing event handlers, watch handlers, or config
411
464
  * state. Intended for mobile environments where the OS may kill background connections (e.g.
@@ -435,6 +488,9 @@ declare class ConfigDirectorInitializationError extends Error {
435
488
  }
436
489
  //#endregion
437
490
  //#region src/ConfigDirectorProvider.d.ts
491
+ type TrackingEventDetails = {
492
+ value?: number;
493
+ } & Record<string, unknown>;
438
494
  declare class ConfigDirectorProvider implements Provider {
439
495
  private readonly client;
440
496
  private awaitingRecovery;
@@ -457,6 +513,7 @@ declare class ConfigDirectorProvider implements Provider {
457
513
  resolveStringEvaluation(flagKey: string, defaultValue: string): ResolutionDetails<string>;
458
514
  resolveNumberEvaluation(flagKey: string, defaultValue: number): ResolutionDetails<number>;
459
515
  resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T): ResolutionDetails<T>;
516
+ track(trackingEventName: string, _context: EvaluationContext, trackingEventDetails: TrackingEventDetails): void;
460
517
  onClose?(): Promise<void>;
461
518
  private requireReady;
462
519
  private reportStatusOnceTheSdkRecordedTheOutcome;
@@ -1 +1 @@
1
- {"version":3,"file":"configdirector-openfeature-web-provider.d.mts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts","../../shared/src/errors.ts","../src/ConfigDirectorProvider.ts"],"mappings":";;;KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAevD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;;;;;ADnClB;;;;KC8CY,gBAAA;;;;KAcA,gBAAA,WAA2B,eAAA,GAAkB,eAAA;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B,YAAA,WAAuB,iBAAA;EAIhE,uBAAA,CAAwB,OAAA,UAAiB,YAAA,WAAuB,iBAAA;EAIhE,uBAAA,WAAkC,SAAA,CAAA,CAAW,OAAA,UAAiB,YAAA,EAAc,CAAA,GAAI,iBAAA,CAAkB,CAAA;EAMlG,OAAA,CAAA,CAAA,GAAY,OAAA;EAAA,QAKJ,YAAA;EAAA,QASA,wCAAA;EAAA,QAYA,UAAA;AAAA"}
1
+ {"version":3,"file":"configdirector-openfeature-web-provider.d.mts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts","../../shared/src/errors.ts","../src/ConfigDirectorProvider.ts"],"mappings":";;;KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAkBvD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;;;;;;;;;;;KAaN,gBAAA;;;;KAeA,SAAA;EDlEyC,gGCoEnD,EAAA,UDnEG;EC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