@launchdarkly/cloudflare-server-sdk 2.6.3 → 2.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{EventEmitter as e}from"node:events";import t from"semver";import i from"crypto-js";var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n={},s={};Object.defineProperty(s,"__esModule",{value:!0});s.default=class{constructor(e){this._onRequestStatus=e}getStatus(){return this._lastStatus}async requireStatus(){return this._lastStatus||await this._onRequestStatus(),this._lastStatus}notify(){var e;this._lastStatus&&(null===(e=this._listener)||void 0===e||e.call(this,this._lastStatus))}setListener(e){this._listener=e}setStatus(e){this._lastStatus=e}};var a={},o={};!function(e){function t(e){return e.indexOf("~")?e.replace(/~1/g,"/").replace(/~0/g,"~"):e}class i{constructor(e,i=!1){if(i){const t=e;this._components=[t],this.isValid=""!==t,this.redactionName=t.startsWith("/")?`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`:t}else{if(this.redactionName=e,""===e||"/"===e||e.match(/\/\/|(^\/.*~[^0|^1])|~$/))return this.isValid=!1,void(this._components=[]);!function(e){return!e.startsWith("/")}(e)?e.indexOf("/",1)<0?this._components=[t(e.slice(1))]:this._components=function(e){return(e.startsWith("/")?e.substring(1):e).split("/").map((e=>t(e)))}(e):this._components=[e],"_meta"===this._components[0]?this.isValid=!1:this.isValid=!0}}get(e){const{_components:t,isValid:i}=this;if(!i)return;let r=e;for(let e=0;e<t.length;e+=1){const i=t[e];if(null==r||!Object.prototype.hasOwnProperty.call(r,i)||"object"!=typeof r||Array.isArray(r))return;r=r[i]}return r}getComponent(e){return this._components[e]}get depth(){return this._components.length}get isKind(){return 1===this._components.length&&"kind"===this._components[0]}compare(e){return this.depth===e.depth&&this._components.every(((t,i)=>t===e.getComponent(i)))}}i.InvalidReference=new i("");class r{is(e){if(Array.isArray(e))return!1;const t=typeof e;return"function"===t||"object"===t}getType(){return"factory method or object"}}class n{constructor(e,t){this._typeName=e,this.typeOf=typeof t}is(e){return!Array.isArray(e)&&typeof e===this.typeOf}getType(){return this._typeName}}class s{constructor(e,t){this._typeName=e,this.typeOf=typeof t}is(e){return!!Array.isArray(e)&&(!(e.length>0)||e.every((e=>typeof e===this.typeOf)))}getType(){return this._typeName}}class a extends n{constructor(e){super(`number with minimum value of ${e}`,0),this.min=e}is(e){return typeof e===this.typeOf&&e>=this.min}}class o extends n{constructor(e){super(`string matching ${e}`,""),this.expression=e}is(e){return"string"==typeof e&&!!e.match(this.expression)}}class l{is(e){return"function"==typeof e}getType(){return"function"}}class u{is(e){return"boolean"==typeof e||null==e}getType(){return"boolean | undefined | null"}}const c=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/;class d{is(e){return"number"==typeof e||"string"==typeof e&&c.test(e)}getType(){return"date"}}class h extends o{constructor(){super(/^(\w|\.|-)+$/)}is(e){return super.is(e)&&"kind"!==e}}class f{static createTypeArray(e,t){return new s(e,t)}static numberWithMin(e){return new a(e)}static stringMatchingRegex(e){return new o(e)}}function g(e){return"kind"in e&&(f.String.is(e.kind)&&"multi"!==e.kind)}function v(e){return"kind"in e&&(f.String.is(e.kind)&&"multi"===e.kind)}function _(e){return!("kind"in e)||null===e.kind||void 0===e.kind}f.String=new n("string",""),f.Number=new n("number",0),f.ObjectOrFactory=new r,f.Object=new n("object",{}),f.StringArray=new s("string[]",""),f.Boolean=new n("boolean",!0),f.Function=new l,f.Date=new d,f.Kind=new h,f.NullableBoolean=new u;const p="user";function y(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}function m(e){return f.Kind.is(e)}function b(e){return f.String.is(e)&&""!==e}function w(e,t=!1){return e?e.map((e=>new i(e,t))):[]}class S{constructor(e,t,i){this._isMulti=!1,this._isUser=!1,this._wasLegacy=!1,this._contexts={},this.kind=t,this.valid=e,this.message=i}static _contextForError(e,t){return new S(!1,e,t)}static _getValueFromContext(e,t){if(t&&e.isValid)return 1===e.depth&&"anonymous"===e.getComponent(0)?!!t?.anonymous:e.get(t)}_contextForKind(e){return this._isMulti?this._contexts[e]:this.kind===e?this._context:void 0}static _fromMultiKindContext(e){const t=Object.keys(e).filter((e=>"kind"!==e)),i=t.every(m);if(!t.length)return S._contextForError("multi","A multi-kind context must contain at least one kind");if(!i)return S._contextForError("multi","Context contains invalid kinds");const r={};let n=!0;const s=t.reduce(((t,i)=>{const s=e[i];var a;return(a=s)&&f.Object.is(a)?(t[i]=s,r[i]=w(s._meta?.privateAttributes)):n=!1,t}),{});if(!n)return S._contextForError("multi","Context contained contexts that were not objects");if(!Object.values(s).every((e=>b(e.key))))return S._contextForError("multi","Context contained invalid keys");if(1===t.length){const e=t[0],i=new S(!0,e);return i._context={...s[e],kind:e},i._privateAttributeReferences=r,i._isUser="user"===e,i}const a=new S(!0,e.kind);return a._contexts=s,a._privateAttributeReferences=r,a._isMulti=!0,a}static _fromSingleKindContext(e){const{key:t,kind:i}=e,r=m(i),n=b(t);if(!r)return S._contextForError(i??"unknown","The kind was not valid for the context");if(!n)return S._contextForError(i,"The key for the context was not valid");const s=w(e._meta?.privateAttributes),a=new S(!0,i);return a._isUser="user"===i,a._context=e,a._privateAttributeReferences={[i]:s},a}static _fromLegacyUser(e){if(!(void 0!==e.key&&null!==e.key))return S._contextForError("user","The key for the context was not valid");const t=new S(!0,"user");return t._isUser=!0,t._wasLegacy=!0,t._context=function(e){const t={...e.custom||[],kind:"user",key:String(e.key)};if(null!=e.anonymous){const i=!!e.anonymous;delete t.anonymous,t.anonymous=i}return null!==e.name&&void 0!==e.name&&(t.name=e.name),null!==e.ip&&void 0!==e.ip&&(t.ip=e.ip),null!==e.firstName&&void 0!==e.firstName&&(t.firstName=e.firstName),null!==e.lastName&&void 0!==e.lastName&&(t.lastName=e.lastName),null!==e.email&&void 0!==e.email&&(t.email=e.email),null!==e.avatar&&void 0!==e.avatar&&(t.avatar=e.avatar),null!==e.country&&void 0!==e.country&&(t.country=e.country),null!==e.privateAttributeNames&&void 0!==e.privateAttributeNames&&(t._meta={privateAttributes:e.privateAttributeNames}),t}(e),t._privateAttributeReferences={user:w(e.privateAttributeNames,!0)},t}static fromLDContext(e){return e?g(e)?S._fromSingleKindContext(e):v(e)?S._fromMultiKindContext(e):_(e)?S._fromLegacyUser(e):S._contextForError("unknown","Context was not of a valid kind"):S._contextForError("unknown","No context specified. Returning default value")}static toLDContext(e){if(!e.valid)return;const t=e.getContexts();if(!e._isMulti)return t[0][1];const i={kind:"multi"};return t.forEach((e=>{const t=e[0],r=e[1];i[t]=r})),i}valueForKind(e,t=p){return e.isKind?this.kinds:S._getValueFromContext(e,this._contextForKind(t))}key(e=p){return this._contextForKind(e)?.key}get isMultiKind(){return this._isMulti}get canonicalKey(){return this._isUser?this._context.key:this._isMulti?Object.keys(this._contexts).sort().map((e=>`${e}:${y(this._contexts[e].key)}`)).join(":"):`${this.kind}:${y(this._context.key)}`}get kinds(){return this._isMulti?Object.keys(this._contexts):[this.kind]}get kindsAndKeys(){return this._isMulti?Object.entries(this._contexts).reduce(((e,[t,i])=>(e[t]=i.key,e)),{}):{[this.kind]:this._context.key}}privateAttributes(e){return this._privateAttributeReferences?.[e]||[]}getContexts(){return this._isMulti?Object.entries(this._contexts):[[this.kind,this._context]]}get legacy(){return this._wasLegacy}}S.UserKind=p;const k=["key","kind","_meta","anonymous"].map((e=>new i(e,!0))),E=["name","ip","firstName","lastName","email","avatar","country"];class O{constructor(e,t){this._allAttributesPrivate=e,this._privateAttributes=t}filter(e,t=!1){const i=e.getContexts();if(1===i.length)return this._filterSingleKind(e,i[0][1],i[0][0],t);const r={kind:"multi"};return i.forEach((([i,n])=>{r[i]=this._filterSingleKind(e,n,i,t)})),r}_getAttributesToFilter(e,t,r,n){return(n?Object.keys(t).map((e=>new i(e,!0))):[...this._privateAttributes,...e.privateAttributes(r)]).filter((e=>!k.some((t=>t.compare(e)))))}_filterSingleKind(e,t,i,r){const n=this._allAttributesPrivate||r&&!0===t.anonymous,{cloned:s,excluded:a}=function(e,t){const i=[],r={},n=[];for(i.push(...Object.keys(e).map((t=>({key:t,ptr:[t],source:e,parent:r,visited:[e]}))));i.length;){const e=i.pop(),r=t.find((t=>{return i=t,r=e.ptr,i.depth===r.length&&r.every(((e,t)=>e===i.getComponent(t)));var i,r}));if(r)n.push(r.redactionName);else{const t=e.source[e.key];null===t?e.parent[e.key]=t:Array.isArray(t)?e.parent[e.key]=[...t]:"object"==typeof t?e.visited.includes(t)||(e.parent[e.key]={},i.push(...Object.keys(t).map((i=>({key:i,ptr:[...e.ptr,i],source:t,parent:e.parent[e.key],visited:[...e.visited,t]}))))):e.parent[e.key]=t}}return{cloned:r,excluded:n.sort()}}(t,this._getAttributesToFilter(e,t,i,n));return e.legacy&&E.forEach((e=>{e in s&&(s[e]=String(s[e]))})),a.length&&(s._meta||(s._meta={}),s._meta.redactedAttributes=a),s._meta&&(delete s._meta.privateAttributes,0===Object.keys(s._meta).length&&delete s._meta),s}}var x,D,M,P;e.DataSourceErrorKind=void 0,(x=e.DataSourceErrorKind||(e.DataSourceErrorKind={})).Unknown="UNKNOWN",x.NetworkError="NETWORK_ERROR",x.ErrorResponse="ERROR_RESPONSE",x.InvalidData="INVALID_DATA";class T extends Error{constructor(e){super(e),this.name="LaunchDarklyFileDataSourceError"}}class C extends Error{constructor(e,t,i,r=!0){super(t),this.kind=e,this.status=i,this.name="LaunchDarklyPollingError",this.recoverable=r}}class F extends Error{constructor(e,t,i,r=!0){super(t),this.kind=e,this.code=i,this.name="LaunchDarklyStreamingError",this.recoverable=r}}e.AutoEnvAttributes=void 0,(D=e.AutoEnvAttributes||(e.AutoEnvAttributes={}))[D.Disabled=0]="Disabled",D[D.Enabled=1]="Enabled",function(e){e[e.AnalyticsEvents=0]="AnalyticsEvents",e[e.DiagnosticEvent=1]="DiagnosticEvent"}(M||(M={})),function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.FailedAndMustShutDown=2]="FailedAndMustShutDown"}(P||(P={}));var j=Object.freeze({__proto__:null,get LDDeliveryStatus(){return P},get LDEventType(){return M}});function I(e){if("string"==typeof e)return e;if(void 0===e)return"undefined";if(null===e)return"null";if(Object.prototype.hasOwnProperty.call(e,"toString"))try{return e.toString()}catch{}if("bigint"==typeof e)return`${e}n`;try{return JSON.stringify(e)}catch(e){return e instanceof TypeError&&e.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}const R={s:e=>I(e),d:e=>function(e){return"symbol"==typeof e?"NaN":"bigint"==typeof e?`${e}n`:String(Number(e))}(e),i:e=>function(e){return"symbol"==typeof e?"NaN":"bigint"==typeof e?`${e}n`:String(parseInt(e,10))}(e),f:e=>function(e){return"symbol"==typeof e?"NaN":String(parseFloat(e))}(e),j:e=>I(e),o:e=>I(e),O:e=>I(e),c:()=>""};function A(...e){const t=e.shift();if(f.String.is(t)){let i="",r=0;for(;r<t.length;){const n=t.charAt(r);if("%"===n){if(r+1<t.length){const n=t.charAt(r+1);if(n in R&&e.length){const t=e.shift();i+=R[n]?.(t)}else i+="%"===n?"%":`%${n}`;r+=2}}else i+=n,r+=1}return e.length&&(i.length&&(i+=" "),i+=e.map(I).join(" ")),i}return e.map(I).join(" ")}var V;!function(e){e[e.debug=0]="debug",e[e.info=1]="info",e[e.warn=2]="warn",e[e.error=3]="error",e[e.none=4]="none"}(V||(V={}));const N=["debug","info","warn","error","none"];class L{static get(){return new L({})}constructor(e){if(this._logLevel=V[e.level??"info"]??V.info,this._name=e.name??"LaunchDarkly",this._formatter=e.formatter,"object"==typeof e.destination)this._destinations={[V.debug]:e.destination.debug,[V.info]:e.destination.info,[V.warn]:e.destination.warn,[V.error]:e.destination.error};else if("function"==typeof e.destination){const{destination:t}=e;this._destinations={[V.debug]:t,[V.info]:t,[V.warn]:t,[V.error]:t}}}_tryFormat(...e){try{return this._formatter?this._formatter?.(...e):A(...e)}catch{return A(...e)}}_tryWrite(e,t){try{e(t)}catch{console.error(t)}}_log(e,t){if(e>=this._logLevel){const i=`${N[e]}: [${this._name}]`;try{const r=this._destinations?.[e];r?this._tryWrite(r,`${i} ${this._tryFormat(...t)}`):console.error(...t)}catch{console.error(...t)}}}error(...e){this._log(V.error,e)}warn(...e){this._log(V.warn,e)}info(...e){this._log(V.info,e)}debug(...e){this._log(V.debug,e)}}const K={error:f.Function,warn:f.Function,info:f.Function,debug:f.Function};class ${constructor(e,t){Object.entries(K).forEach((([t,i])=>{if(!i.is(e[t]))throw new Error(`Provided logger instance must support logger.${t}(...) method`)})),this._logger=e,this._fallback=t}_log(e,t){try{this._logger[e](...t)}catch{this._fallback[e](...t)}}error(...e){this._log("error",e)}warn(...e){this._log("warn",e)}info(...e){this._log("info",e)}debug(...e){this._log("debug",e)}}class U{static deprecated(e,t){return`"${e}" is deprecated, please use "${t}"`}static optionBelowMinimum(e,t,i){return`Config option "${e}" had invalid value of ${t}, using minimum of ${i} instead`}static unknownOption(e){return`Ignoring unknown config option "${e}"`}static wrongOptionType(e,t,i){return`Config option "${e}" should be of type ${t}, got ${i}, using default value`}static wrongOptionTypeBoolean(e,t){return`Config option "${e}" should be a boolean, got ${t}, converting to boolean`}static invalidTagValue(e){return`Config option "${e}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(e){return`Value of "${e}" was longer than 64 characters and was discarded.`}static partialEndpoint(e){return`You have set custom uris without specifying the ${e} URI; connections may not work properly`}}const z=f.stringMatchingRegex(/^(\w|\.|-)+$/),B=(e,t)=>z.is(e)?e.length>64?{valid:!1,message:U.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:U.invalidTagValue(t)};function q(e){return e.replace(/\/+$/,"")}function H(e){return e.replace(/^\/+/,"").replace(/\?$/,"")}class W{constructor(e,t,i=W.DEFAULT_EVENTS,r="/bulk",n="/diagnostic",s=!0,a){this.streaming=q(e),this.polling=q(t),this.events=q(i),this.analyticsEventPath=r,this.diagnosticEventPath=n,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}}function J(e,t){if(0===t.length)return e;return`${e}?${t.map((({key:e,value:t})=>`${e}=${t}`)).join("&")}`}function G(e,t,i){const r=H(t);return J(`${e.events}/${r}`,i)}W.DEFAULT_EVENTS="https://events.launchdarkly.com";class X extends Error{constructor(e){super(e),this.name="LaunchDarklyUnexpectedResponseError"}}class Y extends Error{constructor(e){super(e),this.name="LaunchDarklyClientError"}}class Q extends Error{constructor(e){super(e),this.name="LaunchDarklyTimeoutError"}}function Z(e){return!(e>=400&&e<500)||(400===e||408===e||429===e)}function ee(e){return 413===e||Z(e)}const te=(e,t)=>e?Object.entries(e).reduce(((e,[i,r])=>(!Boolean(r)||(e=>"{}"===JSON.stringify(e))(r)||t?.includes(i)||(e[i]="object"==typeof r?te(r,t):r),e)),{}):e;function ie(e,t,i){let r;r=e.status?`error ${e.status}${401===e.status?" (invalid SDK key)":""}`:`I/O error (${e.message||"unknown error"})`;return`Received ${r} for ${t} - ${i??"giving up permanently"}`}const re=async(e=1e3)=>new Promise((t=>{setTimeout(t,e)}));var ne;!function(e){e.MalformedFlag="MALFORMED_FLAG",e.UserNotSpecified="USER_NOT_SPECIFIED",e.FlagNotFound="FLAG_NOT_FOUND",e.ClientNotReady="CLIENT_NOT_READY",e.WrongType="WRONG_TYPE"}(ne||(ne={}));var se=ne;class ae{static invalidMetricValue(e){return`The track function was called with a non-numeric "metricValue" (${e}), only numeric metric values are supported.`}}ae.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";class oe{constructor(e,t){const{basicConfiguration:i,platform:r}=e,{serviceEndpoints:{analyticsEventPath:n,diagnosticEventPath:s}}=i,{crypto:a,requests:o}=r;this._defaultHeaders={...t},this._eventsUri=G(i.serviceEndpoints,n,[]),this._diagnosticEventsUri=G(i.serviceEndpoints,s,[]),this._requests=o,this._crypto=a}async _tryPostingEvents(e,t,i,r){const n={status:P.Succeeded},s={...this._defaultHeaders,"content-type":"application/json"};let a;i&&(s["x-launchdarkly-payload-id"]=i,s["x-launchDarkly-event-schema"]="4");try{const{status:i,headers:r}=await this._requests.fetch(t,{headers:s,body:JSON.stringify(e),method:"POST",keepalive:!0}),o=Date.parse(r.get("date")||"");if(o&&(n.serverTime=o),i<=204)return n;if(a=new X(ie({status:i,message:"some events were dropped"},"event posting")),!Z(i))return ee(i)?n.status=P.Failed:n.status=P.FailedAndMustShutDown,n.error=a,n}catch(e){a=e}return a&&!r?(n.status=P.Failed,n.error=a,n):(await re(),this._tryPostingEvents(e,this._eventsUri,i,!1))}async sendEventData(e,t){const i=e===M.AnalyticsEvents?this._crypto.randomUUID():void 0,r=e===M.AnalyticsEvents?this._eventsUri:this._diagnosticEventsUri;return this._tryPostingEvents(t,r,i,!0)}}function le(e){return"feature"===e.kind}class ue{constructor(e,t,i,r,n,s){this.count=e,this.key=t,this.value=i,this.version=n,this.variation=s,this.default=r}increment(){this.count+=1}}class ce{constructor(){this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}summarizeEvent(e){if(le(e)&&!e.excludeFromSummaries){const t=function(e){return`${e.key}:${null!==e.variation&&void 0!==e.variation?e.variation:""}:${null!==e.version&&void 0!==e.version?e.version:""}`}(e),i=this._counters[t];let r=this._contextKinds[e.key];r||(r=new Set,this._contextKinds[e.key]=r),e.context.kinds.forEach((e=>r.add(e))),i?i.increment():this._counters[t]=new ue(1,e.key,e.value,e.default,e.version,e.variation),(0===this._startDate||e.creationDate<this._startDate)&&(this._startDate=e.creationDate),e.creationDate>this._endDate&&(this._endDate=e.creationDate)}}getSummary(){const e=Object.values(this._counters).reduce(((e,t)=>{let i=e[t.key];i||(i={default:t.default,counters:[],contextKinds:[...this._contextKinds[t.key]]},e[t.key]=i);const r={value:t.value,count:t.count};return void 0!==t.variation&&null!==t.variation&&(r.variation=t.variation),void 0!==t.version&&null!==t.version?r.version=t.version:r.unknown=!0,i.counters.push(r),e}),{});return{startDate:this._startDate,endDate:this._endDate,features:e,kind:"summary"}}clearSummary(){this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}}class de extends Error{constructor(e){super(e),this.name="LaunchDarklyInvalidSDKKeyError"}}function he(e){const t=Math.trunc(e);return 1===t||0!==t&&0===Math.floor(Math.random()*t)}class fe{constructor(e,t,i,r,n=1,s){this.context=e,this.key=t,this.data=i,this.metricValue=r,this.samplingRatio=n,this.url=s,this.kind="custom",this.creationDate=Date.now(),this.context=e}}class ge{constructor(e,t,i,r,n,s,a,o,l,u,c,d,h=1){this.withReasons=e,this.context=t,this.key=i,this.samplingRatio=h,this.kind="feature",this.creationDate=Date.now(),this.value=r,this.default=n,void 0!==s&&(this.version=s),void 0!==a&&(this.variation=a),void 0!==o&&(this.trackEvents=o),void 0!==l&&(this.prereqOf=l),void 0!==u&&(this.reason=u),void 0!==c&&(this.debugEventsUntilDate=c),void 0!==d&&(this.excludeFromSummaries=d)}}class ve{constructor(e,t=1){this.context=e,this.samplingRatio=t,this.kind="identify",this.creationDate=Date.now()}}var _e=Object.freeze({__proto__:null,ClientMessages:ae,DiagnosticsManager:class{constructor(e,t,i){this._platform=t,this._diagnosticInitConfig=i,this._streamInits=[],this._startTime=Date.now(),this._dataSinceDate=this._startTime,this._id={diagnosticId:t.crypto.randomUUID(),sdkKeySuffix:e.length>6?e.substring(e.length-6):e}}createInitEvent(){const e=this._platform.info.sdkData(),t=this._platform.info.platformData();return{kind:"diagnostic-init",id:this._id,creationDate:this._startTime,sdk:e,configuration:this._diagnosticInitConfig,platform:{name:t.name,osArch:t.os?.arch,osName:t.os?.name,osVersion:t.os?.version,...t.additional||{}}}}recordStreamInit(e,t,i){const r={timestamp:e,failed:t,durationMillis:i};this._streamInits.push(r)}createStatsEventAndReset(e,t,i){const r=Date.now(),n={kind:"diagnostic",id:this._id,creationDate:r,dataSinceDate:this._dataSinceDate,droppedEvents:e,deduplicatedUsers:t,eventsInLastBatch:i,streamInits:this._streamInits};return this._streamInits=[],this._dataSinceDate=r,n}},ErrorKinds:se,EventFactoryBase:class{constructor(e){this._withReasons=e}evalEvent(e){return new ge(this._withReasons,e.context,e.flagKey,e.value,e.defaultVal,e.version,e.variation??void 0,e.trackEvents||e.addExperimentData,e.prereqOfFlagKey,this._withReasons||e.addExperimentData?e.reason:void 0,e.debugEventsUntilDate,e.excludeFromSummaries,e.samplingRatio)}unknownFlagEvent(e,t,i){return new ge(this._withReasons,i,e,t,t,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(e){return new ve(e,1)}customEvent(e,t,i,r,n=1){return new fe(t,e,i??void 0,r??void 0,n)}},EventProcessor:class{constructor(e,t,r,n,s,a=!0){this._config=e,this._contextDeduplicator=n,this._diagnosticsManager=s,this._summarizer=new ce,this._queue=[],this._lastKnownPastTime=0,this._droppedEvents=0,this._deduplicatedUsers=0,this._exceededCapacity=!1,this._eventsInLastBatch=0,this._shutdown=!1,this._flushUsersTimer=null,this._capacity=e.eventsCapacity,this._logger=t.basicConfiguration.logger,this._eventSender=new oe(t,r),this._contextFilter=new O(e.allAttributesPrivate,e.privateAttributes.map((e=>new i(e)))),a&&this.start()}start(){if(void 0!==this._contextDeduplicator?.flushInterval&&(this._flushUsersTimer=setInterval((()=>{this._contextDeduplicator?.flush()}),1e3*this._contextDeduplicator.flushInterval)),this._flushTimer=setInterval((async()=>{try{await this.flush()}catch(e){this._logger?.debug(`Flush failed: ${e}`)}}),1e3*this._config.flushInterval),this._diagnosticsManager){const e=this._diagnosticsManager.createInitEvent();this._postDiagnosticEvent(e),this._diagnosticsTimer=setInterval((()=>{const e=this._diagnosticsManager.createStatsEventAndReset(this._droppedEvents,this._deduplicatedUsers,this._eventsInLastBatch);this._droppedEvents=0,this._deduplicatedUsers=0,this._postDiagnosticEvent(e)}),1e3*this._config.diagnosticRecordingInterval)}this._logger?.debug("Started EventProcessor.")}_postDiagnosticEvent(e){this._eventSender.sendEventData(M.DiagnosticEvent,e)}close(){clearInterval(this._flushTimer),this._flushUsersTimer&&clearInterval(this._flushUsersTimer),this._diagnosticsTimer&&clearInterval(this._diagnosticsTimer)}async flush(){if(this._shutdown)throw new de("Events cannot be posted because a permanent error has been encountered. This is most likely an invalid SDK key. The specific error information is logged independently.");const e=this._queue;this._queue=[];const t=this._summarizer.getSummary();this._summarizer.clearSummary(),Object.keys(t.features).length&&e.push(t),e.length&&(this._eventsInLastBatch=e.length,this._logger?.debug("Flushing %d events",e.length),await this._tryPostingEvents(e))}sendEvent(e){if(this._shutdown)return;if("migration_op"===e.kind){if(he(e.samplingRatio)){const t={...e};1===t.samplingRatio&&delete t.samplingRatio,this._enqueue(t)}return}this._summarizer.summarizeEvent(e);const t=le(e),i=t&&e.trackEvents||!t,r=this._shouldDebugEvent(e),n=function(e){return"identify"===e.kind}(e),s=this._contextDeduplicator?.processContext(e.context);s||n||(this._deduplicatedUsers+=1);s&&!n&&this._enqueue(this._makeOutputEvent({kind:"index",creationDate:e.creationDate,context:e.context,samplingRatio:1},!1)),i&&he(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!1)),r&&he(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!0))}_makeOutputEvent(e,t){switch(e.kind){case"feature":{const i={kind:t?"debug":"feature",creationDate:e.creationDate,context:this._contextFilter.filter(e.context,!t),key:e.key,value:e.value,default:e.default};return 1!==e.samplingRatio&&(i.samplingRatio=e.samplingRatio),e.prereqOf&&(i.prereqOf=e.prereqOf),void 0!==e.variation&&(i.variation=e.variation),void 0!==e.version&&(i.version=e.version),e.reason&&(i.reason=e.reason),i}case"index":case"identify":{const t={kind:e.kind,creationDate:e.creationDate,context:this._contextFilter.filter(e.context)};return 1!==e.samplingRatio&&(t.samplingRatio=e.samplingRatio),t}case"custom":{const t={kind:"custom",creationDate:e.creationDate,key:e.key,contextKeys:e.context.kindsAndKeys};return 1!==e.samplingRatio&&(t.samplingRatio=e.samplingRatio),void 0!==e.data&&(t.data=e.data),void 0!==e.metricValue&&(t.metricValue=e.metricValue),void 0!==e.url&&(t.url=e.url),t}case"click":return{kind:"click",creationDate:e.creationDate,contextKeys:e.context.kindsAndKeys,key:e.key,url:e.url,selector:e.selector};case"pageview":return{kind:"pageview",creationDate:e.creationDate,contextKeys:e.context.kindsAndKeys,key:e.key,url:e.url};default:return e}}_enqueue(e){this._queue.length<this._capacity?(this._queue.push(e),this._exceededCapacity=!1):(this._exceededCapacity||(this._exceededCapacity=!0,this._logger?.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this._droppedEvents+=1)}_shouldDebugEvent(e){return le(e)&&e.debugEventsUntilDate&&e.debugEventsUntilDate>this._lastKnownPastTime&&e.debugEventsUntilDate>Date.now()}async _tryPostingEvents(e){const t=await this._eventSender.sendEventData(M.AnalyticsEvents,e);if(t.status===P.FailedAndMustShutDown&&(this._shutdown=!0),t.serverTime&&(this._lastKnownPastTime=t.serverTime),t.error)throw t.error}},InputCustomEvent:fe,InputEvalEvent:ge,InputIdentifyEvent:ve,NullEventProcessor:class{close(){}async flush(){}sendEvent(){}},isLegacyUser:_,isMultiKind:v,isSingleKind:g,shouldSample:he});e.ApplicationTags=class{constructor(e){const t={},i=e?.application,r=e?.logger;i&&Object.entries(i).forEach((([e,i])=>{if(null!=i){const{valid:n,message:s}=B(i,`application.${e}`);n?"versionName"===e?t["application-version-name"]=[i]:t[`application-${e}`]=[i]:r?.warn(s)}}));const n=Object.keys(t);n.length&&(this.value=n.sort().flatMap((e=>t[e].sort().map((t=>`${e}/${t}`)))).join(" "))}},e.AttributeReference=i,e.BasicLogger=L,e.ClientContext=class{constructor(e,t,i){this.platform=i,this.basicConfiguration={tags:t.tags,logger:t.logger,offline:t.offline,serviceEndpoints:t.serviceEndpoints,sdkKey:e}}},e.Context=S,e.ContextFilter=O,e.DateValidator=d,e.FactoryOrInstance=r,e.Function=l,e.KindValidator=h,e.LDClientError=Y,e.LDFileDataSourceError=T,e.LDPollingError=C,e.LDStreamingError=F,e.LDTimeoutError=Q,e.LDUnexpectedResponseError=X,e.NullableBoolean=u,e.NumberWithMinimum=a,e.OptionMessages=U,e.SafeLogger=$,e.ServiceEndpoints=W,e.StringMatchingRegex=o,e.Type=n,e.TypeArray=s,e.TypeValidators=f,e.base64UrlEncode=(e,t)=>t.btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.cancelableTimedPromise=function(e,t){let i,r;return{promise:new Promise(((n,s)=>{r=n,i=setTimeout((()=>{s(new Q(`${t} timed out after ${e} seconds.`))}),1e3*e)})),cancel:()=>{r(),clearTimeout(i)}}},e.clone=function(e){return null==e?e:JSON.parse(JSON.stringify(e))},e.createSafeLogger=e=>{const t=new L({level:"info",destination:console.error,formatter:A});return e?new $(e,t):t},e.debounce=(e,t=5e3)=>{let i;return(...r)=>{clearTimeout(i),i=setTimeout((()=>{e(...r)}),t)}},e.deepCompact=te,e.defaultHeaders=function(e,t,i,r=!0,n="user-agent"){const{userAgentBase:s,version:a,wrapperName:o,wrapperVersion:l}=t.sdkData(),u={[n]:`${s??"NodeJSClient"}/${a}`};return r&&(u.authorization=e),o&&(u["x-launchdarkly-wrapper"]=l?`${o}/${l}`:o),i?.value&&(u["x-launchdarkly-tags"]=i.value),u},e.fastDeepEqual=function e(t,i){if(t===i)return!0;if(t&&i&&"object"==typeof t&&"object"==typeof i){if(t.constructor!==i.constructor)return!1;var r,n,s;if(Array.isArray(t)){if((r=t.length)!=i.length)return!1;for(n=r;0!=n--;)if(!e(t[n],i[n]))return!1;return!0}if(t instanceof Map&&i instanceof Map){if(t.size!==i.size)return!1;for(n of t.entries())if(!i.has(n[0]))return!1;for(n of t.entries())if(!e(n[1],i.get(n[0])))return!1;return!0}if(t instanceof Set&&i instanceof Set){if(t.size!==i.size)return!1;for(n of t.entries())if(!i.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(i)){if((r=t.length)!=i.length)return!1;for(n=r;0!=n--;)if(t[n]!==i[n])return!1;return!0}if(t.constructor===RegExp)return t.source===i.source&&t.flags===i.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===i.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===i.toString();if((r=(s=Object.keys(t)).length)!==Object.keys(i).length)return!1;for(n=r;0!=n--;)if(!Object.prototype.hasOwnProperty.call(i,s[n]))return!1;for(n=r;0!=n--;){var a=s[n];if(!e(t[a],i[a]))return!1}return!0}return t!=t&&i!=i},e.getEventsUri=G,e.getPollingUri=function(e,t,i){const r=H(t),n=[...i];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),J(`${e.polling}/${r}`,n)},e.getStreamingUri=function(e,t,i){const r=H(t),n=[...i];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),J(`${e.streaming}/${r}`,n)},e.httpErrorMessage=ie,e.internal=_e,e.isHttpLocallyRecoverable=ee,e.isHttpRecoverable=Z,e.noop=()=>{},e.secondsToMillis=function(e){return Math.trunc(1e3*e)},e.shouldRetry=function({status:e}){return!e||Z(e)},e.sleep=re,e.subsystem=j,e.timedPromise=(e,t)=>new Promise(((i,r)=>{setTimeout((()=>{r(new Q(`${t} timed out after ${e} seconds.`))}),1e3*e)}))}(o);var l={},u={},c={};Object.defineProperty(c,"__esModule",{value:!0});var d={};Object.defineProperty(d,"__esModule",{value:!0});var h,f,g={};Object.defineProperty(g,"__esModule",{value:!0}),g.IsMigrationStage=g.LDMigrationStage=void 0,(f=h||(g.LDMigrationStage=h={})).Off="off",f.DualWrite="dualwrite",f.Shadow="shadow",f.Live="live",f.RampDown="rampdown",f.Complete="complete",g.IsMigrationStage=function(e){return Object.values(h).includes(e)};var v={};Object.defineProperty(v,"__esModule",{value:!0});var _,p,y,m,b,w={};Object.defineProperty(w,"__esModule",{value:!0}),w.LDConsistencyCheck=void 0,(p=_||(w.LDConsistencyCheck=_={}))[p.Inconsistent=0]="Inconsistent",p[p.Consistent=1]="Consistent",p[p.NotChecked=2]="NotChecked",y=u,m=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),b=r&&r.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||m(t,e,i)},Object.defineProperty(y,"__esModule",{value:!0}),b(c,y),b(d,y),b(g,y),b(v,y),b(w,y);var S={},k={};Object.defineProperty(k,"__esModule",{value:!0});var E={};Object.defineProperty(E,"__esModule",{value:!0});var O={};Object.defineProperty(O,"__esModule",{value:!0});var x={};Object.defineProperty(x,"__esModule",{value:!0});var D,M,P,T,C={};Object.defineProperty(C,"__esModule",{value:!0}),C.LDConcurrentExecution=C.LDSerialExecution=C.LDExecution=C.LDExecutionOrdering=void 0,(M=D||(C.LDExecutionOrdering=D={}))[M.Fixed=0]="Fixed",M[M.Random=1]="Random",(T=P||(C.LDExecution=P={}))[T.Serial=0]="Serial",T[T.Concurrent=1]="Concurrent";C.LDSerialExecution=class{constructor(e){this.ordering=e,this.type=P.Serial}};C.LDConcurrentExecution=class{constructor(){this.type=P.Concurrent}},function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(k,e),i(E,e),i(O,e),i(x,e),i(C,e)}(S);var F={};Object.defineProperty(F,"__esModule",{value:!0});var j={};Object.defineProperty(j,"__esModule",{value:!0});var I={};Object.defineProperty(I,"__esModule",{value:!0});var R={};Object.defineProperty(R,"__esModule",{value:!0});var A={};Object.defineProperty(A,"__esModule",{value:!0});var V={},N={};Object.defineProperty(N,"__esModule",{value:!0});var L={};Object.defineProperty(L,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(N,e),i(L,e)}(V);var K={},$={};Object.defineProperty($,"__esModule",{value:!0});var U={};Object.defineProperty(U,"__esModule",{value:!0});var z={};Object.defineProperty(z,"__esModule",{value:!0});var B={};Object.defineProperty(B,"__esModule",{value:!0});var q={};Object.defineProperty(q,"__esModule",{value:!0});var H={};Object.defineProperty(H,"__esModule",{value:!0});var W={};Object.defineProperty(W,"__esModule",{value:!0});var J={};Object.defineProperty(J,"__esModule",{value:!0});var G={};Object.defineProperty(G,"__esModule",{value:!0});var X={};Object.defineProperty(X,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i($,e),i(U,e),i(z,e),i(B,e),i(q,e),i(I,e),i(H,e),i(W,e),i(J,e),i(G,e),i(X,e)}(K);var Y={},Q={};Object.defineProperty(Q,"__esModule",{value:!0});var Z={};Object.defineProperty(Z,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(Q,e),i(R,e),i(Z,e)}(Y),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.subsystems=e.interfaces=e.integrations=void 0,i(u,e),i(S,e),i(F,e),i(j,e),i(I,e),i(R,e),i(A,e),e.integrations=V,e.interfaces=K,e.subsystems=Y}(l);var ee={},te={};Object.defineProperty(te,"__esModule",{value:!0});te.default=class{constructor(e){this._keyMap=new Map,this._head=0,this._tail=0,this._size=0;const{max:t}=e;this._max=t,this._values=new Array(t),this._keys=new Array(t),this._next=new Uint32Array(t),this._prev=new Uint32Array(t),e.maxAge?(this._lastUpdated=new Array(t).fill(0),this._maxAge=e.maxAge):(this._lastUpdated=[],this._maxAge=0)}set(e,t){let i=this._keyMap.get(e);void 0===i?(i=this._index(),this._keys[i]=e,this._keyMap.set(e,i),this._next[this._tail]=i,this._prev[i]=this._tail,this._tail=i,this._size+=1):this._setTail(i),this._values[i]=t,this._maxAge&&(this._lastUpdated[i]=Date.now())}get(e){const t=this._keyMap.get(e);if(void 0!==t){if(this._maxAge){const e=this._lastUpdated[t];if(Date.now()-e>this._maxAge)return}return this._setTail(t),this._maxAge&&(this._lastUpdated[t]=Date.now()),this._values[t]}}clear(){this._head=0,this._tail=0,this._size=0,this._values.fill(void 0),this._keys.fill(void 0),this._next.fill(0),this._prev.fill(0),this._keyMap.clear()}_index(){return 0===this._size?this._tail:this._size===this._max?this._evict():this._size}_evict(){const{_head:e}=this,t=this._keys[e];return this._head=this._next[e],this._keyMap.delete(t),this._size-=1,e}_link(e,t){this._prev[t]=e,this._next[e]=t}_setTail(e){e!==this._tail&&(e===this._head?this._head=this._next[e]:this._link(this._prev[e],this._next[e]),this._link(this._tail,e),this._tail=e)}},Object.defineProperty(ee,"__esModule",{value:!0});const ie=o,re=s,ne=te;ee.default=class{constructor(e,t,i,r){this._store=e,this._logger=i,this._crypto=r,this.statusProvider=new re.default((async()=>this._pollStoreAndUpdateStatus())),this._staleTimeMs=1e3*(ie.TypeValidators.Number.is(t.staleAfter)&&t.staleAfter>0?t.staleAfter:120);const n=1e3*(ie.TypeValidators.Number.is(t.statusPollInterval)&&t.statusPollInterval>0?t.statusPollInterval:5);this._pollHandle=e?setInterval((()=>this._pollStoreAndUpdateStatus()),n):null,e&&(this._cache=new ne.default({max:t.userCacheSize||1e3,maxAge:1e3*(t.userCacheTime||5)}))}close(){this._pollHandle&&(clearInterval(this._pollHandle),this._pollHandle=void 0),this._store&&this._store.close()}async getUserMembership(e){var t,i,r;if(!this._store)return;const n=null===(t=this._cache)||void 0===t?void 0:t.get(e);let s;if(n)s=n.membership;else try{s=await this._store.getUserMembership(this._hashForUserKey(e));const t={membership:s};null===(i=this._cache)||void 0===i||i.set(e,t)}catch(e){return null===(r=this._logger)||void 0===r||r.error(`Big Segment store membership query returned error: ${e}`),[null,"STORE_ERROR"]}this.statusProvider.getStatus()||await this._pollStoreAndUpdateStatus();const a=this.statusProvider.getStatus();return a.available?[s||null,a.stale?"STALE":"HEALTHY"]:[s||null,"STORE_ERROR"]}async _pollStoreAndUpdateStatus(){var e,t,i;if(!this._store)return void this.statusProvider.setStatus({available:!1,stale:!1});let r;null===(e=this._logger)||void 0===e||e.debug("Querying Big Segment store status");try{const e=await this._store.getMetadata();r={available:!0,stale:!e||!e.lastUpToDate||this._isStale(e.lastUpToDate)}}catch(e){null===(t=this._logger)||void 0===t||t.error(`Big Segment store status query returned error: ${e}`),r={available:!1,stale:!1}}const n=this.statusProvider.getStatus();n&&n.available===r.available&&n.stale===r.stale||(null===(i=this._logger)||void 0===i||i.debug("Big Segment store status changed from %s to %s",JSON.stringify(n),JSON.stringify(r)),this.statusProvider.setStatus(r),this.statusProvider.notify())}_hashForUserKey(e){const t=this._crypto.createHash("sha256");if(t.update(e),!t.digest)throw new Error("Platform must implement digest or asyncDigest");return t.digest("base64")}_isStale(e){return Date.now()-e>=this._staleTimeMs}};var se={},ae={},oe={};Object.defineProperty(oe,"__esModule",{value:!0});class le{static getKeyFromPath(e,t){return t.startsWith(e.streamApiPath)?t.substring(e.streamApiPath.length):void 0}}le.Features={namespace:"features",streamApiPath:"/flags/"},le.Segments={namespace:"segments",streamApiPath:"/segments/"},oe.default=le,Object.defineProperty(ae,"__esModule",{value:!0}),ae.deserializeSegment=ae.serializeSegment=ae.deserializeFlag=ae.serializeFlag=ae.deserializeDelete=ae.deserializePatch=ae.deserializePoll=ae.deserializeAll=ae.processSegment=ae.processFlag=ae.replacer=ae.nullReplacer=void 0;const ue=o,ce=oe,de=100;function he(e,t){const i=[];if(null==e)return;const r=Object.entries(e).filter((([e,i])=>!(null==t?void 0:t.includes(e))));for(i.push(...r.map((([t,i])=>({key:t,value:i,parent:e}))));i.length;){const e=i.pop();null!==e.value||Array.isArray(e.parent)?"object"==typeof e.value&&null!==e.value&&i.push(...Object.entries(e.value).map((([t,i])=>({key:t,value:i,parent:e.value})))):delete e.parent[e.key]}}function fe(e,t){if(!(t instanceof ue.AttributeReference||Array.isArray(t)&&t[0]&&t[0]instanceof ue.AttributeReference))return null==t||(t.generated_includedSet&&(t.included=[...t.generated_includedSet],delete t.generated_includedSet),t.generated_excludedSet&&(t.excluded=[...t.generated_excludedSet],delete t.generated_excludedSet),t.includedContexts&&t.includedContexts.forEach((e=>{e.generated_valuesSet&&(e.values=[...e.generated_valuesSet]),delete e.generated_valuesSet})),t.excludedContexts&&t.excludedContexts.forEach((e=>{e.generated_valuesSet&&(e.values=[...e.generated_valuesSet]),delete e.generated_valuesSet}))),t}function ge(e){e&&e.bucketBy&&(e.bucketByAttributeReference=new ue.AttributeReference(e.bucketBy,!e.contextKind))}function ve(e){var t;if(he(e,["variations"]),e.fallthrough&&e.fallthrough.rollout){ge(e.fallthrough.rollout)}null===(t=null==e?void 0:e.rules)||void 0===t||t.forEach((e=>{var t;ge(e.rollout),null===(t=null==e?void 0:e.clauses)||void 0===t||t.forEach((e=>{e&&e.attribute?e.attributeReference=new ue.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ue.AttributeReference.InvalidReference)}))}))}function _e(e){var t,i,r,n,s;he(e),(null===(t=null==e?void 0:e.included)||void 0===t?void 0:t.length)&&e.included.length>de&&(e.generated_includedSet=new Set(e.included),delete e.included),(null===(i=null==e?void 0:e.excluded)||void 0===i?void 0:i.length)&&e.excluded.length>de&&(e.generated_excludedSet=new Set(e.excluded),delete e.excluded),(null===(r=null==e?void 0:e.includedContexts)||void 0===r?void 0:r.length)&&e.includedContexts.forEach((e=>{var t;(null===(t=null==e?void 0:e.values)||void 0===t?void 0:t.length)&&e.values.length>de&&(e.generated_valuesSet=new Set(e.values),e.values=[])})),(null===(n=null==e?void 0:e.excludedContexts)||void 0===n?void 0:n.length)&&e.excludedContexts.forEach((e=>{var t;(null===(t=null==e?void 0:e.values)||void 0===t?void 0:t.length)&&e.values.length>de&&(e.generated_valuesSet=new Set(e.values),e.values=[])})),null===(s=null==e?void 0:e.rules)||void 0===s||s.forEach((e=>{var t;e.bucketBy&&(e.bucketByAttributeReference=new ue.AttributeReference(e.bucketBy,!e.rolloutContextKind)),null===(t=null==e?void 0:e.clauses)||void 0===t||t.forEach((e=>{e&&e.attribute?e.attributeReference=new ue.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ue.AttributeReference.InvalidReference)}))}))}function pe(e){try{return JSON.parse(e)}catch(e){return}}ae.nullReplacer=he,ae.replacer=fe,ae.processFlag=ve,ae.processSegment=_e,ae.deserializeAll=function(e){var t,i;const r=pe(e);if(r)return Object.values((null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.flags)||[]).forEach((e=>{ve(e)})),Object.values((null===(i=null==r?void 0:r.data)||void 0===i?void 0:i.segments)||[]).forEach((e=>{_e(e)})),r},ae.deserializePoll=function(e){const t=pe(e);if(t)return Object.values((null==t?void 0:t.flags)||[]).forEach((e=>{ve(e)})),Object.values((null==t?void 0:t.segments)||[]).forEach((e=>{_e(e)})),t},ae.deserializePatch=function(e){const t=pe(e);if(t)return t.path.startsWith(ce.default.Features.streamApiPath)?(ve(t.data),t.kind=ce.default.Features):t.path.startsWith(ce.default.Segments.streamApiPath)&&(_e(t.data),t.kind=ce.default.Segments),t},ae.deserializeDelete=function(e){const t=pe(e);if(t)return t.path.startsWith(ce.default.Features.streamApiPath)?t.kind=ce.default.Features:t.path.startsWith(ce.default.Segments.streamApiPath)&&(t.kind=ce.default.Segments),t},ae.serializeFlag=function(e){return JSON.stringify(e,fe)},ae.deserializeFlag=function(e){const t=pe(e);if(t)return ve(t),t},ae.serializeSegment=function(e){return JSON.stringify(e,fe)},ae.deserializeSegment=function(e){const t=pe(e);if(t)return _e(t),t},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createStreamListeners=e.createDeleteListener=e.createPatchListener=e.createPutListener=void 0;const t=ae,i=oe;e.createPutListener=(e,r,n=()=>{})=>({deserializeData:t.deserializeAll,processJson:async({data:{flags:t,segments:s}})=>{const a={[i.default.Features.namespace]:t,[i.default.Segments.namespace]:s};null==r||r.debug("Initializing all data"),e.init(a,n)}});e.createPatchListener=(e,r,n=()=>{})=>({deserializeData:t.deserializePatch,processJson:async({data:t,kind:s,path:a})=>{if(s){const o=i.default.getKeyFromPath(s,a);o&&(null==r||r.debug(`Updating ${o} in ${s.namespace}`),e.upsert(s,t,n))}}});e.createDeleteListener=(e,r,n=()=>{})=>({deserializeData:t.deserializeDelete,processJson:async({kind:t,path:s,version:a})=>{if(t){const o=i.default.getKeyFromPath(t,s);o&&(null==r||r.debug(`Deleting ${o} in ${t.namespace}`),e.upsert(t,{key:o,version:a,deleted:!0},n))}}});e.createStreamListeners=(t,i,r)=>{const n=new Map;return n.set("put",(0,e.createPutListener)(t,i,null==r?void 0:r.put)),n.set("patch",(0,e.createPatchListener)(t,i,null==r?void 0:r.patch)),n.set("delete",(0,e.createDeleteListener)(t,i,null==r?void 0:r.delete)),n}}(se);var ye={},me={},be={};Object.defineProperty(be,"__esModule",{value:!0});be.default=class{constructor(){this._itemsByNamespace={}}get(e,t){var i;return null===(i=this._itemsByNamespace[e])||void 0===i?void 0:i[t]}set(e,t,i){e in this._itemsByNamespace||(this._itemsByNamespace[e]={}),this._itemsByNamespace[e][t]=i}remove(e,t){const i=this._itemsByNamespace[e];i&&delete i[t]}removeAll(){this._itemsByNamespace={}}enumerate(e){Object.entries(this._itemsByNamespace).forEach((([t,i])=>{Object.entries(i).forEach((([i,r])=>{e(t,i,r)}))}))}mergeFrom(e){e.enumerate(this.set.bind(this))}},Object.defineProperty(me,"__esModule",{value:!0});const we=be;me.default=class{constructor(){this._dependenciesFrom=new we.default,this._dependenciesTo=new we.default}updateDependenciesFrom(e,t,i){const r=this._dependenciesFrom.get(e,t);null==r||r.enumerate(((i,r)=>{const n=this._dependenciesTo.get(i,r);null==n||n.remove(e,t)})),this._dependenciesFrom.set(e,t,i),null==i||i.enumerate(((i,r)=>{let n=this._dependenciesTo.get(i,r);n||(n=new we.default,this._dependenciesTo.set(i,r,n)),n.set(e,t,!0)}))}updateModifiedItems(e,t,i){if(!e.get(t,i)){e.set(t,i,!0);const r=this._dependenciesTo.get(t,i);null==r||r.enumerate(((t,i)=>{this.updateModifiedItems(e,t,i)}))}}reset(){this._dependenciesFrom.removeAll(),this._dependenciesTo.removeAll()}},Object.defineProperty(ye,"__esModule",{value:!0});const Se=oe,ke=me,Ee=be;function Oe(e,t){var i,r;const n=new Ee.default,s=e===Se.default.Features.namespace,a=e===Se.default.Segments.namespace;if(s){const r=t;null===(i=null==r?void 0:r.prerequisites)||void 0===i||i.forEach((t=>{n.set(e,t.key,!0)}))}if(s||a){const e=t;null===(r=null==e?void 0:e.rules)||void 0===r||r.forEach((e=>{var t;null===(t=e.clauses)||void 0===t||t.forEach((e=>{"segmentMatch"===e.op&&e.values.forEach((e=>{n.set(Se.default.Segments.namespace,e,!0)}))}))}))}return n}ye.default=class{constructor(e,t,i){this._featureStore=e,this._hasEventListeners=t,this._onChange=i,this._dependencyTracker=new ke.default}init(e,t){const i=this._hasEventListeners(),r=r=>{this._featureStore.init(e,(()=>{Promise.resolve().then((()=>{if(this._dependencyTracker.reset(),Object.entries(e).forEach((([e,t])=>{Object.keys(t||{}).forEach((i=>{const r=t[i];this._dependencyTracker.updateDependenciesFrom(e,i,Oe(e,r))}))})),i){const t=new Ee.default;Object.keys(e).forEach((i=>{const n=(null==r?void 0:r[i])||{},s=e[i],a=Object.assign(Object.assign({},n),s);Object.keys(a).forEach((e=>{this.addIfModified(i,e,n&&n[e],s&&s[e],t)}))})),this.sendChangeEvents(t)}})),null==t||t()}))};i?this._featureStore.all(Se.default.Features,(e=>{this._featureStore.all(Se.default.Segments,(t=>{const i={[Se.default.Features.namespace]:e,[Se.default.Segments.namespace]:t};r(i)}))})):r()}upsert(e,t,i){const{key:r}=t,n=this._hasEventListeners(),s=s=>{this._featureStore.upsert(e,t,(()=>{Promise.resolve().then((()=>{if(this._dependencyTracker.updateDependenciesFrom(e.namespace,r,Oe(e.namespace,t)),n){const i=new Ee.default;this.addIfModified(e.namespace,r,s,t,i),this.sendChangeEvents(i)}})),null==i||i()}))};n?this._featureStore.get(e,r,s):s()}addIfModified(e,t,i,r,n){r&&i&&r.version<=i.version||this._dependencyTracker.updateModifiedItems(n,e,t)}sendChangeEvents(e){e.enumerate(((e,t)=>{e===Se.default.Features.namespace&&this._onChange(t)}))}};var xe={},De={},Me={},Pe={};Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.default=function(e){return new Promise((t=>{e((e=>{t(e)}))}))},Object.defineProperty(Me,"__esModule",{value:!0});const Te=Pe;Me.default=class{constructor(e){this._store=e}async get(e,t){return(0,Te.default)((i=>{this._store.get(e,t,i)}))}async all(e){return(0,Te.default)((t=>{this._store.all(e,t)}))}async init(e){return(0,Te.default)((t=>{this._store.init(e,t)}))}async delete(e,t,i){return(0,Te.default)((r=>{this._store.delete(e,t,i,r)}))}async upsert(e,t){return(0,Te.default)((i=>{this._store.upsert(e,t,i)}))}async initialized(){return(0,Te.default)((e=>{this._store.initialized(e)}))}close(){this._store.close()}};var Ce={},Fe={};function je(e){return Date.now()>e.expiration}Object.defineProperty(Fe,"__esModule",{value:!0});Fe.default=class{constructor(e){this._options=e,this._storage=new Map,this._checkIntervalHandle=setInterval((()=>{this._purgeStale()}),1e3*e.checkInterval)}get(e){const t=this._storage.get(e);if(!t||!je(t))return null==t?void 0:t.value;this._storage.delete(e)}set(e,t){this._storage.set(e,{value:t,expiration:Date.now()+1e3*this._options.ttl})}delete(e){this._storage.delete(e)}clear(){this._storage.clear()}close(){this.clear(),this._checkIntervalHandle&&(clearInterval(this._checkIntervalHandle),this._checkIntervalHandle=null)}_purgeStale(){this._storage.forEach(((e,t)=>{je(e)&&this._storage.delete(t)}))}get size(){return this._storage.size}};var Ie={};Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.persistentStoreKinds=void 0;const Re=ae,Ae=oe;Ie.persistentStoreKinds={segments:{namespace:Ae.default.Segments.namespace,deserialize:e=>{const t=(0,Re.deserializeSegment)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Re.serializeSegment)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:0},features:{namespace:Ae.default.Features.namespace,deserialize:e=>{const t=(0,Re.deserializeFlag)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Re.serializeFlag)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:1}};var Ve={};Object.defineProperty(Ve,"__esModule",{value:!0});const Ne=Ie;function Le(e,t){const i=[],r=new Set(Object.keys(t)),n=s=>{if(!r.has(s))return;r.delete(s);const a=t[s];var o;"features"===e.namespace&&(o=a,o.prerequisites&&o.prerequisites.length?o.prerequisites.map((e=>e.key)):[]).forEach((e=>{n(e)})),i.push({key:s,item:e.serialize(a)})};for(;r.size>0;){const e=r.values().next().value;n(e)}return i}Ve.default=function(e){const t=[];return Object.keys(e).forEach((i=>{const r=Ne.persistentStoreKinds[i];t.push({key:r,item:Le(r,e[i])})})),t.sort(((e,t)=>e.key.priority-t.key.priority)),t};var Ke={};Object.defineProperty(Ke,"__esModule",{value:!0});Ke.default=class{constructor(){this._queue=[]}enqueue(e,t){this._queue.push([e,t]),1===this._queue.length&&this.executePendingUpdates()}executePendingUpdates(){if(this._queue.length>0){const[e,t]=this._queue[0];e((()=>{this._queue.shift(),this._queue.length>0&&setTimeout((()=>this.executePendingUpdates()),0),null==t||t()}))}}},Object.defineProperty(Ce,"__esModule",{value:!0});const $e=Fe,Ue=Ie,ze=Ve,Be=Ke;function qe(e,t){return`${e.namespace}:${t}`}function He(e){return`$all:${e.namespace}`}const We="$checkedInit";function Je(e){return!e||e.item.deleted?null:e.item}function Ge(e){return{version:e,item:{version:e,deleted:!0}}}function Xe(e,t){if(t.deleted||!t.serializedItem)return Ge(t.version);const i=e.deserialize(t.serializedItem);return void 0===i?Ge(t.version):0===i.version||i.version===t.version||void 0===i.item?i:{version:t.version,item:i.item}}Ce.default=class{constructor(e,t){this._core=e,this._isInitialized=!1,this._queue=new Be.default,t&&(this._itemCache=new $e.default({ttl:t,checkInterval:600}),this._allItemsCache=new $e.default({ttl:t,checkInterval:600}))}init(e,t){this._queue.enqueue((t=>{this._core.init((0,ze.default)(e),(()=>{this._isInitialized=!0,this._itemCache&&(this._itemCache.clear(),this._allItemsCache.clear(),Object.keys(e).forEach((t=>{const i=Ue.persistentStoreKinds[t],r=e[t];this._allItemsCache.set(He(i),r),Object.keys(r).forEach((e=>{const t=r[e],n={version:t.version,item:t};this._itemCache.set(qe(i,e),n)}))}))),t()}))}),t)}get(e,t,i){if(this._itemCache){const r=this._itemCache.get(qe(e,t));if(r)return void i(Je(r))}const r=Ue.persistentStoreKinds[e.namespace];this._core.get(r,t,(n=>{var s;if(n&&n.serializedItem){const a=Xe(r,n);return null===(s=this._itemCache)||void 0===s||s.set(qe(e,t),a),void i(Je(a))}i(null)}))}initialized(e){var t;this._isInitialized?e(!0):(null===(t=this._itemCache)||void 0===t?void 0:t.get(We))?e(!1):this._core.initialized((t=>{var i;this._isInitialized=t,this._isInitialized||null===(i=this._itemCache)||void 0===i||i.set(We,!0),e(this._isInitialized)}))}all(e,t){var i;const r=null===(i=this._allItemsCache)||void 0===i?void 0:i.get(He(e));if(r)return void t(r);const n=Ue.persistentStoreKinds[e.namespace];this._core.getAll(n,(i=>{var r;if(!i)return void t({});const s={};i.forEach((({key:e,item:t})=>{const i=Je(Xe(n,t));i&&(s[e]=i)})),null===(r=this._allItemsCache)||void 0===r||r.set(He(e),s),t(s)}))}upsert(e,t,i){this._queue.enqueue((i=>{this._allItemsCache&&this._allItemsCache.clear();const r=Ue.persistentStoreKinds[e.namespace];this._core.upsert(r,t.key,r.serialize(t),((n,s)=>{var a,o;if(!n&&s)if(s.serializedItem){const i=Xe(r,s);null===(a=this._itemCache)||void 0===a||a.set(qe(e,t.key),i)}else s.deleted&&(null===(o=this._itemCache)||void 0===o||o.set(t.key,{key:t.key,version:s.version,deleted:!0}));i()}))}),i)}delete(e,t,i,r){this.upsert(e,{key:t,version:i,deleted:!0},r)}close(){var e,t;null===(e=this._itemCache)||void 0===e||e.close(),null===(t=this._allItemsCache)||void 0===t||t.close(),this._core.close()}getDescription(){return this._core.getDescription()}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.deserializePoll=e.PersistentDataStoreWrapper=e.AsyncStoreFacade=void 0;const t=Me;e.AsyncStoreFacade=t.default;const i=Ce;e.PersistentDataStoreWrapper=i.default;const r=ae;Object.defineProperty(e,"deserializePoll",{enumerable:!0,get:function(){return r.deserializePoll}})}(De),Object.defineProperty(xe,"__esModule",{value:!0});const Ye=o,Qe=De,Ze=oe;xe.default=class{constructor(e,t,i,r=()=>{},n){this._requestor=t,this._featureStore=i,this._initSuccessHandler=r,this._errorHandler=n,this._stopped=!1,this._logger=e.logger,this._pollInterval=e.pollInterval}_poll(){var e;if(this._stopped)return;const t=e=>{var t,i,r;null===(t=this._logger)||void 0===t||t.error("Polling received invalid data"),null===(i=this._logger)||void 0===i||i.debug(`Invalid JSON follows: ${e}`),null===(r=this._errorHandler)||void 0===r||r.call(this,new Ye.LDPollingError(Ye.DataSourceErrorKind.InvalidData,"Malformed JSON data in polling response"))},i=Date.now();null===(e=this._logger)||void 0===e||e.debug("Polling LaunchDarkly for feature flag updates"),this._requestor.requestAllData(((e,r)=>{var n,s,a,o;const l=Date.now()-i,u=Math.max(1e3*this._pollInterval-l,0);if(null===(n=this._logger)||void 0===n||n.debug("Elapsed: %d ms, sleeping for %d ms",l,u),e){const{status:t}=e;if(t&&!(0,Ye.isHttpRecoverable)(t)){const i=(0,Ye.httpErrorMessage)(e,"polling request");return null===(s=this._logger)||void 0===s||s.error(i),void(null===(a=this._errorHandler)||void 0===a||a.call(this,new Ye.LDPollingError(Ye.DataSourceErrorKind.ErrorResponse,i,t)))}null===(o=this._logger)||void 0===o||o.warn((0,Ye.httpErrorMessage)(e,"polling request","will retry"))}else if(r){const e=(0,Qe.deserializePoll)(r);if(e){const t={[Ze.default.Features.namespace]:e.flags,[Ze.default.Segments.namespace]:e.segments};return void this._featureStore.init(t,(()=>{this._initSuccessHandler(),this._timeoutHandle=setTimeout((()=>{this._poll()}),u)}))}t(r)}this._timeoutHandle=setTimeout((()=>{this._poll()}),u)}))}start(){this._poll()}stop(){this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this._stopped=!0}close(){this.stop()}};var et={};Object.defineProperty(et,"__esModule",{value:!0});const tt=o;et.default=class{constructor(e,t,i){this._requests=t,this._eTagCache={},this._headers=Object.assign({},i),this._uri=(0,tt.getPollingUri)(e.serviceEndpoints,"/sdk/latest-all",[])}async _requestWithETagCache(e,t){const i=this._eTagCache[e],r=null==i?void 0:i.etag,n=r?Object.assign(Object.assign({},t),{headers:Object.assign(Object.assign({},t.headers),{"if-none-match":r})}):t,s=await this._requests.fetch(e,n);if(304===s.status&&i)return{res:s,body:i.body};const a=s.headers.get("etag"),o=await s.text();return a&&(this._eTagCache[e]={etag:a,body:o}),{res:s,body:o}}async requestAllData(e){const t={method:"GET",headers:this._headers};try{const{res:i,body:r}=await this._requestWithETagCache(this._uri,t);if(200!==i.status&&304!==i.status){return e(new tt.LDPollingError(tt.DataSourceErrorKind.ErrorResponse,`Unexpected status code: ${i.status}`,i.status),void 0)}return e(void 0,304===i.status?null:r)}catch(t){return e(t,void 0)}}};var it={};Object.defineProperty(it,"__esModule",{value:!0});const rt=o;it.default=class{constructor(e,t,i,r,n,s,a,o=1){this._listeners=r,this._diagnosticsManager=s,this._errorHandler=a,this._streamInitialReconnectDelay=o;const{basicConfiguration:l,platform:u}=e,{logger:c}=l,{requests:d}=u;this._headers=Object.assign({},n),this._logger=c,this._requests=d,this._streamUri=(0,rt.getStreamingUri)(l.serviceEndpoints,t,i)}_logConnectionStarted(){this._connectionAttemptStartTime=Date.now()}_logConnectionResult(e){this._connectionAttemptStartTime&&this._diagnosticsManager&&this._diagnosticsManager.recordStreamInit(this._connectionAttemptStartTime,!e,Date.now()-this._connectionAttemptStartTime),this._connectionAttemptStartTime=void 0}_retryAndHandleError(e){var t,i,r;return(0,rt.shouldRetry)(e)?(null===(r=this._logger)||void 0===r||r.warn((0,rt.httpErrorMessage)(e,"streaming request","will retry")),this._logConnectionResult(!1),this._logConnectionStarted(),!0):(this._logConnectionResult(!1),null===(t=this._errorHandler)||void 0===t||t.call(this,new rt.LDStreamingError(rt.DataSourceErrorKind.ErrorResponse,e.message,e.status)),null===(i=this._logger)||void 0===i||i.error((0,rt.httpErrorMessage)(e,"streaming request")),!1)}start(){this._logConnectionStarted();const e=this._requests.createEventSource(this._streamUri,{headers:this._headers,errorFilter:e=>this._retryAndHandleError(e),initialRetryDelayMillis:1e3*this._streamInitialReconnectDelay,readTimeoutMillis:3e5,retryResetIntervalMillis:6e4});this._eventSource=e,e.onclose=()=>{var e;null===(e=this._logger)||void 0===e||e.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var e;null===(e=this._logger)||void 0===e||e.info("Opened LaunchDarkly stream connection")},e.onretrying=e=>{var t;null===(t=this._logger)||void 0===t||t.info(`Will retry stream connection in ${e.delayMillis} milliseconds`)},this._listeners.forEach((({deserializeData:t,processJson:i},r)=>{e.addEventListener(r,(e=>{var n,s;if(null===(n=this._logger)||void 0===n||n.debug(`Received ${r} event`),null==e?void 0:e.data){this._logConnectionResult(!0);const{data:n}=e,s=t(n);if(!s)return void((e,t,i,r)=>{null==i||i.error(`Stream received invalid data in "${e}" message`),null==i||i.debug(`Invalid JSON follows: ${t}`),null==r||r(new rt.LDStreamingError(rt.DataSourceErrorKind.InvalidData,"Malformed JSON data in event stream"))})(r,n,this._logger,this._errorHandler);i(s)}else null===(s=this._errorHandler)||void 0===s||s.call(this,new rt.LDStreamingError(rt.DataSourceErrorKind.Unknown,"Unexpected payload from event stream"))}))}))}stop(){var e;null===(e=this._eventSource)||void 0===e||e.close(),this._eventSource=void 0}close(){this.stop()}};var nt={},st={},at={};Object.defineProperty(at,"__esModule",{value:!0});at.default=class{constructor(){this._allData={},this._initCalled=!1}_addItem(e,t,i){let r=this._allData[e.namespace];if(r||(r={},this._allData[e.namespace]=r),Object.hasOwnProperty.call(r,t)){const e=r[t];(!e||e.version<i.version)&&(r[t]=i)}else r[t]=i}get(e,t,i){const r=this._allData[e.namespace];if(r&&Object.prototype.hasOwnProperty.call(r,t)){const e=r[t];if(e&&!e.deleted)return null==i?void 0:i(e)}return null==i?void 0:i(null)}all(e,t){var i;const r={},n=null!==(i=this._allData[e.namespace])&&void 0!==i?i:{};Object.entries(n).forEach((([e,t])=>{t&&!t.deleted&&(r[e]=t)})),null==t||t(r)}init(e,t){this._initCalled=!0,this._allData=e,null==t||t()}delete(e,t,i,r){const n={version:i,deleted:!0};this._addItem(e,t,n),null==r||r()}upsert(e,t,i){this._addItem(e,t.key,t),null==i||i()}initialized(e){return null==e?void 0:e(this._initCalled)}close(){}getDescription(){return"memory"}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultValues=void 0;const t=o,i=at,r={baseUri:t.TypeValidators.String,streamUri:t.TypeValidators.String,eventsUri:t.TypeValidators.String,timeout:t.TypeValidators.Number,capacity:t.TypeValidators.Number,logger:t.TypeValidators.Object,featureStore:t.TypeValidators.ObjectOrFactory,bigSegments:t.TypeValidators.Object,updateProcessor:t.TypeValidators.ObjectOrFactory,flushInterval:t.TypeValidators.Number,pollInterval:t.TypeValidators.numberWithMin(30),proxyOptions:t.TypeValidators.Object,offline:t.TypeValidators.Boolean,stream:t.TypeValidators.Boolean,streamInitialReconnectDelay:t.TypeValidators.Number,useLdd:t.TypeValidators.Boolean,sendEvents:t.TypeValidators.Boolean,allAttributesPrivate:t.TypeValidators.Boolean,privateAttributes:t.TypeValidators.StringArray,contextKeysCapacity:t.TypeValidators.Number,contextKeysFlushInterval:t.TypeValidators.Number,tlsParams:t.TypeValidators.Object,diagnosticOptOut:t.TypeValidators.Boolean,diagnosticRecordingInterval:t.TypeValidators.numberWithMin(60),wrapperName:t.TypeValidators.String,wrapperVersion:t.TypeValidators.String,application:t.TypeValidators.Object,payloadFilterKey:t.TypeValidators.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:t.TypeValidators.createTypeArray("Hook[]",{})};e.defaultValues={baseUri:"https://sdk.launchdarkly.com",streamUri:"https://stream.launchdarkly.com",eventsUri:t.ServiceEndpoints.DEFAULT_EVENTS,stream:!0,streamInitialReconnectDelay:1,sendEvents:!0,timeout:5,capacity:1e4,flushInterval:5,pollInterval:30,offline:!1,useLdd:!1,allAttributesPrivate:!1,privateAttributes:[],contextKeysCapacity:1e3,contextKeysFlushInterval:300,diagnosticOptOut:!1,diagnosticRecordingInterval:900,featureStore:()=>new i.default};e.default=class{constructor(i={},n={}){i=i||{},this.logger=i.logger;const{errors:s,validatedOptions:a}=function(i){const n=[],s=Object.assign({},e.defaultValues);return Object.keys(i).forEach((a=>{var o;const l=i[a],u=r[a];if(u)if(u.is(l))s[a]=l;else if("boolean"===u.getType())n.push(t.OptionMessages.wrongOptionTypeBoolean(a,typeof l)),s[a]=!!l;else if(u instanceof t.NumberWithMinimum&&t.TypeValidators.Number.is(l)){const{min:e}=u;n.push(t.OptionMessages.optionBelowMinimum(a,l,e)),s[a]=e}else n.push(t.OptionMessages.wrongOptionType(a,u.getType(),typeof l)),s[a]=e.defaultValues[a];else null===(o=i.logger)||void 0===o||o.warn(t.OptionMessages.unknownOption(a))})),{errors:n,validatedOptions:s}}(i);s.forEach((e=>{var t;null===(t=this.logger)||void 0===t||t.warn(e)})),function(e,i){var r,n,s;const{baseUri:a,streamUri:o,eventsUri:l}=e,u=null!=o,c=null!=a,d=null!=l;u===c&&u===d||(!u&&i.stream&&(null===(r=i.logger)||void 0===r||r.warn(t.OptionMessages.partialEndpoint("streamUri"))),c||null===(n=i.logger)||void 0===n||n.warn(t.OptionMessages.partialEndpoint("baseUri")),!d&&i.sendEvents&&(null===(s=i.logger)||void 0===s||s.warn(t.OptionMessages.partialEndpoint("eventsUri"))))}(i,a),this.serviceEndpoints=new t.ServiceEndpoints(a.streamUri,a.baseUri,a.eventsUri,n.analyticsEventPath,n.diagnosticEventPath,n.includeAuthorizationHeader,a.payloadFilterKey),this.eventsCapacity=a.capacity,this.timeout=a.timeout,this.bigSegments=a.bigSegments,this.flushInterval=a.flushInterval,this.pollInterval=a.pollInterval,this.proxyOptions=a.proxyOptions,this.offline=a.offline,this.stream=a.stream,this.streamInitialReconnectDelay=a.streamInitialReconnectDelay,this.useLdd=a.useLdd,this.sendEvents=a.sendEvents,this.allAttributesPrivate=a.allAttributesPrivate,this.privateAttributes=a.privateAttributes,this.contextKeysCapacity=a.contextKeysCapacity,this.contextKeysFlushInterval=a.contextKeysFlushInterval,this.tlsParams=a.tlsParams,this.diagnosticOptOut=a.diagnosticOptOut,this.wrapperName=a.wrapperName,this.payloadFilterKey=a.payloadFilterKey,this.wrapperVersion=a.wrapperVersion,this.tags=new t.ApplicationTags(a),this.diagnosticRecordingInterval=a.diagnosticRecordingInterval,t.TypeValidators.Function.is(a.updateProcessor)?this.updateProcessorFactory=a.updateProcessor:this.updateProcessorFactory=()=>a.updateProcessor,t.TypeValidators.Function.is(a.featureStore)?this.featureStoreFactory=a.featureStore:this.featureStoreFactory=()=>a.featureStore,this.hooks=a.hooks}}}(st),Object.defineProperty(nt,"__esModule",{value:!0});const ot=o,lt=st;nt.default=(e,t,i)=>{var r,n,s,a,o,l;return{customBaseURI:e.serviceEndpoints.polling!==lt.defaultValues.baseUri,customStreamURI:e.serviceEndpoints.streaming!==lt.defaultValues.streamUri,customEventsURI:e.serviceEndpoints.events!==lt.defaultValues.eventsUri,eventsCapacity:e.eventsCapacity,connectTimeoutMillis:(0,ot.secondsToMillis)(e.timeout),socketTimeoutMillis:(0,ot.secondsToMillis)(e.timeout),eventsFlushIntervalMillis:(0,ot.secondsToMillis)(e.flushInterval),pollingIntervalMillis:(0,ot.secondsToMillis)(e.pollInterval),reconnectTimeMillis:(0,ot.secondsToMillis)(e.streamInitialReconnectDelay),contextKeysFlushIntervalMillis:(0,ot.secondsToMillis)(e.contextKeysFlushInterval),diagnosticRecordingIntervalMillis:(0,ot.secondsToMillis)(e.diagnosticRecordingInterval),streamingDisabled:!e.stream,usingRelayDaemon:e.useLdd,offline:e.offline,allAttributesPrivate:e.allAttributesPrivate,contextKeysCapacity:e.contextKeysCapacity,usingProxy:!!(null===(n=(r=t.requests).usingProxy)||void 0===n?void 0:n.call(r)),usingProxyAuthenticator:!!(null===(a=(s=t.requests).usingProxyAuth)||void 0===a?void 0:a.call(s)),dataStoreType:null!==(l=null===(o=i.getDescription)||void 0===o?void 0:o.call(i))&&void 0!==l?l:"memory"}};var ut={};Object.defineProperty(ut,"__esModule",{value:!0}),ut.allAsync=ut.firstSeriesAsync=ut.allSeriesAsync=ut.firstResult=void 0,ut.firstResult=function(e,t){let i;return null==e||e.some(((e,r)=>(i=t(e,r),!!i))),i};function ct(e,t,i,r,n){e?r<(null==e?void 0:e.length)?t(e[r],r,(s=>{if(i){if(!s)return void n(!1)}else if(s)return void n(!0);e.length>50?Promise.resolve().then((()=>{ct(e,t,i,r+1,n)})):ct(e,t,i,r+1,n)})):n(i):n(!1)}ut.allSeriesAsync=function(e,t,i){ct(e,t,!0,0,i)},ut.firstSeriesAsync=function(e,t,i){ct(e,t,!1,0,i)},ut.allAsync=function(e,t,i){e?Promise.all(null==e?void 0:e.map((e=>new Promise((i=>{t(e,i)}))))).then((e=>{i(e.every((e=>e)))})):i(!1)};var dt={},ht={};Object.defineProperty(ht,"__esModule",{value:!0});class ft{static prerequisiteFailed(e){return{kind:"PREREQUISITE_FAILED",prerequisiteKey:e}}static ruleMatch(e,t){return{kind:"RULE_MATCH",ruleId:e,ruleIndex:t}}}ft.Fallthrough={kind:"FALLTHROUGH"},ft.Off={kind:"OFF"},ft.TargetMatch={kind:"TARGET_MATCH"},ht.default=ft,Object.defineProperty(dt,"__esModule",{value:!0});const gt=ht;class vt{constructor(e,t,i){this.isError=e,this.detail=t,this.message=i,this.isError=e,this.detail=t,this.message=i}get isOff(){return this.detail.reason.kind===gt.default.Off.kind}setDefault(e){this.detail.value=e}static forError(e,t,i){return new vt(!0,{value:null!=i?i:null,variationIndex:null,reason:{kind:"ERROR",errorKind:e}},t)}static forSuccess(e,t,i){return new vt(!1,{value:e,variationIndex:void 0===i?null:i,reason:t})}}dt.default=vt;var _t={},pt={};Object.defineProperty(pt,"__esModule",{value:!0});pt.default=class{constructor(e){this._crypto=e}_sha1Hex(e){const t=this._crypto.createHash("sha1");if(t.update(e),!t.digest)throw new Error("Platform must implement digest or asyncDigest");return t.digest("hex")}bucket(e,t,i,r,n="user",s){const a=function(e){return"string"==typeof e?e:Number.isInteger(e)?String(e):null}(e.valueForKind(i,n));if(null===a){return[0,e.kinds.indexOf(n)>=0]}const o=`${s?Number(s):`${t}.${r}`}.${a}`;return[parseInt(this._sha1Hex(o).substring(0,15),16)/0x1000000000000000,!0]}};var yt={},mt={};Object.defineProperty(mt,"__esModule",{value:!0}),mt.getBucketBy=mt.getOffVariation=mt.getVariation=void 0;const bt=o,wt=dt,{ErrorKinds:St}=bt.internal,kt=new bt.AttributeReference("key");function Et(e,t,i){return bt.TypeValidators.Number.is(t)&&t>=0&&t<e.variations.length?wt.default.forSuccess(e.variations[t],i,t):wt.default.forError(St.MalformedFlag,"Invalid variation index in flag")}mt.getVariation=Et,mt.getOffVariation=function(e,t){return bt.TypeValidators.Number.is(e.offVariation)?Et(e,e.offVariation,t):wt.default.forSuccess(null,t)},mt.getBucketBy=function(e,t){var i;return null!==(i=e?void 0:t)&&void 0!==i?i:kt},Object.defineProperty(yt,"__esModule",{value:!0});const Ot=o,xt=ut,Dt=ht,Mt=mt;function Pt(e,t,i){const r=i.key(t.contextKind);if(void 0!==r){if(t.values.indexOf(r)>=0)return(0,Mt.getVariation)(e,t.variation,Dt.default.TargetMatch)}}yt.default=function(e,t){var i;return(null===(i=e.contextTargets)||void 0===i?void 0:i.length)?(0,xt.firstResult)(e.contextTargets,(i=>{if(!i.contextKind||i.contextKind===Ot.Context.UserKind){const r=(e.targets||[]).find((e=>e.variation===i.variation));return r?Pt(e,r,t):void 0}return Pt(e,i,t)})):(0,xt.firstResult)(e.targets,(i=>Pt(e,i,t)))};var Tt={};Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.default=function(e){return`${e.key}.g${e.generation}`};var Ct={},Ft={};Object.defineProperty(Ft,"__esModule",{value:!0});const jt=t,It=o,Rt=/^\d+(\.\d+)?(\.\d+)?/;function At(e){if(It.TypeValidators.String.is(e)&&!e.startsWith("v")){const t=(0,jt.parse)(e);if(t)return t;const i=Rt.exec(e);if(i){let t=i[0];for(let e=1;e<i.length;e+=1)void 0===i[e]&&(t+=".0");return t+=e.substring(i[0].length),(0,jt.parse)(t)}}return null}function Vt(e){return(t,i)=>{const r=At(t),n=At(i);return!!(r&&n&&e(r,n))}}function Nt(e,t,i){return(r,n)=>!(!t.is(r)||!t.is(n))&&(i?e(i(r),i(n)):e(r,n))}function Lt(e){return"number"==typeof e?e:Date.parse(e)}const Kt={in:(e,t)=>e===t,endsWith:Nt(((e,t)=>e.endsWith(t)),It.TypeValidators.String),startsWith:Nt(((e,t)=>e.startsWith(t)),It.TypeValidators.String),matches:Nt(((e,t)=>function(e,t){try{return new RegExp(e).test(t)}catch(e){return!1}}(t,e)),It.TypeValidators.String),contains:Nt(((e,t)=>e.indexOf(t)>-1),It.TypeValidators.String),lessThan:Nt(((e,t)=>e<t),It.TypeValidators.Number),lessThanOrEqual:Nt(((e,t)=>e<=t),It.TypeValidators.Number),greaterThan:Nt(((e,t)=>e>t),It.TypeValidators.Number),greaterThanOrEqual:Nt(((e,t)=>e>=t),It.TypeValidators.Number),before:Nt(((e,t)=>e<t),It.TypeValidators.Date,Lt),after:Nt(((e,t)=>e>t),It.TypeValidators.Date,Lt),semVerEqual:Vt(((e,t)=>0===e.compare(t))),semVerLessThan:Vt(((e,t)=>e.compare(t)<0)),semVerGreaterThan:Vt(((e,t)=>e.compare(t)>0))};Ft.default=class{static is(e){return Object.prototype.hasOwnProperty.call(Kt,e)}static execute(e,t,i){var r,n;return null!==(n=null===(r=Kt[e])||void 0===r?void 0:r.call(Kt,t,i))&&void 0!==n&&n}},Object.defineProperty(Ct,"__esModule",{value:!0}),Ct.maybeNegate=void 0;const $t=Ft;function Ut(e,t){return e.negate?!t:t}function zt(e,t,i){return i.some((i=>$t.default.execute(e,t,i)))}Ct.maybeNegate=Ut,Ct.default=function(e,t){const i=t.valueForKind(e.attributeReference,e.contextKind);return null!=i&&(Array.isArray(i)?Ut(e,i.some((t=>zt(e.op,t,e.values)))):Ut(e,zt(e.op,i,e.values)))};var Bt={};function qt(e,t,i,r){if(t)for(let i=0;i<t.length;i+=1){const r=t[i],n=e.key(r.contextKind);if(n)if(r.generated_valuesSet){if(r.generated_valuesSet.has(n))return!0}else if(r.values.includes(n))return!0}if(r){const t=e.key("user");if(t&&r.has(t))return!0}else if(i){const t=e.key("user");if(t&&i.includes(t))return!0}return!1}Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.default=function(e,t){if(qt(t,e.includedContexts,e.included,e.generated_includedSet))return!0;const i=qt(t,e.excludedContexts,e.excluded,e.generated_excludedSet);return i?!i:void 0},Object.defineProperty(_t,"__esModule",{value:!0});const Ht=o,Wt=pt,Jt=ut,Gt=dt,Xt=yt,Yt=Tt,Qt=Ct,Zt=Bt,ei=ht,ti=mt,{ErrorKinds:ii}=Ht.internal,ri={HEALTHY:1,STALE:2,STORE_ERROR:3,NOT_CONFIGURED:4};function ni(e){return void 0!==e&&ri[e]||0}function si(e,t){return void 0!==e&&ni(e)>ni(t)?e:t}function ai(e){return{error:!1,isMatch:e,result:void 0}}function oi(e){return{error:!0,isMatch:!1,result:e}}_t.default=class{constructor(e,t){this._queries=t,this._bucketer=new Wt.default(e.crypto)}async evaluate(e,t,i){return new Promise((r=>{this.evaluateCb(e,t,r,i)}))}evaluateCb(e,t,i,r){const n={};this._evaluateInternal(e,t,n,[],(e=>{n.bigSegmentsStatus&&(e.detail.reason=Object.assign(Object.assign({},e.detail.reason),{bigSegmentsStatus:n.bigSegmentsStatus})),n.prerequisites&&(e.prerequisites=n.prerequisites),e.events=n.events,i(e)}),!0,r)}_evaluateInternal(e,t,i,r,n,s,a){e.on?this._checkPrerequisites(e,t,i,r,(r=>{if(r)return void n(r);const s=(0,Xt.default)(e,t);s?n(s):this._evaluateRules(e,t,i,(i=>{n(i||this._variationForContext(e.fallthrough,t,e,ei.default.Fallthrough))}))}),s,a):n((0,ti.getOffVariation)(e,ei.default.Off))}_checkPrerequisites(e,t,i,r,n,s,a){let o;e.prerequisites&&e.prerequisites.length?(0,Jt.allSeriesAsync)(e.prerequisites,((n,l,u)=>{if(-1!==r.indexOf(n.key))return o=Gt.default.forError(ii.MalformedFlag,`Prerequisite of ${e.key} causing a circular reference. This is probably a temporary condition due to an incomplete update.`),void u(!0);const c=[...r,n.key];this._queries.getFlag(n.key,(r=>{if(!r)return o=(0,ti.getOffVariation)(e,ei.default.prerequisiteFailed(n.key)),void u(!1);this._evaluateInternal(r,t,i,c,(l=>{var c,d;return null!==(c=i.events)&&void 0!==c||(i.events=[]),s&&(null!==(d=i.prerequisites)&&void 0!==d||(i.prerequisites=[]),i.prerequisites.push(r.key)),a&&i.events.push(a.evalEventServer(r,t,l.detail,null,e)),l.isError?(o=l,u(!1)):l.isOff||l.detail.variationIndex!==n.variation?(o=(0,ti.getOffVariation)(e,ei.default.prerequisiteFailed(n.key)),u(!1)):u(!0)}),!1,a)}))}),(()=>{n(o)})):n(void 0)}_evaluateRules(e,t,i,r){let n;(0,Jt.firstSeriesAsync)(e.rules,((r,s,a)=>{this._ruleMatchContext(e,r,s,t,i,[],(e=>{n=e,a(!!e)}))}),(()=>r(n)))}_clauseMatchContext(e,t,i,r,n){let s;"segmentMatch"!==e.op?e.attributeReference.isValid?n(ai((0,Qt.default)(e,t))):n(oi(Gt.default.forError(ii.MalformedFlag,"Invalid attribute reference in clause"))):(0,Jt.firstSeriesAsync)(e.values,((e,n,a)=>{this._queries.getSegment(e,(e=>{if(e){if(i.includes(e.key))return s=Gt.default.forError(ii.MalformedFlag,`Segment rule referencing segment ${e.key} caused a circular reference. This is probably a temporary condition due to an incomplete update`),void a(!0);const n=[...i,null==e?void 0:e.key];this.segmentMatchContext(e,t,r,n,(e=>{e.error&&(s=e.result),a(e.error||e.isMatch)}))}else a(!1)}))}),(t=>n(s?oi(s):ai((0,Qt.maybeNegate)(e,t)))))}_ruleMatchContext(e,t,i,r,n,s,a){if(!t.clauses)return void a(void 0);let o;(0,Jt.allSeriesAsync)(t.clauses,((e,t,i)=>{this._clauseMatchContext(e,r,s,n,(e=>(o=e.result,i(e.error||e.isMatch))))}),(n=>a(o||(n?this._variationForContext(t,r,e,ei.default.ruleMatch(t.id,i)):void 0))))}_variationForContext(e,t,i,r){if(void 0===e)return Gt.default.forError(ii.MalformedFlag,"Fallthrough variation undefined");if(void 0!==e.variation)return(0,ti.getVariation)(i,e.variation,r);if(e.rollout){const{rollout:n}=e,{variations:s}=n,a="experiment"===n.kind;if(s&&s.length){const e=(0,ti.getBucketBy)(a,n.bucketByAttributeReference);if(!e.isValid)return Gt.default.forError(ii.MalformedFlag,"Invalid attribute reference for bucketBy in rollout");const[o,l]=this._bucketer.bucket(t,i.key,e,i.salt||"",n.contextKind,n.seed),u=Object.assign({},r);let c=0;for(let e=0;e<s.length;e+=1){const t=s[e];if(c+=t.weight/1e5,o<c)return a&&l&&!t.untracked&&(u.inExperiment=!0),(0,ti.getVariation)(i,t.variation,u)}const d=s[s.length-1];return a&&!d.untracked&&(u.inExperiment=!0),(0,ti.getVariation)(i,d.variation,u)}}return Gt.default.forError(ii.MalformedFlag,"Variation/rollout object with no variation or rollout")}segmentRuleMatchContext(e,t,i,r,n,s){let a;(0,Jt.allSeriesAsync)(t.clauses,((e,t,s)=>{this._clauseMatchContext(e,i,n,r,(e=>{a=e.result,s(e.error||e.isMatch)}))}),(r=>{if(a)return s(oi(a));if(r){if(void 0===t.weight)return s(ai(r));const n=(0,ti.getBucketBy)(!1,t.bucketByAttributeReference);if(!n.isValid)return s(oi(Gt.default.forError(ii.MalformedFlag,"Invalid attribute reference in clause")));const[a]=this._bucketer.bucket(i,e.key,n,e.salt||"",t.rolloutContextKind);return s(ai(a<t.weight/1e5))}return s(ai(!1))}))}simpleSegmentMatchContext(e,t,i,r,n){if(!e.unbounded){const i=(0,Zt.default)(e,t);if(void 0!==i)return void n(ai(i))}let s;(0,Jt.firstSeriesAsync)(e.rules,((n,a,o)=>{this.segmentRuleMatchContext(e,n,t,i,r,(e=>(s=e.result,o(e.error||e.isMatch))))}),(e=>n(s?oi(s):ai(e))))}segmentMatchContext(e,t,i,r,n){if(!e.unbounded)return void this.simpleSegmentMatchContext(e,t,i,r,n);const s=e.unboundedContextKind||"user",a=t.key(s);if(a)return e.generation?void(i.bigSegmentsMembership&&i.bigSegmentsMembership[a]?this.bigSegmentMatchContext(i.bigSegmentsMembership[a],e,t,i).then(n):this._queries.getBigSegmentsMembership(a).then((r=>{if(i.bigSegmentsMembership=i.bigSegmentsMembership||{},r){const[e,t]=r;i.bigSegmentsMembership[a]=e,i.bigSegmentsStatus=si(i.bigSegmentsStatus,t)}else i.bigSegmentsStatus=si(i.bigSegmentsStatus,"NOT_CONFIGURED");this.bigSegmentMatchContext(i.bigSegmentsMembership[a],e,t,i).then(n)}))):(i.bigSegmentsStatus=si(i.bigSegmentsStatus,"NOT_CONFIGURED"),void n(ai(!1)));n(ai(!1))}bigSegmentMatchContext(e,t,i,r){const n=(0,Yt.default)(t),s=null==e?void 0:e[n];return new Promise((e=>{null==s?this.simpleSegmentMatchContext(t,i,r,[],e):e(ai(s))}))}};var li={};Object.defineProperty(li,"__esModule",{value:!0});const ui=te;li.default=class{constructor(e){this._contextKeysCache=new ui.default({max:e.contextKeysCapacity}),this.flushInterval=e.contextKeysFlushInterval}processContext(e){const{canonicalKey:t}=e,i=this._contextKeysCache.get(t);return this._contextKeysCache.set(t,!0),!i}flush(){this._contextKeysCache.clear()}};var ci={},di={};Object.defineProperty(di,"__esModule",{value:!0}),di.default=function(e,t){if(t){if(t.inExperiment)return!0;switch(t.kind){case"RULE_MATCH":{const i=t.ruleIndex;if(void 0!==i){const t=e.rules||[];return i>=0&&i<t.length&&!!t[i].trackEvents}break}case"FALLTHROUGH":return!!e.trackEventsFallthrough}}return!1},Object.defineProperty(ci,"__esModule",{value:!0});const hi=o,fi=di;class gi extends hi.internal.EventFactoryBase{evalEventServer(e,t,i,r,n){var s;const a=(0,fi.default)(e,i.reason);return super.evalEvent({addExperimentData:a,context:t,debugEventsUntilDate:e.debugEventsUntilDate,defaultVal:r,excludeFromSummaries:e.excludeFromSummaries,flagKey:e.key,prereqOfFlagKey:null==n?void 0:n.key,reason:i.reason,samplingRatio:e.samplingRatio,trackEvents:e.trackEvents||a,value:i.value,variation:null!==(s=i.variationIndex)&&void 0!==s?s:void 0,version:e.version})}}ci.default=gi;var vi={};Object.defineProperty(vi,"__esModule",{value:!0});vi.default=class{constructor(e,t){this._valid=e,this._withReasons=t,this._flagValues={},this._flagMetadata={}}addFlag(e,t,i,r,n,s,a,o){this._flagValues[e.key]=t;const l={};void 0!==i&&(l.variation=i);const u=a&&!n&&!s&&void 0===e.debugEventsUntilDate;u||(l.version=e.version),r&&(s||this._withReasons&&!u)&&(l.reason=r),n&&(l.trackEvents=!0),s&&(l.trackReason=!0),void 0!==e.debugEventsUntilDate&&(l.debugEventsUntilDate=e.debugEventsUntilDate),o&&o.length&&(l.prerequisites=o),this._flagMetadata[e.key]=l}build(){return{valid:this._valid,allValues:()=>this._flagValues,getFlagValue:e=>this._flagValues[e],getFlagReason:e=>{var t;return null!==(t=this._flagMetadata[e]?this._flagMetadata[e].reason:null)&&void 0!==t?t:null},toJSON:()=>Object.assign(Object.assign({},this._flagValues),{$flagsState:this._flagMetadata,$valid:this._valid})}}};var _i={};Object.defineProperty(_i,"__esModule",{value:!0});const pi="unknown hook";_i.default=class{constructor(e,t){this._logger=e,this._hooks=[],this._hooks.push(...t)}async withEvaluationSeries(e,t,i,r,n){return 0===this._hooks.length?n():this.withEvaluationSeriesExtraDetail(e,t,i,r,(async()=>({detail:await n()}))).then((({detail:e})=>e))}async withEvaluationSeriesExtraDetail(e,t,i,r,n){if(0===this._hooks.length)return n();const{hooks:s,hookContext:a}=this._prepareHooks(e,t,i,r),o=this._executeBeforeEvaluation(s,a),l=await n();return this._executeAfterEvaluation(s,a,o,l.detail),l}_tryExecuteStage(e,t,i){var r;try{return i()}catch(i){return null===(r=this._logger)||void 0===r||r.error(`An error was encountered in "${e}" of the "${t}" hook: ${i}`),{}}}_hookName(e){var t,i;try{return null!==(t=null==e?void 0:e.getMetadata().name)&&void 0!==t?t:pi}catch(e){return null===(i=this._logger)||void 0===i||i.error("Exception thrown getting metadata for hook. Unable to get hook name."),pi}}_executeAfterEvaluation(e,t,i,r){var n;for(let s=e.length-1;s>=0;s-=1){const a=e[s],o=null!==(n=i[s])&&void 0!==n?n:{};this._tryExecuteStage("afterEvaluation",this._hookName(a),(()=>{var e,i;return null!==(i=null===(e=null==a?void 0:a.afterEvaluation)||void 0===e?void 0:e.call(a,t,o,r))&&void 0!==i?i:{}}))}}_executeBeforeEvaluation(e,t){return e.map((e=>this._tryExecuteStage("beforeEvaluation",this._hookName(e),(()=>{var i,r;return null!==(r=null===(i=null==e?void 0:e.beforeEvaluation)||void 0===i?void 0:i.call(e,t,{}))&&void 0!==r?r:{}}))))}_prepareHooks(e,t,i,r){return{hooks:[...this._hooks],hookContext:{flagKey:e,context:t,defaultValue:i,method:r}}}addHook(e){this._hooks.push(e)}};var yi={};Object.defineProperty(yi,"__esModule",{value:!0});const mi=o;function bi(e){const t=e.old,i=e.new;return!(void 0!==t&&!mi.TypeValidators.Boolean.is(t))&&!(void 0!==i&&!mi.TypeValidators.Boolean.is(i))}function wi(e){if(mi.TypeValidators.String.is(e.key)&&""!==e.key){if("latency_ms"===e.key){if(!mi.TypeValidators.Object.is(e.values))return;if(!function(e){const t=e.old,i=e.new;return!(void 0!==t&&!mi.TypeValidators.Number.is(t)||void 0!==i&&!mi.TypeValidators.Number.is(i))}(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}if(function(e){return"error"===e.key}(e)){if(!mi.TypeValidators.Object.is(e.values))return;if(!bi(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}if(function(e){return"consistent"===e.key}(e)){if(!mi.TypeValidators.Boolean.is(e.value)||!mi.TypeValidators.Number.is(e.samplingRatio))return;return{key:e.key,value:e.value,samplingRatio:e.samplingRatio}}if(function(e){return"invoked"===e.key}(e)){if(!mi.TypeValidators.Object.is(e.values))return;if(!bi(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}}}yi.default=function(e){var t,i;if("migration_op"!==e.kind)return;if(i=e.operation,!mi.TypeValidators.String.is(i)||"read"!==i&&"write"!==i)return;if(!mi.TypeValidators.Object.is(e.contextKeys))return;if(!mi.TypeValidators.Number.is(e.creationDate))return;if(!Object.keys(e.contextKeys).every((e=>mi.TypeValidators.Kind.is(e))))return;const r=null!==(t=e.samplingRatio)&&void 0!==t?t:1;if(!mi.TypeValidators.Number.is(r))return;if(!Object.values(e.contextKeys).every((e=>mi.TypeValidators.String.is(e)&&""!==e)))return;const n=function(e){if(!mi.TypeValidators.String.is(e.key)||""===e.key)return;if(!mi.TypeValidators.Object.is(e.reason))return;if(!mi.TypeValidators.String.is(e.reason.kind)||""===e.reason.kind)return;const t={key:e.key,value:e.value,default:e.default,reason:{kind:e.reason.kind}},i=e.reason,r=t.reason;return mi.TypeValidators.String.is(i.errorKind)&&(r.errorKind=i.errorKind),mi.TypeValidators.String.is(i.ruleId)&&(r.ruleId=i.ruleId),mi.TypeValidators.String.is(i.prerequisiteKey)&&(r.prerequisiteKey=i.prerequisiteKey),mi.TypeValidators.Boolean.is(i.inExperiment)&&(r.inExperiment=i.inExperiment),mi.TypeValidators.Number.is(i.ruleIndex)&&(r.ruleIndex=i.ruleIndex),mi.TypeValidators.String.is(i.bigSegmentsStatus)&&(r.bigSegmentsStatus=i.bigSegmentsStatus),void 0!==e.variation&&mi.TypeValidators.Number.is(e.variation)&&(t.variation=e.variation),void 0!==e.version&&mi.TypeValidators.Number.is(e.version)&&(t.version=e.version),t}(e.evaluation);var s;return n?{kind:e.kind,operation:e.operation,creationDate:e.creationDate,contextKeys:Object.assign({},e.contextKeys),measurements:(s=e.measurements,s.map(wi).filter((e=>void 0!==e))),evaluation:n,samplingRatio:r}:void 0};var Si={};Object.defineProperty(Si,"__esModule",{value:!0});const ki=o,Ei=u;function Oi(e){return!Number.isNaN(e)}Si.default=class{constructor(e,t,i,r,n,s,a,o,l,u){this._flagKey=e,this._contextKeys=t,this._defaultStage=i,this._stage=r,this._reason=n,this._checkRatio=s,this._variation=a,this._version=o,this._samplingRatio=l,this._logger=u,this._errors={old:!1,new:!1},this._wasInvoked={old:!1,new:!1},this._consistencyCheck=Ei.LDConsistencyCheck.NotChecked,this._latencyMeasurement={old:NaN,new:NaN}}op(e){this._operation=e}error(e){this._errors[e]=!0}consistency(e){var t,i;if(ki.internal.shouldSample(null!==(t=this._checkRatio)&&void 0!==t?t:1))try{const t=e();this._consistencyCheck=t?Ei.LDConsistencyCheck.Consistent:Ei.LDConsistencyCheck.Inconsistent}catch(e){null===(i=this._logger)||void 0===i||i.error(`Exception when executing consistency check function for migration '${this._flagKey}' the consistency check will not be included in the generated migration op event. Exception: ${e}`)}}latency(e,t){this._latencyMeasurement[e]=t}invoked(e){this._wasInvoked[e]=!0}createEvent(){var e,t,i,r,n;if(!ki.TypeValidators.String.is(this._flagKey)||""===this._flagKey)return void(null===(e=this._logger)||void 0===e||e.error("The flag key for a migration operation must be a non-empty string."));if(!this._operation)return void(null===(t=this._logger)||void 0===t||t.error('The operation must be set using "op" before an event can be created.'));if(0===Object.keys(this._contextKeys).length)return void(null===(i=this._logger)||void 0===i||i.error("The migration was not done against a valid context and cannot generate an event."));if(!this._wasInvoked.old&&!this._wasInvoked.new)return void(null===(r=this._logger)||void 0===r||r.error('The migration invoked neither the "old" or "new" implementation andan event cannot be generated'));if(!this._measurementConsistencyCheck())return;const s=[];return this._populateInvoked(s),this._populateConsistency(s),this._populateLatency(s),this._populateErrors(s),{kind:"migration_op",operation:this._operation,creationDate:Date.now(),contextKeys:this._contextKeys,evaluation:{key:this._flagKey,value:this._stage,default:this._defaultStage,reason:this._reason,variation:this._variation,version:this._version},measurements:s,samplingRatio:null!==(n=this._samplingRatio)&&void 0!==n?n:1}}_logTag(){return`For migration ${this._operation}-${this._flagKey}:`}_latencyConsistencyMessage(e){return`Latency measurement for "${e}", but "${e}" was not invoked.`}_errorConsistencyMessage(e){return`Error occurred for "${e}", but "${e}" was not invoked.`}_consistencyCheckConsistencyMessage(e){return`Consistency check was done, but "${e}" was not invoked.Both "old" and "new" must be invoked to do a consistency check.`}_checkOriginEventConsistency(e){var t,i,r;return!!this._wasInvoked[e]||(Number.isNaN(this._latencyMeasurement[e])?this._errors[e]?(null===(i=this._logger)||void 0===i||i.error(`${this._logTag()} ${this._errorConsistencyMessage(e)}`),!1):this._consistencyCheck===Ei.LDConsistencyCheck.NotChecked||(null===(r=this._logger)||void 0===r||r.error(`${this._logTag()} ${this._consistencyCheckConsistencyMessage(e)}`),!1):(null===(t=this._logger)||void 0===t||t.error(`${this._logTag()} ${this._latencyConsistencyMessage(e)}`),!1))}_measurementConsistencyCheck(){return this._checkOriginEventConsistency("old")&&this._checkOriginEventConsistency("new")}_populateInvoked(e){var t;const i={key:"invoked",values:{}};this._wasInvoked.old||this._wasInvoked.new||null===(t=this._logger)||void 0===t||t.error("Migration op completed without executing any origins (old/new)."),this._wasInvoked.old&&(i.values.old=!0),this._wasInvoked.new&&(i.values.new=!0),e.push(i)}_populateConsistency(e){var t;void 0!==this._consistencyCheck&&this._consistencyCheck!==Ei.LDConsistencyCheck.NotChecked&&e.push({key:"consistent",value:this._consistencyCheck===Ei.LDConsistencyCheck.Consistent,samplingRatio:null!==(t=this._checkRatio)&&void 0!==t?t:1})}_populateErrors(e){if(this._errors.new||this._errors.old){const t={key:"error",values:{}};this._errors.new&&(t.values.new=!0),this._errors.old&&(t.values.old=!0),e.push(t)}}_populateLatency(e){const t=Oi(this._latencyMeasurement.new),i=Oi(this._latencyMeasurement.old);if(t||i){const r={};t&&(r.new=this._latencyMeasurement.new),i&&(r.old=this._latencyMeasurement.old),e.push({key:"latency_ms",values:r})}}},Object.defineProperty(a,"__esModule",{value:!0});const xi=o,Di=l,Mi=ee,Pi=se,Ti=ye,Ci=xe,Fi=et,ji=it,Ii=nt,Ri=ut,Ai=dt,Vi=_t,Ni=li,Li=ci,Ki=di,$i=vi,Ui=_i,zi=yi,Bi=Si,qi=st,Hi=oe,{ClientMessages:Wi,ErrorKinds:Ji,NullEventProcessor:Gi}=xi.internal;var Xi,Yi;(Yi=Xi||(Xi={}))[Yi.Initializing=0]="Initializing",Yi[Yi.Initialized=1]="Initialized",Yi[Yi.Failed=2]="Failed";a.default=class{get logger(){return this._logger}constructor(e,t,i,r,n){var s,a,o,l,u;this._sdkKey=e,this._platform=t,this._initState=Xi.Initializing,this._eventFactoryDefault=new Li.default(!1),this._eventFactoryWithReasons=new Li.default(!0),this._onError=r.onError,this._onFailed=r.onFailed,this._onReady=r.onReady;const{onUpdate:c,hasEventListeners:d}=r,h=new qi.default(i,n);if(this._hookRunner=new Ui.default(h.logger,h.hooks||[]),!e&&!h.offline)throw new Error("You must configure the client with an SDK key");this._config=h,this._logger=h.logger;const f=(0,xi.defaultHeaders)(e,t.info,h.tags),g=new xi.ClientContext(e,h,t),v=h.featureStoreFactory(g),_=new Ti.default(v,d,c);!h.sendEvents||h.offline||h.diagnosticOptOut||(this._diagnosticsManager=new xi.internal.DiagnosticsManager(e,t,(0,Ii.default)(h,t,v))),!h.sendEvents||h.offline?this._eventProcessor=new Gi:this._eventProcessor=new xi.internal.EventProcessor(h,g,f,new Ni.default(h),this._diagnosticsManager),this._featureStore=v;const p=new Mi.default(null===(a=null===(s=h.bigSegments)||void 0===s?void 0:s.store)||void 0===a?void 0:a.call(s,g),null!==(o=h.bigSegments)&&void 0!==o?o:{},h.logger,this._platform.crypto);this._bigSegmentsManager=p,this.bigSegmentStatusProviderInternal=p.statusProvider;const y={getFlag(e,t){v.get(Hi.default.Features,e,(e=>t(e)))},getSegment(e,t){v.get(Hi.default.Segments,e,(e=>t(e)))},getBigSegmentsMembership:e=>p.getUserMembership(e)};this._evaluator=new Vi.default(this._platform,y);const m=(0,Pi.createStreamListeners)(_,this._logger,{put:()=>this._initSuccess()}),b=()=>h.stream?new ji.default(g,"/all",[],m,f,this._diagnosticsManager,(e=>this._dataSourceErrorHandler(e)),this._config.streamInitialReconnectDelay):new Ci.default(h,new Fi.default(h,this._platform.requests,f),_,(()=>this._initSuccess()),(e=>this._dataSourceErrorHandler(e)));h.offline||h.useLdd||(this._updateProcessor=null!==(u=null===(l=h.updateProcessorFactory)||void 0===l?void 0:l.call(h,g,_,(()=>this._initSuccess()),(e=>this._dataSourceErrorHandler(e))))&&void 0!==u?u:b()),this._updateProcessor?this._updateProcessor.start():setTimeout((()=>this._initSuccess()),0)}initialized(){return this._initState===Xi.Initialized}waitForInitialization(e){var t,i;return void 0===(null==e?void 0:e.timeout)&&void 0!==this._updateProcessor&&(null===(t=this._logger)||void 0===t||t.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.")),void 0!==(null==e?void 0:e.timeout)&&(null==e?void 0:e.timeout)>60&&void 0!==this._updateProcessor&&(null===(i=this._logger)||void 0===i||i.warn("The waitForInitialization function was called with a timeout greater than 60 seconds. We recommend a timeout of less than 60 seconds.")),this._initializedPromise?this._clientWithTimeout(this._initializedPromise,null==e?void 0:e.timeout,this._logger):this._initState===Xi.Initialized?(this._initializedPromise=Promise.resolve(this),this._initializedPromise):this._initState===Xi.Failed?(this._initializedPromise=Promise.reject(this._rejectionReason),this._initializedPromise):(this._initializedPromise||(this._initializedPromise=new Promise(((e,t)=>{this._initResolve=e,this._initReject=t}))),this._clientWithTimeout(this._initializedPromise,null==e?void 0:e.timeout,this._logger))}variation(e,t,i,r){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.variation",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryDefault,(e=>{r(e.detail)}))})))).then((e=>(null==r||r(null,e.value),e.value)))}variationDetail(e,t,i,r){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.variationDetail",(()=>new Promise((n=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(e=>{n(e.detail),null==r||r(null,e.detail)}))}))))}_typedEval(e,t,i,r,n,s){return this._hookRunner.withEvaluationSeries(e,t,i,n,(()=>new Promise((n=>{this._evaluateIfPossible(e,t,i,r,(e=>{const t={value:e.detail.value,reason:e.detail.reason,variationIndex:e.detail.variationIndex};n(t)}),s)}))))}async boolVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.boolVariation",(e=>[xi.TypeValidators.Boolean.is(e),xi.TypeValidators.Boolean.getType()]))).value}async numberVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.numberVariation",(e=>[xi.TypeValidators.Number.is(e),xi.TypeValidators.Number.getType()]))).value}async stringVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.stringVariation",(e=>[xi.TypeValidators.String.is(e),xi.TypeValidators.String.getType()]))).value}jsonVariation(e,t,i){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.jsonVariation",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryDefault,(e=>{r(e.detail)}))})))).then((e=>e.value))}boolVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.boolVariationDetail",(e=>[xi.TypeValidators.Boolean.is(e),xi.TypeValidators.Boolean.getType()]))}numberVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.numberVariationDetail",(e=>[xi.TypeValidators.Number.is(e),xi.TypeValidators.Number.getType()]))}stringVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.stringVariationDetail",(e=>[xi.TypeValidators.String.is(e),xi.TypeValidators.String.getType()]))}jsonVariationDetail(e,t,i){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.jsonVariationDetail",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(e=>{r(e.detail)}))}))))}async _migrationVariationInternal(e,t,i){var r;const n=xi.Context.fromLDContext(t),s=await new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(({detail:t},n)=>{if((0,Di.IsMigrationStage)(t.value))r({detail:t,flag:n});else{const t=new Error(`Unrecognized MigrationState for "${e}"; returning default value.`);this._onError(t);const s={kind:"ERROR",errorKind:Ji.WrongType};r({detail:{value:i,reason:s},flag:n})}}))})),{detail:a,flag:o}=s,l=n.valid?n.kindsAndKeys:{},u=null===(r=null==o?void 0:o.migration)||void 0===r?void 0:r.checkRatio,c=null==o?void 0:o.samplingRatio;return{detail:a,migration:{value:a.value,tracker:new Bi.default(e,l,i,a.value,a.reason,u,null===a.variationIndex?void 0:a.variationIndex,null==o?void 0:o.version,c,this._logger)}}}async migrationVariation(e,t,i){return(await this._hookRunner.withEvaluationSeriesExtraDetail(e,t,i,"LDClient.migrationVariation",(()=>this._migrationVariationInternal(e,t,i)))).migration}allFlagsState(e,t,i){var r,n,s;if(this._config.offline){null===(r=this._logger)||void 0===r||r.info("allFlagsState() called in offline mode. Returning empty state.");const e=new $i.default(!1,!1).build();return null==i||i(null,e),Promise.resolve(e)}const a=xi.Context.fromLDContext(e);return a.valid?new Promise((e=>{const r=r=>this._featureStore.all(Hi.default.Features,(n=>{const s=new $i.default(r,!!(null==t?void 0:t.withReasons)),o=!!(null==t?void 0:t.clientSideOnly),l=!!(null==t?void 0:t.detailsOnlyForTrackedFlags);(0,Ri.allAsync)(Object.values(n),((e,t)=>{var i;const r=e;!o||(null===(i=r.clientSideAvailability)||void 0===i?void 0:i.usingEnvironmentId)?this._evaluator.evaluateCb(r,a,(e=>{var i;e.isError&&this._onError(new Error(`Error for feature flag "${r.key}" while evaluating all flags: ${e.message}`));const n=(0,Ki.default)(r,e.detail.reason);s.addFlag(r,e.detail.value,null!==(i=e.detail.variationIndex)&&void 0!==i?i:void 0,e.detail.reason,r.trackEvents||n,n,l,e.prerequisites),t(!0)})):t(!0)}),(()=>{const t=s.build();null==i||i(null,t),e(t)}))}));this.initialized()?r(!0):this._featureStore.initialized((e=>{var t,i;let n=!0;e?null===(t=this._logger)||void 0===t||t.warn("Called allFlagsState before client initialization; using last known values from data store"):(null===(i=this._logger)||void 0===i||i.warn("Called allFlagsState before client initialization. Data store not available; returning empty state"),n=!1),r(n)}))})):(null===(n=this._logger)||void 0===n||n.info(`${null!==(s=a.message)&&void 0!==s?s:"Invalid context."}. Returning empty state.`),Promise.resolve(new $i.default(!1,!1).build()))}secureModeHash(e){const t=xi.Context.fromLDContext(e),i=t.valid?t.canonicalKey:void 0;if(!this._platform.crypto.createHmac)throw new Error("Platform must implement createHmac");const r=this._platform.crypto.createHmac("sha256",this._sdkKey);if(void 0===i)throw new xi.LDClientError("Could not generate secure mode hash for invalid context");return r.update(i),r.digest("hex")}close(){var e;this._eventProcessor.close(),null===(e=this._updateProcessor)||void 0===e||e.close(),this._featureStore.close(),this._bigSegmentsManager.close()}isOffline(){return this._config.offline}track(e,t,i,r){var n,s;const a=xi.Context.fromLDContext(t);a.valid?(void 0===r||xi.TypeValidators.Number.is(r)||null===(s=this._logger)||void 0===s||s.warn(Wi.invalidMetricValue(typeof r)),this._eventProcessor.sendEvent(this._eventFactoryDefault.customEvent(e,a,i,r))):null===(n=this._logger)||void 0===n||n.warn(Wi.MissingContextKeyNoEvent)}trackMigration(e){const t=(0,zi.default)(e);t&&this._eventProcessor.sendEvent(t)}identify(e){var t;const i=xi.Context.fromLDContext(e);i.valid?this._eventProcessor.sendEvent(this._eventFactoryDefault.identifyEvent(i)):null===(t=this._logger)||void 0===t||t.warn(Wi.MissingContextKeyNoEvent)}async flush(e){try{await this._eventProcessor.flush()}catch(t){null==e||e(t,!1)}null==e||e(null,!0)}addHook(e){this._hookRunner.addHook(e)}_variationInternal(e,t,i,r,n,s){var a,o;if(this._config.offline)return null===(a=this._logger)||void 0===a||a.info("Variation called in offline mode. Returning default value."),void n(Ai.default.forError(Ji.ClientNotReady,void 0,i));const l=xi.Context.fromLDContext(t);if(!l.valid)return this._onError(new xi.LDClientError(`${null!==(o=l.message)&&void 0!==o?o:"Context not valid;"} returning default value.`)),void n(Ai.default.forError(Ji.UserNotSpecified,void 0,i));this._featureStore.get(Hi.default.Features,e,(t=>{const a=t;if(!a){const t=new xi.LDClientError(`Unknown feature flag "${e}"; returning default value`);this._onError(t);const r=Ai.default.forError(Ji.FlagNotFound,void 0,i);return this._eventProcessor.sendEvent(this._eventFactoryDefault.unknownFlagEvent(e,i,l)),void n(r)}this._evaluator.evaluateCb(a,l,(t=>{var o;if(void 0!==t.detail.variationIndex&&null!==t.detail.variationIndex||(null===(o=this._logger)||void 0===o||o.debug("Result value is null in variation"),t.setDefault(i)),s){const[o,u]=s(t.detail.value);if(!o){const t=Ai.default.forError(Ji.WrongType,`Did not receive expected type (${u}) evaluating feature flag "${e}"`,i);return this._sendEvalEvent(t,r,a,l,i),void n(t,a)}}this._sendEvalEvent(t,r,a,l,i),n(t,a)}),r)}))}_sendEvalEvent(e,t,i,r,n){var s;null===(s=e.events)||void 0===s||s.forEach((e=>{this._eventProcessor.sendEvent(Object.assign({},e))})),this._eventProcessor.sendEvent(t.evalEventServer(i,r,e.detail,n,void 0))}_evaluateIfPossible(e,t,i,r,n,s){this.initialized()?this._variationInternal(e,t,i,r,n,s):this._featureStore.initialized((a=>{var o,l;if(a)return null===(o=this._logger)||void 0===o||o.warn("Variation called before LaunchDarkly client initialization completed (did you wait for the 'ready' event?) - using last known values from feature store"),void this._variationInternal(e,t,i,r,n,s);null===(l=this._logger)||void 0===l||l.warn("Variation called before LaunchDarkly client initialization completed (did you wait for the'ready' event?) - using default value"),n(Ai.default.forError(Ji.ClientNotReady,void 0,i))}))}_dataSourceErrorHandler(e){var t;const i=401===e.code?new Error("Authentication failed. Double check your SDK key."):e;this._onError(i),this._onFailed(i),this.initialized()||(this._initState=Xi.Failed,this._rejectionReason=i,null===(t=this._initReject)||void 0===t||t.call(this,i))}_initSuccess(){var e;this.initialized()||(this._initState=Xi.Initialized,null===(e=this._initResolve)||void 0===e||e.call(this,this),this._onReady())}_clientWithTimeout(e,t,i){if(t){const r=(0,xi.cancelableTimedPromise)(t,"waitForInitialization");return Promise.race([e.then((()=>r.cancel())).then((()=>this)),r.promise.then((()=>this))]).catch((e=>{throw e instanceof xi.LDTimeoutError&&(null==i||i.error(e.message)),e}))}return e}};var Qi={};Object.defineProperty(Qi,"__esModule",{value:!0}),Qi.createMigration=Qi.LDMigrationError=Qi.LDMigrationSuccess=void 0;const Zi=l,er=C;Qi.LDMigrationSuccess=function(e){return{success:!0,result:e}},Qi.LDMigrationError=function(e){return{success:!1,error:e}};class tr{constructor(e,t){var i,r;this._client=e,this._config=t,this._readTable={[Zi.LDMigrationStage.Off]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[Zi.LDMigrationStage.DualWrite]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[Zi.LDMigrationStage.Shadow]:async e=>{const{fromOld:t,fromNew:i}=await this._doRead(e);return this._trackConsistency(e,t,i),t},[Zi.LDMigrationStage.Live]:async e=>{const{fromNew:t,fromOld:i}=await this._doRead(e);return this._trackConsistency(e,i,t),t},[Zi.LDMigrationStage.RampDown]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[Zi.LDMigrationStage.Complete]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config))},this._writeTable={[Zi.LDMigrationStage.Off]:async e=>({authoritative:await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config))}),[Zi.LDMigrationStage.DualWrite]:async e=>{const t=await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config));if(!t.success)return{authoritative:t};return{authoritative:t,nonAuthoritative:await this._doSingleOp(e,"new",this._config.writeNew.bind(this._config))}},[Zi.LDMigrationStage.Shadow]:async e=>{const t=await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config));if(!t.success)return{authoritative:t};return{authoritative:t,nonAuthoritative:await this._doSingleOp(e,"new",this._config.writeNew.bind(this._config))}},[Zi.LDMigrationStage.Live]:async e=>{const t=await this._doSingleOp(e,"new",this._config.writeNew.bind(this._config));if(!t.success)return{authoritative:t};return{authoritative:t,nonAuthoritative:await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config))}},[Zi.LDMigrationStage.RampDown]:async e=>{const t=await this._doSingleOp(e,"new",this._config.writeNew.bind(this._config));if(!t.success)return{authoritative:t};return{authoritative:t,nonAuthoritative:await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config))}},[Zi.LDMigrationStage.Complete]:async e=>({authoritative:await this._doSingleOp(e,"new",this._config.writeNew.bind(this._config))})},this._config.execution?this._execution=this._config.execution:this._execution=new er.LDConcurrentExecution,this._latencyTracking=null===(i=this._config.latencyTracking)||void 0===i||i,this._errorTracking=null===(r=this._config.errorTracking)||void 0===r||r}async read(e,t,i,r){const n=await this._client.migrationVariation(e,t,i),s=await this._readTable[n.value]({payload:r,tracker:n.tracker});return n.tracker.op("read"),this._sendEvent(n.tracker),s}async write(e,t,i,r){const n=await this._client.migrationVariation(e,t,i),s=await this._writeTable[n.value]({payload:r,tracker:n.tracker});return n.tracker.op("write"),this._sendEvent(n.tracker),s}_sendEvent(e){const t=e.createEvent();t&&this._client.trackMigration(t)}_trackConsistency(e,t,i){this._config.check&&t.success&&i.success&&e.tracker.consistency((()=>this._config.check(t.result,i.result)))}async _readSequentialFixed(e){return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:await this._doSingleOp(e,"new",this._config.readNew.bind(this._config))}}async _readConcurrent(e){const t=this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),i=this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[r,n]=await Promise.all([t,i]);return{fromOld:r,fromNew:n}}async _readSequentialRandom(e){if(0===Math.floor(2*Math.random())){return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:await this._doSingleOp(e,"new",this._config.readNew.bind(this._config))}}const t=await this._doSingleOp(e,"new",this._config.readNew.bind(this._config));return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:t}}async _doRead(e){var t;if((null===(t=this._execution)||void 0===t?void 0:t.type)===er.LDExecution.Serial){return this._execution.ordering===er.LDExecutionOrdering.Fixed?this._readSequentialFixed(e):this._readSequentialRandom(e)}return this._readConcurrent(e)}async _doSingleOp(e,t,i){e.tracker.invoked(t);const r=await this._trackLatency(e.tracker,t,(()=>async function(e){try{return await e()}catch(e){return{success:!1,error:e}}}((()=>i(e.payload)))));return!r.success&&this._errorTracking&&e.tracker.error(t),Object.assign({origin:t},r)}async _trackLatency(e,t,i){if(!this._latencyTracking)return i();let r,n,s;"undefined"!=typeof performance?(r=performance.now(),s=await i(),n=performance.now()):(r=Date.now(),s=await i(),n=Date.now());const a=n-r;return e.latency(t,a),s}}Qi.createMigration=function(e,t){return new tr(e,t)};var ir={},rr={},nr={},sr={};Object.defineProperty(sr,"__esModule",{value:!0});sr.default=class{constructor(e,t,i,r){this._filesystem=e,this._paths=t,this._watch=i,this._callback=r,this._watchers=[],this._fileData={},this._fileTimestamps={}}async loadAndWatch(){const e=this._paths.map((async e=>({data:await this._filesystem.readFile(e),path:e,timeStamp:await this._filesystem.getFileTimestamp(e)}))),t=await Promise.all(e);t.forEach((e=>{this._fileData[e.path]=e.data,this._fileTimestamps[e.path]=e.timeStamp})),this._callback(t),this._watch&&this._paths.forEach((e=>{const t=this._filesystem.watch(e,(async(e,t)=>{const i=await this._filesystem.getFileTimestamp(t);if(i===this._fileTimestamps[t])return;this._fileTimestamps[t]=i;const r=await this._filesystem.readFile(t);this._fileData[t]=r,this._debounceCallback()}));this._watchers.push(t)}))}close(){this._watchers.forEach((e=>e.close()))}_debounceCallback(){this._debounceHandle||(this._debounceHandle=setTimeout((()=>{this._debounceHandle=void 0,this._callback(Object.entries(this._fileData).reduce(((e,[t,i])=>(e.push({path:t,data:i}),e)),[]))}),10))}},Object.defineProperty(nr,"__esModule",{value:!0});const ar=ae,or=oe,lr=sr;nr.default=class{constructor(e,t,i,r=()=>{},n){var s;this._featureStore=i,this._initSuccessHandler=r,this._errorHandler=n,this._allData={},this._fileLoader=new lr.default(t,e.paths,null!==(s=e.autoUpdate)&&void 0!==s&&s,(e=>{var t,i;try{this._processFileData(e)}catch(e){null===(t=this._errorHandler)||void 0===t||t.call(this,e),null===(i=this._logger)||void 0===i||i.error(`Error processing files: ${e}`)}})),this._logger=e.logger,this._yamlParser=e.yamlParser}start(){(async()=>{var e;try{await this._fileLoader.loadAndWatch()}catch(t){null===(e=this._errorHandler)||void 0===e||e.call(this,t)}})()}stop(){this._fileLoader.close()}close(){this.stop()}_addItem(e,t){if(this._allData[e.namespace]||(this._allData[e.namespace]={}),this._allData[e.namespace][t.key])throw new Error(`found duplicate key: "${t.key}"`);this._allData[e.namespace][t.key]=t}_processFileData(e){const t=this._allData;this._allData={},e.forEach((e=>{let i;if(e.path.endsWith(".yml")||e.path.endsWith(".yaml")){if(!this._yamlParser)throw new Error(`Attempted to parse yaml file (${e.path}) without parser.`);i=this._yamlParser(e.data)}else i=JSON.parse(e.data);this._processParsedData(i,t)})),this._featureStore.init(this._allData,(()=>{this._initSuccessHandler(),this._initSuccessHandler=()=>{}}))}_processParsedData(e,t){Object.keys(e.flags||{}).forEach((t=>{(0,ar.processFlag)(e.flags[t]),this._addItem(or.default.Features,e.flags[t])})),Object.keys(e.flagValues||{}).forEach((i=>{var r,n;const s=null===(r=t[or.default.Features.namespace])||void 0===r?void 0:r[i];let{version:a}=null!=s?s:{version:1};s&&JSON.stringify(e.flagValues[i])!==JSON.stringify(null===(n=null==s?void 0:s.variations)||void 0===n?void 0:n[0])&&(a+=1);const o=function(e,t,i){return{key:e,on:!0,fallthrough:{variation:0},variations:[t],version:i}}(i,e.flagValues[i],a);(0,ar.processFlag)(o),this._addItem(or.default.Features,o)})),Object.keys(e.segments||{}).forEach((t=>{(0,ar.processSegment)(e.segments[t]),this._addItem(or.default.Segments,e.segments[t])}))}},Object.defineProperty(rr,"__esModule",{value:!0});const ur=nr;rr.default=class{constructor(e){this._options=e}create(e,t,i,r){const n={paths:this._options.paths,autoUpdate:this._options.autoUpdate,logger:this._options.logger||e.basicConfiguration.logger,yamlParser:this._options.yamlParser};return new ur.default(n,e.platform.fileSystem,t,i,r)}getFactory(){return(e,t,i,r)=>this.create(e,t,i,r)}};var cr={},dr={},hr={},fr={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.variationForBoolean=e.FALSE_VARIATION_INDEX=e.TRUE_VARIATION_INDEX=void 0,e.TRUE_VARIATION_INDEX=0,e.FALSE_VARIATION_INDEX=1,e.variationForBoolean=function(t){return t?e.TRUE_VARIATION_INDEX:e.FALSE_VARIATION_INDEX}}(fr);var gr={};Object.defineProperty(gr,"__esModule",{value:!0});const vr=o,_r=fr;class pr{constructor(e,t,i){this._flagBuilder=e,this._clauses=[],t&&(this._clauses=[...t]),void 0!==i&&(this._variation=i)}andMatch(e,t,...i){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new vr.AttributeReference(t),op:"in",values:i,negate:!1}),this}andNotMatch(e,t,...i){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new vr.AttributeReference(t),op:"in",values:i,negate:!0}),this}thenReturn(e){return vr.TypeValidators.Boolean.is(e)?(this._flagBuilder.booleanFlag(),this.thenReturn((0,_r.variationForBoolean)(e))):(this._variation=e,this._flagBuilder.addRule(this),this._flagBuilder)}build(e){return{id:`rule${e}`,variation:this._variation,clauses:this._clauses}}clone(){return new pr(this._flagBuilder,this._clauses,this._variation)}}gr.default=pr,Object.defineProperty(hr,"__esModule",{value:!0});const yr=o,mr=fr,br=gr;class wr{constructor(e,t){this._key=e,this._data={on:!0,variations:[]},t&&(this._data={on:t.on,variations:[...t.variations]},void 0!==t.offVariation&&(this._data.offVariation=t.offVariation),void 0!==t.fallthroughVariation&&(this._data.fallthroughVariation=t.fallthroughVariation),t.targetsByVariation&&(this._data.targetsByVariation=JSON.parse(JSON.stringify(t.targetsByVariation))),t.rules&&(this._data.rules=[],t.rules.forEach((e=>{var t;null===(t=this._data.rules)||void 0===t||t.push(e.clone())}))))}get _isBooleanFlag(){return 2===this._data.variations.length&&!0===this._data.variations[mr.TRUE_VARIATION_INDEX]&&!1===this._data.variations[mr.FALSE_VARIATION_INDEX]}booleanFlag(){return this._isBooleanFlag?this:this.variations(!0,!1).fallthroughVariation(mr.TRUE_VARIATION_INDEX).offVariation(mr.FALSE_VARIATION_INDEX)}variations(...e){return this._data.variations=[...e],this}on(e){return this._data.on=e,this}fallthroughVariation(e){return yr.TypeValidators.Boolean.is(e)?this.booleanFlag().fallthroughVariation((0,mr.variationForBoolean)(e)):(this._data.fallthroughVariation=e,this)}offVariation(e){return yr.TypeValidators.Boolean.is(e)?this.booleanFlag().offVariation((0,mr.variationForBoolean)(e)):(this._data.offVariation=e,this)}variationForAll(e){return this.on(!0).clearRules().clearAllTargets().fallthroughVariation(e)}valueForAll(e){return this.variations(e).variationForAll(0)}variationForUser(e,t){return this.variationForContext("user",e,t)}variationForContext(e,t,i){return yr.TypeValidators.Boolean.is(i)?this.booleanFlag().variationForContext(e,t,(0,mr.variationForBoolean)(i)):(this._data.targetsByVariation||(this._data.targetsByVariation={}),this._data.variations.forEach(((r,n)=>{if(n===i){const i=this._data.targetsByVariation[n]||{};e in i||(i[e]=[]);-1!==i[e].indexOf(t)||i[e].push(t),this._data.targetsByVariation[n]=i}else{const i=this._data.targetsByVariation[n];if(i){const r=i[e];if(r){const n=r.indexOf(t);-1!==n&&(r.splice(n,1),r.length||delete i[e])}Object.keys(i).length||delete this._data.targetsByVariation[n]}}})),this)}clearRules(){return delete this._data.rules,this}clearAllTargets(){return delete this._data.targetsByVariation,this}ifMatch(e,t,...i){return new br.default(this).andMatch(e,t,...i)}ifNotMatch(e,t,...i){return new br.default(this).andNotMatch(e,t,...i)}checkRatio(e){var t;return this._data.migration=null!==(t=this._data.migration)&&void 0!==t?t:{},this._data.migration.checkRatio=e,this}samplingRatio(e){return this._data.samplingRatio=e,this}addRule(e){this._data.rules||(this._data.rules=[]),this._data.rules.push(e)}build(e){const t={key:this._key,version:e,on:this._data.on,offVariation:this._data.offVariation,fallthrough:{variation:this._data.fallthroughVariation},variations:[...this._data.variations],migration:this._data.migration,samplingRatio:this._data.samplingRatio};if(this._data.targetsByVariation){const e=[],i=[];Object.entries(this._data.targetsByVariation).forEach((([t,r])=>{Object.entries(r).forEach((([r,n])=>{const s=parseInt(t,10);e.push({contextKind:r,values:"user"===r?[]:n,variation:s}),"user"===r&&i.push({values:n,variation:s})}))})),t.targets=i,t.contextTargets=e}return this._data.rules&&(t.rules=this._data.rules.map(((e,t)=>e.build(String(t))))),t}clone(){return new wr(this._key,this._data)}getKey(){return this._key}}hr.default=wr;var Sr={};Object.defineProperty(Sr,"__esModule",{value:!0});Sr.default=class{constructor(e,t,i,r,n){this._featureStore=e,this._onStop=r,this._listeners=n,this._flags=Object.assign({},t),this._segments=Object.assign({},i)}async start(){this._listeners.forEach((({processJson:e})=>{e({data:{flags:this._flags,segments:this._segments}})}))}stop(){this._onStop(this)}close(){this.stop()}async upsert(e,t){return this._featureStore.upsert(e,t)}},Object.defineProperty(dr,"__esModule",{value:!0});const kr=se,Er=Me,Or=ae,xr=oe,Dr=hr,Mr=Sr;dr.default=class{constructor(){this._currentFlags={},this._currentSegments={},this._dataSources=[],this._flagBuilders={}}getFactory(){return(e,t,i,r)=>{const n=(0,kr.createStreamListeners)(t,e.basicConfiguration.logger,{put:i}),s=new Mr.default(new Er.default(t),this._currentFlags,this._currentSegments,(e=>{this._dataSources.splice(this._dataSources.indexOf(e))}),n);return this._dataSources.push(s),s}}flag(e){return this._flagBuilders[e]?this._flagBuilders[e].clone():new Dr.default(e).booleanFlag()}update(e){const t=e.getKey(),i=this._currentFlags[t],r=i?i.version:0,n=e.build(r+1);return this._currentFlags[t]=n,this._flagBuilders[t]=e.clone(),Promise.all(this._dataSources.map((e=>e.upsert(xr.default.Features,n))))}usePreconfiguredFlag(e){const t=JSON.parse(JSON.stringify(e)),i=this._currentFlags[t.key],r=Object.assign(Object.assign({},t),{version:i?i.version+1:t.version});return(0,Or.processFlag)(r),this._currentFlags[t.key]=r,Promise.all(this._dataSources.map((e=>e.upsert(xr.default.Features,r))))}usePreconfiguredSegment(e){const t=JSON.parse(JSON.stringify(e)),i=this._currentSegments[t.key],r=Object.assign(Object.assign({},t),{version:i?i.version+1:t.version});return(0,Or.processSegment)(r),this._currentSegments[t.key]=r,Promise.all(this._dataSources.map((e=>e.upsert(xr.default.Segments,r))))}},Object.defineProperty(cr,"__esModule",{value:!0}),cr.TestDataRuleBuilder=cr.TestDataFlagBuilder=cr.TestData=void 0;const Pr=dr;cr.TestData=Pr.default;const Tr=hr;cr.TestDataFlagBuilder=Tr.default;const Cr=gr;cr.TestDataRuleBuilder=Cr.default,function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.FileDataSourceFactory=void 0;const n=rr;e.FileDataSourceFactory=n.default,i(cr,e),i(V,e)}(ir);var Fr={},jr={};Object.defineProperty(jr,"__esModule",{value:!0});jr.default=class{constructor(e,t){this.handlers={},this.closed=!1,this.url=e,this.options=t}addEventListener(e,t){this.handlers[e]=t}close(){this.closed=!0}simulateError(e){this.options.errorFilter(e)||(this.closed=!0)}},Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.NullEventSource=void 0;const Ir=jr;Fr.NullEventSource=Ir.default,function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.createMigration=e.LDMigrationSuccess=e.LDMigrationError=e.BigSegmentStoreStatusProviderImpl=e.LDClientImpl=e.platform=e.integrations=void 0;const n=s;e.BigSegmentStoreStatusProviderImpl=n.default;const u=a;e.LDClientImpl=u.default;const c=Qi;Object.defineProperty(e,"createMigration",{enumerable:!0,get:function(){return c.createMigration}}),Object.defineProperty(e,"LDMigrationError",{enumerable:!0,get:function(){return c.LDMigrationError}}),Object.defineProperty(e,"LDMigrationSuccess",{enumerable:!0,get:function(){return c.LDMigrationSuccess}}),e.integrations=ir,e.platform=o,i(l,e),i(De,e),i(Fr,e),i(o,e)}(n);class Rr{constructor(e){let t;switch(e){case"sha1":t=i.algo.SHA1;break;case"sha256":t=i.algo.SHA256;break;default:throw new Error("unsupported hash algorithm. Only sha1 and sha256 are supported.")}this._cryptoJSHasher=t.create()}digest(e){const t=this._cryptoJSHasher.finalize();let r;switch(e){case"base64":r=i.enc.Base64;break;case"hex":r=i.enc.Hex;break;default:throw new Error("unsupported output encoding. Only base64 and hex are supported.")}return t.toString(r)}update(e){return this._cryptoJSHasher.update(e),this}}class Ar{constructor(e,t){let r;switch(e){case"sha1":r=i.algo.SHA1;break;case"sha256":r=i.algo.SHA256;break;default:throw new Error("unsupported hash algorithm. Only sha1 and sha256 are supported.")}this._cryptoJSHmac=i.algo.HMAC.create(r,t)}digest(e){const t=this._cryptoJSHmac.finalize();if("base64"===e)return t.toString(i.enc.Base64);if("hex"===e)return t.toString(i.enc.Hex);throw new Error("unsupported output encoding. Only base64 and hex are supported.")}update(e){return this._cryptoJSHmac.update(e),this}}class Vr{createHash(e){return new Rr(e)}createHmac(e,t){return new Ar(e,t)}randomUUID(){return crypto.randomUUID()}}class Nr{fetch(e,t={}){return fetch(e,t)}createEventSource(e,t){return new n.NullEventSource(e,t)}getEventSourceCapabilities(){return{readTimeout:!1,headers:!1,customMethod:!1}}}class Lr{constructor(e){this.crypto=new Vr,this.requests=new Nr,this.info=e}}const Kr={stream:!1,sendEvents:!1,useLdd:!0,diagnosticOptOut:!0,logger:n.BasicLogger.get()};class $r extends n.LDClientImpl{constructor(t,i,r){const s=new e,a=new Lr(i),o={analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1},l=(e=>{var t;const i=Object.assign(Object.assign({},Kr),e);return null===(t=i.logger)||void 0===t||t.debug(`Using LD options: ${JSON.stringify(i)}`),i})(r);var u,c;super(t,a,l,(u=s,c=l.logger,{onError:e=>{u.listenerCount("error")?u.emit("error",e):null==c||c.error(e.message)},onFailed:e=>{u.emit("failed",e)},onReady:()=>{u.emit("ready")},onUpdate:n.noop,hasEventListeners:()=>!1}),o),this.emitter=s}}class Ur{constructor(e,t,i,r){this._edgeProvider=e,this._description=i,this._logger=r,this.close=n.noop,this.delete=n.noop,this.upsert=n.noop,this._rootKey=`LD-Env-${t}`}async get(e,t,i){const{namespace:r}=e,s="features"===r?"flags":r;this._logger.debug(`Requesting ${t} from ${this._rootKey}.${s}`);try{const e=await this._edgeProvider.get(this._rootKey);if(!e)throw new Error(`${this._rootKey}.${s} is not found in KV.`);const a=n.deserializePoll(e);if(!a)throw new Error(`Error deserializing ${s}`);switch(r){case"features":i(a.flags[t]);break;case"segments":i(a.segments[t]);break;default:i(null)}}catch(e){this._logger.error(e),i(null)}}async all(e,t=n.noop){const{namespace:i}=e,r="features"===i?"flags":i;this._logger.debug(`Requesting all from ${this._rootKey}.${r}`);try{const e=await this._edgeProvider.get(this._rootKey);if(!e)throw new Error(`${this._rootKey}.${r} is not found in KV.`);const s=n.deserializePoll(e);if(!s)throw new Error(`Error deserializing ${r}`);switch(i){case"features":t(s.flags);break;case"segments":t(s.segments);break;default:t({})}}catch(e){this._logger.error(e),t({})}}async initialized(e=n.noop){const t=null!==await this._edgeProvider.get(this._rootKey);this._logger.debug(`Is ${this._rootKey} initialized? ${t}`),e(t)}init(e,t){t()}getDescription(){return this._description}}const zr=(e,t)=>{const{featureStore:i,logger:r,sendEvents:n}=t,s=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]])}return i}(t,["featureStore","logger","sendEvents"]);if(!e)throw new Error("You must configure the client with a client key");if(!i||"object"!=typeof i||!i.get)throw new Error("You must configure the client with a feature store");if(!r)throw new Error("You must configure the client with a logger");if("{}"!==JSON.stringify(s))throw new Error(`Invalid configuration: ${Object.keys(s).toString()} not supported`);return!0};class Br{platformData(){return{name:"Cloudflare"}}sdkData(){return{name:"@launchdarkly/cloudflare-server-sdk",version:"2.6.3",userAgentBase:"CloudflareEdgeSDK"}}}var qr=Object.defineProperty,Hr=Object.getOwnPropertySymbols,Wr=Object.prototype.hasOwnProperty,Jr=Object.prototype.propertyIsEnumerable,Gr=(e,t,i)=>t in e?qr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;const Xr=(e,t,i={})=>{var r;const s=null!=(r=i.logger)?r:n.BasicLogger.get();return((e,t,i)=>(zr(e,i),new $r(e,t,i)))(e,new Br,((e,t)=>{for(var i in t||(t={}))Wr.call(t,i)&&Gr(e,i,t[i]);if(Hr)for(var i of Hr(t))Jr.call(t,i)&&Gr(e,i,t[i]);return e})({featureStore:new Ur(t,e,"Cloudflare",s),logger:s},i))};export{Ur as EdgeFeatureStore,Xr as init};
1
+ import{EventEmitter as e}from"node:events";import t from"semver";import i from"crypto-js";var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n={},s={};Object.defineProperty(s,"__esModule",{value:!0});s.default=class{constructor(e){this._onRequestStatus=e}getStatus(){return this._lastStatus}async requireStatus(){return this._lastStatus||await this._onRequestStatus(),this._lastStatus}notify(){var e;this._lastStatus&&(null===(e=this._listener)||void 0===e||e.call(this,this._lastStatus))}setListener(e){this._listener=e}setStatus(e){this._lastStatus=e}};var a={},o={};!function(e){function t(e){return e.indexOf("~")?e.replace(/~1/g,"/").replace(/~0/g,"~"):e}class i{constructor(e,i=!1){if(i){const t=e;this._components=[t],this.isValid=""!==t,this.redactionName=t.startsWith("/")?`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`:t}else{if(this.redactionName=e,""===e||"/"===e||e.match(/\/\/|(^\/.*~[^0|^1])|~$/))return this.isValid=!1,void(this._components=[]);!function(e){return!e.startsWith("/")}(e)?e.indexOf("/",1)<0?this._components=[t(e.slice(1))]:this._components=function(e){return(e.startsWith("/")?e.substring(1):e).split("/").map((e=>t(e)))}(e):this._components=[e],"_meta"===this._components[0]?this.isValid=!1:this.isValid=!0}}get(e){const{_components:t,isValid:i}=this;if(!i)return;let r=e;for(let e=0;e<t.length;e+=1){const i=t[e];if(null==r||!Object.prototype.hasOwnProperty.call(r,i)||"object"!=typeof r||Array.isArray(r))return;r=r[i]}return r}getComponent(e){return this._components[e]}get depth(){return this._components.length}get isKind(){return 1===this._components.length&&"kind"===this._components[0]}compare(e){return this.depth===e.depth&&this._components.every(((t,i)=>t===e.getComponent(i)))}}i.InvalidReference=new i("");class r{is(e){if(Array.isArray(e))return!1;const t=typeof e;return"function"===t||"object"===t}getType(){return"factory method or object"}}class n{constructor(e,t){this._typeName=e,this.typeOf=typeof t}is(e){return!Array.isArray(e)&&typeof e===this.typeOf}getType(){return this._typeName}}class s{constructor(e,t){this._typeName=e,this.typeOf=typeof t}is(e){return!!Array.isArray(e)&&(!(e.length>0)||e.every((e=>typeof e===this.typeOf)))}getType(){return this._typeName}}class a extends n{constructor(e){super(`number with minimum value of ${e}`,0),this.min=e}is(e){return typeof e===this.typeOf&&e>=this.min}}class o extends n{constructor(e){super(`string matching ${e}`,""),this.expression=e}is(e){return"string"==typeof e&&!!e.match(this.expression)}}class l{is(e){return"function"==typeof e}getType(){return"function"}}class u{is(e){return"boolean"==typeof e||null==e}getType(){return"boolean | undefined | null"}}const c=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/;class d{is(e){return"number"==typeof e||"string"==typeof e&&c.test(e)}getType(){return"date"}}class h extends o{constructor(){super(/^(\w|\.|-)+$/)}is(e){return super.is(e)&&"kind"!==e}}class f{static createTypeArray(e,t){return new s(e,t)}static numberWithMin(e){return new a(e)}static stringMatchingRegex(e){return new o(e)}}function g(e){return"kind"in e&&(f.String.is(e.kind)&&"multi"!==e.kind)}function _(e){return"kind"in e&&(f.String.is(e.kind)&&"multi"===e.kind)}function v(e){return!("kind"in e)||null===e.kind||void 0===e.kind}f.String=new n("string",""),f.Number=new n("number",0),f.ObjectOrFactory=new r,f.Object=new n("object",{}),f.StringArray=new s("string[]",""),f.Boolean=new n("boolean",!0),f.Function=new l,f.Date=new d,f.Kind=new h,f.NullableBoolean=new u;const p="user";function y(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}function m(e){return f.Kind.is(e)}function b(e){return f.String.is(e)&&""!==e}function w(e,t=!1){return e?e.map((e=>new i(e,t))):[]}class S{constructor(e,t,i){this._isMulti=!1,this._isUser=!1,this._wasLegacy=!1,this._contexts={},this.kind=t,this.valid=e,this.message=i}static _contextForError(e,t){return new S(!1,e,t)}static _getValueFromContext(e,t){if(t&&e.isValid)return 1===e.depth&&"anonymous"===e.getComponent(0)?!!t?.anonymous:e.get(t)}_contextForKind(e){return this._isMulti?this._contexts[e]:this.kind===e?this._context:void 0}static _fromMultiKindContext(e){const t=Object.keys(e).filter((e=>"kind"!==e)),i=t.every(m);if(!t.length)return S._contextForError("multi","A multi-kind context must contain at least one kind");if(!i)return S._contextForError("multi","Context contains invalid kinds");const r={};let n=!0;const s=t.reduce(((t,i)=>{const s=e[i];var a;return(a=s)&&f.Object.is(a)?(t[i]=s,r[i]=w(s._meta?.privateAttributes)):n=!1,t}),{});if(!n)return S._contextForError("multi","Context contained contexts that were not objects");if(!Object.values(s).every((e=>b(e.key))))return S._contextForError("multi","Context contained invalid keys");if(1===t.length){const e=t[0],i=new S(!0,e);return i._context={...s[e],kind:e},i._privateAttributeReferences=r,i._isUser="user"===e,i}const a=new S(!0,e.kind);return a._contexts=s,a._privateAttributeReferences=r,a._isMulti=!0,a}static _fromSingleKindContext(e){const{key:t,kind:i}=e,r=m(i),n=b(t);if(!r)return S._contextForError(i??"unknown","The kind was not valid for the context");if(!n)return S._contextForError(i,"The key for the context was not valid");const s=w(e._meta?.privateAttributes),a=new S(!0,i);return a._isUser="user"===i,a._context=e,a._privateAttributeReferences={[i]:s},a}static _fromLegacyUser(e){if(!(void 0!==e.key&&null!==e.key))return S._contextForError("user","The key for the context was not valid");const t=new S(!0,"user");return t._isUser=!0,t._wasLegacy=!0,t._context=function(e){const t={...e.custom||[],kind:"user",key:String(e.key)};if(null!=e.anonymous){const i=!!e.anonymous;delete t.anonymous,t.anonymous=i}return null!==e.name&&void 0!==e.name&&(t.name=e.name),null!==e.ip&&void 0!==e.ip&&(t.ip=e.ip),null!==e.firstName&&void 0!==e.firstName&&(t.firstName=e.firstName),null!==e.lastName&&void 0!==e.lastName&&(t.lastName=e.lastName),null!==e.email&&void 0!==e.email&&(t.email=e.email),null!==e.avatar&&void 0!==e.avatar&&(t.avatar=e.avatar),null!==e.country&&void 0!==e.country&&(t.country=e.country),null!==e.privateAttributeNames&&void 0!==e.privateAttributeNames&&(t._meta={privateAttributes:e.privateAttributeNames}),t}(e),t._privateAttributeReferences={user:w(e.privateAttributeNames,!0)},t}static fromLDContext(e){return e?g(e)?S._fromSingleKindContext(e):_(e)?S._fromMultiKindContext(e):v(e)?S._fromLegacyUser(e):S._contextForError("unknown","Context was not of a valid kind"):S._contextForError("unknown","No context specified. Returning default value")}static toLDContext(e){if(!e.valid)return;const t=e.getContexts();if(!e._isMulti)return t[0][1];const i={kind:"multi"};return t.forEach((e=>{const t=e[0],r=e[1];i[t]=r})),i}valueForKind(e,t=p){return e.isKind?this.kinds:S._getValueFromContext(e,this._contextForKind(t))}key(e=p){return this._contextForKind(e)?.key}get isMultiKind(){return this._isMulti}get canonicalKey(){return this._isUser?this._context.key:this._isMulti?Object.keys(this._contexts).sort().map((e=>`${e}:${y(this._contexts[e].key)}`)).join(":"):`${this.kind}:${y(this._context.key)}`}get kinds(){return this._isMulti?Object.keys(this._contexts):[this.kind]}get kindsAndKeys(){return this._isMulti?Object.entries(this._contexts).reduce(((e,[t,i])=>(e[t]=i.key,e)),{}):{[this.kind]:this._context.key}}privateAttributes(e){return this._privateAttributeReferences?.[e]||[]}getContexts(){return this._isMulti?Object.entries(this._contexts):[[this.kind,this._context]]}get legacy(){return this._wasLegacy}}S.UserKind=p;const k=["key","kind","_meta","anonymous"].map((e=>new i(e,!0))),E=["name","ip","firstName","lastName","email","avatar","country"];class O{constructor(e,t){this._allAttributesPrivate=e,this._privateAttributes=t}filter(e,t=!1){const i=e.getContexts();if(1===i.length)return this._filterSingleKind(e,i[0][1],i[0][0],t);const r={kind:"multi"};return i.forEach((([i,n])=>{r[i]=this._filterSingleKind(e,n,i,t)})),r}_getAttributesToFilter(e,t,r,n){return(n?Object.keys(t).map((e=>new i(e,!0))):[...this._privateAttributes,...e.privateAttributes(r)]).filter((e=>!k.some((t=>t.compare(e)))))}_filterSingleKind(e,t,i,r){const n=this._allAttributesPrivate||r&&!0===t.anonymous,{cloned:s,excluded:a}=function(e,t){const i=[],r={},n=[];for(i.push(...Object.keys(e).map((t=>({key:t,ptr:[t],source:e,parent:r,visited:[e]}))));i.length;){const e=i.pop(),r=t.find((t=>{return i=t,r=e.ptr,i.depth===r.length&&r.every(((e,t)=>e===i.getComponent(t)));var i,r}));if(r)n.push(r.redactionName);else{const t=e.source[e.key];null===t?e.parent[e.key]=t:Array.isArray(t)?e.parent[e.key]=[...t]:"object"==typeof t?e.visited.includes(t)||(e.parent[e.key]={},i.push(...Object.keys(t).map((i=>({key:i,ptr:[...e.ptr,i],source:t,parent:e.parent[e.key],visited:[...e.visited,t]}))))):e.parent[e.key]=t}}return{cloned:r,excluded:n.sort()}}(t,this._getAttributesToFilter(e,t,i,n));return e.legacy&&E.forEach((e=>{e in s&&(s[e]=String(s[e]))})),a.length&&(s._meta||(s._meta={}),s._meta.redactedAttributes=a),s._meta&&(delete s._meta.privateAttributes,0===Object.keys(s._meta).length&&delete s._meta),s}}var x,D,P,M;e.DataSourceErrorKind=void 0,(x=e.DataSourceErrorKind||(e.DataSourceErrorKind={})).Unknown="UNKNOWN",x.NetworkError="NETWORK_ERROR",x.ErrorResponse="ERROR_RESPONSE",x.InvalidData="INVALID_DATA";class T extends Error{constructor(e){super(e),this.name="LaunchDarklyFileDataSourceError"}}class j extends Error{constructor(e,t,i,r=!0){super(t),this.kind=e,this.status=i,this.name="LaunchDarklyPollingError",this.recoverable=r}}class I extends Error{constructor(e,t,i,r=!0){super(t),this.kind=e,this.code=i,this.name="LaunchDarklyStreamingError",this.recoverable=r}}e.AutoEnvAttributes=void 0,(D=e.AutoEnvAttributes||(e.AutoEnvAttributes={}))[D.Disabled=0]="Disabled",D[D.Enabled=1]="Enabled",function(e){e[e.AnalyticsEvents=0]="AnalyticsEvents",e[e.DiagnosticEvent=1]="DiagnosticEvent"}(P||(P={})),function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.FailedAndMustShutDown=2]="FailedAndMustShutDown"}(M||(M={}));var C=Object.freeze({__proto__:null,get LDDeliveryStatus(){return M},get LDEventType(){return P}});function F(e){if("string"==typeof e)return e;if(void 0===e)return"undefined";if(null===e)return"null";if(Object.prototype.hasOwnProperty.call(e,"toString"))try{return e.toString()}catch{}if("bigint"==typeof e)return`${e}n`;try{return JSON.stringify(e)}catch(e){return e instanceof TypeError&&e.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}const R={s:e=>F(e),d:e=>function(e){return"symbol"==typeof e?"NaN":"bigint"==typeof e?`${e}n`:String(Number(e))}(e),i:e=>function(e){return"symbol"==typeof e?"NaN":"bigint"==typeof e?`${e}n`:String(parseInt(e,10))}(e),f:e=>function(e){return"symbol"==typeof e?"NaN":String(parseFloat(e))}(e),j:e=>F(e),o:e=>F(e),O:e=>F(e),c:()=>""};function A(...e){const t=e.shift();if(f.String.is(t)){let i="",r=0;for(;r<t.length;){const n=t.charAt(r);if("%"===n){if(r+1<t.length){const n=t.charAt(r+1);if(n in R&&e.length){const t=e.shift();i+=R[n]?.(t)}else i+="%"===n?"%":`%${n}`;r+=2}}else i+=n,r+=1}return e.length&&(i.length&&(i+=" "),i+=e.map(F).join(" ")),i}return e.map(F).join(" ")}var V;!function(e){e[e.debug=0]="debug",e[e.info=1]="info",e[e.warn=2]="warn",e[e.error=3]="error",e[e.none=4]="none"}(V||(V={}));const N=["debug","info","warn","error","none"];class L{static get(){return new L({})}constructor(e){if(this._logLevel=V[e.level??"info"]??V.info,this._name=e.name??"LaunchDarkly",this._formatter=e.formatter,"object"==typeof e.destination)this._destinations={[V.debug]:e.destination.debug,[V.info]:e.destination.info,[V.warn]:e.destination.warn,[V.error]:e.destination.error};else if("function"==typeof e.destination){const{destination:t}=e;this._destinations={[V.debug]:t,[V.info]:t,[V.warn]:t,[V.error]:t}}}_tryFormat(...e){try{return this._formatter?this._formatter?.(...e):A(...e)}catch{return A(...e)}}_tryWrite(e,t){try{e(t)}catch{console.error(t)}}_log(e,t){if(e>=this._logLevel){const i=`${N[e]}: [${this._name}]`;try{const r=this._destinations?.[e];r?this._tryWrite(r,`${i} ${this._tryFormat(...t)}`):console.error(...t)}catch{console.error(...t)}}}error(...e){this._log(V.error,e)}warn(...e){this._log(V.warn,e)}info(...e){this._log(V.info,e)}debug(...e){this._log(V.debug,e)}}const K={error:f.Function,warn:f.Function,info:f.Function,debug:f.Function};class ${constructor(e,t){Object.entries(K).forEach((([t,i])=>{if(!i.is(e[t]))throw new Error(`Provided logger instance must support logger.${t}(...) method`)})),this._logger=e,this._fallback=t}_log(e,t){try{this._logger[e](...t)}catch{this._fallback[e](...t)}}error(...e){this._log("error",e)}warn(...e){this._log("warn",e)}info(...e){this._log("info",e)}debug(...e){this._log("debug",e)}}class U{static deprecated(e,t){return`"${e}" is deprecated, please use "${t}"`}static optionBelowMinimum(e,t,i){return`Config option "${e}" had invalid value of ${t}, using minimum of ${i} instead`}static unknownOption(e){return`Ignoring unknown config option "${e}"`}static wrongOptionType(e,t,i){return`Config option "${e}" should be of type ${t}, got ${i}, using default value`}static wrongOptionTypeBoolean(e,t){return`Config option "${e}" should be a boolean, got ${t}, converting to boolean`}static invalidTagValue(e){return`Config option "${e}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(e){return`Value of "${e}" was longer than 64 characters and was discarded.`}static partialEndpoint(e){return`You have set custom uris without specifying the ${e} URI; connections may not work properly`}}const z=f.stringMatchingRegex(/^(\w|\.|-)+$/),B=(e,t)=>z.is(e)?e.length>64?{valid:!1,message:U.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:U.invalidTagValue(t)};function H(e){return e.replace(/\/+$/,"")}function q(e){return e.replace(/^\/+/,"").replace(/\?$/,"")}class W{constructor(e,t,i=W.DEFAULT_EVENTS,r="/bulk",n="/diagnostic",s=!0,a){this.streaming=H(e),this.polling=H(t),this.events=H(i),this.analyticsEventPath=r,this.diagnosticEventPath=n,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}}function J(e,t){if(0===t.length)return e;return`${e}?${t.map((({key:e,value:t})=>`${e}=${t}`)).join("&")}`}function G(e,t,i){const r=q(t);return J(`${e.events}/${r}`,i)}W.DEFAULT_EVENTS="https://events.launchdarkly.com";class X extends Error{constructor(e){super(e),this.name="LaunchDarklyUnexpectedResponseError"}}class Y extends Error{constructor(e){super(e),this.name="LaunchDarklyClientError"}}class Q extends Error{constructor(e){super(e),this.name="LaunchDarklyTimeoutError"}}function Z(e){return!(e>=400&&e<500)||(400===e||408===e||429===e)}function ee(e){return 413===e||Z(e)}const te=(e,t)=>e?Object.entries(e).reduce(((e,[i,r])=>(!Boolean(r)||(e=>"{}"===JSON.stringify(e))(r)||t?.includes(i)||(e[i]="object"==typeof r?te(r,t):r),e)),{}):e;function ie(e,t,i){let r;r=e.status?`error ${e.status}${401===e.status?" (invalid SDK key)":""}`:`I/O error (${e.message||"unknown error"})`;return`Received ${r} for ${t} - ${i??"giving up permanently"}`}const re=async(e=1e3)=>new Promise((t=>{setTimeout(t,e)}));var ne;!function(e){e.MalformedFlag="MALFORMED_FLAG",e.UserNotSpecified="USER_NOT_SPECIFIED",e.FlagNotFound="FLAG_NOT_FOUND",e.ClientNotReady="CLIENT_NOT_READY",e.WrongType="WRONG_TYPE"}(ne||(ne={}));var se=ne;class ae{static invalidMetricValue(e){return`The track function was called with a non-numeric "metricValue" (${e}), only numeric metric values are supported.`}}ae.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";class oe{constructor(e,t){const{basicConfiguration:i,platform:r}=e,{serviceEndpoints:{analyticsEventPath:n,diagnosticEventPath:s}}=i,{crypto:a,requests:o}=r;this._defaultHeaders={...t},this._eventsUri=G(i.serviceEndpoints,n,[]),this._diagnosticEventsUri=G(i.serviceEndpoints,s,[]),this._requests=o,this._crypto=a}async _tryPostingEvents(e,t,i,r){const n={status:M.Succeeded},s={...this._defaultHeaders,"content-type":"application/json"};let a;i&&(s["x-launchdarkly-payload-id"]=i,s["x-launchDarkly-event-schema"]="4");try{const{status:i,headers:r}=await this._requests.fetch(t,{headers:s,body:JSON.stringify(e),method:"POST",keepalive:!0}),o=Date.parse(r.get("date")||"");if(o&&(n.serverTime=o),i<=204)return n;if(a=new X(ie({status:i,message:"some events were dropped"},"event posting")),!Z(i))return ee(i)?n.status=M.Failed:n.status=M.FailedAndMustShutDown,n.error=a,n}catch(e){a=e}return a&&!r?(n.status=M.Failed,n.error=a,n):(await re(),this._tryPostingEvents(e,this._eventsUri,i,!1))}async sendEventData(e,t){const i=e===P.AnalyticsEvents?this._crypto.randomUUID():void 0,r=e===P.AnalyticsEvents?this._eventsUri:this._diagnosticEventsUri;return this._tryPostingEvents(t,r,i,!0)}}function le(e){return"feature"===e.kind}class ue{constructor(e,t,i,r,n,s){this.count=e,this.key=t,this.value=i,this.version=n,this.variation=s,this.default=r}increment(){this.count+=1}}class ce{constructor(){this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}summarizeEvent(e){if(le(e)&&!e.excludeFromSummaries){const t=function(e){return`${e.key}:${null!==e.variation&&void 0!==e.variation?e.variation:""}:${null!==e.version&&void 0!==e.version?e.version:""}`}(e),i=this._counters[t];let r=this._contextKinds[e.key];r||(r=new Set,this._contextKinds[e.key]=r),e.context.kinds.forEach((e=>r.add(e))),i?i.increment():this._counters[t]=new ue(1,e.key,e.value,e.default,e.version,e.variation),(0===this._startDate||e.creationDate<this._startDate)&&(this._startDate=e.creationDate),e.creationDate>this._endDate&&(this._endDate=e.creationDate)}}getSummary(){const e=Object.values(this._counters).reduce(((e,t)=>{let i=e[t.key];i||(i={default:t.default,counters:[],contextKinds:[...this._contextKinds[t.key]]},e[t.key]=i);const r={value:t.value,count:t.count};return void 0!==t.variation&&null!==t.variation&&(r.variation=t.variation),void 0!==t.version&&null!==t.version?r.version=t.version:r.unknown=!0,i.counters.push(r),e}),{});return{startDate:this._startDate,endDate:this._endDate,features:e,kind:"summary"}}clearSummary(){this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}}class de extends Error{constructor(e){super(e),this.name="LaunchDarklyInvalidSDKKeyError"}}function he(e){const t=Math.trunc(e);return 1===t||0!==t&&0===Math.floor(Math.random()*t)}class fe{constructor(e,t,i,r,n=1,s){this.context=e,this.key=t,this.data=i,this.metricValue=r,this.samplingRatio=n,this.url=s,this.kind="custom",this.creationDate=Date.now(),this.context=e}}class ge{constructor(e,t,i,r,n,s,a,o,l,u,c,d,h=1){this.withReasons=e,this.context=t,this.key=i,this.samplingRatio=h,this.kind="feature",this.creationDate=Date.now(),this.value=r,this.default=n,void 0!==s&&(this.version=s),void 0!==a&&(this.variation=a),void 0!==o&&(this.trackEvents=o),void 0!==l&&(this.prereqOf=l),void 0!==u&&(this.reason=u),void 0!==c&&(this.debugEventsUntilDate=c),void 0!==d&&(this.excludeFromSummaries=d)}}class _e{constructor(e,t=1){this.context=e,this.samplingRatio=t,this.kind="identify",this.creationDate=Date.now()}}var ve=Object.freeze({__proto__:null,ClientMessages:ae,DiagnosticsManager:class{constructor(e,t,i){this._platform=t,this._diagnosticInitConfig=i,this._streamInits=[],this._startTime=Date.now(),this._dataSinceDate=this._startTime,this._id={diagnosticId:t.crypto.randomUUID(),sdkKeySuffix:e.length>6?e.substring(e.length-6):e}}createInitEvent(){const e=this._platform.info.sdkData(),t=this._platform.info.platformData();return{kind:"diagnostic-init",id:this._id,creationDate:this._startTime,sdk:e,configuration:this._diagnosticInitConfig,platform:{name:t.name,osArch:t.os?.arch,osName:t.os?.name,osVersion:t.os?.version,...t.additional||{}}}}recordStreamInit(e,t,i){const r={timestamp:e,failed:t,durationMillis:i};this._streamInits.push(r)}createStatsEventAndReset(e,t,i){const r=Date.now(),n={kind:"diagnostic",id:this._id,creationDate:r,dataSinceDate:this._dataSinceDate,droppedEvents:e,deduplicatedUsers:t,eventsInLastBatch:i,streamInits:this._streamInits};return this._streamInits=[],this._dataSinceDate=r,n}},ErrorKinds:se,EventFactoryBase:class{constructor(e){this._withReasons=e}evalEvent(e){return new ge(this._withReasons,e.context,e.flagKey,e.value,e.defaultVal,e.version,e.variation??void 0,e.trackEvents||e.addExperimentData,e.prereqOfFlagKey,this._withReasons||e.addExperimentData?e.reason:void 0,e.debugEventsUntilDate,e.excludeFromSummaries,e.samplingRatio)}unknownFlagEvent(e,t,i){return new ge(this._withReasons,i,e,t,t,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(e){return new _e(e,1)}customEvent(e,t,i,r,n=1){return new fe(t,e,i??void 0,r??void 0,n)}},EventProcessor:class{constructor(e,t,r,n,s,a=!0){this._config=e,this._contextDeduplicator=n,this._diagnosticsManager=s,this._summarizer=new ce,this._queue=[],this._lastKnownPastTime=0,this._droppedEvents=0,this._deduplicatedUsers=0,this._exceededCapacity=!1,this._eventsInLastBatch=0,this._shutdown=!1,this._flushUsersTimer=null,this._capacity=e.eventsCapacity,this._logger=t.basicConfiguration.logger,this._eventSender=new oe(t,r),this._contextFilter=new O(e.allAttributesPrivate,e.privateAttributes.map((e=>new i(e)))),a&&this.start()}start(){if(void 0!==this._contextDeduplicator?.flushInterval&&(this._flushUsersTimer=setInterval((()=>{this._contextDeduplicator?.flush()}),1e3*this._contextDeduplicator.flushInterval)),this._flushTimer=setInterval((async()=>{try{await this.flush()}catch(e){this._logger?.debug(`Flush failed: ${e}`)}}),1e3*this._config.flushInterval),this._diagnosticsManager){const e=this._diagnosticsManager.createInitEvent();this._postDiagnosticEvent(e),this._diagnosticsTimer=setInterval((()=>{const e=this._diagnosticsManager.createStatsEventAndReset(this._droppedEvents,this._deduplicatedUsers,this._eventsInLastBatch);this._droppedEvents=0,this._deduplicatedUsers=0,this._postDiagnosticEvent(e)}),1e3*this._config.diagnosticRecordingInterval)}this._logger?.debug("Started EventProcessor.")}_postDiagnosticEvent(e){this._eventSender.sendEventData(P.DiagnosticEvent,e)}close(){clearInterval(this._flushTimer),this._flushUsersTimer&&clearInterval(this._flushUsersTimer),this._diagnosticsTimer&&clearInterval(this._diagnosticsTimer)}async flush(){if(this._shutdown)throw new de("Events cannot be posted because a permanent error has been encountered. This is most likely an invalid SDK key. The specific error information is logged independently.");const e=this._queue;this._queue=[];const t=this._summarizer.getSummary();this._summarizer.clearSummary(),Object.keys(t.features).length&&e.push(t),e.length&&(this._eventsInLastBatch=e.length,this._logger?.debug("Flushing %d events",e.length),await this._tryPostingEvents(e))}sendEvent(e){if(this._shutdown)return;if("migration_op"===e.kind){if(he(e.samplingRatio)){const t={...e};1===t.samplingRatio&&delete t.samplingRatio,this._enqueue(t)}return}this._summarizer.summarizeEvent(e);const t=le(e),i=t&&e.trackEvents||!t,r=this._shouldDebugEvent(e),n=function(e){return"identify"===e.kind}(e),s=this._contextDeduplicator?.processContext(e.context);s||n||(this._deduplicatedUsers+=1);s&&!n&&this._enqueue(this._makeOutputEvent({kind:"index",creationDate:e.creationDate,context:e.context,samplingRatio:1},!1)),i&&he(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!1)),r&&he(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!0))}_makeOutputEvent(e,t){switch(e.kind){case"feature":{const i={kind:t?"debug":"feature",creationDate:e.creationDate,context:this._contextFilter.filter(e.context,!t),key:e.key,value:e.value,default:e.default};return 1!==e.samplingRatio&&(i.samplingRatio=e.samplingRatio),e.prereqOf&&(i.prereqOf=e.prereqOf),void 0!==e.variation&&(i.variation=e.variation),void 0!==e.version&&(i.version=e.version),e.reason&&(i.reason=e.reason),i}case"index":case"identify":{const t={kind:e.kind,creationDate:e.creationDate,context:this._contextFilter.filter(e.context)};return 1!==e.samplingRatio&&(t.samplingRatio=e.samplingRatio),t}case"custom":{const t={kind:"custom",creationDate:e.creationDate,key:e.key,contextKeys:e.context.kindsAndKeys};return 1!==e.samplingRatio&&(t.samplingRatio=e.samplingRatio),void 0!==e.data&&(t.data=e.data),void 0!==e.metricValue&&(t.metricValue=e.metricValue),void 0!==e.url&&(t.url=e.url),t}case"click":return{kind:"click",creationDate:e.creationDate,contextKeys:e.context.kindsAndKeys,key:e.key,url:e.url,selector:e.selector};case"pageview":return{kind:"pageview",creationDate:e.creationDate,contextKeys:e.context.kindsAndKeys,key:e.key,url:e.url};default:return e}}_enqueue(e){this._queue.length<this._capacity?(this._queue.push(e),this._exceededCapacity=!1):(this._exceededCapacity||(this._exceededCapacity=!0,this._logger?.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this._droppedEvents+=1)}_shouldDebugEvent(e){return le(e)&&e.debugEventsUntilDate&&e.debugEventsUntilDate>this._lastKnownPastTime&&e.debugEventsUntilDate>Date.now()}async _tryPostingEvents(e){const t=await this._eventSender.sendEventData(P.AnalyticsEvents,e);if(t.status===M.FailedAndMustShutDown&&(this._shutdown=!0),t.serverTime&&(this._lastKnownPastTime=t.serverTime),t.error)throw t.error}},InputCustomEvent:fe,InputEvalEvent:ge,InputIdentifyEvent:_e,NullEventProcessor:class{close(){}async flush(){}sendEvent(){}},PayloadReader:class{constructor(e,t,i,r){this._objProcessors=t,this._errorHandler=i,this._logger=r,this._listeners=[],this._tempId=void 0,this._tempBasis=void 0,this._tempUpdates=[],this._processServerIntent=e=>{if(this._resetState(),!e.payloads.length)return;const t=e.payloads[0];switch(t?.code){case"xfer-full":this._tempBasis=!0;break;case"xfer-changes":case"none":this._tempBasis=!1;break;default:return}this._tempId=t?.id},this._processPutObject=e=>{if(!(this._tempId&&e.kind&&e.key&&e.version&&e.object))return;const t=this._processObj(e.kind,e.object);t?this._tempUpdates.push({kind:e.kind,key:e.key,version:e.version,object:t}):this._logger?.warn(`Unable to prcoess object for kind: '${e.kind}'`)},this._processDeleteObject=e=>{this._tempId&&e.kind&&e.key&&e.version&&this._tempUpdates.push({kind:e.kind,key:e.key,version:e.version,deleted:!0})},this._processPayloadTransferred=e=>{if(!this._tempId||!e.state||!e.version||void 0===this._tempBasis)return void this._resetState();const t={id:this._tempId,version:e.version,state:e.state,basis:this._tempBasis,updates:this._tempUpdates};this._listeners.forEach((e=>e(t))),this._resetState()},this._processGoodbye=e=>{this._logger?.info(`Goodbye was received from the LaunchDarkly connection with reason: ${e.reason}.`),this._resetState()},this._processError=e=>{this._logger?.info(`An issue was encountered receiving updates for payload ${this._tempId} with reason: ${e.reason}. Automatic retry will occur.`),this._resetState()},this._attachHandler(e,"server-intent",this._processServerIntent),this._attachHandler(e,"put-object",this._processPutObject),this._attachHandler(e,"delete-object",this._processDeleteObject),this._attachHandler(e,"payload-transferred",this._processPayloadTransferred),this._attachHandler(e,"goodbye",this._processGoodbye),this._attachHandler(e,"error",this._processError)}addPayloadListener(e){this._listeners.push(e)}removePayloadListener(e){const t=this._listeners.indexOf(e,0);t>-1&&this._listeners.splice(t,1)}_attachHandler(t,i,r){t.addEventListener(i,(async t=>{if(t?.data){this._logger?.debug(`Received ${i} event. Data is ${t.data}`);try{r(JSON.parse(t.data))}catch{this._logger?.error(`Stream received data that was unable to be processed in "${i}" message`),this._logger?.debug(`Data follows: ${t.data}`),this._errorHandler?.(e.DataSourceErrorKind.InvalidData,"Malformed data in event stream")}}else this._errorHandler?.(e.DataSourceErrorKind.Unknown,"Unexpected message from event stream")}))}_processObj(e,t){return this._objProcessors[e]?.(t)}_resetState(){this._tempId=void 0,this._tempBasis=void 0,this._tempUpdates=[]}},isLegacyUser:v,isMultiKind:_,isSingleKind:g,shouldSample:he});e.ApplicationTags=class{constructor(e){const t={},i=e?.application,r=e?.logger;i&&Object.entries(i).forEach((([e,i])=>{if(null!=i){const{valid:n,message:s}=B(i,`application.${e}`);n?"versionName"===e?t["application-version-name"]=[i]:t[`application-${e}`]=[i]:r?.warn(s)}}));const n=Object.keys(t);n.length&&(this.value=n.sort().flatMap((e=>t[e].sort().map((t=>`${e}/${t}`)))).join(" "))}},e.AttributeReference=i,e.BasicLogger=L,e.ClientContext=class{constructor(e,t,i){this.platform=i,this.basicConfiguration={tags:t.tags,logger:t.logger,offline:t.offline,serviceEndpoints:t.serviceEndpoints,sdkKey:e}}},e.Context=S,e.ContextFilter=O,e.DateValidator=d,e.FactoryOrInstance=r,e.Function=l,e.KindValidator=h,e.LDClientError=Y,e.LDFileDataSourceError=T,e.LDPollingError=j,e.LDStreamingError=I,e.LDTimeoutError=Q,e.LDUnexpectedResponseError=X,e.NullableBoolean=u,e.NumberWithMinimum=a,e.OptionMessages=U,e.SafeLogger=$,e.ServiceEndpoints=W,e.StringMatchingRegex=o,e.Type=n,e.TypeArray=s,e.TypeValidators=f,e.base64UrlEncode=(e,t)=>t.btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.cancelableTimedPromise=function(e,t){let i,r;return{promise:new Promise(((n,s)=>{r=n,i=setTimeout((()=>{s(new Q(`${t} timed out after ${e} seconds.`))}),1e3*e)})),cancel:()=>{r(),clearTimeout(i)}}},e.clone=function(e){return null==e?e:JSON.parse(JSON.stringify(e))},e.createSafeLogger=e=>{const t=new L({level:"info",destination:console.error,formatter:A});return e?new $(e,t):t},e.debounce=(e,t=5e3)=>{let i;return(...r)=>{clearTimeout(i),i=setTimeout((()=>{e(...r)}),t)}},e.deepCompact=te,e.defaultHeaders=function(e,t,i,r=!0,n="user-agent"){const{userAgentBase:s,version:a,wrapperName:o,wrapperVersion:l}=t.sdkData(),u={[n]:`${s??"NodeJSClient"}/${a}`};return r&&(u.authorization=e),o&&(u["x-launchdarkly-wrapper"]=l?`${o}/${l}`:o),i?.value&&(u["x-launchdarkly-tags"]=i.value),u},e.fastDeepEqual=function e(t,i){if(t===i)return!0;if(t&&i&&"object"==typeof t&&"object"==typeof i){if(t.constructor!==i.constructor)return!1;var r,n,s;if(Array.isArray(t)){if((r=t.length)!=i.length)return!1;for(n=r;0!=n--;)if(!e(t[n],i[n]))return!1;return!0}if(t instanceof Map&&i instanceof Map){if(t.size!==i.size)return!1;for(n of t.entries())if(!i.has(n[0]))return!1;for(n of t.entries())if(!e(n[1],i.get(n[0])))return!1;return!0}if(t instanceof Set&&i instanceof Set){if(t.size!==i.size)return!1;for(n of t.entries())if(!i.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(i)){if((r=t.length)!=i.length)return!1;for(n=r;0!=n--;)if(t[n]!==i[n])return!1;return!0}if(t.constructor===RegExp)return t.source===i.source&&t.flags===i.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===i.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===i.toString();if((r=(s=Object.keys(t)).length)!==Object.keys(i).length)return!1;for(n=r;0!=n--;)if(!Object.prototype.hasOwnProperty.call(i,s[n]))return!1;for(n=r;0!=n--;){var a=s[n];if(!e(t[a],i[a]))return!1}return!0}return t!=t&&i!=i},e.getEventsUri=G,e.getPollingUri=function(e,t,i){const r=q(t),n=[...i];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),J(`${e.polling}/${r}`,n)},e.getStreamingUri=function(e,t,i){const r=q(t),n=[...i];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),J(`${e.streaming}/${r}`,n)},e.httpErrorMessage=ie,e.internal=ve,e.isHttpLocallyRecoverable=ee,e.isHttpRecoverable=Z,e.noop=()=>{},e.secondsToMillis=function(e){return Math.trunc(1e3*e)},e.shouldRetry=function({status:e}){return!e||Z(e)},e.sleep=re,e.subsystem=C,e.timedPromise=(e,t)=>new Promise(((i,r)=>{setTimeout((()=>{r(new Q(`${t} timed out after ${e} seconds.`))}),1e3*e)}))}(o);var l={},u={},c={};Object.defineProperty(c,"__esModule",{value:!0});var d={};Object.defineProperty(d,"__esModule",{value:!0});var h,f,g={};Object.defineProperty(g,"__esModule",{value:!0}),g.IsMigrationStage=g.LDMigrationStage=void 0,(f=h||(g.LDMigrationStage=h={})).Off="off",f.DualWrite="dualwrite",f.Shadow="shadow",f.Live="live",f.RampDown="rampdown",f.Complete="complete",g.IsMigrationStage=function(e){return Object.values(h).includes(e)};var _={};Object.defineProperty(_,"__esModule",{value:!0});var v,p,y,m,b,w={};Object.defineProperty(w,"__esModule",{value:!0}),w.LDConsistencyCheck=void 0,(p=v||(w.LDConsistencyCheck=v={}))[p.Inconsistent=0]="Inconsistent",p[p.Consistent=1]="Consistent",p[p.NotChecked=2]="NotChecked",y=u,m=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),b=r&&r.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||m(t,e,i)},Object.defineProperty(y,"__esModule",{value:!0}),b(c,y),b(d,y),b(g,y),b(_,y),b(w,y);var S={},k={};Object.defineProperty(k,"__esModule",{value:!0});var E={};Object.defineProperty(E,"__esModule",{value:!0});var O={};Object.defineProperty(O,"__esModule",{value:!0});var x={};Object.defineProperty(x,"__esModule",{value:!0});var D,P,M,T,j={};Object.defineProperty(j,"__esModule",{value:!0}),j.LDConcurrentExecution=j.LDSerialExecution=j.LDExecution=j.LDExecutionOrdering=void 0,(P=D||(j.LDExecutionOrdering=D={}))[P.Fixed=0]="Fixed",P[P.Random=1]="Random",(T=M||(j.LDExecution=M={}))[T.Serial=0]="Serial",T[T.Concurrent=1]="Concurrent";j.LDSerialExecution=class{constructor(e){this.ordering=e,this.type=M.Serial}};j.LDConcurrentExecution=class{constructor(){this.type=M.Concurrent}},function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(k,e),i(E,e),i(O,e),i(x,e),i(j,e)}(S);var I={};Object.defineProperty(I,"__esModule",{value:!0});var C={};Object.defineProperty(C,"__esModule",{value:!0});var F={};Object.defineProperty(F,"__esModule",{value:!0});var R={};Object.defineProperty(R,"__esModule",{value:!0});var A={};Object.defineProperty(A,"__esModule",{value:!0});var V={},N={};Object.defineProperty(N,"__esModule",{value:!0});var L={};Object.defineProperty(L,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(N,e),i(L,e)}(V);var K={},$={};Object.defineProperty($,"__esModule",{value:!0});var U={};Object.defineProperty(U,"__esModule",{value:!0});var z={};Object.defineProperty(z,"__esModule",{value:!0});var B={};Object.defineProperty(B,"__esModule",{value:!0});var H={};Object.defineProperty(H,"__esModule",{value:!0});var q={};Object.defineProperty(q,"__esModule",{value:!0});var W={};Object.defineProperty(W,"__esModule",{value:!0});var J={};Object.defineProperty(J,"__esModule",{value:!0});var G={};Object.defineProperty(G,"__esModule",{value:!0});var X={};Object.defineProperty(X,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i($,e),i(U,e),i(z,e),i(B,e),i(H,e),i(F,e),i(q,e),i(W,e),i(J,e),i(G,e),i(X,e)}(K);var Y={},Q={};Object.defineProperty(Q,"__esModule",{value:!0});var Z={};Object.defineProperty(Z,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(Q,e),i(R,e),i(Z,e)}(Y),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.subsystems=e.interfaces=e.integrations=void 0,i(u,e),i(S,e),i(I,e),i(C,e),i(F,e),i(R,e),i(A,e),e.integrations=V,e.interfaces=K,e.subsystems=Y}(l);var ee={},te={};Object.defineProperty(te,"__esModule",{value:!0});te.default=class{constructor(e){this._keyMap=new Map,this._head=0,this._tail=0,this._size=0;const{max:t}=e;this._max=t,this._values=new Array(t),this._keys=new Array(t),this._next=new Uint32Array(t),this._prev=new Uint32Array(t),e.maxAge?(this._lastUpdated=new Array(t).fill(0),this._maxAge=e.maxAge):(this._lastUpdated=[],this._maxAge=0)}set(e,t){let i=this._keyMap.get(e);void 0===i?(i=this._index(),this._keys[i]=e,this._keyMap.set(e,i),this._next[this._tail]=i,this._prev[i]=this._tail,this._tail=i,this._size+=1):this._setTail(i),this._values[i]=t,this._maxAge&&(this._lastUpdated[i]=Date.now())}get(e){const t=this._keyMap.get(e);if(void 0!==t){if(this._maxAge){const e=this._lastUpdated[t];if(Date.now()-e>this._maxAge)return}return this._setTail(t),this._maxAge&&(this._lastUpdated[t]=Date.now()),this._values[t]}}clear(){this._head=0,this._tail=0,this._size=0,this._values.fill(void 0),this._keys.fill(void 0),this._next.fill(0),this._prev.fill(0),this._keyMap.clear()}_index(){return 0===this._size?this._tail:this._size===this._max?this._evict():this._size}_evict(){const{_head:e}=this,t=this._keys[e];return this._head=this._next[e],this._keyMap.delete(t),this._size-=1,e}_link(e,t){this._prev[t]=e,this._next[e]=t}_setTail(e){e!==this._tail&&(e===this._head?this._head=this._next[e]:this._link(this._prev[e],this._next[e]),this._link(this._tail,e),this._tail=e)}},Object.defineProperty(ee,"__esModule",{value:!0});const ie=o,re=s,ne=te;ee.default=class{constructor(e,t,i,r){this._store=e,this._logger=i,this._crypto=r,this.statusProvider=new re.default((async()=>this._pollStoreAndUpdateStatus())),this._staleTimeMs=1e3*(ie.TypeValidators.Number.is(t.staleAfter)&&t.staleAfter>0?t.staleAfter:120);const n=1e3*(ie.TypeValidators.Number.is(t.statusPollInterval)&&t.statusPollInterval>0?t.statusPollInterval:5);this._pollHandle=e?setInterval((()=>this._pollStoreAndUpdateStatus()),n):null,e&&(this._cache=new ne.default({max:t.userCacheSize||1e3,maxAge:1e3*(t.userCacheTime||5)}))}close(){this._pollHandle&&(clearInterval(this._pollHandle),this._pollHandle=void 0),this._store&&this._store.close()}async getUserMembership(e){var t,i,r;if(!this._store)return;const n=null===(t=this._cache)||void 0===t?void 0:t.get(e);let s;if(n)s=n.membership;else try{s=await this._store.getUserMembership(this._hashForUserKey(e));const t={membership:s};null===(i=this._cache)||void 0===i||i.set(e,t)}catch(e){return null===(r=this._logger)||void 0===r||r.error(`Big Segment store membership query returned error: ${e}`),[null,"STORE_ERROR"]}this.statusProvider.getStatus()||await this._pollStoreAndUpdateStatus();const a=this.statusProvider.getStatus();return a.available?[s||null,a.stale?"STALE":"HEALTHY"]:[s||null,"STORE_ERROR"]}async _pollStoreAndUpdateStatus(){var e,t,i;if(!this._store)return void this.statusProvider.setStatus({available:!1,stale:!1});let r;null===(e=this._logger)||void 0===e||e.debug("Querying Big Segment store status");try{const e=await this._store.getMetadata();r={available:!0,stale:!e||!e.lastUpToDate||this._isStale(e.lastUpToDate)}}catch(e){null===(t=this._logger)||void 0===t||t.error(`Big Segment store status query returned error: ${e}`),r={available:!1,stale:!1}}const n=this.statusProvider.getStatus();n&&n.available===r.available&&n.stale===r.stale||(null===(i=this._logger)||void 0===i||i.debug("Big Segment store status changed from %s to %s",JSON.stringify(n),JSON.stringify(r)),this.statusProvider.setStatus(r),this.statusProvider.notify())}_hashForUserKey(e){const t=this._crypto.createHash("sha256");if(t.update(e),!t.digest)throw new Error("Platform must implement digest or asyncDigest");return t.digest("base64")}_isStale(e){return Date.now()-e>=this._staleTimeMs}};var se={},ae={},oe={};Object.defineProperty(oe,"__esModule",{value:!0});class le{static getKeyFromPath(e,t){return t.startsWith(e.streamApiPath)?t.substring(e.streamApiPath.length):void 0}}le.Features={namespace:"features",streamApiPath:"/flags/"},le.Segments={namespace:"segments",streamApiPath:"/segments/"},oe.default=le,Object.defineProperty(ae,"__esModule",{value:!0}),ae.deserializeSegment=ae.serializeSegment=ae.deserializeFlag=ae.serializeFlag=ae.deserializeDelete=ae.deserializePatch=ae.deserializePoll=ae.deserializeAll=ae.processSegment=ae.processFlag=ae.replacer=ae.nullReplacer=void 0;const ue=o,ce=oe,de=100;function he(e,t){const i=[];if(null==e)return;const r=Object.entries(e).filter((([e,i])=>!(null==t?void 0:t.includes(e))));for(i.push(...r.map((([t,i])=>({key:t,value:i,parent:e}))));i.length;){const e=i.pop();null!==e.value||Array.isArray(e.parent)?"object"==typeof e.value&&null!==e.value&&i.push(...Object.entries(e.value).map((([t,i])=>({key:t,value:i,parent:e.value})))):delete e.parent[e.key]}}function fe(e,t){if(!(t instanceof ue.AttributeReference||Array.isArray(t)&&t[0]&&t[0]instanceof ue.AttributeReference))return null==t||(t.generated_includedSet&&(t.included=[...t.generated_includedSet],delete t.generated_includedSet),t.generated_excludedSet&&(t.excluded=[...t.generated_excludedSet],delete t.generated_excludedSet),t.includedContexts&&t.includedContexts.forEach((e=>{e.generated_valuesSet&&(e.values=[...e.generated_valuesSet]),delete e.generated_valuesSet})),t.excludedContexts&&t.excludedContexts.forEach((e=>{e.generated_valuesSet&&(e.values=[...e.generated_valuesSet]),delete e.generated_valuesSet}))),t}function ge(e){e&&e.bucketBy&&(e.bucketByAttributeReference=new ue.AttributeReference(e.bucketBy,!e.contextKind))}function _e(e){var t;if(he(e,["variations"]),e.fallthrough&&e.fallthrough.rollout){ge(e.fallthrough.rollout)}null===(t=null==e?void 0:e.rules)||void 0===t||t.forEach((e=>{var t;ge(e.rollout),null===(t=null==e?void 0:e.clauses)||void 0===t||t.forEach((e=>{e&&e.attribute?e.attributeReference=new ue.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ue.AttributeReference.InvalidReference)}))}))}function ve(e){var t,i,r,n,s;he(e),(null===(t=null==e?void 0:e.included)||void 0===t?void 0:t.length)&&e.included.length>de&&(e.generated_includedSet=new Set(e.included),delete e.included),(null===(i=null==e?void 0:e.excluded)||void 0===i?void 0:i.length)&&e.excluded.length>de&&(e.generated_excludedSet=new Set(e.excluded),delete e.excluded),(null===(r=null==e?void 0:e.includedContexts)||void 0===r?void 0:r.length)&&e.includedContexts.forEach((e=>{var t;(null===(t=null==e?void 0:e.values)||void 0===t?void 0:t.length)&&e.values.length>de&&(e.generated_valuesSet=new Set(e.values),e.values=[])})),(null===(n=null==e?void 0:e.excludedContexts)||void 0===n?void 0:n.length)&&e.excludedContexts.forEach((e=>{var t;(null===(t=null==e?void 0:e.values)||void 0===t?void 0:t.length)&&e.values.length>de&&(e.generated_valuesSet=new Set(e.values),e.values=[])})),null===(s=null==e?void 0:e.rules)||void 0===s||s.forEach((e=>{var t;e.bucketBy&&(e.bucketByAttributeReference=new ue.AttributeReference(e.bucketBy,!e.rolloutContextKind)),null===(t=null==e?void 0:e.clauses)||void 0===t||t.forEach((e=>{e&&e.attribute?e.attributeReference=new ue.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ue.AttributeReference.InvalidReference)}))}))}function pe(e){try{return JSON.parse(e)}catch(e){return}}ae.nullReplacer=he,ae.replacer=fe,ae.processFlag=_e,ae.processSegment=ve,ae.deserializeAll=function(e){var t,i;const r=pe(e);if(r)return Object.values((null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.flags)||[]).forEach((e=>{_e(e)})),Object.values((null===(i=null==r?void 0:r.data)||void 0===i?void 0:i.segments)||[]).forEach((e=>{ve(e)})),r},ae.deserializePoll=function(e){const t=pe(e);if(t)return Object.values((null==t?void 0:t.flags)||[]).forEach((e=>{_e(e)})),Object.values((null==t?void 0:t.segments)||[]).forEach((e=>{ve(e)})),t},ae.deserializePatch=function(e){const t=pe(e);if(t)return t.path.startsWith(ce.default.Features.streamApiPath)?(_e(t.data),t.kind=ce.default.Features):t.path.startsWith(ce.default.Segments.streamApiPath)&&(ve(t.data),t.kind=ce.default.Segments),t},ae.deserializeDelete=function(e){const t=pe(e);if(t)return t.path.startsWith(ce.default.Features.streamApiPath)?t.kind=ce.default.Features:t.path.startsWith(ce.default.Segments.streamApiPath)&&(t.kind=ce.default.Segments),t},ae.serializeFlag=function(e){return JSON.stringify(e,fe)},ae.deserializeFlag=function(e){const t=pe(e);if(t)return _e(t),t},ae.serializeSegment=function(e){return JSON.stringify(e,fe)},ae.deserializeSegment=function(e){const t=pe(e);if(t)return ve(t),t},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createStreamListeners=e.createDeleteListener=e.createPatchListener=e.createPutListener=void 0;const t=ae,i=oe;e.createPutListener=(e,r,n=()=>{})=>({deserializeData:t.deserializeAll,processJson:async({data:{flags:t,segments:s}})=>{const a={[i.default.Features.namespace]:t,[i.default.Segments.namespace]:s};null==r||r.debug("Initializing all data"),e.init(a,n)}});e.createPatchListener=(e,r,n=()=>{})=>({deserializeData:t.deserializePatch,processJson:async({data:t,kind:s,path:a})=>{if(s){const o=i.default.getKeyFromPath(s,a);o&&(null==r||r.debug(`Updating ${o} in ${s.namespace}`),e.upsert(s,t,n))}}});e.createDeleteListener=(e,r,n=()=>{})=>({deserializeData:t.deserializeDelete,processJson:async({kind:t,path:s,version:a})=>{if(t){const o=i.default.getKeyFromPath(t,s);o&&(null==r||r.debug(`Deleting ${o} in ${t.namespace}`),e.upsert(t,{key:o,version:a,deleted:!0},n))}}});e.createStreamListeners=(t,i,r)=>{const n=new Map;return n.set("put",(0,e.createPutListener)(t,i,null==r?void 0:r.put)),n.set("patch",(0,e.createPatchListener)(t,i,null==r?void 0:r.patch)),n.set("delete",(0,e.createDeleteListener)(t,i,null==r?void 0:r.delete)),n}}(se);var ye={},me={},be={};Object.defineProperty(be,"__esModule",{value:!0});be.default=class{constructor(){this._itemsByNamespace={}}get(e,t){var i;return null===(i=this._itemsByNamespace[e])||void 0===i?void 0:i[t]}set(e,t,i){e in this._itemsByNamespace||(this._itemsByNamespace[e]={}),this._itemsByNamespace[e][t]=i}remove(e,t){const i=this._itemsByNamespace[e];i&&delete i[t]}removeAll(){this._itemsByNamespace={}}enumerate(e){Object.entries(this._itemsByNamespace).forEach((([t,i])=>{Object.entries(i).forEach((([i,r])=>{e(t,i,r)}))}))}mergeFrom(e){e.enumerate(this.set.bind(this))}},Object.defineProperty(me,"__esModule",{value:!0});const we=be;me.default=class{constructor(){this._dependenciesFrom=new we.default,this._dependenciesTo=new we.default}updateDependenciesFrom(e,t,i){const r=this._dependenciesFrom.get(e,t);null==r||r.enumerate(((i,r)=>{const n=this._dependenciesTo.get(i,r);null==n||n.remove(e,t)})),this._dependenciesFrom.set(e,t,i),null==i||i.enumerate(((i,r)=>{let n=this._dependenciesTo.get(i,r);n||(n=new we.default,this._dependenciesTo.set(i,r,n)),n.set(e,t,!0)}))}updateModifiedItems(e,t,i){if(!e.get(t,i)){e.set(t,i,!0);const r=this._dependenciesTo.get(t,i);null==r||r.enumerate(((t,i)=>{this.updateModifiedItems(e,t,i)}))}}reset(){this._dependenciesFrom.removeAll(),this._dependenciesTo.removeAll()}},Object.defineProperty(ye,"__esModule",{value:!0});const Se=oe,ke=me,Ee=be;function Oe(e,t){var i,r;const n=new Ee.default,s=e===Se.default.Features.namespace,a=e===Se.default.Segments.namespace;if(s){const r=t;null===(i=null==r?void 0:r.prerequisites)||void 0===i||i.forEach((t=>{n.set(e,t.key,!0)}))}if(s||a){const e=t;null===(r=null==e?void 0:e.rules)||void 0===r||r.forEach((e=>{var t;null===(t=e.clauses)||void 0===t||t.forEach((e=>{"segmentMatch"===e.op&&e.values.forEach((e=>{n.set(Se.default.Segments.namespace,e,!0)}))}))}))}return n}ye.default=class{constructor(e,t,i){this._featureStore=e,this._hasEventListeners=t,this._onChange=i,this._dependencyTracker=new ke.default}init(e,t){const i=this._hasEventListeners(),r=r=>{this._featureStore.init(e,(()=>{Promise.resolve().then((()=>{if(this._dependencyTracker.reset(),Object.entries(e).forEach((([e,t])=>{Object.keys(t||{}).forEach((i=>{const r=t[i];this._dependencyTracker.updateDependenciesFrom(e,i,Oe(e,r))}))})),i){const t=new Ee.default;Object.keys(e).forEach((i=>{const n=(null==r?void 0:r[i])||{},s=e[i],a=Object.assign(Object.assign({},n),s);Object.keys(a).forEach((e=>{this.addIfModified(i,e,n&&n[e],s&&s[e],t)}))})),this.sendChangeEvents(t)}})),null==t||t()}))};i?this._featureStore.all(Se.default.Features,(e=>{this._featureStore.all(Se.default.Segments,(t=>{const i={[Se.default.Features.namespace]:e,[Se.default.Segments.namespace]:t};r(i)}))})):r()}upsert(e,t,i){const{key:r}=t,n=this._hasEventListeners(),s=s=>{this._featureStore.upsert(e,t,(()=>{Promise.resolve().then((()=>{if(this._dependencyTracker.updateDependenciesFrom(e.namespace,r,Oe(e.namespace,t)),n){const i=new Ee.default;this.addIfModified(e.namespace,r,s,t,i),this.sendChangeEvents(i)}})),null==i||i()}))};n?this._featureStore.get(e,r,s):s()}addIfModified(e,t,i,r,n){r&&i&&r.version<=i.version||this._dependencyTracker.updateModifiedItems(n,e,t)}sendChangeEvents(e){e.enumerate(((e,t)=>{e===Se.default.Features.namespace&&this._onChange(t)}))}};var xe={},De={},Pe={},Me={};Object.defineProperty(Me,"__esModule",{value:!0}),Me.default=function(e){return new Promise((t=>{e((e=>{t(e)}))}))},Object.defineProperty(Pe,"__esModule",{value:!0});const Te=Me;Pe.default=class{constructor(e){this._store=e}async get(e,t){return(0,Te.default)((i=>{this._store.get(e,t,i)}))}async all(e){return(0,Te.default)((t=>{this._store.all(e,t)}))}async init(e){return(0,Te.default)((t=>{this._store.init(e,t)}))}async delete(e,t,i){return(0,Te.default)((r=>{this._store.delete(e,t,i,r)}))}async upsert(e,t){return(0,Te.default)((i=>{this._store.upsert(e,t,i)}))}async initialized(){return(0,Te.default)((e=>{this._store.initialized(e)}))}close(){this._store.close()}};var je={},Ie={};function Ce(e){return Date.now()>e.expiration}Object.defineProperty(Ie,"__esModule",{value:!0});Ie.default=class{constructor(e){this._options=e,this._storage=new Map,this._checkIntervalHandle=setInterval((()=>{this._purgeStale()}),1e3*e.checkInterval)}get(e){const t=this._storage.get(e);if(!t||!Ce(t))return null==t?void 0:t.value;this._storage.delete(e)}set(e,t){this._storage.set(e,{value:t,expiration:Date.now()+1e3*this._options.ttl})}delete(e){this._storage.delete(e)}clear(){this._storage.clear()}close(){this.clear(),this._checkIntervalHandle&&(clearInterval(this._checkIntervalHandle),this._checkIntervalHandle=null)}_purgeStale(){this._storage.forEach(((e,t)=>{Ce(e)&&this._storage.delete(t)}))}get size(){return this._storage.size}};var Fe={};Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.persistentStoreKinds=void 0;const Re=ae,Ae=oe;Fe.persistentStoreKinds={segments:{namespace:Ae.default.Segments.namespace,deserialize:e=>{const t=(0,Re.deserializeSegment)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Re.serializeSegment)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:0},features:{namespace:Ae.default.Features.namespace,deserialize:e=>{const t=(0,Re.deserializeFlag)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Re.serializeFlag)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:1}};var Ve={};Object.defineProperty(Ve,"__esModule",{value:!0});const Ne=Fe;function Le(e,t){const i=[],r=new Set(Object.keys(t)),n=s=>{if(!r.has(s))return;r.delete(s);const a=t[s];var o;"features"===e.namespace&&(o=a,o.prerequisites&&o.prerequisites.length?o.prerequisites.map((e=>e.key)):[]).forEach((e=>{n(e)})),i.push({key:s,item:e.serialize(a)})};for(;r.size>0;){const e=r.values().next().value;n(e)}return i}Ve.default=function(e){const t=[];return Object.keys(e).forEach((i=>{const r=Ne.persistentStoreKinds[i];t.push({key:r,item:Le(r,e[i])})})),t.sort(((e,t)=>e.key.priority-t.key.priority)),t};var Ke={};Object.defineProperty(Ke,"__esModule",{value:!0});Ke.default=class{constructor(){this._queue=[]}enqueue(e,t){this._queue.push([e,t]),1===this._queue.length&&this.executePendingUpdates()}executePendingUpdates(){if(this._queue.length>0){const[e,t]=this._queue[0];e((()=>{this._queue.shift(),this._queue.length>0&&setTimeout((()=>this.executePendingUpdates()),0),null==t||t()}))}}},Object.defineProperty(je,"__esModule",{value:!0});const $e=Ie,Ue=Fe,ze=Ve,Be=Ke;function He(e,t){return`${e.namespace}:${t}`}function qe(e){return`$all:${e.namespace}`}const We="$checkedInit";function Je(e){return!e||e.item.deleted?null:e.item}function Ge(e){return{version:e,item:{version:e,deleted:!0}}}function Xe(e,t){if(t.deleted||!t.serializedItem)return Ge(t.version);const i=e.deserialize(t.serializedItem);return void 0===i?Ge(t.version):0===i.version||i.version===t.version||void 0===i.item?i:{version:t.version,item:i.item}}je.default=class{constructor(e,t){this._core=e,this._isInitialized=!1,this._queue=new Be.default,t&&(this._itemCache=new $e.default({ttl:t,checkInterval:600}),this._allItemsCache=new $e.default({ttl:t,checkInterval:600}))}init(e,t){this._queue.enqueue((t=>{this._core.init((0,ze.default)(e),(()=>{this._isInitialized=!0,this._itemCache&&(this._itemCache.clear(),this._allItemsCache.clear(),Object.keys(e).forEach((t=>{const i=Ue.persistentStoreKinds[t],r=e[t];this._allItemsCache.set(qe(i),r),Object.keys(r).forEach((e=>{const t=r[e],n={version:t.version,item:t};this._itemCache.set(He(i,e),n)}))}))),t()}))}),t)}get(e,t,i){if(this._itemCache){const r=this._itemCache.get(He(e,t));if(r)return void i(Je(r))}const r=Ue.persistentStoreKinds[e.namespace];this._core.get(r,t,(n=>{var s;if(n&&n.serializedItem){const a=Xe(r,n);return null===(s=this._itemCache)||void 0===s||s.set(He(e,t),a),void i(Je(a))}i(null)}))}initialized(e){var t;this._isInitialized?e(!0):(null===(t=this._itemCache)||void 0===t?void 0:t.get(We))?e(!1):this._core.initialized((t=>{var i;this._isInitialized=t,this._isInitialized||null===(i=this._itemCache)||void 0===i||i.set(We,!0),e(this._isInitialized)}))}all(e,t){var i;const r=null===(i=this._allItemsCache)||void 0===i?void 0:i.get(qe(e));if(r)return void t(r);const n=Ue.persistentStoreKinds[e.namespace];this._core.getAll(n,(i=>{var r;if(!i)return void t({});const s={};i.forEach((({key:e,item:t})=>{const i=Je(Xe(n,t));i&&(s[e]=i)})),null===(r=this._allItemsCache)||void 0===r||r.set(qe(e),s),t(s)}))}upsert(e,t,i){this._queue.enqueue((i=>{this._allItemsCache&&this._allItemsCache.clear();const r=Ue.persistentStoreKinds[e.namespace];this._core.upsert(r,t.key,r.serialize(t),((n,s)=>{var a,o;if(!n&&s)if(s.serializedItem){const i=Xe(r,s);null===(a=this._itemCache)||void 0===a||a.set(He(e,t.key),i)}else s.deleted&&(null===(o=this._itemCache)||void 0===o||o.set(t.key,{key:t.key,version:s.version,deleted:!0}));i()}))}),i)}delete(e,t,i,r){this.upsert(e,{key:t,version:i,deleted:!0},r)}close(){var e,t;null===(e=this._itemCache)||void 0===e||e.close(),null===(t=this._allItemsCache)||void 0===t||t.close(),this._core.close()}getDescription(){return this._core.getDescription()}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.deserializePoll=e.PersistentDataStoreWrapper=e.AsyncStoreFacade=void 0;const t=Pe;e.AsyncStoreFacade=t.default;const i=je;e.PersistentDataStoreWrapper=i.default;const r=ae;Object.defineProperty(e,"deserializePoll",{enumerable:!0,get:function(){return r.deserializePoll}})}(De),Object.defineProperty(xe,"__esModule",{value:!0});const Ye=o,Qe=De,Ze=oe;xe.default=class{constructor(e,t,i,r=()=>{},n){this._requestor=t,this._featureStore=i,this._initSuccessHandler=r,this._errorHandler=n,this._stopped=!1,this._logger=e.logger,this._pollInterval=e.pollInterval}_poll(){var e;if(this._stopped)return;const t=e=>{var t,i,r;null===(t=this._logger)||void 0===t||t.error("Polling received invalid data"),null===(i=this._logger)||void 0===i||i.debug(`Invalid JSON follows: ${e}`),null===(r=this._errorHandler)||void 0===r||r.call(this,new Ye.LDPollingError(Ye.DataSourceErrorKind.InvalidData,"Malformed JSON data in polling response"))},i=Date.now();null===(e=this._logger)||void 0===e||e.debug("Polling LaunchDarkly for feature flag updates"),this._requestor.requestAllData(((e,r)=>{var n,s,a,o;const l=Date.now()-i,u=Math.max(1e3*this._pollInterval-l,0);if(null===(n=this._logger)||void 0===n||n.debug("Elapsed: %d ms, sleeping for %d ms",l,u),e){const{status:t}=e;if(t&&!(0,Ye.isHttpRecoverable)(t)){const i=(0,Ye.httpErrorMessage)(e,"polling request");return null===(s=this._logger)||void 0===s||s.error(i),void(null===(a=this._errorHandler)||void 0===a||a.call(this,new Ye.LDPollingError(Ye.DataSourceErrorKind.ErrorResponse,i,t)))}null===(o=this._logger)||void 0===o||o.warn((0,Ye.httpErrorMessage)(e,"polling request","will retry"))}else if(r){const e=(0,Qe.deserializePoll)(r);if(e){const t={[Ze.default.Features.namespace]:e.flags,[Ze.default.Segments.namespace]:e.segments};return void this._featureStore.init(t,(()=>{this._initSuccessHandler(),this._timeoutHandle=setTimeout((()=>{this._poll()}),u)}))}t(r)}this._timeoutHandle=setTimeout((()=>{this._poll()}),u)}))}start(){this._poll()}stop(){this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this._stopped=!0}close(){this.stop()}};var et={};Object.defineProperty(et,"__esModule",{value:!0});const tt=o;et.default=class{constructor(e,t,i){this._requests=t,this._eTagCache={},this._headers=Object.assign({},i),this._uri=(0,tt.getPollingUri)(e.serviceEndpoints,"/sdk/latest-all",[])}async _requestWithETagCache(e,t){const i=this._eTagCache[e],r=null==i?void 0:i.etag,n=r?Object.assign(Object.assign({},t),{headers:Object.assign(Object.assign({},t.headers),{"if-none-match":r})}):t,s=await this._requests.fetch(e,n);if(304===s.status&&i)return{res:s,body:i.body};const a=s.headers.get("etag"),o=await s.text();return a&&(this._eTagCache[e]={etag:a,body:o}),{res:s,body:o}}async requestAllData(e){const t={method:"GET",headers:this._headers};try{const{res:i,body:r}=await this._requestWithETagCache(this._uri,t);if(200!==i.status&&304!==i.status){return e(new tt.LDPollingError(tt.DataSourceErrorKind.ErrorResponse,`Unexpected status code: ${i.status}`,i.status),void 0)}return e(void 0,304===i.status?null:r)}catch(t){return e(t,void 0)}}};var it={};Object.defineProperty(it,"__esModule",{value:!0});const rt=o;it.default=class{constructor(e,t,i,r,n,s,a,o=1){this._listeners=r,this._diagnosticsManager=s,this._errorHandler=a,this._streamInitialReconnectDelay=o;const{basicConfiguration:l,platform:u}=e,{logger:c}=l,{requests:d}=u;this._headers=Object.assign({},n),this._logger=c,this._requests=d,this._streamUri=(0,rt.getStreamingUri)(l.serviceEndpoints,t,i)}_logConnectionStarted(){this._connectionAttemptStartTime=Date.now()}_logConnectionResult(e){this._connectionAttemptStartTime&&this._diagnosticsManager&&this._diagnosticsManager.recordStreamInit(this._connectionAttemptStartTime,!e,Date.now()-this._connectionAttemptStartTime),this._connectionAttemptStartTime=void 0}_retryAndHandleError(e){var t,i,r;return(0,rt.shouldRetry)(e)?(null===(r=this._logger)||void 0===r||r.warn((0,rt.httpErrorMessage)(e,"streaming request","will retry")),this._logConnectionResult(!1),this._logConnectionStarted(),!0):(this._logConnectionResult(!1),null===(t=this._errorHandler)||void 0===t||t.call(this,new rt.LDStreamingError(rt.DataSourceErrorKind.ErrorResponse,e.message,e.status)),null===(i=this._logger)||void 0===i||i.error((0,rt.httpErrorMessage)(e,"streaming request")),!1)}start(){this._logConnectionStarted();const e=this._requests.createEventSource(this._streamUri,{headers:this._headers,errorFilter:e=>this._retryAndHandleError(e),initialRetryDelayMillis:1e3*this._streamInitialReconnectDelay,readTimeoutMillis:3e5,retryResetIntervalMillis:6e4});this._eventSource=e,e.onclose=()=>{var e;null===(e=this._logger)||void 0===e||e.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var e;null===(e=this._logger)||void 0===e||e.info("Opened LaunchDarkly stream connection")},e.onretrying=e=>{var t;null===(t=this._logger)||void 0===t||t.info(`Will retry stream connection in ${e.delayMillis} milliseconds`)},this._listeners.forEach((({deserializeData:t,processJson:i},r)=>{e.addEventListener(r,(e=>{var n,s;if(null===(n=this._logger)||void 0===n||n.debug(`Received ${r} event`),null==e?void 0:e.data){this._logConnectionResult(!0);const{data:n}=e,s=t(n);if(!s)return void((e,t,i,r)=>{null==i||i.error(`Stream received invalid data in "${e}" message`),null==i||i.debug(`Invalid JSON follows: ${t}`),null==r||r(new rt.LDStreamingError(rt.DataSourceErrorKind.InvalidData,"Malformed JSON data in event stream"))})(r,n,this._logger,this._errorHandler);i(s)}else null===(s=this._errorHandler)||void 0===s||s.call(this,new rt.LDStreamingError(rt.DataSourceErrorKind.Unknown,"Unexpected payload from event stream"))}))}))}stop(){var e;null===(e=this._eventSource)||void 0===e||e.close(),this._eventSource=void 0}close(){this.stop()}};var nt={},st={},at={};Object.defineProperty(at,"__esModule",{value:!0});at.default=class{constructor(){this._allData={},this._initCalled=!1}_addItem(e,t,i){let r=this._allData[e.namespace];if(r||(r={},this._allData[e.namespace]=r),Object.hasOwnProperty.call(r,t)){const e=r[t];(!e||e.version<i.version)&&(r[t]=i)}else r[t]=i}get(e,t,i){const r=this._allData[e.namespace];if(r&&Object.prototype.hasOwnProperty.call(r,t)){const e=r[t];if(e&&!e.deleted)return null==i?void 0:i(e)}return null==i?void 0:i(null)}all(e,t){var i;const r={},n=null!==(i=this._allData[e.namespace])&&void 0!==i?i:{};Object.entries(n).forEach((([e,t])=>{t&&!t.deleted&&(r[e]=t)})),null==t||t(r)}init(e,t){this._initCalled=!0,this._allData=e,null==t||t()}delete(e,t,i,r){const n={version:i,deleted:!0};this._addItem(e,t,n),null==r||r()}upsert(e,t,i){this._addItem(e,t.key,t),null==i||i()}initialized(e){return null==e?void 0:e(this._initCalled)}close(){}getDescription(){return"memory"}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultValues=void 0;const t=o,i=at,r={baseUri:t.TypeValidators.String,streamUri:t.TypeValidators.String,eventsUri:t.TypeValidators.String,timeout:t.TypeValidators.Number,capacity:t.TypeValidators.Number,logger:t.TypeValidators.Object,featureStore:t.TypeValidators.ObjectOrFactory,bigSegments:t.TypeValidators.Object,updateProcessor:t.TypeValidators.ObjectOrFactory,flushInterval:t.TypeValidators.Number,pollInterval:t.TypeValidators.numberWithMin(30),proxyOptions:t.TypeValidators.Object,offline:t.TypeValidators.Boolean,stream:t.TypeValidators.Boolean,streamInitialReconnectDelay:t.TypeValidators.Number,useLdd:t.TypeValidators.Boolean,sendEvents:t.TypeValidators.Boolean,allAttributesPrivate:t.TypeValidators.Boolean,privateAttributes:t.TypeValidators.StringArray,contextKeysCapacity:t.TypeValidators.Number,contextKeysFlushInterval:t.TypeValidators.Number,tlsParams:t.TypeValidators.Object,diagnosticOptOut:t.TypeValidators.Boolean,diagnosticRecordingInterval:t.TypeValidators.numberWithMin(60),wrapperName:t.TypeValidators.String,wrapperVersion:t.TypeValidators.String,application:t.TypeValidators.Object,payloadFilterKey:t.TypeValidators.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:t.TypeValidators.createTypeArray("Hook[]",{})};e.defaultValues={baseUri:"https://sdk.launchdarkly.com",streamUri:"https://stream.launchdarkly.com",eventsUri:t.ServiceEndpoints.DEFAULT_EVENTS,stream:!0,streamInitialReconnectDelay:1,sendEvents:!0,timeout:5,capacity:1e4,flushInterval:5,pollInterval:30,offline:!1,useLdd:!1,allAttributesPrivate:!1,privateAttributes:[],contextKeysCapacity:1e3,contextKeysFlushInterval:300,diagnosticOptOut:!1,diagnosticRecordingInterval:900,featureStore:()=>new i.default};e.default=class{constructor(i={},n={}){i=i||{},this.logger=i.logger;const{errors:s,validatedOptions:a}=function(i){const n=[],s=Object.assign({},e.defaultValues);return Object.keys(i).forEach((a=>{var o;const l=i[a],u=r[a];if(u)if(u.is(l))s[a]=l;else if("boolean"===u.getType())n.push(t.OptionMessages.wrongOptionTypeBoolean(a,typeof l)),s[a]=!!l;else if(u instanceof t.NumberWithMinimum&&t.TypeValidators.Number.is(l)){const{min:e}=u;n.push(t.OptionMessages.optionBelowMinimum(a,l,e)),s[a]=e}else n.push(t.OptionMessages.wrongOptionType(a,u.getType(),typeof l)),s[a]=e.defaultValues[a];else null===(o=i.logger)||void 0===o||o.warn(t.OptionMessages.unknownOption(a))})),{errors:n,validatedOptions:s}}(i);s.forEach((e=>{var t;null===(t=this.logger)||void 0===t||t.warn(e)})),function(e,i){var r,n,s;const{baseUri:a,streamUri:o,eventsUri:l}=e,u=null!=o,c=null!=a,d=null!=l;u===c&&u===d||(!u&&i.stream&&(null===(r=i.logger)||void 0===r||r.warn(t.OptionMessages.partialEndpoint("streamUri"))),c||null===(n=i.logger)||void 0===n||n.warn(t.OptionMessages.partialEndpoint("baseUri")),!d&&i.sendEvents&&(null===(s=i.logger)||void 0===s||s.warn(t.OptionMessages.partialEndpoint("eventsUri"))))}(i,a),this.serviceEndpoints=new t.ServiceEndpoints(a.streamUri,a.baseUri,a.eventsUri,n.analyticsEventPath,n.diagnosticEventPath,n.includeAuthorizationHeader,a.payloadFilterKey),this.eventsCapacity=a.capacity,this.timeout=a.timeout,this.bigSegments=a.bigSegments,this.flushInterval=a.flushInterval,this.pollInterval=a.pollInterval,this.proxyOptions=a.proxyOptions,this.offline=a.offline,this.stream=a.stream,this.streamInitialReconnectDelay=a.streamInitialReconnectDelay,this.useLdd=a.useLdd,this.sendEvents=a.sendEvents,this.allAttributesPrivate=a.allAttributesPrivate,this.privateAttributes=a.privateAttributes,this.contextKeysCapacity=a.contextKeysCapacity,this.contextKeysFlushInterval=a.contextKeysFlushInterval,this.tlsParams=a.tlsParams,this.diagnosticOptOut=a.diagnosticOptOut,this.wrapperName=a.wrapperName,this.payloadFilterKey=a.payloadFilterKey,this.wrapperVersion=a.wrapperVersion,this.tags=new t.ApplicationTags(a),this.diagnosticRecordingInterval=a.diagnosticRecordingInterval,t.TypeValidators.Function.is(a.updateProcessor)?this.updateProcessorFactory=a.updateProcessor:this.updateProcessorFactory=()=>a.updateProcessor,t.TypeValidators.Function.is(a.featureStore)?this.featureStoreFactory=a.featureStore:this.featureStoreFactory=()=>a.featureStore,this.hooks=a.hooks}}}(st),Object.defineProperty(nt,"__esModule",{value:!0});const ot=o,lt=st;nt.default=(e,t,i)=>{var r,n,s,a,o,l;return{customBaseURI:e.serviceEndpoints.polling!==lt.defaultValues.baseUri,customStreamURI:e.serviceEndpoints.streaming!==lt.defaultValues.streamUri,customEventsURI:e.serviceEndpoints.events!==lt.defaultValues.eventsUri,eventsCapacity:e.eventsCapacity,connectTimeoutMillis:(0,ot.secondsToMillis)(e.timeout),socketTimeoutMillis:(0,ot.secondsToMillis)(e.timeout),eventsFlushIntervalMillis:(0,ot.secondsToMillis)(e.flushInterval),pollingIntervalMillis:(0,ot.secondsToMillis)(e.pollInterval),reconnectTimeMillis:(0,ot.secondsToMillis)(e.streamInitialReconnectDelay),contextKeysFlushIntervalMillis:(0,ot.secondsToMillis)(e.contextKeysFlushInterval),diagnosticRecordingIntervalMillis:(0,ot.secondsToMillis)(e.diagnosticRecordingInterval),streamingDisabled:!e.stream,usingRelayDaemon:e.useLdd,offline:e.offline,allAttributesPrivate:e.allAttributesPrivate,contextKeysCapacity:e.contextKeysCapacity,usingProxy:!!(null===(n=(r=t.requests).usingProxy)||void 0===n?void 0:n.call(r)),usingProxyAuthenticator:!!(null===(a=(s=t.requests).usingProxyAuth)||void 0===a?void 0:a.call(s)),dataStoreType:null!==(l=null===(o=i.getDescription)||void 0===o?void 0:o.call(i))&&void 0!==l?l:"memory"}};var ut={};Object.defineProperty(ut,"__esModule",{value:!0}),ut.allAsync=ut.firstSeriesAsync=ut.allSeriesAsync=ut.firstResult=void 0,ut.firstResult=function(e,t){let i;return null==e||e.some(((e,r)=>(i=t(e,r),!!i))),i};function ct(e,t,i,r,n){e?r<(null==e?void 0:e.length)?t(e[r],r,(s=>{if(i){if(!s)return void n(!1)}else if(s)return void n(!0);e.length>50?Promise.resolve().then((()=>{ct(e,t,i,r+1,n)})):ct(e,t,i,r+1,n)})):n(i):n(!1)}ut.allSeriesAsync=function(e,t,i){ct(e,t,!0,0,i)},ut.firstSeriesAsync=function(e,t,i){ct(e,t,!1,0,i)},ut.allAsync=function(e,t,i){e?Promise.all(null==e?void 0:e.map((e=>new Promise((i=>{t(e,i)}))))).then((e=>{i(e.every((e=>e)))})):i(!1)};var dt={},ht={};Object.defineProperty(ht,"__esModule",{value:!0});class ft{static prerequisiteFailed(e){return{kind:"PREREQUISITE_FAILED",prerequisiteKey:e}}static ruleMatch(e,t){return{kind:"RULE_MATCH",ruleId:e,ruleIndex:t}}}ft.Fallthrough={kind:"FALLTHROUGH"},ft.Off={kind:"OFF"},ft.TargetMatch={kind:"TARGET_MATCH"},ht.default=ft,Object.defineProperty(dt,"__esModule",{value:!0});const gt=ht;class _t{constructor(e,t,i){this.isError=e,this.detail=t,this.message=i,this.isError=e,this.detail=t,this.message=i}get isOff(){return this.detail.reason.kind===gt.default.Off.kind}setDefault(e){this.detail.value=e}static forError(e,t,i){return new _t(!0,{value:null!=i?i:null,variationIndex:null,reason:{kind:"ERROR",errorKind:e}},t)}static forSuccess(e,t,i){return new _t(!1,{value:e,variationIndex:void 0===i?null:i,reason:t})}}dt.default=_t;var vt={},pt={};Object.defineProperty(pt,"__esModule",{value:!0});pt.default=class{constructor(e){this._crypto=e}_sha1Hex(e){const t=this._crypto.createHash("sha1");if(t.update(e),!t.digest)throw new Error("Platform must implement digest or asyncDigest");return t.digest("hex")}bucket(e,t,i,r,n="user",s){const a=function(e){return"string"==typeof e?e:Number.isInteger(e)?String(e):null}(e.valueForKind(i,n));if(null===a){return[0,e.kinds.indexOf(n)>=0]}const o=`${s?Number(s):`${t}.${r}`}.${a}`;return[parseInt(this._sha1Hex(o).substring(0,15),16)/0x1000000000000000,!0]}};var yt={},mt={};Object.defineProperty(mt,"__esModule",{value:!0}),mt.getBucketBy=mt.getOffVariation=mt.getVariation=void 0;const bt=o,wt=dt,{ErrorKinds:St}=bt.internal,kt=new bt.AttributeReference("key");function Et(e,t,i){return bt.TypeValidators.Number.is(t)&&t>=0&&t<e.variations.length?wt.default.forSuccess(e.variations[t],i,t):wt.default.forError(St.MalformedFlag,"Invalid variation index in flag")}mt.getVariation=Et,mt.getOffVariation=function(e,t){return bt.TypeValidators.Number.is(e.offVariation)?Et(e,e.offVariation,t):wt.default.forSuccess(null,t)},mt.getBucketBy=function(e,t){var i;return null!==(i=e?void 0:t)&&void 0!==i?i:kt},Object.defineProperty(yt,"__esModule",{value:!0});const Ot=o,xt=ut,Dt=ht,Pt=mt;function Mt(e,t,i){const r=i.key(t.contextKind);if(void 0!==r){if(t.values.indexOf(r)>=0)return(0,Pt.getVariation)(e,t.variation,Dt.default.TargetMatch)}}yt.default=function(e,t){var i;return(null===(i=e.contextTargets)||void 0===i?void 0:i.length)?(0,xt.firstResult)(e.contextTargets,(i=>{if(!i.contextKind||i.contextKind===Ot.Context.UserKind){const r=(e.targets||[]).find((e=>e.variation===i.variation));return r?Mt(e,r,t):void 0}return Mt(e,i,t)})):(0,xt.firstResult)(e.targets,(i=>Mt(e,i,t)))};var Tt={};Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.default=function(e){return`${e.key}.g${e.generation}`};var jt={},It={};Object.defineProperty(It,"__esModule",{value:!0});const Ct=t,Ft=o,Rt=/^\d+(\.\d+)?(\.\d+)?/;function At(e){if(Ft.TypeValidators.String.is(e)&&!e.startsWith("v")){const t=(0,Ct.parse)(e);if(t)return t;const i=Rt.exec(e);if(i){let t=i[0];for(let e=1;e<i.length;e+=1)void 0===i[e]&&(t+=".0");return t+=e.substring(i[0].length),(0,Ct.parse)(t)}}return null}function Vt(e){return(t,i)=>{const r=At(t),n=At(i);return!!(r&&n&&e(r,n))}}function Nt(e,t,i){return(r,n)=>!(!t.is(r)||!t.is(n))&&(i?e(i(r),i(n)):e(r,n))}function Lt(e){return"number"==typeof e?e:Date.parse(e)}const Kt={in:(e,t)=>e===t,endsWith:Nt(((e,t)=>e.endsWith(t)),Ft.TypeValidators.String),startsWith:Nt(((e,t)=>e.startsWith(t)),Ft.TypeValidators.String),matches:Nt(((e,t)=>function(e,t){try{return new RegExp(e).test(t)}catch(e){return!1}}(t,e)),Ft.TypeValidators.String),contains:Nt(((e,t)=>e.indexOf(t)>-1),Ft.TypeValidators.String),lessThan:Nt(((e,t)=>e<t),Ft.TypeValidators.Number),lessThanOrEqual:Nt(((e,t)=>e<=t),Ft.TypeValidators.Number),greaterThan:Nt(((e,t)=>e>t),Ft.TypeValidators.Number),greaterThanOrEqual:Nt(((e,t)=>e>=t),Ft.TypeValidators.Number),before:Nt(((e,t)=>e<t),Ft.TypeValidators.Date,Lt),after:Nt(((e,t)=>e>t),Ft.TypeValidators.Date,Lt),semVerEqual:Vt(((e,t)=>0===e.compare(t))),semVerLessThan:Vt(((e,t)=>e.compare(t)<0)),semVerGreaterThan:Vt(((e,t)=>e.compare(t)>0))};It.default=class{static is(e){return Object.prototype.hasOwnProperty.call(Kt,e)}static execute(e,t,i){var r,n;return null!==(n=null===(r=Kt[e])||void 0===r?void 0:r.call(Kt,t,i))&&void 0!==n&&n}},Object.defineProperty(jt,"__esModule",{value:!0}),jt.maybeNegate=void 0;const $t=It;function Ut(e,t){return e.negate?!t:t}function zt(e,t,i){return i.some((i=>$t.default.execute(e,t,i)))}jt.maybeNegate=Ut,jt.default=function(e,t){const i=t.valueForKind(e.attributeReference,e.contextKind);return null!=i&&(Array.isArray(i)?Ut(e,i.some((t=>zt(e.op,t,e.values)))):Ut(e,zt(e.op,i,e.values)))};var Bt={};function Ht(e,t,i,r){if(t)for(let i=0;i<t.length;i+=1){const r=t[i],n=e.key(r.contextKind);if(n)if(r.generated_valuesSet){if(r.generated_valuesSet.has(n))return!0}else if(r.values.includes(n))return!0}if(r){const t=e.key("user");if(t&&r.has(t))return!0}else if(i){const t=e.key("user");if(t&&i.includes(t))return!0}return!1}Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.default=function(e,t){if(Ht(t,e.includedContexts,e.included,e.generated_includedSet))return!0;const i=Ht(t,e.excludedContexts,e.excluded,e.generated_excludedSet);return i?!i:void 0},Object.defineProperty(vt,"__esModule",{value:!0});const qt=o,Wt=pt,Jt=ut,Gt=dt,Xt=yt,Yt=Tt,Qt=jt,Zt=Bt,ei=ht,ti=mt,{ErrorKinds:ii}=qt.internal,ri={HEALTHY:1,STALE:2,STORE_ERROR:3,NOT_CONFIGURED:4};function ni(e){return void 0!==e&&ri[e]||0}function si(e,t){return void 0!==e&&ni(e)>ni(t)?e:t}function ai(e){return{error:!1,isMatch:e,result:void 0}}function oi(e){return{error:!0,isMatch:!1,result:e}}vt.default=class{constructor(e,t){this._queries=t,this._bucketer=new Wt.default(e.crypto)}async evaluate(e,t,i){return new Promise((r=>{this.evaluateCb(e,t,r,i)}))}evaluateCb(e,t,i,r){const n={};this._evaluateInternal(e,t,n,[],(e=>{n.bigSegmentsStatus&&(e.detail.reason=Object.assign(Object.assign({},e.detail.reason),{bigSegmentsStatus:n.bigSegmentsStatus})),n.prerequisites&&(e.prerequisites=n.prerequisites),e.events=n.events,i(e)}),!0,r)}_evaluateInternal(e,t,i,r,n,s,a){e.on?this._checkPrerequisites(e,t,i,r,(r=>{if(r)return void n(r);const s=(0,Xt.default)(e,t);s?n(s):this._evaluateRules(e,t,i,(i=>{n(i||this._variationForContext(e.fallthrough,t,e,ei.default.Fallthrough))}))}),s,a):n((0,ti.getOffVariation)(e,ei.default.Off))}_checkPrerequisites(e,t,i,r,n,s,a){let o;e.prerequisites&&e.prerequisites.length?(0,Jt.allSeriesAsync)(e.prerequisites,((n,l,u)=>{if(-1!==r.indexOf(n.key))return o=Gt.default.forError(ii.MalformedFlag,`Prerequisite of ${e.key} causing a circular reference. This is probably a temporary condition due to an incomplete update.`),void u(!0);const c=[...r,n.key];this._queries.getFlag(n.key,(r=>{if(!r)return o=(0,ti.getOffVariation)(e,ei.default.prerequisiteFailed(n.key)),void u(!1);this._evaluateInternal(r,t,i,c,(l=>{var c,d;return null!==(c=i.events)&&void 0!==c||(i.events=[]),s&&(null!==(d=i.prerequisites)&&void 0!==d||(i.prerequisites=[]),i.prerequisites.push(r.key)),a&&i.events.push(a.evalEventServer(r,t,l.detail,null,e)),l.isError?(o=l,u(!1)):l.isOff||l.detail.variationIndex!==n.variation?(o=(0,ti.getOffVariation)(e,ei.default.prerequisiteFailed(n.key)),u(!1)):u(!0)}),!1,a)}))}),(()=>{n(o)})):n(void 0)}_evaluateRules(e,t,i,r){let n;(0,Jt.firstSeriesAsync)(e.rules,((r,s,a)=>{this._ruleMatchContext(e,r,s,t,i,[],(e=>{n=e,a(!!e)}))}),(()=>r(n)))}_clauseMatchContext(e,t,i,r,n){let s;"segmentMatch"!==e.op?e.attributeReference.isValid?n(ai((0,Qt.default)(e,t))):n(oi(Gt.default.forError(ii.MalformedFlag,"Invalid attribute reference in clause"))):(0,Jt.firstSeriesAsync)(e.values,((e,n,a)=>{this._queries.getSegment(e,(e=>{if(e){if(i.includes(e.key))return s=Gt.default.forError(ii.MalformedFlag,`Segment rule referencing segment ${e.key} caused a circular reference. This is probably a temporary condition due to an incomplete update`),void a(!0);const n=[...i,null==e?void 0:e.key];this.segmentMatchContext(e,t,r,n,(e=>{e.error&&(s=e.result),a(e.error||e.isMatch)}))}else a(!1)}))}),(t=>n(s?oi(s):ai((0,Qt.maybeNegate)(e,t)))))}_ruleMatchContext(e,t,i,r,n,s,a){if(!t.clauses)return void a(void 0);let o;(0,Jt.allSeriesAsync)(t.clauses,((e,t,i)=>{this._clauseMatchContext(e,r,s,n,(e=>(o=e.result,i(e.error||e.isMatch))))}),(n=>a(o||(n?this._variationForContext(t,r,e,ei.default.ruleMatch(t.id,i)):void 0))))}_variationForContext(e,t,i,r){if(void 0===e)return Gt.default.forError(ii.MalformedFlag,"Fallthrough variation undefined");if(void 0!==e.variation)return(0,ti.getVariation)(i,e.variation,r);if(e.rollout){const{rollout:n}=e,{variations:s}=n,a="experiment"===n.kind;if(s&&s.length){const e=(0,ti.getBucketBy)(a,n.bucketByAttributeReference);if(!e.isValid)return Gt.default.forError(ii.MalformedFlag,"Invalid attribute reference for bucketBy in rollout");const[o,l]=this._bucketer.bucket(t,i.key,e,i.salt||"",n.contextKind,n.seed),u=Object.assign({},r);let c=0;for(let e=0;e<s.length;e+=1){const t=s[e];if(c+=t.weight/1e5,o<c)return a&&l&&!t.untracked&&(u.inExperiment=!0),(0,ti.getVariation)(i,t.variation,u)}const d=s[s.length-1];return a&&!d.untracked&&(u.inExperiment=!0),(0,ti.getVariation)(i,d.variation,u)}}return Gt.default.forError(ii.MalformedFlag,"Variation/rollout object with no variation or rollout")}segmentRuleMatchContext(e,t,i,r,n,s){let a;(0,Jt.allSeriesAsync)(t.clauses,((e,t,s)=>{this._clauseMatchContext(e,i,n,r,(e=>{a=e.result,s(e.error||e.isMatch)}))}),(r=>{if(a)return s(oi(a));if(r){if(void 0===t.weight)return s(ai(r));const n=(0,ti.getBucketBy)(!1,t.bucketByAttributeReference);if(!n.isValid)return s(oi(Gt.default.forError(ii.MalformedFlag,"Invalid attribute reference in clause")));const[a]=this._bucketer.bucket(i,e.key,n,e.salt||"",t.rolloutContextKind);return s(ai(a<t.weight/1e5))}return s(ai(!1))}))}simpleSegmentMatchContext(e,t,i,r,n){if(!e.unbounded){const i=(0,Zt.default)(e,t);if(void 0!==i)return void n(ai(i))}let s;(0,Jt.firstSeriesAsync)(e.rules,((n,a,o)=>{this.segmentRuleMatchContext(e,n,t,i,r,(e=>(s=e.result,o(e.error||e.isMatch))))}),(e=>n(s?oi(s):ai(e))))}segmentMatchContext(e,t,i,r,n){if(!e.unbounded)return void this.simpleSegmentMatchContext(e,t,i,r,n);const s=e.unboundedContextKind||"user",a=t.key(s);if(a)return e.generation?void(i.bigSegmentsMembership&&i.bigSegmentsMembership[a]?this.bigSegmentMatchContext(i.bigSegmentsMembership[a],e,t,i).then(n):this._queries.getBigSegmentsMembership(a).then((r=>{if(i.bigSegmentsMembership=i.bigSegmentsMembership||{},r){const[e,t]=r;i.bigSegmentsMembership[a]=e,i.bigSegmentsStatus=si(i.bigSegmentsStatus,t)}else i.bigSegmentsStatus=si(i.bigSegmentsStatus,"NOT_CONFIGURED");this.bigSegmentMatchContext(i.bigSegmentsMembership[a],e,t,i).then(n)}))):(i.bigSegmentsStatus=si(i.bigSegmentsStatus,"NOT_CONFIGURED"),void n(ai(!1)));n(ai(!1))}bigSegmentMatchContext(e,t,i,r){const n=(0,Yt.default)(t),s=null==e?void 0:e[n];return new Promise((e=>{null==s?this.simpleSegmentMatchContext(t,i,r,[],e):e(ai(s))}))}};var li={};Object.defineProperty(li,"__esModule",{value:!0});const ui=te;li.default=class{constructor(e){this._contextKeysCache=new ui.default({max:e.contextKeysCapacity}),this.flushInterval=e.contextKeysFlushInterval}processContext(e){const{canonicalKey:t}=e,i=this._contextKeysCache.get(t);return this._contextKeysCache.set(t,!0),!i}flush(){this._contextKeysCache.clear()}};var ci={},di={};Object.defineProperty(di,"__esModule",{value:!0}),di.default=function(e,t){if(t){if(t.inExperiment)return!0;switch(t.kind){case"RULE_MATCH":{const i=t.ruleIndex;if(void 0!==i){const t=e.rules||[];return i>=0&&i<t.length&&!!t[i].trackEvents}break}case"FALLTHROUGH":return!!e.trackEventsFallthrough}}return!1},Object.defineProperty(ci,"__esModule",{value:!0});const hi=o,fi=di;class gi extends hi.internal.EventFactoryBase{evalEventServer(e,t,i,r,n){var s;const a=(0,fi.default)(e,i.reason);return super.evalEvent({addExperimentData:a,context:t,debugEventsUntilDate:e.debugEventsUntilDate,defaultVal:r,excludeFromSummaries:e.excludeFromSummaries,flagKey:e.key,prereqOfFlagKey:null==n?void 0:n.key,reason:i.reason,samplingRatio:e.samplingRatio,trackEvents:e.trackEvents||a,value:i.value,variation:null!==(s=i.variationIndex)&&void 0!==s?s:void 0,version:e.version})}}ci.default=gi;var _i={};Object.defineProperty(_i,"__esModule",{value:!0});_i.default=class{constructor(e,t){this._valid=e,this._withReasons=t,this._flagValues={},this._flagMetadata={}}addFlag(e,t,i,r,n,s,a,o){this._flagValues[e.key]=t;const l={};void 0!==i&&(l.variation=i);const u=a&&!n&&!s&&void 0===e.debugEventsUntilDate;u||(l.version=e.version),r&&(s||this._withReasons&&!u)&&(l.reason=r),n&&(l.trackEvents=!0),s&&(l.trackReason=!0),void 0!==e.debugEventsUntilDate&&(l.debugEventsUntilDate=e.debugEventsUntilDate),o&&o.length&&(l.prerequisites=o),this._flagMetadata[e.key]=l}build(){return{valid:this._valid,allValues:()=>this._flagValues,getFlagValue:e=>this._flagValues[e],getFlagReason:e=>{var t;return null!==(t=this._flagMetadata[e]?this._flagMetadata[e].reason:null)&&void 0!==t?t:null},toJSON:()=>Object.assign(Object.assign({},this._flagValues),{$flagsState:this._flagMetadata,$valid:this._valid})}}};var vi={};Object.defineProperty(vi,"__esModule",{value:!0});const pi="unknown hook";vi.default=class{constructor(e,t){this._logger=e,this._hooks=[],this._hooks.push(...t)}async withEvaluationSeries(e,t,i,r,n){return 0===this._hooks.length?n():this.withEvaluationSeriesExtraDetail(e,t,i,r,(async()=>({detail:await n()}))).then((({detail:e})=>e))}async withEvaluationSeriesExtraDetail(e,t,i,r,n){if(0===this._hooks.length)return n();const{hooks:s,hookContext:a}=this._prepareHooks(e,t,i,r),o=this._executeBeforeEvaluation(s,a),l=await n();return this._executeAfterEvaluation(s,a,o,l.detail),l}_tryExecuteStage(e,t,i){var r;try{return i()}catch(i){return null===(r=this._logger)||void 0===r||r.error(`An error was encountered in "${e}" of the "${t}" hook: ${i}`),{}}}_hookName(e){var t,i;try{return null!==(t=null==e?void 0:e.getMetadata().name)&&void 0!==t?t:pi}catch(e){return null===(i=this._logger)||void 0===i||i.error("Exception thrown getting metadata for hook. Unable to get hook name."),pi}}_executeAfterEvaluation(e,t,i,r){var n;for(let s=e.length-1;s>=0;s-=1){const a=e[s],o=null!==(n=i[s])&&void 0!==n?n:{};this._tryExecuteStage("afterEvaluation",this._hookName(a),(()=>{var e,i;return null!==(i=null===(e=null==a?void 0:a.afterEvaluation)||void 0===e?void 0:e.call(a,t,o,r))&&void 0!==i?i:{}}))}}_executeBeforeEvaluation(e,t){return e.map((e=>this._tryExecuteStage("beforeEvaluation",this._hookName(e),(()=>{var i,r;return null!==(r=null===(i=null==e?void 0:e.beforeEvaluation)||void 0===i?void 0:i.call(e,t,{}))&&void 0!==r?r:{}}))))}_prepareHooks(e,t,i,r){return{hooks:[...this._hooks],hookContext:{flagKey:e,context:t,defaultValue:i,method:r}}}addHook(e){this._hooks.push(e)}};var yi={};Object.defineProperty(yi,"__esModule",{value:!0});const mi=o;function bi(e){const t=e.old,i=e.new;return!(void 0!==t&&!mi.TypeValidators.Boolean.is(t))&&!(void 0!==i&&!mi.TypeValidators.Boolean.is(i))}function wi(e){if(mi.TypeValidators.String.is(e.key)&&""!==e.key){if("latency_ms"===e.key){if(!mi.TypeValidators.Object.is(e.values))return;if(!function(e){const t=e.old,i=e.new;return!(void 0!==t&&!mi.TypeValidators.Number.is(t)||void 0!==i&&!mi.TypeValidators.Number.is(i))}(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}if(function(e){return"error"===e.key}(e)){if(!mi.TypeValidators.Object.is(e.values))return;if(!bi(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}if(function(e){return"consistent"===e.key}(e)){if(!mi.TypeValidators.Boolean.is(e.value)||!mi.TypeValidators.Number.is(e.samplingRatio))return;return{key:e.key,value:e.value,samplingRatio:e.samplingRatio}}if(function(e){return"invoked"===e.key}(e)){if(!mi.TypeValidators.Object.is(e.values))return;if(!bi(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}}}yi.default=function(e){var t,i;if("migration_op"!==e.kind)return;if(i=e.operation,!mi.TypeValidators.String.is(i)||"read"!==i&&"write"!==i)return;if(!mi.TypeValidators.Object.is(e.contextKeys))return;if(!mi.TypeValidators.Number.is(e.creationDate))return;if(!Object.keys(e.contextKeys).every((e=>mi.TypeValidators.Kind.is(e))))return;const r=null!==(t=e.samplingRatio)&&void 0!==t?t:1;if(!mi.TypeValidators.Number.is(r))return;if(!Object.values(e.contextKeys).every((e=>mi.TypeValidators.String.is(e)&&""!==e)))return;const n=function(e){if(!mi.TypeValidators.String.is(e.key)||""===e.key)return;if(!mi.TypeValidators.Object.is(e.reason))return;if(!mi.TypeValidators.String.is(e.reason.kind)||""===e.reason.kind)return;const t={key:e.key,value:e.value,default:e.default,reason:{kind:e.reason.kind}},i=e.reason,r=t.reason;return mi.TypeValidators.String.is(i.errorKind)&&(r.errorKind=i.errorKind),mi.TypeValidators.String.is(i.ruleId)&&(r.ruleId=i.ruleId),mi.TypeValidators.String.is(i.prerequisiteKey)&&(r.prerequisiteKey=i.prerequisiteKey),mi.TypeValidators.Boolean.is(i.inExperiment)&&(r.inExperiment=i.inExperiment),mi.TypeValidators.Number.is(i.ruleIndex)&&(r.ruleIndex=i.ruleIndex),mi.TypeValidators.String.is(i.bigSegmentsStatus)&&(r.bigSegmentsStatus=i.bigSegmentsStatus),void 0!==e.variation&&mi.TypeValidators.Number.is(e.variation)&&(t.variation=e.variation),void 0!==e.version&&mi.TypeValidators.Number.is(e.version)&&(t.version=e.version),t}(e.evaluation);var s;return n?{kind:e.kind,operation:e.operation,creationDate:e.creationDate,contextKeys:Object.assign({},e.contextKeys),measurements:(s=e.measurements,s.map(wi).filter((e=>void 0!==e))),evaluation:n,samplingRatio:r}:void 0};var Si={};Object.defineProperty(Si,"__esModule",{value:!0});const ki=o,Ei=u;function Oi(e){return!Number.isNaN(e)}Si.default=class{constructor(e,t,i,r,n,s,a,o,l,u){this._flagKey=e,this._contextKeys=t,this._defaultStage=i,this._stage=r,this._reason=n,this._checkRatio=s,this._variation=a,this._version=o,this._samplingRatio=l,this._logger=u,this._errors={old:!1,new:!1},this._wasInvoked={old:!1,new:!1},this._consistencyCheck=Ei.LDConsistencyCheck.NotChecked,this._latencyMeasurement={old:NaN,new:NaN}}op(e){this._operation=e}error(e){this._errors[e]=!0}consistency(e){var t,i;if(ki.internal.shouldSample(null!==(t=this._checkRatio)&&void 0!==t?t:1))try{const t=e();this._consistencyCheck=t?Ei.LDConsistencyCheck.Consistent:Ei.LDConsistencyCheck.Inconsistent}catch(e){null===(i=this._logger)||void 0===i||i.error(`Exception when executing consistency check function for migration '${this._flagKey}' the consistency check will not be included in the generated migration op event. Exception: ${e}`)}}latency(e,t){this._latencyMeasurement[e]=t}invoked(e){this._wasInvoked[e]=!0}createEvent(){var e,t,i,r,n;if(!ki.TypeValidators.String.is(this._flagKey)||""===this._flagKey)return void(null===(e=this._logger)||void 0===e||e.error("The flag key for a migration operation must be a non-empty string."));if(!this._operation)return void(null===(t=this._logger)||void 0===t||t.error('The operation must be set using "op" before an event can be created.'));if(0===Object.keys(this._contextKeys).length)return void(null===(i=this._logger)||void 0===i||i.error("The migration was not done against a valid context and cannot generate an event."));if(!this._wasInvoked.old&&!this._wasInvoked.new)return void(null===(r=this._logger)||void 0===r||r.error('The migration invoked neither the "old" or "new" implementation andan event cannot be generated'));if(!this._measurementConsistencyCheck())return;const s=[];return this._populateInvoked(s),this._populateConsistency(s),this._populateLatency(s),this._populateErrors(s),{kind:"migration_op",operation:this._operation,creationDate:Date.now(),contextKeys:this._contextKeys,evaluation:{key:this._flagKey,value:this._stage,default:this._defaultStage,reason:this._reason,variation:this._variation,version:this._version},measurements:s,samplingRatio:null!==(n=this._samplingRatio)&&void 0!==n?n:1}}_logTag(){return`For migration ${this._operation}-${this._flagKey}:`}_latencyConsistencyMessage(e){return`Latency measurement for "${e}", but "${e}" was not invoked.`}_errorConsistencyMessage(e){return`Error occurred for "${e}", but "${e}" was not invoked.`}_consistencyCheckConsistencyMessage(e){return`Consistency check was done, but "${e}" was not invoked.Both "old" and "new" must be invoked to do a consistency check.`}_checkOriginEventConsistency(e){var t,i,r;return!!this._wasInvoked[e]||(Number.isNaN(this._latencyMeasurement[e])?this._errors[e]?(null===(i=this._logger)||void 0===i||i.error(`${this._logTag()} ${this._errorConsistencyMessage(e)}`),!1):this._consistencyCheck===Ei.LDConsistencyCheck.NotChecked||(null===(r=this._logger)||void 0===r||r.error(`${this._logTag()} ${this._consistencyCheckConsistencyMessage(e)}`),!1):(null===(t=this._logger)||void 0===t||t.error(`${this._logTag()} ${this._latencyConsistencyMessage(e)}`),!1))}_measurementConsistencyCheck(){return this._checkOriginEventConsistency("old")&&this._checkOriginEventConsistency("new")}_populateInvoked(e){var t;const i={key:"invoked",values:{}};this._wasInvoked.old||this._wasInvoked.new||null===(t=this._logger)||void 0===t||t.error("Migration op completed without executing any origins (old/new)."),this._wasInvoked.old&&(i.values.old=!0),this._wasInvoked.new&&(i.values.new=!0),e.push(i)}_populateConsistency(e){var t;void 0!==this._consistencyCheck&&this._consistencyCheck!==Ei.LDConsistencyCheck.NotChecked&&e.push({key:"consistent",value:this._consistencyCheck===Ei.LDConsistencyCheck.Consistent,samplingRatio:null!==(t=this._checkRatio)&&void 0!==t?t:1})}_populateErrors(e){if(this._errors.new||this._errors.old){const t={key:"error",values:{}};this._errors.new&&(t.values.new=!0),this._errors.old&&(t.values.old=!0),e.push(t)}}_populateLatency(e){const t=Oi(this._latencyMeasurement.new),i=Oi(this._latencyMeasurement.old);if(t||i){const r={};t&&(r.new=this._latencyMeasurement.new),i&&(r.old=this._latencyMeasurement.old),e.push({key:"latency_ms",values:r})}}},Object.defineProperty(a,"__esModule",{value:!0});const xi=o,Di=l,Pi=ee,Mi=se,Ti=ye,ji=xe,Ii=et,Ci=it,Fi=nt,Ri=ut,Ai=dt,Vi=vt,Ni=li,Li=ci,Ki=di,$i=_i,Ui=vi,zi=yi,Bi=Si,Hi=st,qi=oe,{ClientMessages:Wi,ErrorKinds:Ji,NullEventProcessor:Gi}=xi.internal;var Xi,Yi;(Yi=Xi||(Xi={}))[Yi.Initializing=0]="Initializing",Yi[Yi.Initialized=1]="Initialized",Yi[Yi.Failed=2]="Failed";a.default=class{get logger(){return this._logger}constructor(e,t,i,r,n){var s,a,o,l,u;this._sdkKey=e,this._platform=t,this._initState=Xi.Initializing,this._eventFactoryDefault=new Li.default(!1),this._eventFactoryWithReasons=new Li.default(!0),this._onError=r.onError,this._onFailed=r.onFailed,this._onReady=r.onReady;const{onUpdate:c,hasEventListeners:d}=r,h=new Hi.default(i,n);if(this._hookRunner=new Ui.default(h.logger,h.hooks||[]),!e&&!h.offline)throw new Error("You must configure the client with an SDK key");this._config=h,this._logger=h.logger;const f=(0,xi.defaultHeaders)(e,t.info,h.tags),g=new xi.ClientContext(e,h,t),_=h.featureStoreFactory(g),v=new Ti.default(_,d,c);!h.sendEvents||h.offline||h.diagnosticOptOut||(this._diagnosticsManager=new xi.internal.DiagnosticsManager(e,t,(0,Fi.default)(h,t,_))),!h.sendEvents||h.offline?this._eventProcessor=new Gi:this._eventProcessor=new xi.internal.EventProcessor(h,g,f,new Ni.default(h),this._diagnosticsManager),this._featureStore=_;const p=new Pi.default(null===(a=null===(s=h.bigSegments)||void 0===s?void 0:s.store)||void 0===a?void 0:a.call(s,g),null!==(o=h.bigSegments)&&void 0!==o?o:{},h.logger,this._platform.crypto);this._bigSegmentsManager=p,this.bigSegmentStatusProviderInternal=p.statusProvider;const y={getFlag(e,t){_.get(qi.default.Features,e,(e=>t(e)))},getSegment(e,t){_.get(qi.default.Segments,e,(e=>t(e)))},getBigSegmentsMembership:e=>p.getUserMembership(e)};this._evaluator=new Vi.default(this._platform,y);const m=(0,Mi.createStreamListeners)(v,this._logger,{put:()=>this._initSuccess()}),b=()=>h.stream?new Ci.default(g,"/all",[],m,f,this._diagnosticsManager,(e=>this._dataSourceErrorHandler(e)),this._config.streamInitialReconnectDelay):new ji.default(h,new Ii.default(h,this._platform.requests,f),v,(()=>this._initSuccess()),(e=>this._dataSourceErrorHandler(e)));h.offline||h.useLdd||(this._updateProcessor=null!==(u=null===(l=h.updateProcessorFactory)||void 0===l?void 0:l.call(h,g,v,(()=>this._initSuccess()),(e=>this._dataSourceErrorHandler(e))))&&void 0!==u?u:b()),this._updateProcessor?this._updateProcessor.start():setTimeout((()=>this._initSuccess()),0)}initialized(){return this._initState===Xi.Initialized}waitForInitialization(e){var t,i;return void 0===(null==e?void 0:e.timeout)&&void 0!==this._updateProcessor&&(null===(t=this._logger)||void 0===t||t.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.")),void 0!==(null==e?void 0:e.timeout)&&(null==e?void 0:e.timeout)>60&&void 0!==this._updateProcessor&&(null===(i=this._logger)||void 0===i||i.warn("The waitForInitialization function was called with a timeout greater than 60 seconds. We recommend a timeout of less than 60 seconds.")),this._initializedPromise?this._clientWithTimeout(this._initializedPromise,null==e?void 0:e.timeout,this._logger):this._initState===Xi.Initialized?(this._initializedPromise=Promise.resolve(this),this._initializedPromise):this._initState===Xi.Failed?(this._initializedPromise=Promise.reject(this._rejectionReason),this._initializedPromise):(this._initializedPromise||(this._initializedPromise=new Promise(((e,t)=>{this._initResolve=e,this._initReject=t}))),this._clientWithTimeout(this._initializedPromise,null==e?void 0:e.timeout,this._logger))}variation(e,t,i,r){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.variation",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryDefault,(e=>{r(e.detail)}))})))).then((e=>(null==r||r(null,e.value),e.value)))}variationDetail(e,t,i,r){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.variationDetail",(()=>new Promise((n=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(e=>{n(e.detail),null==r||r(null,e.detail)}))}))))}_typedEval(e,t,i,r,n,s){return this._hookRunner.withEvaluationSeries(e,t,i,n,(()=>new Promise((n=>{this._evaluateIfPossible(e,t,i,r,(e=>{const t={value:e.detail.value,reason:e.detail.reason,variationIndex:e.detail.variationIndex};n(t)}),s)}))))}async boolVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.boolVariation",(e=>[xi.TypeValidators.Boolean.is(e),xi.TypeValidators.Boolean.getType()]))).value}async numberVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.numberVariation",(e=>[xi.TypeValidators.Number.is(e),xi.TypeValidators.Number.getType()]))).value}async stringVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.stringVariation",(e=>[xi.TypeValidators.String.is(e),xi.TypeValidators.String.getType()]))).value}jsonVariation(e,t,i){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.jsonVariation",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryDefault,(e=>{r(e.detail)}))})))).then((e=>e.value))}boolVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.boolVariationDetail",(e=>[xi.TypeValidators.Boolean.is(e),xi.TypeValidators.Boolean.getType()]))}numberVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.numberVariationDetail",(e=>[xi.TypeValidators.Number.is(e),xi.TypeValidators.Number.getType()]))}stringVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.stringVariationDetail",(e=>[xi.TypeValidators.String.is(e),xi.TypeValidators.String.getType()]))}jsonVariationDetail(e,t,i){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.jsonVariationDetail",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(e=>{r(e.detail)}))}))))}async _migrationVariationInternal(e,t,i){var r;const n=xi.Context.fromLDContext(t),s=await new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(({detail:t},n)=>{if((0,Di.IsMigrationStage)(t.value))r({detail:t,flag:n});else{const t=new Error(`Unrecognized MigrationState for "${e}"; returning default value.`);this._onError(t);const s={kind:"ERROR",errorKind:Ji.WrongType};r({detail:{value:i,reason:s},flag:n})}}))})),{detail:a,flag:o}=s,l=n.valid?n.kindsAndKeys:{},u=null===(r=null==o?void 0:o.migration)||void 0===r?void 0:r.checkRatio,c=null==o?void 0:o.samplingRatio;return{detail:a,migration:{value:a.value,tracker:new Bi.default(e,l,i,a.value,a.reason,u,null===a.variationIndex?void 0:a.variationIndex,null==o?void 0:o.version,c,this._logger)}}}async migrationVariation(e,t,i){return(await this._hookRunner.withEvaluationSeriesExtraDetail(e,t,i,"LDClient.migrationVariation",(()=>this._migrationVariationInternal(e,t,i)))).migration}allFlagsState(e,t,i){var r,n,s;if(this._config.offline){null===(r=this._logger)||void 0===r||r.info("allFlagsState() called in offline mode. Returning empty state.");const e=new $i.default(!1,!1).build();return null==i||i(null,e),Promise.resolve(e)}const a=xi.Context.fromLDContext(e);return a.valid?new Promise((e=>{const r=r=>this._featureStore.all(qi.default.Features,(n=>{const s=new $i.default(r,!!(null==t?void 0:t.withReasons)),o=!!(null==t?void 0:t.clientSideOnly),l=!!(null==t?void 0:t.detailsOnlyForTrackedFlags);(0,Ri.allAsync)(Object.values(n),((e,t)=>{var i;const r=e;!o||(null===(i=r.clientSideAvailability)||void 0===i?void 0:i.usingEnvironmentId)?this._evaluator.evaluateCb(r,a,(e=>{var i;e.isError&&this._onError(new Error(`Error for feature flag "${r.key}" while evaluating all flags: ${e.message}`));const n=(0,Ki.default)(r,e.detail.reason);s.addFlag(r,e.detail.value,null!==(i=e.detail.variationIndex)&&void 0!==i?i:void 0,e.detail.reason,r.trackEvents||n,n,l,e.prerequisites),t(!0)})):t(!0)}),(()=>{const t=s.build();null==i||i(null,t),e(t)}))}));this.initialized()?r(!0):this._featureStore.initialized((e=>{var t,i;let n=!0;e?null===(t=this._logger)||void 0===t||t.warn("Called allFlagsState before client initialization; using last known values from data store"):(null===(i=this._logger)||void 0===i||i.warn("Called allFlagsState before client initialization. Data store not available; returning empty state"),n=!1),r(n)}))})):(null===(n=this._logger)||void 0===n||n.info(`${null!==(s=a.message)&&void 0!==s?s:"Invalid context."}. Returning empty state.`),Promise.resolve(new $i.default(!1,!1).build()))}secureModeHash(e){const t=xi.Context.fromLDContext(e),i=t.valid?t.canonicalKey:void 0;if(!this._platform.crypto.createHmac)throw new Error("Platform must implement createHmac");const r=this._platform.crypto.createHmac("sha256",this._sdkKey);if(void 0===i)throw new xi.LDClientError("Could not generate secure mode hash for invalid context");return r.update(i),r.digest("hex")}close(){var e;this._eventProcessor.close(),null===(e=this._updateProcessor)||void 0===e||e.close(),this._featureStore.close(),this._bigSegmentsManager.close()}isOffline(){return this._config.offline}track(e,t,i,r){var n,s;const a=xi.Context.fromLDContext(t);a.valid?(void 0===r||xi.TypeValidators.Number.is(r)||null===(s=this._logger)||void 0===s||s.warn(Wi.invalidMetricValue(typeof r)),this._eventProcessor.sendEvent(this._eventFactoryDefault.customEvent(e,a,i,r))):null===(n=this._logger)||void 0===n||n.warn(Wi.MissingContextKeyNoEvent)}trackMigration(e){const t=(0,zi.default)(e);t&&this._eventProcessor.sendEvent(t)}identify(e){var t;const i=xi.Context.fromLDContext(e);i.valid?this._eventProcessor.sendEvent(this._eventFactoryDefault.identifyEvent(i)):null===(t=this._logger)||void 0===t||t.warn(Wi.MissingContextKeyNoEvent)}async flush(e){try{await this._eventProcessor.flush()}catch(t){return null==e?void 0:e(t,!1)}return null==e?void 0:e(null,!0)}addHook(e){this._hookRunner.addHook(e)}_variationInternal(e,t,i,r,n,s){var a,o;if(this._config.offline)return null===(a=this._logger)||void 0===a||a.info("Variation called in offline mode. Returning default value."),void n(Ai.default.forError(Ji.ClientNotReady,void 0,i));const l=xi.Context.fromLDContext(t);if(!l.valid)return this._onError(new xi.LDClientError(`${null!==(o=l.message)&&void 0!==o?o:"Context not valid;"} returning default value.`)),void n(Ai.default.forError(Ji.UserNotSpecified,void 0,i));this._featureStore.get(qi.default.Features,e,(t=>{const a=t;if(!a){const t=new xi.LDClientError(`Unknown feature flag "${e}"; returning default value`);this._onError(t);const r=Ai.default.forError(Ji.FlagNotFound,void 0,i);return this._eventProcessor.sendEvent(this._eventFactoryDefault.unknownFlagEvent(e,i,l)),void n(r)}this._evaluator.evaluateCb(a,l,(t=>{var o;if(void 0!==t.detail.variationIndex&&null!==t.detail.variationIndex||(null===(o=this._logger)||void 0===o||o.debug("Result value is null in variation"),t.setDefault(i)),s){const[o,u]=s(t.detail.value);if(!o){const t=Ai.default.forError(Ji.WrongType,`Did not receive expected type (${u}) evaluating feature flag "${e}"`,i);return this._sendEvalEvent(t,r,a,l,i),void n(t,a)}}this._sendEvalEvent(t,r,a,l,i),n(t,a)}),r)}))}_sendEvalEvent(e,t,i,r,n){var s;null===(s=e.events)||void 0===s||s.forEach((e=>{this._eventProcessor.sendEvent(Object.assign({},e))})),this._eventProcessor.sendEvent(t.evalEventServer(i,r,e.detail,n,void 0))}_evaluateIfPossible(e,t,i,r,n,s){this.initialized()?this._variationInternal(e,t,i,r,n,s):this._featureStore.initialized((a=>{var o,l;if(a)return null===(o=this._logger)||void 0===o||o.warn("Variation called before LaunchDarkly client initialization completed (did you wait for the 'ready' event?) - using last known values from feature store"),void this._variationInternal(e,t,i,r,n,s);null===(l=this._logger)||void 0===l||l.warn("Variation called before LaunchDarkly client initialization completed (did you wait for the'ready' event?) - using default value"),n(Ai.default.forError(Ji.ClientNotReady,void 0,i))}))}_dataSourceErrorHandler(e){var t;const i=401===e.code?new Error("Authentication failed. Double check your SDK key."):e;this._onError(i),this._onFailed(i),this.initialized()||(this._initState=Xi.Failed,this._rejectionReason=i,null===(t=this._initReject)||void 0===t||t.call(this,i))}_initSuccess(){var e;this.initialized()||(this._initState=Xi.Initialized,null===(e=this._initResolve)||void 0===e||e.call(this,this),this._onReady())}_clientWithTimeout(e,t,i){if(t){const r=(0,xi.cancelableTimedPromise)(t,"waitForInitialization");return Promise.race([e.then((()=>r.cancel())).then((()=>this)),r.promise.then((()=>this))]).catch((e=>{throw e instanceof xi.LDTimeoutError&&(null==i||i.error(e.message)),e}))}return e}};var Qi={};Object.defineProperty(Qi,"__esModule",{value:!0}),Qi.createMigration=Qi.LDMigrationError=Qi.LDMigrationSuccess=void 0;const Zi=l,er=j;Qi.LDMigrationSuccess=function(e){return{success:!0,result:e}},Qi.LDMigrationError=function(e){return{success:!1,error:e}};class tr{constructor(e,t){var i,r;this._client=e,this._config=t,this._readTable={[Zi.LDMigrationStage.Off]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[Zi.LDMigrationStage.DualWrite]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[Zi.LDMigrationStage.Shadow]:async e=>{const{fromOld:t,fromNew:i}=await this._doRead(e);return this._trackConsistency(e,t,i),t},[Zi.LDMigrationStage.Live]:async e=>{const{fromNew:t,fromOld:i}=await this._doRead(e);return this._trackConsistency(e,i,t),t},[Zi.LDMigrationStage.RampDown]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[Zi.LDMigrationStage.Complete]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config))},this._writeTable={[Zi.LDMigrationStage.Off]:async e=>({authoritative:await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config))}),[Zi.LDMigrationStage.DualWrite]:async e=>{const t=await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config));if(!t.success)return{authoritative:t};return{authoritative:t,nonAuthoritative:await this._doSingleOp(e,"new",this._config.writeNew.bind(this._config))}},[Zi.LDMigrationStage.Shadow]:async e=>{const t=await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config));if(!t.success)return{authoritative:t};return{authoritative:t,nonAuthoritative:await this._doSingleOp(e,"new",this._config.writeNew.bind(this._config))}},[Zi.LDMigrationStage.Live]:async e=>{const t=await this._doSingleOp(e,"new",this._config.writeNew.bind(this._config));if(!t.success)return{authoritative:t};return{authoritative:t,nonAuthoritative:await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config))}},[Zi.LDMigrationStage.RampDown]:async e=>{const t=await this._doSingleOp(e,"new",this._config.writeNew.bind(this._config));if(!t.success)return{authoritative:t};return{authoritative:t,nonAuthoritative:await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config))}},[Zi.LDMigrationStage.Complete]:async e=>({authoritative:await this._doSingleOp(e,"new",this._config.writeNew.bind(this._config))})},this._config.execution?this._execution=this._config.execution:this._execution=new er.LDConcurrentExecution,this._latencyTracking=null===(i=this._config.latencyTracking)||void 0===i||i,this._errorTracking=null===(r=this._config.errorTracking)||void 0===r||r}async read(e,t,i,r){const n=await this._client.migrationVariation(e,t,i),s=await this._readTable[n.value]({payload:r,tracker:n.tracker});return n.tracker.op("read"),this._sendEvent(n.tracker),s}async write(e,t,i,r){const n=await this._client.migrationVariation(e,t,i),s=await this._writeTable[n.value]({payload:r,tracker:n.tracker});return n.tracker.op("write"),this._sendEvent(n.tracker),s}_sendEvent(e){const t=e.createEvent();t&&this._client.trackMigration(t)}_trackConsistency(e,t,i){this._config.check&&t.success&&i.success&&e.tracker.consistency((()=>this._config.check(t.result,i.result)))}async _readSequentialFixed(e){return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:await this._doSingleOp(e,"new",this._config.readNew.bind(this._config))}}async _readConcurrent(e){const t=this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),i=this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[r,n]=await Promise.all([t,i]);return{fromOld:r,fromNew:n}}async _readSequentialRandom(e){if(0===Math.floor(2*Math.random())){return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:await this._doSingleOp(e,"new",this._config.readNew.bind(this._config))}}const t=await this._doSingleOp(e,"new",this._config.readNew.bind(this._config));return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:t}}async _doRead(e){var t;if((null===(t=this._execution)||void 0===t?void 0:t.type)===er.LDExecution.Serial){return this._execution.ordering===er.LDExecutionOrdering.Fixed?this._readSequentialFixed(e):this._readSequentialRandom(e)}return this._readConcurrent(e)}async _doSingleOp(e,t,i){e.tracker.invoked(t);const r=await this._trackLatency(e.tracker,t,(()=>async function(e){try{return await e()}catch(e){return{success:!1,error:e}}}((()=>i(e.payload)))));return!r.success&&this._errorTracking&&e.tracker.error(t),Object.assign({origin:t},r)}async _trackLatency(e,t,i){if(!this._latencyTracking)return i();let r,n,s;"undefined"!=typeof performance?(r=performance.now(),s=await i(),n=performance.now()):(r=Date.now(),s=await i(),n=Date.now());const a=n-r;return e.latency(t,a),s}}Qi.createMigration=function(e,t){return new tr(e,t)};var ir={},rr={},nr={},sr={};Object.defineProperty(sr,"__esModule",{value:!0});sr.default=class{constructor(e,t,i,r){this._filesystem=e,this._paths=t,this._watch=i,this._callback=r,this._watchers=[],this._fileData={},this._fileTimestamps={}}async loadAndWatch(){const e=this._paths.map((async e=>({data:await this._filesystem.readFile(e),path:e,timeStamp:await this._filesystem.getFileTimestamp(e)}))),t=await Promise.all(e);t.forEach((e=>{this._fileData[e.path]=e.data,this._fileTimestamps[e.path]=e.timeStamp})),this._callback(t),this._watch&&this._paths.forEach((e=>{const t=this._filesystem.watch(e,(async(e,t)=>{const i=await this._filesystem.getFileTimestamp(t);if(i===this._fileTimestamps[t])return;this._fileTimestamps[t]=i;const r=await this._filesystem.readFile(t);this._fileData[t]=r,this._debounceCallback()}));this._watchers.push(t)}))}close(){this._watchers.forEach((e=>e.close()))}_debounceCallback(){this._debounceHandle||(this._debounceHandle=setTimeout((()=>{this._debounceHandle=void 0,this._callback(Object.entries(this._fileData).reduce(((e,[t,i])=>(e.push({path:t,data:i}),e)),[]))}),10))}},Object.defineProperty(nr,"__esModule",{value:!0});const ar=ae,or=oe,lr=sr;nr.default=class{constructor(e,t,i,r=()=>{},n){var s;this._featureStore=i,this._initSuccessHandler=r,this._errorHandler=n,this._allData={},this._fileLoader=new lr.default(t,e.paths,null!==(s=e.autoUpdate)&&void 0!==s&&s,(e=>{var t,i;try{this._processFileData(e)}catch(e){null===(t=this._errorHandler)||void 0===t||t.call(this,e),null===(i=this._logger)||void 0===i||i.error(`Error processing files: ${e}`)}})),this._logger=e.logger,this._yamlParser=e.yamlParser}start(){(async()=>{var e;try{await this._fileLoader.loadAndWatch()}catch(t){null===(e=this._errorHandler)||void 0===e||e.call(this,t)}})()}stop(){this._fileLoader.close()}close(){this.stop()}_addItem(e,t){if(this._allData[e.namespace]||(this._allData[e.namespace]={}),this._allData[e.namespace][t.key])throw new Error(`found duplicate key: "${t.key}"`);this._allData[e.namespace][t.key]=t}_processFileData(e){const t=this._allData;this._allData={},e.forEach((e=>{let i;if(e.path.endsWith(".yml")||e.path.endsWith(".yaml")){if(!this._yamlParser)throw new Error(`Attempted to parse yaml file (${e.path}) without parser.`);i=this._yamlParser(e.data)}else i=JSON.parse(e.data);this._processParsedData(i,t)})),this._featureStore.init(this._allData,(()=>{this._initSuccessHandler(),this._initSuccessHandler=()=>{}}))}_processParsedData(e,t){Object.keys(e.flags||{}).forEach((t=>{(0,ar.processFlag)(e.flags[t]),this._addItem(or.default.Features,e.flags[t])})),Object.keys(e.flagValues||{}).forEach((i=>{var r,n;const s=null===(r=t[or.default.Features.namespace])||void 0===r?void 0:r[i];let{version:a}=null!=s?s:{version:1};s&&JSON.stringify(e.flagValues[i])!==JSON.stringify(null===(n=null==s?void 0:s.variations)||void 0===n?void 0:n[0])&&(a+=1);const o=function(e,t,i){return{key:e,on:!0,fallthrough:{variation:0},variations:[t],version:i}}(i,e.flagValues[i],a);(0,ar.processFlag)(o),this._addItem(or.default.Features,o)})),Object.keys(e.segments||{}).forEach((t=>{(0,ar.processSegment)(e.segments[t]),this._addItem(or.default.Segments,e.segments[t])}))}},Object.defineProperty(rr,"__esModule",{value:!0});const ur=nr;rr.default=class{constructor(e){this._options=e}create(e,t,i,r){const n={paths:this._options.paths,autoUpdate:this._options.autoUpdate,logger:this._options.logger||e.basicConfiguration.logger,yamlParser:this._options.yamlParser};return new ur.default(n,e.platform.fileSystem,t,i,r)}getFactory(){return(e,t,i,r)=>this.create(e,t,i,r)}};var cr={},dr={},hr={},fr={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.variationForBoolean=e.FALSE_VARIATION_INDEX=e.TRUE_VARIATION_INDEX=void 0,e.TRUE_VARIATION_INDEX=0,e.FALSE_VARIATION_INDEX=1,e.variationForBoolean=function(t){return t?e.TRUE_VARIATION_INDEX:e.FALSE_VARIATION_INDEX}}(fr);var gr={};Object.defineProperty(gr,"__esModule",{value:!0});const _r=o,vr=fr;class pr{constructor(e,t,i){this._flagBuilder=e,this._clauses=[],t&&(this._clauses=[...t]),void 0!==i&&(this._variation=i)}andMatch(e,t,...i){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new _r.AttributeReference(t),op:"in",values:i,negate:!1}),this}andNotMatch(e,t,...i){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new _r.AttributeReference(t),op:"in",values:i,negate:!0}),this}thenReturn(e){return _r.TypeValidators.Boolean.is(e)?(this._flagBuilder.booleanFlag(),this.thenReturn((0,vr.variationForBoolean)(e))):(this._variation=e,this._flagBuilder.addRule(this),this._flagBuilder)}build(e){return{id:`rule${e}`,variation:this._variation,clauses:this._clauses}}clone(){return new pr(this._flagBuilder,this._clauses,this._variation)}}gr.default=pr,Object.defineProperty(hr,"__esModule",{value:!0});const yr=o,mr=fr,br=gr;class wr{constructor(e,t){this._key=e,this._data={on:!0,variations:[]},t&&(this._data={on:t.on,variations:[...t.variations]},void 0!==t.offVariation&&(this._data.offVariation=t.offVariation),void 0!==t.fallthroughVariation&&(this._data.fallthroughVariation=t.fallthroughVariation),t.targetsByVariation&&(this._data.targetsByVariation=JSON.parse(JSON.stringify(t.targetsByVariation))),t.rules&&(this._data.rules=[],t.rules.forEach((e=>{var t;null===(t=this._data.rules)||void 0===t||t.push(e.clone())}))))}get _isBooleanFlag(){return 2===this._data.variations.length&&!0===this._data.variations[mr.TRUE_VARIATION_INDEX]&&!1===this._data.variations[mr.FALSE_VARIATION_INDEX]}booleanFlag(){return this._isBooleanFlag?this:this.variations(!0,!1).fallthroughVariation(mr.TRUE_VARIATION_INDEX).offVariation(mr.FALSE_VARIATION_INDEX)}variations(...e){return this._data.variations=[...e],this}on(e){return this._data.on=e,this}fallthroughVariation(e){return yr.TypeValidators.Boolean.is(e)?this.booleanFlag().fallthroughVariation((0,mr.variationForBoolean)(e)):(this._data.fallthroughVariation=e,this)}offVariation(e){return yr.TypeValidators.Boolean.is(e)?this.booleanFlag().offVariation((0,mr.variationForBoolean)(e)):(this._data.offVariation=e,this)}variationForAll(e){return this.on(!0).clearRules().clearAllTargets().fallthroughVariation(e)}valueForAll(e){return this.variations(e).variationForAll(0)}variationForUser(e,t){return this.variationForContext("user",e,t)}variationForContext(e,t,i){return yr.TypeValidators.Boolean.is(i)?this.booleanFlag().variationForContext(e,t,(0,mr.variationForBoolean)(i)):(this._data.targetsByVariation||(this._data.targetsByVariation={}),this._data.variations.forEach(((r,n)=>{if(n===i){const i=this._data.targetsByVariation[n]||{};e in i||(i[e]=[]);-1!==i[e].indexOf(t)||i[e].push(t),this._data.targetsByVariation[n]=i}else{const i=this._data.targetsByVariation[n];if(i){const r=i[e];if(r){const n=r.indexOf(t);-1!==n&&(r.splice(n,1),r.length||delete i[e])}Object.keys(i).length||delete this._data.targetsByVariation[n]}}})),this)}clearRules(){return delete this._data.rules,this}clearAllTargets(){return delete this._data.targetsByVariation,this}ifMatch(e,t,...i){return new br.default(this).andMatch(e,t,...i)}ifNotMatch(e,t,...i){return new br.default(this).andNotMatch(e,t,...i)}checkRatio(e){var t;return this._data.migration=null!==(t=this._data.migration)&&void 0!==t?t:{},this._data.migration.checkRatio=e,this}samplingRatio(e){return this._data.samplingRatio=e,this}addRule(e){this._data.rules||(this._data.rules=[]),this._data.rules.push(e)}build(e){const t={key:this._key,version:e,on:this._data.on,offVariation:this._data.offVariation,fallthrough:{variation:this._data.fallthroughVariation},variations:[...this._data.variations],migration:this._data.migration,samplingRatio:this._data.samplingRatio};if(this._data.targetsByVariation){const e=[],i=[];Object.entries(this._data.targetsByVariation).forEach((([t,r])=>{Object.entries(r).forEach((([r,n])=>{const s=parseInt(t,10);e.push({contextKind:r,values:"user"===r?[]:n,variation:s}),"user"===r&&i.push({values:n,variation:s})}))})),t.targets=i,t.contextTargets=e}return this._data.rules&&(t.rules=this._data.rules.map(((e,t)=>e.build(String(t))))),t}clone(){return new wr(this._key,this._data)}getKey(){return this._key}}hr.default=wr;var Sr={};Object.defineProperty(Sr,"__esModule",{value:!0});Sr.default=class{constructor(e,t,i,r,n){this._featureStore=e,this._onStop=r,this._listeners=n,this._flags=Object.assign({},t),this._segments=Object.assign({},i)}async start(){this._listeners.forEach((({processJson:e})=>{e({data:{flags:this._flags,segments:this._segments}})}))}stop(){this._onStop(this)}close(){this.stop()}async upsert(e,t){return this._featureStore.upsert(e,t)}},Object.defineProperty(dr,"__esModule",{value:!0});const kr=se,Er=Pe,Or=ae,xr=oe,Dr=hr,Pr=Sr;dr.default=class{constructor(){this._currentFlags={},this._currentSegments={},this._dataSources=[],this._flagBuilders={}}getFactory(){return(e,t,i,r)=>{const n=(0,kr.createStreamListeners)(t,e.basicConfiguration.logger,{put:i}),s=new Pr.default(new Er.default(t),this._currentFlags,this._currentSegments,(e=>{this._dataSources.splice(this._dataSources.indexOf(e))}),n);return this._dataSources.push(s),s}}flag(e){return this._flagBuilders[e]?this._flagBuilders[e].clone():new Dr.default(e).booleanFlag()}update(e){const t=e.getKey(),i=this._currentFlags[t],r=i?i.version:0,n=e.build(r+1);return this._currentFlags[t]=n,this._flagBuilders[t]=e.clone(),Promise.all(this._dataSources.map((e=>e.upsert(xr.default.Features,n))))}usePreconfiguredFlag(e){const t=JSON.parse(JSON.stringify(e)),i=this._currentFlags[t.key],r=Object.assign(Object.assign({},t),{version:i?i.version+1:t.version});return(0,Or.processFlag)(r),this._currentFlags[t.key]=r,Promise.all(this._dataSources.map((e=>e.upsert(xr.default.Features,r))))}usePreconfiguredSegment(e){const t=JSON.parse(JSON.stringify(e)),i=this._currentSegments[t.key],r=Object.assign(Object.assign({},t),{version:i?i.version+1:t.version});return(0,Or.processSegment)(r),this._currentSegments[t.key]=r,Promise.all(this._dataSources.map((e=>e.upsert(xr.default.Segments,r))))}},Object.defineProperty(cr,"__esModule",{value:!0}),cr.TestDataRuleBuilder=cr.TestDataFlagBuilder=cr.TestData=void 0;const Mr=dr;cr.TestData=Mr.default;const Tr=hr;cr.TestDataFlagBuilder=Tr.default;const jr=gr;cr.TestDataRuleBuilder=jr.default,function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.FileDataSourceFactory=void 0;const n=rr;e.FileDataSourceFactory=n.default,i(cr,e),i(V,e)}(ir);var Ir={},Cr={};Object.defineProperty(Cr,"__esModule",{value:!0});Cr.default=class{constructor(e,t){this.handlers={},this.closed=!1,this.url=e,this.options=t}addEventListener(e,t){this.handlers[e]=t}close(){this.closed=!0}simulateError(e){this.options.errorFilter(e)||(this.closed=!0)}},Object.defineProperty(Ir,"__esModule",{value:!0}),Ir.NullEventSource=void 0;const Fr=Cr;Ir.NullEventSource=Fr.default,function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.createMigration=e.LDMigrationSuccess=e.LDMigrationError=e.BigSegmentStoreStatusProviderImpl=e.LDClientImpl=e.platform=e.integrations=void 0;const n=s;e.BigSegmentStoreStatusProviderImpl=n.default;const u=a;e.LDClientImpl=u.default;const c=Qi;Object.defineProperty(e,"createMigration",{enumerable:!0,get:function(){return c.createMigration}}),Object.defineProperty(e,"LDMigrationError",{enumerable:!0,get:function(){return c.LDMigrationError}}),Object.defineProperty(e,"LDMigrationSuccess",{enumerable:!0,get:function(){return c.LDMigrationSuccess}}),e.integrations=ir,e.platform=o,i(l,e),i(De,e),i(Ir,e),i(o,e)}(n);class Rr{constructor(e){let t;switch(e){case"sha1":t=i.algo.SHA1;break;case"sha256":t=i.algo.SHA256;break;default:throw new Error("unsupported hash algorithm. Only sha1 and sha256 are supported.")}this._cryptoJSHasher=t.create()}digest(e){const t=this._cryptoJSHasher.finalize();let r;switch(e){case"base64":r=i.enc.Base64;break;case"hex":r=i.enc.Hex;break;default:throw new Error("unsupported output encoding. Only base64 and hex are supported.")}return t.toString(r)}update(e){return this._cryptoJSHasher.update(e),this}}class Ar{constructor(e,t){let r;switch(e){case"sha1":r=i.algo.SHA1;break;case"sha256":r=i.algo.SHA256;break;default:throw new Error("unsupported hash algorithm. Only sha1 and sha256 are supported.")}this._cryptoJSHmac=i.algo.HMAC.create(r,t)}digest(e){const t=this._cryptoJSHmac.finalize();if("base64"===e)return t.toString(i.enc.Base64);if("hex"===e)return t.toString(i.enc.Hex);throw new Error("unsupported output encoding. Only base64 and hex are supported.")}update(e){return this._cryptoJSHmac.update(e),this}}class Vr{createHash(e){return new Rr(e)}createHmac(e,t){return new Ar(e,t)}randomUUID(){return crypto.randomUUID()}}class Nr{fetch(e,t={}){return fetch(e,t)}createEventSource(e,t){return new n.NullEventSource(e,t)}getEventSourceCapabilities(){return{readTimeout:!1,headers:!1,customMethod:!1}}}class Lr{constructor(e){this.crypto=new Vr,this.requests=new Nr,this.info=e}}const Kr={stream:!1,sendEvents:!1,useLdd:!0,diagnosticOptOut:!0,logger:n.BasicLogger.get()};class $r extends n.LDClientImpl{constructor(t,i,r){const s=new e,a=new Lr(i),o={analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1},l=(e=>{var t;const i=Object.assign(Object.assign({},Kr),e);return null===(t=i.logger)||void 0===t||t.debug(`Using LD options: ${JSON.stringify(i)}`),i})(r);var u,c;super(t,a,l,(u=s,c=l.logger,{onError:e=>{u.listenerCount("error")?u.emit("error",e):null==c||c.error(e.message)},onFailed:e=>{u.emit("failed",e)},onReady:()=>{u.emit("ready")},onUpdate:n.noop,hasEventListeners:()=>!1}),o),this.emitter=s}}class Ur{constructor(e,t,i,r){this._edgeProvider=e,this._description=i,this._logger=r,this.close=n.noop,this.delete=n.noop,this.upsert=n.noop,this._rootKey=`LD-Env-${t}`}async get(e,t,i){const{namespace:r}=e,s="features"===r?"flags":r;this._logger.debug(`Requesting ${t} from ${this._rootKey}.${s}`);try{const e=await this._edgeProvider.get(this._rootKey);if(!e)throw new Error(`${this._rootKey}.${s} is not found in KV.`);const a=n.deserializePoll(e);if(!a)throw new Error(`Error deserializing ${s}`);switch(r){case"features":i(a.flags[t]);break;case"segments":i(a.segments[t]);break;default:i(null)}}catch(e){this._logger.error(e),i(null)}}async all(e,t=n.noop){const{namespace:i}=e,r="features"===i?"flags":i;this._logger.debug(`Requesting all from ${this._rootKey}.${r}`);try{const e=await this._edgeProvider.get(this._rootKey);if(!e)throw new Error(`${this._rootKey}.${r} is not found in KV.`);const s=n.deserializePoll(e);if(!s)throw new Error(`Error deserializing ${r}`);switch(i){case"features":t(s.flags);break;case"segments":t(s.segments);break;default:t({})}}catch(e){this._logger.error(e),t({})}}async initialized(e=n.noop){const t=null!==await this._edgeProvider.get(this._rootKey);this._logger.debug(`Is ${this._rootKey} initialized? ${t}`),e(t)}init(e,t){t()}getDescription(){return this._description}}const zr=(e,t)=>{const{featureStore:i,logger:r,sendEvents:n}=t,s=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]])}return i}(t,["featureStore","logger","sendEvents"]);if(!e)throw new Error("You must configure the client with a client key");if(!i||"object"!=typeof i||!i.get)throw new Error("You must configure the client with a feature store");if(!r)throw new Error("You must configure the client with a logger");if("{}"!==JSON.stringify(s))throw new Error(`Invalid configuration: ${Object.keys(s).toString()} not supported`);return!0};class Br{platformData(){return{name:"Cloudflare"}}sdkData(){return{name:"@launchdarkly/cloudflare-server-sdk",version:"2.6.5",userAgentBase:"CloudflareEdgeSDK"}}}var Hr=Object.defineProperty,qr=Object.getOwnPropertySymbols,Wr=Object.prototype.hasOwnProperty,Jr=Object.prototype.propertyIsEnumerable,Gr=(e,t,i)=>t in e?Hr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;const Xr=(e,t,i={})=>{var r;const s=null!=(r=i.logger)?r:n.BasicLogger.get();return((e,t,i)=>(zr(e,i),new $r(e,t,i)))(e,new Br,((e,t)=>{for(var i in t||(t={}))Wr.call(t,i)&&Gr(e,i,t[i]);if(qr)for(var i of qr(t))Jr.call(t,i)&&Gr(e,i,t[i]);return e})({featureStore:new Ur(t,e,"Cloudflare",s),logger:s},i))};export{Ur as EdgeFeatureStore,Xr as init};
2
2
  //# sourceMappingURL=index.js.map