@configdirector/client-sdk 0.1.4 → 0.1.6

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.
@@ -0,0 +1,2 @@
1
+ import{createEventSource as e}from"eventsource-client";var t=class{constructor(){this.handlerMap=new Map}on(e,t){let n=this.handlerMap.get(e);n?n.push(t):this.handlerMap.set(e,[t])}once(e,t){let n=this;function r(i){n.off(e,r),t.apply(n,i)}this.on(e,r)}off(e,t){let n=this.handlerMap.get(e);if(n)if(t){let e=n.indexOf(t);e>=0&&n.splice(e,1)}else this.handlerMap.set(e,[])}clear(){this.handlerMap.clear()}emit(e,t){let n=this.handlerMap.get(e);n&&n.slice().map(e=>e(t))}},n=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}};const i=e=>{if(e instanceof DOMException){if(e.name===`NotAllowedError`)return!0}else if(e instanceof TypeError)return!0;return!1};var a=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=new URL(`sse/v1`,e.baseUrl)}async connect(t,n){this.eventSource&&this.close();let r,i,a=async(e,t)=>{let n=await fetch(e,t);return r=n.status,n.ok||(i=await n.text()),n},o=new Promise((n,o)=>{this.eventSource=e({url:this.url,fetch:a,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey}),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{r&&this.isStatusFatal(r)?(this.close(),o(this.prepareFatalError(r,i))):(this.logger.debug(`[EventSourceTransport] Connected, status: %s`,r),n(this))},onScheduleReconnect:e=>{r&&this.isStatusFatal(r)?(this.close(),o(this.prepareFatalError(r,i))):this.logger.warn(`[EventSourceTransport] Scheduling reconnect in ${e.delay}. Response status: ${r}`)},onDisconnect:()=>{this.logger.debug(`[EventSourceTransport] Disconnected`)}})});return Promise.race([o,new Promise(e=>{setTimeout(()=>e(this),n)})])}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[EventSourceTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let r=e??0;return new n(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){this.eventSource?.close()}dispose(){this.close(),this.clear()}};const o=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},s=e=>e===`number`||e===`bigint`,c=(e,t)=>{let n=e.value,r=o(t);if(!n)return{parsedValue:t,requestedType:r,usedDefault:!0,reason:`value-missing`};if(typeof t==`string`)return{parsedValue:n,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&e.type===`boolean`){let e=l(n),i=typeof e==`boolean`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-boolean`}}if(s(typeof t)&&e.type===`integer`){let e=u(n),i=typeof e==`number`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-number`}}if(s(typeof t)&&(e.type===`float`||e.type===`enum`)){let e=d(n),i=typeof e==`number`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-number`}}return{parsedValue:n,requestedType:r,usedDefault:!1,reason:`found-match`}},l=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},u=e=>{if(!e)return;let t=Number.parseInt(e);if(!(isNaN(t)||!isFinite(t)))return t},d=e=>{if(!e)return;let t=Number.parseFloat(e);if(!(isNaN(t)||!isFinite(t)))return t},f={off:-1,error:0,warn:1,info:2,debug:3},p=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,{...e,fractionalSecondDigits:3})}catch{return new Intl.DateTimeFormat(void 0,e)}};var m=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=p()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){f[this.level]>=f[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},h=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const g=(e,t)=>new m(e??`warn`,t??new h);var _=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}))}},v=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}},y=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.url=new URL(`telemetry/v1`,e.baseUrl)}report({discreteEvents:e,aggregatedEvents:t,droppedEvents:n}){if(!this.executeRequests)return{success:!1,fatalError:!0};let r={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:t,droppedEvents:n};if(this.isReportEmpty(r))return{success:!0,fatalError:!1};let i=this.sendReport(r);return i.fatalError&&(this.executeRequests=!1),i}isReportEmpty(e){return this.isEventListEmpty(e.discreteEvents)&&this.isEventListEmpty(e.aggregatedEvents)&&this.isDroppedEventsEmpty(e.droppedEvents)}isDroppedEventsEmpty(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}isEventListEmpty(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}sendReport(e){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(e)),fatalError:!1}}catch(e){return this.logger.warn(`[EventReporter] Fatal error attempting to send telemetry data: ${e}. No more telemetry data will be sent.`),{success:!1,fatalError:!0}}}};const b=e=>x(new TextEncoder().encode(e)).toString(16).padStart(8,`0`),x=e=>{let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e[n],t>>>=0;return t};var S=class{constructor(e){this.evaluationEventQueue=new v,this.aggregator=new _,this.collectEvents=!0,this.logger=e.logger,this.reporter=new y(e),this.flushIntervalDelay=3e4,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),5e3);try{document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&this.flush()})}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(e))}sanitizeEvaluatedConfigEvent(e){return{key:e.key,type:e.type,defaultValue:this.sanitizeValue(e.defaultValue,e.type),requestedType:e.requestedType,evaluatedValue:this.sanitizeValue(e.evaluatedValue,e.type),usedDefault:e.usedDefault,evaluationReason:e.evaluationReason}}sanitizeValue(e,t){if(t===`json`)try{return b(JSON.stringify(e))}catch{return e.toString().slice(0,500)}return e.toString().slice(0,500)}flushAndScheduleNext(){this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay)}flush(){let e=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}close(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()}dispose(){this.close()}};const C=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(t,{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var w=class{constructor(e){this.options=e,this.eventEmitter=new t,this.fatalError=!1,this.options=e,this.logger=e.logger,this.url=new URL(`pull/v1`,e.baseUrl)}async connect(e,t){if(this.fatalError)return this.logger.warn(`[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`),this;try{let r=await C(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger);if(!r.ok)throw this.isStatusFatal(r.status)?(this.fatalError=!0,this.prepareFatalResponseStatusError(r.status,await r.text())):new n(`Connection failed with status: ${r.status}`,r.status);let i=JSON.parse(await r.text());return this.eventEmitter.emit(`configSetReceived`,i),this}catch(e){throw i(e)?(this.fatalError=!0,new n(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new n(`Failed to parse the response from the server: ${e}`):new n(`Connection failed with error: ${e}.`)}}prepareFatalResponseStatusError(e,t){let r=e??0;return new n(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){}dispose(){this.close(),this.clear()}};const T=new URL(`https://client-sdk-api.configdirector.com`);var E=class{constructor(e,n,r){this.handlersMap=new Map,this.eventEmitter=new t,this.ready=!1,this.logger=r?.logger??g(),this.timeout=r?.connection?.timeout??3e3;let i=this.parseUrl(r?.connection?.url)??T;this.streaming=r?.connection?.streaming!==!1;let o=this.streaming?a:w;this.usageEventCollector=new S({sdkKey:e,logger:this.logger,baseUrl:i}),this.transport=new o({clientSdkKey:e,baseUrl:i,metaContext:{...r?.metadata,sdkName:n.sdkName,sdkVersion:n.sdkVersion,userAgent:navigator?.userAgent},logger:this.logger}),this.transport.on(`configSetReceived`,e=>{this.readyResolve?.();let t=Object.keys(e.configs);!this.configSet||e.kind==`full`?(this.configSet=e,this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)):(this.configSet.configs={...this.configSet.configs,...e.configs},this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:t})})}async initialize(e){await this.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}async connectToTransport(e,t){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(()=>{this.ready=!0,this.eventEmitter.emit(`clientReady`,{action:t}),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`)});let n=new Date().getTime();await this.transport.connect(e??{},this.timeout),this.currentContext=e;let r=new Date().getTime()-n,i=this.timeout-r;if(i>0&&await Promise.race([this.readyPromise,new Promise(e=>{setTimeout(()=>e(),i)})]),!this.ready){let e=this.streaming?`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`:`Since the client was configured without streaming, configs may not update and always return the default value.`;this.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${this.timeout}ms. ${e}`)}}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}updateWatchers(e){Object.values(e).forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){this.handlersMap.get(e.key)?.forEach(t=>{let n=this.getValueFromConfigState(e.key,e,t.defaultValue);t.handler(n)})}watch(e,t,n){this.validateDefaultValue(t);let r=this.handlersMap.get(e),i={handler:n,defaultValue:t,requestedType:typeof t};return r?r.push(i):this.handlersMap.set(e,[i]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t){this.validateDefaultValue(t);let n=this.configSet?.configs[e];return this.getValueFromConfigState(e,n,t)}getValueFromConfigState(e,t,n){if(!t)return this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`),this.usageEventCollector.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:o(n),evaluatedValue:n,usedDefault:!0,evaluationReason:`config-state-missing`}),n;let r=c(t,n);return this.usageEventCollector.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:r.requestedType,evaluatedValue:r.parsedValue,usedDefault:r.usedDefault,evaluationReason:r.reason}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),r.parsedValue}parseUrl(e){if(e)try{return new URL(e)}catch(t){throw new r(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateDefaultValue(e){if(e==null)throw new r(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new r(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}close(){this.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),this.transport.close(),this.ready=!1}dispose(){this.clear(),this.close()}};const D=(e,t)=>new E(e,{sdkName:`js-client-sdk`,sdkVersion:`0.1.6`},t),O=(e,t)=>g(e,t);export{D as createClient,O as createConsoleLogger};
2
+ //# sourceMappingURL=configdirector-client.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@configdirector/client-sdk",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Javascript client SDK for ConfigDirector. ConfigDirector is a remote configuration and feature flag service.",
5
5
  "license": "MIT",
6
6
  "author": "ConfigDirector",
@@ -23,12 +23,12 @@
23
23
  "exports": {
24
24
  ".": {
25
25
  "require": {
26
- "types": "./dist/configdirector-client.d.ts",
27
- "default": "./dist/configdirector-client.cjs.js"
26
+ "types": "./dist/configdirector-client.d.cts",
27
+ "default": "./dist/configdirector-client.cjs"
28
28
  },
29
29
  "default": {
30
- "types": "./dist/configdirector-client.d.ts",
31
- "default": "./dist/configdirector-client.es.js"
30
+ "types": "./dist/configdirector-client.d.mts",
31
+ "default": "./dist/configdirector-client.mjs"
32
32
  }
33
33
  }
34
34
  },
@@ -36,18 +36,18 @@
36
36
  "dist/*.js",
37
37
  "dist/*-client.d.ts"
38
38
  ],
39
- "types": "dist/configdirector-client.d.ts",
40
- "browser": "dist/configdirector-client.es.js",
41
- "module": "dist/configdirector-client.es.js",
39
+ "types": "dist/configdirector-client.d.mts",
40
+ "browser": "dist/configdirector-client.mjs",
41
+ "module": "dist/configdirector-client.mjs",
42
42
  "scripts": {
43
- "build": "rollup -c rollup.config.js",
43
+ "build": "tsdown",
44
44
  "clean": "rimraf dist/**",
45
45
  "lint": "eslint .",
46
46
  "test": "vitest",
47
47
  "ci:test": "vitest run"
48
48
  },
49
49
  "dependencies": {
50
- "@configdirector/client-core": "workspace:^"
50
+ "eventsource-client": "^1.2.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@eslint/js": "^9.39.2",
@@ -65,9 +65,11 @@
65
65
  "rimraf": "^6.1.2",
66
66
  "rollup": "^4.57.1",
67
67
  "rollup-plugin-dts": "^6.3.0",
68
+ "tsdown": "^0.21.0-beta.2",
68
69
  "tslib": "^2.8.1",
69
70
  "typescript": "^5.9.3",
70
71
  "typescript-eslint": "^8.54.0",
72
+ "vite-tsconfig-paths": "^6.1.1",
71
73
  "vitest": "^4.0.18"
72
74
  }
73
75
  }
