@configdirector/vue-sdk 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-D7S6zs2D.cjs`);let t=require(`vue`);const n=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 r=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}},i=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new r,this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}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)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class{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=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),y=e=>{try{self.postMessage(e)}catch{self.postMessage(v(e.payload.level,e.payload.message))}},b={debug:function(e,...t){y(v(`debug`,e,t))},info:function(e,...t){y(v(`info`,e,t))},warn:function(e,...t){y(v(`warn`,e,t))},error:function(e,...t){y(v(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){b.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(b.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){b.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:b}),_.start();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.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}}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:n({value:e.defaultValue,type:e.type}),evaluatedValue:n({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}};const a=(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`)},o=Math.ceil(128/Math.log2(62)),s=new TextEncoder,c=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,s.encode(e?.toString()??``));return a(new Uint8Array(t,0,16),o)},l=(t,n,r)=>e.t.from(({clientSdkKey:t,baseUrl:r,logger:a,metadata:o})=>new i({sdkKey:t,sdkIdentity:{sdkName:n.sdkName,sdkVersion:n.sdkVersion},metaContext:{appName:o?.appName,appVersion:o?.appVersion},logger:a,baseUrl:r,urlFactory:e.n,valueIdGenerator:c}),t,n,r);var u=class{decorateMessage(e){return`[ConfigDirector:vue-sdk] ${e}`}};const d=t=>e.i(t,new u),f=(e,t)=>l(e,{sdkName:`vue-sdk`,sdkVersion:`1.8.0`},t),p=e=>f(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:e.logger??d(`warn`),hooks:e.hooks}),m=async e=>{let t=p(e);return await t.initialize(e.context),t},h=Symbol(`ConfigDirector.Client`),g=Symbol(`ConfigDirector.ClientStatus`),_=Symbol(`ConfigDirector.Context`),v={install:(e,n)=>{let r=y(n)?n:p(n),i=(0,t.ref)(r.isReady?`ready`:`loading`),a=(0,t.readonly)(i);r.on(`clientReady`,()=>i.value=`ready`);let o=(0,t.ref)(n.context),s=(0,t.readonly)(o);r.on(`contextUpdated`,({context:e})=>o.value=e),!r.isReady&&!r.isInitializing&&r.initialize(n.context).then(()=>{r.isReady||(i.value=`default`)}),e.provide(h,r),e.provide(g,a),e.provide(_,s)}},y=e=>{let t=e;return typeof t.initialize==`function`&&typeof t.getValue==`function`&&typeof t.watch==`function`&&typeof t.on==`function`},b=n=>{let r=(0,t.inject)(n);if(r===void 0)throw new e.s(`Could not inject ${n.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`);return r},x=()=>({client:b(h)}),S=()=>{let e=b(g);return{readyStatus:e,loading:(0,t.computed)(()=>e.value===`loading`)}},C=(e,n)=>{let{client:r}=x(),{readyStatus:i,loading:a}=S(),o=(0,t.shallowRef)(r.getValue(e,n)),s=e=>o.value=e;return r.watch(e,n,s),(0,t.onBeforeUnmount)(()=>r.unwatch(e,s)),{value:o,readyStatus:i,loading:a}},w=()=>{let{client:e}=x();return{context:b(_),updateContext:async n=>{let r=(0,t.toRaw)(n);JSON.stringify(e.context)!=JSON.stringify(r)&&await e.updateContext(r)}}};exports.ConfigDirectorPlugin=v,exports.createConsoleLogger=d,exports.initializeClient=m,exports.useClient=x,exports.useClientStatus=S,exports.useConfigValue=C,exports.useContext=w;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-BSBC3rBa.cjs`);let t=require(`vue`);const n=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 r=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}},i=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new r,this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}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)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class{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=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),y=e=>{try{self.postMessage(e)}catch{self.postMessage(v(e.payload.level,e.payload.message))}},b={debug:function(e,...t){y(v(`debug`,e,t))},info:function(e,...t){y(v(`info`,e,t))},warn:function(e,...t){y(v(`warn`,e,t))},error:function(e,...t){y(v(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){b.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(b.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){b.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:b}),_.start();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.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}}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:n({value:e.defaultValue,type:e.type}),evaluatedValue:n({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}};const a=(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`)},o=Math.ceil(128/Math.log2(62)),s=new TextEncoder,c=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,s.encode(e?.toString()??``));return a(new Uint8Array(t,0,16),o)},l=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),u=async t=>{let n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return e.n+l(new Uint8Array(n))},d=()=>typeof crypto<`u`&&crypto.subtle!=null,f=t=>{let n=e.i();if(!n||!d())return;let r=u(t);return{read:async()=>n.getItem(await r),write:async e=>n.setItem(await r,e),remove:async()=>n.removeItem(await r),sizeLimit:()=>e.r}},p=(t,n,r)=>e.t.from(({clientSdkKey:t,baseUrl:r,logger:a,metadata:o})=>new i({sdkKey:t,sdkIdentity:{sdkName:n.sdkName,sdkVersion:n.sdkVersion},metaContext:{appName:o?.appName,appVersion:o?.appVersion},logger:a,baseUrl:r,urlFactory:e.a,valueIdGenerator:c}),t,n,r,{platformCachingProvider:f});var m=class{decorateMessage(e){return`[ConfigDirector:vue-sdk] ${e}`}};const h=t=>e.s(t,new m),g=(e,t)=>p(e,{sdkName:`vue-sdk`,sdkVersion:`1.9.0`},t),_=e=>g(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:e.logger??h(`warn`),hooks:e.hooks,caching:e.caching}),v=async e=>{let t=_(e);return await t.initialize(e.context),t},y=Symbol(`ConfigDirector.Client`),b=Symbol(`ConfigDirector.ClientStatus`),x=Symbol(`ConfigDirector.Context`),S={install:(e,n)=>{let r=C(n)?n:_(n),i=(0,t.ref)(r.isReady?`ready`:`loading`),a=(0,t.readonly)(i);r.on(`clientReady`,()=>i.value=`ready`);let o=(0,t.ref)(n.context),s=(0,t.readonly)(o);r.on(`contextUpdated`,({context:e})=>o.value=e),!r.isReady&&!r.isInitializing&&r.initialize(n.context).then(()=>{r.isReady||(i.value=`default`)}),e.provide(y,r),e.provide(b,a),e.provide(x,s)}},C=e=>{let t=e;return typeof t.initialize==`function`&&typeof t.getValue==`function`&&typeof t.watch==`function`&&typeof t.on==`function`},w=n=>{let r=(0,t.inject)(n);if(r===void 0)throw new e.u(`Could not inject ${n.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`);return r},T=()=>({client:w(y)}),E=()=>{let e=w(b);return{readyStatus:e,loading:(0,t.computed)(()=>e.value===`loading`)}},D=(e,n)=>{let{client:r}=T(),{readyStatus:i,loading:a}=E(),o=(0,t.shallowRef)(r.getValue(e,n)),s=e=>o.value=e;return r.watch(e,n,s),(0,t.onBeforeUnmount)(()=>r.unwatch(e,s)),{value:o,readyStatus:i,loading:a}},O=()=>{let{client:e}=T();return{context:w(x),updateContext:async n=>{let r=(0,t.toRaw)(n);JSON.stringify(e.context)!=JSON.stringify(r)&&await e.updateContext(r)}}};exports.ConfigDirectorPlugin=S,exports.createConsoleLogger=h,exports.initializeClient=v,exports.useClient=T,exports.useClientStatus=E,exports.useConfigValue=D,exports.useContext=O;
@@ -1,4 +1,4 @@
1
- import { c as ConfigDirectorContext, d as ConfigValueType, f as ConnectionMode, i as OfflineValues, l as ConfigDirectorLogger, n as ConfigDirectorClient, r as OfflineValue, t as ClientHooks, u as ConfigDirectorLoggingLevel } from "./types-DJSy0ELn.cjs";
1
+ import { a as OfflineValue, d as ConfigDirectorLogger, f as ConfigDirectorLoggingLevel, i as ConfigDirectorClient, m as ConnectionMode, n as CachingProvider, o as OfflineValues, p as ConfigValueType, r as ClientHooks, t as CachingOptions, u as ConfigDirectorContext } from "./types-CFBLmqUM.cjs";
2
2
  import * as _$vue from "vue";
3
3
  import { App, Ref, ShallowRef } from "vue";
4
4
 
@@ -43,6 +43,12 @@ type ConfigDirectorPluginOptions = {
43
43
  context?: ConfigDirectorContext;
44
44
  logger?: ConfigDirectorLogger;
45
45
  hooks?: ClientHooks;
46
+ /**
47
+ * Options for the values the client keeps on the device between launches. The last values received
48
+ * are kept by default and served, with the evaluation reason `cached`, on the next launch of the same
49
+ * context until live values arrive.
50
+ */
51
+ caching?: CachingOptions;
46
52
  };
47
53
  //#endregion
48
54
  //#region src/plugin.d.ts
@@ -77,5 +83,5 @@ declare const useContext: () => {
77
83
  //#region src/client.d.ts
78
84
  declare const initializeClient: (options: ConfigDirectorPluginOptions) => Promise<ConfigDirectorClient>;
79
85
  //#endregion
80
- export { type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorPlugin, type ConfigDirectorPluginOptions, type ConnectionMode, type OfflineValue, type OfflineValues, createConsoleLogger, initializeClient, useClient, useClientStatus, useConfigValue, useContext };
86
+ export { type CachingOptions, type CachingProvider, type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorPlugin, type ConfigDirectorPluginOptions, type ConnectionMode, type OfflineValue, type OfflineValues, createConsoleLogger, initializeClient, useClient, useClientStatus, useConfigValue, useContext };
81
87
  //# sourceMappingURL=configdirector-vue-client.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"configdirector-vue-client.d.cts","names":[],"sources":["../src/logger.ts","../src/types.ts","../src/plugin.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts","../src/client.ts"],"mappings":";;;;;cAca,mBAAA,GAAuB,KAAA,EAAO,0BAAA,KAA6B,oBAAA;;;KCH5D,YAAA;AAAA,KAEA,2BAAA;;ADCZ;;ECGE,MAAA;EACA,OAAA;EACA,UAAA;EACA,GAAA;EACA,OAAA;EDLD;;;;;ACLD;;;;EAoBE,IAAA,GAAO,cAAA;EAlBG;;;;;;EAyBV,MAAA,GAAS,aAAA;EAUD;;;;;;EAHR,eAAA;EACA,OAAA,GAAU,qBAAA;EACV,MAAA,GAAS,oBAAA;EACT,KAAA,GAAQ,WAAA;AAAA;;;cCpCG,oBAAA;iBACI,GAAA,EAAG,eAAA,EAAmB,2BAAA,GAA8B,oBAAA;AAAA;;;cCTxD,SAAA;EAAkB,MAAA,EAAQ,oBAAA;AAAA;;;cCE1B,eAAA;EACX,WAAA,EAAa,QAAA,CAAS,GAAA,CAAI,YAAA;EAC1B,OAAA,EAAS,QAAA,CAAS,GAAA;AAAA;;;cCDP,cAAA,aAA4B,eAAA,EACvC,SAAA,UACA,YAAA,EAAc,CAAA;EACX,KAAA,EAAO,UAAA,CAAW,CAAA;EAAI,WAAA,EAAa,QAAA,CAAS,GAAA,CAAI,YAAA;EAAgB,OAAA,EAAS,QAAA,CAAS,GAAA;AAAA;;;cCJ1E,UAAA;;2BAI2B,qBAAA,KAAqB,OAAA;AAAA;;;cCiBhD,gBAAA,GACX,OAAA,EAAS,2BAAA,KACR,OAAA,CAAQ,oBAAA"}
1
+ {"version":3,"file":"configdirector-vue-client.d.cts","names":[],"sources":["../src/logger.ts","../src/types.ts","../src/plugin.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts","../src/client.ts"],"mappings":";;;;;cAca,mBAAA,GAAuB,KAAA,EAAO,0BAAA,KAA6B,oBAAA;;;KCF5D,YAAA;AAAA,KAEA,2BAAA;;ADAZ;;ECIE,MAAA;EACA,OAAA;EACA,UAAA;EACA,GAAA;EACA,OAAA;EDND;;;;;ACJD;;;;EAoBE,IAAA,GAAO,cAAA;EAlBG;;;;;;EAyBV,MAAA,GAAS,aAAA;EAUD;;;;;;EAHR,eAAA;EACA,OAAA,GAAU,qBAAA;EACV,MAAA,GAAS,oBAAA;EACT,KAAA,GAAQ,WAAA;EAjBD;;;;;EAuBP,OAAA,GAAU,cAAA;AAAA;;;cC3CC,oBAAA;iBACI,GAAA,EAAG,eAAA,EAAmB,2BAAA,GAA8B,oBAAA;AAAA;;;cCTxD,SAAA;EAAkB,MAAA,EAAQ,oBAAA;AAAA;;;cCE1B,eAAA;EACX,WAAA,EAAa,QAAA,CAAS,GAAA,CAAI,YAAA;EAC1B,OAAA,EAAS,QAAA,CAAS,GAAA;AAAA;;;cCDP,cAAA,aAA4B,eAAA,EACvC,SAAA,UACA,YAAA,EAAc,CAAA;EACX,KAAA,EAAO,UAAA,CAAW,CAAA;EAAI,WAAA,EAAa,QAAA,CAAS,GAAA,CAAI,YAAA;EAAgB,OAAA,EAAS,QAAA,CAAS,GAAA;AAAA;;;cCJ1E,UAAA;;2BAI2B,qBAAA,KAAqB,OAAA;AAAA;;;cCkBhD,gBAAA,GACX,OAAA,EAAS,2BAAA,KACR,OAAA,CAAQ,oBAAA"}
@@ -1,4 +1,4 @@
1
- import { c as ConfigDirectorContext, d as ConfigValueType, f as ConnectionMode, i as OfflineValues, l as ConfigDirectorLogger, n as ConfigDirectorClient, r as OfflineValue, t as ClientHooks, u as ConfigDirectorLoggingLevel } from "./types-BfakBTXM.mjs";
1
+ import { a as OfflineValue, d as ConfigDirectorLogger, f as ConfigDirectorLoggingLevel, i as ConfigDirectorClient, m as ConnectionMode, n as CachingProvider, o as OfflineValues, p as ConfigValueType, r as ClientHooks, t as CachingOptions, u as ConfigDirectorContext } from "./types-CrgXfAWw.mjs";
2
2
  import * as _$vue from "vue";
3
3
  import { App, Ref, ShallowRef } from "vue";
4
4
 
@@ -43,6 +43,12 @@ type ConfigDirectorPluginOptions = {
43
43
  context?: ConfigDirectorContext;
44
44
  logger?: ConfigDirectorLogger;
45
45
  hooks?: ClientHooks;
46
+ /**
47
+ * Options for the values the client keeps on the device between launches. The last values received
48
+ * are kept by default and served, with the evaluation reason `cached`, on the next launch of the same
49
+ * context until live values arrive.
50
+ */
51
+ caching?: CachingOptions;
46
52
  };
47
53
  //#endregion
48
54
  //#region src/plugin.d.ts
@@ -77,5 +83,5 @@ declare const useContext: () => {
77
83
  //#region src/client.d.ts
78
84
  declare const initializeClient: (options: ConfigDirectorPluginOptions) => Promise<ConfigDirectorClient>;
79
85
  //#endregion
80
- export { type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorPlugin, type ConfigDirectorPluginOptions, type ConnectionMode, type OfflineValue, type OfflineValues, createConsoleLogger, initializeClient, useClient, useClientStatus, useConfigValue, useContext };
86
+ export { type CachingOptions, type CachingProvider, type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorPlugin, type ConfigDirectorPluginOptions, type ConnectionMode, type OfflineValue, type OfflineValues, createConsoleLogger, initializeClient, useClient, useClientStatus, useConfigValue, useContext };
81
87
  //# sourceMappingURL=configdirector-vue-client.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"configdirector-vue-client.d.mts","names":[],"sources":["../src/logger.ts","../src/types.ts","../src/plugin.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts","../src/client.ts"],"mappings":";;;;;cAca,mBAAA,GAAuB,KAAA,EAAO,0BAAA,KAA6B,oBAAA;;;KCH5D,YAAA;AAAA,KAEA,2BAAA;;ADCZ;;ECGE,MAAA;EACA,OAAA;EACA,UAAA;EACA,GAAA;EACA,OAAA;EDLD;;;;;ACLD;;;;EAoBE,IAAA,GAAO,cAAA;EAlBG;;;;;;EAyBV,MAAA,GAAS,aAAA;EAUD;;;;;;EAHR,eAAA;EACA,OAAA,GAAU,qBAAA;EACV,MAAA,GAAS,oBAAA;EACT,KAAA,GAAQ,WAAA;AAAA;;;cCpCG,oBAAA;iBACI,GAAA,EAAG,eAAA,EAAmB,2BAAA,GAA8B,oBAAA;AAAA;;;cCTxD,SAAA;EAAkB,MAAA,EAAQ,oBAAA;AAAA;;;cCE1B,eAAA;EACX,WAAA,EAAa,QAAA,CAAS,GAAA,CAAI,YAAA;EAC1B,OAAA,EAAS,QAAA,CAAS,GAAA;AAAA;;;cCDP,cAAA,aAA4B,eAAA,EACvC,SAAA,UACA,YAAA,EAAc,CAAA;EACX,KAAA,EAAO,UAAA,CAAW,CAAA;EAAI,WAAA,EAAa,QAAA,CAAS,GAAA,CAAI,YAAA;EAAgB,OAAA,EAAS,QAAA,CAAS,GAAA;AAAA;;;cCJ1E,UAAA;;2BAI2B,qBAAA,KAAqB,OAAA;AAAA;;;cCiBhD,gBAAA,GACX,OAAA,EAAS,2BAAA,KACR,OAAA,CAAQ,oBAAA"}
1
+ {"version":3,"file":"configdirector-vue-client.d.mts","names":[],"sources":["../src/logger.ts","../src/types.ts","../src/plugin.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts","../src/client.ts"],"mappings":";;;;;cAca,mBAAA,GAAuB,KAAA,EAAO,0BAAA,KAA6B,oBAAA;;;KCF5D,YAAA;AAAA,KAEA,2BAAA;;ADAZ;;ECIE,MAAA;EACA,OAAA;EACA,UAAA;EACA,GAAA;EACA,OAAA;EDND;;;;;ACJD;;;;EAoBE,IAAA,GAAO,cAAA;EAlBG;;;;;;EAyBV,MAAA,GAAS,aAAA;EAUD;;;;;;EAHR,eAAA;EACA,OAAA,GAAU,qBAAA;EACV,MAAA,GAAS,oBAAA;EACT,KAAA,GAAQ,WAAA;EAjBD;;;;;EAuBP,OAAA,GAAU,cAAA;AAAA;;;cC3CC,oBAAA;iBACI,GAAA,EAAG,eAAA,EAAmB,2BAAA,GAA8B,oBAAA;AAAA;;;cCTxD,SAAA;EAAkB,MAAA,EAAQ,oBAAA;AAAA;;;cCE1B,eAAA;EACX,WAAA,EAAa,QAAA,CAAS,GAAA,CAAI,YAAA;EAC1B,OAAA,EAAS,QAAA,CAAS,GAAA;AAAA;;;cCDP,cAAA,aAA4B,eAAA,EACvC,SAAA,UACA,YAAA,EAAc,CAAA;EACX,KAAA,EAAO,UAAA,CAAW,CAAA;EAAI,WAAA,EAAa,QAAA,CAAS,GAAA,CAAI,YAAA;EAAgB,OAAA,EAAS,QAAA,CAAS,GAAA;AAAA;;;cCJ1E,UAAA;;2BAI2B,qBAAA,KAAqB,OAAA;AAAA;;;cCkBhD,gBAAA,GACX,OAAA,EAAS,2BAAA,KACR,OAAA,CAAQ,oBAAA"}
@@ -1,2 +1,2 @@
1
- import{i as e,n as t,s as n,t as r,u as i}from"./DefaultConfigDirectorClient-zODkltqb.mjs";import{computed as a,inject as o,onBeforeUnmount as s,readonly as c,ref as l,shallowRef as u,toRaw as d}from"vue";const f=e=>{var t;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(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var p=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime!=null||(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(){var e;let t=new Date,n=(e=this.startTime)==null?t:e,r=(e,r)=>({startTime:n,endTime:t,count:e,event:{reason:`invalid-context-kind`,kindSample:r}}),i=Array.from(this.countsByKindSample,([e,t])=>r(t,e)),a=this.countBeyondSampleLimit>0?[...i,r(this.countBeyondSampleLimit)]:i;return this.clear(),a}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},m=class{constructor(e){var t,n,r,i;this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new p,this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t,this.pendingEvaluationLimit=(n=e.evaluationQueueLimit)==null?1e3:n,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}},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)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class{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=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),y=e=>{try{self.postMessage(e)}catch{self.postMessage(v(e.payload.level,e.payload.message))}},b={debug:function(e,...t){y(v(`debug`,e,t))},info:function(e,...t){y(v(`info`,e,t))},warn:function(e,...t){y(v(`warn`,e,t))},error:function(e,...t){y(v(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){b.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(b.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){b.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:b}),_.start();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.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}}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){var t=this,n;if(t.closePromise)return;let r={type:`UpdateContext`,payload:{context:e}};(n=t.startWorker())==null||n.postMessage(r)}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 i(i({},e),{},{defaultValue:f({value:e.defaultValue,type:e.type}),evaluatedValue:f({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){var e;(e=this.worker)==null||e.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(){var e,t;clearTimeout(this.closeTimer),this.closeTimer=void 0,(e=this.worker)==null||e.terminate(),(t=this.closeResolve)==null||t.call(this)}};const h=(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`)},g=Math.ceil(128/Math.log2(62)),_=new TextEncoder,v=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,_.encode((t=e==null?void 0:e.toString())==null?``:t));return h(new Uint8Array(n,0,16),g)},y=(e,n,i)=>r.from(({clientSdkKey:e,baseUrl:r,logger:i,metadata:a})=>new m({sdkKey:e,sdkIdentity:{sdkName:n.sdkName,sdkVersion:n.sdkVersion},metaContext:{appName:a==null?void 0:a.appName,appVersion:a==null?void 0:a.appVersion},logger:i,baseUrl:r,urlFactory:t,valueIdGenerator:v}),e,n,i);var b=class{decorateMessage(e){return`[ConfigDirector:vue-sdk] ${e}`}};const x=t=>e(t,new b),S=(e,t)=>y(e,{sdkName:`vue-sdk`,sdkVersion:`1.8.0`},t),C=e=>{var t;return S(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:(t=e.logger)==null?x(`warn`):t,hooks:e.hooks})},w=async e=>{let t=C(e);return await t.initialize(e.context),t},T=Symbol(`ConfigDirector.Client`),E=Symbol(`ConfigDirector.ClientStatus`),D=Symbol(`ConfigDirector.Context`),O={install:(e,t)=>{let n=k(t)?t:C(t),r=l(n.isReady?`ready`:`loading`),i=c(r);n.on(`clientReady`,()=>r.value=`ready`);let a=l(t.context),o=c(a);n.on(`contextUpdated`,({context:e})=>a.value=e),!n.isReady&&!n.isInitializing&&n.initialize(t.context).then(()=>{n.isReady||(r.value=`default`)}),e.provide(T,n),e.provide(E,i),e.provide(D,o)}},k=e=>{let t=e;return typeof t.initialize==`function`&&typeof t.getValue==`function`&&typeof t.watch==`function`&&typeof t.on==`function`},A=e=>{let t=o(e);if(t===void 0)throw new n(`Could not inject ${e.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`);return t},j=()=>({client:A(T)}),M=()=>{let e=A(E);return{readyStatus:e,loading:a(()=>e.value===`loading`)}},N=(e,t)=>{let{client:n}=j(),{readyStatus:r,loading:i}=M(),a=u(n.getValue(e,t)),o=e=>a.value=e;return n.watch(e,t,o),s(()=>n.unwatch(e,o)),{value:a,readyStatus:r,loading:i}},P=()=>{let{client:e}=j();return{context:A(D),updateContext:async t=>{let n=d(t);JSON.stringify(e.context)!=JSON.stringify(n)&&await e.updateContext(n)}}};export{O as ConfigDirectorPlugin,x as createConsoleLogger,w as initializeClient,j as useClient,M as useClientStatus,N as useConfigValue,P as useContext};
1
+ import{a as e,i as t,n,p as r,r as i,s as a,t as o,u as s}from"./DefaultConfigDirectorClient-CgL72BvL.mjs";import{computed as c,inject as l,onBeforeUnmount as u,readonly as d,ref as f,shallowRef as p,toRaw as m}from"vue";const h=e=>{var t;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(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var g=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime!=null||(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(){var e;let t=new Date,n=(e=this.startTime)==null?t:e,r=(e,r)=>({startTime:n,endTime:t,count:e,event:{reason:`invalid-context-kind`,kindSample:r}}),i=Array.from(this.countsByKindSample,([e,t])=>r(t,e)),a=this.countBeyondSampleLimit>0?[...i,r(this.countBeyondSampleLimit)]:i;return this.clear(),a}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},_=class{constructor(e){var t,n,r,i;this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new g,this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t,this.pendingEvaluationLimit=(n=e.evaluationQueueLimit)==null?1e3:n,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}},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)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class{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=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),y=e=>{try{self.postMessage(e)}catch{self.postMessage(v(e.payload.level,e.payload.message))}},b={debug:function(e,...t){y(v(`debug`,e,t))},info:function(e,...t){y(v(`info`,e,t))},warn:function(e,...t){y(v(`warn`,e,t))},error:function(e,...t){y(v(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){b.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(b.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){b.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:b}),_.start();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.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}}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){var t=this,n;if(t.closePromise)return;let r={type:`UpdateContext`,payload:{context:e}};(n=t.startWorker())==null||n.postMessage(r)}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 r(r({},e),{},{defaultValue:h({value:e.defaultValue,type:e.type}),evaluatedValue:h({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){var e;(e=this.worker)==null||e.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(){var e,t;clearTimeout(this.closeTimer),this.closeTimer=void 0,(e=this.worker)==null||e.terminate(),(t=this.closeResolve)==null||t.call(this)}};const v=(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`)},y=Math.ceil(128/Math.log2(62)),b=new TextEncoder,x=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,b.encode((t=e==null?void 0:e.toString())==null?``:t));return v(new Uint8Array(n,0,16),y)},S=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),C=async e=>{let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return n+S(new Uint8Array(t))},w=()=>typeof crypto<`u`&&crypto.subtle!=null,T=e=>{let n=t();if(!n||!w())return;let r=C(e);return{read:async()=>n.getItem(await r),write:async e=>n.setItem(await r,e),remove:async()=>n.removeItem(await r),sizeLimit:()=>i}},E=(t,n,r)=>o.from(({clientSdkKey:t,baseUrl:r,logger:i,metadata:a})=>new _({sdkKey:t,sdkIdentity:{sdkName:n.sdkName,sdkVersion:n.sdkVersion},metaContext:{appName:a==null?void 0:a.appName,appVersion:a==null?void 0:a.appVersion},logger:i,baseUrl:r,urlFactory:e,valueIdGenerator:x}),t,n,r,{platformCachingProvider:T});var D=class{decorateMessage(e){return`[ConfigDirector:vue-sdk] ${e}`}};const O=e=>a(e,new D),k=(e,t)=>E(e,{sdkName:`vue-sdk`,sdkVersion:`1.9.0`},t),A=e=>{var t;return k(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:(t=e.logger)==null?O(`warn`):t,hooks:e.hooks,caching:e.caching})},j=async e=>{let t=A(e);return await t.initialize(e.context),t},M=Symbol(`ConfigDirector.Client`),N=Symbol(`ConfigDirector.ClientStatus`),P=Symbol(`ConfigDirector.Context`),F={install:(e,t)=>{let n=I(t)?t:A(t),r=f(n.isReady?`ready`:`loading`),i=d(r);n.on(`clientReady`,()=>r.value=`ready`);let a=f(t.context),o=d(a);n.on(`contextUpdated`,({context:e})=>a.value=e),!n.isReady&&!n.isInitializing&&n.initialize(t.context).then(()=>{n.isReady||(r.value=`default`)}),e.provide(M,n),e.provide(N,i),e.provide(P,o)}},I=e=>{let t=e;return typeof t.initialize==`function`&&typeof t.getValue==`function`&&typeof t.watch==`function`&&typeof t.on==`function`},L=e=>{let t=l(e);if(t===void 0)throw new s(`Could not inject ${e.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`);return t},R=()=>({client:L(M)}),z=()=>{let e=L(N);return{readyStatus:e,loading:c(()=>e.value===`loading`)}},B=(e,t)=>{let{client:n}=R(),{readyStatus:r,loading:i}=z(),a=p(n.getValue(e,t)),o=e=>a.value=e;return n.watch(e,t,o),u(()=>n.unwatch(e,o)),{value:a,readyStatus:r,loading:i}},V=()=>{let{client:e}=R();return{context:L(P),updateContext:async t=>{let n=m(t);JSON.stringify(e.context)!=JSON.stringify(n)&&await e.updateContext(n)}}};export{F as ConfigDirectorPlugin,O as createConsoleLogger,j as initializeClient,R as useClient,z as useClientStatus,B as useConfigValue,V as useContext};
2
2
  //# sourceMappingURL=configdirector-vue-client.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"configdirector-vue-client.mjs","names":["createJsSdkLogger"],"sources":["../../shared/src/telemetry/utils.ts","../../shared/src/telemetry/InvalidContextSubmissions.ts","../../js-browser-client/src/telemetry/WebWorkerTelemetryClient.ts","../../shared/src/base62-encoder.ts","../../shared/src/value-id.ts","../../js-browser-client/src/telemetry/value-id-generator.ts","../../js-browser-client/src/BrowserConfigDirectorClient.ts","../src/logger.ts","../src/client.ts","../src/plugin.ts","../src/composables/util.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts"],"sourcesContent":["import type { ConfigType, ConfigValueType } from \"../types\";\nimport type { ValueIdGenerator, DroppedEvents } from \"./types\";\n\nconst CONFIG_VALUE_MAX_LENGTH = 500;\n\nexport type TelemetryValue = {\n value?: string;\n valueId?: string;\n type?: ConfigType;\n};\n\nexport type TelemetryEvaluationValue<TV extends ConfigValueType> = {\n value: TV;\n valueId?: string | null | undefined;\n type?: ConfigType;\n};\n\nexport const compactTelemetryValue = async (\n tv: TelemetryValue,\n valueIdGenerator: ValueIdGenerator,\n): Promise<TelemetryValue> => {\n if (tv.valueId) {\n return { valueId: tv.valueId };\n }\n if (tv.value) {\n if (tv.value.length <= CONFIG_VALUE_MAX_LENGTH && tv.type != \"json\") {\n return { value: tv.value };\n }\n\n return { valueId: await valueIdGenerator(tv.value) };\n }\n\n return tv;\n};\n\nexport const mapToTelemetryValue = <TV extends ConfigValueType>(\n ev: TelemetryEvaluationValue<TV>,\n): TelemetryValue => {\n if (ev.type === \"json\" || (ev.type == null && typeof ev.value === \"object\")) {\n if (ev.valueId) {\n return { valueId: ev.valueId, type: \"json\" };\n }\n try {\n const json = JSON.stringify(ev.value);\n return { value: json, type: \"json\" };\n } catch {\n return { value: ev.value.toString(), type: \"json\" };\n }\n }\n\n const stringValue = ev.value?.toString();\n if (stringValue && stringValue.length <= CONFIG_VALUE_MAX_LENGTH) {\n return { value: stringValue };\n }\n\n return ev.valueId ? { valueId: ev.valueId } : { value: stringValue };\n};\n\nexport const djb2Hash = (data: string): string => {\n const hash = djb2(new TextEncoder().encode(data));\n return hash.toString(16).padStart(8, \"0\");\n};\n\nconst djb2 = (bytes: Uint8Array): number => {\n let hash = 5381;\n for (let i = 0; i < bytes.length; i++) {\n hash = (hash << 5) + hash + (bytes[i] ?? 0);\n hash = hash >>> 0;\n }\n return hash;\n};\n\nexport const isEventListEmpty = <T extends Record<string | symbol, any[]>>(eventList: T): boolean => {\n const keys = Object.keys(eventList);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((eventList[key]?.length ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isDroppedEventsEmpty = (droppedEvents?: DroppedEvents): boolean => {\n if (!droppedEvents) {\n return true;\n }\n const keys = Object.keys(droppedEvents);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((droppedEvents[key] ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n","import type { InvalidContextEvent } from \"./telemetry-events\";\nimport type { AggregatedEvent } from \"./types\";\n\nexport const DISTINCT_KIND_SAMPLE_LIMIT = 20;\n\nexport type InvalidContextRecording =\n | \"new-kind-sample\"\n | \"known-kind-sample\"\n | \"first-beyond-sample-limit\"\n | \"beyond-sample-limit\";\n\nexport class InvalidContextSubmissions {\n private readonly countsByKindSample = new Map<string, number>();\n private countBeyondSampleLimit = 0;\n private startTime: Date | undefined;\n\n public record(kindSample: string): InvalidContextRecording {\n this.startTime ??= new Date();\n return this.add(kindSample, 1);\n }\n\n public absorb(entries: AggregatedEvent<InvalidContextEvent>[]): void {\n for (const entry of entries) {\n if (this.startTime === undefined || entry.startTime < this.startTime) {\n this.startTime = entry.startTime;\n }\n this.add(entry.event.kindSample, entry.count);\n }\n }\n\n private add(kindSample: string | undefined, count: number): InvalidContextRecording {\n if (kindSample !== undefined) {\n const knownCount = this.countsByKindSample.get(kindSample);\n if (knownCount !== undefined) {\n this.countsByKindSample.set(kindSample, knownCount + count);\n return \"known-kind-sample\";\n }\n if (this.countsByKindSample.size < DISTINCT_KIND_SAMPLE_LIMIT) {\n this.countsByKindSample.set(kindSample, count);\n return \"new-kind-sample\";\n }\n }\n const firstBeyondSampleLimit = this.countBeyondSampleLimit === 0;\n this.countBeyondSampleLimit += count;\n return firstBeyondSampleLimit ? \"first-beyond-sample-limit\" : \"beyond-sample-limit\";\n }\n\n public takeSnapshot(): AggregatedEvent<InvalidContextEvent>[] {\n const endTime = new Date();\n const startTime = this.startTime ?? endTime;\n const entryOf = (count: number, kindSample?: string): AggregatedEvent<InvalidContextEvent> => ({\n startTime,\n endTime,\n count,\n event: { reason: \"invalid-context-kind\", kindSample },\n });\n const sampledEntries = Array.from(this.countsByKindSample, ([kindSample, count]) =>\n entryOf(count, kindSample),\n );\n const entries =\n this.countBeyondSampleLimit > 0\n ? [...sampledEntries, entryOf(this.countBeyondSampleLimit)]\n : sampledEntries;\n this.clear();\n return entries;\n }\n\n private clear() {\n this.countsByKindSample.clear();\n this.countBeyondSampleLimit = 0;\n this.startTime = undefined;\n }\n}\n","import { type TelemetryEventCollectorOptions } from \"@shared/telemetry/TelemetryEventCollector\";\nimport type { ConfigDirectorContext, ConfigDirectorLogger, ConfigValueType } from \"@js-client-core/types\";\nimport type { TelemetryClient, EvaluatedConfigEvent } from \"@js-client-core/telemetry\";\nimport type {\n TelemetryCloseEvent,\n TelemetryEvaluatedConfigEvent,\n TelemetryFlushEvent,\n TelemetryInitializeEvent,\n TelemetryInvalidContextSubmissionsEvent,\n TelemetryUpdateContextEvent,\n TelemetryWorkerResponseEvent,\n} from \"./types\";\nimport type { TelemetryValue } from \"@shared/telemetry/utils\";\nimport { mapToTelemetryValue } from \"@shared/telemetry/utils\";\nimport { InvalidContextSubmissions } from \"@shared/telemetry/InvalidContextSubmissions\";\n\nconst DEFAULT_WORKER_CLOSE_TIMEOUT = 6_000;\n\nexport type WebWorkerTelemetryClientOptions = TelemetryEventCollectorOptions & {\n workerCloseTimeout?: number;\n};\n\nexport class WebWorkerTelemetryClient implements TelemetryClient {\n private readonly logger: ConfigDirectorLogger;\n private readonly initializeMessage: TelemetryInitializeEvent;\n private worker: Worker | undefined;\n private turnedOff = false;\n private readonly pendingEvaluations: TelemetryEvaluatedConfigEvent[] = [];\n private readonly pendingEvaluationLimit: number;\n private readonly pendingInvalidContextSubmissions = new InvalidContextSubmissions();\n private closePromise: Promise<void> | undefined;\n private closeResolve: (() => void) | undefined;\n private closeTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly workerCloseTimeout: number;\n private readonly visibilityHandler: () => void;\n\n constructor(options: WebWorkerTelemetryClientOptions) {\n this.logger = options.logger;\n this.workerCloseTimeout = options.workerCloseTimeout ?? DEFAULT_WORKER_CLOSE_TIMEOUT;\n this.pendingEvaluationLimit = options.evaluationQueueLimit ?? 1_000;\n\n this.initializeMessage = {\n type: \"Initialize\",\n payload: {\n sdkKey: options.sdkKey,\n sdkIdentity: options.sdkIdentity,\n metaContext: options.metaContext,\n baseUrl: options.baseUrl.toString(),\n evaluationQueueLimit: this.pendingEvaluationLimit,\n initialFlushIntervalDelay: options.initialFlushIntervalDelay ?? 5_000,\n flushIntervalDelay: options.flushIntervalDelay ?? 30_000,\n },\n };\n\n this.visibilityHandler = () => {\n if (document.visibilityState === \"hidden\") {\n this.flush();\n }\n };\n }\n\n private createWorkerOrTurnOff(): Worker | undefined {\n if (typeof Worker === \"undefined\") {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.\",\n );\n return undefined;\n }\n try {\n return new Worker(new URL(\"./worker.ts\", import.meta.url), { type: \"module\" });\n } catch (error) {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: \",\n error,\n );\n return undefined;\n }\n }\n\n private turnOff(warning: string, ...details: unknown[]) {\n this.turnedOff = true;\n this.pendingEvaluations.length = 0;\n this.logger.warn(warning, ...details);\n }\n\n private startWorker(): Worker | undefined {\n if (this.worker || this.turnedOff) {\n return this.worker;\n }\n const worker = this.createWorkerOrTurnOff();\n if (!worker) {\n return undefined;\n }\n worker.onmessage = (message: MessageEvent<TelemetryWorkerResponseEvent>) => {\n this.handleWorkerEvent(message.data);\n };\n worker.postMessage(this.initializeMessage);\n this.worker = worker;\n\n try {\n document.addEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[TelemetryEventCollector] Could not configure 'visibilitychange' listener: \", error);\n }\n\n for (const evaluation of this.pendingEvaluations) {\n worker.postMessage(evaluation);\n }\n this.pendingEvaluations.length = 0;\n this.forwardInvalidContextSubmissions(worker);\n return worker;\n }\n\n private forwardInvalidContextSubmissions(worker: Worker | undefined) {\n if (!worker) {\n return;\n }\n const entries = this.pendingInvalidContextSubmissions.takeSnapshot();\n if (entries.length === 0) {\n return;\n }\n const submissionsMessage: TelemetryInvalidContextSubmissionsEvent = {\n type: \"InvalidContextSubmissions\",\n payload: { entries },\n };\n worker.postMessage(submissionsMessage);\n }\n\n public async updateContext(value: ConfigDirectorContext | undefined) {\n if (this.closePromise) {\n return;\n }\n const updateContextMessage: TelemetryUpdateContextEvent = {\n type: \"UpdateContext\",\n payload: {\n context: value,\n },\n };\n this.startWorker()?.postMessage(updateContextMessage);\n }\n\n public evaluatedConfig<T extends ConfigValueType>(event: EvaluatedConfigEvent<T>): void {\n if (this.turnedOff) {\n return;\n }\n const evaluatedConfigMessage: TelemetryEvaluatedConfigEvent = {\n type: \"EvaluatedConfigEvent\",\n payload: this.sanitizeEvaluatedConfigEvent(event),\n };\n if (this.worker) {\n this.worker.postMessage(evaluatedConfigMessage);\n return;\n }\n if (this.pendingEvaluations.length >= this.pendingEvaluationLimit) {\n this.pendingEvaluations.shift();\n }\n this.pendingEvaluations.push(evaluatedConfigMessage);\n }\n\n public recordInvalidContext(kindSample: string): void {\n this.pendingInvalidContextSubmissions.record(kindSample);\n this.forwardInvalidContextSubmissions(this.worker);\n }\n\n private sanitizeEvaluatedConfigEvent<T extends ConfigValueType>(\n event: EvaluatedConfigEvent<T>,\n ): EvaluatedConfigEvent<TelemetryValue> {\n return {\n ...event,\n defaultValue: mapToTelemetryValue({ value: event.defaultValue, type: event.type }),\n evaluatedValue: mapToTelemetryValue({\n value: event.evaluatedValue,\n valueId: event.evaluatedValueId,\n type: event.type,\n }),\n };\n }\n\n private handleWorkerEvent(event: TelemetryWorkerResponseEvent) {\n if (event.type === \"Closed\") {\n this.finishClose();\n return;\n }\n if (!event.payload?.level || !event.payload?.message) {\n return;\n }\n const { level, message, args } = event.payload;\n\n switch (level) {\n case \"debug\":\n this.logger.debug(message, ...args);\n break;\n case \"info\":\n this.logger.info(message, ...args);\n break;\n case \"warn\":\n this.logger.warn(message, ...args);\n break;\n case \"error\":\n this.logger.error(message, ...args);\n break;\n }\n }\n\n private flush() {\n const flushMessage: TelemetryFlushEvent = {\n type: \"Flush\",\n };\n this.worker?.postMessage(flushMessage);\n }\n\n public close(): Promise<void> {\n if (this.closePromise) {\n return this.closePromise;\n }\n\n return this.performClose();\n }\n\n private performClose(): Promise<void> {\n const worker = this.worker;\n if (!worker) {\n this.pendingEvaluations.length = 0;\n this.closePromise = Promise.resolve();\n return this.closePromise;\n }\n try {\n document.removeEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: \", error);\n }\n this.closePromise = new Promise<void>((resolve) => {\n this.closeResolve = resolve;\n this.closeTimer = setTimeout(() => {\n this.logger.warn(\n \"[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.\",\n );\n this.finishClose();\n }, this.workerCloseTimeout);\n const closeMessage: TelemetryCloseEvent = { type: \"Close\" };\n worker.postMessage(closeMessage);\n });\n return this.closePromise;\n }\n\n private finishClose() {\n clearTimeout(this.closeTimer);\n this.closeTimer = undefined;\n this.worker?.terminate();\n this.closeResolve?.();\n }\n}\n","const BASE62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nexport const toBase62 = (buf: Uint8Array, length: number): string => {\n const ZERO = BigInt(0);\n const BASE = BigInt(62);\n const hex = Array.from(buf)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n let n = BigInt(\"0x\" + hex);\n let result = \"\";\n while (n > ZERO) {\n result = BASE62[Number(n % BASE)] + result;\n n /= BASE;\n }\n return result.padStart(length, \"0\");\n};\n","export const DIGEST_BYTES = 16;\nexport const BASE62_LENGTH = Math.ceil((DIGEST_BYTES * 8) / Math.log2(62));\n","import { toBase62 } from \"@shared/base62-encoder\";\nimport { DIGEST_BYTES, BASE62_LENGTH } from \"@shared/value-id\";\n\nconst encoder = new TextEncoder();\n\nexport const generateValueId = async (\n v: string | number | boolean | null | undefined,\n): Promise<string | undefined> => {\n if (typeof crypto === \"undefined\" || crypto.subtle == null) {\n return undefined;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encoder.encode(v?.toString() ?? \"\"));\n return toBase62(new Uint8Array(hashBuffer, 0, DIGEST_BYTES), BASE62_LENGTH);\n};\n","import {\n type ConfigDirectorClientOptions,\n type ConfigDirectorClient,\n type IdentifyingSdkOptions,\n type OfflineClientOptions,\n} from \"@js-client-core/index\";\nimport { WebWorkerTelemetryClient } from \"./telemetry/WebWorkerTelemetryClient\";\nimport { DefaultConfigDirectorClient } from \"@js-client-core/DefaultConfigDirectorClient\";\nimport { defaultUrlFactory } from \"@shared/url\";\nimport { generateValueId } from \"./telemetry/value-id-generator\";\n\n/**\n * Creates a browser client. With a client SDK key it connects to ConfigDirector; with\n * {@link OfflineClientOptions} alone it runs in `offline` mode and serves `connection.values`. An\n * absent key with `clientOptions` is the same as the options alone when their mode is `offline`,\n * and fails like a missing key otherwise.\n */\nexport const createBrowserClient = (\n clientSdkKeyOrOptions: string | OfflineClientOptions | undefined,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return DefaultConfigDirectorClient.from(\n ({ clientSdkKey, baseUrl, logger, metadata }) =>\n new WebWorkerTelemetryClient({\n sdkKey: clientSdkKey,\n sdkIdentity: {\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n },\n metaContext: {\n appName: metadata?.appName,\n appVersion: metadata?.appVersion,\n },\n logger,\n baseUrl,\n urlFactory: defaultUrlFactory,\n valueIdGenerator: generateValueId,\n }),\n clientSdkKeyOrOptions,\n sdkOptions,\n clientOptions,\n );\n};\n","import type {\n ConfigDirectorLogMessageDecorator,\n ConfigDirectorLogger} from \"@js-browser-client/index\";\nimport {\n type ConfigDirectorLoggingLevel,\n createDefaultLogger as createJsSdkLogger,\n} from \"@js-browser-client/index\";\n\nclass MessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:vue-sdk] ${message}`;\n }\n}\n\nexport const createConsoleLogger = (level: ConfigDirectorLoggingLevel): ConfigDirectorLogger => {\n return createJsSdkLogger(level, new MessageDecorator());\n};\n","import type { ConfigDirectorClient, ConfigDirectorClientOptions } from \"@js-browser-client/index\";\nimport { createBrowserClient } from \"@js-browser-client/index\";\nimport type { ConfigDirectorPluginOptions } from \"./types\";\nimport { createConsoleLogger } from \"./logger\";\n\nconst createClient = (\n clientSdkKey: string | undefined,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return createBrowserClient(clientSdkKey, { sdkName: \"vue-sdk\", sdkVersion: \"__VERSION__\" }, clientOptions);\n};\n\nexport const createClientFromPluginOptions = (options: ConfigDirectorPluginOptions): ConfigDirectorClient => {\n return createClient(options.sdkKey, {\n connection: {\n url: options.url,\n timeout: options.timeout,\n mode: options.mode,\n pollingInterval: options.pollingInterval,\n values: options.values,\n },\n metadata: { appName: options.appName, appVersion: options.appVersion },\n logger: options.logger ?? createConsoleLogger(\"warn\"),\n hooks: options.hooks,\n });\n};\n\nexport const initializeClient = async (\n options: ConfigDirectorPluginOptions,\n): Promise<ConfigDirectorClient> => {\n const client = createClientFromPluginOptions(options);\n await client.initialize(options.context);\n return client;\n};\n","import { readonly, ref, type InjectionKey, type Ref, type App } from \"vue\";\nimport type { ClientStatus, ConfigDirectorPluginOptions } from \"./types\";\nimport { createClientFromPluginOptions } from \"./client\";\nimport type { ConfigDirectorClient, ConfigDirectorContext } from \"@js-client-core/types\";\n\nexport const ConfigDirectorClientKey: InjectionKey<ConfigDirectorClient> = Symbol(\"ConfigDirector.Client\");\nexport const ConfigDirectorStatusKey: InjectionKey<Readonly<Ref<ClientStatus>>> = Symbol(\n \"ConfigDirector.ClientStatus\",\n);\nexport const ConfigDirectorContextKey: InjectionKey<Readonly<Ref<ConfigDirectorContext | undefined>>> =\n Symbol(\"ConfigDirector.Context\");\n\nexport const ConfigDirectorPlugin = {\n install: (app: App, optionsOrClient: ConfigDirectorPluginOptions | ConfigDirectorClient) => {\n const client = isClientObject(optionsOrClient)\n ? optionsOrClient\n : createClientFromPluginOptions(optionsOrClient);\n\n const status = ref<ClientStatus>(client.isReady ? \"ready\" : \"loading\");\n const readonlyStatus = readonly(status);\n client.on(\"clientReady\", () => (status.value = \"ready\"));\n\n const context = ref<ConfigDirectorContext | undefined>(optionsOrClient.context);\n const readonlyContext = readonly(context);\n client.on(\"contextUpdated\", ({ context: newContext }) => (context.value = newContext));\n\n if (!client.isReady && !client.isInitializing) {\n client.initialize(optionsOrClient.context).then(() => {\n if (!client.isReady) {\n // The client timed-out initialization and it is serving default values\n status.value = \"default\";\n }\n });\n }\n\n app.provide(ConfigDirectorClientKey, client);\n app.provide(ConfigDirectorStatusKey, readonlyStatus);\n app.provide(ConfigDirectorContextKey, readonlyContext);\n },\n};\n\nconst isClientObject = (options: ConfigDirectorPluginOptions | ConfigDirectorClient): options is ConfigDirectorClient => {\n const candidate = options as Partial<ConfigDirectorClient>;\n return (\n typeof candidate.initialize === \"function\" &&\n typeof candidate.getValue === \"function\" &&\n typeof candidate.watch === \"function\" &&\n typeof candidate.on === \"function\"\n );\n};\n","import type { InjectionKey } from \"vue\";\nimport { inject } from \"vue\";\nimport { ConfigDirectorInitializationError } from \"@shared/errors\";\n\nexport const injectOrThrow = <T>(key: InjectionKey<T>): T => {\n const injected = inject(key);\n if (injected === undefined) {\n throw new ConfigDirectorInitializationError(\n `Could not inject ${key.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`,\n );\n }\n return injected;\n};\n","import type { ConfigDirectorClient } from \"@js-browser-client/index\";\nimport { ConfigDirectorClientKey } from \"../plugin\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useClient = (): { client: ConfigDirectorClient } => {\n const client = injectOrThrow(ConfigDirectorClientKey);\n return { client };\n};\n","import type { Ref } from \"vue\";\nimport { computed } from \"vue\";\nimport type { ClientStatus } from \"../types\";\nimport { injectOrThrow } from \"./util\";\nimport { ConfigDirectorStatusKey } from \"../plugin\";\n\nexport const useClientStatus = (): {\n readyStatus: Readonly<Ref<ClientStatus>>;\n loading: Readonly<Ref<boolean>>;\n} => {\n const readyStatus = injectOrThrow(ConfigDirectorStatusKey);\n const loading = computed(() => readyStatus.value === \"loading\");\n return { readyStatus, loading };\n};\n","import { shallowRef, onBeforeUnmount } from \"vue\";\nimport type { Ref, ShallowRef } from \"vue\";\nimport type { ConfigValueType } from \"@js-client-core/types\";\nimport type { ClientStatus } from \"../types\";\nimport { useClient } from \"./useClient\";\nimport { useClientStatus } from \"./useClientStatus\";\n\nexport const useConfigValue = <T extends ConfigValueType>(\n configKey: string,\n defaultValue: T,\n): { value: ShallowRef<T>; readyStatus: Readonly<Ref<ClientStatus>>; loading: Readonly<Ref<boolean>> } => {\n const { client } = useClient();\n const { readyStatus, loading } = useClientStatus();\n const configValue = shallowRef(client.getValue<T>(configKey, defaultValue)) as ShallowRef<T>;\n\n const watcher = (newValue: T) => (configValue.value = newValue);\n client.watch(configKey, defaultValue, watcher);\n\n onBeforeUnmount(() => client.unwatch(configKey, watcher));\n\n return { value: configValue, readyStatus, loading };\n};\n","import type { ConfigDirectorContext } from \"@js-browser-client/index\";\nimport { toRaw } from \"vue\";\nimport { ConfigDirectorContextKey } from \"../plugin\";\nimport { useClient } from \"./useClient\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useContext = () => {\n const { client } = useClient();\n const currentContext = injectOrThrow(ConfigDirectorContextKey);\n\n const updateContext = async (context: ConfigDirectorContext) => {\n const rawContext = toRaw(context);\n const oldContextJson = JSON.stringify(client.context);\n const newContextJson = JSON.stringify(rawContext);\n if (oldContextJson != newContextJson) {\n await client.updateContext(rawContext);\n }\n };\n\n return {\n context: currentContext,\n updateContext,\n };\n};\n"],"mappings":"6MAGA,MAgCa,EACX,GACmB,OACnB,GAAI,EAAG,OAAS,QAAW,EAAG,MAAQ,MAAQ,OAAO,EAAG,OAAU,SAAW,CAC3E,GA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AAgB,EAEzD,CAEK,EAAkB,GAAiG,CACvH,IAAM,EAAY,EAClB,OACE,OAAO,EAAU,YAAe,YAChC,OAAO,EAAU,UAAa,YAC9B,OAAO,EAAU,OAAU,YAC3B,OAAO,EAAU,IAAO,YC3Cf,EAAoB,GAA4B,CAC3D,IAAM,EAAW,EAAO,EAAI,CAC7B,GAAI,IAAa,IAAA,GACd,MAAM,IAAI,EACR,oBAAoB,EAAI,YAAY,8EACrC,CAEH,OAAO,GCPI,OAEJ,CAAE,OADM,EAAc,EAAwB,CACpC,ECAN,MAGR,CACH,IAAM,EAAc,EAAc,EAAwB,CAE1D,MAAO,CAAE,cAAa,QADN,MAAe,EAAY,QAAU,UAAU,CAChC,ECLpB,GACX,EACA,IACwG,CACxG,GAAM,CAAE,UAAW,GAAW,CACxB,CAAE,cAAa,WAAY,GAAiB,CAC5C,EAAc,EAAW,EAAO,SAAY,EAAW,EAAa,CAAC,CAErE,EAAW,GAAiB,EAAY,MAAQ,EAKtD,OAJA,EAAO,MAAM,EAAW,EAAc,EAAQ,CAE9C,MAAsB,EAAO,QAAQ,EAAW,EAAQ,CAAC,CAElD,CAAE,MAAO,EAAa,cAAa,UAAS,ECdxC,MAAmB,CAC9B,GAAM,CAAE,UAAW,GAAW,CAY9B,MAAO,CACL,QAZqB,EAAc,EAAyB,CAa5D,cAXoB,KAAO,IAAmC,CAC9D,IAAM,EAAa,EAAM,EAAQ,CACV,KAAK,UAAU,EAAO,QAAQ,EAC9B,KAAK,UAAU,EAAW,EAE/C,MAAM,EAAO,cAAc,EAAW,EAOzC"}
1
+ {"version":3,"file":"configdirector-vue-client.mjs","names":["createJsSdkLogger"],"sources":["../../shared/src/telemetry/utils.ts","../../shared/src/telemetry/InvalidContextSubmissions.ts","../../js-browser-client/src/telemetry/WebWorkerTelemetryClient.ts","../../shared/src/base62-encoder.ts","../../shared/src/value-id.ts","../../js-browser-client/src/telemetry/value-id-generator.ts","../../js-browser-client/src/local-storage-caching-provider.ts","../../js-browser-client/src/BrowserConfigDirectorClient.ts","../src/logger.ts","../src/client.ts","../src/plugin.ts","../src/composables/util.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts"],"sourcesContent":["import type { ConfigType, ConfigValueType } from \"../types\";\nimport type { ValueIdGenerator, DroppedEvents } from \"./types\";\n\nconst CONFIG_VALUE_MAX_LENGTH = 500;\n\nexport type TelemetryValue = {\n value?: string;\n valueId?: string;\n type?: ConfigType;\n};\n\nexport type TelemetryEvaluationValue<TV extends ConfigValueType> = {\n value: TV;\n valueId?: string | null | undefined;\n type?: ConfigType;\n};\n\nexport const compactTelemetryValue = async (\n tv: TelemetryValue,\n valueIdGenerator: ValueIdGenerator,\n): Promise<TelemetryValue> => {\n if (tv.valueId) {\n return { valueId: tv.valueId };\n }\n if (tv.value) {\n if (tv.value.length <= CONFIG_VALUE_MAX_LENGTH && tv.type != \"json\") {\n return { value: tv.value };\n }\n\n return { valueId: await valueIdGenerator(tv.value) };\n }\n\n return tv;\n};\n\nexport const mapToTelemetryValue = <TV extends ConfigValueType>(\n ev: TelemetryEvaluationValue<TV>,\n): TelemetryValue => {\n if (ev.type === \"json\" || (ev.type == null && typeof ev.value === \"object\")) {\n if (ev.valueId) {\n return { valueId: ev.valueId, type: \"json\" };\n }\n try {\n const json = JSON.stringify(ev.value);\n return { value: json, type: \"json\" };\n } catch {\n return { value: ev.value.toString(), type: \"json\" };\n }\n }\n\n const stringValue = ev.value?.toString();\n if (stringValue && stringValue.length <= CONFIG_VALUE_MAX_LENGTH) {\n return { value: stringValue };\n }\n\n return ev.valueId ? { valueId: ev.valueId } : { value: stringValue };\n};\n\nexport const djb2Hash = (data: string): string => {\n const hash = djb2(new TextEncoder().encode(data));\n return hash.toString(16).padStart(8, \"0\");\n};\n\nconst djb2 = (bytes: Uint8Array): number => {\n let hash = 5381;\n for (let i = 0; i < bytes.length; i++) {\n hash = (hash << 5) + hash + (bytes[i] ?? 0);\n hash = hash >>> 0;\n }\n return hash;\n};\n\nexport const isEventListEmpty = <T extends Record<string | symbol, any[]>>(eventList: T): boolean => {\n const keys = Object.keys(eventList);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((eventList[key]?.length ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isDroppedEventsEmpty = (droppedEvents?: DroppedEvents): boolean => {\n if (!droppedEvents) {\n return true;\n }\n const keys = Object.keys(droppedEvents);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((droppedEvents[key] ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n","import type { InvalidContextEvent } from \"./telemetry-events\";\nimport type { AggregatedEvent } from \"./types\";\n\nexport const DISTINCT_KIND_SAMPLE_LIMIT = 20;\n\nexport type InvalidContextRecording =\n | \"new-kind-sample\"\n | \"known-kind-sample\"\n | \"first-beyond-sample-limit\"\n | \"beyond-sample-limit\";\n\nexport class InvalidContextSubmissions {\n private readonly countsByKindSample = new Map<string, number>();\n private countBeyondSampleLimit = 0;\n private startTime: Date | undefined;\n\n public record(kindSample: string): InvalidContextRecording {\n this.startTime ??= new Date();\n return this.add(kindSample, 1);\n }\n\n public absorb(entries: AggregatedEvent<InvalidContextEvent>[]): void {\n for (const entry of entries) {\n if (this.startTime === undefined || entry.startTime < this.startTime) {\n this.startTime = entry.startTime;\n }\n this.add(entry.event.kindSample, entry.count);\n }\n }\n\n private add(kindSample: string | undefined, count: number): InvalidContextRecording {\n if (kindSample !== undefined) {\n const knownCount = this.countsByKindSample.get(kindSample);\n if (knownCount !== undefined) {\n this.countsByKindSample.set(kindSample, knownCount + count);\n return \"known-kind-sample\";\n }\n if (this.countsByKindSample.size < DISTINCT_KIND_SAMPLE_LIMIT) {\n this.countsByKindSample.set(kindSample, count);\n return \"new-kind-sample\";\n }\n }\n const firstBeyondSampleLimit = this.countBeyondSampleLimit === 0;\n this.countBeyondSampleLimit += count;\n return firstBeyondSampleLimit ? \"first-beyond-sample-limit\" : \"beyond-sample-limit\";\n }\n\n public takeSnapshot(): AggregatedEvent<InvalidContextEvent>[] {\n const endTime = new Date();\n const startTime = this.startTime ?? endTime;\n const entryOf = (count: number, kindSample?: string): AggregatedEvent<InvalidContextEvent> => ({\n startTime,\n endTime,\n count,\n event: { reason: \"invalid-context-kind\", kindSample },\n });\n const sampledEntries = Array.from(this.countsByKindSample, ([kindSample, count]) =>\n entryOf(count, kindSample),\n );\n const entries =\n this.countBeyondSampleLimit > 0\n ? [...sampledEntries, entryOf(this.countBeyondSampleLimit)]\n : sampledEntries;\n this.clear();\n return entries;\n }\n\n private clear() {\n this.countsByKindSample.clear();\n this.countBeyondSampleLimit = 0;\n this.startTime = undefined;\n }\n}\n","import { type TelemetryEventCollectorOptions } from \"@shared/telemetry/TelemetryEventCollector\";\nimport type { ConfigDirectorContext, ConfigDirectorLogger, ConfigValueType } from \"@js-client-core/types\";\nimport type { TelemetryClient, EvaluatedConfigEvent } from \"@js-client-core/telemetry\";\nimport type {\n TelemetryCloseEvent,\n TelemetryEvaluatedConfigEvent,\n TelemetryFlushEvent,\n TelemetryInitializeEvent,\n TelemetryInvalidContextSubmissionsEvent,\n TelemetryUpdateContextEvent,\n TelemetryWorkerResponseEvent,\n} from \"./types\";\nimport type { TelemetryValue } from \"@shared/telemetry/utils\";\nimport { mapToTelemetryValue } from \"@shared/telemetry/utils\";\nimport { InvalidContextSubmissions } from \"@shared/telemetry/InvalidContextSubmissions\";\n\nconst DEFAULT_WORKER_CLOSE_TIMEOUT = 6_000;\n\nexport type WebWorkerTelemetryClientOptions = TelemetryEventCollectorOptions & {\n workerCloseTimeout?: number;\n};\n\nexport class WebWorkerTelemetryClient implements TelemetryClient {\n private readonly logger: ConfigDirectorLogger;\n private readonly initializeMessage: TelemetryInitializeEvent;\n private worker: Worker | undefined;\n private turnedOff = false;\n private readonly pendingEvaluations: TelemetryEvaluatedConfigEvent[] = [];\n private readonly pendingEvaluationLimit: number;\n private readonly pendingInvalidContextSubmissions = new InvalidContextSubmissions();\n private closePromise: Promise<void> | undefined;\n private closeResolve: (() => void) | undefined;\n private closeTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly workerCloseTimeout: number;\n private readonly visibilityHandler: () => void;\n\n constructor(options: WebWorkerTelemetryClientOptions) {\n this.logger = options.logger;\n this.workerCloseTimeout = options.workerCloseTimeout ?? DEFAULT_WORKER_CLOSE_TIMEOUT;\n this.pendingEvaluationLimit = options.evaluationQueueLimit ?? 1_000;\n\n this.initializeMessage = {\n type: \"Initialize\",\n payload: {\n sdkKey: options.sdkKey,\n sdkIdentity: options.sdkIdentity,\n metaContext: options.metaContext,\n baseUrl: options.baseUrl.toString(),\n evaluationQueueLimit: this.pendingEvaluationLimit,\n initialFlushIntervalDelay: options.initialFlushIntervalDelay ?? 5_000,\n flushIntervalDelay: options.flushIntervalDelay ?? 30_000,\n },\n };\n\n this.visibilityHandler = () => {\n if (document.visibilityState === \"hidden\") {\n this.flush();\n }\n };\n }\n\n private createWorkerOrTurnOff(): Worker | undefined {\n if (typeof Worker === \"undefined\") {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.\",\n );\n return undefined;\n }\n try {\n return new Worker(new URL(\"./worker.ts\", import.meta.url), { type: \"module\" });\n } catch (error) {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: \",\n error,\n );\n return undefined;\n }\n }\n\n private turnOff(warning: string, ...details: unknown[]) {\n this.turnedOff = true;\n this.pendingEvaluations.length = 0;\n this.logger.warn(warning, ...details);\n }\n\n private startWorker(): Worker | undefined {\n if (this.worker || this.turnedOff) {\n return this.worker;\n }\n const worker = this.createWorkerOrTurnOff();\n if (!worker) {\n return undefined;\n }\n worker.onmessage = (message: MessageEvent<TelemetryWorkerResponseEvent>) => {\n this.handleWorkerEvent(message.data);\n };\n worker.postMessage(this.initializeMessage);\n this.worker = worker;\n\n try {\n document.addEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[TelemetryEventCollector] Could not configure 'visibilitychange' listener: \", error);\n }\n\n for (const evaluation of this.pendingEvaluations) {\n worker.postMessage(evaluation);\n }\n this.pendingEvaluations.length = 0;\n this.forwardInvalidContextSubmissions(worker);\n return worker;\n }\n\n private forwardInvalidContextSubmissions(worker: Worker | undefined) {\n if (!worker) {\n return;\n }\n const entries = this.pendingInvalidContextSubmissions.takeSnapshot();\n if (entries.length === 0) {\n return;\n }\n const submissionsMessage: TelemetryInvalidContextSubmissionsEvent = {\n type: \"InvalidContextSubmissions\",\n payload: { entries },\n };\n worker.postMessage(submissionsMessage);\n }\n\n public async updateContext(value: ConfigDirectorContext | undefined) {\n if (this.closePromise) {\n return;\n }\n const updateContextMessage: TelemetryUpdateContextEvent = {\n type: \"UpdateContext\",\n payload: {\n context: value,\n },\n };\n this.startWorker()?.postMessage(updateContextMessage);\n }\n\n public evaluatedConfig<T extends ConfigValueType>(event: EvaluatedConfigEvent<T>): void {\n if (this.turnedOff) {\n return;\n }\n const evaluatedConfigMessage: TelemetryEvaluatedConfigEvent = {\n type: \"EvaluatedConfigEvent\",\n payload: this.sanitizeEvaluatedConfigEvent(event),\n };\n if (this.worker) {\n this.worker.postMessage(evaluatedConfigMessage);\n return;\n }\n if (this.pendingEvaluations.length >= this.pendingEvaluationLimit) {\n this.pendingEvaluations.shift();\n }\n this.pendingEvaluations.push(evaluatedConfigMessage);\n }\n\n public recordInvalidContext(kindSample: string): void {\n this.pendingInvalidContextSubmissions.record(kindSample);\n this.forwardInvalidContextSubmissions(this.worker);\n }\n\n private sanitizeEvaluatedConfigEvent<T extends ConfigValueType>(\n event: EvaluatedConfigEvent<T>,\n ): EvaluatedConfigEvent<TelemetryValue> {\n return {\n ...event,\n defaultValue: mapToTelemetryValue({ value: event.defaultValue, type: event.type }),\n evaluatedValue: mapToTelemetryValue({\n value: event.evaluatedValue,\n valueId: event.evaluatedValueId,\n type: event.type,\n }),\n };\n }\n\n private handleWorkerEvent(event: TelemetryWorkerResponseEvent) {\n if (event.type === \"Closed\") {\n this.finishClose();\n return;\n }\n if (!event.payload?.level || !event.payload?.message) {\n return;\n }\n const { level, message, args } = event.payload;\n\n switch (level) {\n case \"debug\":\n this.logger.debug(message, ...args);\n break;\n case \"info\":\n this.logger.info(message, ...args);\n break;\n case \"warn\":\n this.logger.warn(message, ...args);\n break;\n case \"error\":\n this.logger.error(message, ...args);\n break;\n }\n }\n\n private flush() {\n const flushMessage: TelemetryFlushEvent = {\n type: \"Flush\",\n };\n this.worker?.postMessage(flushMessage);\n }\n\n public close(): Promise<void> {\n if (this.closePromise) {\n return this.closePromise;\n }\n\n return this.performClose();\n }\n\n private performClose(): Promise<void> {\n const worker = this.worker;\n if (!worker) {\n this.pendingEvaluations.length = 0;\n this.closePromise = Promise.resolve();\n return this.closePromise;\n }\n try {\n document.removeEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: \", error);\n }\n this.closePromise = new Promise<void>((resolve) => {\n this.closeResolve = resolve;\n this.closeTimer = setTimeout(() => {\n this.logger.warn(\n \"[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.\",\n );\n this.finishClose();\n }, this.workerCloseTimeout);\n const closeMessage: TelemetryCloseEvent = { type: \"Close\" };\n worker.postMessage(closeMessage);\n });\n return this.closePromise;\n }\n\n private finishClose() {\n clearTimeout(this.closeTimer);\n this.closeTimer = undefined;\n this.worker?.terminate();\n this.closeResolve?.();\n }\n}\n","const BASE62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nexport const toBase62 = (buf: Uint8Array, length: number): string => {\n const ZERO = BigInt(0);\n const BASE = BigInt(62);\n const hex = Array.from(buf)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n let n = BigInt(\"0x\" + hex);\n let result = \"\";\n while (n > ZERO) {\n result = BASE62[Number(n % BASE)] + result;\n n /= BASE;\n }\n return result.padStart(length, \"0\");\n};\n","export const DIGEST_BYTES = 16;\nexport const BASE62_LENGTH = Math.ceil((DIGEST_BYTES * 8) / Math.log2(62));\n","import { toBase62 } from \"@shared/base62-encoder\";\nimport { DIGEST_BYTES, BASE62_LENGTH } from \"@shared/value-id\";\n\nconst encoder = new TextEncoder();\n\nexport const generateValueId = async (\n v: string | number | boolean | null | undefined,\n): Promise<string | undefined> => {\n if (typeof crypto === \"undefined\" || crypto.subtle == null) {\n return undefined;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encoder.encode(v?.toString() ?? \"\"));\n return toBase62(new Uint8Array(hashBuffer, 0, DIGEST_BYTES), BASE62_LENGTH);\n};\n","import type { CachingProvider } from \"@js-client-core/index\";\nimport { CACHED_VALUES_STORAGE_KEY_PREFIX, DEFAULT_CACHING_SIZE_LIMIT_BYTES } from \"@js-client-core/cached-values\";\nimport { localStorageIfAvailable } from \"@js-client-core/browser-globals\";\n\nconst toHex = (bytes: Uint8Array): string =>\n Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\nconst storageKeyFor = async (clientSdkKey: string): Promise<string> => {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(clientSdkKey));\n return CACHED_VALUES_STORAGE_KEY_PREFIX + toHex(new Uint8Array(digest));\n};\n\nconst subtleCryptoAvailable = (): boolean => typeof crypto !== \"undefined\" && crypto.subtle != null;\n\nexport const localStorageCachingProvider = (clientSdkKey: string): CachingProvider | undefined => {\n const storage = localStorageIfAvailable();\n if (!storage || !subtleCryptoAvailable()) {\n return undefined;\n }\n const storageKey = storageKeyFor(clientSdkKey);\n return {\n read: async () => storage.getItem(await storageKey),\n write: async (value) => storage.setItem(await storageKey, value),\n remove: async () => storage.removeItem(await storageKey),\n sizeLimit: () => DEFAULT_CACHING_SIZE_LIMIT_BYTES,\n };\n};\n","import {\n type ConfigDirectorClientOptions,\n type ConfigDirectorClient,\n type IdentifyingSdkOptions,\n type OfflineClientOptions,\n} from \"@js-client-core/index\";\nimport { WebWorkerTelemetryClient } from \"./telemetry/WebWorkerTelemetryClient\";\nimport { DefaultConfigDirectorClient } from \"@js-client-core/DefaultConfigDirectorClient\";\nimport { defaultUrlFactory } from \"@shared/url\";\nimport { generateValueId } from \"./telemetry/value-id-generator\";\nimport { localStorageCachingProvider } from \"./local-storage-caching-provider\";\n\n/**\n * Creates a browser client. With a client SDK key it connects to ConfigDirector; with\n * {@link OfflineClientOptions} alone it runs in `offline` mode and serves `connection.values`. An\n * absent key with `clientOptions` is the same as the options alone when their mode is `offline`,\n * and fails like a missing key otherwise.\n */\nexport const createBrowserClient = (\n clientSdkKeyOrOptions: string | OfflineClientOptions | undefined,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return DefaultConfigDirectorClient.from(\n ({ clientSdkKey, baseUrl, logger, metadata }) =>\n new WebWorkerTelemetryClient({\n sdkKey: clientSdkKey,\n sdkIdentity: {\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n },\n metaContext: {\n appName: metadata?.appName,\n appVersion: metadata?.appVersion,\n },\n logger,\n baseUrl,\n urlFactory: defaultUrlFactory,\n valueIdGenerator: generateValueId,\n }),\n clientSdkKeyOrOptions,\n sdkOptions,\n clientOptions,\n { platformCachingProvider: localStorageCachingProvider },\n );\n};\n","import type {\n ConfigDirectorLogMessageDecorator,\n ConfigDirectorLogger} from \"@js-browser-client/index\";\nimport {\n type ConfigDirectorLoggingLevel,\n createDefaultLogger as createJsSdkLogger,\n} from \"@js-browser-client/index\";\n\nclass MessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:vue-sdk] ${message}`;\n }\n}\n\nexport const createConsoleLogger = (level: ConfigDirectorLoggingLevel): ConfigDirectorLogger => {\n return createJsSdkLogger(level, new MessageDecorator());\n};\n","import type { ConfigDirectorClient, ConfigDirectorClientOptions } from \"@js-browser-client/index\";\nimport { createBrowserClient } from \"@js-browser-client/index\";\nimport type { ConfigDirectorPluginOptions } from \"./types\";\nimport { createConsoleLogger } from \"./logger\";\n\nconst createClient = (\n clientSdkKey: string | undefined,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return createBrowserClient(clientSdkKey, { sdkName: \"vue-sdk\", sdkVersion: \"__VERSION__\" }, clientOptions);\n};\n\nexport const createClientFromPluginOptions = (options: ConfigDirectorPluginOptions): ConfigDirectorClient => {\n return createClient(options.sdkKey, {\n connection: {\n url: options.url,\n timeout: options.timeout,\n mode: options.mode,\n pollingInterval: options.pollingInterval,\n values: options.values,\n },\n metadata: { appName: options.appName, appVersion: options.appVersion },\n logger: options.logger ?? createConsoleLogger(\"warn\"),\n hooks: options.hooks,\n caching: options.caching,\n });\n};\n\nexport const initializeClient = async (\n options: ConfigDirectorPluginOptions,\n): Promise<ConfigDirectorClient> => {\n const client = createClientFromPluginOptions(options);\n await client.initialize(options.context);\n return client;\n};\n","import { readonly, ref, type InjectionKey, type Ref, type App } from \"vue\";\nimport type { ClientStatus, ConfigDirectorPluginOptions } from \"./types\";\nimport { createClientFromPluginOptions } from \"./client\";\nimport type { ConfigDirectorClient, ConfigDirectorContext } from \"@js-client-core/types\";\n\nexport const ConfigDirectorClientKey: InjectionKey<ConfigDirectorClient> = Symbol(\"ConfigDirector.Client\");\nexport const ConfigDirectorStatusKey: InjectionKey<Readonly<Ref<ClientStatus>>> = Symbol(\n \"ConfigDirector.ClientStatus\",\n);\nexport const ConfigDirectorContextKey: InjectionKey<Readonly<Ref<ConfigDirectorContext | undefined>>> =\n Symbol(\"ConfigDirector.Context\");\n\nexport const ConfigDirectorPlugin = {\n install: (app: App, optionsOrClient: ConfigDirectorPluginOptions | ConfigDirectorClient) => {\n const client = isClientObject(optionsOrClient)\n ? optionsOrClient\n : createClientFromPluginOptions(optionsOrClient);\n\n const status = ref<ClientStatus>(client.isReady ? \"ready\" : \"loading\");\n const readonlyStatus = readonly(status);\n client.on(\"clientReady\", () => (status.value = \"ready\"));\n\n const context = ref<ConfigDirectorContext | undefined>(optionsOrClient.context);\n const readonlyContext = readonly(context);\n client.on(\"contextUpdated\", ({ context: newContext }) => (context.value = newContext));\n\n if (!client.isReady && !client.isInitializing) {\n client.initialize(optionsOrClient.context).then(() => {\n if (!client.isReady) {\n // The client timed-out initialization and it is serving default values\n status.value = \"default\";\n }\n });\n }\n\n app.provide(ConfigDirectorClientKey, client);\n app.provide(ConfigDirectorStatusKey, readonlyStatus);\n app.provide(ConfigDirectorContextKey, readonlyContext);\n },\n};\n\nconst isClientObject = (options: ConfigDirectorPluginOptions | ConfigDirectorClient): options is ConfigDirectorClient => {\n const candidate = options as Partial<ConfigDirectorClient>;\n return (\n typeof candidate.initialize === \"function\" &&\n typeof candidate.getValue === \"function\" &&\n typeof candidate.watch === \"function\" &&\n typeof candidate.on === \"function\"\n );\n};\n","import type { InjectionKey } from \"vue\";\nimport { inject } from \"vue\";\nimport { ConfigDirectorInitializationError } from \"@shared/errors\";\n\nexport const injectOrThrow = <T>(key: InjectionKey<T>): T => {\n const injected = inject(key);\n if (injected === undefined) {\n throw new ConfigDirectorInitializationError(\n `Could not inject ${key.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`,\n );\n }\n return injected;\n};\n","import type { ConfigDirectorClient } from \"@js-browser-client/index\";\nimport { ConfigDirectorClientKey } from \"../plugin\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useClient = (): { client: ConfigDirectorClient } => {\n const client = injectOrThrow(ConfigDirectorClientKey);\n return { client };\n};\n","import type { Ref } from \"vue\";\nimport { computed } from \"vue\";\nimport type { ClientStatus } from \"../types\";\nimport { injectOrThrow } from \"./util\";\nimport { ConfigDirectorStatusKey } from \"../plugin\";\n\nexport const useClientStatus = (): {\n readyStatus: Readonly<Ref<ClientStatus>>;\n loading: Readonly<Ref<boolean>>;\n} => {\n const readyStatus = injectOrThrow(ConfigDirectorStatusKey);\n const loading = computed(() => readyStatus.value === \"loading\");\n return { readyStatus, loading };\n};\n","import { shallowRef, onBeforeUnmount } from \"vue\";\nimport type { Ref, ShallowRef } from \"vue\";\nimport type { ConfigValueType } from \"@js-client-core/types\";\nimport type { ClientStatus } from \"../types\";\nimport { useClient } from \"./useClient\";\nimport { useClientStatus } from \"./useClientStatus\";\n\nexport const useConfigValue = <T extends ConfigValueType>(\n configKey: string,\n defaultValue: T,\n): { value: ShallowRef<T>; readyStatus: Readonly<Ref<ClientStatus>>; loading: Readonly<Ref<boolean>> } => {\n const { client } = useClient();\n const { readyStatus, loading } = useClientStatus();\n const configValue = shallowRef(client.getValue<T>(configKey, defaultValue)) as ShallowRef<T>;\n\n const watcher = (newValue: T) => (configValue.value = newValue);\n client.watch(configKey, defaultValue, watcher);\n\n onBeforeUnmount(() => client.unwatch(configKey, watcher));\n\n return { value: configValue, readyStatus, loading };\n};\n","import type { ConfigDirectorContext } from \"@js-browser-client/index\";\nimport { toRaw } from \"vue\";\nimport { ConfigDirectorContextKey } from \"../plugin\";\nimport { useClient } from \"./useClient\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useContext = () => {\n const { client } = useClient();\n const currentContext = injectOrThrow(ConfigDirectorContextKey);\n\n const updateContext = async (context: ConfigDirectorContext) => {\n const rawContext = toRaw(context);\n const oldContextJson = JSON.stringify(client.context);\n const newContextJson = JSON.stringify(rawContext);\n if (oldContextJson != newContextJson) {\n await client.updateContext(rawContext);\n }\n };\n\n return {\n context: currentContext,\n updateContext,\n };\n};\n"],"mappings":"6NAGA,MAgCa,EACX,GACmB,OACnB,GAAI,EAAG,OAAS,QAAW,EAAG,MAAQ,MAAQ,OAAO,EAAG,OAAU,SAAW,CAC3E,GAAI,EAAG,QACL,MAAO,CAAE,QAAS,EAAG,QAAS,KAAM,OAAQ,CAE9C,GAAI,CAEF,MAAO,CAAE,MADI,KAAK,UAAU,EAAG,MAAM,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,CAAC,CAElD,CAAE,MAAO,EAAa,cAAa,UAAS,ECdxC,MAAmB,CAC9B,GAAM,CAAE,UAAW,GAAW,CAY9B,MAAO,CACL,QAZqB,EAAc,EAAyB,CAa5D,cAXoB,KAAO,IAAmC,CAC9D,IAAM,EAAa,EAAM,EAAQ,CACV,KAAK,UAAU,EAAO,QAAQ,EAC9B,KAAK,UAAU,EAAW,EAE/C,MAAM,EAAO,cAAc,EAAW,EAOzC"}
@@ -20,7 +20,7 @@ interface ConfigDirectorLogger {
20
20
  warn(message: string, ...args: any): void;
21
21
  error(message: string, ...args: any): void;
22
22
  }
23
- type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
23
+ type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
24
24
  type ConfigEvaluation = {
25
25
  key: string;
26
26
  value: ConfigValueType;
@@ -39,9 +39,11 @@ type ConfigDirectorContext = {
39
39
  * The context's identifier. This should be a value that uniquely identifies the user or other
40
40
  * entity among contexts of the same {@link kind}.
41
41
  * In the case of anonymous users, you could generate a UUID or alternatively not provide
42
- * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
43
- * value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
44
- * could result in the context being assigned to a different percentile.
42
+ * the {@link id}. In a client SDK, ConfigDirector then derives an identifier from an ID the SDK
43
+ * stores for the app install or the website, so it stays the same until the app is uninstalled
44
+ * or the site's data is cleared. However, keep in mind that this value is used for segmenting
45
+ * contexts in percentage rollouts, and changes to the {@link id} could result in the context
46
+ * being assigned to a different percentile.
45
47
  */
46
48
  id?: string;
47
49
  /**
@@ -89,6 +91,45 @@ type NativeValue = boolean | number | string | NativeJsonValue[] | {
89
91
  type NativeValues = Record<string, NativeValue>;
90
92
  //#endregion
91
93
  //#region ../js-client-core/src/types.d.ts
94
+ /**
95
+ * A store for the values the client keeps on the device between launches. One provider instance
96
+ * serves one client: the provider decides where the entry lives, and the SDK owns the entry's
97
+ * format, which may change between SDK versions.
98
+ */
99
+ type CachingProvider = {
100
+ /**
101
+ * Returns the stored entry, or `null` or `undefined` when nothing is stored.
102
+ */
103
+ read(): string | null | undefined | Promise<string | null | undefined>;
104
+ /**
105
+ * Replaces the stored entry. The SDK never writes an entry larger than {@link sizeLimit}.
106
+ */
107
+ write(value: string): void | Promise<void>;
108
+ /**
109
+ * Removes the stored entry.
110
+ */
111
+ remove(): void | Promise<void>;
112
+ /**
113
+ * The largest entry, in UTF-8 bytes, the provider accepts. When the values received from
114
+ * ConfigDirector exceed it, the SDK removes the stored entry and keeps nothing on the device.
115
+ */
116
+ sizeLimit(): number;
117
+ };
118
+ /**
119
+ * Options for the values the client keeps on the device, served on the next launch of the same
120
+ * context until live values arrive. Ignored in `offline` mode.
121
+ */
122
+ type CachingOptions = {
123
+ /**
124
+ * Whether to keep the last values received on the device. Defaults to `true`.
125
+ */
126
+ enabled?: boolean;
127
+ /**
128
+ * The store for the values. Defaults to the platform's own store: `localStorage` in the
129
+ * browser, AsyncStorage on React Native.
130
+ */
131
+ provider?: CachingProvider;
132
+ };
92
133
  /**
93
134
  * One value an offline client serves for a config key. The config type follows from the value: a
94
135
  * boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
@@ -106,6 +147,7 @@ type ClientHooks = {
106
147
  contextUpdated?: HookHandler<"contextUpdated"> | HookHandler<"contextUpdated">[];
107
148
  configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
108
149
  connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
150
+ cachedValuesLoaded?: HookHandler<"cachedValuesLoaded"> | HookHandler<"cachedValuesLoaded">[];
109
151
  };
110
152
  type ClientConnectAction = "initialization" | "context update" | "network resume";
111
153
  type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
@@ -126,6 +168,7 @@ type ClientEvents = {
126
168
  connectionError: {
127
169
  error: Error;
128
170
  };
171
+ cachedValuesLoaded: Record<string, never>;
129
172
  };
130
173
  type WatchHandler<T extends ConfigValueType> = (message: T) => void;
131
174
  /**
@@ -247,5 +290,5 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
247
290
  dispose(): void;
248
291
  }
249
292
  //#endregion
250
- export { NativeJsonValue as a, ConfigDirectorContext as c, ConfigValueType as d, ConnectionMode as f, OfflineValues as i, ConfigDirectorLogger as l, ConfigDirectorClient as n, NativeValue as o, OfflineValue as r, NativeValues as s, ClientHooks as t, ConfigDirectorLoggingLevel as u };
251
- //# sourceMappingURL=types-DJSy0ELn.d.cts.map
293
+ export { OfflineValue as a, NativeValue as c, ConfigDirectorLogger as d, ConfigDirectorLoggingLevel as f, ConfigDirectorClient as i, NativeValues as l, ConnectionMode as m, CachingProvider as n, OfflineValues as o, ConfigValueType as p, ClientHooks as r, NativeJsonValue as s, CachingOptions as t, ConfigDirectorContext as u };
294
+ //# sourceMappingURL=types-CFBLmqUM.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-CFBLmqUM.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"],"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;AA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,CAAa,CAAA;EA9DvD;;;EAmEvB,UAAA;EA5BqE;;;;;;;EAqCrE,YAAA;EAdiE;;;;EAoBjE,aAAA,IAAiB,OAAA;EA9G2B;;;;;;EAsH5C,OAAA;AAAA"}
@@ -20,7 +20,7 @@ interface ConfigDirectorLogger {
20
20
  warn(message: string, ...args: any): void;
21
21
  error(message: string, ...args: any): void;
22
22
  }
23
- type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
23
+ type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
24
24
  type ConfigEvaluation = {
25
25
  key: string;
26
26
  value: ConfigValueType;
@@ -39,9 +39,11 @@ type ConfigDirectorContext = {
39
39
  * The context's identifier. This should be a value that uniquely identifies the user or other
40
40
  * entity among contexts of the same {@link kind}.
41
41
  * In the case of anonymous users, you could generate a UUID or alternatively not provide
42
- * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
43
- * value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
44
- * could result in the context being assigned to a different percentile.
42
+ * the {@link id}. In a client SDK, ConfigDirector then derives an identifier from an ID the SDK
43
+ * stores for the app install or the website, so it stays the same until the app is uninstalled
44
+ * or the site's data is cleared. However, keep in mind that this value is used for segmenting
45
+ * contexts in percentage rollouts, and changes to the {@link id} could result in the context
46
+ * being assigned to a different percentile.
45
47
  */
46
48
  id?: string;
47
49
  /**
@@ -89,6 +91,45 @@ type NativeValue = boolean | number | string | NativeJsonValue[] | {
89
91
  type NativeValues = Record<string, NativeValue>;
90
92
  //#endregion
91
93
  //#region ../js-client-core/src/types.d.ts
94
+ /**
95
+ * A store for the values the client keeps on the device between launches. One provider instance
96
+ * serves one client: the provider decides where the entry lives, and the SDK owns the entry's
97
+ * format, which may change between SDK versions.
98
+ */
99
+ type CachingProvider = {
100
+ /**
101
+ * Returns the stored entry, or `null` or `undefined` when nothing is stored.
102
+ */
103
+ read(): string | null | undefined | Promise<string | null | undefined>;
104
+ /**
105
+ * Replaces the stored entry. The SDK never writes an entry larger than {@link sizeLimit}.
106
+ */
107
+ write(value: string): void | Promise<void>;
108
+ /**
109
+ * Removes the stored entry.
110
+ */
111
+ remove(): void | Promise<void>;
112
+ /**
113
+ * The largest entry, in UTF-8 bytes, the provider accepts. When the values received from
114
+ * ConfigDirector exceed it, the SDK removes the stored entry and keeps nothing on the device.
115
+ */
116
+ sizeLimit(): number;
117
+ };
118
+ /**
119
+ * Options for the values the client keeps on the device, served on the next launch of the same
120
+ * context until live values arrive. Ignored in `offline` mode.
121
+ */
122
+ type CachingOptions = {
123
+ /**
124
+ * Whether to keep the last values received on the device. Defaults to `true`.
125
+ */
126
+ enabled?: boolean;
127
+ /**
128
+ * The store for the values. Defaults to the platform's own store: `localStorage` in the
129
+ * browser, AsyncStorage on React Native.
130
+ */
131
+ provider?: CachingProvider;
132
+ };
92
133
  /**
93
134
  * One value an offline client serves for a config key. The config type follows from the value: a
94
135
  * boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
@@ -106,6 +147,7 @@ type ClientHooks = {
106
147
  contextUpdated?: HookHandler<"contextUpdated"> | HookHandler<"contextUpdated">[];
107
148
  configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
108
149
  connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
150
+ cachedValuesLoaded?: HookHandler<"cachedValuesLoaded"> | HookHandler<"cachedValuesLoaded">[];
109
151
  };
110
152
  type ClientConnectAction = "initialization" | "context update" | "network resume";
111
153
  type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
@@ -126,6 +168,7 @@ type ClientEvents = {
126
168
  connectionError: {
127
169
  error: Error;
128
170
  };
171
+ cachedValuesLoaded: Record<string, never>;
129
172
  };
130
173
  type WatchHandler<T extends ConfigValueType> = (message: T) => void;
131
174
  /**
@@ -247,5 +290,5 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
247
290
  dispose(): void;
248
291
  }
249
292
  //#endregion
250
- export { NativeJsonValue as a, ConfigDirectorContext as c, ConfigValueType as d, ConnectionMode as f, OfflineValues as i, ConfigDirectorLogger as l, ConfigDirectorClient as n, NativeValue as o, OfflineValue as r, NativeValues as s, ClientHooks as t, ConfigDirectorLoggingLevel as u };
251
- //# sourceMappingURL=types-BfakBTXM.d.mts.map
293
+ export { OfflineValue as a, NativeValue as c, ConfigDirectorLogger as d, ConfigDirectorLoggingLevel as f, ConfigDirectorClient as i, NativeValues as l, ConnectionMode as m, CachingProvider as n, OfflineValues as o, ConfigValueType as p, ClientHooks as r, NativeJsonValue as s, CachingOptions as t, ConfigDirectorContext as u };
294
+ //# sourceMappingURL=types-CrgXfAWw.d.mts.map