@@ -1,2 +0,0 @@
1
- "use strict";var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},n.apply(this,arguments)};function r(t,e,n,r){return new(n||(n=Promise))(function(e,o){function i(t){try{s(r.next(t))}catch(t){o(t)}}function a(t){try{s(r.throw(t))}catch(t){o(t)}}function s(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(t){t(r)})).then(i,a)}s((r=r.apply(t,[])).next())})}function o(t,e){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(u){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}function i(t,e,n){if(2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var a=function(){function t(){this.handlerMap=new Map}return t.prototype.on=function(t,e){var n=this.handlerMap.get(t);n?n.push(e):this.handlerMap.set(t,[e])},t.prototype.once=function(t,e){var n=this;this.on(t,function r(o){n.off(t,r),e.apply(n,o)})},t.prototype.off=function(t,e){var n=this.handlerMap.get(t);if(n)if(e){var r=n.indexOf(e);r>=0&&n.splice(r,1)}else this.handlerMap.set(t,[])},t.prototype.clear=function(){this.handlerMap.clear()},t.prototype.emit=function(t,e){var n=this.handlerMap.get(t);n&&n.slice().map(function(t){return t(e)})},t}();class s extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}function u(t){}function c(t){if("function"==typeof t)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=u,onError:n=u,onRetry:r=u,onComment:o}=t;let i,a="",c=!0,l="",f="";function d(t){if(""===t)return l.length>0&&e({id:i,event:f||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),i=void 0,l="",void(f="");if(t.startsWith(":"))return void(o&&o(t.slice(t.startsWith(": ")?2:1)));const n=t.indexOf(":");if(-1!==n){const e=t.slice(0,n),r=" "===t[n+1]?2:1;return void p(e,t.slice(n+r),t)}p(t,"",t)}function p(t,e,o){switch(t){case"event":f=e;break;case"data":l=`${l}${e}\n`;break;case"id":i=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?r(parseInt(e,10)):n(new s(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:o}));break;default:n(new s(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:o}))}}return{feed:function(t){const e=c?t.replace(/^\xEF\xBB\xBF/,""):t,[n,r]=function(t){const e=[];let n="",r=0;for(;r<t.length;){const o=t.indexOf("\r",r),i=t.indexOf("\n",r);let a=-1;if(-1!==o&&-1!==i?a=Math.min(o,i):-1!==o?a=o===t.length-1?-1:o:-1!==i&&(a=i),-1===a){n=t.slice(r);break}{const n=t.slice(r,a);e.push(n),r=a+1,"\r"===t[r-1]&&"\n"===t[r]&&r++}}return[e,n]}(`${a}${e}`);for(const t of n)d(t);a=r,c=!1},reset:function(t={}){a&&t.consume&&d(a),c=!0,i=void 0,l="",f="",a=""}}}const l="connecting",f="closed",d=()=>{};function p(t,{getStream:e}){const n="string"==typeof t||t instanceof URL?{url:t}:t,{onMessage:r,onComment:o=d,onConnect:i=d,onDisconnect:a=d,onScheduleReconnect:s=d}=n,{fetch:u,url:p,initialLastEventId:h}=function(t){const e=t.fetch||globalThis.fetch;if(!function(t){return"function"==typeof t}(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if("function"!=typeof AbortController)throw new Error("Missing AbortController implementation");const{url:n,initialLastEventId:r}=t;if("string"!=typeof n&&!(n instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if("string"!=typeof r&&void 0!==r)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:n,initialLastEventId:r}}(n),v={...n.headers},g=[],y=r?[r]:[],m=c({onEvent:function(t){var e;"string"==typeof t.id&&(T=t.id),e=t,y.forEach(t=>t(e))},onRetry:function(t){S=t},onComment:o});let w,b,E=p.toString(),C=new AbortController,T=h,S=2e3,k=f;return x(),{close:D,connect:x,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:function(){const t=[],e=[],n=function(n){const r=t.shift();r?r({value:n,done:!1}):e.push(n)};function r(){for(y.splice(y.indexOf(n),1);t.shift(););for(;e.shift(););}return g.push(function(){const e=t.shift();e&&(e({done:!0,value:void 0}),r())}),y.push(n),{next(){return k===f?this.return():new Promise(n=>{const r=e.shift();r?n({value:r,done:!1}):t.push(n)})},return:()=>(r(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r(),Promise.reject(t)),[Symbol.asyncIterator](){return this}}},get lastEventId(){return T},get url(){return E},get readyState(){return k}};function x(){w||(k=l,C=new AbortController,w=u(p,function(){const{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s}=n;return{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s,headers:{Accept:"text/event-stream",...v,...T?{"Last-Event-ID":T}:void 0},cache:"no-store",signal:C.signal}}()).then(O).catch(t=>{w=null,"AbortError"!==t.name&&"aborted"!==t.type&&!C.signal.aborted&&R()}))}function D(){k=f,C.abort(),m.reset(),clearTimeout(b),g.forEach(t=>t())}function R(){s({delay:S}),!C.signal.aborted&&(k=l,b=setTimeout(x,S))}async function O(t){i(),m.reset();const{body:n,redirected:r,status:o}=t;if(204===o)return a(),void D();if(!n)throw new Error("Missing response body");r&&(E=t.url);const s=e(n),u=new TextDecoder,c=s.getReader();let l=!0;k="open";do{const{done:t,value:e}=await c.read();e&&m.feed(u.decode(e,{stream:!t})),t&&(l=!1,w=null,m.reset(),R(),a())}while(l)}}const h={getStream:function(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}};var v=function(t){function n(e,r){var o=t.call(this,e)||this;return o.name="ConfigDirectorConnectionError",o.status=r,Object.setPrototypeOf(o,n.prototype),o}return e(n,t),n}(Error),g=function(t){function n(e){var r=t.call(this,e)||this;return r.name="ConfigDirectorValidationError",Object.setPrototypeOf(r,n.prototype),r}return e(n,t),n}(Error),y=function(){function t(t){this.options=t,this.eventEmitter=new a,this.options=t,this.logger=t.logger,this.url=new URL("sse/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,0,void 0,function(){var n,i,a,s,u=this;return o(this,function(c){return this.eventSource&&this.close(),n=void 0,i=void 0,a=function(t,e){return r(u,0,void 0,function(){var r;return o(this,function(o){switch(o.label){case 0:return[4,fetch(t,e)];case 1:return r=o.sent(),n=r.status,r.ok?[3,3]:[4,r.text()];case 2:i=o.sent(),o.label=3;case 3:return[2,r]}})})},s=new Promise(function(e,r){var o;u.eventSource=(o={url:u.url,fetch:a,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:u.options.metaContext,clientSdkKey:u.options.clientSdkKey}),onMessage:function(t){var e=t.data;u.dispatchMessage(e)},onConnect:function(){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):(u.logger.debug("[EventSourceTransport] Connected, status: %s",n),e(u))},onScheduleReconnect:function(t){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):u.logger.warn("[EventSourceTransport] Scheduling reconnect in ".concat(t.delay,". Response status: ").concat(n))},onDisconnect:function(){u.logger.debug("[EventSourceTransport] Disconnected")}},p(o,h))}),[2,Promise.race([s,new Promise(function(t){setTimeout(function(){return t(u)},e)})])]})})},t.prototype.dispatchMessage=function(t){try{var e=JSON.parse(t);this.eventEmitter.emit("configSetReceived",e)}catch(t){this.logger.error("[EventSourceTransport] Error parsing and dispatching config data update: ",t)}},t.prototype.prepareFatalError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, will not attempt to reconnect.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){var t;null===(t=this.eventSource)||void 0===t||t.close()},t.prototype.dispose=function(){this.close(),this.clear()},t}(),m=function(t){var e,n,r=typeof t;if("object"===r)try{return null!==(n=null===(e=t.constructor)||void 0===e?void 0:e.name)&&void 0!==n?n:r}catch(t){return r}else if("function"===r)try{var o=t.name;return o?"function: ".concat(o):r}catch(t){return r}return r},w=function(t){return"number"===t||"bigint"===t},b=function(t){if(t){var e=Number.parseInt(t);if(!isNaN(e)&&isFinite(e))return e}},E=function(t){if(t){var e=Number.parseFloat(t);if(!isNaN(e)&&isFinite(e))return e}},C={off:-1,error:0,warn:1,info:2,debug:3},T=function(){function t(t,e){this.level=t,this.decorator=e,this.level=t,this.decorator=e,this.dateFormatter=function(){var t={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short"};try{return new Intl.DateTimeFormat(void 0,n(n({},t),{fractionalSecondDigits:3}))}catch(e){return new Intl.DateTimeFormat(void 0,t)}}()}return t.prototype.debug=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.debug,"debug",t],e,!1))},t.prototype.info=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.info,"info",t],e,!1))},t.prototype.warn=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.warn,"warn",t],e,!1))},t.prototype.error=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.error,"error",t],e,!1))},t.prototype.log=function(t,e,n){for(var r,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];C[this.level]>=C[e]&&t.apply(void 0,i(["[".concat(this.dateFormatter.format(new Date),"] ").concat(null===(r=this.decorator)||void 0===r?void 0:r.decorateMessage(n))],o,!1))},t}(),S=function(){function t(){}return t.prototype.decorateMessage=function(t){return"[ConfigDirector:js-client-sdk] ".concat(t)},t}(),k=function(t,e){return new T(null!=t?t:"warn",null!=e?e:new S)},x=function(){function t(){}return t.prototype.aggregate=function(t){var e;if(0==t.events.length)return[];for(var n=new Map,r=0,o=t.events;r<o.length;r++){var i=o[r],a=JSON.stringify(i),s=(null===(e=n.get(a))||void 0===e?void 0:e.count)||0;n.set(a,{event:i,count:s+1})}return Array.from(n).map(function(e){var n=e[1];return{startTime:t.startTime,endTime:t.endTime,count:n.count,event:n.event}})},t}(),D=function(){function t(t){this._events=[],this._droppedEventCount=0,this.limit=null!=t?t:1e3}return Object.defineProperty(t.prototype,"events",{get:function(){return this._events},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reachedLimit",{get:function(){return this._events.length>=this.limit},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"droppedEventCount",{get:function(){return this._droppedEventCount},enumerable:!1,configurable:!0}),t.prototype.push=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.startTime||(this.startTime=new Date);var r=Math.max(0,e.length-this.limit),o=e.slice(r,e.length);if(this._droppedEventCount+=r,this._events.length+o.length>this.limit){var i=this._events.length+o.length-this.limit;this._events.splice(0,i),this._droppedEventCount+=i}return(t=this._events).push.apply(t,o)},t.prototype.takeSnapshot=function(){var t,e=new Date,n=null!==(t=this.startTime)&&void 0!==t?t:e,r=this._events.splice(0),o=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:n,endTime:e,events:r,droppedCount:o}},t.prototype.clear=function(){this._events=[],this.startTime=void 0,this._droppedEventCount=0},t}(),R=function(){function t(t){this.executeRequests=!0,this.sdkKey=t.sdkKey,this.logger=t.logger,this.url=new URL("telemetry/v1",t.baseUrl)}return t.prototype.report=function(t){var e=t.discreteEvents,n=t.aggregatedEvents,r=t.droppedEvents;if(!this.executeRequests)return{success:!1,fatalError:!0};var o={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(o))return{success:!0,fatalError:!1};var i=this.sendReport(o);return i.fatalError&&(this.executeRequests=!1),i},t.prototype.isReportEmpty=function(t){return this.isEventListEmpty(t.discreteEvents)&&this.isEventListEmpty(t.aggregatedEvents)&&this.isDroppedEventsEmpty(t.droppedEvents)},t.prototype.isDroppedEventsEmpty=function(t){var e;if(!t)return!0;var n=Object.keys(t);if(0==n.length)return!0;for(var r=0,o=n;r<o.length;r++)if((null!==(e=t[o[r]])&&void 0!==e?e:0)>0)return!1;return!0},t.prototype.isEventListEmpty=function(t){var e,n,r=Object.keys(t);if(0==r.length)return!0;for(var o=0,i=r;o<i.length;o++)if((null!==(n=null===(e=t[i[o]])||void 0===e?void 0:e.length)&&void 0!==n?n:0)>0)return!1;return!0},t.prototype.sendReport=function(t){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(t)),fatalError:!1}}catch(t){return this.logger.warn("[EventReporter] Fatal error attempting to send telemetry data: ".concat(t,". No more telemetry data will be sent.")),{success:!1,fatalError:!0}}},t}(),O=function(){function t(t){var e=this;this.evaluationEventQueue=new D,this.aggregator=new x,this.collectEvents=!0,this.logger=t.logger,this.reporter=new R(t),this.flushIntervalDelay=3e4,this.flushTimeout=setTimeout(function(){return e.flushAndScheduleNext()},5e3);try{document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.flush()})}catch(t){this.logger.warn("[TelemetryEventCollector] Could not configure 'visibilitychange' listener: ",t)}}return t.prototype.evaluatedConfig=function(t){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))},t.prototype.sanitizeEvaluatedConfigEvent=function(t){return{key:t.key,type:t.type,defaultValue:this.sanitizeValue(t.defaultValue,t.type),requestedType:t.requestedType,evaluatedValue:this.sanitizeValue(t.evaluatedValue,t.type),usedDefault:t.usedDefault,evaluationReason:t.evaluationReason}},t.prototype.sanitizeValue=function(t,e){if("json"===e)try{return n=JSON.stringify(t),function(t){for(var e=5381,n=0;n<t.length;n++)e=(e<<5)+e+t[n],e>>>=0;return e}((new TextEncoder).encode(n)).toString(16).padStart(8,"0")}catch(e){return t.toString().slice(0,500)}var n;return t.toString().slice(0,500)},t.prototype.flushAndScheduleNext=function(){var t=this;this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn("[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.")):this.flushTimeout=setTimeout(function(){return t.flushAndScheduleNext()},this.flushIntervalDelay)},t.prototype.flush=function(){var t=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(t)},droppedEvents:{evaluatedConfig:t.droppedCount}})},t.prototype.close=function(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()},t.prototype.dispose=function(){this.close()},t}(),V=function(t,e,i,a){return r(void 0,0,void 0,function(){var r,s,u,c;return o(this,function(o){switch(o.label){case 0:r=new AbortController,s=setTimeout(function(){a.debug("[fetchWithTimeout] Reached timeout, aborting request"),r.abort()},t),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,fetch(e,n(n({},i),{signal:r.signal}))];case 2:return u=o.sent(),clearTimeout(s),[2,u];case 3:throw c=o.sent(),a.warn("[fetchWithTimeout] Fetch error: ",c),clearTimeout(s),c;case 4:return[2]}})})},M=function(){function t(t){this.options=t,this.eventEmitter=new a,this.fatalError=!1,this.options=t,this.logger=t.logger,this.url=new URL("pull/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,0,void 0,function(){var n,r,i,a,s,u,c;return o(this,function(o){switch(o.label){case 0:if(this.fatalError)return this.logger.warn("[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect."),[2,this];o.label=1;case 1:return o.trys.push([1,7,,8]),[4,V(e,this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger)];case 2:return(n=o.sent()).ok?[3,5]:this.isStatusFatal(n.status)?(this.fatalError=!0,r=this.prepareFatalResponseStatusError,i=[n.status],[4,n.text()]):[3,4];case 3:throw r.apply(this,i.concat([o.sent()]));case 4:throw new v("Connection failed with status: ".concat(n.status),n.status);case 5:return u=(s=JSON).parse,[4,n.text()];case 6:return a=u.apply(s,[o.sent()]),this.eventEmitter.emit("configSetReceived",a),[2,this];case 7:throw function(t){if(t instanceof DOMException){if("NotAllowedError"===t.name)return!0}else if(t instanceof TypeError)return!0;return!1}(c=o.sent())?(this.fatalError=!0,new v("Connection failed with fatal error: ".concat(c,". This is an unrecoverable error, retry attempts will be ignored."))):c instanceof SyntaxError?new v("Failed to parse the response from the server: ".concat(c)):new v("Connection failed with error: ".concat(c,"."));case 8:return[2]}})})},t.prototype.prepareFatalResponseStatusError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, retry attempts will be ignored.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){},t.prototype.dispose=function(){this.close(),this.clear()},t}(),P=new URL("https://client-sdk-api.configdirector.com"),F=function(){function t(t,e,r){var o,i,s,u,c,l,f=this;this.handlersMap=new Map,this.eventEmitter=new a,this.ready=!1,this.logger=null!==(o=null==r?void 0:r.logger)&&void 0!==o?o:k(),this.timeout=null!==(s=null===(i=null==r?void 0:r.connection)||void 0===i?void 0:i.timeout)&&void 0!==s?s:3e3;var d=null!==(c=this.parseUrl(null===(u=null==r?void 0:r.connection)||void 0===u?void 0:u.url))&&void 0!==c?c:P;this.streaming=!1!==(null===(l=null==r?void 0:r.connection)||void 0===l?void 0:l.streaming);var p=this.streaming?y:M;this.usageEventCollector=new O({sdkKey:t,logger:this.logger,baseUrl:d}),this.transport=new p({clientSdkKey:t,baseUrl:d,metaContext:n(n({},null==r?void 0:r.metadata),{sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:null===navigator||void 0===navigator?void 0:navigator.userAgent}),logger:this.logger}),this.transport.on("configSetReceived",function(t){var e;null===(e=f.readyResolve)||void 0===e||e.call(f);var r=Object.keys(t.configs);f.configSet&&"full"!=t.kind?(f.configSet.configs=n(n({},f.configSet.configs),t.configs),f.eventEmitter.emit("configsUpdated",{keys:r}),f.updateWatchers(t.configs)):(f.configSet=t,f.eventEmitter.emit("configsUpdated",{keys:r}),f.updateWatchers(t.configs)),f.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:",{keys:r})})}return t.prototype.initialize=function(t){return r(this,0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"initialization")];case 1:return e.sent(),[2]}})})},t.prototype.updateContext=function(t){return r(this,0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"context update")];case 1:return e.sent(),[2]}})})},t.prototype.connectToTransport=function(t,e){return r(this,0,void 0,function(){var n,r,i,a,s,u=this;return o(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),this.ready=!1,this.readyPromise=new Promise(function(t){u.readyResolve=t}).then(function(){u.ready=!0,u.eventEmitter.emit("clientReady",{action:e}),u.logger.debug("[ConfigDirectorClient] Received initial payload from the server, client is ready")}),n=(new Date).getTime(),[4,this.transport.connect(null!=t?t:{},this.timeout)];case 1:return o.sent(),this.currentContext=t,r=(new Date).getTime()-n,(i=this.timeout-r)>0?[4,Promise.race([this.readyPromise,new Promise(function(t){setTimeout(function(){return t()},i)})])]:[3,3];case 2:o.sent(),o.label=3;case 3:return this.ready||(a=this.streaming?"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.":"Since the client was configured without streaming, configs may not update and always return the default value.",this.logger.warn("[ConfigDirectorClient] Timed out waiting for ".concat(e," after ").concat(this.timeout,"ms. ").concat(a))),[3,5];case 4:return s=o.sent(),this.logger.error("[ConfigDirectorClient] An error occurred during ".concat(e,": "),s),[3,5];case 5:return[2]}})})},t.prototype.updateWatchers=function(t){var e=this;Object.values(t).forEach(function(t){return e.updateWatchersForConfig(t)})},t.prototype.updateWatchersForConfig=function(t){var e,n=this;null===(e=this.handlersMap.get(t.key))||void 0===e||e.forEach(function(e){var r=n.getValueFromConfigState(t.key,t,e.defaultValue);e.handler(r)})},t.prototype.watch=function(t,e,n){var r=this;this.validateDefaultValue(e);var o=this.handlersMap.get(t),i={handler:n,defaultValue:e,requestedType:typeof e};return o?o.push(i):this.handlersMap.set(t,[i]),function(){return r.unwatch(t,n)}},t.prototype.unwatch=function(t,e){var n=this.handlersMap.get(t);if(n)if(e){var r=n.findIndex(function(t){return t.handler==e});r>=0&&(null==n||n.splice(r,1))}else n.splice(0)},t.prototype.getValue=function(t,e){var n;this.validateDefaultValue(e);var r=null===(n=this.configSet)||void 0===n?void 0:n.configs[t];return this.getValueFromConfigState(t,r,e)},t.prototype.getValueFromConfigState=function(t,e,n){var r,o;if(!e)return this.logger.debug("[ConfigDirectorClient] No config state found for '".concat(t,"', returning default value '").concat(n,"'")),this.usageEventCollector.evaluatedConfig({contextId:null===(r=this.currentContext)||void 0===r?void 0:r.id,key:t,defaultValue:n,requestedType:m(n),evaluatedValue:n,usedDefault:!0,evaluationReason:"config-state-missing"}),n;var i=function(t,e){var n,r,o=t.value,i=m(e);if(!o)return{parsedValue:e,requestedType:i,usedDefault:!0,reason:"value-missing"};if("string"==typeof e)return{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"};if("boolean"==typeof e&&"boolean"===t.type){var a=function(t){if(t){var e=t.toLowerCase();if("true"==e||"false"==e)return"true"===e}}(o),s="boolean"==typeof a;return{parsedValue:s?a:e,requestedType:i,usedDefault:!s,reason:s?"found-match":"invalid-boolean"}}return w(typeof e)&&"integer"===t.type?{parsedValue:(r="number"==typeof(n=b(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}:!w(typeof e)||"float"!==t.type&&"enum"!==t.type?{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"}:{parsedValue:(r="number"==typeof(n=E(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}}(e,n);return this.usageEventCollector.evaluatedConfig({contextId:null===(o=this.currentContext)||void 0===o?void 0:o.id,key:t,defaultValue:n,requestedType:i.requestedType,evaluatedValue:i.parsedValue,usedDefault:i.usedDefault,evaluationReason:i.reason}),this.logger.debug("[ConfigDirectorClient] Evaluated '".concat(t,"' to '").concat(i.parsedValue,"'")),i.parsedValue},t.prototype.parseUrl=function(t){if(t)try{return new URL(t)}catch(e){throw new g("Invalid base URL '".concat(t,"'. Parsing failed: ").concat(e))}},t.prototype.validateDefaultValue=function(t){if(null==t)throw new g("Invalid default value. The default value for a config must be defined and non-null.");if("function"==typeof t)throw new g("Invalid default value. The default value for a config cannot be a function.")},Object.defineProperty(t.prototype,"isReady",{get:function(){return this.ready},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.logger.debug("[ConfigDirectorClient] clear() has been called, removing all observers"),this.eventEmitter.clear(),this.handlersMap.clear()},t.prototype.unwatchAll=function(){this.handlersMap.clear()},t.prototype.close=function(){this.logger.debug("[ConfigDirectorClient] close() has been called, closing connection to server"),this.transport.close(),this.ready=!1},t.prototype.dispose=function(){this.clear(),this.close()},t}();exports.createClient=function(t,e){return new F(t,{sdkName:"js-client-sdk",sdkVersion:"0.1.4"},e)},exports.createConsoleLogger=function(t,e){return k(t,e)};
2
- //# sourceMappingURL=configdirector-client.cjs.js.map
@@ -1,208 +0,0 @@
1
- type EventType = string | symbol;
2
- type EventsRecord = Record<EventType, any>;
3
- type Handler<TEventsRecord extends EventsRecord, TKey extends keyof TEventsRecord> = (payload: TEventsRecord[TKey]) => void;
4
- interface EventProvider<TEventsRecord extends EventsRecord> {
5
- on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>): void;
6
- off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>): void;
7
- clear(): void;
8
- }
9
-
10
- type ConfigEnumLikeType = {
11
- [key: string]: string | number;
12
- };
13
- type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
14
- type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
15
- interface ConfigDirectorLogger {
16
- debug(message: string, ...args: any): void;
17
- info(message: string, ...args: any): void;
18
- warn(message: string, ...args: any): void;
19
- error(message: string, ...args: any): void;
20
- }
21
- interface ConfigDirectorLogMessageDecorator {
22
- decorateMessage(message: string): string;
23
- }
24
- /**
25
- * The user's context to be sent to ConfigDirector. This context will be used for targeting
26
- * rules evaluation.
27
- */
28
- type ConfigDirectorContext = {
29
- /**
30
- * The user's identifier. This should be a value that uniquely identifies an application
31
- * user.
32
- * In the case of anonymous users, you could generate a UUID or alternatively not provide
33
- * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
34
- * value is used for segmenting users in percentage rollouts, and changes to the {@link id}
35
- * could result in the user being assigned to a different percentile.
36
- */
37
- id?: string;
38
- /**
39
- * The user's display name. This will be shown in the ConfigDirector dashboard and may be
40
- * used for targeting rules.
41
- */
42
- name?: string;
43
- /**
44
- * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
45
- * dashboard and may be used for targeting rules.
46
- */
47
- traits?: {
48
- [key: string]: unknown;
49
- };
50
- };
51
- /**
52
- * Configuration options for the {@link ConfigDirectorClient}
53
- */
54
- type ConfigDirectorClientOptions = {
55
- /**
56
- * Application metadata that remains constant through the lifetime of the connection
57
- */
58
- metadata?: {
59
- appVersion?: string;
60
- appName?: string;
61
- };
62
- /**
63
- * Connection options
64
- */
65
- connection?: {
66
- /**
67
- * Whether to open a streaming connection or use a one-time pull of configuration state.
68
- * If set to true, the streaming connection will remain open and receive updates whenever
69
- * config state is updated on the ConfigDirector dashboard.
70
- * When set to false, there will be an initial request to retrieve config state during
71
- * initialization, and an additional request whenever {@link ConfigDirectorClient.updateContext}
72
- * is called. But not updates will be received after those requests.
73
- *
74
- * Defaults to true (streaming connection)
75
- */
76
- streaming?: boolean;
77
- /**
78
- * The timeout, in milliseconds, to be used in initialization and when updating the context.
79
- * If streaming is enabled, the operation (initialization or context update) may still succeed
80
- * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
81
- * If streaming is disabled, if the operation times out, it will not be retried.
82
- */
83
- timeout?: number;
84
- /**
85
- * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
86
- * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
87
- * a proxy for the client SDK.
88
- */
89
- url?: string;
90
- };
91
- /**
92
- * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
93
- * logger set to 'warn' level.
94
- *
95
- * The log level of the default logger can be adjusted by creating a default logger with the desired
96
- * level and providing it in this property:
97
- * @example
98
- * import { createClient, createConsoleLogger } from "@configdirector/client-sdk";
99
- * const client = createClient(
100
- * "YOUR-SDK-KEY",
101
- * { logger: createConsoleLogger("debug") },
102
- * );
103
- */
104
- logger?: ConfigDirectorLogger;
105
- };
106
- type ClientConnectAction = "initialization" | "context update";
107
- type ClientEvents = {
108
- configsUpdated: {
109
- keys: string[];
110
- };
111
- clientReady: {
112
- action: ClientConnectAction;
113
- };
114
- };
115
- type WatchHandler<T extends ConfigValueType> = (message: T) => void;
116
- /**
117
- * The ConfigDirector SDK client object.
118
- *
119
- * Applications should create a single instance of `ConfigDirectorClient`, and call
120
- * {@link initialize} during application initialization.
121
- *
122
- * After initialization, to update the user's context, so that targeting rules are evaluated
123
- * with the updated context, call {@link updateContext}.
124
- */
125
- interface ConfigDirectorClient extends EventProvider<ClientEvents> {
126
- /**
127
- * Initializes the connection to ConfigDirector to retrieve config evaluations. Until
128
- * initialization is successful, all flags will return their default value provided to
129
- * {@link watch} or {@link getValue}.
130
- *
131
- * If the connection fails or is interrupted with a transient error (network error,
132
- * internal server error, etc) the client will continue to attempt to connect. However,
133
- * if the connection fails with a persistent error, like an invalid SDK key, the client will
134
- * not attempt to re-connect and an error will be logged to the console or the provided
135
- * logger.
136
- *
137
- * @param context The current user's context to be used for evaluating targeting rules (optional).
138
- */
139
- initialize(context?: ConfigDirectorContext): Promise<void>;
140
- /**
141
- * Updates the user's context and re-evaluates all config and flag values based on the new context.
142
- *
143
- * @param context The current user's context to be used for evaluating targeting rules (required).
144
- */
145
- updateContext(context: ConfigDirectorContext): Promise<void>;
146
- /**
147
- * Returns whether or not the client is ready after calling {@link initialize} or {@link updateContext}
148
- *
149
- * The definition of ready is that the connection to the server was successful, and config state
150
- * was received.
151
- */
152
- get isReady(): boolean;
153
- /**
154
- * Evaluates a config and returns its value based on the current context and targeting rules
155
- *
156
- * @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
157
- * @param configKey The config key to evaluate
158
- * @param defaultValue The default value to be returned if the config state is unavailable. For
159
- * example, if the client cannot connect to the server due to network conditions, or if getValue
160
- * is called before initialization is done.
161
- */
162
- getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
163
- /**
164
- * Watches for changes to a a config evaluation value. Whenever the config value changes, the
165
- * provided callback function will be called with the new value. Changes can happen due to updates
166
- * to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
167
- *
168
- * @returns An 'unwatch' function that can be called to remove the subscriber
169
- *
170
- * @param configKey The config key to watch
171
- * @param defaultValue The default value to be referenced if the config state is unavailable
172
- * @param callback The callback function to be called whenever the config value is updated
173
- */
174
- watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>): () => void;
175
- /**
176
- * Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
177
- * is provided.
178
- *
179
- * @param configKey The config key to remove subscribers from
180
- * @param callback The subscriber to be removed. If not provided, all subscribers are removed for
181
- * the given `configKey`.
182
- */
183
- unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
184
- /**
185
- * Removes all subscribers from all config keys
186
- */
187
- unwatchAll(): void;
188
- /**
189
- * Disposes of the client. All connections are closed, and all event and config key subscribers
190
- * are removed.
191
- *
192
- * Intended to be called when your application shuts down
193
- */
194
- dispose(): void;
195
- }
196
-
197
- declare class ConfigDirectorConnectionError extends Error {
198
- readonly name: string;
199
- readonly status?: number;
200
- constructor(message: string, status?: number);
201
- }
202
- declare class ConfigDirectorValidationError extends Error {
203
- readonly name: string;
204
- constructor(message: string);
205
- }
206
-
207
- export { ConfigDirectorConnectionError, ConfigDirectorValidationError };
208
- export type { ConfigDirectorClient, ConfigDirectorClientOptions, ConfigDirectorContext, ConfigDirectorLogMessageDecorator, ConfigDirectorLogger, ConfigDirectorLoggingLevel, ConfigValueType };
@@ -1,2 +0,0 @@
1
- var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},n.apply(this,arguments)};function r(t,e,n,r){return new(n||(n=Promise))(function(e,o){function i(t){try{s(r.next(t))}catch(t){o(t)}}function a(t){try{s(r.throw(t))}catch(t){o(t)}}function s(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(t){t(r)})).then(i,a)}s((r=r.apply(t,[])).next())})}function o(t,e){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(u){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}function i(t,e,n){if(2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var a=function(){function t(){this.handlerMap=new Map}return t.prototype.on=function(t,e){var n=this.handlerMap.get(t);n?n.push(e):this.handlerMap.set(t,[e])},t.prototype.once=function(t,e){var n=this;this.on(t,function r(o){n.off(t,r),e.apply(n,o)})},t.prototype.off=function(t,e){var n=this.handlerMap.get(t);if(n)if(e){var r=n.indexOf(e);r>=0&&n.splice(r,1)}else this.handlerMap.set(t,[])},t.prototype.clear=function(){this.handlerMap.clear()},t.prototype.emit=function(t,e){var n=this.handlerMap.get(t);n&&n.slice().map(function(t){return t(e)})},t}();class s extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}function u(t){}function c(t){if("function"==typeof t)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=u,onError:n=u,onRetry:r=u,onComment:o}=t;let i,a="",c=!0,l="",f="";function d(t){if(""===t)return l.length>0&&e({id:i,event:f||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),i=void 0,l="",void(f="");if(t.startsWith(":"))return void(o&&o(t.slice(t.startsWith(": ")?2:1)));const n=t.indexOf(":");if(-1!==n){const e=t.slice(0,n),r=" "===t[n+1]?2:1;return void p(e,t.slice(n+r),t)}p(t,"",t)}function p(t,e,o){switch(t){case"event":f=e;break;case"data":l=`${l}${e}\n`;break;case"id":i=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?r(parseInt(e,10)):n(new s(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:o}));break;default:n(new s(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:o}))}}return{feed:function(t){const e=c?t.replace(/^\xEF\xBB\xBF/,""):t,[n,r]=function(t){const e=[];let n="",r=0;for(;r<t.length;){const o=t.indexOf("\r",r),i=t.indexOf("\n",r);let a=-1;if(-1!==o&&-1!==i?a=Math.min(o,i):-1!==o?a=o===t.length-1?-1:o:-1!==i&&(a=i),-1===a){n=t.slice(r);break}{const n=t.slice(r,a);e.push(n),r=a+1,"\r"===t[r-1]&&"\n"===t[r]&&r++}}return[e,n]}(`${a}${e}`);for(const t of n)d(t);a=r,c=!1},reset:function(t={}){a&&t.consume&&d(a),c=!0,i=void 0,l="",f="",a=""}}}const l="connecting",f="closed",d=()=>{};function p(t,{getStream:e}){const n="string"==typeof t||t instanceof URL?{url:t}:t,{onMessage:r,onComment:o=d,onConnect:i=d,onDisconnect:a=d,onScheduleReconnect:s=d}=n,{fetch:u,url:p,initialLastEventId:h}=function(t){const e=t.fetch||globalThis.fetch;if(!function(t){return"function"==typeof t}(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if("function"!=typeof AbortController)throw new Error("Missing AbortController implementation");const{url:n,initialLastEventId:r}=t;if("string"!=typeof n&&!(n instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if("string"!=typeof r&&void 0!==r)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:n,initialLastEventId:r}}(n),v={...n.headers},g=[],y=r?[r]:[],m=c({onEvent:function(t){var e;"string"==typeof t.id&&(T=t.id),e=t,y.forEach(t=>t(e))},onRetry:function(t){S=t},onComment:o});let w,b,E=p.toString(),C=new AbortController,T=h,S=2e3,k=f;return x(),{close:D,connect:x,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:function(){const t=[],e=[],n=function(n){const r=t.shift();r?r({value:n,done:!1}):e.push(n)};function r(){for(y.splice(y.indexOf(n),1);t.shift(););for(;e.shift(););}return g.push(function(){const e=t.shift();e&&(e({done:!0,value:void 0}),r())}),y.push(n),{next(){return k===f?this.return():new Promise(n=>{const r=e.shift();r?n({value:r,done:!1}):t.push(n)})},return:()=>(r(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r(),Promise.reject(t)),[Symbol.asyncIterator](){return this}}},get lastEventId(){return T},get url(){return E},get readyState(){return k}};function x(){w||(k=l,C=new AbortController,w=u(p,function(){const{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s}=n;return{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s,headers:{Accept:"text/event-stream",...v,...T?{"Last-Event-ID":T}:void 0},cache:"no-store",signal:C.signal}}()).then(O).catch(t=>{w=null,"AbortError"!==t.name&&"aborted"!==t.type&&!C.signal.aborted&&R()}))}function D(){k=f,C.abort(),m.reset(),clearTimeout(b),g.forEach(t=>t())}function R(){s({delay:S}),!C.signal.aborted&&(k=l,b=setTimeout(x,S))}async function O(t){i(),m.reset();const{body:n,redirected:r,status:o}=t;if(204===o)return a(),void D();if(!n)throw new Error("Missing response body");r&&(E=t.url);const s=e(n),u=new TextDecoder,c=s.getReader();let l=!0;k="open";do{const{done:t,value:e}=await c.read();e&&m.feed(u.decode(e,{stream:!t})),t&&(l=!1,w=null,m.reset(),R(),a())}while(l)}}const h={getStream:function(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}};var v=function(t){function n(e,r){var o=t.call(this,e)||this;return o.name="ConfigDirectorConnectionError",o.status=r,Object.setPrototypeOf(o,n.prototype),o}return e(n,t),n}(Error),g=function(t){function n(e){var r=t.call(this,e)||this;return r.name="ConfigDirectorValidationError",Object.setPrototypeOf(r,n.prototype),r}return e(n,t),n}(Error),y=function(){function t(t){this.options=t,this.eventEmitter=new a,this.options=t,this.logger=t.logger,this.url=new URL("sse/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,0,void 0,function(){var n,i,a,s,u=this;return o(this,function(c){return this.eventSource&&this.close(),n=void 0,i=void 0,a=function(t,e){return r(u,0,void 0,function(){var r;return o(this,function(o){switch(o.label){case 0:return[4,fetch(t,e)];case 1:return r=o.sent(),n=r.status,r.ok?[3,3]:[4,r.text()];case 2:i=o.sent(),o.label=3;case 3:return[2,r]}})})},s=new Promise(function(e,r){var o;u.eventSource=(o={url:u.url,fetch:a,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:u.options.metaContext,clientSdkKey:u.options.clientSdkKey}),onMessage:function(t){var e=t.data;u.dispatchMessage(e)},onConnect:function(){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):(u.logger.debug("[EventSourceTransport] Connected, status: %s",n),e(u))},onScheduleReconnect:function(t){n&&u.isStatusFatal(n)?(u.close(),r(u.prepareFatalError(n,i))):u.logger.warn("[EventSourceTransport] Scheduling reconnect in ".concat(t.delay,". Response status: ").concat(n))},onDisconnect:function(){u.logger.debug("[EventSourceTransport] Disconnected")}},p(o,h))}),[2,Promise.race([s,new Promise(function(t){setTimeout(function(){return t(u)},e)})])]})})},t.prototype.dispatchMessage=function(t){try{var e=JSON.parse(t);this.eventEmitter.emit("configSetReceived",e)}catch(t){this.logger.error("[EventSourceTransport] Error parsing and dispatching config data update: ",t)}},t.prototype.prepareFatalError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, will not attempt to reconnect.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){var t;null===(t=this.eventSource)||void 0===t||t.close()},t.prototype.dispose=function(){this.close(),this.clear()},t}(),m=function(t){var e,n,r=typeof t;if("object"===r)try{return null!==(n=null===(e=t.constructor)||void 0===e?void 0:e.name)&&void 0!==n?n:r}catch(t){return r}else if("function"===r)try{var o=t.name;return o?"function: ".concat(o):r}catch(t){return r}return r},w=function(t){return"number"===t||"bigint"===t},b=function(t){if(t){var e=Number.parseInt(t);if(!isNaN(e)&&isFinite(e))return e}},E=function(t){if(t){var e=Number.parseFloat(t);if(!isNaN(e)&&isFinite(e))return e}},C={off:-1,error:0,warn:1,info:2,debug:3},T=function(){function t(t,e){this.level=t,this.decorator=e,this.level=t,this.decorator=e,this.dateFormatter=function(){var t={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short"};try{return new Intl.DateTimeFormat(void 0,n(n({},t),{fractionalSecondDigits:3}))}catch(e){return new Intl.DateTimeFormat(void 0,t)}}()}return t.prototype.debug=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.debug,"debug",t],e,!1))},t.prototype.info=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.info,"info",t],e,!1))},t.prototype.warn=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.warn,"warn",t],e,!1))},t.prototype.error=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,i([console.error,"error",t],e,!1))},t.prototype.log=function(t,e,n){for(var r,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];C[this.level]>=C[e]&&t.apply(void 0,i(["[".concat(this.dateFormatter.format(new Date),"] ").concat(null===(r=this.decorator)||void 0===r?void 0:r.decorateMessage(n))],o,!1))},t}(),S=function(){function t(){}return t.prototype.decorateMessage=function(t){return"[ConfigDirector:js-client-sdk] ".concat(t)},t}(),k=function(t,e){return new T(null!=t?t:"warn",null!=e?e:new S)},x=function(){function t(){}return t.prototype.aggregate=function(t){var e;if(0==t.events.length)return[];for(var n=new Map,r=0,o=t.events;r<o.length;r++){var i=o[r],a=JSON.stringify(i),s=(null===(e=n.get(a))||void 0===e?void 0:e.count)||0;n.set(a,{event:i,count:s+1})}return Array.from(n).map(function(e){var n=e[1];return{startTime:t.startTime,endTime:t.endTime,count:n.count,event:n.event}})},t}(),D=function(){function t(t){this._events=[],this._droppedEventCount=0,this.limit=null!=t?t:1e3}return Object.defineProperty(t.prototype,"events",{get:function(){return this._events},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reachedLimit",{get:function(){return this._events.length>=this.limit},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"droppedEventCount",{get:function(){return this._droppedEventCount},enumerable:!1,configurable:!0}),t.prototype.push=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.startTime||(this.startTime=new Date);var r=Math.max(0,e.length-this.limit),o=e.slice(r,e.length);if(this._droppedEventCount+=r,this._events.length+o.length>this.limit){var i=this._events.length+o.length-this.limit;this._events.splice(0,i),this._droppedEventCount+=i}return(t=this._events).push.apply(t,o)},t.prototype.takeSnapshot=function(){var t,e=new Date,n=null!==(t=this.startTime)&&void 0!==t?t:e,r=this._events.splice(0),o=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:n,endTime:e,events:r,droppedCount:o}},t.prototype.clear=function(){this._events=[],this.startTime=void 0,this._droppedEventCount=0},t}(),R=function(){function t(t){this.executeRequests=!0,this.sdkKey=t.sdkKey,this.logger=t.logger,this.url=new URL("telemetry/v1",t.baseUrl)}return t.prototype.report=function(t){var e=t.discreteEvents,n=t.aggregatedEvents,r=t.droppedEvents;if(!this.executeRequests)return{success:!1,fatalError:!0};var o={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(o))return{success:!0,fatalError:!1};var i=this.sendReport(o);return i.fatalError&&(this.executeRequests=!1),i},t.prototype.isReportEmpty=function(t){return this.isEventListEmpty(t.discreteEvents)&&this.isEventListEmpty(t.aggregatedEvents)&&this.isDroppedEventsEmpty(t.droppedEvents)},t.prototype.isDroppedEventsEmpty=function(t){var e;if(!t)return!0;var n=Object.keys(t);if(0==n.length)return!0;for(var r=0,o=n;r<o.length;r++)if((null!==(e=t[o[r]])&&void 0!==e?e:0)>0)return!1;return!0},t.prototype.isEventListEmpty=function(t){var e,n,r=Object.keys(t);if(0==r.length)return!0;for(var o=0,i=r;o<i.length;o++)if((null!==(n=null===(e=t[i[o]])||void 0===e?void 0:e.length)&&void 0!==n?n:0)>0)return!1;return!0},t.prototype.sendReport=function(t){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(t)),fatalError:!1}}catch(t){return this.logger.warn("[EventReporter] Fatal error attempting to send telemetry data: ".concat(t,". No more telemetry data will be sent.")),{success:!1,fatalError:!0}}},t}(),O=function(){function t(t){var e=this;this.evaluationEventQueue=new D,this.aggregator=new x,this.collectEvents=!0,this.logger=t.logger,this.reporter=new R(t),this.flushIntervalDelay=3e4,this.flushTimeout=setTimeout(function(){return e.flushAndScheduleNext()},5e3);try{document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.flush()})}catch(t){this.logger.warn("[TelemetryEventCollector] Could not configure 'visibilitychange' listener: ",t)}}return t.prototype.evaluatedConfig=function(t){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))},t.prototype.sanitizeEvaluatedConfigEvent=function(t){return{key:t.key,type:t.type,defaultValue:this.sanitizeValue(t.defaultValue,t.type),requestedType:t.requestedType,evaluatedValue:this.sanitizeValue(t.evaluatedValue,t.type),usedDefault:t.usedDefault,evaluationReason:t.evaluationReason}},t.prototype.sanitizeValue=function(t,e){if("json"===e)try{return n=JSON.stringify(t),function(t){for(var e=5381,n=0;n<t.length;n++)e=(e<<5)+e+t[n],e>>>=0;return e}((new TextEncoder).encode(n)).toString(16).padStart(8,"0")}catch(e){return t.toString().slice(0,500)}var n;return t.toString().slice(0,500)},t.prototype.flushAndScheduleNext=function(){var t=this;this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn("[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.")):this.flushTimeout=setTimeout(function(){return t.flushAndScheduleNext()},this.flushIntervalDelay)},t.prototype.flush=function(){var t=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(t)},droppedEvents:{evaluatedConfig:t.droppedCount}})},t.prototype.close=function(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()},t.prototype.dispose=function(){this.close()},t}(),V=function(t,e,i,a){return r(void 0,0,void 0,function(){var r,s,u,c;return o(this,function(o){switch(o.label){case 0:r=new AbortController,s=setTimeout(function(){a.debug("[fetchWithTimeout] Reached timeout, aborting request"),r.abort()},t),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,fetch(e,n(n({},i),{signal:r.signal}))];case 2:return u=o.sent(),clearTimeout(s),[2,u];case 3:throw c=o.sent(),a.warn("[fetchWithTimeout] Fetch error: ",c),clearTimeout(s),c;case 4:return[2]}})})},M=function(){function t(t){this.options=t,this.eventEmitter=new a,this.fatalError=!1,this.options=t,this.logger=t.logger,this.url=new URL("pull/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return r(this,0,void 0,function(){var n,r,i,a,s,u,c;return o(this,function(o){switch(o.label){case 0:if(this.fatalError)return this.logger.warn("[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect."),[2,this];o.label=1;case 1:return o.trys.push([1,7,,8]),[4,V(e,this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger)];case 2:return(n=o.sent()).ok?[3,5]:this.isStatusFatal(n.status)?(this.fatalError=!0,r=this.prepareFatalResponseStatusError,i=[n.status],[4,n.text()]):[3,4];case 3:throw r.apply(this,i.concat([o.sent()]));case 4:throw new v("Connection failed with status: ".concat(n.status),n.status);case 5:return u=(s=JSON).parse,[4,n.text()];case 6:return a=u.apply(s,[o.sent()]),this.eventEmitter.emit("configSetReceived",a),[2,this];case 7:throw function(t){if(t instanceof DOMException){if("NotAllowedError"===t.name)return!0}else if(t instanceof TypeError)return!0;return!1}(c=o.sent())?(this.fatalError=!0,new v("Connection failed with fatal error: ".concat(c,". This is an unrecoverable error, retry attempts will be ignored."))):c instanceof SyntaxError?new v("Failed to parse the response from the server: ".concat(c)):new v("Connection failed with error: ".concat(c,"."));case 8:return[2]}})})},t.prototype.prepareFatalResponseStatusError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, retry attempts will be ignored.");return new v(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){},t.prototype.dispose=function(){this.close(),this.clear()},t}(),P=new URL("https://client-sdk-api.configdirector.com"),F=function(){function t(t,e,r){var o,i,s,u,c,l,f=this;this.handlersMap=new Map,this.eventEmitter=new a,this.ready=!1,this.logger=null!==(o=null==r?void 0:r.logger)&&void 0!==o?o:k(),this.timeout=null!==(s=null===(i=null==r?void 0:r.connection)||void 0===i?void 0:i.timeout)&&void 0!==s?s:3e3;var d=null!==(c=this.parseUrl(null===(u=null==r?void 0:r.connection)||void 0===u?void 0:u.url))&&void 0!==c?c:P;this.streaming=!1!==(null===(l=null==r?void 0:r.connection)||void 0===l?void 0:l.streaming);var p=this.streaming?y:M;this.usageEventCollector=new O({sdkKey:t,logger:this.logger,baseUrl:d}),this.transport=new p({clientSdkKey:t,baseUrl:d,metaContext:n(n({},null==r?void 0:r.metadata),{sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:null===navigator||void 0===navigator?void 0:navigator.userAgent}),logger:this.logger}),this.transport.on("configSetReceived",function(t){var e;null===(e=f.readyResolve)||void 0===e||e.call(f);var r=Object.keys(t.configs);f.configSet&&"full"!=t.kind?(f.configSet.configs=n(n({},f.configSet.configs),t.configs),f.eventEmitter.emit("configsUpdated",{keys:r}),f.updateWatchers(t.configs)):(f.configSet=t,f.eventEmitter.emit("configsUpdated",{keys:r}),f.updateWatchers(t.configs)),f.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:",{keys:r})})}return t.prototype.initialize=function(t){return r(this,0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"initialization")];case 1:return e.sent(),[2]}})})},t.prototype.updateContext=function(t){return r(this,0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"context update")];case 1:return e.sent(),[2]}})})},t.prototype.connectToTransport=function(t,e){return r(this,0,void 0,function(){var n,r,i,a,s,u=this;return o(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),this.ready=!1,this.readyPromise=new Promise(function(t){u.readyResolve=t}).then(function(){u.ready=!0,u.eventEmitter.emit("clientReady",{action:e}),u.logger.debug("[ConfigDirectorClient] Received initial payload from the server, client is ready")}),n=(new Date).getTime(),[4,this.transport.connect(null!=t?t:{},this.timeout)];case 1:return o.sent(),this.currentContext=t,r=(new Date).getTime()-n,(i=this.timeout-r)>0?[4,Promise.race([this.readyPromise,new Promise(function(t){setTimeout(function(){return t()},i)})])]:[3,3];case 2:o.sent(),o.label=3;case 3:return this.ready||(a=this.streaming?"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.":"Since the client was configured without streaming, configs may not update and always return the default value.",this.logger.warn("[ConfigDirectorClient] Timed out waiting for ".concat(e," after ").concat(this.timeout,"ms. ").concat(a))),[3,5];case 4:return s=o.sent(),this.logger.error("[ConfigDirectorClient] An error occurred during ".concat(e,": "),s),[3,5];case 5:return[2]}})})},t.prototype.updateWatchers=function(t){var e=this;Object.values(t).forEach(function(t){return e.updateWatchersForConfig(t)})},t.prototype.updateWatchersForConfig=function(t){var e,n=this;null===(e=this.handlersMap.get(t.key))||void 0===e||e.forEach(function(e){var r=n.getValueFromConfigState(t.key,t,e.defaultValue);e.handler(r)})},t.prototype.watch=function(t,e,n){var r=this;this.validateDefaultValue(e);var o=this.handlersMap.get(t),i={handler:n,defaultValue:e,requestedType:typeof e};return o?o.push(i):this.handlersMap.set(t,[i]),function(){return r.unwatch(t,n)}},t.prototype.unwatch=function(t,e){var n=this.handlersMap.get(t);if(n)if(e){var r=n.findIndex(function(t){return t.handler==e});r>=0&&(null==n||n.splice(r,1))}else n.splice(0)},t.prototype.getValue=function(t,e){var n;this.validateDefaultValue(e);var r=null===(n=this.configSet)||void 0===n?void 0:n.configs[t];return this.getValueFromConfigState(t,r,e)},t.prototype.getValueFromConfigState=function(t,e,n){var r,o;if(!e)return this.logger.debug("[ConfigDirectorClient] No config state found for '".concat(t,"', returning default value '").concat(n,"'")),this.usageEventCollector.evaluatedConfig({contextId:null===(r=this.currentContext)||void 0===r?void 0:r.id,key:t,defaultValue:n,requestedType:m(n),evaluatedValue:n,usedDefault:!0,evaluationReason:"config-state-missing"}),n;var i=function(t,e){var n,r,o=t.value,i=m(e);if(!o)return{parsedValue:e,requestedType:i,usedDefault:!0,reason:"value-missing"};if("string"==typeof e)return{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"};if("boolean"==typeof e&&"boolean"===t.type){var a=function(t){if(t){var e=t.toLowerCase();if("true"==e||"false"==e)return"true"===e}}(o),s="boolean"==typeof a;return{parsedValue:s?a:e,requestedType:i,usedDefault:!s,reason:s?"found-match":"invalid-boolean"}}return w(typeof e)&&"integer"===t.type?{parsedValue:(r="number"==typeof(n=b(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}:!w(typeof e)||"float"!==t.type&&"enum"!==t.type?{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"}:{parsedValue:(r="number"==typeof(n=E(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}}(e,n);return this.usageEventCollector.evaluatedConfig({contextId:null===(o=this.currentContext)||void 0===o?void 0:o.id,key:t,defaultValue:n,requestedType:i.requestedType,evaluatedValue:i.parsedValue,usedDefault:i.usedDefault,evaluationReason:i.reason}),this.logger.debug("[ConfigDirectorClient] Evaluated '".concat(t,"' to '").concat(i.parsedValue,"'")),i.parsedValue},t.prototype.parseUrl=function(t){if(t)try{return new URL(t)}catch(e){throw new g("Invalid base URL '".concat(t,"'. Parsing failed: ").concat(e))}},t.prototype.validateDefaultValue=function(t){if(null==t)throw new g("Invalid default value. The default value for a config must be defined and non-null.");if("function"==typeof t)throw new g("Invalid default value. The default value for a config cannot be a function.")},Object.defineProperty(t.prototype,"isReady",{get:function(){return this.ready},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.logger.debug("[ConfigDirectorClient] clear() has been called, removing all observers"),this.eventEmitter.clear(),this.handlersMap.clear()},t.prototype.unwatchAll=function(){this.handlersMap.clear()},t.prototype.close=function(){this.logger.debug("[ConfigDirectorClient] close() has been called, closing connection to server"),this.transport.close(),this.ready=!1},t.prototype.dispose=function(){this.clear(),this.close()},t}(),I=function(t,e){return new F(t,{sdkName:"js-client-sdk",sdkVersion:"0.1.4"},e)},j=function(t,e){return k(t,e)};export{I as createClient,j as createConsoleLogger};
2
- //# sourceMappingURL=configdirector-client.es.js.map
@@ -1,2 +0,0 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ConfigDirectorClient={})}(this,function(t){"use strict";var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r=function(){return r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},r.apply(this,arguments)};function o(t,e,n,r){return new(n||(n=Promise))(function(e,o){function i(t){try{s(r.next(t))}catch(t){o(t)}}function a(t){try{s(r.throw(t))}catch(t){o(t)}}function s(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(t){t(r)})).then(i,a)}s((r=r.apply(t,[])).next())})}function i(t,e){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(u){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}}function a(t,e,n){if(2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var s=function(){function t(){this.handlerMap=new Map}return t.prototype.on=function(t,e){var n=this.handlerMap.get(t);n?n.push(e):this.handlerMap.set(t,[e])},t.prototype.once=function(t,e){var n=this;this.on(t,function r(o){n.off(t,r),e.apply(n,o)})},t.prototype.off=function(t,e){var n=this.handlerMap.get(t);if(n)if(e){var r=n.indexOf(e);r>=0&&n.splice(r,1)}else this.handlerMap.set(t,[])},t.prototype.clear=function(){this.handlerMap.clear()},t.prototype.emit=function(t,e){var n=this.handlerMap.get(t);n&&n.slice().map(function(t){return t(e)})},t}();class u extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}}function c(t){}function l(t){if("function"==typeof t)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=c,onError:n=c,onRetry:r=c,onComment:o}=t;let i,a="",s=!0,l="",f="";function d(t){if(""===t)return l.length>0&&e({id:i,event:f||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),i=void 0,l="",void(f="");if(t.startsWith(":"))return void(o&&o(t.slice(t.startsWith(": ")?2:1)));const n=t.indexOf(":");if(-1!==n){const e=t.slice(0,n),r=" "===t[n+1]?2:1;return void p(e,t.slice(n+r),t)}p(t,"",t)}function p(t,e,o){switch(t){case"event":f=e;break;case"data":l=`${l}${e}\n`;break;case"id":i=e.includes("\0")?void 0:e;break;case"retry":/^\d+$/.test(e)?r(parseInt(e,10)):n(new u(`Invalid \`retry\` value: "${e}"`,{type:"invalid-retry",value:e,line:o}));break;default:n(new u(`Unknown field "${t.length>20?`${t.slice(0,20)}…`:t}"`,{type:"unknown-field",field:t,value:e,line:o}))}}return{feed:function(t){const e=s?t.replace(/^\xEF\xBB\xBF/,""):t,[n,r]=function(t){const e=[];let n="",r=0;for(;r<t.length;){const o=t.indexOf("\r",r),i=t.indexOf("\n",r);let a=-1;if(-1!==o&&-1!==i?a=Math.min(o,i):-1!==o?a=o===t.length-1?-1:o:-1!==i&&(a=i),-1===a){n=t.slice(r);break}{const n=t.slice(r,a);e.push(n),r=a+1,"\r"===t[r-1]&&"\n"===t[r]&&r++}}return[e,n]}(`${a}${e}`);for(const t of n)d(t);a=r,s=!1},reset:function(t={}){a&&t.consume&&d(a),s=!0,i=void 0,l="",f="",a=""}}}const f="connecting",d="closed",p=()=>{};function h(t,{getStream:e}){const n="string"==typeof t||t instanceof URL?{url:t}:t,{onMessage:r,onComment:o=p,onConnect:i=p,onDisconnect:a=p,onScheduleReconnect:s=p}=n,{fetch:u,url:c,initialLastEventId:h}=function(t){const e=t.fetch||globalThis.fetch;if(!function(t){return"function"==typeof t}(e))throw new Error("No fetch implementation provided, and one was not found on the global object.");if("function"!=typeof AbortController)throw new Error("Missing AbortController implementation");const{url:n,initialLastEventId:r}=t;if("string"!=typeof n&&!(n instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if("string"!=typeof r&&void 0!==r)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:e,url:n,initialLastEventId:r}}(n),v={...n.headers},g=[],y=r?[r]:[],m=l({onEvent:function(t){var e;"string"==typeof t.id&&(T=t.id),e=t,y.forEach(t=>t(e))},onRetry:function(t){S=t},onComment:o});let w,b,E=c.toString(),C=new AbortController,T=h,S=2e3,k=d;return x(),{close:D,connect:x,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:function(){const t=[],e=[],n=function(n){const r=t.shift();r?r({value:n,done:!1}):e.push(n)};function r(){for(y.splice(y.indexOf(n),1);t.shift(););for(;e.shift(););}return g.push(function(){const e=t.shift();e&&(e({done:!0,value:void 0}),r())}),y.push(n),{next(){return k===d?this.return():new Promise(n=>{const r=e.shift();r?n({value:r,done:!1}):t.push(n)})},return:()=>(r(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r(),Promise.reject(t)),[Symbol.asyncIterator](){return this}}},get lastEventId(){return T},get url(){return E},get readyState(){return k}};function x(){w||(k=f,C=new AbortController,w=u(c,function(){const{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s}=n;return{mode:t,credentials:e,body:r,method:o,redirect:i,referrer:a,referrerPolicy:s,headers:{Accept:"text/event-stream",...v,...T?{"Last-Event-ID":T}:void 0},cache:"no-store",signal:C.signal}}()).then(O).catch(t=>{w=null,"AbortError"!==t.name&&"aborted"!==t.type&&!C.signal.aborted&&R()}))}function D(){k=d,C.abort(),m.reset(),clearTimeout(b),g.forEach(t=>t())}function R(){s({delay:S}),!C.signal.aborted&&(k=f,b=setTimeout(x,S))}async function O(t){i(),m.reset();const{body:n,redirected:r,status:o}=t;if(204===o)return a(),void D();if(!n)throw new Error("Missing response body");r&&(E=t.url);const s=e(n),u=new TextDecoder,c=s.getReader();let l=!0;k="open";do{const{done:t,value:e}=await c.read();e&&m.feed(u.decode(e,{stream:!t})),t&&(l=!1,w=null,m.reset(),R(),a())}while(l)}}const v={getStream:function(t){if(!(t instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return t}};var g=function(t){function e(n,r){var o=t.call(this,n)||this;return o.name="ConfigDirectorConnectionError",o.status=r,Object.setPrototypeOf(o,e.prototype),o}return n(e,t),e}(Error),y=function(t){function e(n){var r=t.call(this,n)||this;return r.name="ConfigDirectorValidationError",Object.setPrototypeOf(r,e.prototype),r}return n(e,t),e}(Error),m=function(){function t(t){this.options=t,this.eventEmitter=new s,this.options=t,this.logger=t.logger,this.url=new URL("sse/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return o(this,0,void 0,function(){var n,r,a,s,u=this;return i(this,function(c){return this.eventSource&&this.close(),n=void 0,r=void 0,a=function(t,e){return o(u,0,void 0,function(){var o;return i(this,function(i){switch(i.label){case 0:return[4,fetch(t,e)];case 1:return o=i.sent(),n=o.status,o.ok?[3,3]:[4,o.text()];case 2:r=i.sent(),i.label=3;case 3:return[2,o]}})})},s=new Promise(function(e,o){var i;u.eventSource=(i={url:u.url,fetch:a,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:u.options.metaContext,clientSdkKey:u.options.clientSdkKey}),onMessage:function(t){var e=t.data;u.dispatchMessage(e)},onConnect:function(){n&&u.isStatusFatal(n)?(u.close(),o(u.prepareFatalError(n,r))):(u.logger.debug("[EventSourceTransport] Connected, status: %s",n),e(u))},onScheduleReconnect:function(t){n&&u.isStatusFatal(n)?(u.close(),o(u.prepareFatalError(n,r))):u.logger.warn("[EventSourceTransport] Scheduling reconnect in ".concat(t.delay,". Response status: ").concat(n))},onDisconnect:function(){u.logger.debug("[EventSourceTransport] Disconnected")}},h(i,v))}),[2,Promise.race([s,new Promise(function(t){setTimeout(function(){return t(u)},e)})])]})})},t.prototype.dispatchMessage=function(t){try{var e=JSON.parse(t);this.eventEmitter.emit("configSetReceived",e)}catch(t){this.logger.error("[EventSourceTransport] Error parsing and dispatching config data update: ",t)}},t.prototype.prepareFatalError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, will not attempt to reconnect.");return new g(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){var t;null===(t=this.eventSource)||void 0===t||t.close()},t.prototype.dispose=function(){this.close(),this.clear()},t}(),w=function(t){var e,n,r=typeof t;if("object"===r)try{return null!==(n=null===(e=t.constructor)||void 0===e?void 0:e.name)&&void 0!==n?n:r}catch(t){return r}else if("function"===r)try{var o=t.name;return o?"function: ".concat(o):r}catch(t){return r}return r},b=function(t){return"number"===t||"bigint"===t},E=function(t){if(t){var e=Number.parseInt(t);if(!isNaN(e)&&isFinite(e))return e}},C=function(t){if(t){var e=Number.parseFloat(t);if(!isNaN(e)&&isFinite(e))return e}},T={off:-1,error:0,warn:1,info:2,debug:3},S=function(){function t(t,e){this.level=t,this.decorator=e,this.level=t,this.decorator=e,this.dateFormatter=function(){var t={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short"};try{return new Intl.DateTimeFormat(void 0,r(r({},t),{fractionalSecondDigits:3}))}catch(e){return new Intl.DateTimeFormat(void 0,t)}}()}return t.prototype.debug=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.debug,"debug",t],e,!1))},t.prototype.info=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.info,"info",t],e,!1))},t.prototype.warn=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.warn,"warn",t],e,!1))},t.prototype.error=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];this.log.apply(this,a([console.error,"error",t],e,!1))},t.prototype.log=function(t,e,n){for(var r,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];T[this.level]>=T[e]&&t.apply(void 0,a(["[".concat(this.dateFormatter.format(new Date),"] ").concat(null===(r=this.decorator)||void 0===r?void 0:r.decorateMessage(n))],o,!1))},t}(),k=function(){function t(){}return t.prototype.decorateMessage=function(t){return"[ConfigDirector:js-client-sdk] ".concat(t)},t}(),x=function(t,e){return new S(null!=t?t:"warn",null!=e?e:new k)},D=function(){function t(){}return t.prototype.aggregate=function(t){var e;if(0==t.events.length)return[];for(var n=new Map,r=0,o=t.events;r<o.length;r++){var i=o[r],a=JSON.stringify(i),s=(null===(e=n.get(a))||void 0===e?void 0:e.count)||0;n.set(a,{event:i,count:s+1})}return Array.from(n).map(function(e){var n=e[1];return{startTime:t.startTime,endTime:t.endTime,count:n.count,event:n.event}})},t}(),R=function(){function t(t){this._events=[],this._droppedEventCount=0,this.limit=null!=t?t:1e3}return Object.defineProperty(t.prototype,"events",{get:function(){return this._events},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reachedLimit",{get:function(){return this._events.length>=this.limit},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"droppedEventCount",{get:function(){return this._droppedEventCount},enumerable:!1,configurable:!0}),t.prototype.push=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.startTime||(this.startTime=new Date);var r=Math.max(0,e.length-this.limit),o=e.slice(r,e.length);if(this._droppedEventCount+=r,this._events.length+o.length>this.limit){var i=this._events.length+o.length-this.limit;this._events.splice(0,i),this._droppedEventCount+=i}return(t=this._events).push.apply(t,o)},t.prototype.takeSnapshot=function(){var t,e=new Date,n=null!==(t=this.startTime)&&void 0!==t?t:e,r=this._events.splice(0),o=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:n,endTime:e,events:r,droppedCount:o}},t.prototype.clear=function(){this._events=[],this.startTime=void 0,this._droppedEventCount=0},t}(),O=function(){function t(t){this.executeRequests=!0,this.sdkKey=t.sdkKey,this.logger=t.logger,this.url=new URL("telemetry/v1",t.baseUrl)}return t.prototype.report=function(t){var e=t.discreteEvents,n=t.aggregatedEvents,r=t.droppedEvents;if(!this.executeRequests)return{success:!1,fatalError:!0};var o={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(o))return{success:!0,fatalError:!1};var i=this.sendReport(o);return i.fatalError&&(this.executeRequests=!1),i},t.prototype.isReportEmpty=function(t){return this.isEventListEmpty(t.discreteEvents)&&this.isEventListEmpty(t.aggregatedEvents)&&this.isDroppedEventsEmpty(t.droppedEvents)},t.prototype.isDroppedEventsEmpty=function(t){var e;if(!t)return!0;var n=Object.keys(t);if(0==n.length)return!0;for(var r=0,o=n;r<o.length;r++)if((null!==(e=t[o[r]])&&void 0!==e?e:0)>0)return!1;return!0},t.prototype.isEventListEmpty=function(t){var e,n,r=Object.keys(t);if(0==r.length)return!0;for(var o=0,i=r;o<i.length;o++)if((null!==(n=null===(e=t[i[o]])||void 0===e?void 0:e.length)&&void 0!==n?n:0)>0)return!1;return!0},t.prototype.sendReport=function(t){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(t)),fatalError:!1}}catch(t){return this.logger.warn("[EventReporter] Fatal error attempting to send telemetry data: ".concat(t,". No more telemetry data will be sent.")),{success:!1,fatalError:!0}}},t}(),V=function(){function t(t){var e=this;this.evaluationEventQueue=new R,this.aggregator=new D,this.collectEvents=!0,this.logger=t.logger,this.reporter=new O(t),this.flushIntervalDelay=3e4,this.flushTimeout=setTimeout(function(){return e.flushAndScheduleNext()},5e3);try{document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e.flush()})}catch(t){this.logger.warn("[TelemetryEventCollector] Could not configure 'visibilitychange' listener: ",t)}}return t.prototype.evaluatedConfig=function(t){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))},t.prototype.sanitizeEvaluatedConfigEvent=function(t){return{key:t.key,type:t.type,defaultValue:this.sanitizeValue(t.defaultValue,t.type),requestedType:t.requestedType,evaluatedValue:this.sanitizeValue(t.evaluatedValue,t.type),usedDefault:t.usedDefault,evaluationReason:t.evaluationReason}},t.prototype.sanitizeValue=function(t,e){if("json"===e)try{return n=JSON.stringify(t),function(t){for(var e=5381,n=0;n<t.length;n++)e=(e<<5)+e+t[n],e>>>=0;return e}((new TextEncoder).encode(n)).toString(16).padStart(8,"0")}catch(e){return t.toString().slice(0,500)}var n;return t.toString().slice(0,500)},t.prototype.flushAndScheduleNext=function(){var t=this;this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn("[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.")):this.flushTimeout=setTimeout(function(){return t.flushAndScheduleNext()},this.flushIntervalDelay)},t.prototype.flush=function(){var t=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(t)},droppedEvents:{evaluatedConfig:t.droppedCount}})},t.prototype.close=function(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()},t.prototype.dispose=function(){this.close()},t}(),M=function(t,e,n,a){return o(void 0,0,void 0,function(){var o,s,u,c;return i(this,function(i){switch(i.label){case 0:o=new AbortController,s=setTimeout(function(){a.debug("[fetchWithTimeout] Reached timeout, aborting request"),o.abort()},t),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,fetch(e,r(r({},n),{signal:o.signal}))];case 2:return u=i.sent(),clearTimeout(s),[2,u];case 3:throw c=i.sent(),a.warn("[fetchWithTimeout] Fetch error: ",c),clearTimeout(s),c;case 4:return[2]}})})},P=function(){function t(t){this.options=t,this.eventEmitter=new s,this.fatalError=!1,this.options=t,this.logger=t.logger,this.url=new URL("pull/v1",t.baseUrl)}return t.prototype.connect=function(t,e){return o(this,0,void 0,function(){var n,r,o,a,s,u,c;return i(this,function(i){switch(i.label){case 0:if(this.fatalError)return this.logger.warn("[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect."),[2,this];i.label=1;case 1:return i.trys.push([1,7,,8]),[4,M(e,this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger)];case 2:return(n=i.sent()).ok?[3,5]:this.isStatusFatal(n.status)?(this.fatalError=!0,r=this.prepareFatalResponseStatusError,o=[n.status],[4,n.text()]):[3,4];case 3:throw r.apply(this,o.concat([i.sent()]));case 4:throw new g("Connection failed with status: ".concat(n.status),n.status);case 5:return u=(s=JSON).parse,[4,n.text()];case 6:return a=u.apply(s,[i.sent()]),this.eventEmitter.emit("configSetReceived",a),[2,this];case 7:throw function(t){if(t instanceof DOMException){if("NotAllowedError"===t.name)return!0}else if(t instanceof TypeError)return!0;return!1}(c=i.sent())?(this.fatalError=!0,new g("Connection failed with fatal error: ".concat(c,". This is an unrecoverable error, retry attempts will be ignored."))):c instanceof SyntaxError?new g("Failed to parse the response from the server: ".concat(c)):new g("Connection failed with error: ".concat(c,"."));case 8:return[2]}})})},t.prototype.prepareFatalResponseStatusError=function(t,e){var n,r,o=null!=t?t:0,i="Connection failed with status: ".concat(null!=t?t:"unknown"),a=(null!==(r=null===(n=null==e?void 0:e.trim())||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0?" (".concat(e,")"):"",s="".concat(i).concat(a,". This is an unrecoverable error, retry attempts will be ignored.");return new g(s,o)},t.prototype.isStatusFatal=function(t){return!!t&&t>=400&&t<500},t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.eventEmitter.clear()},t.prototype.close=function(){},t.prototype.dispose=function(){this.close(),this.clear()},t}(),j=new URL("https://client-sdk-api.configdirector.com"),F=function(){function t(t,e,n){var o,i,a,u,c,l,f=this;this.handlersMap=new Map,this.eventEmitter=new s,this.ready=!1,this.logger=null!==(o=null==n?void 0:n.logger)&&void 0!==o?o:x(),this.timeout=null!==(a=null===(i=null==n?void 0:n.connection)||void 0===i?void 0:i.timeout)&&void 0!==a?a:3e3;var d=null!==(c=this.parseUrl(null===(u=null==n?void 0:n.connection)||void 0===u?void 0:u.url))&&void 0!==c?c:j;this.streaming=!1!==(null===(l=null==n?void 0:n.connection)||void 0===l?void 0:l.streaming);var p=this.streaming?m:P;this.usageEventCollector=new V({sdkKey:t,logger:this.logger,baseUrl:d}),this.transport=new p({clientSdkKey:t,baseUrl:d,metaContext:r(r({},null==n?void 0:n.metadata),{sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:null===navigator||void 0===navigator?void 0:navigator.userAgent}),logger:this.logger}),this.transport.on("configSetReceived",function(t){var e;null===(e=f.readyResolve)||void 0===e||e.call(f);var n=Object.keys(t.configs);f.configSet&&"full"!=t.kind?(f.configSet.configs=r(r({},f.configSet.configs),t.configs),f.eventEmitter.emit("configsUpdated",{keys:n}),f.updateWatchers(t.configs)):(f.configSet=t,f.eventEmitter.emit("configsUpdated",{keys:n}),f.updateWatchers(t.configs)),f.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:",{keys:n})})}return t.prototype.initialize=function(t){return o(this,0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"initialization")];case 1:return e.sent(),[2]}})})},t.prototype.updateContext=function(t){return o(this,0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,this.connectToTransport(t,"context update")];case 1:return e.sent(),[2]}})})},t.prototype.connectToTransport=function(t,e){return o(this,0,void 0,function(){var n,r,o,a,s,u=this;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,4,,5]),this.ready=!1,this.readyPromise=new Promise(function(t){u.readyResolve=t}).then(function(){u.ready=!0,u.eventEmitter.emit("clientReady",{action:e}),u.logger.debug("[ConfigDirectorClient] Received initial payload from the server, client is ready")}),n=(new Date).getTime(),[4,this.transport.connect(null!=t?t:{},this.timeout)];case 1:return i.sent(),this.currentContext=t,r=(new Date).getTime()-n,(o=this.timeout-r)>0?[4,Promise.race([this.readyPromise,new Promise(function(t){setTimeout(function(){return t()},o)})])]:[3,3];case 2:i.sent(),i.label=3;case 3:return this.ready||(a=this.streaming?"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.":"Since the client was configured without streaming, configs may not update and always return the default value.",this.logger.warn("[ConfigDirectorClient] Timed out waiting for ".concat(e," after ").concat(this.timeout,"ms. ").concat(a))),[3,5];case 4:return s=i.sent(),this.logger.error("[ConfigDirectorClient] An error occurred during ".concat(e,": "),s),[3,5];case 5:return[2]}})})},t.prototype.updateWatchers=function(t){var e=this;Object.values(t).forEach(function(t){return e.updateWatchersForConfig(t)})},t.prototype.updateWatchersForConfig=function(t){var e,n=this;null===(e=this.handlersMap.get(t.key))||void 0===e||e.forEach(function(e){var r=n.getValueFromConfigState(t.key,t,e.defaultValue);e.handler(r)})},t.prototype.watch=function(t,e,n){var r=this;this.validateDefaultValue(e);var o=this.handlersMap.get(t),i={handler:n,defaultValue:e,requestedType:typeof e};return o?o.push(i):this.handlersMap.set(t,[i]),function(){return r.unwatch(t,n)}},t.prototype.unwatch=function(t,e){var n=this.handlersMap.get(t);if(n)if(e){var r=n.findIndex(function(t){return t.handler==e});r>=0&&(null==n||n.splice(r,1))}else n.splice(0)},t.prototype.getValue=function(t,e){var n;this.validateDefaultValue(e);var r=null===(n=this.configSet)||void 0===n?void 0:n.configs[t];return this.getValueFromConfigState(t,r,e)},t.prototype.getValueFromConfigState=function(t,e,n){var r,o;if(!e)return this.logger.debug("[ConfigDirectorClient] No config state found for '".concat(t,"', returning default value '").concat(n,"'")),this.usageEventCollector.evaluatedConfig({contextId:null===(r=this.currentContext)||void 0===r?void 0:r.id,key:t,defaultValue:n,requestedType:w(n),evaluatedValue:n,usedDefault:!0,evaluationReason:"config-state-missing"}),n;var i=function(t,e){var n,r,o=t.value,i=w(e);if(!o)return{parsedValue:e,requestedType:i,usedDefault:!0,reason:"value-missing"};if("string"==typeof e)return{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"};if("boolean"==typeof e&&"boolean"===t.type){var a=function(t){if(t){var e=t.toLowerCase();if("true"==e||"false"==e)return"true"===e}}(o),s="boolean"==typeof a;return{parsedValue:s?a:e,requestedType:i,usedDefault:!s,reason:s?"found-match":"invalid-boolean"}}return b(typeof e)&&"integer"===t.type?{parsedValue:(r="number"==typeof(n=E(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}:!b(typeof e)||"float"!==t.type&&"enum"!==t.type?{parsedValue:o,requestedType:i,usedDefault:!1,reason:"found-match"}:{parsedValue:(r="number"==typeof(n=C(o)))?n:e,requestedType:i,usedDefault:!r,reason:r?"found-match":"invalid-number"}}(e,n);return this.usageEventCollector.evaluatedConfig({contextId:null===(o=this.currentContext)||void 0===o?void 0:o.id,key:t,defaultValue:n,requestedType:i.requestedType,evaluatedValue:i.parsedValue,usedDefault:i.usedDefault,evaluationReason:i.reason}),this.logger.debug("[ConfigDirectorClient] Evaluated '".concat(t,"' to '").concat(i.parsedValue,"'")),i.parsedValue},t.prototype.parseUrl=function(t){if(t)try{return new URL(t)}catch(e){throw new y("Invalid base URL '".concat(t,"'. Parsing failed: ").concat(e))}},t.prototype.validateDefaultValue=function(t){if(null==t)throw new y("Invalid default value. The default value for a config must be defined and non-null.");if("function"==typeof t)throw new y("Invalid default value. The default value for a config cannot be a function.")},Object.defineProperty(t.prototype,"isReady",{get:function(){return this.ready},enumerable:!1,configurable:!0}),t.prototype.on=function(t,e){this.eventEmitter.on(t,e)},t.prototype.off=function(t,e){this.eventEmitter.off(t,e)},t.prototype.clear=function(){this.logger.debug("[ConfigDirectorClient] clear() has been called, removing all observers"),this.eventEmitter.clear(),this.handlersMap.clear()},t.prototype.unwatchAll=function(){this.handlersMap.clear()},t.prototype.close=function(){this.logger.debug("[ConfigDirectorClient] close() has been called, closing connection to server"),this.transport.close(),this.ready=!1},t.prototype.dispose=function(){this.clear(),this.close()},t}();t.createClient=function(t,e){return new F(t,{sdkName:"js-client-sdk",sdkVersion:"0.1.4"},e)},t.createConsoleLogger=function(t,e){return x(t,e)}});
2
- //# sourceMappingURL=configdirector-client.min.js.map