@launchdarkly/akamai-server-base-sdk 3.0.32 → 3.0.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("crypto"),t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},r={},i={},n={};Object.defineProperty(n,"__esModule",{value:!0});n.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 s={},a={};!function(e){function t(e){return e.indexOf("~")?e.replace(/~1/g,"/").replace(/~0/g,"~"):e}class r{constructor(e,r=!1){if(r){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:r}=this;if(!r)return;let i=e;for(let e=0;e<t.length;e+=1){const r=t[e];if(null==i||!Object.prototype.hasOwnProperty.call(i,r)||"object"!=typeof i||Array.isArray(i))return;i=i[r]}return i}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,r)=>t===e.getComponent(r))}get components(){return[...this._components]}}r.InvalidReference=new r("");class i{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 c{is(e){return"boolean"==typeof e||null==e}getType(){return"boolean | undefined | null"}}const u=/^\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&&u.test(e)}getType(){return"date"}}class h extends o{constructor(){super(/^(\w|\.|-)+$/)}is(e){return super.is(e)&&"kind"!==e}}class f{constructor(e){this._values=e}is(e){return"string"==typeof e&&this._values.includes(e)}getType(){return this._values.join(" | ")}}function p(e){return null==e}class v{static createTypeArray(e,t){return new s(e,t)}static numberWithMin(e){return new a(e)}static stringMatchingRegex(e){return new o(e)}static oneOf(...e){return new f(e)}}function g(e){return"kind"in e&&(v.String.is(e.kind)&&"multi"!==e.kind)}function _(e){return"kind"in e&&(v.String.is(e.kind)&&"multi"===e.kind)}function m(e){return!("kind"in e)||null===e.kind||void 0===e.kind}function y(e,t=[]){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(t.includes(e))throw new Error("Cycle detected");if(Array.isArray(e)){return`[${e.map(r=>y(r,[...t,e])).map(e=>void 0===e?"null":e).join(",")}]`}return`{${Object.keys(e).sort().map(r=>{const i=y(e[r],[...t,e]);if(void 0!==i)return`${JSON.stringify(r)}:${i}`}).filter(e=>void 0!==e).join(",")}}`}v.String=new n("string",""),v.Number=new n("number",0),v.ObjectOrFactory=new i,v.Object=new n("object",{}),v.StringArray=new s("string[]",""),v.Boolean=new n("boolean",!0),v.Function=new l,v.Date=new d,v.Kind=new h,v.NullableBoolean=new c;const b="user";function E(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}function S(e){return v.Kind.is(e)}function w(e){return v.String.is(e)&&""!==e}function O(e,t=!1){return e?e.map(e=>new r(e,t)):[]}class k{constructor(e,t,r){this._isMulti=!1,this._isUser=!1,this._wasLegacy=!1,this._contexts={},this.kind=t,this.valid=e,this.message=r}static _contextForError(e,t){return new k(!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),r=t.every(S);if(!t.length)return k._contextForError("multi","A multi-kind context must contain at least one kind");if(!r)return k._contextForError("multi","Context contains invalid kinds");const i={};let n=!0;const s=t.reduce((t,r)=>{const s=e[r];var a;return(a=s)&&v.Object.is(a)?(t[r]=s,i[r]=O(s._meta?.privateAttributes)):n=!1,t},{});if(!n)return k._contextForError("multi","Context contained contexts that were not objects");if(!Object.values(s).every(e=>w(e.key)))return k._contextForError("multi","Context contained invalid keys");if(1===t.length){const e=t[0],r=new k(!0,e);return r._context={...s[e],kind:e},r._privateAttributeReferences=i,r._isUser="user"===e,r}const a=new k(!0,e.kind);return a._contexts=s,a._privateAttributeReferences=i,a._isMulti=!0,a}static _fromSingleKindContext(e){const{key:t,kind:r}=e,i=S(r),n=w(t);if(!i)return k._contextForError(r??"unknown","The kind was not valid for the context");if(!n)return k._contextForError(r,"The key for the context was not valid");const s=O(e._meta?.privateAttributes),a=new k(!0,r);return a._isUser="user"===r,a._context=e,a._privateAttributeReferences={[r]:s},a}static _fromLegacyUser(e){if(!(void 0!==e.key&&null!==e.key))return k._contextForError("user","The key for the context was not valid");const t=new k(!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 r=!!e.anonymous;delete t.anonymous,t.anonymous=r}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:O(e.privateAttributeNames,!0)},t}static fromLDContext(e){return e?g(e)?k._fromSingleKindContext(e):_(e)?k._fromMultiKindContext(e):m(e)?k._fromLegacyUser(e):k._contextForError("unknown","Context was not of a valid kind"):k._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 r={kind:"multi"};return t.forEach(e=>{const t=e[0],i=e[1];r[t]=i}),r}valueForKind(e,t=b){return e.isKind?this.kinds:k._getValueFromContext(e,this._contextForKind(t))}key(e=b){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}:${E(this._contexts[e].key)}`).join(":"):`${this.kind}:${E(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,r])=>(e[t]=r.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}canonicalUnfilteredJson(){if(this.valid){if(this._cachedCanonicalJson)return this._cachedCanonicalJson;try{this._cachedCanonicalJson=y(k.toLDContext(this))}catch{}return this._cachedCanonicalJson}}}k.UserKind=b;const D=["key","kind","_meta","anonymous"].map(e=>new r(e,!0)),P=["name","ip","firstName","lastName","email","avatar","country"];class T{constructor(e,t){this._allAttributesPrivate=e,this._privateAttributes=t}filter(e,t=!1){const r=e.getContexts();if(1===r.length)return this._filterSingleKind(e,r[0][1],r[0][0],t);const i={kind:"multi"};return r.forEach(([r,n])=>{i[r]=this._filterSingleKind(e,n,r,t)}),i}_getAttributesToFilter(e,t,i,n){return(n?Object.keys(t).map(e=>new r(e,!0)):[...this._privateAttributes,...e.privateAttributes(i)]).filter(e=>!D.some(t=>t.compare(e)))}_filterSingleKind(e,t,r,i){const n=this._allAttributesPrivate||i&&!0===t.anonymous,{cloned:s,excluded:a}=function(e,t){const r=[],i={},n=[];for(r.push(...Object.keys(e).map(t=>({key:t,ptr:[t],source:e,parent:i,visited:[e]})));r.length;){const e=r.pop(),i=t.find(t=>{return r=t,i=e.ptr,r.depth===i.length&&i.every((e,t)=>e===r.getComponent(t));var r,i});if(i)n.push(i.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]={},r.push(...Object.keys(t).map(r=>({key:r,ptr:[...e.ptr,r],source:t,parent:e.parent[e.key],visited:[...e.visited,t]})))):e.parent[e.key]=t}}return{cloned:i,excluded:n.sort()}}(t,this._getAttributesToFilter(e,t,r,n));return e.legacy&&P.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}}class I{constructor(e,t,r=Math.random){this._retryResetIntervalMillis=t,this._random=r,this._retryCount=0,this._initialRetryDelayMillis=Math.max(1,e),this._maxExponent=Math.ceil(Math.log2(3e4/this._initialRetryDelayMillis))}_backoff(){const e=Math.min(this._retryCount,this._maxExponent),t=this._initialRetryDelayMillis*2**e;return Math.min(t,3e4)}_jitter(e){return e-Math.trunc(.5*this._random()*e)}success(e=Date.now()){this._activeSince=e}fail(e=Date.now()){void 0!==this._activeSince&&e-this._activeSince>this._retryResetIntervalMillis&&(this._retryCount=0),this._activeSince=void 0;const t=this._jitter(this._backoff());return this._retryCount+=1,t}}class x{constructor(e,t){this._dataCallback=e,this._statusCallback=t,this._disabled=!1}disable(){this._disabled=!0}async dataHandler(e,t){this._disabled||this._dataCallback(e,t)}async statusHandler(e,t){this._disabled||this._statusCallback(e,t)}}var R;!function(e){e[e.Valid=0]="Valid",e[e.Initializing=1]="Initializing",e[e.Interrupted=2]="Interrupted",e[e.Closed=3]="Closed"}(R||(R={}));class M{constructor(e,t){this._list=t?[...t]:[],this._circular=e,this._pos=0}next(){if(this._list.length<=0||this._pos>=this._list.length)return;const e=this._list[this._pos];return this._circular?this._pos=(this._pos+1)%this._list.length:this._pos+=1,e}replace(e){this._list=[...e],this._pos=0}remove(e){const t=this._list.indexOf(e);return!(t<0)&&(this._list.splice(t,1),this._list.length>0&&(t<this._pos&&(this._pos-=1),this._circular&&this._pos>this._list.length-1&&(this._pos=0)),!0)}reset(){this._pos=0}pos(){return this._pos}length(){return this._list.length}clear(){this._list=[],this._pos=0}}class A extends Error{constructor(e){super(e),this.name="LaunchDarklyFileDataSourceError"}}class F extends Error{constructor(e,t,r,i=!0){super(t),this.kind=e,this.status=r,this.name="LaunchDarklyPollingError",this.recoverable=i}}class C extends Error{constructor(e,t,r,i=!0){super(t),this.kind=e,this.code=r,this.name="LaunchDarklyStreamingError",this.recoverable=i}}class L extends Error{constructor(e,t,r){super(t),this.kind=e,this.code=r,this.name="LDFlagDeliveryFallbackError",this.recoverable=!1}}var j,N,$,V;e.DataSourceErrorKind=void 0,(j=e.DataSourceErrorKind||(e.DataSourceErrorKind={})).Unknown="UNKNOWN",j.NetworkError="NETWORK_ERROR",j.ErrorResponse="ERROR_RESPONSE",j.InvalidData="INVALID_DATA",e.AutoEnvAttributes=void 0,(N=e.AutoEnvAttributes||(e.AutoEnvAttributes={}))[N.Disabled=0]="Disabled",N[N.Enabled=1]="Enabled",function(e){e[e.AnalyticsEvents=0]="AnalyticsEvents",e[e.DiagnosticEvent=1]="DiagnosticEvent"}($||($={})),function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.FailedAndMustShutDown=2]="FailedAndMustShutDown"}(V||(V={}));var U=Object.freeze({__proto__:null,get DataSourceState(){return R},get LDDeliveryStatus(){return V},get LDEventType(){return $}});function K(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 z={s:e=>K(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=>K(e),o:e=>K(e),O:e=>K(e),c:()=>""};function B(...e){const t=e.shift();if(v.String.is(t)){let r="",i=0;for(;i<t.length;){const n=t.charAt(i);if("%"===n){if(i+1<t.length){const n=t.charAt(i+1);if(n in z&&e.length){const t=e.shift();r+=z[n]?.(t)}else r+="%"===n?"%":`%${n}`;i+=2}}else r+=n,i+=1}return e.length&&(r.length&&(r+=" "),r+=e.map(K).join(" ")),r}return e.map(K).join(" ")}var H;!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"}(H||(H={}));const q=["debug","info","warn","error","none"];class W{static get(){return new W({})}constructor(e){if(this._logLevel=H[e.level??"info"]??H.info,this._name=e.name??"LaunchDarkly",this._formatter=e.formatter,"object"==typeof e.destination)this._destinations={[H.debug]:e.destination.debug,[H.info]:e.destination.info,[H.warn]:e.destination.warn,[H.error]:e.destination.error};else if("function"==typeof e.destination){const{destination:t}=e;this._destinations={[H.debug]:t,[H.info]:t,[H.warn]:t,[H.error]:t}}}_tryFormat(...e){try{return this._formatter?this._formatter?.(...e):B(...e)}catch{return B(...e)}}_tryWrite(e,t){try{e(t)}catch{console.error(t)}}_log(e,t){if(e>=this._logLevel){const r=`${q[e]}: [${this._name}]`;try{const i=this._destinations?.[e];i?this._tryWrite(i,`${r} ${this._tryFormat(...t)}`):console.error(...t)}catch{console.error(...t)}}}error(...e){this._log(H.error,e)}warn(...e){this._log(H.warn,e)}info(...e){this._log(H.info,e)}debug(...e){this._log(H.debug,e)}}const G={error:v.Function,warn:v.Function,info:v.Function,debug:v.Function};class J{constructor(e,t){Object.entries(G).forEach(([t,r])=>{if(!r.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 X{static deprecated(e,t){return`"${e}" is deprecated, please use "${t}"`}static optionBelowMinimum(e,t,r){return`Config option "${e}" had invalid value of ${t}, using minimum of ${r} instead`}static unknownOption(e){return`Ignoring unknown config option "${e}"`}static wrongOptionType(e,t,r){return`Config option "${e}" should be of type ${t}, got ${r}, 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 Y=v.stringMatchingRegex(/^(\w|\.|-)+$/),Z=(e,t)=>Y.is(e)?e.length>64?{valid:!1,message:X.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:X.invalidTagValue(t)};function Q(e){return e.replace(/\/+$/,"")}function ee(e){return e.replace(/^\/+/,"").replace(/\?$/,"")}class te{constructor(e,t,r=te.DEFAULT_EVENTS,i="/bulk",n="/diagnostic",s=!0,a){this.streaming=Q(e),this.polling=Q(t),this.events=Q(r),this.analyticsEventPath=i,this.diagnosticEventPath=n,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}}function re(e,t=[]){if(0===t.length)return e;return`${e}?${t.map(({key:e,value:t})=>`${e}=${t}`).join("&")}`}function ie(e,t,r=[]){const i=ee(t);return re(`${e.events}/${i}`,r)}te.DEFAULT_EVENTS="https://events.launchdarkly.com";class ne extends Error{constructor(e){super(e),this.name="LaunchDarklyUnexpectedResponseError"}}class se extends Error{constructor(e){super(e),this.name="LaunchDarklyClientError"}}class ae extends Error{constructor(e){super(e),this.name="LaunchDarklyTimeoutError"}}function oe(e){return!(e>=400&&e<500)||(400===e||408===e||429===e)}function le(e){return 413===e||oe(e)}const ce=(e,t)=>e?Object.entries(e).reduce((e,[r,i])=>(!Boolean(i)||(e=>"{}"===JSON.stringify(e))(i)||t?.includes(r)||(e[r]="object"==typeof i?ce(i,t):i),e),{}):e;function ue(e,t,r){let i;i=e.status?`error ${e.status}${401===e.status?" (invalid SDK key)":""}`:`I/O error (${e.message||"unknown error"})`;return`Received ${i} for ${t} - ${r??"giving up permanently"}`}const de=async(e=1e3)=>new Promise(e=>{});var he;!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"}(he||(he={}));var fe=he;class pe{static invalidMetricValue(e){return`The track function was called with a non-numeric "metricValue" (${e}), only numeric metric values are supported.`}}pe.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";class ve{constructor(e,t){const{basicConfiguration:r,platform:i}=e,{serviceEndpoints:{analyticsEventPath:n,diagnosticEventPath:s}}=r,{crypto:a,requests:o}=i;this._defaultHeaders={...t},this._eventsUri=ie(r.serviceEndpoints,n,[]),this._diagnosticEventsUri=ie(r.serviceEndpoints,s,[]),this._requests=o,this._crypto=a}async _tryPostingEvents(e,t,r,i){const n={status:V.Succeeded},s={...this._defaultHeaders,"content-type":"application/json"};let a;r&&(s["x-launchdarkly-payload-id"]=r,s["x-launchDarkly-event-schema"]="4");try{const{status:r,headers:i}=await this._requests.fetch(t,{headers:s,body:JSON.stringify(e),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),o=Date.parse(i.get("date")||"");if(o&&(n.serverTime=o),r<=204)return n;if(a=new ne(ue({status:r,message:"some events were dropped"},"event posting")),!oe(r))return le(r)?n.status=V.Failed:n.status=V.FailedAndMustShutDown,n.error=a,n}catch(e){a=e}return a&&!i?(n.status=V.Failed,n.error=a,n):(await de(),this._tryPostingEvents(e,this._eventsUri,r,!1))}async sendEventData(e,t){const r=e===$.AnalyticsEvents?this._crypto.randomUUID():void 0,i=e===$.AnalyticsEvents?this._eventsUri:this._diagnosticEventsUri;return this._tryPostingEvents(t,i,r,!0)}}function ge(e){return"feature"===e.kind}class _e{constructor(e,t,r,i,n,s){this.count=e,this.key=t,this.value=r,this.version=n,this.variation=s,this.default=i}increment(){this.count+=1}}class me{constructor(e=!1,t){this._singleContext=e,this._contextFilter=t,this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}summarizeEvent(e){if(ge(e)&&!e.excludeFromSummaries){this._context||(this._context=e.context);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),r=this._counters[t];let i=this._contextKinds[e.key];i||(i=new Set,this._contextKinds[e.key]=i),e.context.kinds.forEach(e=>i.add(e)),r?r.increment():this._counters[t]=new _e(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 r=e[t.key];r||(r={default:t.default,counters:[],contextKinds:[...this._contextKinds[t.key]]},e[t.key]=r);const i={value:t.value,count:t.count};return void 0!==t.variation&&null!==t.variation&&(i.variation=t.variation),void 0!==t.version&&null!==t.version?i.version=t.version:i.unknown=!0,r.counters.push(i),e},{}),t={startDate:this._startDate,endDate:this._endDate,features:e,kind:"summary",context:void 0!==this._context&&this._singleContext?this._contextFilter?.filter(this._context):void 0};return this._clearSummary(),t}_clearSummary(){this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}}class ye extends Error{constructor(e){super(e),this.name="LaunchDarklyInvalidSDKKeyError"}}class be{constructor(e,t){this._contextFilter=e,this._logger=t,this._summarizers={}}summarizeEvent(e){if(ge(e)){const t=e.context.canonicalUnfilteredJson();if(!t)return void(e.context.valid&&this._logger?.error("Unable to serialize context, likely the context contains a cycle."));let r=this._summarizers[t];r||(this._summarizers[t]=new me(!0,this._contextFilter),r=this._summarizers[t]),r.summarizeEvent(e)}}getSummaries(){const e=this._summarizers;return this._summarizers={},Object.values(e).map(e=>e.getSummary())}}function Ee(e){const t=Math.trunc(e);return 1===t||0!==t&&0===Math.floor(Math.random()*t)}class Se{constructor(e,t,r,i,n=1,s){this.context=e,this.key=t,this.data=r,this.metricValue=i,this.samplingRatio=n,this.url=s,this.kind="custom",this.creationDate=Date.now(),this.context=e}}class we{constructor(e,t,r,i,n,s,a,o,l,c,u,d,h=1){this.withReasons=e,this.context=t,this.key=r,this.samplingRatio=h,this.kind="feature",this.creationDate=Date.now(),this.value=i,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!==c&&(this.reason=c),void 0!==u&&(this.debugEventsUntilDate=u),void 0!==d&&(this.excludeFromSummaries=d)}}class Oe{constructor(e,t=1){this.context=e,this.samplingRatio=t,this.kind="identify",this.creationDate=Date.now()}}const ke="FDv1Fallback";const De={type:"none"};function Pe(e,t){let r="inactive",i="partial",n=[];function s(){r="inactive",i="partial",n=[]}function a(e){if(!e.payloads?.length)return{type:"error",kind:"MISSING_PAYLOAD",message:"No payload present in server-intent"};const s=e.payloads[0];switch(s?.intentCode){case"xfer-full":return r="full",n=[],i="full",De;case"xfer-changes":return r="changes",n=[],i="partial",De;case"none":return r="changes",n=[],i="partial",p((a=s).target)?(t?.warn(`Ignoring 'none' intent with missing fields: target=${a.target}`),De):{type:"payload",payload:{version:a.target,type:"none",updates:[]}};default:return t?.warn(`Unable to process intent code '${s?.intentCode}'.`),De}var a}function o(i){if("inactive"===r)return t?.warn("Received put-object before server-intent was established. Ignoring."),De;if(!i.kind||!i.key||p(i.version)||!i.object)return t?.warn(`Ignoring put-object with missing fields: kind=${i.kind}, key=${i.key}, version=${i.version}`),De;const s=(a=i.kind,o=i.object,e[a]?.(o));var a,o;return s?(n.push({kind:i.kind,key:i.key,version:i.version,object:s}),De):(t?.warn(`Unable to process object for kind: '${i.kind}'`),De)}function l(e){if("inactive"===r)return{type:"error",kind:"PROTOCOL_ERROR",message:"A payload transferred has been received without an intent having been established."};if(p(e.state)||p(e.version))return t?.warn(`Ignoring payload-transferred with missing fields: state=${e.state}, version=${e.version}`),s(),De;const a={type:"payload",payload:{version:e.version,state:e.state,type:i,updates:n}};return r="changes",i="partial",n=[],a}function c(e){return t?.info(`An issue was encountered receiving updates with reason: ${e.reason}.`),n=[],{type:"serverError",id:e.payload_id,reason:e.reason}}return{get state(){return r},processEvent(e){switch(e.event){case"server-intent":return a(e.data);case"put-object":return o(e.data);case"delete-object":return function(e){return"inactive"===r?(t?.warn("Received delete-object before server-intent was established. Ignoring."),De):e.kind&&e.key&&!p(e.version)?(n.push({kind:e.kind,key:e.key,version:e.version,deleted:!0}),De):(t?.warn(`Ignoring delete-object with missing fields: kind=${e.kind}, key=${e.key}, version=${e.version}`),De)}(e.data);case"payload-transferred":return l(e.data);case"goodbye":return function(e){return t?.info(`Goodbye was received from the LaunchDarkly connection with reason: ${e.reason}.`),s(),{type:"goodbye",reason:e.reason}}(e.data);case"error":return c(e.data);case"heart-beat":return De;default:return{type:"error",kind:"UNKNOWN_EVENT",message:`Received an unknown event of type '${e.event}'`}}},reset(){s()}}}class Te{constructor(e,t,r){this._errorHandler=t,this._logger=r,this._listeners=[],this._handler=Pe(e,r)}addPayloadListener(e){this._listeners.push(e)}removePayloadListener(e){const t=this._listeners.indexOf(e,0);t>-1&&this._listeners.splice(t,1)}processEvents(t){t.forEach(t=>{const r=this._handler.processEvent(t);switch(r.type){case"payload":this._listeners.forEach(e=>e(r.payload));break;case"error":"MISSING_PAYLOAD"===(i=r.kind)||"PROTOCOL_ERROR"===i?this._errorHandler?.(e.DataSourceErrorKind.InvalidData,r.message):this._logger?.warn(r.message)}var i})}}const Ie="unknown plugin";function xe(e,t){try{return t.getMetadata().name||Ie}catch{return e.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),Ie}}var Re=Object.freeze({__proto__:null,ClientMessages:pe,DiagnosticsManager:class{constructor(e,t,r){this._platform=t,this._diagnosticInitConfig=r,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,r){const i={timestamp:e,failed:t,durationMillis:r};this._streamInits.push(i)}createStatsEventAndReset(e,t,r){const i=Date.now(),n={kind:"diagnostic",id:this._id,creationDate:i,dataSinceDate:this._dataSinceDate,droppedEvents:e,deduplicatedUsers:t,eventsInLastBatch:r,streamInits:this._streamInits};return this._streamInits=[],this._dataSinceDate=i,n}},ErrorKinds:fe,EventFactoryBase:class{constructor(e){this._withReasons=e}evalEvent(e){return new we(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,r){return new we(this._withReasons,r,e,t,t,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(e){return new Oe(e,1)}customEvent(e,t,r,i,n=1){return new Se(t,e,r??void 0,i??void 0,n)}},EventProcessor:class{constructor(e,t,i,n,s,a=!0,o=!1){this._config=e,this._contextDeduplicator=n,this._diagnosticsManager=s,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 ve(t,i),this._contextFilter=new T(e.allAttributesPrivate,e.privateAttributes.map(e=>new r(e))),this._summarizer=o?new be(this._contextFilter,this._logger):new me,a&&this.start()}start(){if(void 0!==this._contextDeduplicator?.flushInterval&&(this._flushUsersTimer=void this._contextDeduplicator.flushInterval),this._flushTimer=void this._config.flushInterval,this._diagnosticsManager){const e=this._diagnosticsManager.createInitEvent();this._postDiagnosticEvent(e),this._diagnosticsTimer=void this._config.diagnosticRecordingInterval}this._logger?.debug("Started EventProcessor.")}_postDiagnosticEvent(e){this._eventSender.sendEventData($.DiagnosticEvent,e)}close(){clearInterval(this._flushTimer),this._flushUsersTimer&&clearInterval(this._flushUsersTimer),this._diagnosticsTimer&&clearInterval(this._diagnosticsTimer)}async flush(){if(this._shutdown)throw new ye("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;if(this._queue=[],void 0!==this._summarizer.getSummaries){this._summarizer.getSummaries().forEach(t=>{Object.keys(t.features).length&&e.push(t)})}else{const t=this._summarizer.getSummary();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(Ee(e.samplingRatio)){const t={...e,context:e.context?this._contextFilter.filter(e.context,this._config.redactAnonymousAllEvents??!1):void 0};1===t.samplingRatio&&delete t.samplingRatio,this._enqueue(t)}return}this._summarizer.summarizeEvent(e);const t=ge(e),r=t&&e.trackEvents||!t,i=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)),r&&Ee(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!1)),i&&Ee(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!0))}_makeOutputEvent(e,t){switch(e.kind){case"feature":{const r={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&&(r.samplingRatio=e.samplingRatio),e.prereqOf&&(r.prereqOf=e.prereqOf),void 0!==e.variation&&(r.variation=e.variation),void 0!==e.version&&(r.version=e.version),e.reason&&(r.reason=e.reason),r}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,context:this._contextFilter.filter(e.context,this._config.redactAnonymousAllEvents??!1)};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 ge(e)&&e.debugEventsUntilDate&&e.debugEventsUntilDate>this._lastKnownPastTime&&e.debugEventsUntilDate>Date.now()}async _tryPostingEvents(e){const t=await this._eventSender.sendEventData($.AnalyticsEvents,e);if(t.status===V.FailedAndMustShutDown&&(this._shutdown=!0),t.serverTime&&(this._lastKnownPastTime=t.serverTime),t.error)throw t.error}},FDv1PayloadAdaptor:function(e){return{_processor:e,_selector:"",useSelector(e){return this._selector=e,this},processFullTransfer(e){const t=[{event:"server-intent",data:{payloads:[{id:ke,target:1,intentCode:"xfer-full",reason:"payload-missing"}]}}];Object.entries(e?.flags||[]).forEach(([e,r])=>{t.push({event:"put-object",data:{kind:"flag",key:e,version:r.version||1,object:r}})}),Object.entries(e?.segments||[]).forEach(([e,r])=>{t.push({event:"put-object",data:{kind:"segment",key:e,version:r.version||1,object:r}})}),t.push({event:"payload-transferred",data:{state:this._selector,version:1,id:ke}}),this._processor.processEvents(t)}}},InputCustomEvent:Se,InputEvalEvent:we,InputIdentifyEvent:Oe,NullEventProcessor:class{close(){}async flush(){}sendEvent(){}},PayloadProcessor:Te,PayloadStreamReader:class{constructor(e,t,r,i){this._errorHandler=r,this._logger=i,this._attachHandler(e,"server-intent"),this._attachHandler(e,"put-object"),this._attachHandler(e,"delete-object"),this._attachHandler(e,"payload-transferred"),this._attachHandler(e,"goodbye"),this._attachHandler(e,"error"),this._payloadProcessor=new Te(t,r,i)}addPayloadListener(e){this._payloadProcessor.addPayloadListener(e)}removePayloadListener(e){this._payloadProcessor.removePayloadListener(e)}_attachHandler(t,r){t.addEventListener(r,async t=>{if(t?.data){this._logger?.debug(`Received ${r} event. Data is ${t.data}`);try{this._payloadProcessor.processEvents([{event:r,data:JSON.parse(t.data)}])}catch{this._logger?.error(`Stream received data that was unable to be processed in "${r}" message`),this._logger?.debug(`Data follows: ${t.data}`),this._errorHandler?.(e.DataSourceErrorKind.InvalidData,"Malformed data in EventStream.")}}else this._errorHandler?.(e.DataSourceErrorKind.Unknown,"Event from EventStream missing data.")})}},canonicalize:y,createProtocolHandler:Pe,initMetadataFromHeaders:function(e){if(e){const t=Object.keys(e).find(e=>"x-ld-envid"===e.toLowerCase());if(t)return{environmentId:e[t]}}},isLegacyUser:m,isMultiKind:_,isSingleKind:g,safeGetHooks:function(e,t,r){const i=[];return r.forEach(r=>{try{const n=r.getHooks?.(t);void 0===n?e.error(`Plugin ${xe(e,r)} returned undefined from getHooks.`):n&&n.length>0&&i.push(...n)}catch(t){e.error(`Exception thrown getting hooks for plugin ${xe(e,r)}. Unable to get hooks.`)}}),i},safeGetName:xe,safeRegisterPlugins:function(e,t,r,i){i.forEach(i=>{try{i.register(r,t)}catch(t){e.error(`Exception thrown registering plugin ${xe(e,i)}.`)}})},shouldSample:Ee});e.ApplicationTags=class{constructor(e){const t={},r=e?.application,i=e?.logger;r&&Object.entries(r).forEach(([e,r])=>{if(null!=r){const{valid:n,message:s}=Z(r,`application.${e}`);n?"versionName"===e?t["application-version-name"]=[r]:t[`application-${e}`]=[r]:i?.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=r,e.BasicLogger=W,e.ClientContext=class{constructor(e,t,r){this.platform=r,this.basicConfiguration={tags:t.tags,logger:t.logger,offline:t.offline,serviceEndpoints:t.serviceEndpoints,sdkKey:e}}},e.CompositeDataSource=class{constructor(e,t,r,i,n={[R.Valid]:{durationMS:3e5,transition:"recover"},[R.Interrupted]:{durationMS:12e4,transition:"fallback"}},s=new I(1e3,3e4)){this._logger=i,this._transitionConditions=n,this._backoff=s,this._fdv1FallbackEngaged=!1,this._stopped=!0,this._cancelTokens=[],this._cancellableDelay=e=>{let t;return{promise:new Promise((e,r)=>{t=e=>{e()}}),cancel(){t&&(clearTimeout(t),t=void 0)}}},this._externalTransitionPromise=new Promise(e=>{this._externalTransitionResolve=e}),this._initPhaseActive=e.length>0,this._initFactories=new M(!1,e),this._syncFactories=new M(!0,t),this._fdv1Synchronizers=new M(!0,r)}async start(e,t,r){if(!this._stopped)return void this._logger?.info("CompositeDataSource already running. Ignoring call to start.");this._stopped=!1,this._logger?.debug(`CompositeDataSource starting with (${this._initFactories.length()} initializers, ${this._syncFactories.length()} synchronizers).`);const i=this._wrapStatusCallbackWithSanitizer(t);let n;for(i(R.Initializing);;){const{dataSource:s,isPrimary:a,cullDSFactory:o}=this._pickDataSource(n),l=new Promise(t=>{if(s){let n,l=()=>{};const c=(e,r)=>{this._fdv1Synchronizers.length()>0?this._logger?.warn("Falling back to FDv1"):this._logger?.warn("FDv1 fallback was requested but no FDv1 fallback synchronizer is configured; data source will terminate"),this._fdv1FallbackEngaged=!0,this._syncFactories=this._fdv1Synchronizers,i(e,r),this._consumeCancelToken(l),t({transition:"switchToSync",err:r})},u=new x((r,n)=>{if(this._backoff.success(),e(r,n),n?.fallbackToFDv1&&!this._fdv1FallbackEngaged)return u.disable(),void c(R.Interrupted,void 0);r&&this._initPhaseActive&&(u.disable(),this._consumeCancelToken(l),i(R.Interrupted),t({transition:"switchToSync"}))},(e,r)=>{if(this._logger?.debug(`CompositeDataSource received state ${e} from underlying data source. Err is ${r}`),r||e===R.Closed){if(u.disable(),!1===r?.recoverable&&(this._logger?.debug(`Culling data source due to err ${r}`),o?.()),r instanceof L&&!this._fdv1FallbackEngaged)return void c(e,r);i(e,r),this._consumeCancelToken(l),t({transition:"fallback",err:r})}else if(i(e),e!==n){n=e,this._consumeCancelToken(l);const r=this._lookupTransitionCondition(e,a);if(r){const{promise:e,cancel:n}=this._cancellableDelay(r.durationMS);l=n,this._cancelTokens.push(l),e.then(()=>{this._consumeCancelToken(n),u.disable(),i(R.Interrupted),t({transition:r.transition})})}}});s.start((e,t)=>u.dataHandler(e,t),(e,t)=>u.statusHandler(e,t),r)}else t({transition:"stop",err:{name:"ExhaustedDataSources",message:"CompositeDataSource has exhausted all configured initializers and synchronizers."}})});let c=await Promise.race([l,this._externalTransitionPromise]);s?.stop();const u="switchToSync"===c.transition&&c.err instanceof L;if(c.err&&"stop"!==c.transition&&!u){const e=this._initPhaseActive?0:this._backoff.fail(),{promise:t,cancel:r}=this._cancellableDelay(e);this._cancelTokens.push(r);const i=t.then(()=>(this._consumeCancelToken(r),c));c=await Promise.race([i,this._externalTransitionPromise]),this._consumeCancelToken(r)}if(n=c.transition,"stop"===c.transition){t(R.Closed,c.err);break}}this._reset()}async stop(){this._cancelTokens.forEach(e=>e()),this._cancelTokens=[],this._externalTransitionResolve?.({transition:"stop"})}_reset(){this._stopped=!0,this._initPhaseActive=this._initFactories.length()>0,this._initFactories.reset(),this._syncFactories.reset(),this._fdv1Synchronizers.reset(),this._fdv1FallbackEngaged=!1,this._externalTransitionPromise=new Promise(e=>{this._externalTransitionResolve=e})}_pickDataSource(e){let t,r;switch(e){case"switchToSync":this._initPhaseActive=!1,this._syncFactories.reset(),r=0===this._syncFactories.pos(),t=this._syncFactories.next();break;case"recover":this._initPhaseActive?(this._initFactories.reset(),r=0===this._initFactories.pos(),t=this._initFactories.next()):(this._syncFactories.reset(),r=0===this._syncFactories.pos(),t=this._syncFactories.next());break;default:this._initPhaseActive&&this._initFactories.pos()>=this._initFactories.length()&&(this._initPhaseActive=!1,this._syncFactories.reset()),this._initPhaseActive?(r=0===this._initFactories.pos(),t=this._initFactories.next()):(r=0===this._syncFactories.pos(),t=this._syncFactories.next())}return t?{dataSource:t(),isPrimary:r,cullDSFactory:()=>{t&&this._syncFactories.remove(t)}}:{dataSource:void 0,isPrimary:r,cullDSFactory:void 0}}_lookupTransitionCondition(e,t){const r=this._transitionConditions[e];if(!t||"recover"!==r?.transition)return r}_consumeCancelToken(e){e();const t=this._cancelTokens.indexOf(e,0);t>-1&&this._cancelTokens.splice(t,1)}_wrapStatusCallbackWithSanitizer(e){let t,r,i=!1;return(n,s)=>{let a=n;if(n===R.Closed&&(a=R.Interrupted),a!==t||s!==r){if(a===R.Initializing){if(i)return;i=!0}t=a,r=s,e(a,s)}}}},e.Context=k,e.ContextFilter=T,e.DateValidator=d,e.DefaultBackoff=I,e.FactoryOrInstance=i,e.Function=l,e.KindValidator=h,e.LDClientError=se,e.LDFileDataSourceError=A,e.LDFlagDeliveryFallbackError=L,e.LDPollingError=F,e.LDStreamingError=C,e.LDTimeoutError=ae,e.LDUnexpectedResponseError=ne,e.NullableBoolean=c,e.NumberWithMinimum=a,e.OneOf=f,e.OptionMessages=X,e.SafeLogger=J,e.ServiceEndpoints=te,e.StringMatchingRegex=o,e.Type=n,e.TypeArray=s,e.TypeValidators=v,e.base64UrlEncode=(e,t)=>t.btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.cancelableTimedPromise=function(e,t){let r,i;return{promise:new Promise((e,t)=>{i=e,r=e=>{e()}}),cancel:()=>{i(),clearTimeout(r)}}},e.clone=function(e){return null==e?e:JSON.parse(JSON.stringify(e))},e.createSafeLogger=e=>{const t=new W({level:"info",destination:console.error,formatter:B});return e?new J(e,t):t},e.debounce=(e,t=5e3)=>{let r;return(...e)=>{clearTimeout(r),r=e=>{e()}}},e.deepCompact=ce,e.defaultHeaders=function(e,t,r,i=!0,n="user-agent",s){const{userAgentBase:a,version:o,wrapperName:l,wrapperVersion:c}=t.sdkData(),u={[n]:`${a??"NodeJSClient"}/${o}`};return i&&(u.authorization=e),l&&(u["x-launchdarkly-wrapper"]=c?`${l}/${c}`:l),r?.value&&(u["x-launchdarkly-tags"]=r.value),s&&(u["x-launchdarkly-instance-id"]=s),u},e.fastDeepEqual=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var i,n,s;if(Array.isArray(t)){if((i=t.length)!=r.length)return!1;for(n=i;0!==n--;)if(!e(t[n],r[n]))return!1;return!0}if(t instanceof Map&&r instanceof Map){if(t.size!==r.size)return!1;for(n of t.entries())if(!r.has(n[0]))return!1;for(n of t.entries())if(!e(n[1],r.get(n[0])))return!1;return!0}if(t instanceof Set&&r instanceof Set){if(t.size!==r.size)return!1;for(n of t.entries())if(!r.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(r)){if((i=t.length)!=r.length)return!1;for(n=i;0!==n--;)if(t[n]!==r[n])return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((i=(s=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(n=i;0!==n--;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=i;0!==n--;){var a=s[n];if(!e(t[a],r[a]))return!1}return!0}return t!=t&&r!=r},e.getEventsUri=ie,e.getPollingUri=function(e,t,r=[]){const i=ee(t),n=[...r];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),re(`${e.polling}/${i}`,n)},e.getStreamingUri=function(e,t,r){const i=ee(t),n=[...r];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),re(`${e.streaming}/${i}`,n)},e.httpErrorMessage=ue,e.internal=Re,e.isHttpLocallyRecoverable=le,e.isHttpRecoverable=oe,e.isNullish=p,e.noop=()=>{},e.secondsToMillis=function(e){return Math.trunc(1e3*e)},e.shouldRetry=function({status:e}){return!e||oe(e)},e.sleep=de,e.subsystem=U,e.timedPromise=(e,t)=>new Promise((e,t)=>{})}(a);var o={},l={},c={};Object.defineProperty(c,"__esModule",{value:!0});var u={};Object.defineProperty(u,"__esModule",{value:!0});var d,h={};Object.defineProperty(h,"__esModule",{value:!0}),h.IsMigrationStage=h.LDMigrationStage=void 0,function(e){e.Off="off",e.DualWrite="dualwrite",e.Shadow="shadow",e.Live="live",e.RampDown="rampdown",e.Complete="complete"}(d||(h.LDMigrationStage=d={})),h.IsMigrationStage=function(e){return Object.values(d).includes(e)};var f={};Object.defineProperty(f,"__esModule",{value:!0});var p,v={};Object.defineProperty(v,"__esModule",{value:!0}),v.LDConsistencyCheck=void 0,function(e){e[e.Inconsistent=0]="Inconsistent",e[e.Consistent=1]="Consistent",e[e.NotChecked=2]="NotChecked"}(p||(v.LDConsistencyCheck=p={})),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(c,e),i(u,e),i(h,e),i(f,e),i(v,e)}(l);var g={},_={};Object.defineProperty(_,"__esModule",{value:!0});var m={};Object.defineProperty(m,"__esModule",{value:!0});var y={};Object.defineProperty(y,"__esModule",{value:!0});var b={};Object.defineProperty(b,"__esModule",{value:!0});var E,S,w={};Object.defineProperty(w,"__esModule",{value:!0}),w.LDConcurrentExecution=w.LDSerialExecution=w.LDExecution=w.LDExecutionOrdering=void 0,function(e){e[e.Fixed=0]="Fixed",e[e.Random=1]="Random"}(E||(w.LDExecutionOrdering=E={})),function(e){e[e.Serial=0]="Serial",e[e.Concurrent=1]="Concurrent"}(S||(w.LDExecution=S={}));w.LDSerialExecution=class{constructor(e){this.ordering=e,this.type=S.Serial}};w.LDConcurrentExecution=class{constructor(){this.type=S.Concurrent}};var O={};Object.defineProperty(O,"__esModule",{value:!0}),O.isCustomOptions=O.isPollingOnlyOptions=O.isStreamingOnlyOptions=O.isStandardOptions=void 0,O.isStandardOptions=function(e){return"standard"===e.dataSourceOptionsType},O.isStreamingOnlyOptions=function(e){return"streamingOnly"===e.dataSourceOptionsType},O.isPollingOnlyOptions=function(e){return"pollingOnly"===e.dataSourceOptionsType},O.isCustomOptions=function(e){return"custom"===e.dataSourceOptionsType},function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(_,e),i(m,e),i(y,e),i(b,e),i(w,e),i(O,e)}(g);var k={};Object.defineProperty(k,"__esModule",{value:!0});var D={};Object.defineProperty(D,"__esModule",{value:!0});var P={};Object.defineProperty(P,"__esModule",{value:!0});var T={};Object.defineProperty(T,"__esModule",{value:!0});var I={};Object.defineProperty(I,"__esModule",{value:!0});var x={};Object.defineProperty(x,"__esModule",{value:!0});var R={},M={};Object.defineProperty(M,"__esModule",{value:!0});var A={};Object.defineProperty(A,"__esModule",{value:!0}),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(M,e),i(A,e)}(R);var F={},C={};Object.defineProperty(C,"__esModule",{value:!0});var L={};Object.defineProperty(L,"__esModule",{value:!0});var j={};Object.defineProperty(j,"__esModule",{value:!0});var N={};Object.defineProperty(N,"__esModule",{value:!0});var $={};Object.defineProperty($,"__esModule",{value:!0});var V={};Object.defineProperty(V,"__esModule",{value:!0});var U={};Object.defineProperty(U,"__esModule",{value:!0});var K={};Object.defineProperty(K,"__esModule",{value:!0});var z={};Object.defineProperty(z,"__esModule",{value:!0});var B={};Object.defineProperty(B,"__esModule",{value:!0}),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(C,e),i(L,e),i(j,e),i(N,e),i($,e),i(P,e),i(V,e),i(U,e),i(K,e),i(z,e),i(B,e)}(F);var H={},q={};Object.defineProperty(q,"__esModule",{value:!0});var W={};Object.defineProperty(W,"__esModule",{value:!0});var G={};Object.defineProperty(G,"__esModule",{value:!0}),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(q,e),i(W,e),i(T,e),i(G,e),i(I,e)}(H),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),e.subsystems=e.interfaces=e.integrations=void 0,i(l,e),i(g,e),i(k,e),i(D,e),i(P,e),i(T,e),i(I,e),i(x,e),e.integrations=R,e.interfaces=F,e.subsystems=H}(o);var J={},X={};Object.defineProperty(X,"__esModule",{value:!0});X.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 r=this._keyMap.get(e);void 0===r?(r=this._index(),this._keys[r]=e,this._keyMap.set(e,r),this._next[this._tail]=r,this._prev[r]=this._tail,this._tail=r,this._size+=1):this._setTail(r),this._values[r]=t,this._maxAge&&(this._lastUpdated[r]=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(J,"__esModule",{value:!0});const Y=a,Z=n,Q=X;J.default=class{constructor(e,t,r,i){this._store=e,this._logger=r,this._crypto=i,this.statusProvider=new Z.default(async()=>this._pollStoreAndUpdateStatus()),this._staleTimeMs=1e3*(Y.TypeValidators.Number.is(t.staleAfter)&&t.staleAfter>0?t.staleAfter:120);Y.TypeValidators.Number.is(t.statusPollInterval)&&t.statusPollInterval>0&&t.statusPollInterval;this._pollHandle=e?void 0:null,e&&(this._cache=new Q.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,r,i;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===(r=this._cache)||void 0===r||r.set(e,t)}catch(e){return null===(i=this._logger)||void 0===i||i.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,r;if(!this._store)return void this.statusProvider.setStatus({available:!1,stale:!1});let i;null===(e=this._logger)||void 0===e||e.debug("Querying Big Segment store status");try{const e=await this._store.getMetadata();i={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}`),i={available:!1,stale:!1}}const n=this.statusProvider.getStatus();n&&n.available===i.available&&n.stale===i.stale||(null===(r=this._logger)||void 0===r||r.debug("Big Segment store status changed from %s to %s",JSON.stringify(n),JSON.stringify(i)),this.statusProvider.setStatus(i),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 ee={};Object.defineProperty(ee,"__esModule",{value:!0}),ee.createPluginEnvironmentMetadata=void 0,ee.createPluginEnvironmentMetadata=function(e,t,r){const i={sdk:{name:e.info.sdkData().userAgentBase,version:e.info.sdkData().version},sdkKey:t};return e.info.sdkData().wrapperName&&(i.sdk.wrapperName=e.info.sdkData().wrapperName),e.info.sdkData().wrapperVersion&&(i.sdk.wrapperVersion=e.info.sdkData().wrapperVersion),r.applicationInfo&&(i.application=r.applicationInfo),i};var te={};Object.defineProperty(te,"__esModule",{value:!0}),te.createPayloadListener=void 0;te.createPayloadListener=(e,t,r=()=>{})=>i=>{const{initMetadata:n,payload:s}=i;if("full"===s.type)null==t||t.debug("Initializing all data");else{if(!(s.updates.length>0))return void(null==t||t.debug("Payload had no updates, ignoring."));null==t||t.debug("Applying updates")}const a={};s.updates.forEach(e=>{const r=(e=>{switch(e){case"flag":return"features";case"segment":return"segments";default:return e}})(e.kind);a[r]?a[r][e.key]=Object.assign(Object.assign({version:e.version},e.deleted&&{deleted:e.deleted}),e.object):a[r]={[e.key]:Object.assign(Object.assign({version:e.version},e.deleted&&{deleted:e.deleted}),e.object)},e.deleted?null==t||t.debug(`Deleting ${e.key} in ${e.kind}`):null==t||t.debug(`Updating ${e.key} in ${e.kind}`)}),e.applyChanges("full"===s.type,a,()=>{""!==s.state&&r()},n,s.state)};var re={},ie={},ne={};Object.defineProperty(ne,"__esModule",{value:!0});class se{static getKeyFromPath(e,t){return t.startsWith(e.streamApiPath)?t.substring(e.streamApiPath.length):void 0}}se.Features={namespace:"features",streamApiPath:"/flags/"},se.Segments={namespace:"segments",streamApiPath:"/segments/"},ne.default=se,Object.defineProperty(ie,"__esModule",{value:!0}),ie.deserializeSegment=ie.serializeSegment=ie.deserializeFlag=ie.serializeFlag=ie.deserializeDelete=ie.deserializePatch=ie.deserializePoll=ie.deserializeAll=ie.reviveFullPayload=ie.processSegment=ie.processFlag=ie.replacer=ie.nullReplacer=void 0;const ae=a,oe=ne,le=100;function ce(e,t){const r=[];if(null==e)return;const i=Object.entries(e).filter(([e,r])=>!(null==t?void 0:t.includes(e)));for(r.push(...i.map(([t,r])=>({key:t,value:r,parent:e})));r.length;){const e=r.pop();null!==e.value||Array.isArray(e.parent)?"object"==typeof e.value&&null!==e.value&&r.push(...Object.entries(e.value).map(([t,r])=>({key:t,value:r,parent:e.value}))):delete e.parent[e.key]}}function ue(e,t){if(!(t instanceof ae.AttributeReference||Array.isArray(t)&&t[0]&&t[0]instanceof ae.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 de(e){e&&e.bucketBy&&(e.bucketByAttributeReference=new ae.AttributeReference(e.bucketBy,!e.contextKind))}function he(e){var t;if(ce(e,["variations"]),e.fallthrough&&e.fallthrough.rollout){de(e.fallthrough.rollout)}null===(t=null==e?void 0:e.rules)||void 0===t||t.forEach(e=>{var t;de(e.rollout),null===(t=null==e?void 0:e.clauses)||void 0===t||t.forEach(e=>{e&&e.attribute?e.attributeReference=new ae.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ae.AttributeReference.InvalidReference)})})}function fe(e){var t,r,i,n,s;ce(e),(null===(t=null==e?void 0:e.included)||void 0===t?void 0:t.length)&&e.included.length>le&&(e.generated_includedSet=new Set(e.included),delete e.included),(null===(r=null==e?void 0:e.excluded)||void 0===r?void 0:r.length)&&e.excluded.length>le&&(e.generated_excludedSet=new Set(e.excluded),delete e.excluded),(null===(i=null==e?void 0:e.includedContexts)||void 0===i?void 0:i.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>le&&(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>le&&(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 ae.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 ae.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ae.AttributeReference.InvalidReference)})})}function pe(e){try{return JSON.parse(e)}catch(e){return}}function ve(e){const t=e;return Object.values((null==t?void 0:t.flags)||[]).forEach(e=>{he(e)}),Object.values((null==t?void 0:t.segments)||[]).forEach(e=>{fe(e)}),t}ie.nullReplacer=ce,ie.replacer=ue,ie.processFlag=he,ie.processSegment=fe,ie.reviveFullPayload=ve,ie.deserializeAll=function(e){const t=pe(e);if(t)return ve(null==t?void 0:t.data),t},ie.deserializePoll=function(e){const t=pe(e);if(t)return ve(t),t},ie.deserializePatch=function(e){const t=pe(e);if(t)return t.path.startsWith(oe.default.Features.streamApiPath)?(he(t.data),t.kind=oe.default.Features):t.path.startsWith(oe.default.Segments.streamApiPath)&&(fe(t.data),t.kind=oe.default.Segments),t},ie.deserializeDelete=function(e){const t=pe(e);if(t)return t.path.startsWith(oe.default.Features.streamApiPath)?t.kind=oe.default.Features:t.path.startsWith(oe.default.Segments.streamApiPath)&&(t.kind=oe.default.Segments),t},ie.serializeFlag=function(e){return JSON.stringify(e,ue)},ie.deserializeFlag=function(e){const t=pe(e);if(t)return he(t),t},ie.serializeSegment=function(e){return JSON.stringify(e,ue)},ie.deserializeSegment=function(e){const t=pe(e);if(t)return fe(t),t},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createStreamListeners=e.createDeleteListener=e.createPatchListener=e.createPutListener=void 0;const t=a,r=ie,i=ne,{initMetadataFromHeaders:n}=t.internal;e.createPutListener=(e,t,s=()=>{})=>({deserializeData:r.deserializeAll,processJson:async({data:{flags:r,segments:a}},o)=>{const l={[i.default.Features.namespace]:r,[i.default.Segments.namespace]:a};null==t||t.debug("Initializing all data"),e.init(l,s,n(o))}});e.createPatchListener=(e,t,n=()=>{})=>({deserializeData:r.deserializePatch,processJson:async({data:r,kind:s,path:a})=>{if(s){const o=i.default.getKeyFromPath(s,a);o&&(null==t||t.debug(`Updating ${o} in ${s.namespace}`),e.upsert(s,r,n))}}});e.createDeleteListener=(e,t,n=()=>{})=>({deserializeData:r.deserializeDelete,processJson:async({kind:r,path:s,version:a})=>{if(r){const o=i.default.getKeyFromPath(r,s);o&&(null==t||t.debug(`Deleting ${o} in ${r.namespace}`),e.upsert(r,{key:o,version:a,deleted:!0},n))}}});e.createStreamListeners=(t,r,i)=>{const n=new Map;return n.set("put",(0,e.createPutListener)(t,r,null==i?void 0:i.put)),n.set("patch",(0,e.createPatchListener)(t,r,null==i?void 0:i.patch)),n.set("delete",(0,e.createDeleteListener)(t,r,null==i?void 0:i.delete)),n}}(re);var ge={},_e={},me={};Object.defineProperty(me,"__esModule",{value:!0});me.default=class{constructor(){this._itemsByNamespace={}}get(e,t){var r;return null===(r=this._itemsByNamespace[e])||void 0===r?void 0:r[t]}set(e,t,r){e in this._itemsByNamespace||(this._itemsByNamespace[e]={}),this._itemsByNamespace[e][t]=r}remove(e,t){const r=this._itemsByNamespace[e];r&&delete r[t]}removeAll(){this._itemsByNamespace={}}enumerate(e){Object.entries(this._itemsByNamespace).forEach(([t,r])=>{Object.entries(r).forEach(([r,i])=>{e(t,r,i)})})}mergeFrom(e){e.enumerate(this.set.bind(this))}},Object.defineProperty(_e,"__esModule",{value:!0});const ye=me;_e.default=class{constructor(){this._dependenciesFrom=new ye.default,this._dependenciesTo=new ye.default}updateDependenciesFrom(e,t,r){const i=this._dependenciesFrom.get(e,t);null==i||i.enumerate((r,i)=>{const n=this._dependenciesTo.get(r,i);null==n||n.remove(e,t)}),this._dependenciesFrom.set(e,t,r),null==r||r.enumerate((r,i)=>{let n=this._dependenciesTo.get(r,i);n||(n=new ye.default,this._dependenciesTo.set(r,i,n)),n.set(e,t,!0)})}updateModifiedItems(e,t,r){if(!e.get(t,r)){e.set(t,r,!0);const i=this._dependenciesTo.get(t,r);null==i||i.enumerate((t,r)=>{this.updateModifiedItems(e,t,r)})}}reset(){this._dependenciesFrom.removeAll(),this._dependenciesTo.removeAll()}},Object.defineProperty(ge,"__esModule",{value:!0}),ge.computeDependencies=void 0;const be=ne,Ee=_e,Se=me;function we(e,t){var r,i;const n=new Se.default,s=e===be.default.Features.namespace,a=e===be.default.Segments.namespace;if(s){const i=t;null===(r=null==i?void 0:i.prerequisites)||void 0===r||r.forEach(t=>{n.set(e,t.key,!0)})}if(s||a){const e=t;null===(i=null==e?void 0:e.rules)||void 0===i||i.forEach(e=>{var t;null===(t=e.clauses)||void 0===t||t.forEach(e=>{"segmentMatch"===e.op&&e.values.forEach(e=>{n.set(be.default.Segments.namespace,e,!0)})})})}return n}ge.computeDependencies=we;ge.default=class{constructor(e,t,r){this._featureStore=e,this._hasEventListeners=t,this._onChange=r,this._dependencyTracker=new Ee.default}init(e,t,r){const i=this._hasEventListeners(),n=n=>{this._featureStore.init(e,()=>{Promise.resolve().then(()=>{if(this._dependencyTracker.reset(),Object.entries(e).forEach(([e,t])=>{Object.keys(t||{}).forEach(r=>{const i=t[r];this._dependencyTracker.updateDependenciesFrom(e,r,we(e,i))})}),i){const t=new Se.default;Object.keys(e).forEach(r=>{const i=(null==n?void 0:n[r])||{},s=e[r],a=Object.assign(Object.assign({},i),s);Object.keys(a).forEach(e=>{this.addIfModified(r,e,i&&i[e],s&&s[e],t)})}),this.sendChangeEvents(t)}}),null==t||t()},r)};i?this._featureStore.all(be.default.Features,e=>{this._featureStore.all(be.default.Segments,t=>{const r={[be.default.Features.namespace]:e,[be.default.Segments.namespace]:t};n(r)})}):n()}upsert(e,t,r){const{key:i}=t,n=this._hasEventListeners(),s=s=>{this._featureStore.upsert(e,t,()=>{Promise.resolve().then(()=>{if(this._dependencyTracker.updateDependenciesFrom(e.namespace,i,we(e.namespace,t)),n){const r=new Se.default;this.addIfModified(e.namespace,i,s,t,r),this.sendChangeEvents(r)}}),null==r||r()})};n?this._featureStore.get(e,i,s):s()}addIfModified(e,t,r,i,n){i&&r&&i.version<=r.version||this._dependencyTracker.updateModifiedItems(n,e,t)}sendChangeEvents(e){e.enumerate((e,t)=>{e===be.default.Features.namespace&&this._onChange(t)})}};var Oe={},ke={};Object.defineProperty(ke,"__esModule",{value:!0});ke.default=class{constructor(e,t,r,i){this._filesystem=e,this._paths=t,this._watch=r,this._callback=i,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 r=await this._filesystem.getFileTimestamp(t);if(r===this._fileTimestamps[t])return;this._fileTimestamps[t]=r;const i=await this._filesystem.readFile(t);this._fileData[t]=i,this._debounceCallback()});this._watchers.push(t)})}close(){this._watchers.forEach(e=>e.close())}_debounceCallback(){this._debounceHandle||(this._debounceHandle=e=>{e()})}};var De={};Object.defineProperty(De,"__esModule",{value:!0}),De.makeFlagWithValue=void 0;const Pe=ie,Te=ne,Ie=ke;function xe(e,t,r){return{key:e,on:!0,fallthrough:{variation:0},variations:[t],version:r}}De.makeFlagWithValue=xe;De.default=class{constructor(e,t,r,i=()=>{},n){var s;this._featureStore=r,this._initSuccessHandler=i,this._errorHandler=n,this._allData={},this._fileLoader=new Ie.default(t,e.paths,null!==(s=e.autoUpdate)&&void 0!==s&&s,e=>{var t,r;try{this._processFileData(e)}catch(e){null===(t=this._errorHandler)||void 0===t||t.call(this,e),null===(r=this._logger)||void 0===r||r.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 r;if(e.path.endsWith(".yml")||e.path.endsWith(".yaml")){if(!this._yamlParser)throw new Error(`Attempted to parse yaml file (${e.path}) without parser.`);r=this._yamlParser(e.data)}else r=JSON.parse(e.data);this._processParsedData(r,t)}),this._featureStore.init(this._allData,()=>{this._initSuccessHandler(),this._initSuccessHandler=()=>{}})}_processParsedData(e,t){Object.keys(e.flags||{}).forEach(t=>{(0,Pe.processFlag)(e.flags[t]),this._addItem(Te.default.Features,e.flags[t])}),Object.keys(e.flagValues||{}).forEach(r=>{var i,n;const s=null===(i=t[Te.default.Features.namespace])||void 0===i?void 0:i[r];let{version:a}=null!=s?s:{version:1};s&&JSON.stringify(e.flagValues[r])!==JSON.stringify(null===(n=null==s?void 0:s.variations)||void 0===n?void 0:n[0])&&(a+=1);const o=xe(r,e.flagValues[r],a);(0,Pe.processFlag)(o),this._addItem(Te.default.Features,o)}),Object.keys(e.segments||{}).forEach(t=>{(0,Pe.processSegment)(e.segments[t]),this._addItem(Te.default.Segments,e.segments[t])})}},Object.defineProperty(Oe,"__esModule",{value:!0});const Re=a,Me=ie,Ae=ke,Fe=De;Oe.default=class{constructor(e,t,r){this._validateInputs(e,t),this._paths=e.paths,this._logger=r,this._filesystem=t.fileSystem,this._yamlParser=e.yamlParser}_validateInputs(e,t){if(!e.paths||0===e.paths.length)throw new Error("FileDataInitializerFDv2: paths are required");if(!t.fileSystem)throw new Error("FileDataInitializerFDv2: file system is required")}start(e,t){t(Re.subsystem.DataSourceState.Initializing);const r=Re.internal.initMetadataFromHeaders(void 0),i=new Re.internal.PayloadProcessor({flag:e=>((0,Me.processFlag)(e),e),segment:e=>((0,Me.processSegment)(e),e)},(e,r)=>{t(Re.subsystem.DataSourceState.Interrupted,new Re.LDPollingError(e,r))},this._logger),n=Re.internal.FDv1PayloadAdaptor(i);this._fileLoader=new Ae.default(this._filesystem,this._paths,!1,s=>{var a;try{const a=this._processFileData(s);i.addPayloadListener(t=>{e(!1,{initMetadata:r,payload:t})}),t(Re.subsystem.DataSourceState.Valid),n.processFullTransfer(a),t(Re.subsystem.DataSourceState.Closed)}catch(e){null===(a=this._logger)||void 0===a||a.error("File contained invalid data",e),t(Re.subsystem.DataSourceState.Closed,new Re.LDPollingError(Re.DataSourceErrorKind.InvalidData,"Malformed data in file response"))}}),this._fileLoader.loadAndWatch().catch(e=>{var r;null===(r=this._logger)||void 0===r||r.error("Error loading files",e),t(Re.subsystem.DataSourceState.Closed,new Re.LDPollingError(Re.DataSourceErrorKind.NetworkError,`Failed to load files: ${e instanceof Error?e.message:String(e)}`))})}_processFileData(e){return e.reduce((e,t)=>{var r,i,n;let s;if(t.path.endsWith(".yml")||t.path.endsWith(".yaml")){if(!this._yamlParser)throw new Error(`Attempted to parse yaml file (${t.path}) without parser.`);s=this._yamlParser(t.data)}else s=JSON.parse(t.data);const a={};return Object.entries(null!==(r=s.flagValues)&&void 0!==r?r:{}).forEach(([e,t])=>{a[e]=(0,Fe.makeFlagWithValue)(e,t,1)}),{segments:Object.assign(Object.assign({},e.segments),null!==(i=s.segments)&&void 0!==i?i:{}),flags:Object.assign(Object.assign(Object.assign({},e.flags),null!==(n=s.flags)&&void 0!==n?n:{}),a)}},{segments:{},flags:{}})}stop(){this._fileLoader&&this._fileLoader.close()}};var Ce={};Object.defineProperty(Ce,"__esModule",{value:!0});const Le=a,je=ie;Ce.default=class{constructor(e,t){this._requestor=e,this._logger=t,this._stopped=!1}start(e,t){var r;t(Le.subsystem.DataSourceState.Initializing),null===(r=this._logger)||void 0===r||r.debug("Performing initialization request to LaunchDarkly for feature flag data."),this._requestor.requestAllData((r,i,n,s)=>{var a,o,l;if(this._stopped)return;const c=()=>{var e;const i=null==r?void 0:r.status,n=r?(0,Le.httpErrorMessage)(r,"initializer","falling back to FDv1"):"Response header indicates to fallback to FDv1";null===(e=this._logger)||void 0===e||e.warn(n),t(Le.subsystem.DataSourceState.Closed,new Le.LDFlagDeliveryFallbackError(Le.DataSourceErrorKind.ErrorResponse,n,i))};if(r){if(s)return void c();const{status:e}=r,i=(0,Le.httpErrorMessage)(r,"initializer","initializer does not retry");return null===(a=this._logger)||void 0===a||a.error(i),void t(Le.subsystem.DataSourceState.Closed,new Le.LDPollingError(Le.DataSourceErrorKind.ErrorResponse,i,e))}if(!i)return s?void c():void t(Le.subsystem.DataSourceState.Closed,new Le.LDPollingError(Le.DataSourceErrorKind.InvalidData,"One shot initializer response missing body."));const u=Le.internal.initMetadataFromHeaders(n);try{const r=JSON.parse(i),n=new Le.internal.PayloadProcessor({flag:e=>((0,je.processFlag)(e),e),segment:e=>((0,je.processSegment)(e),e)},(e,r)=>{s?c():t(Le.subsystem.DataSourceState.Interrupted,new Le.LDPollingError(e,r))},this._logger);t(Le.subsystem.DataSourceState.Valid),n.addPayloadListener(t=>{var r;const i={initMetadata:u,payload:t};s&&(i.fallbackToFDv1=!0,null===(r=this._logger)||void 0===r||r.warn("Response header indicates to fallback to FDv1")),e("full"===t.type,i)}),n.processEvents(r.events),t(Le.subsystem.DataSourceState.Closed)}catch(e){if(null===(o=this._logger)||void 0===o||o.error("Response contained invalid data"),null===(l=this._logger)||void 0===l||l.debug(`${e} - Body follows: ${i}`),s)return void c();t(Le.subsystem.DataSourceState.Closed,new Le.LDPollingError(Le.DataSourceErrorKind.InvalidData,"Malformed data in polling response"))}})}stop(){this._stopped=!0}};var Ne={},$e={},Ve={},Ue={};Object.defineProperty(Ue,"__esModule",{value:!0}),Ue.default=function(e){return new Promise(t=>{e(e=>{t(e)})})},Object.defineProperty(Ve,"__esModule",{value:!0});const Ke=Ue;Ve.default=class{constructor(e){this._store=e}async get(e,t){return(0,Ke.default)(r=>{this._store.get(e,t,r)})}async all(e){return(0,Ke.default)(t=>{this._store.all(e,t)})}async init(e,t){return(0,Ke.default)(r=>{this._store.init(e,r,t)})}async delete(e,t,r){return(0,Ke.default)(i=>{this._store.delete(e,t,r,i)})}async upsert(e,t){return(0,Ke.default)(r=>{this._store.upsert(e,t,r)})}async initialized(){return(0,Ke.default)(e=>{this._store.initialized(e)})}close(){this._store.close()}getInitMetadata(){var e,t;return null===(t=(e=this._store).getInitMetaData)||void 0===t?void 0:t.call(e)}};var ze={};Object.defineProperty(ze,"__esModule",{value:!0});const Be=Ue;ze.default=class{constructor(e){this._store=e}async get(e,t){return(0,Be.default)(r=>{this._store.get(e,t,r)})}async all(e){return(0,Be.default)(t=>{this._store.all(e,t)})}async init(e,t){return(0,Be.default)(r=>{this._store.init(e,r,t)})}async delete(e,t,r){return(0,Be.default)(i=>{this._store.delete(e,t,r,i)})}async upsert(e,t){return(0,Be.default)(r=>{this._store.upsert(e,t,r)})}async initialized(){return(0,Be.default)(e=>{this._store.initialized(e)})}async applyChanges(e,t,r,i){return(0,Be.default)(n=>{this._store.applyChanges(e,t,n,r,i)})}close(){this._store.close()}getInitMetadata(){var e,t;return null===(t=(e=this._store).getInitMetaData)||void 0===t?void 0:t.call(e)}};var He={},qe={};function We(e){return Date.now()>e.expiration}Object.defineProperty(qe,"__esModule",{value:!0});qe.default=class{constructor(e){this._options=e,this._storage=new Map,this._checkIntervalHandle=void e.checkInterval}get(e){const t=this._storage.get(e);if(!t||!We(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)=>{We(e)&&this._storage.delete(t)})}get size(){return this._storage.size}};var Ge={};Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.persistentStoreKinds=void 0;const Je=ie,Xe=ne;Ge.persistentStoreKinds={segments:{namespace:Xe.default.Segments.namespace,deserialize:e=>{const t=(0,Je.deserializeSegment)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Je.serializeSegment)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:0},features:{namespace:Xe.default.Features.namespace,deserialize:e=>{const t=(0,Je.deserializeFlag)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Je.serializeFlag)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:1}};var Ye={};Object.defineProperty(Ye,"__esModule",{value:!0});const Ze=Ge;function Qe(e,t){const r=[],i=new Set(Object.keys(t)),n=s=>{if(!i.has(s))return;i.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)}),r.push({key:s,item:e.serialize(a)})};for(;i.size>0;){const e=i.values().next().value;n(e)}return r}Ye.default=function(e){const t=[];return Object.keys(e).forEach(r=>{const i=Ze.persistentStoreKinds[r];t.push({key:i,item:Qe(i,e[r])})}),t.sort((e,t)=>e.key.priority-t.key.priority),t};var et={};Object.defineProperty(et,"__esModule",{value:!0});et.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,null==t||t()})}}},Object.defineProperty(He,"__esModule",{value:!0});const tt=qe,rt=Ge,it=Ye,nt=et;function st(e,t){return`${e.namespace}:${t}`}function at(e){return`$all:${e.namespace}`}const ot="$checkedInit";function lt(e){return!e||e.item.deleted?null:e.item}function ct(e){return{version:e,item:{version:e,deleted:!0}}}function ut(e,t){if(t.deleted||!t.serializedItem)return ct(t.version);const r=e.deserialize(t.serializedItem);return void 0===r?ct(t.version):0===r.version||r.version===t.version||void 0===r.item?r:{version:t.version,item:r.item}}He.default=class{constructor(e,t){this._core=e,this._isInitialized=!1,this._queue=new nt.default,t&&(this._itemCache=new tt.default({ttl:t,checkInterval:600}),this._allItemsCache=new tt.default({ttl:t,checkInterval:600}))}init(e,t){this._queue.enqueue(t=>{this._core.init((0,it.default)(e),()=>{this._isInitialized=!0,this._itemCache&&(this._itemCache.clear(),this._allItemsCache.clear(),Object.keys(e).forEach(t=>{const r=rt.persistentStoreKinds[t],i=e[t];this._allItemsCache.set(at(r),i),Object.keys(i).forEach(e=>{const t=i[e],n={version:t.version,item:t};this._itemCache.set(st(r,e),n)})})),t()})},t)}get(e,t,r){if(this._itemCache){const i=this._itemCache.get(st(e,t));if(i)return void r(lt(i))}const i=rt.persistentStoreKinds[e.namespace];this._core.get(i,t,n=>{var s;if(n&&n.serializedItem){const a=ut(i,n);return null===(s=this._itemCache)||void 0===s||s.set(st(e,t),a),void r(lt(a))}r(null)})}initialized(e){var t;this._isInitialized?e(!0):(null===(t=this._itemCache)||void 0===t?void 0:t.get(ot))?e(!1):this._core.initialized(t=>{var r;this._isInitialized=t,this._isInitialized||null===(r=this._itemCache)||void 0===r||r.set(ot,!0),e(this._isInitialized)})}all(e,t){var r;const i=null===(r=this._allItemsCache)||void 0===r?void 0:r.get(at(e));if(i)return void t(i);const n=rt.persistentStoreKinds[e.namespace];this._core.getAll(n,r=>{var i;if(!r)return void t({});const s={};r.forEach(({key:e,item:t})=>{const r=lt(ut(n,t));r&&(s[e]=r)}),null===(i=this._allItemsCache)||void 0===i||i.set(at(e),s),t(s)})}upsert(e,t,r){this._queue.enqueue(r=>{this._allItemsCache&&this._allItemsCache.clear();const i=rt.persistentStoreKinds[e.namespace];this._core.upsert(i,t.key,i.serialize(t),(n,s)=>{var a,o;if(!n&&s)if(s.serializedItem){const r=ut(i,s);null===(a=this._itemCache)||void 0===a||a.set(st(e,t.key),r)}else s.deleted&&(null===(o=this._itemCache)||void 0===o||o.set(t.key,{key:t.key,version:s.version,deleted:!0}));r()})},r)}delete(e,t,r,i){this.upsert(e,{key:t,version:r,deleted:!0},i)}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()}};var dt={},ht={};Object.defineProperty(ht,"__esModule",{value:!0});ht.default=class{constructor(){this._allData={},this._initCalled=!1}get(e,t,r){const i=this._allData[e.namespace];if(i&&Object.prototype.hasOwnProperty.call(i,t)){const e=i[t];if(e&&!e.deleted)return null==r?void 0:r(e)}return null==r?void 0:r(null)}all(e,t){var r;const i={},n=null!==(r=this._allData[e.namespace])&&void 0!==r?r:{};Object.entries(n).forEach(([e,t])=>{t&&!t.deleted&&(i[e]=t)}),null==t||t(i)}init(e,t,r){this.applyChanges(!0,e,t,r)}delete(e,t,r,i){const n={key:t,version:r,deleted:!0};this.applyChanges(!1,{[e.namespace]:{[t]:n}},i)}upsert(e,t,r){this.applyChanges(!1,{[e.namespace]:{[t.key]:t}},r)}applyChanges(e,t,r,i,n){if(e)this._initCalled=!0,this._allData=t,this._initMetadata=i;else{const e={};Object.entries(this._allData).forEach(([t,r])=>{e[t]=Object.assign({},r)}),Object.entries(t).forEach(([t,r])=>{Object.keys(r||{}).forEach(i=>{let n=e[t];n||(n={},e[t]=n);const s=r[i];if(Object.hasOwnProperty.call(n,i)){const e=n[i];(!e||e.version<s.version)&&(n[i]=Object.assign({key:i},s))}else n[i]=Object.assign({key:i},s)})}),this._allData=e}this._selector=n,null==r||r()}initialized(e){return null==e?void 0:e(this._initCalled)}close(){}getDescription(){return"memory"}getInitMetaData(){return this._initMetadata}getSelector(){return this._selector}},Object.defineProperty(dt,"__esModule",{value:!0});const ft=ht;dt.default=class{constructor(e){this._nonTransPersistenceStore=e,this._activeStore=this._nonTransPersistenceStore,this._memoryStore=new ft.default}get(e,t,r){this._activeStore.get(e,t,r)}all(e,t){this._activeStore.all(e,t)}init(e,t){this.applyChanges(!0,e,t)}delete(e,t,r,i){const n={key:t,version:r,deleted:!0};this.applyChanges(!1,{[e.namespace]:{[t]:n}},i)}upsert(e,t,r){this.applyChanges(!1,{[e.namespace]:{[t.key]:t}},r)}applyChanges(e,t,r,i,n){this._memoryStore.applyChanges(e,t,()=>{if(e)this._activeStore=this._memoryStore,this._nonTransPersistenceStore.init(t,r);else{const e=[];Object.entries(t).forEach(([t,r])=>{Object.keys(r||{}).forEach(i=>{e.push({dataKind:{namespace:t},item:Object.assign({key:i},r[i])})})}),e.reduce((e,t)=>e.then(()=>new Promise(e=>{this._nonTransPersistenceStore.upsert(t.dataKind,t.item,e)})),Promise.resolve()).then(r)}},i,n)}initialized(e){this._activeStore.initialized(e)}close(){this._nonTransPersistenceStore.close(),this._memoryStore.close()}getDescription(){return"transactional persistent store"}getInitMetaData(){var e,t;return null===(t=(e=this._memoryStore).getInitMetaData)||void 0===t?void 0:t.call(e)}getSelector(){var e,t;return null===(t=(e=this._memoryStore).getSelector)||void 0===t?void 0:t.call(e)}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.reviveFullPayload=e.deserializePoll=e.TransactionalFeatureStore=e.PersistentDataStoreWrapper=e.AsyncTransactionalStoreFacade=e.AsyncStoreFacade=void 0;const t=Ve;e.AsyncStoreFacade=t.default;const r=ze;e.AsyncTransactionalStoreFacade=r.default;const i=He;e.PersistentDataStoreWrapper=i.default;const n=ie;Object.defineProperty(e,"deserializePoll",{enumerable:!0,get:function(){return n.deserializePoll}}),Object.defineProperty(e,"reviveFullPayload",{enumerable:!0,get:function(){return n.reviveFullPayload}});const s=dt;e.TransactionalFeatureStore=s.default}($e),Object.defineProperty(Ne,"__esModule",{value:!0});const pt=a,vt=$e,gt=ne,{initMetadataFromHeaders:_t}=pt.internal;Ne.default=class{constructor(e,t,r,i,n=()=>{},s){this._requestor=e,this._pollInterval=t,this._featureStore=r,this._logger=i,this._initSuccessHandler=n,this._errorHandler=s,this._stopped=!1}_poll(){var e;if(this._stopped)return;const t=e=>{var t,r,i;null===(t=this._logger)||void 0===t||t.error("Polling received invalid data"),null===(r=this._logger)||void 0===r||r.debug(`Invalid JSON follows: ${e}`),null===(i=this._errorHandler)||void 0===i||i.call(this,new pt.LDPollingError(pt.DataSourceErrorKind.InvalidData,"Malformed JSON data in polling response"))},r=Date.now();null===(e=this._logger)||void 0===e||e.debug("Polling LaunchDarkly for feature flag updates"),this._requestor.requestAllData((e,i,n)=>{var s,a,o,l;const c=Date.now()-r,u=Math.max(1e3*this._pollInterval-c,0);if(null===(s=this._logger)||void 0===s||s.debug("Elapsed: %d ms, sleeping for %d ms",c,u),e){const{status:t}=e;if(t&&!(0,pt.isHttpRecoverable)(t)){const r=(0,pt.httpErrorMessage)(e,"polling request");return null===(a=this._logger)||void 0===a||a.error(r),void(null===(o=this._errorHandler)||void 0===o||o.call(this,new pt.LDPollingError(pt.DataSourceErrorKind.ErrorResponse,r,t)))}null===(l=this._logger)||void 0===l||l.warn((0,pt.httpErrorMessage)(e,"polling request","will retry"))}else if(i){const e=(0,vt.deserializePoll)(i);if(e){const t={[gt.default.Features.namespace]:e.flags,[gt.default.Segments.namespace]:e.segments};return void this._featureStore.init(t,()=>{this._initSuccessHandler(),this._timeoutHandle=e=>{e()}},_t(n))}t(i)}this._timeoutHandle=e=>{e()}})}start(){this._poll()}stop(){this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this._stopped=!0}close(){this.stop()}};var mt={};Object.defineProperty(mt,"__esModule",{value:!0});const yt=a,bt=ie;mt.default=class{constructor(e,t=30,r,i=!1){this._requestor=e,this._pollInterval=t,this._logger=r,this._processResponseAsFDv1=i,this._stopped=!1}_poll(e,t,r){var i;if(this._stopped)return;const n=Date.now();var s;null===(i=this._logger)||void 0===i||i.debug("Polling LaunchDarkly for feature flag updates"),this._requestor.requestAllData((r,i,s,a)=>{var o,l,c,u,d,h;if(this._stopped)return;const f=Date.now()-n,p=Math.max(1e3*this._pollInterval-f,0),v=()=>{var e;const i=r instanceof yt.LDFlagDeliveryFallbackError?r:new yt.LDFlagDeliveryFallbackError(yt.DataSourceErrorKind.ErrorResponse,r?(0,yt.httpErrorMessage)(r,"polling request","falling back to FDv1"):"Response header indicates to fallback to FDv1",null==r?void 0:r.status);null===(e=this._logger)||void 0===e||e.warn(i.message),t(yt.subsystem.DataSourceState.Closed,i)};if(null===(o=this._logger)||void 0===o||o.debug("Elapsed: %d ms, sleeping for %d ms",f,p),r){if(a||r instanceof yt.LDFlagDeliveryFallbackError)return void v();const{status:e}=r;if(e&&!(0,yt.isHttpRecoverable)(e)){const i=(0,yt.httpErrorMessage)(r,"polling request");return null===(l=this._logger)||void 0===l||l.error(i),void t(yt.subsystem.DataSourceState.Closed,new yt.LDPollingError(yt.DataSourceErrorKind.ErrorResponse,i,e,!1))}const i=(0,yt.httpErrorMessage)(r,"polling request","will retry");return t(yt.subsystem.DataSourceState.Interrupted,new yt.LDPollingError(yt.DataSourceErrorKind.ErrorResponse,i,e)),null===(c=this._logger)||void 0===c||c.warn(i),void(this._timeoutHandle=e=>{e()})}const g=yt.internal.initMetadataFromHeaders(s);if(i)try{const r=new yt.internal.PayloadProcessor({flag:e=>((0,bt.processFlag)(e),e),segment:e=>((0,bt.processSegment)(e),e)},(e,r)=>{a?v():t(yt.subsystem.DataSourceState.Interrupted,new yt.LDPollingError(e,r))},this._logger);if(r.addPayloadListener(t=>{var r;const i={initMetadata:g,payload:t};a&&(i.fallbackToFDv1=!0,null===(r=this._logger)||void 0===r||r.warn("Response header indicates to fallback to FDv1")),e("full"===t.type,i)}),null===(u=this._logger)||void 0===u||u.debug(`Got body: ${i}`),this._processResponseAsFDv1){!function(e,t){yt.internal.FDv1PayloadAdaptor(e).useSelector("FDv1Fallback").processFullTransfer(t)}(r,JSON.parse(i))}else{const e=JSON.parse(i);r.processEvents(e.events)}if(a)return;t(yt.subsystem.DataSourceState.Valid)}catch(e){if(null===(d=this._logger)||void 0===d||d.error("Response contained invalid data"),null===(h=this._logger)||void 0===h||h.debug(`${r} - Body follows: ${i}`),a)return void v();t(yt.subsystem.DataSourceState.Interrupted,new yt.LDPollingError(yt.DataSourceErrorKind.InvalidData,"Malformed data in polling response"))}else if(a)return void v();this._timeoutHandle=e=>{e()}},(s=null==r?void 0:r())?[{key:"basis",value:s}]:[])}start(e,t,r){this._statusCallback=t,t(yt.subsystem.DataSourceState.Initializing),this._poll(e,t,r)}stop(){var e;this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),null===(e=this._statusCallback)||void 0===e||e.call(this,yt.subsystem.DataSourceState.Closed),this._stopped=!0,this._statusCallback=void 0}};var Et={};Object.defineProperty(Et,"__esModule",{value:!0});const St=a;Et.default=class{constructor(e,t,r,i="/sdk/latest-all",n,s){this._requests=t,this._path=i,this._logger=n,this._eTagCache={},this._headers=Object.assign({},r),this._serviceEndpoints=null!=s?s:e.serviceEndpoints,this._timeoutMs=1e3*e.timeout}async _requestWithETagCache(e,t){const r=this._eTagCache[e],i=null==r?void 0:r.etag,n=i?Object.assign(Object.assign({},t),{headers:Object.assign(Object.assign({},t.headers),{"if-none-match":i})}):t,s=await this._requests.fetch(e,n);if(304===s.status&&r)return{res:s,body:r.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,t=[]){var r,i;const n={method:"GET",headers:this._headers,timeout:this._timeoutMs},s=(0,St.getPollingUri)(this._serviceEndpoints,this._path,t);null===(r=this._logger)||void 0===r||r.debug(`Requestor making request to uri: ${s}`);try{const{res:t,body:r}=await this._requestWithETagCache(s,n);null===(i=this._logger)||void 0===i||i.debug(`Requestor got (possibly cached) body: ${JSON.stringify(r)}`);const a="true"===t.headers.get("x-ld-fd-fallback"),o=Object.fromEntries(t.headers.entries());if(200!==t.status&&304!==t.status){return e(a?new St.LDFlagDeliveryFallbackError(St.DataSourceErrorKind.ErrorResponse,"Response header indicates to fallback to FDv1.",t.status):new St.LDPollingError(St.DataSourceErrorKind.ErrorResponse,`Unexpected status code: ${t.status}`,t.status),void 0,o,a)}return e(void 0,304===t.status?null:r,o,a)}catch(t){return e(t,void 0,void 0,!1)}}};var wt={};Object.defineProperty(wt,"__esModule",{value:!0});const Ot=a;wt.default=class{constructor(e,t,r,i,n,s,a,o=1){this._listeners=i,this._diagnosticsManager=s,this._errorHandler=a,this._streamInitialReconnectDelay=o;const{basicConfiguration:l,platform:c}=e,{logger:u}=l,{requests:d}=c;this._headers=Object.assign({},n),this._logger=u,this._requests=d,this._streamUri=(0,Ot.getStreamingUri)(l.serviceEndpoints,t,r)}_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,r,i;return(0,Ot.shouldRetry)(e)?(null===(i=this._logger)||void 0===i||i.warn((0,Ot.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 Ot.LDStreamingError(Ot.DataSourceErrorKind.ErrorResponse,e.message,e.status)),null===(r=this._logger)||void 0===r||r.error((0,Ot.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=e=>{var t;this._initHeaders=e.headers,null===(t=this._logger)||void 0===t||t.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:r},i)=>{e.addEventListener(i,e=>{var n,s;if(null===(n=this._logger)||void 0===n||n.debug(`Received ${i} event`),null==e?void 0:e.data){this._logConnectionResult(!0);const{data:n}=e,s=t(n);if(!s)return void((e,t,r,i)=>{null==r||r.error(`Stream received invalid data in "${e}" message`),null==r||r.debug(`Invalid JSON follows: ${t}`),null==i||i(new Ot.LDStreamingError(Ot.DataSourceErrorKind.InvalidData,"Malformed JSON data in event stream"))})(i,n,this._logger,this._errorHandler);r(s,this._initHeaders)}else null===(s=this._errorHandler)||void 0===s||s.call(this,new Ot.LDStreamingError(Ot.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 kt={};Object.defineProperty(kt,"__esModule",{value:!0});const Dt=a,Pt=ie;kt.default=class{constructor(e,t,r,i,n,s=1,a){this._streamUriPath=t,this._parameters=r,this._diagnosticsManager=n,this._streamInitialReconnectDelay=s;const{basicConfiguration:o,platform:l}=e,{logger:c,serviceEndpoints:u}=o,{requests:d}=l;this._headers=Object.assign({},i),this._serviceEndpoints=null!=a?a:u,this._logger=c,this._requests=d}_logConnectionAttempt(){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,t){var r,i,n;if("true"===(null===(r=e.headers)||void 0===r?void 0:r["x-ld-fd-fallback"])){const r=new Dt.LDFlagDeliveryFallbackError(Dt.DataSourceErrorKind.ErrorResponse,"Response header indicates to fallback to FDv1",e.status);return t(Dt.subsystem.DataSourceState.Closed,r),!1}return(0,Dt.shouldRetry)(e)?(null===(n=this._logger)||void 0===n||n.warn((0,Dt.httpErrorMessage)(e,"streaming request","will retry")),this._logConnectionResult(!1),this._logConnectionAttempt(),t(Dt.subsystem.DataSourceState.Interrupted),!0):(null===(i=this._logger)||void 0===i||i.error((0,Dt.httpErrorMessage)(e,"streaming request")),this._logConnectionResult(!1),t(Dt.subsystem.DataSourceState.Closed,new Dt.LDStreamingError(Dt.DataSourceErrorKind.ErrorResponse,e.message,e.status,!1)),!1)}start(e,t,r){var i;this._logConnectionAttempt(),t(Dt.subsystem.DataSourceState.Initializing);const n=null==r?void 0:r(),s=n?[...this._parameters,{key:"basis",value:n}]:this._parameters,a=(0,Dt.getStreamingUri)(this._serviceEndpoints,this._streamUriPath,s);null===(i=this._logger)||void 0===i||i.debug(`Streaming processor opening event source to uri: ${a}`);let o=!1;const l=this._requests.createEventSource(a,{headers:this._headers,errorFilter:e=>this._retryAndHandleError(e,t),initialRetryDelayMillis:1e3*this._streamInitialReconnectDelay,readTimeoutMillis:3e5,retryResetIntervalMillis:6e4});this._eventSource=l;const c=new Dt.internal.PayloadStreamReader(l,{flag:e=>((0,Pt.processFlag)(e),e),segment:e=>((0,Pt.processSegment)(e),e)},(e,r)=>{var i;if(o){const e=new Dt.LDFlagDeliveryFallbackError(Dt.DataSourceErrorKind.ErrorResponse,"Response header indicates to fallback to FDv1");null===(i=this._logger)||void 0===i||i.warn(e.message),t(Dt.subsystem.DataSourceState.Closed,e)}else t(Dt.subsystem.DataSourceState.Interrupted,new Dt.LDStreamingError(e,r));this.stop()},this._logger);c.addPayloadListener(t=>{var r;this._logConnectionResult(!0);const i={initMetadata:this._initMetadata,payload:t};o&&(i.fallbackToFDv1=!0,null===(r=this._logger)||void 0===r||r.warn("Response header indicates to fallback to FDv1")),e("full"===t.type,i),o&&this.stop()}),l.onclose=()=>{var e;null===(e=this._logger)||void 0===e||e.info("Closed LaunchDarkly stream connection"),t(Dt.subsystem.DataSourceState.Closed)},l.onerror=()=>{},l.onopen=e=>{var r,i;null===(r=this._logger)||void 0===r||r.info("Opened LaunchDarkly stream connection"),this._initMetadata=Dt.internal.initMetadataFromHeaders(e.headers),"true"===(null===(i=e.headers)||void 0===i?void 0:i["x-ld-fd-fallback"])&&(o=!0),t(Dt.subsystem.DataSourceState.Valid)},l.onretrying=e=>{var t;null===(t=this._logger)||void 0===t||t.info(`Will retry stream connection in ${e.delayMillis} milliseconds`)}}stop(){var e;null===(e=this._eventSource)||void 0===e||e.close(),this._eventSource=void 0}close(){this.stop()}};var Tt={};Object.defineProperty(Tt,"__esModule",{value:!0});const It=ne,xt=ge,Rt=_e,Mt=me;Tt.default=class{constructor(e,t,r){this._featureStore=e,this._hasEventListeners=t,this._onChange=r,this._dependencyTracker=new Rt.default}init(e,t,r){this.applyChanges(!0,e,t,r)}upsert(e,t,r){this.applyChanges(!1,{[e.namespace]:{[t.key]:t}},r)}applyChanges(e,t,r,i,n){const s=this._hasEventListeners();let a={};s&&this._featureStore.all(It.default.Features,e=>{this._featureStore.all(It.default.Segments,t=>{a={[It.default.Features.namespace]:e,[It.default.Segments.namespace]:t}})}),(a=>{this._featureStore.applyChanges(e,t,()=>{Promise.resolve().then(()=>{if(e&&this._dependencyTracker.reset(),Object.entries(t).forEach(([e,t])=>{Object.keys(t||{}).forEach(r=>{const i=t[r];this._dependencyTracker.updateDependenciesFrom(e,r,(0,xt.computeDependencies)(e,i))})}),s){const r=new Mt.default;Object.keys(t).forEach(i=>{const n=a[i],s=t[i];let o;o=e?Object.assign(Object.assign({},n),s):Object.assign({},s),Object.keys(o).forEach(e=>{this.addIfModified(i,e,n&&n[e],s&&s[e],r)})}),this.sendChangeEvents(r)}}),null==r||r()},i,n)})(a)}addIfModified(e,t,r,i,n){i&&r&&i.version<=r.version||this._dependencyTracker.updateModifiedItems(n,e,t)}sendChangeEvents(e){e.enumerate((e,t)=>{e===It.default.Features.namespace&&this._onChange(t)})}};var At={},Ft={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultValues=e.DEFAULT_STREAM_RECONNECT_DELAY=e.DEFAULT_POLL_INTERVAL=void 0;const t=a,r=O,i=ht,n=dt,s={baseUri:t.TypeValidators.String,streamUri:t.TypeValidators.String,eventsUri:t.TypeValidators.String,timeout:t.TypeValidators.numberWithMin(1),capacity:t.TypeValidators.Number,logger:t.TypeValidators.Object,featureStore:t.TypeValidators.ObjectOrFactory,dataSystem:t.TypeValidators.Object,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[]",{}),enableEventCompression:t.TypeValidators.Boolean,dataSourceOptionsType:t.TypeValidators.String};e.DEFAULT_POLL_INTERVAL=30,e.DEFAULT_STREAM_RECONNECT_DELAY=1;const o={dataSourceOptionsType:"standard",streamInitialReconnectDelay:e.DEFAULT_STREAM_RECONNECT_DELAY,pollInterval:e.DEFAULT_POLL_INTERVAL},l={dataSourceOptionsType:"streamingOnly",streamInitialReconnectDelay:e.DEFAULT_STREAM_RECONNECT_DELAY},c={dataSourceOptionsType:"pollingOnly",pollInterval:e.DEFAULT_POLL_INTERVAL},u={dataSource:o};function d(r,i){const n=[],a=Object.assign({},i);return Object.keys(r).forEach(i=>{var o;const l=r[i],c=s[i];if(c)if(c.is(l))a[i]=l;else if("boolean"===c.getType())n.push(t.OptionMessages.wrongOptionTypeBoolean(i,typeof l)),a[i]=!!l;else if(c instanceof t.NumberWithMinimum&&t.TypeValidators.Number.is(l)){const{min:e}=c;n.push(t.OptionMessages.optionBelowMinimum(i,l,e)),a[i]=e}else n.push(t.OptionMessages.wrongOptionType(i,c.getType(),typeof l)),a[i]=e.defaultValues[i];else null===(o=r.logger)||void 0===o||o.warn(t.OptionMessages.unknownOption(i))}),{errors:n,validatedOptions:a}}e.defaultValues={baseUri:"https://sdk.launchdarkly.com",streamUri:"https://stream.launchdarkly.com",eventsUri:t.ServiceEndpoints.DEFAULT_EVENTS,stream:!0,streamInitialReconnectDelay:e.DEFAULT_STREAM_RECONNECT_DELAY,sendEvents:!0,timeout:10,capacity:1e4,flushInterval:5,pollInterval:e.DEFAULT_POLL_INTERVAL,offline:!1,useLdd:!1,allAttributesPrivate:!1,privateAttributes:[],contextKeysCapacity:1e3,contextKeysFlushInterval:300,diagnosticOptOut:!1,diagnosticRecordingInterval:900,featureStore:()=>new i.default,enableEventCompression:!1,dataSystem:u};const h={baseUri:t.TypeValidators.String,pollInterval:t.TypeValidators.numberWithMin(30)};function f(e,r){return Object.prototype.hasOwnProperty.call(e,"baseUri")?(delete r.baseUri,[t.OptionMessages.unknownOption("dataSystem.dataSource.baseUri")]):[]}function p(e){const i=[],n=Object.assign({},e);if(e.persistentStore&&!t.TypeValidators.ObjectOrFactory.is(e.persistentStore)&&(n.persistentStore=void 0,i.push(t.OptionMessages.wrongOptionType("persistentStore","LDFeatureStore",typeof e.persistentStore))),void 0!==e.fdv1Fallback&&null!==e.fdv1Fallback)if(t.TypeValidators.Object.is(e.fdv1Fallback)){const{errors:r,validatedOptions:s}=function(e){const r=[],i={};return Object.keys(e).forEach(n=>{const s=e[n],a=h[n];if(a)if(a.is(s))i[n]=s;else if(a instanceof t.NumberWithMinimum&&t.TypeValidators.Number.is(s)){const{min:e}=a;r.push(t.OptionMessages.optionBelowMinimum(`dataSystem.fdv1Fallback.${n}`,s,e)),i[n]=e}else r.push(t.OptionMessages.wrongOptionType(`dataSystem.fdv1Fallback.${n}`,a.getType(),typeof s));else r.push(t.OptionMessages.unknownOption(`dataSystem.fdv1Fallback.${n}`))}),{errors:r,validatedOptions:i}}(e.fdv1Fallback);n.fdv1Fallback=s,i.push(...r)}else n.fdv1Fallback=void 0,i.push(t.OptionMessages.wrongOptionType("dataSystem.fdv1Fallback","FDv1FallbackConfiguration",typeof e.fdv1Fallback));if(e.dataSource){let s,a;(0,r.isStandardOptions)(e.dataSource)?(({errors:s,validatedOptions:a}=d(e.dataSource,o)),s.push(...f(e.dataSource,a))):(0,r.isStreamingOnlyOptions)(e.dataSource)?(({errors:s,validatedOptions:a}=d(e.dataSource,l)),s.push(...f(e.dataSource,a))):(0,r.isPollingOnlyOptions)(e.dataSource)?(({errors:s,validatedOptions:a}=d(e.dataSource,c)),s.push(...f(e.dataSource,a))):(0,r.isCustomOptions)(e.dataSource)?(a=e.dataSource,s=[]):(a=o,s=[t.OptionMessages.wrongOptionType("dataSource","DataSourceOptions",typeof e.dataSource)]),n.dataSource=a,i.push(...s)}else n.dataSource=o;return{errors:i,validatedOptions:n}}e.default=class{constructor(r={},s={}){var a;r=r||{},this.logger=r.logger;const{errors:o,validatedOptions:l}=d(r,e.defaultValues),c=l;if(o.forEach(e=>{var t;null===(t=this.logger)||void 0===t||t.warn(e)}),function(e,r){var i,n,s;const{baseUri:a,streamUri:o,eventsUri:l}=e,c=null!=o,u=null!=a,d=null!=l;c===u&&c===d||(!c&&r.stream&&(null===(i=r.logger)||void 0===i||i.warn(t.OptionMessages.partialEndpoint("streamUri"))),u||null===(n=r.logger)||void 0===n||n.warn(t.OptionMessages.partialEndpoint("baseUri")),!d&&r.sendEvents&&(null===(s=r.logger)||void 0===s||s.warn(t.OptionMessages.partialEndpoint("eventsUri"))))}(r,c),r.dataSystem){const{errors:e,validatedOptions:s}=p(r.dataSystem),a=s;this.dataSystem={dataSource:a.dataSource,useLdd:a.useLdd,fdv1Fallback:a.fdv1Fallback,featureStoreFactory:e=>{const{persistentStore:r}=a;let s;return s=void 0===r?new i.default:t.TypeValidators.Function.is(r)?r(e):r,t.TypeValidators.Function.is(s.applyChanges)?s:new n.default(s)}},e.forEach(e=>{var t;null===(t=this.logger)||void 0===t||t.warn(e)})}this.serviceEndpoints=new t.ServiceEndpoints(c.streamUri,c.baseUri,c.eventsUri,s.analyticsEventPath,s.diagnosticEventPath,s.includeAuthorizationHeader,c.payloadFilterKey),this.eventsCapacity=c.capacity,this.timeout=c.timeout,this.bigSegments=c.bigSegments,this.flushInterval=c.flushInterval,this.pollInterval=c.pollInterval,this.proxyOptions=c.proxyOptions,this.offline=c.offline,this.stream=c.stream,this.streamInitialReconnectDelay=c.streamInitialReconnectDelay,this.useLdd=c.useLdd,this.sendEvents=c.sendEvents,this.allAttributesPrivate=c.allAttributesPrivate,this.privateAttributes=c.privateAttributes,this.contextKeysCapacity=c.contextKeysCapacity,this.contextKeysFlushInterval=c.contextKeysFlushInterval,this.tlsParams=c.tlsParams,this.diagnosticOptOut=c.diagnosticOptOut,this.wrapperName=c.wrapperName,this.payloadFilterKey=c.payloadFilterKey,this.wrapperVersion=c.wrapperVersion,this.tags=new t.ApplicationTags(c),this.diagnosticRecordingInterval=c.diagnosticRecordingInterval,t.TypeValidators.Function.is(c.updateProcessor)?this.updateProcessorFactory=c.updateProcessor:this.updateProcessorFactory=()=>c.updateProcessor,t.TypeValidators.Function.is(c.featureStore)?this.featureStoreFactory=c.featureStore:this.featureStoreFactory=()=>c.featureStore,this.hooks=c.hooks,this.enableEventCompression=c.enableEventCompression,this.getImplementationHooks=null!==(a=s.getImplementationHooks)&&void 0!==a?a:()=>[],this.applicationInfo=c.application}}}(Ft),Object.defineProperty(At,"__esModule",{value:!0});const Ct=a,Lt=o,jt=Ft;At.default=(e,t,r)=>{var i,n,s,a,o,l,c,u,d,h,f,p;let v,g,_;return(null===(i=e.dataSystem)||void 0===i?void 0:i.dataSource)?((0,Lt.isStandardOptions)(e.dataSystem.dataSource)||(0,Lt.isPollingOnlyOptions)(e.dataSystem.dataSource))&&e.dataSystem.dataSource.pollInterval&&(v=(0,Ct.secondsToMillis)(e.dataSystem.dataSource.pollInterval)):v=(0,Ct.secondsToMillis)(e.pollInterval),(null===(n=e.dataSystem)||void 0===n?void 0:n.dataSource)?((0,Lt.isStandardOptions)(e.dataSystem.dataSource)||(0,Lt.isStreamingOnlyOptions)(e.dataSystem.dataSource))&&e.dataSystem.dataSource.streamInitialReconnectDelay&&(g=(0,Ct.secondsToMillis)(e.dataSystem.dataSource.streamInitialReconnectDelay)):g=(0,Ct.secondsToMillis)(e.streamInitialReconnectDelay),_=(null===(s=e.dataSystem)||void 0===s?void 0:s.dataSource)?(0,Lt.isPollingOnlyOptions)(null===(a=e.dataSystem)||void 0===a?void 0:a.dataSource):!e.stream,Object.assign(Object.assign(Object.assign({customBaseURI:e.serviceEndpoints.polling!==jt.defaultValues.baseUri,customStreamURI:e.serviceEndpoints.streaming!==jt.defaultValues.streamUri,customEventsURI:e.serviceEndpoints.events!==jt.defaultValues.eventsUri,eventsCapacity:e.eventsCapacity,connectTimeoutMillis:(0,Ct.secondsToMillis)(e.timeout),socketTimeoutMillis:(0,Ct.secondsToMillis)(e.timeout),eventsFlushIntervalMillis:(0,Ct.secondsToMillis)(e.flushInterval)},v?{pollingIntervalMillis:v}:null),g?{reconnectTimeMillis:g}:null),{contextKeysFlushIntervalMillis:(0,Ct.secondsToMillis)(e.contextKeysFlushInterval),diagnosticRecordingIntervalMillis:(0,Ct.secondsToMillis)(e.diagnosticRecordingInterval),streamingDisabled:_,usingRelayDaemon:null!==(l=null===(o=e.dataSystem)||void 0===o?void 0:o.useLdd)&&void 0!==l?l:e.useLdd,offline:e.offline,allAttributesPrivate:e.allAttributesPrivate,contextKeysCapacity:e.contextKeysCapacity,usingProxy:!!(null===(u=(c=t.requests).usingProxy)||void 0===u?void 0:u.call(c)),usingProxyAuthenticator:!!(null===(h=(d=t.requests).usingProxyAuth)||void 0===h?void 0:h.call(d)),dataStoreType:null!==(p=null===(f=r.getDescription)||void 0===f?void 0:f.call(r))&&void 0!==p?p:"memory"})};var Nt={};Object.defineProperty(Nt,"__esModule",{value:!0}),Nt.allAsync=Nt.firstSeriesAsync=Nt.allSeriesAsync=Nt.firstResult=void 0,Nt.firstResult=function(e,t){let r;return null==e||e.some((e,i)=>(r=t(e,i),!!r)),r};function $t(e,t,r,i,n){e?i<(null==e?void 0:e.length)?t(e[i],i,s=>{if(r){if(!s)return void n(!1)}else if(s)return void n(!0);e.length>50?Promise.resolve().then(()=>{$t(e,t,r,i+1,n)}):$t(e,t,r,i+1,n)}):n(r):n(!1)}Nt.allSeriesAsync=function(e,t,r){$t(e,t,!0,0,r)},Nt.firstSeriesAsync=function(e,t,r){$t(e,t,!1,0,r)},Nt.allAsync=function(e,t,r){e?Promise.all(null==e?void 0:e.map(e=>new Promise(r=>{t(e,r)}))).then(e=>{r(e.every(e=>e))}):r(!1)};var Vt={},Ut={};Object.defineProperty(Ut,"__esModule",{value:!0});class Kt{static prerequisiteFailed(e){return{kind:"PREREQUISITE_FAILED",prerequisiteKey:e}}static ruleMatch(e,t){return{kind:"RULE_MATCH",ruleId:e,ruleIndex:t}}}Kt.Fallthrough={kind:"FALLTHROUGH"},Kt.Off={kind:"OFF"},Kt.TargetMatch={kind:"TARGET_MATCH"},Ut.default=Kt,Object.defineProperty(Vt,"__esModule",{value:!0});const zt=Ut;class Bt{constructor(e,t,r){this.isError=e,this.detail=t,this.message=r,this.isError=e,this.detail=t,this.message=r}get isOff(){return this.detail.reason.kind===zt.default.Off.kind}setDefault(e){this.detail.value=e}static forError(e,t,r){return new Bt(!0,{value:null!=r?r:null,variationIndex:null,reason:{kind:"ERROR",errorKind:e}},t)}static forSuccess(e,t,r){return new Bt(!1,{value:e,variationIndex:void 0===r?null:r,reason:t})}}Vt.default=Bt;var Ht={},qt={};Object.defineProperty(qt,"__esModule",{value:!0});qt.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,r,i,n="user",s){const a=function(e){return"string"==typeof e?e:Number.isInteger(e)?String(e):null}(e.valueForKind(r,n));if(null===a){return[0,e.kinds.indexOf(n)>=0]}const o=`${s?Number(s):`${t}.${i}`}.${a}`;return[parseInt(this._sha1Hex(o).substring(0,15),16)/0x1000000000000000,!0]}};var Wt={},Gt={};Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.getBucketBy=Gt.getOffVariation=Gt.getVariation=void 0;const Jt=a,Xt=Vt,{ErrorKinds:Yt}=Jt.internal,Zt=new Jt.AttributeReference("key");function Qt(e,t,r){return Jt.TypeValidators.Number.is(t)&&t>=0&&t<e.variations.length?Xt.default.forSuccess(e.variations[t],r,t):Xt.default.forError(Yt.MalformedFlag,"Invalid variation index in flag")}Gt.getVariation=Qt,Gt.getOffVariation=function(e,t){return Jt.TypeValidators.Number.is(e.offVariation)?Qt(e,e.offVariation,t):Xt.default.forSuccess(null,t)},Gt.getBucketBy=function(e,t){var r;return null!==(r=e?void 0:t)&&void 0!==r?r:Zt},Object.defineProperty(Wt,"__esModule",{value:!0});const er=a,tr=Nt,rr=Ut,ir=Gt;function nr(e,t,r){const i=r.key(t.contextKind);if(void 0!==i){if(t.values.indexOf(i)>=0)return(0,ir.getVariation)(e,t.variation,rr.default.TargetMatch)}}Wt.default=function(e,t){var r;return(null===(r=e.contextTargets)||void 0===r?void 0:r.length)?(0,tr.firstResult)(e.contextTargets,r=>{if(!r.contextKind||r.contextKind===er.Context.UserKind){const i=(e.targets||[]).find(e=>e.variation===r.variation);return i?nr(e,i,t):void 0}return nr(e,r,t)}):(0,tr.firstResult)(e.targets,r=>nr(e,r,t))};var sr={};Object.defineProperty(sr,"__esModule",{value:!0}),sr.default=function(e){return`${e.key}.g${e.generation}`};var ar={},or={},lr={exports:{}};var cr={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};var ur="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};!function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:i,MAX_LENGTH:n}=cr,s=ur,a=(t=e.exports={}).re=[],o=t.safeRe=[],l=t.src=[],c=t.t={};let u=0;const d="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",n],[d,i]],f=(e,t,r)=>{const i=(e=>{for(const[t,r]of h)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),n=u++;s(e,n,t),c[e]=n,l[n]=t,a[n]=new RegExp(t,r?"g":void 0),o[n]=new RegExp(i,r?"g":void 0)};f("NUMERICIDENTIFIER","0|[1-9]\\d*"),f("NUMERICIDENTIFIERLOOSE","\\d+"),f("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),f("MAINVERSION",`(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})`),f("MAINVERSIONLOOSE",`(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASEIDENTIFIER",`(?:${l[c.NUMERICIDENTIFIER]}|${l[c.NONNUMERICIDENTIFIER]})`),f("PRERELEASEIDENTIFIERLOOSE",`(?:${l[c.NUMERICIDENTIFIERLOOSE]}|${l[c.NONNUMERICIDENTIFIER]})`),f("PRERELEASE",`(?:-(${l[c.PRERELEASEIDENTIFIER]}(?:\\.${l[c.PRERELEASEIDENTIFIER]})*))`),f("PRERELEASELOOSE",`(?:-?(${l[c.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[c.PRERELEASEIDENTIFIERLOOSE]})*))`),f("BUILDIDENTIFIER",`${d}+`),f("BUILD",`(?:\\+(${l[c.BUILDIDENTIFIER]}(?:\\.${l[c.BUILDIDENTIFIER]})*))`),f("FULLPLAIN",`v?${l[c.MAINVERSION]}${l[c.PRERELEASE]}?${l[c.BUILD]}?`),f("FULL",`^${l[c.FULLPLAIN]}$`),f("LOOSEPLAIN",`[v=\\s]*${l[c.MAINVERSIONLOOSE]}${l[c.PRERELEASELOOSE]}?${l[c.BUILD]}?`),f("LOOSE",`^${l[c.LOOSEPLAIN]}$`),f("GTLT","((?:<|>)?=?)"),f("XRANGEIDENTIFIERLOOSE",`${l[c.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),f("XRANGEIDENTIFIER",`${l[c.NUMERICIDENTIFIER]}|x|X|\\*`),f("XRANGEPLAIN",`[v=\\s]*(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:${l[c.PRERELEASE]})?${l[c.BUILD]}?)?)?`),f("XRANGEPLAINLOOSE",`[v=\\s]*(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:${l[c.PRERELEASELOOSE]})?${l[c.BUILD]}?)?)?`),f("XRANGE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAIN]}$`),f("XRANGELOOSE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAINLOOSE]}$`),f("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),f("COERCERTL",l[c.COERCE],!0),f("LONETILDE","(?:~>?)"),f("TILDETRIM",`(\\s*)${l[c.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",f("TILDE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAIN]}$`),f("TILDELOOSE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAINLOOSE]}$`),f("LONECARET","(?:\\^)"),f("CARETTRIM",`(\\s*)${l[c.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",f("CARET",`^${l[c.LONECARET]}${l[c.XRANGEPLAIN]}$`),f("CARETLOOSE",`^${l[c.LONECARET]}${l[c.XRANGEPLAINLOOSE]}$`),f("COMPARATORLOOSE",`^${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]})$|^$`),f("COMPARATOR",`^${l[c.GTLT]}\\s*(${l[c.FULLPLAIN]})$|^$`),f("COMPARATORTRIM",`(\\s*)${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]}|${l[c.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",f("HYPHENRANGE",`^\\s*(${l[c.XRANGEPLAIN]})\\s+-\\s+(${l[c.XRANGEPLAIN]})\\s*$`),f("HYPHENRANGELOOSE",`^\\s*(${l[c.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[c.XRANGEPLAINLOOSE]})\\s*$`),f("STAR","(<|>)?=?\\s*\\*"),f("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),f("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(lr,lr.exports);var dr=lr.exports;const hr=Object.freeze({loose:!0}),fr=Object.freeze({});var pr=e=>e?"object"!=typeof e?hr:e:fr;const vr=/^[0-9]+$/,gr=(e,t)=>{const r=vr.test(e),i=vr.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};var _r={compareIdentifiers:gr,rcompareIdentifiers:(e,t)=>gr(t,e)};const mr=ur,{MAX_LENGTH:yr,MAX_SAFE_INTEGER:br}=cr,{safeRe:Er,t:Sr}=dr,wr=pr,{compareIdentifiers:Or}=_r;var kr=class e{constructor(t,r){if(r=wr(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>yr)throw new TypeError(`version is longer than ${yr} characters`);mr("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;const i=t.trim().match(r.loose?Er[Sr.LOOSE]:Er[Sr.FULL]);if(!i)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>br||this.major<0)throw new TypeError("Invalid major version");if(this.minor>br||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>br||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<br)return t}return e}):this.prerelease=[],this.build=i[5]?i[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(mr("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if("string"==typeof t&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),Or(this.major,t.major)||Or(this.minor,t.minor)||Or(this.patch,t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{const e=this.prerelease[r],i=t.prerelease[r];if(mr("prerelease compare",r,e,i),void 0===e&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===e)return-1;if(e!==i)return Or(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{const e=this.build[r],i=t.build[r];if(mr("prerelease compare",r,e,i),void 0===e&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===e)return-1;if(e!==i)return Or(e,i)}while(++r)}inc(e,t,r){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(r)?1:0;if(!t&&!1===r)throw new Error("invalid increment argument: identifier is empty");if(0===this.prerelease.length)this.prerelease=[e];else{let i=this.prerelease.length;for(;--i>=0;)"number"==typeof this.prerelease[i]&&(this.prerelease[i]++,i=-2);if(-1===i){if(t===this.prerelease.join(".")&&!1===r)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let i=[t,e];!1===r&&(i=[t]),0===Or(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};const Dr=kr;var Pr=(e,t,r=!1)=>{if(e instanceof Dr)return e;try{return new Dr(e,t)}catch(e){if(!r)return null;throw e}};const Tr=Pr;var Ir=(e,t)=>{const r=Tr(e,t);return r?r.version:null};const xr=Pr;var Rr=(e,t)=>{const r=xr(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};const Mr=kr;var Ar=(e,t,r,i,n)=>{"string"==typeof r&&(n=i,i=r,r=void 0);try{return new Mr(e instanceof Mr?e.version:e,r).inc(t,i,n).version}catch(e){return null}};const Fr=Pr;var Cr=(e,t)=>{const r=Fr(e,null,!0),i=Fr(t,null,!0),n=r.compare(i);if(0===n)return null;const s=n>0,a=s?r:i,o=s?i:r,l=!!a.prerelease.length;if(!!o.prerelease.length&&!l)return o.patch||o.minor?a.patch?"patch":a.minor?"minor":"major":"major";const c=l?"pre":"";return r.major!==i.major?c+"major":r.minor!==i.minor?c+"minor":r.patch!==i.patch?c+"patch":"prerelease"};const Lr=kr;var jr=(e,t)=>new Lr(e,t).major;const Nr=kr;var $r=(e,t)=>new Nr(e,t).minor;const Vr=kr;var Ur=(e,t)=>new Vr(e,t).patch;const Kr=Pr;var zr=(e,t)=>{const r=Kr(e,t);return r&&r.prerelease.length?r.prerelease:null};const Br=kr;var Hr=(e,t,r)=>new Br(e,r).compare(new Br(t,r));const qr=Hr;var Wr=(e,t,r)=>qr(t,e,r);const Gr=Hr;var Jr=(e,t)=>Gr(e,t,!0);const Xr=kr;var Yr=(e,t,r)=>{const i=new Xr(e,r),n=new Xr(t,r);return i.compare(n)||i.compareBuild(n)};const Zr=Yr;var Qr=(e,t)=>e.sort((e,r)=>Zr(e,r,t));const ei=Yr;var ti=(e,t)=>e.sort((e,r)=>ei(r,e,t));const ri=Hr;var ii=(e,t,r)=>ri(e,t,r)>0;const ni=Hr;var si=(e,t,r)=>ni(e,t,r)<0;const ai=Hr;var oi=(e,t,r)=>0===ai(e,t,r);const li=Hr;var ci=(e,t,r)=>0!==li(e,t,r);const ui=Hr;var di=(e,t,r)=>ui(e,t,r)>=0;const hi=Hr;var fi=(e,t,r)=>hi(e,t,r)<=0;const pi=oi,vi=ci,gi=ii,_i=di,mi=si,yi=fi;var bi=(e,t,r,i)=>{switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return pi(e,r,i);case"!=":return vi(e,r,i);case">":return gi(e,r,i);case">=":return _i(e,r,i);case"<":return mi(e,r,i);case"<=":return yi(e,r,i);default:throw new TypeError(`Invalid operator: ${t}`)}};const Ei=kr,Si=Pr,{safeRe:wi,t:Oi}=dr;var ki,Di,Pi,Ti,Ii,xi,Ri,Mi,Ai,Fi,Ci=(e,t)=>{if(e instanceof Ei)return e;if("number"==typeof e&&(e=String(e)),"string"!=typeof e)return null;let r=null;if((t=t||{}).rtl){let t;for(;(t=wi[Oi.COERCERTL].exec(e))&&(!r||r.index+r[0].length!==e.length);)r&&t.index+t[0].length===r.index+r[0].length||(r=t),wi[Oi.COERCERTL].lastIndex=t.index+t[1].length+t[2].length;wi[Oi.COERCERTL].lastIndex=-1}else r=e.match(wi[Oi.COERCE]);return null===r?null:Si(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,t)};function Li(){if(Ti)return Pi;function e(t){var r=this;if(r instanceof e||(r=new e),r.tail=null,r.head=null,r.length=0,t&&"function"==typeof t.forEach)t.forEach(function(e){r.push(e)});else if(arguments.length>0)for(var i=0,n=arguments.length;i<n;i++)r.push(arguments[i]);return r}function t(e,t,r){var i=t===e.head?new n(r,null,t,e):new n(r,t,t.next,e);return null===i.next&&(e.tail=i),null===i.prev&&(e.head=i),e.length++,i}function r(e,t){e.tail=new n(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function i(e,t){e.head=new n(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function n(e,t,r,i){if(!(this instanceof n))return new n(e,t,r,i);this.list=i,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,r?(r.prev=this,this.next=r):this.next=null}Ti=1,Pi=e,e.Node=n,e.create=e,e.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,r=e.prev;return t&&(t.prev=r),r&&(r.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=r),e.list.length--,e.next=null,e.prev=null,e.list=null,t},e.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},e.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},e.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)r(this,arguments[e]);return this.length},e.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)i(this,arguments[e]);return this.length},e.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},e.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},e.prototype.forEach=function(e,t){t=t||this;for(var r=this.head,i=0;null!==r;i++)e.call(t,r.value,i,this),r=r.next},e.prototype.forEachReverse=function(e,t){t=t||this;for(var r=this.tail,i=this.length-1;null!==r;i--)e.call(t,r.value,i,this),r=r.prev},e.prototype.get=function(e){for(var t=0,r=this.head;null!==r&&t<e;t++)r=r.next;if(t===e&&null!==r)return r.value},e.prototype.getReverse=function(e){for(var t=0,r=this.tail;null!==r&&t<e;t++)r=r.prev;if(t===e&&null!==r)return r.value},e.prototype.map=function(t,r){r=r||this;for(var i=new e,n=this.head;null!==n;)i.push(t.call(r,n.value,this)),n=n.next;return i},e.prototype.mapReverse=function(t,r){r=r||this;for(var i=new e,n=this.tail;null!==n;)i.push(t.call(r,n.value,this)),n=n.prev;return i},e.prototype.reduce=function(e,t){var r,i=this.head;if(arguments.length>1)r=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");i=this.head.next,r=this.head.value}for(var n=0;null!==i;n++)r=e(r,i.value,n),i=i.next;return r},e.prototype.reduceReverse=function(e,t){var r,i=this.tail;if(arguments.length>1)r=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");i=this.tail.prev,r=this.tail.value}for(var n=this.length-1;null!==i;n--)r=e(r,i.value,n),i=i.prev;return r},e.prototype.toArray=function(){for(var e=new Array(this.length),t=0,r=this.head;null!==r;t++)e[t]=r.value,r=r.next;return e},e.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,r=this.tail;null!==r;t++)e[t]=r.value,r=r.prev;return e},e.prototype.slice=function(t,r){(r=r||this.length)<0&&(r+=this.length),(t=t||0)<0&&(t+=this.length);var i=new e;if(r<t||r<0)return i;t<0&&(t=0),r>this.length&&(r=this.length);for(var n=0,s=this.head;null!==s&&n<t;n++)s=s.next;for(;null!==s&&n<r;n++,s=s.next)i.push(s.value);return i},e.prototype.sliceReverse=function(t,r){(r=r||this.length)<0&&(r+=this.length),(t=t||0)<0&&(t+=this.length);var i=new e;if(r<t||r<0)return i;t<0&&(t=0),r>this.length&&(r=this.length);for(var n=this.length,s=this.tail;null!==s&&n>r;n--)s=s.prev;for(;null!==s&&n>t;n--,s=s.prev)i.push(s.value);return i},e.prototype.splice=function(e,r,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var n=0,s=this.head;null!==s&&n<e;n++)s=s.next;var a=[];for(n=0;s&&n<r;n++)a.push(s.value),s=this.removeNode(s);null===s&&(s=this.tail),s!==this.head&&s!==this.tail&&(s=s.prev);for(n=0;n<i.length;n++)s=t(this,s,i[n]);return a},e.prototype.reverse=function(){for(var e=this.head,t=this.tail,r=e;null!==r;r=r.prev){var i=r.prev;r.prev=r.next,r.next=i}return this.head=t,this.tail=e,this};try{(Di?ki:(Di=1,ki=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}))(e)}catch(e){}return Pi}function ji(){if(Mi)return Ri;Mi=1;class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof n)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().split(/\s+/).join(" "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter(e=>!p(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&v(e[0])){this.set=[e];break}}this.format()}format(){return this.range=this.set.map(e=>e.join(" ").trim()).join("||").trim(),this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&h)|(this.options.loose&&f))+":"+e,i=r.get(t);if(i)return i;const a=this.options.loose,v=a?o[l.HYPHENRANGELOOSE]:o[l.HYPHENRANGE];e=e.replace(v,P(this.options.includePrerelease)),s("hyphen replace",e),e=e.replace(o[l.COMPARATORTRIM],c),s("comparator trim",e),e=e.replace(o[l.TILDETRIM],u),s("tilde trim",e),e=e.replace(o[l.CARETTRIM],d),s("caret trim",e);let g=e.split(" ").map(e=>_(e,this.options)).join(" ").split(/\s+/).map(e=>D(e,this.options));a&&(g=g.filter(e=>(s("loose invalid filter",e,this.options),!!e.match(o[l.COMPARATORLOOSE])))),s("range list",g);const m=new Map,y=g.map(e=>new n(e,this.options));for(const e of y){if(p(e))return[e];m.set(e.value,e)}m.size>1&&m.has("")&&m.delete("");const b=[...m.values()];return r.set(t,b),b}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(e=>g(e,r)&&t.set.some(t=>g(t,r)&&e.every(e=>t.every(t=>e.intersects(t,r)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new a(e,this.options)}catch(e){return!1}for(let t=0;t<this.set.length;t++)if(T(this.set[t],e,this.options))return!0;return!1}}Ri=e;const t=function(){if(xi)return Ii;xi=1;const e=Li(),t=Symbol("max"),r=Symbol("length"),i=Symbol("lengthCalculator"),n=Symbol("allowStale"),s=Symbol("maxAge"),a=Symbol("dispose"),o=Symbol("noDisposeOnSet"),l=Symbol("lruList"),c=Symbol("cache"),u=Symbol("updateAgeOnGet"),d=()=>1,h=(e,t,r)=>{const i=e[c].get(t);if(i){const t=i.value;if(f(e,t)){if(v(e,i),!e[n])return}else r&&(e[u]&&(i.value.now=Date.now()),e[l].unshiftNode(i));return t.value}},f=(e,t)=>{if(!t||!t.maxAge&&!e[s])return!1;const r=Date.now()-t.now;return t.maxAge?r>t.maxAge:e[s]&&r>e[s]},p=e=>{if(e[r]>e[t])for(let i=e[l].tail;e[r]>e[t]&&null!==i;){const t=i.prev;v(e,i),i=t}},v=(e,t)=>{if(t){const i=t.value;e[a]&&e[a](i.key,i.value),e[r]-=i.length,e[c].delete(i.key),e[l].removeNode(t)}};class g{constructor(e,t,r,i,n){this.key=e,this.value=t,this.length=r,this.now=i,this.maxAge=n||0}}const _=(e,t,r,i)=>{let s=r.value;f(e,s)&&(v(e,r),e[n]||(s=void 0)),s&&t.call(i,s.value,s.key,e)};return Ii=class{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[t]=e.max||1/0;const r=e.length||d;if(this[i]="function"!=typeof r?d:r,this[n]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[s]=e.maxAge||0,this[a]=e.dispose,this[o]=e.noDisposeOnSet||!1,this[u]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[t]=e||1/0,p(this)}get max(){return this[t]}set allowStale(e){this[n]=!!e}get allowStale(){return this[n]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[s]=e,p(this)}get maxAge(){return this[s]}set lengthCalculator(e){"function"!=typeof e&&(e=d),e!==this[i]&&(this[i]=e,this[r]=0,this[l].forEach(e=>{e.length=this[i](e.value,e.key),this[r]+=e.length})),p(this)}get lengthCalculator(){return this[i]}get length(){return this[r]}get itemCount(){return this[l].length}rforEach(e,t){t=t||this;for(let r=this[l].tail;null!==r;){const i=r.prev;_(this,e,r,t),r=i}}forEach(e,t){t=t||this;for(let r=this[l].head;null!==r;){const i=r.next;_(this,e,r,t),r=i}}keys(){return this[l].toArray().map(e=>e.key)}values(){return this[l].toArray().map(e=>e.value)}reset(){this[a]&&this[l]&&this[l].length&&this[l].forEach(e=>this[a](e.key,e.value)),this[c]=new Map,this[l]=new e,this[r]=0}dump(){return this[l].map(e=>!f(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)}).toArray().filter(e=>e)}dumpLru(){return this[l]}set(e,n,u){if((u=u||this[s])&&"number"!=typeof u)throw new TypeError("maxAge must be a number");const d=u?Date.now():0,h=this[i](n,e);if(this[c].has(e)){if(h>this[t])return v(this,this[c].get(e)),!1;const i=this[c].get(e).value;return this[a]&&(this[o]||this[a](e,i.value)),i.now=d,i.maxAge=u,i.value=n,this[r]+=h-i.length,i.length=h,this.get(e),p(this),!0}const f=new g(e,n,h,d,u);return f.length>this[t]?(this[a]&&this[a](e,n),!1):(this[r]+=f.length,this[l].unshift(f),this[c].set(e,this[l].head),p(this),!0)}has(e){if(!this[c].has(e))return!1;const t=this[c].get(e).value;return!f(this,t)}get(e){return h(this,e,!0)}peek(e){return h(this,e,!1)}pop(){const e=this[l].tail;return e?(v(this,e),e.value):null}del(e){v(this,this[c].get(e))}load(e){this.reset();const t=Date.now();for(let r=e.length-1;r>=0;r--){const i=e[r],n=i.e||0;if(0===n)this.set(i.k,i.v);else{const e=n-t;e>0&&this.set(i.k,i.v,e)}}}prune(){this[c].forEach((e,t)=>h(this,t,!1))}},Ii}(),r=new t({max:1e3}),i=pr,n=Ni(),s=ur,a=kr,{safeRe:o,t:l,comparatorTrimReplace:c,tildeTrimReplace:u,caretTrimReplace:d}=dr,{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:f}=cr,p=e=>"<0.0.0-0"===e.value,v=e=>""===e.value,g=(e,t)=>{let r=!0;const i=e.slice();let n=i.pop();for(;r&&i.length;)r=i.every(e=>n.intersects(e,t)),n=i.pop();return r},_=(e,t)=>(s("comp",e,t),e=E(e,t),s("caret",e),e=y(e,t),s("tildes",e),e=w(e,t),s("xrange",e),e=k(e,t),s("stars",e),e),m=e=>!e||"x"===e.toLowerCase()||"*"===e,y=(e,t)=>e.trim().split(/\s+/).map(e=>b(e,t)).join(" "),b=(e,t)=>{const r=t.loose?o[l.TILDELOOSE]:o[l.TILDE];return e.replace(r,(t,r,i,n,a)=>{let o;return s("tilde",e,t,r,i,n,a),m(r)?o="":m(i)?o=`>=${r}.0.0 <${+r+1}.0.0-0`:m(n)?o=`>=${r}.${i}.0 <${r}.${+i+1}.0-0`:a?(s("replaceTilde pr",a),o=`>=${r}.${i}.${n}-${a} <${r}.${+i+1}.0-0`):o=`>=${r}.${i}.${n} <${r}.${+i+1}.0-0`,s("tilde return",o),o})},E=(e,t)=>e.trim().split(/\s+/).map(e=>S(e,t)).join(" "),S=(e,t)=>{s("caret",e,t);const r=t.loose?o[l.CARETLOOSE]:o[l.CARET],i=t.includePrerelease?"-0":"";return e.replace(r,(t,r,n,a,o)=>{let l;return s("caret",e,t,r,n,a,o),m(r)?l="":m(n)?l=`>=${r}.0.0${i} <${+r+1}.0.0-0`:m(a)?l="0"===r?`>=${r}.${n}.0${i} <${r}.${+n+1}.0-0`:`>=${r}.${n}.0${i} <${+r+1}.0.0-0`:o?(s("replaceCaret pr",o),l="0"===r?"0"===n?`>=${r}.${n}.${a}-${o} <${r}.${n}.${+a+1}-0`:`>=${r}.${n}.${a}-${o} <${r}.${+n+1}.0-0`:`>=${r}.${n}.${a}-${o} <${+r+1}.0.0-0`):(s("no pr"),l="0"===r?"0"===n?`>=${r}.${n}.${a}${i} <${r}.${n}.${+a+1}-0`:`>=${r}.${n}.${a}${i} <${r}.${+n+1}.0-0`:`>=${r}.${n}.${a} <${+r+1}.0.0-0`),s("caret return",l),l})},w=(e,t)=>(s("replaceXRanges",e,t),e.split(/\s+/).map(e=>O(e,t)).join(" ")),O=(e,t)=>{e=e.trim();const r=t.loose?o[l.XRANGELOOSE]:o[l.XRANGE];return e.replace(r,(r,i,n,a,o,l)=>{s("xRange",e,r,i,n,a,o,l);const c=m(n),u=c||m(a),d=u||m(o),h=d;return"="===i&&h&&(i=""),l=t.includePrerelease?"-0":"",c?r=">"===i||"<"===i?"<0.0.0-0":"*":i&&h?(u&&(a=0),o=0,">"===i?(i=">=",u?(n=+n+1,a=0,o=0):(a=+a+1,o=0)):"<="===i&&(i="<",u?n=+n+1:a=+a+1),"<"===i&&(l="-0"),r=`${i+n}.${a}.${o}${l}`):u?r=`>=${n}.0.0${l} <${+n+1}.0.0-0`:d&&(r=`>=${n}.${a}.0${l} <${n}.${+a+1}.0-0`),s("xRange return",r),r})},k=(e,t)=>(s("replaceStars",e,t),e.trim().replace(o[l.STAR],"")),D=(e,t)=>(s("replaceGTE0",e,t),e.trim().replace(o[t.includePrerelease?l.GTE0PRE:l.GTE0],"")),P=e=>(t,r,i,n,s,a,o,l,c,u,d,h,f)=>`${r=m(i)?"":m(n)?`>=${i}.0.0${e?"-0":""}`:m(s)?`>=${i}.${n}.0${e?"-0":""}`:a?`>=${r}`:`>=${r}${e?"-0":""}`} ${l=m(c)?"":m(u)?`<${+c+1}.0.0-0`:m(d)?`<${c}.${+u+1}.0-0`:h?`<=${c}.${u}.${d}-${h}`:e?`<${c}.${u}.${+d+1}-0`:`<=${l}`}`.trim(),T=(e,t,r)=>{for(let r=0;r<e.length;r++)if(!e[r].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let r=0;r<e.length;r++)if(s(e[r].semver),e[r].semver!==n.ANY&&e[r].semver.prerelease.length>0){const i=e[r].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0};return Ri}function Ni(){if(Fi)return Ai;Fi=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(i,n){if(n=r(n),i instanceof t){if(i.loose===!!n.loose)return i;i=i.value}i=i.trim().split(/\s+/).join(" "),a("comparator",i,n),this.options=n,this.loose=!!n.loose,this.parse(i),this.semver===e?this.value="":this.value=this.operator+this.semver.version,a("comp",this)}parse(t){const r=this.options.loose?i[n.COMPARATORLOOSE]:i[n.COMPARATOR],s=t.match(r);if(!s)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==s[1]?s[1]:"","="===this.operator&&(this.operator=""),s[2]?this.semver=new o(s[2],this.options.loose):this.semver=e}toString(){return this.value}test(t){if(a("Comparator.test",t,this.options.loose),this.semver===e||t===e)return!0;if("string"==typeof t)try{t=new o(t,this.options)}catch(e){return!1}return s(t,this.operator,this.semver,this.options)}intersects(e,i){if(!(e instanceof t))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new l(e.value,i).test(this.value):""===e.operator?""===e.value||new l(this.value,i).test(e.semver):(!(i=r(i)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!i.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(s(this.semver,"<",e.semver,i)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(s(this.semver,">",e.semver,i)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}Ai=t;const r=pr,{safeRe:i,t:n}=dr,s=bi,a=ur,o=kr,l=ji();return Ai}const $i=ji();var Vi=(e,t,r)=>{try{t=new $i(t,r)}catch(e){return!1}return t.test(e)};const Ui=ji();var Ki=(e,t)=>new Ui(e,t).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" "));const zi=kr,Bi=ji();var Hi=(e,t,r)=>{let i=null,n=null,s=null;try{s=new Bi(t,r)}catch(e){return null}return e.forEach(e=>{s.test(e)&&(i&&-1!==n.compare(e)||(i=e,n=new zi(i,r)))}),i};const qi=kr,Wi=ji();var Gi=(e,t,r)=>{let i=null,n=null,s=null;try{s=new Wi(t,r)}catch(e){return null}return e.forEach(e=>{s.test(e)&&(i&&1!==n.compare(e)||(i=e,n=new qi(i,r)))}),i};const Ji=kr,Xi=ji(),Yi=ii;var Zi=(e,t)=>{e=new Xi(e,t);let r=new Ji("0.0.0");if(e.test(r))return r;if(r=new Ji("0.0.0-0"),e.test(r))return r;r=null;for(let t=0;t<e.set.length;++t){const i=e.set[t];let n=null;i.forEach(e=>{const t=new Ji(e.semver.version);switch(e.operator){case">":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":n&&!Yi(t,n)||(n=t);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}),!n||r&&!Yi(r,n)||(r=n)}return r&&e.test(r)?r:null};const Qi=ji();var en=(e,t)=>{try{return new Qi(e,t).range||"*"}catch(e){return null}};const tn=kr,rn=Ni(),{ANY:nn}=rn,sn=ji(),an=Vi,on=ii,ln=si,cn=fi,un=di;var dn=(e,t,r,i)=>{let n,s,a,o,l;switch(e=new tn(e,i),t=new sn(t,i),r){case">":n=on,s=cn,a=ln,o=">",l=">=";break;case"<":n=ln,s=un,a=on,o="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(an(e,t,i))return!1;for(let r=0;r<t.set.length;++r){const c=t.set[r];let u=null,d=null;if(c.forEach(e=>{e.semver===nn&&(e=new rn(">=0.0.0")),u=u||e,d=d||e,n(e.semver,u.semver,i)?u=e:a(e.semver,d.semver,i)&&(d=e)}),u.operator===o||u.operator===l)return!1;if((!d.operator||d.operator===o)&&s(e,d.semver))return!1;if(d.operator===l&&a(e,d.semver))return!1}return!0};const hn=dn;var fn=(e,t,r)=>hn(e,t,">",r);const pn=dn;var vn=(e,t,r)=>pn(e,t,"<",r);const gn=ji();var _n=(e,t,r)=>(e=new gn(e,r),t=new gn(t,r),e.intersects(t,r));const mn=Vi,yn=Hr;const bn=ji(),En=Ni(),{ANY:Sn}=En,wn=Vi,On=Hr,kn=[new En(">=0.0.0-0")],Dn=[new En(">=0.0.0")],Pn=(e,t,r)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===Sn){if(1===t.length&&t[0].semver===Sn)return!0;e=r.includePrerelease?kn:Dn}if(1===t.length&&t[0].semver===Sn){if(r.includePrerelease)return!0;t=Dn}const i=new Set;let n,s,a,o,l,c,u;for(const t of e)">"===t.operator||">="===t.operator?n=Tn(n,t,r):"<"===t.operator||"<="===t.operator?s=In(s,t,r):i.add(t.semver);if(i.size>1)return null;if(n&&s){if(a=On(n.semver,s.semver,r),a>0)return null;if(0===a&&(">="!==n.operator||"<="!==s.operator))return null}for(const e of i){if(n&&!wn(e,String(n),r))return null;if(s&&!wn(e,String(s),r))return null;for(const i of t)if(!wn(e,String(i),r))return!1;return!0}let d=!(!s||r.includePrerelease||!s.semver.prerelease.length)&&s.semver,h=!(!n||r.includePrerelease||!n.semver.prerelease.length)&&n.semver;d&&1===d.prerelease.length&&"<"===s.operator&&0===d.prerelease[0]&&(d=!1);for(const e of t){if(u=u||">"===e.operator||">="===e.operator,c=c||"<"===e.operator||"<="===e.operator,n)if(h&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===h.major&&e.semver.minor===h.minor&&e.semver.patch===h.patch&&(h=!1),">"===e.operator||">="===e.operator){if(o=Tn(n,e,r),o===e&&o!==n)return!1}else if(">="===n.operator&&!wn(n.semver,String(e),r))return!1;if(s)if(d&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===d.major&&e.semver.minor===d.minor&&e.semver.patch===d.patch&&(d=!1),"<"===e.operator||"<="===e.operator){if(l=In(s,e,r),l===e&&l!==s)return!1}else if("<="===s.operator&&!wn(s.semver,String(e),r))return!1;if(!e.operator&&(s||n)&&0!==a)return!1}return!(n&&c&&!s&&0!==a)&&(!(s&&u&&!n&&0!==a)&&(!h&&!d))},Tn=(e,t,r)=>{if(!e)return t;const i=On(e.semver,t.semver,r);return i>0?e:i<0||">"===t.operator&&">="===e.operator?t:e},In=(e,t,r)=>{if(!e)return t;const i=On(e.semver,t.semver,r);return i<0?e:i>0||"<"===t.operator&&"<="===e.operator?t:e};var xn=(e,t,r={})=>{if(e===t)return!0;e=new bn(e,r),t=new bn(t,r);let i=!1;e:for(const n of e.set){for(const e of t.set){const t=Pn(n,e,r);if(i=i||null!==t,t)continue e}if(i)return!1}return!0};const Rn=dr,Mn=cr,An=kr,Fn=_r,Cn=(e,t,r)=>{const i=[];let n=null,s=null;const a=e.sort((e,t)=>yn(e,t,r));for(const e of a){mn(e,t,r)?(s=e,n||(n=e)):(s&&i.push([n,s]),s=null,n=null)}n&&i.push([n,null]);const o=[];for(const[e,t]of i)e===t?o.push(e):t||e!==a[0]?t?e===a[0]?o.push(`<=${t}`):o.push(`${e} - ${t}`):o.push(`>=${e}`):o.push("*");const l=o.join(" || "),c="string"==typeof t.raw?t.raw:String(t);return l.length<c.length?l:t};var Ln={parse:Pr,valid:Ir,clean:Rr,inc:Ar,diff:Cr,major:jr,minor:$r,patch:Ur,prerelease:zr,compare:Hr,rcompare:Wr,compareLoose:Jr,compareBuild:Yr,sort:Qr,rsort:ti,gt:ii,lt:si,eq:oi,neq:ci,gte:di,lte:fi,cmp:bi,coerce:Ci,Comparator:Ni(),Range:ji(),satisfies:Vi,toComparators:Ki,maxSatisfying:Hi,minSatisfying:Gi,minVersion:Zi,validRange:en,outside:dn,gtr:fn,ltr:vn,intersects:_n,simplifyRange:Cn,subset:xn,SemVer:An,re:Rn.re,src:Rn.src,tokens:Rn.t,SEMVER_SPEC_VERSION:Mn.SEMVER_SPEC_VERSION,RELEASE_TYPES:Mn.RELEASE_TYPES,compareIdentifiers:Fn.compareIdentifiers,rcompareIdentifiers:Fn.rcompareIdentifiers};Object.defineProperty(or,"__esModule",{value:!0});const jn=Ln,Nn=a,$n=/^\d+(\.\d+)?(\.\d+)?/;function Vn(e){if(Nn.TypeValidators.String.is(e)&&!e.startsWith("v")){const t=(0,jn.parse)(e);if(t)return t;const r=$n.exec(e);if(r){let t=r[0];for(let e=1;e<r.length;e+=1)void 0===r[e]&&(t+=".0");return t+=e.substring(r[0].length),(0,jn.parse)(t)}}return null}function Un(e){return(t,r)=>{const i=Vn(t),n=Vn(r);return!!(i&&n&&e(i,n))}}function Kn(e,t,r){return(i,n)=>!(!t.is(i)||!t.is(n))&&(r?e(r(i),r(n)):e(i,n))}function zn(e){return"number"==typeof e?e:Date.parse(e)}const Bn={in:(e,t)=>e===t,endsWith:Kn((e,t)=>e.endsWith(t),Nn.TypeValidators.String),startsWith:Kn((e,t)=>e.startsWith(t),Nn.TypeValidators.String),matches:Kn((e,t)=>function(e,t){try{return new RegExp(e).test(t)}catch(e){return!1}}(t,e),Nn.TypeValidators.String),contains:Kn((e,t)=>e.indexOf(t)>-1,Nn.TypeValidators.String),lessThan:Kn((e,t)=>e<t,Nn.TypeValidators.Number),lessThanOrEqual:Kn((e,t)=>e<=t,Nn.TypeValidators.Number),greaterThan:Kn((e,t)=>e>t,Nn.TypeValidators.Number),greaterThanOrEqual:Kn((e,t)=>e>=t,Nn.TypeValidators.Number),before:Kn((e,t)=>e<t,Nn.TypeValidators.Date,zn),after:Kn((e,t)=>e>t,Nn.TypeValidators.Date,zn),semVerEqual:Un((e,t)=>0===e.compare(t)),semVerLessThan:Un((e,t)=>e.compare(t)<0),semVerGreaterThan:Un((e,t)=>e.compare(t)>0)};or.default=class{static is(e){return Object.prototype.hasOwnProperty.call(Bn,e)}static execute(e,t,r){var i,n;return null!==(n=null===(i=Bn[e])||void 0===i?void 0:i.call(Bn,t,r))&&void 0!==n&&n}},Object.defineProperty(ar,"__esModule",{value:!0}),ar.maybeNegate=void 0;const Hn=or;function qn(e,t){return e.negate?!t:t}function Wn(e,t,r){return r.some(r=>Hn.default.execute(e,t,r))}ar.maybeNegate=qn,ar.default=function(e,t){const r=t.valueForKind(e.attributeReference,e.contextKind);return null!=r&&(Array.isArray(r)?qn(e,r.some(t=>Wn(e.op,t,e.values))):qn(e,Wn(e.op,r,e.values)))};var Gn={};function Jn(e,t,r,i){if(t)for(let r=0;r<t.length;r+=1){const i=t[r],n=e.key(i.contextKind);if(n)if(i.generated_valuesSet){if(i.generated_valuesSet.has(n))return!0}else if(i.values.includes(n))return!0}if(i){const t=e.key("user");if(t&&i.has(t))return!0}else if(r){const t=e.key("user");if(t&&r.includes(t))return!0}return!1}Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.default=function(e,t){if(Jn(t,e.includedContexts,e.included,e.generated_includedSet))return!0;const r=Jn(t,e.excludedContexts,e.excluded,e.generated_excludedSet);return r?!r:void 0},Object.defineProperty(Ht,"__esModule",{value:!0});const Xn=a,Yn=qt,Zn=Nt,Qn=Vt,es=Wt,ts=sr,rs=ar,is=Gn,ns=Ut,ss=Gt,{ErrorKinds:as}=Xn.internal,os={HEALTHY:1,STALE:2,STORE_ERROR:3,NOT_CONFIGURED:4};function ls(e){return void 0!==e&&os[e]||0}function cs(e,t){return void 0!==e&&ls(e)>ls(t)?e:t}function us(e){return{error:!1,isMatch:e,result:void 0}}function ds(e){return{error:!0,isMatch:!1,result:e}}Ht.default=class{constructor(e,t){this._queries=t,this._bucketer=new Yn.default(e.crypto)}async evaluate(e,t,r){return new Promise(i=>{this.evaluateCb(e,t,i,r)})}evaluateCb(e,t,r,i){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,r(e)},!0,i)}_evaluateInternal(e,t,r,i,n,s,a){e.on?this._checkPrerequisites(e,t,r,i,i=>{if(i)return void n(i);const s=(0,es.default)(e,t);s?n(s):this._evaluateRules(e,t,r,r=>{n(r||this._variationForContext(e.fallthrough,t,e,ns.default.Fallthrough))})},s,a):n((0,ss.getOffVariation)(e,ns.default.Off))}_checkPrerequisites(e,t,r,i,n,s,a){let o;e.prerequisites&&e.prerequisites.length?(0,Zn.allSeriesAsync)(e.prerequisites,(n,l,c)=>{if(-1!==i.indexOf(n.key))return o=Qn.default.forError(as.MalformedFlag,`Prerequisite of ${e.key} causing a circular reference. This is probably a temporary condition due to an incomplete update.`),void c(!0);const u=[...i,n.key];this._queries.getFlag(n.key,i=>{if(!i)return o=(0,ss.getOffVariation)(e,ns.default.prerequisiteFailed(n.key)),void c(!1);this._evaluateInternal(i,t,r,u,l=>{var u,d;return null!==(u=r.events)&&void 0!==u||(r.events=[]),s&&(null!==(d=r.prerequisites)&&void 0!==d||(r.prerequisites=[]),r.prerequisites.push(i.key)),a&&r.events.push(a.evalEventServer(i,t,l.detail,null,e)),l.isError?(o=l,c(!1)):l.isOff||l.detail.variationIndex!==n.variation?(o=(0,ss.getOffVariation)(e,ns.default.prerequisiteFailed(n.key)),c(!1)):c(!0)},!1,a)})},()=>{n(o)}):n(void 0)}_evaluateRules(e,t,r,i){let n;(0,Zn.firstSeriesAsync)(e.rules,(i,s,a)=>{this._ruleMatchContext(e,i,s,t,r,[],e=>{n=e,a(!!e)})},()=>i(n))}_clauseMatchContext(e,t,r,i,n){let s;"segmentMatch"!==e.op?e.attributeReference.isValid?n(us((0,rs.default)(e,t))):n(ds(Qn.default.forError(as.MalformedFlag,"Invalid attribute reference in clause"))):(0,Zn.firstSeriesAsync)(e.values,(e,n,a)=>{this._queries.getSegment(e,e=>{if(e){if(r.includes(e.key))return s=Qn.default.forError(as.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=[...r,null==e?void 0:e.key];this.segmentMatchContext(e,t,i,n,e=>{e.error&&(s=e.result),a(e.error||e.isMatch)})}else a(!1)})},t=>n(s?ds(s):us((0,rs.maybeNegate)(e,t))))}_ruleMatchContext(e,t,r,i,n,s,a){if(!t.clauses)return void a(void 0);let o;(0,Zn.allSeriesAsync)(t.clauses,(e,t,r)=>{this._clauseMatchContext(e,i,s,n,e=>(o=e.result,r(e.error||e.isMatch)))},n=>a(o||(n?this._variationForContext(t,i,e,ns.default.ruleMatch(t.id,r)):void 0)))}_variationForContext(e,t,r,i){if(void 0===e)return Qn.default.forError(as.MalformedFlag,"Fallthrough variation undefined");if(void 0!==e.variation)return(0,ss.getVariation)(r,e.variation,i);if(e.rollout){const{rollout:n}=e,{variations:s}=n,a="experiment"===n.kind;if(s&&s.length){const e=(0,ss.getBucketBy)(a,n.bucketByAttributeReference);if(!e.isValid)return Qn.default.forError(as.MalformedFlag,"Invalid attribute reference for bucketBy in rollout");const[o,l]=this._bucketer.bucket(t,r.key,e,r.salt||"",n.contextKind,n.seed),c=Object.assign({},i);let u=0;for(let e=0;e<s.length;e+=1){const t=s[e];if(u+=t.weight/1e5,o<u)return a&&l&&!t.untracked&&(c.inExperiment=!0),(0,ss.getVariation)(r,t.variation,c)}const d=s[s.length-1];return a&&!d.untracked&&(c.inExperiment=!0),(0,ss.getVariation)(r,d.variation,c)}}return Qn.default.forError(as.MalformedFlag,"Variation/rollout object with no variation or rollout")}segmentRuleMatchContext(e,t,r,i,n,s){let a;(0,Zn.allSeriesAsync)(t.clauses,(e,t,s)=>{this._clauseMatchContext(e,r,n,i,e=>{a=e.result,s(e.error||e.isMatch)})},i=>{if(a)return s(ds(a));if(i){if(void 0===t.weight)return s(us(i));const n=(0,ss.getBucketBy)(!1,t.bucketByAttributeReference);if(!n.isValid)return s(ds(Qn.default.forError(as.MalformedFlag,"Invalid attribute reference in clause")));const[a]=this._bucketer.bucket(r,e.key,n,e.salt||"",t.rolloutContextKind);return s(us(a<t.weight/1e5))}return s(us(!1))})}simpleSegmentMatchContext(e,t,r,i,n){if(!e.unbounded){const r=(0,is.default)(e,t);if(void 0!==r)return void n(us(r))}let s;(0,Zn.firstSeriesAsync)(e.rules,(n,a,o)=>{this.segmentRuleMatchContext(e,n,t,r,i,e=>(s=e.result,o(e.error||e.isMatch)))},e=>n(s?ds(s):us(e)))}segmentMatchContext(e,t,r,i,n){if(!e.unbounded)return void this.simpleSegmentMatchContext(e,t,r,i,n);const s=e.unboundedContextKind||"user",a=t.key(s);if(a)return e.generation?void(r.bigSegmentsMembership&&r.bigSegmentsMembership[a]?this.bigSegmentMatchContext(r.bigSegmentsMembership[a],e,t,r).then(n):this._queries.getBigSegmentsMembership(a).then(i=>{if(r.bigSegmentsMembership=r.bigSegmentsMembership||{},i){const[e,t]=i;r.bigSegmentsMembership[a]=e,r.bigSegmentsStatus=cs(r.bigSegmentsStatus,t)}else r.bigSegmentsStatus=cs(r.bigSegmentsStatus,"NOT_CONFIGURED");this.bigSegmentMatchContext(r.bigSegmentsMembership[a],e,t,r).then(n)})):(r.bigSegmentsStatus=cs(r.bigSegmentsStatus,"NOT_CONFIGURED"),void n(us(!1)));n(us(!1))}bigSegmentMatchContext(e,t,r,i){const n=(0,ts.default)(t),s=null==e?void 0:e[n];return new Promise(e=>{null==s?this.simpleSegmentMatchContext(t,r,i,[],e):e(us(s))})}};var hs={};Object.defineProperty(hs,"__esModule",{value:!0});const fs=X;hs.default=class{constructor(e){this._contextKeysCache=new fs.default({max:e.contextKeysCapacity}),this.flushInterval=e.contextKeysFlushInterval}processContext(e){const{canonicalKey:t}=e,r=this._contextKeysCache.get(t);return this._contextKeysCache.set(t,!0),!r}flush(){this._contextKeysCache.clear()}};var ps={},vs={};Object.defineProperty(vs,"__esModule",{value:!0}),vs.default=function(e,t){if(t){if(t.inExperiment)return!0;switch(t.kind){case"RULE_MATCH":{const r=t.ruleIndex;if(void 0!==r){const t=e.rules||[];return r>=0&&r<t.length&&!!t[r].trackEvents}break}case"FALLTHROUGH":return!!e.trackEventsFallthrough}}return!1},Object.defineProperty(ps,"__esModule",{value:!0});const gs=a,_s=vs;class ms extends gs.internal.EventFactoryBase{evalEventServer(e,t,r,i,n){var s;const a=(0,_s.default)(e,r.reason);return super.evalEvent({addExperimentData:a,context:t,debugEventsUntilDate:e.debugEventsUntilDate,defaultVal:i,excludeFromSummaries:e.excludeFromSummaries,flagKey:e.key,prereqOfFlagKey:null==n?void 0:n.key,reason:r.reason,samplingRatio:e.samplingRatio,trackEvents:e.trackEvents||a,value:r.value,variation:null!==(s=r.variationIndex)&&void 0!==s?s:void 0,version:e.version})}}ps.default=ms;var ys={};Object.defineProperty(ys,"__esModule",{value:!0});ys.default=class{constructor(e,t){this._valid=e,this._withReasons=t,this._flagValues={},this._flagMetadata={}}addFlag(e,t,r,i,n,s,a,o){this._flagValues[e.key]=t;const l={};void 0!==r&&(l.variation=r);const c=a&&!n&&!s&&void 0===e.debugEventsUntilDate;c||(l.version=e.version),i&&(s||this._withReasons&&!c)&&(l.reason=i),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 bs={};Object.defineProperty(bs,"__esModule",{value:!0});const Es="unknown hook";bs.default=class{constructor(e,t){this._logger=e,this._hooks=[],this._hooks.push(...t)}async withEvaluationSeries(e,t,r,i,n,s){return 0===this._hooks.length?n():this.withEvaluationSeriesExtraDetail(e,t,r,i,async()=>({detail:await n()}),s).then(({detail:e})=>e)}async withEvaluationSeriesExtraDetail(e,t,r,i,n,s){if(0===this._hooks.length)return n();const{hooks:a,hookContext:o}=this._prepareHooks(e,t,r,i,s),l=this._executeBeforeEvaluation(a,o),c=await n();return this._executeAfterEvaluation(a,o,l,c.detail),c}_tryExecuteStage(e,t,r){var i;try{return r()}catch(r){return null===(i=this._logger)||void 0===i||i.error(`An error was encountered in "${e}" of the "${t}" hook: ${r}`),{}}}_hookName(e){var t,r;try{return null!==(t=null==e?void 0:e.getMetadata().name)&&void 0!==t?t:Es}catch(e){return null===(r=this._logger)||void 0===r||r.error("Exception thrown getting metadata for hook. Unable to get hook name."),Es}}_executeAfterEvaluation(e,t,r,i){var n;for(let s=e.length-1;s>=0;s-=1){const a=e[s],o=null!==(n=r[s])&&void 0!==n?n:{};this._tryExecuteStage("afterEvaluation",this._hookName(a),()=>{var e,r;return null!==(r=null===(e=null==a?void 0:a.afterEvaluation)||void 0===e?void 0:e.call(a,t,o,i))&&void 0!==r?r:{}})}}_executeBeforeEvaluation(e,t){return e.map(e=>this._tryExecuteStage("beforeEvaluation",this._hookName(e),()=>{var r,i;return null!==(i=null===(r=null==e?void 0:e.beforeEvaluation)||void 0===r?void 0:r.call(e,t,{}))&&void 0!==i?i:{}}))}_prepareHooks(e,t,r,i,n){return{hooks:[...this._hooks],hookContext:{flagKey:e,context:t,defaultValue:r,method:i,environmentId:n}}}addHook(e){this._hooks.push(e)}};var Ss={};Object.defineProperty(Ss,"__esModule",{value:!0});const ws=a;function Os(e){const t=e.old,r=e.new;return!(void 0!==t&&!ws.TypeValidators.Boolean.is(t))&&!(void 0!==r&&!ws.TypeValidators.Boolean.is(r))}function ks(e){if(ws.TypeValidators.String.is(e.key)&&""!==e.key){if("latency_ms"===e.key){if(!ws.TypeValidators.Object.is(e.values))return;if(!function(e){const t=e.old,r=e.new;return!(void 0!==t&&!ws.TypeValidators.Number.is(t)||void 0!==r&&!ws.TypeValidators.Number.is(r))}(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(!ws.TypeValidators.Object.is(e.values))return;if(!Os(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(!ws.TypeValidators.Boolean.is(e.value)||!ws.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(!ws.TypeValidators.Object.is(e.values))return;if(!Os(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}}}Ss.default=function(e){var t,r;if("migration_op"!==e.kind)return;if(r=e.operation,!ws.TypeValidators.String.is(r)||"read"!==r&&"write"!==r)return;if(!ws.TypeValidators.Number.is(e.creationDate))return;const i={};if(ws.TypeValidators.Object.is(e.context)){const t=ws.Context.fromLDContext(e.context);t.valid&&(i.context=t)}else ws.TypeValidators.Object.is(e.contextKeys)&&Object.keys(e.contextKeys).every(e=>ws.TypeValidators.Kind.is(e))&&Object.values(e.contextKeys).every(e=>ws.TypeValidators.String.is(e)&&""!==e)&&(i.contextKeys=Object.assign({},e.contextKeys));if(!i.context&&!i.contextKeys)return;const n=null!==(t=e.samplingRatio)&&void 0!==t?t:1;if(!ws.TypeValidators.Number.is(n))return;const s=function(e){if(!ws.TypeValidators.String.is(e.key)||""===e.key)return;if(!ws.TypeValidators.Object.is(e.reason))return;if(!ws.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}},r=e.reason,i=t.reason;return ws.TypeValidators.String.is(r.errorKind)&&(i.errorKind=r.errorKind),ws.TypeValidators.String.is(r.ruleId)&&(i.ruleId=r.ruleId),ws.TypeValidators.String.is(r.prerequisiteKey)&&(i.prerequisiteKey=r.prerequisiteKey),ws.TypeValidators.Boolean.is(r.inExperiment)&&(i.inExperiment=r.inExperiment),ws.TypeValidators.Number.is(r.ruleIndex)&&(i.ruleIndex=r.ruleIndex),ws.TypeValidators.String.is(r.bigSegmentsStatus)&&(i.bigSegmentsStatus=r.bigSegmentsStatus),void 0!==e.variation&&ws.TypeValidators.Number.is(e.variation)&&(t.variation=e.variation),void 0!==e.version&&ws.TypeValidators.Number.is(e.version)&&(t.version=e.version),t}(e.evaluation);var a;return s?Object.assign(Object.assign({kind:e.kind,operation:e.operation,creationDate:e.creationDate},i),{measurements:(a=e.measurements,a.map(ks).filter(e=>void 0!==e)),evaluation:s,samplingRatio:n}):void 0};var Ds={};Object.defineProperty(Ds,"__esModule",{value:!0});const Ps=a,Ts=l;function Is(e){return!Number.isNaN(e)}Ds.default=class{constructor(e,t,r,i,n,s,a,o,l,c){this._flagKey=e,this._context=t,this._defaultStage=r,this._stage=i,this._reason=n,this._checkRatio=s,this._variation=a,this._version=o,this._samplingRatio=l,this._logger=c,this._errors={old:!1,new:!1},this._wasInvoked={old:!1,new:!1},this._consistencyCheck=Ts.LDConsistencyCheck.NotChecked,this._latencyMeasurement={old:NaN,new:NaN}}op(e){this._operation=e}error(e){this._errors[e]=!0}consistency(e){var t,r;if(Ps.internal.shouldSample(null!==(t=this._checkRatio)&&void 0!==t?t:1))try{const t=e();this._consistencyCheck=t?Ts.LDConsistencyCheck.Consistent:Ts.LDConsistencyCheck.Inconsistent}catch(e){null===(r=this._logger)||void 0===r||r.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,r,i,n;if(!Ps.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(!Ps.Context.fromLDContext(this._context).valid)return void(null===(r=this._logger)||void 0===r||r.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===(i=this._logger)||void 0===i||i.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(),context:this._context,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,r,i;return!!this._wasInvoked[e]||(Number.isNaN(this._latencyMeasurement[e])?this._errors[e]?(null===(r=this._logger)||void 0===r||r.error(`${this._logTag()} ${this._errorConsistencyMessage(e)}`),!1):this._consistencyCheck===Ts.LDConsistencyCheck.NotChecked||(null===(i=this._logger)||void 0===i||i.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 r={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&&(r.values.old=!0),this._wasInvoked.new&&(r.values.new=!0),e.push(r)}_populateConsistency(e){var t;void 0!==this._consistencyCheck&&this._consistencyCheck!==Ts.LDConsistencyCheck.NotChecked&&e.push({key:"consistent",value:this._consistencyCheck===Ts.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=Is(this._latencyMeasurement.new),r=Is(this._latencyMeasurement.old);if(t||r){const i={};t&&(i.new=this._latencyMeasurement.new),r&&(i.old=this._latencyMeasurement.old),e.push({key:"latency_ms",values:i})}}},Object.defineProperty(s,"__esModule",{value:!0});const xs=a,Rs=o,Ms=O,As=J,Fs=ee,Cs=te,Ls=re,js=ge,Ns=Oe,$s=Ce,Vs=Ne,Us=mt,Ks=Et,zs=wt,Bs=kt,Hs=Tt,qs=At,Ws=Nt,Gs=Vt,Js=Ht,Xs=hs,Ys=ps,Zs=vs,Qs=ys,ea=bs,ta=Ss,ra=Ds,ia=Ft,na=ne,{ClientMessages:sa,ErrorKinds:aa,NullEventProcessor:oa}=xs.internal;var la;!function(e){e[e.Initializing=0]="Initializing",e[e.Initialized=1]="Initialized",e[e.Failed=2]="Failed"}(la||(la={}));function ca(e,t,r,i,n,s,a,o,l,c){var u,d,h,f,p;const{onUpdate:v,hasEventListeners:g}=i,_=new ea.default(r.logger,a);if(!e&&!r.offline)throw new Error("You must configure the client with an SDK key");const{logger:m}=r,y=(0,xs.defaultHeaders)(e,t.info,r.tags,!0,l,o),b=new xs.ClientContext(e,r,t),E=r.featureStoreFactory(b),S=new js.default(E,g,v);let w,O;!r.sendEvents||r.offline||r.diagnosticOptOut||(w=new xs.internal.DiagnosticsManager(e,t,(0,qs.default)(r,t,E))),O=!r.sendEvents||r.offline?new oa:new xs.internal.EventProcessor(Object.assign(Object.assign({},r),{redactAnonymousAllEvents:!0}),b,y,new Xs.default(r),w,c);const k=new As.default(null===(d=null===(u=r.bigSegments)||void 0===u?void 0:u.store)||void 0===d?void 0:d.call(u,b),null!==(h=r.bigSegments)&&void 0!==h?h:{},r.logger,t.crypto),D={getFlag(e,t){E.get(na.default.Features,e,e=>t(e))},getSegment(e,t){E.get(na.default.Segments,e,e=>t(e))},getBigSegmentsMembership:e=>k.getUserMembership(e)},P=new Js.default(t,D),T=(0,Ls.createStreamListeners)(S,m,{put:n});let I;return r.offline||r.useLdd||(I=null!==(p=null===(f=r.updateProcessorFactory)||void 0===f?void 0:f.call(r,b,S,n,s))&&void 0!==p?p:r.stream?new zs.default(b,"/all",[],T,y,w,s,r.streamInitialReconnectDelay):new Vs.default(new Ks.default(r,t.requests,y),r.pollInterval,S,r.logger,n,s)),{config:r,logger:m,evaluator:P,featureStore:E,updateProcessor:I,eventProcessor:O,bigSegmentsManager:k,hookRunner:_,onError:i.onError,onFailed:i.onFailed,onReady:i.onReady}}function ua(e,t){var r,i;return new xs.ServiceEndpoints(null!==(r=t.streaming)&&void 0!==r?r:e.streaming,null!==(i=t.polling)&&void 0!==i?i:e.polling,e.events,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,e.payloadFilterKey)}s.default=class{get logger(){return this._logger}constructor(e,t,r,i,n){this._sdkKey=e,this._platform=t,this._initState=la.Initializing,this._eventFactoryDefault=new Ys.default(!1),this._eventFactoryWithReasons=new Ys.default(!0);const s=new ia.default(r,n),a=!(null==n?void 0:n.disableBackgroundEventFlush);this.environmentMetadata=(0,Fs.createPluginEnvironmentMetadata)(t,e,s);const o=[];if(s.hooks&&o.push(...s.hooks),s.getImplementationHooks(this.environmentMetadata).forEach(e=>{o.push(e)}),s.dataSystem){let r,l;({config:this._config,logger:this._logger,evaluator:this._evaluator,featureStore:r,dataSource:this._dataSource,payloadListener:l,eventProcessor:this._eventProcessor,bigSegmentsManager:this._bigSegmentsManager,hookRunner:this._hookRunner,onError:this._onError,onFailed:this._onFailed,onReady:this._onReady}=function(e,t,r,i,n,s,a,o,l){var c,u,d,h,f,p;const{onUpdate:v,hasEventListeners:g}=i,_=new ea.default(r.logger,s);if(!e&&!r.offline)throw new Error("You must configure the client with an SDK key");const{logger:m}=r;void 0!==r.payloadFilterKey&&(null==m||m.warn("Payload filtering is not supported with the FDv2 data system; the configured payload filter has no effect on FDv2 requests"));const y=(0,xs.defaultHeaders)(e,t.info,r.tags,!0,o,a),b=new xs.ClientContext(e,r,t),E=r.dataSystem,S=E.featureStoreFactory(b),w=new Hs.default(S,g,v);let O,k;!r.sendEvents||r.offline||r.diagnosticOptOut||(O=new xs.internal.DiagnosticsManager(e,t,(0,qs.default)(r,t,S))),k=!r.sendEvents||r.offline?new oa:new xs.internal.EventProcessor(Object.assign(Object.assign({},r),{redactAnonymousAllEvents:!0}),b,y,new Xs.default(r),O,l);const D=new As.default(null===(u=null===(c=r.bigSegments)||void 0===c?void 0:c.store)||void 0===u?void 0:u.call(c,b),null!==(d=r.bigSegments)&&void 0!==d?d:{},r.logger,t.crypto),P={getFlag(e,t){S.get(na.default.Features,e,e=>t(e))},getSegment(e,t){S.get(na.default.Segments,e,e=>t(e))},getBigSegmentsMembership:e=>D.getUserMembership(e)},T=new Js.default(t,P);let I,x;if(!r.offline&&!r.dataSystem.useLdd){const e=[],i=[],s=[];if((0,Ms.isCustomOptions)(E.dataSource)){const{initializers:n=[],synchronizers:s=[]}=E.dataSource;n.forEach(i=>{switch(i.type){case"file":e.push(()=>new Ns.default(i,t,r.logger));break;case"polling":{const n=i.baseUri?ua(r.serviceEndpoints,{polling:i.baseUri}):void 0;e.push(()=>new $s.default(new Ks.default(r,t.requests,y,"/sdk/poll",r.logger,n),r.logger));break}default:throw new Error("Unsupported initializer type")}}),s.forEach(e=>{switch(e.type){case"streaming":{const{streamInitialReconnectDelay:t=ia.DEFAULT_STREAM_RECONNECT_DELAY}=e,n=e.baseUri?ua(r.serviceEndpoints,{streaming:e.baseUri}):void 0;i.push(()=>new Bs.default(b,"/sdk/stream",[],y,O,t,n));break}case"polling":{const{pollInterval:n=ia.DEFAULT_POLL_INTERVAL}=e,s=e.baseUri?ua(r.serviceEndpoints,{polling:e.baseUri}):void 0;i.push(()=>new Us.default(new Ks.default(r,t.requests,y,"/sdk/poll",r.logger,s),n,r.logger));break}default:throw new Error("Unsupported synchronizer type")}})}else{if((0,Ms.isStandardOptions)(E.dataSource)&&e.push(()=>new $s.default(new Ks.default(r,t.requests,y,"/sdk/poll",r.logger),r.logger)),(0,Ms.isStandardOptions)(E.dataSource)||(0,Ms.isStreamingOnlyOptions)(E.dataSource)){const e=E.dataSource.streamInitialReconnectDelay;i.push(()=>new Bs.default(b,"/sdk/stream",[],y,O,e))}let n=ia.DEFAULT_POLL_INTERVAL;((0,Ms.isStandardOptions)(E.dataSource)||(0,Ms.isPollingOnlyOptions)(E.dataSource))&&(n=null!==(h=E.dataSource.pollInterval)&&void 0!==h?h:ia.DEFAULT_POLL_INTERVAL,i.push(()=>new Us.default(new Ks.default(r,t.requests,y,"/sdk/poll",m),n,m)))}const a=E.fdv1Fallback;if(null!==a){const e=null!==(p=null!==(f=null==a?void 0:a.pollInterval)&&void 0!==f?f:r.pollInterval)&&void 0!==p?p:ia.DEFAULT_POLL_INTERVAL,i=(null==a?void 0:a.baseUri)?ua(r.serviceEndpoints,{polling:a.baseUri}):void 0;s.push(()=>new Us.default(new Ks.default(r,t.requests,y,"/sdk/latest-all",r.logger,i),e,r.logger,!0))}I=new xs.CompositeDataSource(e,i,s,m),x=(0,Cs.createPayloadListener)(w,m,n)}return{config:r,logger:m,evaluator:T,featureStore:S,dataSource:I,payloadListener:x,eventProcessor:k,bigSegmentsManager:D,hookRunner:_,onError:i.onError,onFailed:i.onFailed,onReady:i.onReady}}(e,t,s,i,()=>this._initSuccess(),o,null==n?void 0:n.instanceId,null==n?void 0:n.userAgentHeaderName,a)),this._featureStore=r,this.bigSegmentStatusProviderInternal=this._bigSegmentsManager.statusProvider,this._dataSource&&this._dataSource.start((e,t)=>{null==l||l(t)},(e,t)=>{e===xs.subsystem.DataSourceState.Closed&&t&&this._dataSourceErrorHandler(t)},()=>{var e;return null===(e=r.getSelector)||void 0===e?void 0:e.call(r)})}else({config:this._config,logger:this._logger,evaluator:this._evaluator,featureStore:this._featureStore,updateProcessor:this._updateProcessor,eventProcessor:this._eventProcessor,bigSegmentsManager:this._bigSegmentsManager,hookRunner:this._hookRunner,onError:this._onError,onFailed:this._onFailed,onReady:this._onReady}=ca(e,t,s,i,()=>this._initSuccess(),e=>this._dataSourceErrorHandler(e),o,null==n?void 0:n.instanceId,null==n?void 0:n.userAgentHeaderName,a)),this.bigSegmentStatusProviderInternal=this._bigSegmentsManager.statusProvider,this._updateProcessor&&this._updateProcessor.start()}initialized(){return this._initState===la.Initialized}waitForInitialization(e){var t,r;return void 0!==(null==e?void 0:e.timeout)||void 0===this._updateProcessor&&void 0===this._dataSource||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||void 0!==this._dataSource)&&(null===(r=this._logger)||void 0===r||r.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===la.Initialized?(this._initializedPromise=Promise.resolve(this),this._initializedPromise):this._initState===la.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,r,i){var n,s,a;return this._hookRunner.withEvaluationSeries(e,t,r,"LDClient.variation",()=>new Promise(i=>{this._evaluateIfPossible(e,t,r,this._eventFactoryDefault,e=>{i(e.detail)})}),null===(a=null===(s=(n=this._featureStore).getInitMetaData)||void 0===s?void 0:s.call(n))||void 0===a?void 0:a.environmentId).then(e=>(null==i||i(null,e.value),e.value))}variationDetail(e,t,r,i){var n,s,a;return this._hookRunner.withEvaluationSeries(e,t,r,"LDClient.variationDetail",()=>new Promise(n=>{this._evaluateIfPossible(e,t,r,this._eventFactoryWithReasons,e=>{n(e.detail),null==i||i(null,e.detail)})}),null===(a=null===(s=(n=this._featureStore).getInitMetaData)||void 0===s?void 0:s.call(n))||void 0===a?void 0:a.environmentId)}_typedEval(e,t,r,i,n,s){var a,o,l;return this._hookRunner.withEvaluationSeries(e,t,r,n,()=>new Promise(n=>{this._evaluateIfPossible(e,t,r,i,e=>{const t={value:e.detail.value,reason:e.detail.reason,variationIndex:e.detail.variationIndex};n(t)},s)}),null===(l=null===(o=(a=this._featureStore).getInitMetaData)||void 0===o?void 0:o.call(a))||void 0===l?void 0:l.environmentId)}async boolVariation(e,t,r){return(await this._typedEval(e,t,r,this._eventFactoryDefault,"LDClient.boolVariation",e=>[xs.TypeValidators.Boolean.is(e),xs.TypeValidators.Boolean.getType()])).value}async numberVariation(e,t,r){return(await this._typedEval(e,t,r,this._eventFactoryDefault,"LDClient.numberVariation",e=>[xs.TypeValidators.Number.is(e),xs.TypeValidators.Number.getType()])).value}async stringVariation(e,t,r){return(await this._typedEval(e,t,r,this._eventFactoryDefault,"LDClient.stringVariation",e=>[xs.TypeValidators.String.is(e),xs.TypeValidators.String.getType()])).value}jsonVariation(e,t,r){var i,n,s;return this._hookRunner.withEvaluationSeries(e,t,r,"LDClient.jsonVariation",()=>new Promise(i=>{this._evaluateIfPossible(e,t,r,this._eventFactoryDefault,e=>{i(e.detail)})}),null===(s=null===(n=(i=this._featureStore).getInitMetaData)||void 0===n?void 0:n.call(i))||void 0===s?void 0:s.environmentId).then(e=>e.value)}boolVariationDetail(e,t,r){return this._typedEval(e,t,r,this._eventFactoryWithReasons,"LDClient.boolVariationDetail",e=>[xs.TypeValidators.Boolean.is(e),xs.TypeValidators.Boolean.getType()])}numberVariationDetail(e,t,r){return this._typedEval(e,t,r,this._eventFactoryWithReasons,"LDClient.numberVariationDetail",e=>[xs.TypeValidators.Number.is(e),xs.TypeValidators.Number.getType()])}stringVariationDetail(e,t,r){return this._typedEval(e,t,r,this._eventFactoryWithReasons,"LDClient.stringVariationDetail",e=>[xs.TypeValidators.String.is(e),xs.TypeValidators.String.getType()])}jsonVariationDetail(e,t,r){var i,n,s;return this._hookRunner.withEvaluationSeries(e,t,r,"LDClient.jsonVariationDetail",()=>new Promise(i=>{this._evaluateIfPossible(e,t,r,this._eventFactoryWithReasons,e=>{i(e.detail)})}),null===(s=null===(n=(i=this._featureStore).getInitMetaData)||void 0===n?void 0:n.call(i))||void 0===s?void 0:s.environmentId)}async _migrationVariationInternal(e,t,r){var i;const n=await new Promise(i=>{this._evaluateIfPossible(e,t,r,this._eventFactoryWithReasons,({detail:t},n)=>{if(!(0,Rs.IsMigrationStage)(t.value)){const t=new Error(`Unrecognized MigrationState for "${e}"; returning default value.`);this._onError(t);const s={kind:"ERROR",errorKind:aa.WrongType};return void i({detail:{value:r,reason:s},flag:n})}i({detail:t,flag:n})})}),{detail:s,flag:a}=n,o=null===(i=null==a?void 0:a.migration)||void 0===i?void 0:i.checkRatio,l=null==a?void 0:a.samplingRatio;return{detail:s,migration:{value:s.value,tracker:new ra.default(e,t,r,s.value,s.reason,o,null===s.variationIndex?void 0:s.variationIndex,null==a?void 0:a.version,l,this._logger)}}}async migrationVariation(e,t,r){var i,n,s;return(await this._hookRunner.withEvaluationSeriesExtraDetail(e,t,r,"LDClient.migrationVariation",()=>this._migrationVariationInternal(e,t,r),null===(s=null===(n=(i=this._featureStore).getInitMetaData)||void 0===n?void 0:n.call(i))||void 0===s?void 0:s.environmentId)).migration}allFlagsState(e,t,r){var i,n,s;if(this._config.offline){null===(i=this._logger)||void 0===i||i.info("allFlagsState() called in offline mode. Returning empty state.");const e=new Qs.default(!1,!1).build();return null==r||r(null,e),Promise.resolve(e)}const a=xs.Context.fromLDContext(e);return a.valid?new Promise(e=>{const i=i=>this._featureStore.all(na.default.Features,n=>{const s=new Qs.default(i,!!(null==t?void 0:t.withReasons)),o=!!(null==t?void 0:t.clientSideOnly),l=!!(null==t?void 0:t.detailsOnlyForTrackedFlags);(0,Ws.allAsync)(Object.values(n),(e,t)=>{var r;const i=e;!o||(null===(r=i.clientSideAvailability)||void 0===r?void 0:r.usingEnvironmentId)?this._evaluator.evaluateCb(i,a,e=>{var r;e.isError&&this._onError(new Error(`Error for feature flag "${i.key}" while evaluating all flags: ${e.message}`));const n=(0,Zs.default)(i,e.detail.reason);s.addFlag(i,e.detail.value,null!==(r=e.detail.variationIndex)&&void 0!==r?r:void 0,e.detail.reason,i.trackEvents||n,n,l,e.prerequisites),t(!0)}):t(!0)},()=>{const t=s.build();null==r||r(null,t),e(t)})});this.initialized()?i(!0):this._featureStore.initialized(e=>{var t,r;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===(r=this._logger)||void 0===r||r.warn("Called allFlagsState before client initialization. Data store not available; returning empty state"),n=!1),i(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 Qs.default(!1,!1).build()))}secureModeHash(e){const t=xs.Context.fromLDContext(e),r=t.valid?t.canonicalKey:void 0;if(!this._platform.crypto.createHmac)throw new Error("Platform must implement createHmac");const i=this._platform.crypto.createHmac("sha256",this._sdkKey);if(void 0===r)throw new xs.LDClientError("Could not generate secure mode hash for invalid context");return i.update(r),i.digest("hex")}close(){var e,t;this._eventProcessor.close(),null===(e=this._updateProcessor)||void 0===e||e.close(),null===(t=this._dataSource)||void 0===t||t.stop(),this._featureStore.close(),this._bigSegmentsManager.close()}isOffline(){return this._config.offline}track(e,t,r,i){var n,s;const a=xs.Context.fromLDContext(t);a.valid?(void 0===i||xs.TypeValidators.Number.is(i)||null===(s=this._logger)||void 0===s||s.warn(sa.invalidMetricValue(typeof i)),this._eventProcessor.sendEvent(this._eventFactoryDefault.customEvent(e,a,r,i))):null===(n=this._logger)||void 0===n||n.warn(sa.MissingContextKeyNoEvent)}trackMigration(e){const t=(0,ta.default)(e);t&&this._eventProcessor.sendEvent(t)}identify(e){var t;const r=xs.Context.fromLDContext(e);r.valid?this._eventProcessor.sendEvent(this._eventFactoryDefault.identifyEvent(r)):null===(t=this._logger)||void 0===t||t.warn(sa.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,r,i,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(Gs.default.forError(aa.ClientNotReady,void 0,r));const l=xs.Context.fromLDContext(t);if(!l.valid)return this._onError(new xs.LDClientError(`${null!==(o=l.message)&&void 0!==o?o:"Context not valid;"} returning default value.`)),void n(Gs.default.forError(aa.UserNotSpecified,void 0,r));this._featureStore.get(na.default.Features,e,t=>{const a=t;if(!a){const t=new xs.LDClientError(`Unknown feature flag "${e}"; returning default value`);this._onError(t);const i=Gs.default.forError(aa.FlagNotFound,void 0,r);return this._eventProcessor.sendEvent(this._eventFactoryDefault.unknownFlagEvent(e,r,l)),void n(i)}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(r)),s){const[o,c]=s(t.detail.value);if(!o){const t=Gs.default.forError(aa.WrongType,`Did not receive expected type (${c}) evaluating feature flag "${e}"`,r);return this._sendEvalEvent(t,i,a,l,r),void n(t,a)}}this._sendEvalEvent(t,i,a,l,r),n(t,a)},i)})}_sendEvalEvent(e,t,r,i,n){var s;null===(s=e.events)||void 0===s||s.forEach(e=>{this._eventProcessor.sendEvent(Object.assign({},e))}),this._eventProcessor.sendEvent(t.evalEventServer(r,i,e.detail,n,void 0))}_evaluateIfPossible(e,t,r,i,n,s){this.initialized()?this._variationInternal(e,t,r,i,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,r,i,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(Gs.default.forError(aa.ClientNotReady,void 0,r))})}_dataSourceErrorHandler(e){var t;const r=401===e.code?new Error("Authentication failed. Double check your SDK key."):e;this._onError(r),this._onFailed(r),this.initialized()||(this._initState=la.Failed,this._rejectionReason=r,null===(t=this._initReject)||void 0===t||t.call(this,r))}_initSuccess(){var e;this.initialized()||(this._initState=la.Initialized,null===(e=this._initResolve)||void 0===e||e.call(this,this),this._onReady())}_clientWithTimeout(e,t,r){if(t){const i=(0,xs.cancelableTimedPromise)(t,"waitForInitialization");return Promise.race([e.then(()=>this),i.promise.then(()=>this)]).catch(e=>{throw e instanceof xs.LDTimeoutError&&(null==r||r.error(e.message)),e}).finally(()=>i.cancel())}return e}};var da={};Object.defineProperty(da,"__esModule",{value:!0}),da.createMigration=da.LDMigrationError=da.LDMigrationSuccess=void 0;const ha=o,fa=w;da.LDMigrationSuccess=function(e){return{success:!0,result:e}},da.LDMigrationError=function(e){return{success:!1,error:e}};class pa{constructor(e,t){var r,i;this._client=e,this._config=t,this._readTable={[ha.LDMigrationStage.Off]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[ha.LDMigrationStage.DualWrite]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[ha.LDMigrationStage.Shadow]:async e=>{const{fromOld:t,fromNew:r}=await this._doRead(e);return this._trackConsistency(e,t,r),t},[ha.LDMigrationStage.Live]:async e=>{const{fromNew:t,fromOld:r}=await this._doRead(e);return this._trackConsistency(e,r,t),t},[ha.LDMigrationStage.RampDown]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[ha.LDMigrationStage.Complete]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config))},this._writeTable={[ha.LDMigrationStage.Off]:async e=>({authoritative:await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config))}),[ha.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))}},[ha.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))}},[ha.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))}},[ha.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))}},[ha.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 fa.LDConcurrentExecution,this._latencyTracking=null===(r=this._config.latencyTracking)||void 0===r||r,this._errorTracking=null===(i=this._config.errorTracking)||void 0===i||i}async read(e,t,r,i){const n=await this._client.migrationVariation(e,t,r),s=await this._readTable[n.value]({payload:i,tracker:n.tracker});return n.tracker.op("read"),this._sendEvent(n.tracker),s}async write(e,t,r,i){const n=await this._client.migrationVariation(e,t,r),s=await this._writeTable[n.value]({payload:i,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,r){this._config.check&&t.success&&r.success&&e.tracker.consistency(()=>this._config.check(t.result,r.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)),r=this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[i,n]=await Promise.all([t,r]);return{fromOld:i,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)===fa.LDExecution.Serial){return this._execution.ordering===fa.LDExecutionOrdering.Fixed?this._readSequentialFixed(e):this._readSequentialRandom(e)}return this._readConcurrent(e)}async _doSingleOp(e,t,r){e.tracker.invoked(t);const i=await this._trackLatency(e.tracker,t,()=>async function(e){try{return await e()}catch(e){return{success:!1,error:e}}}(()=>r(e.payload)));return!i.success&&this._errorTracking&&e.tracker.error(t),Object.assign({origin:t},i)}async _trackLatency(e,t,r){if(!this._latencyTracking)return r();let i,n,s;"undefined"!=typeof performance?(i=performance.now(),s=await r(),n=performance.now()):(i=Date.now(),s=await r(),n=Date.now());const a=n-i;return e.latency(t,a),s}}da.createMigration=function(e,t){return new pa(e,t)};var va={},ga={};Object.defineProperty(ga,"__esModule",{value:!0});const _a=De;ga.default=class{constructor(e){this._options=e}create(e,t,r,i){const n={paths:this._options.paths,autoUpdate:this._options.autoUpdate,logger:this._options.logger||e.basicConfiguration.logger,yamlParser:this._options.yamlParser};return new _a.default(n,e.platform.fileSystem,t,r,i)}getFactory(){return(e,t,r,i)=>this.create(e,t,r,i)}};var ma={},ya={},ba={},Ea={};!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}}(Ea);var Sa={};Object.defineProperty(Sa,"__esModule",{value:!0});const wa=a,Oa=Ea;class ka{constructor(e,t,r){this._flagBuilder=e,this._clauses=[],t&&(this._clauses=[...t]),void 0!==r&&(this._variation=r)}andMatch(e,t,...r){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new wa.AttributeReference(t),op:"in",values:r,negate:!1}),this}andNotMatch(e,t,...r){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new wa.AttributeReference(t),op:"in",values:r,negate:!0}),this}thenReturn(e){return wa.TypeValidators.Boolean.is(e)?(this._flagBuilder.booleanFlag(),this.thenReturn((0,Oa.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 ka(this._flagBuilder,this._clauses,this._variation)}}Sa.default=ka,Object.defineProperty(ba,"__esModule",{value:!0});const Da=a,Pa=Ea,Ta=Sa;class Ia{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[Pa.TRUE_VARIATION_INDEX]&&!1===this._data.variations[Pa.FALSE_VARIATION_INDEX]}booleanFlag(){return this._isBooleanFlag?this:this.variations(!0,!1).fallthroughVariation(Pa.TRUE_VARIATION_INDEX).offVariation(Pa.FALSE_VARIATION_INDEX)}variations(...e){return this._data.variations=[...e],this}on(e){return this._data.on=e,this}fallthroughVariation(e){return Da.TypeValidators.Boolean.is(e)?this.booleanFlag().fallthroughVariation((0,Pa.variationForBoolean)(e)):(this._data.fallthroughVariation=e,this)}offVariation(e){return Da.TypeValidators.Boolean.is(e)?this.booleanFlag().offVariation((0,Pa.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,r){return Da.TypeValidators.Boolean.is(r)?this.booleanFlag().variationForContext(e,t,(0,Pa.variationForBoolean)(r)):(this._data.targetsByVariation||(this._data.targetsByVariation={}),this._data.variations.forEach((i,n)=>{if(n===r){const r=this._data.targetsByVariation[n]||{};e in r||(r[e]=[]);-1!==r[e].indexOf(t)||r[e].push(t),this._data.targetsByVariation[n]=r}else{const r=this._data.targetsByVariation[n];if(r){const i=r[e];if(i){const n=i.indexOf(t);-1!==n&&(i.splice(n,1),i.length||delete r[e])}Object.keys(r).length||delete this._data.targetsByVariation[n]}}}),this)}clearRules(){return delete this._data.rules,this}clearAllTargets(){return delete this._data.targetsByVariation,this}ifMatch(e,t,...r){return new Ta.default(this).andMatch(e,t,...r)}ifNotMatch(e,t,...r){return new Ta.default(this).andNotMatch(e,t,...r)}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=[],r=[];Object.entries(this._data.targetsByVariation).forEach(([t,i])=>{Object.entries(i).forEach(([i,n])=>{const s=parseInt(t,10);e.push({contextKind:i,values:"user"===i?[]:n,variation:s}),"user"===i&&r.push({values:n,variation:s})})}),t.targets=r,t.contextTargets=e}return this._data.rules&&(t.rules=this._data.rules.map((e,t)=>e.build(String(t)))),t}clone(){return new Ia(this._key,this._data)}getKey(){return this._key}}ba.default=Ia;var xa={};Object.defineProperty(xa,"__esModule",{value:!0});xa.default=class{constructor(e,t,r,i,n){this._featureStore=e,this._onStop=i,this._listeners=n,this._flags=Object.assign({},t),this._segments=Object.assign({},r)}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(ya,"__esModule",{value:!0});const Ra=re,Ma=Ve,Aa=ie,Fa=ne,Ca=ba,La=xa;ya.default=class{constructor(){this._currentFlags={},this._currentSegments={},this._dataSources=[],this._flagBuilders={}}getFactory(){return(e,t,r,i)=>{const n=(0,Ra.createStreamListeners)(t,e.basicConfiguration.logger,{put:r}),s=new La.default(new Ma.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 Ca.default(e).booleanFlag()}update(e){const t=e.getKey(),r=this._currentFlags[t],i=r?r.version:0,n=e.build(i+1);return this._currentFlags[t]=n,this._flagBuilders[t]=e.clone(),Promise.all(this._dataSources.map(e=>e.upsert(Fa.default.Features,n)))}usePreconfiguredFlag(e){const t=JSON.parse(JSON.stringify(e)),r=this._currentFlags[t.key],i=Object.assign(Object.assign({},t),{version:r?r.version+1:t.version});return(0,Aa.processFlag)(i),this._currentFlags[t.key]=i,Promise.all(this._dataSources.map(e=>e.upsert(Fa.default.Features,i)))}usePreconfiguredSegment(e){const t=JSON.parse(JSON.stringify(e)),r=this._currentSegments[t.key],i=Object.assign(Object.assign({},t),{version:r?r.version+1:t.version});return(0,Aa.processSegment)(i),this._currentSegments[t.key]=i,Promise.all(this._dataSources.map(e=>e.upsert(Fa.default.Segments,i)))}},Object.defineProperty(ma,"__esModule",{value:!0}),ma.TestDataRuleBuilder=ma.TestDataFlagBuilder=ma.TestData=void 0;const ja=ya;ma.TestData=ja.default;const Na=ba;ma.TestDataFlagBuilder=Na.default;const $a=Sa;ma.TestDataRuleBuilder=$a.default,function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),e.FileDataSourceFactory=void 0;const n=ga;e.FileDataSourceFactory=n.default,i(ma,e),i(R,e)}(va);var Va={},Ua={};Object.defineProperty(Ua,"__esModule",{value:!0});Ua.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(Va,"__esModule",{value:!0}),Va.NullEventSource=void 0;const Ka=Ua;Va.NullEventSource=Ka.default;var za={};Object.defineProperty(za,"__esModule",{value:!0}),za.TtlCache=void 0;const Ba=qe;za.TtlCache=Ba.default,function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),e.createMigration=e.LDMigrationSuccess=e.LDMigrationError=e.BigSegmentStoreStatusProviderImpl=e.LDClientImpl=e.internalServer=e.platform=e.integrations=void 0;const l=n;e.BigSegmentStoreStatusProviderImpl=l.default;const c=s;e.LDClientImpl=c.default;const u=da;Object.defineProperty(e,"createMigration",{enumerable:!0,get:function(){return u.createMigration}}),Object.defineProperty(e,"LDMigrationError",{enumerable:!0,get:function(){return u.LDMigrationError}}),Object.defineProperty(e,"LDMigrationSuccess",{enumerable:!0,get:function(){return u.LDMigrationSuccess}}),e.integrations=va,e.platform=a,i(o,e),i($e,e),i(Va,e),i(a,e),e.internalServer=za}(i);var Ha={},qa={},Wa={};Object.defineProperty(Wa,"__esModule",{value:!0}),Wa.createCallbacks=void 0;Wa.createCallbacks=e=>({onError:t=>{var r;null===(r=null==e?void 0:e.error)||void 0===r||r.call(e,t.message)},onFailed:e=>{},onReady:()=>{},onUpdate:e=>{},hasEventListeners:()=>!1});var Ga={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createOptions=e.defaultOptions=void 0;const t=i;e.defaultOptions={stream:!1,sendEvents:!1,useLdd:!0,diagnosticOptOut:!0,logger:t.BasicLogger.get()};e.createOptions=t=>{var r;const i=Object.assign(Object.assign({},e.defaultOptions),t);return null===(r=i.logger)||void 0===r||r.debug(`Using LD options: ${JSON.stringify(i)}`),i}}(Ga);var Ja={},Xa=t&&t.__rest||function(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r};Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.validateOptions=void 0;Ja.validateOptions=(e,t)=>{const{featureStore:r,logger:i,sendEvents:n}=t,s=Xa(t,["featureStore","logger","sendEvents"]);if(!e)throw new Error("You must configure the client with a client key");if(!r||"object"!=typeof r||!r.get)throw new Error("You must configure the client with a feature store");if(!i)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},function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(Wa,e),i(Ga,e),i(Ja,e)}(qa),Object.defineProperty(Ha,"__esModule",{value:!0});const Ya=i,Za=qa;Ha.default=class extends Ya.LDClientImpl{constructor(e,t,r){const i=(0,Za.createOptions)(r);super(e,t,i,(0,Za.createCallbacks)(i.logger))}initialized(){return!0}waitForInitialization(){return Promise.resolve(this)}};var Qa={},eo={};Object.defineProperty(eo,"__esModule",{value:!0});eo.default=class{constructor(e){this._cacheTtlMs=e}get(){if(!(this._cacheTtlMs<0)&&void 0!==this._cache)return 0===this._cacheTtlMs||Date.now()<this._cache.expiration?this._cache.value:void(this._cache=void 0)}set(e){this._cache={value:e,expiration:Date.now()+this._cacheTtlMs}}},function(e){var r=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.EdgeFeatureStore=e.buildRootKey=void 0;const n=i,s=r(eo);e.buildRootKey=e=>`LD-Env-${e}`;e.EdgeFeatureStore=class{constructor(t,r,i,a,o){this._edgeProvider=t,this._sdkKey=r,this._description=i,this._logger=a,this.close=n.noop,this.delete=n.noop,this.upsert=n.noop,this._rootKey=(0,e.buildRootKey)(this._sdkKey),this._cache=new s.default(o)}async get(e,t,r){const{namespace:i}=e,n="features"===i?"flags":i;this._logger.debug(`Requesting ${t} from ${this._rootKey}.${n}`);try{const e=await this._getStorePayload();switch(i){case"features":r(e.flags[t]);break;case"segments":r(e.segments[t]);break;default:r(null)}}catch(e){this._logger.error(e),r(null)}}async all(e,t=n.noop){const{namespace:r}=e,i="features"===r?"flags":r;this._logger.debug(`Requesting all from ${this._rootKey}.${i}`);try{const e=await this._getStorePayload();switch(r){case"features":t(e.flags);break;case"segments":t(e.segments);break;default:throw new Error(`Unsupported DataKind: ${r}`)}}catch(e){this._logger.error(e),t({})}}async _getStorePayload(){let e=this._cache.get();if(void 0!==e)return e;const t=await this._edgeProvider.get(this._rootKey);if(!t)throw new Error(`${this._rootKey} is not found in KV.`);if(e=(0,n.deserializePoll)(t),!e)throw new Error(`Error deserializing ${this._rootKey}`);return this._cache.set(e),e}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}}}(Qa);var to={},ro={},io={};var no,so={exports:{}};so.exports=(no=no||function(e,r){var i;if("undefined"!=typeof window&&window.crypto&&(i=window.crypto),"undefined"!=typeof self&&self.crypto&&(i=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(i=globalThis.crypto),!i&&"undefined"!=typeof window&&window.msCrypto&&(i=window.msCrypto),!i&&void 0!==t&&t.crypto&&(i=t.crypto),!i)try{i=require("crypto")}catch(e){}var n=function(){if(i){if("function"==typeof i.getRandomValues)try{return i.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof i.randomBytes)try{return i.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},s=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),a={},o=a.lib={},l=o.Base={extend:function(e){var t=s(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},c=o.WordArray=l.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=t!=r?t:4*e.length},toString:function(e){return(e||d).stringify(this)},concat:function(e){var t=this.words,r=e.words,i=this.sigBytes,n=e.sigBytes;if(this.clamp(),i%4)for(var s=0;s<n;s++){var a=r[s>>>2]>>>24-s%4*8&255;t[i+s>>>2]|=a<<24-(i+s)%4*8}else for(var o=0;o<n;o+=4)t[i+o>>>2]=r[o>>>2];return this.sigBytes+=n,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=l.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],r=0;r<e;r+=4)t.push(n());return new c.init(t,e)}}),u=a.enc={},d=u.Hex={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n<r;n++){var s=t[n>>>2]>>>24-n%4*8&255;i.push((s>>>4).toString(16)),i.push((15&s).toString(16))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i<t;i+=2)r[i>>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new c.init(r,t/2)}},h=u.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n<r;n++){var s=t[n>>>2]>>>24-n%4*8&255;i.push(String.fromCharCode(s))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i<t;i++)r[i>>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new c.init(r,t)}},f=u.Utf8={stringify:function(e){try{return decodeURIComponent(escape(h.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return h.parse(unescape(encodeURIComponent(e)))}},p=o.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new c.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=f.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r,i=this._data,n=i.words,s=i.sigBytes,a=this.blockSize,o=s/(4*a),l=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,u=e.min(4*l,s);if(l){for(var d=0;d<l;d+=a)this._doProcessBlock(n,d);r=n.splice(0,l),i.sigBytes-=u}return new c.init(r,u)},clone:function(){var e=l.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});o.Hasher=p.extend({cfg:l.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){p.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,r){return new e.init(r).finalize(t)}},_createHmacHelper:function(e){return function(t,r){return new v.HMAC.init(e,r).finalize(t)}}});var v=a.algo={};return a}(Math),no);var ao=so.exports;!function(e){return r=(t=e).lib,i=r.WordArray,n=r.Hasher,s=t.algo,a=[],o=s.SHA1=n.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],n=r[1],s=r[2],o=r[3],l=r[4],c=0;c<80;c++){if(c<16)a[c]=0|e[t+c];else{var u=a[c-3]^a[c-8]^a[c-14]^a[c-16];a[c]=u<<1|u>>>31}var d=(i<<5|i>>>27)+l+a[c];d+=c<20?1518500249+(n&s|~n&o):c<40?1859775393+(n^s^o):c<60?(n&s|n&o|s&o)-1894007588:(n^s^o)-899497514,l=o,o=s,s=n<<30|n>>>2,n=i,i=d}r[0]=r[0]+i|0,r[1]=r[1]+n|0,r[2]=r[2]+s|0,r[3]=r[3]+o|0,r[4]=r[4]+l|0},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;return t[i>>>5]|=128<<24-i%32,t[14+(i+64>>>9<<4)]=Math.floor(r/4294967296),t[15+(i+64>>>9<<4)]=r,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}}),t.SHA1=n._createHelper(o),t.HmacSHA1=n._createHmacHelper(o),e.SHA1;var t,r,i,n,s,a,o}(ao);!function(e){(function(t){var r=e,i=r.lib,n=i.WordArray,s=i.Hasher,a=r.algo,o=[],l=[];!function(){function e(e){for(var r=t.sqrt(e),i=2;i<=r;i++)if(!(e%i))return!1;return!0}function r(e){return 4294967296*(e-(0|e))|0}for(var i=2,n=0;n<64;)e(i)&&(n<8&&(o[n]=r(t.pow(i,.5))),l[n]=r(t.pow(i,1/3)),n++),i++}();var c=[],u=a.SHA256=s.extend({_doReset:function(){this._hash=new n.init(o.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],n=r[1],s=r[2],a=r[3],o=r[4],u=r[5],d=r[6],h=r[7],f=0;f<64;f++){if(f<16)c[f]=0|e[t+f];else{var p=c[f-15],v=(p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3,g=c[f-2],_=(g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10;c[f]=v+c[f-7]+_+c[f-16]}var m=i&n^i&s^n&s,y=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),b=h+((o<<26|o>>>6)^(o<<21|o>>>11)^(o<<7|o>>>25))+(o&u^~o&d)+l[f]+c[f];h=d,d=u,u=o,o=a+b|0,a=s,s=n,n=i,i=b+(y+m)|0}r[0]=r[0]+i|0,r[1]=r[1]+n|0,r[2]=r[2]+s|0,r[3]=r[3]+a|0,r[4]=r[4]+o|0,r[5]=r[5]+u|0,r[6]=r[6]+d|0,r[7]=r[7]+h|0},_doFinalize:function(){var e=this._data,r=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;return r[n>>>5]|=128<<24-n%32,r[14+(n+64>>>9<<4)]=t.floor(i/4294967296),r[15+(n+64>>>9<<4)]=i,e.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});r.SHA256=s._createHelper(u),r.HmacSHA256=s._createHmacHelper(u)})(Math),e.SHA256}(ao);!function(e){(function(){var t=e,r=t.lib.WordArray;function i(e,t,i){for(var n=[],s=0,a=0;a<t;a++)if(a%4){var o=i[e.charCodeAt(a-1)]<<a%4*2|i[e.charCodeAt(a)]>>>6-a%4*2;n[s>>>2]|=o<<24-s%4*8,s++}return r.create(n,s)}t.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,i=this._map;e.clamp();for(var n=[],s=0;s<r;s+=3)for(var a=(t[s>>>2]>>>24-s%4*8&255)<<16|(t[s+1>>>2]>>>24-(s+1)%4*8&255)<<8|t[s+2>>>2]>>>24-(s+2)%4*8&255,o=0;o<4&&s+.75*o<r;o++)n.push(i.charAt(a>>>6*(3-o)&63));var l=i.charAt(64);if(l)for(;n.length%4;)n.push(l);return n.join("")},parse:function(e){var t=e.length,r=this._map,n=this._reverseMap;if(!n){n=this._reverseMap=[];for(var s=0;s<r.length;s++)n[r.charCodeAt(s)]=s}var a=r.charAt(64);if(a){var o=e.indexOf(a);-1!==o&&(t=o)}return i(e,t,n)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(),e.enc.Base64}(ao);var oo=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(io,"__esModule",{value:!0});const lo=oo(ao);io.default=class{constructor(e){let t;switch(e){case"sha1":t=lo.default.algo.SHA1;break;case"sha256":t=lo.default.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=lo.default.enc.Base64;break;case"hex":r=lo.default.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}};var co={};!function(e){var t,r,i;r=(t=e).lib.Base,i=t.enc.Utf8,t.algo.HMAC=r.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=i.parse(t));var r=e.blockSize,n=4*r;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var s=this._oKey=t.clone(),a=this._iKey=t.clone(),o=s.words,l=a.words,c=0;c<r;c++)o[c]^=1549556828,l[c]^=909522486;s.sigBytes=a.sigBytes=n,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher,r=t.finalize(e);return t.reset(),t.finalize(this._oKey.clone().concat(r))}})}(ao);var uo=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(co,"__esModule",{value:!0});const ho=uo(ao);co.default=class{constructor(e,t){let r;switch(e){case"sha1":r=ho.default.algo.SHA1;break;case"sha256":r=ho.default.algo.SHA256;break;default:throw new Error("unsupported hash algorithm. Only sha1 and sha256 are supported.")}this._cryptoJSHmac=ho.default.algo.HMAC.create(r,t)}digest(e){const t=this._cryptoJSHmac.finalize();if("base64"===e)return t.toString(ho.default.enc.Base64);if("hex"===e)return t.toString(ho.default.enc.Hex);throw new Error("unsupported output encoding. Only base64 and hex are supported.")}update(e){return this._cryptoJSHmac.update(e),this}};var fo=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ro,"__esModule",{value:!0});const po=e,vo=fo(io),go=fo(co);ro.default=class{createHash(e){return new vo.default(e)}createHmac(e,t){return new go.default(e,t)}randomUUID(){const e=new Uint32Array(1);return po.crypto.getRandomValues(e),e.join()}};var _o={};Object.defineProperty(_o,"__esModule",{value:!0});const mo=i;class yo{constructor(){this.headers={},this.status=0}text(){return Promise.resolve("")}json(){return Promise.resolve({})}}_o.default=class{fetch(e,t={}){return Promise.resolve(new yo)}createEventSource(e,t){return new mo.NullEventSource(e,t)}getEventSourceCapabilities(){return{readTimeout:!1,headers:!1,customMethod:!1}}};var bo=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(to,"__esModule",{value:!0});const Eo=bo(ro),So=bo(_o);to.default=class{constructor(e){this.crypto=new Eo.default,this.requests=new So.default,this.info=e}};var wo={};Object.defineProperty(wo,"__esModule",{value:!0});class Oo{constructor(e,t,r){this._platformName=e,this._sdkName=t,this._sdkVersion=r}platformData(){return{name:this._platformName}}sdkData(){return{name:this._sdkName,version:this._sdkVersion,userAgentBase:"AkamaiEdgeSDK"}}}wo.default=(e,t,r)=>new Oo(e,t,r),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)},s=t&&t.__rest||function(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r},a=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.init=e.EdgeFeatureStore=void 0;const o=i,l=a(Ha),c=Qa;Object.defineProperty(e,"EdgeFeatureStore",{enumerable:!0,get:function(){return c.EdgeFeatureStore}});const u=a(to),d=a(wo),h=qa;n(i,e);e.init=e=>{var t;const{sdkKey:r,options:i={},featureStoreProvider:n,platformName:a,sdkName:f,sdkVersion:p}=e,v=null!==(t=i.logger)&&void 0!==t?t:o.BasicLogger.get(),g=i,{cacheTtlMs:_}=g,m=s(g,["cacheTtlMs"]),y=new c.EdgeFeatureStore(n,r,"Akamai",v,null!=_?_:100),b=Object.assign({featureStore:y,logger:v},m);(0,h.validateOptions)(e.sdkKey,b);const E=(0,d.default)(a,f,p);return new l.default(r,new u.default(E),b)}}(r);exports.init=({options:e={},sdkKey:t,featureStoreProvider:i})=>r.init({sdkKey:t,options:e,featureStoreProvider:i,platformName:"Akamai EdgeWorker",sdkName:"@launchdarkly/akamai-server-base-sdk",sdkVersion:"3.0.32"});
1
+ "use strict";var e=require("crypto"),t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},r={},i={},n={};Object.defineProperty(n,"__esModule",{value:!0});n.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 s={},a={};!function(e){function t(e){return e.indexOf("~")?e.replace(/~1/g,"/").replace(/~0/g,"~"):e}class r{constructor(e,r=!1){if(r){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:r}=this;if(!r)return;let i=e;for(let e=0;e<t.length;e+=1){const r=t[e];if(null==i||!Object.prototype.hasOwnProperty.call(i,r)||"object"!=typeof i||Array.isArray(i))return;i=i[r]}return i}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,r)=>t===e.getComponent(r))}get components(){return[...this._components]}}r.InvalidReference=new r("");class i{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 c{is(e){return"boolean"==typeof e||null==e}getType(){return"boolean | undefined | null"}}const u=/^\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&&u.test(e)}getType(){return"date"}}class h extends o{constructor(){super(/^(\w|\.|-)+$/)}is(e){return super.is(e)&&"kind"!==e}}class f{constructor(e){this._values=e}is(e){return"string"==typeof e&&this._values.includes(e)}getType(){return this._values.join(" | ")}}function p(e){return null==e}class v{static createTypeArray(e,t){return new s(e,t)}static numberWithMin(e){return new a(e)}static stringMatchingRegex(e){return new o(e)}static oneOf(...e){return new f(e)}}function g(e){return"kind"in e&&(v.String.is(e.kind)&&"multi"!==e.kind)}function _(e){return"kind"in e&&(v.String.is(e.kind)&&"multi"===e.kind)}function m(e){return!("kind"in e)||null===e.kind||void 0===e.kind}function y(e,t=[]){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(t.includes(e))throw new Error("Cycle detected");if(Array.isArray(e)){return`[${e.map(r=>y(r,[...t,e])).map(e=>void 0===e?"null":e).join(",")}]`}return`{${Object.keys(e).sort().map(r=>{const i=y(e[r],[...t,e]);if(void 0!==i)return`${JSON.stringify(r)}:${i}`}).filter(e=>void 0!==e).join(",")}}`}v.String=new n("string",""),v.Number=new n("number",0),v.ObjectOrFactory=new i,v.Object=new n("object",{}),v.StringArray=new s("string[]",""),v.Boolean=new n("boolean",!0),v.Function=new l,v.Date=new d,v.Kind=new h,v.NullableBoolean=new c;const b="user";function E(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}function S(e){return v.Kind.is(e)}function w(e){return v.String.is(e)&&""!==e}function O(e,t=!1){return e?e.map(e=>new r(e,t)):[]}class k{constructor(e,t,r){this._isMulti=!1,this._isUser=!1,this._wasLegacy=!1,this._contexts={},this.kind=t,this.valid=e,this.message=r}static _contextForError(e,t){return new k(!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),r=t.every(S);if(!t.length)return k._contextForError("multi","A multi-kind context must contain at least one kind");if(!r)return k._contextForError("multi","Context contains invalid kinds");const i={};let n=!0;const s=t.reduce((t,r)=>{const s=e[r];var a;return(a=s)&&v.Object.is(a)?(t[r]=s,i[r]=O(s._meta?.privateAttributes)):n=!1,t},{});if(!n)return k._contextForError("multi","Context contained contexts that were not objects");if(!Object.values(s).every(e=>w(e.key)))return k._contextForError("multi","Context contained invalid keys");if(1===t.length){const e=t[0],r=new k(!0,e);return r._context={...s[e],kind:e},r._privateAttributeReferences=i,r._isUser="user"===e,r}const a=new k(!0,e.kind);return a._contexts=s,a._privateAttributeReferences=i,a._isMulti=!0,a}static _fromSingleKindContext(e){const{key:t,kind:r}=e,i=S(r),n=w(t);if(!i)return k._contextForError(r??"unknown","The kind was not valid for the context");if(!n)return k._contextForError(r,"The key for the context was not valid");const s=O(e._meta?.privateAttributes),a=new k(!0,r);return a._isUser="user"===r,a._context=e,a._privateAttributeReferences={[r]:s},a}static _fromLegacyUser(e){if(!(void 0!==e.key&&null!==e.key))return k._contextForError("user","The key for the context was not valid");const t=new k(!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 r=!!e.anonymous;delete t.anonymous,t.anonymous=r}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:O(e.privateAttributeNames,!0)},t}static fromLDContext(e){return e?g(e)?k._fromSingleKindContext(e):_(e)?k._fromMultiKindContext(e):m(e)?k._fromLegacyUser(e):k._contextForError("unknown","Context was not of a valid kind"):k._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 r={kind:"multi"};return t.forEach(e=>{const t=e[0],i=e[1];r[t]=i}),r}valueForKind(e,t=b){return e.isKind?this.kinds:k._getValueFromContext(e,this._contextForKind(t))}key(e=b){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}:${E(this._contexts[e].key)}`).join(":"):`${this.kind}:${E(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,r])=>(e[t]=r.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}canonicalUnfilteredJson(){if(this.valid){if(this._cachedCanonicalJson)return this._cachedCanonicalJson;try{this._cachedCanonicalJson=y(k.toLDContext(this))}catch{}return this._cachedCanonicalJson}}}k.UserKind=b;const D=["key","kind","_meta","anonymous"].map(e=>new r(e,!0)),T=["name","ip","firstName","lastName","email","avatar","country"];class P{constructor(e,t){this._allAttributesPrivate=e,this._privateAttributes=t}filter(e,t=!1){const r=e.getContexts();if(1===r.length)return this._filterSingleKind(e,r[0][1],r[0][0],t);const i={kind:"multi"};return r.forEach(([r,n])=>{i[r]=this._filterSingleKind(e,n,r,t)}),i}_getAttributesToFilter(e,t,i,n){return(n?Object.keys(t).map(e=>new r(e,!0)):[...this._privateAttributes,...e.privateAttributes(i)]).filter(e=>!D.some(t=>t.compare(e)))}_filterSingleKind(e,t,r,i){const n=this._allAttributesPrivate||i&&!0===t.anonymous,{cloned:s,excluded:a}=function(e,t){const r=[],i={},n=[];for(r.push(...Object.keys(e).map(t=>({key:t,ptr:[t],source:e,parent:i,visited:[e]})));r.length;){const e=r.pop(),i=t.find(t=>{return r=t,i=e.ptr,r.depth===i.length&&i.every((e,t)=>e===r.getComponent(t));var r,i});if(i)n.push(i.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]={},r.push(...Object.keys(t).map(r=>({key:r,ptr:[...e.ptr,r],source:t,parent:e.parent[e.key],visited:[...e.visited,t]})))):e.parent[e.key]=t}}return{cloned:i,excluded:n.sort()}}(t,this._getAttributesToFilter(e,t,r,n));return e.legacy&&T.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}}class I{constructor(e,t,r=Math.random){this._retryResetIntervalMillis=t,this._random=r,this._retryCount=0,this._initialRetryDelayMillis=Math.max(1,e),this._maxExponent=Math.ceil(Math.log2(3e4/this._initialRetryDelayMillis))}_backoff(){const e=Math.min(this._retryCount,this._maxExponent),t=this._initialRetryDelayMillis*2**e;return Math.min(t,3e4)}_jitter(e){return e-Math.trunc(.5*this._random()*e)}success(e=Date.now()){this._activeSince=e}fail(e=Date.now()){void 0!==this._activeSince&&e-this._activeSince>this._retryResetIntervalMillis&&(this._retryCount=0),this._activeSince=void 0;const t=this._jitter(this._backoff());return this._retryCount+=1,t}}class x{constructor(e,t){this._dataCallback=e,this._statusCallback=t,this._disabled=!1}disable(){this._disabled=!0}async dataHandler(e,t){this._disabled||this._dataCallback(e,t)}async statusHandler(e,t){this._disabled||this._statusCallback(e,t)}}var R;!function(e){e[e.Valid=0]="Valid",e[e.Initializing=1]="Initializing",e[e.Interrupted=2]="Interrupted",e[e.Closed=3]="Closed"}(R||(R={}));class M{constructor(e,t){this._list=t?[...t]:[],this._circular=e,this._pos=0}next(){if(this._list.length<=0||this._pos>=this._list.length)return;const e=this._list[this._pos];return this._circular?this._pos=(this._pos+1)%this._list.length:this._pos+=1,e}replace(e){this._list=[...e],this._pos=0}remove(e){const t=this._list.indexOf(e);return!(t<0)&&(this._list.splice(t,1),this._list.length>0&&(t<this._pos&&(this._pos-=1),this._circular&&this._pos>this._list.length-1&&(this._pos=0)),!0)}reset(){this._pos=0}pos(){return this._pos}length(){return this._list.length}clear(){this._list=[],this._pos=0}}class F extends Error{constructor(e){super(e),this.name="LaunchDarklyFileDataSourceError"}}class A extends Error{constructor(e,t,r,i=!0){super(t),this.kind=e,this.status=r,this.name="LaunchDarklyPollingError",this.recoverable=i}}class C extends Error{constructor(e,t,r,i=!0){super(t),this.kind=e,this.code=r,this.name="LaunchDarklyStreamingError",this.recoverable=i}}class L extends Error{constructor(e,t,r){super(t),this.kind=e,this.code=r,this.name="LDFlagDeliveryFallbackError",this.recoverable=!1}}var j,N,$,V;e.DataSourceErrorKind=void 0,(j=e.DataSourceErrorKind||(e.DataSourceErrorKind={})).Unknown="UNKNOWN",j.NetworkError="NETWORK_ERROR",j.ErrorResponse="ERROR_RESPONSE",j.InvalidData="INVALID_DATA",e.AutoEnvAttributes=void 0,(N=e.AutoEnvAttributes||(e.AutoEnvAttributes={}))[N.Disabled=0]="Disabled",N[N.Enabled=1]="Enabled",function(e){e[e.AnalyticsEvents=0]="AnalyticsEvents",e[e.DiagnosticEvent=1]="DiagnosticEvent"}($||($={})),function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.FailedAndMustShutDown=2]="FailedAndMustShutDown"}(V||(V={}));var U=Object.freeze({__proto__:null,get DataSourceState(){return R},get LDDeliveryStatus(){return V},get LDEventType(){return $}});function K(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 z={s:e=>K(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=>K(e),o:e=>K(e),O:e=>K(e),c:()=>""};function B(...e){const t=e.shift();if(v.String.is(t)){let r="",i=0;for(;i<t.length;){const n=t.charAt(i);if("%"===n){if(i+1<t.length){const n=t.charAt(i+1);if(n in z&&e.length){const t=e.shift();r+=z[n]?.(t)}else r+="%"===n?"%":`%${n}`;i+=2}}else r+=n,i+=1}return e.length&&(r.length&&(r+=" "),r+=e.map(K).join(" ")),r}return e.map(K).join(" ")}var H;!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"}(H||(H={}));const q=["debug","info","warn","error","none"];class G{static get(){return new G({})}constructor(e){if(this._logLevel=H[e.level??"info"]??H.info,this._name=e.name??"LaunchDarkly",this._formatter=e.formatter,"object"==typeof e.destination)this._destinations={[H.debug]:e.destination.debug,[H.info]:e.destination.info,[H.warn]:e.destination.warn,[H.error]:e.destination.error};else if("function"==typeof e.destination){const{destination:t}=e;this._destinations={[H.debug]:t,[H.info]:t,[H.warn]:t,[H.error]:t}}}_tryFormat(...e){try{return this._formatter?this._formatter?.(...e):B(...e)}catch{return B(...e)}}_tryWrite(e,t){try{e(t)}catch{console.error(t)}}_log(e,t){if(e>=this._logLevel){const r=`${q[e]}: [${this._name}]`;try{const i=this._destinations?.[e];i?this._tryWrite(i,`${r} ${this._tryFormat(...t)}`):console.error(...t)}catch{console.error(...t)}}}error(...e){this._log(H.error,e)}warn(...e){this._log(H.warn,e)}info(...e){this._log(H.info,e)}debug(...e){this._log(H.debug,e)}}const W={error:v.Function,warn:v.Function,info:v.Function,debug:v.Function};class J{constructor(e,t){Object.entries(W).forEach(([t,r])=>{if(!r.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 X{static deprecated(e,t){return`"${e}" is deprecated, please use "${t}"`}static optionBelowMinimum(e,t,r){return`Config option "${e}" had invalid value of ${t}, using minimum of ${r} instead`}static unknownOption(e){return`Ignoring unknown config option "${e}"`}static wrongOptionType(e,t,r){return`Config option "${e}" should be of type ${t}, got ${r}, 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 Y=v.stringMatchingRegex(/^(\w|\.|-)+$/),Z=(e,t)=>Y.is(e)?e.length>64?{valid:!1,message:X.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:X.invalidTagValue(t)};function Q(e){return e.replace(/\/+$/,"")}function ee(e){return e.replace(/^\/+/,"").replace(/\?$/,"")}class te{constructor(e,t,r=te.DEFAULT_EVENTS,i="/bulk",n="/diagnostic",s=!0,a){this.streaming=Q(e),this.polling=Q(t),this.events=Q(r),this.analyticsEventPath=i,this.diagnosticEventPath=n,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}}function re(e,t=[]){if(0===t.length)return e;return`${e}?${t.map(({key:e,value:t})=>`${e}=${t}`).join("&")}`}function ie(e,t,r=[]){const i=ee(t);return re(`${e.events}/${i}`,r)}te.DEFAULT_EVENTS="https://events.launchdarkly.com";class ne extends Error{constructor(e){super(e),this.name="LaunchDarklyUnexpectedResponseError"}}class se extends Error{constructor(e){super(e),this.name="LaunchDarklyClientError"}}class ae extends Error{constructor(e){super(e),this.name="LaunchDarklyTimeoutError"}}function oe(e){return!(e>=400&&e<500)||(400===e||408===e||429===e)}function le(e){return 413===e||oe(e)}const ce=(e,t)=>e?Object.entries(e).reduce((e,[r,i])=>(!Boolean(i)||(e=>"{}"===JSON.stringify(e))(i)||t?.includes(r)||(e[r]="object"==typeof i?ce(i,t):i),e),{}):e;function ue(e,t,r){let i;i=e.status?`error ${e.status}${401===e.status?" (invalid SDK key)":""}`:`I/O error (${e.message||"unknown error"})`;return`Received ${i} for ${t} - ${r??"giving up permanently"}`}const de=async(e=1e3)=>new Promise(e=>{});var he;!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"}(he||(he={}));var fe=he;class pe{static invalidMetricValue(e){return`The track function was called with a non-numeric "metricValue" (${e}), only numeric metric values are supported.`}}pe.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";class ve{constructor(e,t){const{basicConfiguration:r,platform:i}=e,{serviceEndpoints:{analyticsEventPath:n,diagnosticEventPath:s}}=r,{crypto:a,requests:o}=i;this._defaultHeaders={...t},this._eventsUri=ie(r.serviceEndpoints,n,[]),this._diagnosticEventsUri=ie(r.serviceEndpoints,s,[]),this._requests=o,this._crypto=a}async _tryPostingEvents(e,t,r,i){const n={status:V.Succeeded},s={...this._defaultHeaders,"content-type":"application/json"};let a;r&&(s["x-launchdarkly-payload-id"]=r,s["x-launchDarkly-event-schema"]="4");try{const{status:r,headers:i}=await this._requests.fetch(t,{headers:s,body:JSON.stringify(e),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),o=Date.parse(i.get("date")||"");if(o&&(n.serverTime=o),r<=204)return n;if(a=new ne(ue({status:r,message:"some events were dropped"},"event posting")),!oe(r))return le(r)?n.status=V.Failed:n.status=V.FailedAndMustShutDown,n.error=a,n}catch(e){a=e}return a&&!i?(n.status=V.Failed,n.error=a,n):(await de(),this._tryPostingEvents(e,this._eventsUri,r,!1))}async sendEventData(e,t){const r=e===$.AnalyticsEvents?this._crypto.randomUUID():void 0,i=e===$.AnalyticsEvents?this._eventsUri:this._diagnosticEventsUri;return this._tryPostingEvents(t,i,r,!0)}}function ge(e){return"feature"===e.kind}class _e{constructor(e,t,r,i,n,s){this.count=e,this.key=t,this.value=r,this.version=n,this.variation=s,this.default=i}increment(){this.count+=1}}class me{constructor(e=!1,t){this._singleContext=e,this._contextFilter=t,this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}summarizeEvent(e){if(ge(e)&&!e.excludeFromSummaries){this._context||(this._context=e.context);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),r=this._counters[t];let i=this._contextKinds[e.key];i||(i=new Set,this._contextKinds[e.key]=i),e.context.kinds.forEach(e=>i.add(e)),r?r.increment():this._counters[t]=new _e(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 r=e[t.key];r||(r={default:t.default,counters:[],contextKinds:[...this._contextKinds[t.key]]},e[t.key]=r);const i={value:t.value,count:t.count};return void 0!==t.variation&&null!==t.variation&&(i.variation=t.variation),void 0!==t.version&&null!==t.version?i.version=t.version:i.unknown=!0,r.counters.push(i),e},{}),t={startDate:this._startDate,endDate:this._endDate,features:e,kind:"summary",context:void 0!==this._context&&this._singleContext?this._contextFilter?.filter(this._context):void 0};return this._clearSummary(),t}_clearSummary(){this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}}class ye extends Error{constructor(e){super(e),this.name="LaunchDarklyInvalidSDKKeyError"}}class be{constructor(e,t){this._contextFilter=e,this._logger=t,this._summarizers={}}summarizeEvent(e){if(ge(e)){const t=e.context.canonicalUnfilteredJson();if(!t)return void(e.context.valid&&this._logger?.error("Unable to serialize context, likely the context contains a cycle."));let r=this._summarizers[t];r||(this._summarizers[t]=new me(!0,this._contextFilter),r=this._summarizers[t]),r.summarizeEvent(e)}}getSummaries(){const e=this._summarizers;return this._summarizers={},Object.values(e).map(e=>e.getSummary())}}function Ee(e){const t=Math.trunc(e);return 1===t||0!==t&&0===Math.floor(Math.random()*t)}class Se{constructor(e,t,r,i,n=1,s){this.context=e,this.key=t,this.data=r,this.metricValue=i,this.samplingRatio=n,this.url=s,this.kind="custom",this.creationDate=Date.now(),this.context=e}}class we{constructor(e,t,r,i,n,s,a,o,l,c,u,d,h=1){this.withReasons=e,this.context=t,this.key=r,this.samplingRatio=h,this.kind="feature",this.creationDate=Date.now(),this.value=i,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!==c&&(this.reason=c),void 0!==u&&(this.debugEventsUntilDate=u),void 0!==d&&(this.excludeFromSummaries=d)}}class Oe{constructor(e,t=1){this.context=e,this.samplingRatio=t,this.kind="identify",this.creationDate=Date.now()}}const ke="FDv1Fallback";const De={type:"none"};function Te(e,t){let r="inactive",i="partial",n=[];function s(){r="inactive",i="partial",n=[]}function a(e){if(!e.payloads?.length)return{type:"error",kind:"MISSING_PAYLOAD",message:"No payload present in server-intent"};const s=e.payloads[0];switch(s?.intentCode){case"xfer-full":return r="full",n=[],i="full",De;case"xfer-changes":return r="changes",n=[],i="partial",De;case"none":return r="changes",n=[],i="partial",p((a=s).target)?(t?.warn(`Ignoring 'none' intent with missing fields: target=${a.target}`),De):{type:"payload",payload:{version:a.target,type:"none",updates:[]}};default:return t?.warn(`Unable to process intent code '${s?.intentCode}'.`),De}var a}function o(i){if("inactive"===r)return t?.warn("Received put-object before server-intent was established. Ignoring."),De;if(!i.kind||!i.key||p(i.version)||!i.object)return t?.warn(`Ignoring put-object with missing fields: kind=${i.kind}, key=${i.key}, version=${i.version}`),De;const s=(a=i.kind,o=i.object,e[a]?.(o));var a,o;return s?(n.push({kind:i.kind,key:i.key,version:i.version,object:s}),De):(t?.warn(`Unable to process object for kind: '${i.kind}'`),De)}function l(e){if("inactive"===r)return{type:"error",kind:"PROTOCOL_ERROR",message:"A payload transferred has been received without an intent having been established."};if(p(e.state)||p(e.version))return t?.warn(`Ignoring payload-transferred with missing fields: state=${e.state}, version=${e.version}`),s(),De;const a={type:"payload",payload:{version:e.version,state:e.state,type:i,updates:n}};return r="changes",i="partial",n=[],a}function c(e){return t?.info(`An issue was encountered receiving updates with reason: ${e.reason}.`),n=[],{type:"serverError",id:e.payload_id,reason:e.reason}}return{get state(){return r},processEvent(e){switch(e.event){case"server-intent":return a(e.data);case"put-object":return o(e.data);case"delete-object":return function(e){return"inactive"===r?(t?.warn("Received delete-object before server-intent was established. Ignoring."),De):e.kind&&e.key&&!p(e.version)?(n.push({kind:e.kind,key:e.key,version:e.version,deleted:!0}),De):(t?.warn(`Ignoring delete-object with missing fields: kind=${e.kind}, key=${e.key}, version=${e.version}`),De)}(e.data);case"payload-transferred":return l(e.data);case"goodbye":return function(e){return t?.info(`Goodbye was received from the LaunchDarkly connection with reason: ${e.reason}.`),s(),{type:"goodbye",reason:e.reason}}(e.data);case"error":return c(e.data);case"heart-beat":return De;default:return{type:"error",kind:"UNKNOWN_EVENT",message:`Received an unknown event of type '${e.event}'`}}},reset(){s()}}}class Pe{constructor(e,t,r){this._errorHandler=t,this._logger=r,this._listeners=[],this._handler=Te(e,r)}addPayloadListener(e){this._listeners.push(e)}removePayloadListener(e){const t=this._listeners.indexOf(e,0);t>-1&&this._listeners.splice(t,1)}processEvents(t){t.forEach(t=>{const r=this._handler.processEvent(t);switch(r.type){case"payload":this._listeners.forEach(e=>e(r.payload));break;case"error":"MISSING_PAYLOAD"===(i=r.kind)||"PROTOCOL_ERROR"===i?this._errorHandler?.(e.DataSourceErrorKind.InvalidData,r.message):this._logger?.warn(r.message)}var i})}}const Ie="unknown plugin";function xe(e,t){try{return t.getMetadata().name||Ie}catch{return e.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),Ie}}var Re=Object.freeze({__proto__:null,ClientMessages:pe,DiagnosticsManager:class{constructor(e,t,r){this._platform=t,this._diagnosticInitConfig=r,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,r){const i={timestamp:e,failed:t,durationMillis:r};this._streamInits.push(i)}createStatsEventAndReset(e,t,r){const i=Date.now(),n={kind:"diagnostic",id:this._id,creationDate:i,dataSinceDate:this._dataSinceDate,droppedEvents:e,deduplicatedUsers:t,eventsInLastBatch:r,streamInits:this._streamInits};return this._streamInits=[],this._dataSinceDate=i,n}},ErrorKinds:fe,EventFactoryBase:class{constructor(e){this._withReasons=e}evalEvent(e){return new we(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,r){return new we(this._withReasons,r,e,t,t,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(e){return new Oe(e,1)}customEvent(e,t,r,i,n=1){return new Se(t,e,r??void 0,i??void 0,n)}},EventProcessor:class{constructor(e,t,i,n,s,a=!0,o=!1){this._config=e,this._contextDeduplicator=n,this._diagnosticsManager=s,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 ve(t,i),this._contextFilter=new P(e.allAttributesPrivate,e.privateAttributes.map(e=>new r(e))),this._summarizer=o?new be(this._contextFilter,this._logger):new me,a&&this.start()}start(){if(void 0!==this._contextDeduplicator?.flushInterval&&(this._flushUsersTimer=void this._contextDeduplicator.flushInterval),this._flushTimer=void this._config.flushInterval,this._diagnosticsManager){const e=this._diagnosticsManager.createInitEvent();this._postDiagnosticEvent(e),this._diagnosticsTimer=void this._config.diagnosticRecordingInterval}this._logger?.debug("Started EventProcessor.")}_postDiagnosticEvent(e){this._eventSender.sendEventData($.DiagnosticEvent,e)}close(){clearInterval(this._flushTimer),this._flushUsersTimer&&clearInterval(this._flushUsersTimer),this._diagnosticsTimer&&clearInterval(this._diagnosticsTimer)}async flush(){if(this._shutdown)throw new ye("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;if(this._queue=[],void 0!==this._summarizer.getSummaries){this._summarizer.getSummaries().forEach(t=>{Object.keys(t.features).length&&e.push(t)})}else{const t=this._summarizer.getSummary();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(Ee(e.samplingRatio)){const t={...e,context:e.context?this._contextFilter.filter(e.context,this._config.redactAnonymousAllEvents??!1):void 0};1===t.samplingRatio&&delete t.samplingRatio,this._enqueue(t)}return}this._summarizer.summarizeEvent(e);const t=ge(e),r=t&&e.trackEvents||!t,i=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)),r&&Ee(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!1)),i&&Ee(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!0))}_makeOutputEvent(e,t){switch(e.kind){case"feature":{const r={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&&(r.samplingRatio=e.samplingRatio),e.prereqOf&&(r.prereqOf=e.prereqOf),void 0!==e.variation&&(r.variation=e.variation),void 0!==e.version&&(r.version=e.version),e.reason&&(r.reason=e.reason),r}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,context:this._contextFilter.filter(e.context,this._config.redactAnonymousAllEvents??!1)};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 ge(e)&&e.debugEventsUntilDate&&e.debugEventsUntilDate>this._lastKnownPastTime&&e.debugEventsUntilDate>Date.now()}async _tryPostingEvents(e){const t=await this._eventSender.sendEventData($.AnalyticsEvents,e);if(t.status===V.FailedAndMustShutDown&&(this._shutdown=!0),t.serverTime&&(this._lastKnownPastTime=t.serverTime),t.error)throw t.error}},FDv1PayloadAdaptor:function(e){return{_processor:e,_selector:"",useSelector(e){return this._selector=e,this},processFullTransfer(e){const t=[{event:"server-intent",data:{payloads:[{id:ke,target:1,intentCode:"xfer-full",reason:"payload-missing"}]}}];Object.entries(e?.flags||[]).forEach(([e,r])=>{t.push({event:"put-object",data:{kind:"flag",key:e,version:r.version||1,object:r}})}),Object.entries(e?.segments||[]).forEach(([e,r])=>{t.push({event:"put-object",data:{kind:"segment",key:e,version:r.version||1,object:r}})}),t.push({event:"payload-transferred",data:{state:this._selector,version:1,id:ke}}),this._processor.processEvents(t)}}},InputCustomEvent:Se,InputEvalEvent:we,InputIdentifyEvent:Oe,NullEventProcessor:class{close(){}async flush(){}sendEvent(){}},PayloadProcessor:Pe,PayloadStreamReader:class{constructor(e,t,r,i){this._errorHandler=r,this._logger=i,this._attachHandler(e,"server-intent"),this._attachHandler(e,"put-object"),this._attachHandler(e,"delete-object"),this._attachHandler(e,"payload-transferred"),this._attachHandler(e,"goodbye"),this._attachHandler(e,"error"),this._payloadProcessor=new Pe(t,r,i)}addPayloadListener(e){this._payloadProcessor.addPayloadListener(e)}removePayloadListener(e){this._payloadProcessor.removePayloadListener(e)}_attachHandler(t,r){t.addEventListener(r,async t=>{if(t?.data){this._logger?.debug(`Received ${r} event. Data is ${t.data}`);try{this._payloadProcessor.processEvents([{event:r,data:JSON.parse(t.data)}])}catch{this._logger?.error(`Stream received data that was unable to be processed in "${r}" message`),this._logger?.debug(`Data follows: ${t.data}`),this._errorHandler?.(e.DataSourceErrorKind.InvalidData,"Malformed data in EventStream.")}}else this._errorHandler?.(e.DataSourceErrorKind.Unknown,"Event from EventStream missing data.")})}},canonicalize:y,createProtocolHandler:Te,initMetadataFromHeaders:function(e){if(e){const t=Object.keys(e).find(e=>"x-ld-envid"===e.toLowerCase());if(t)return{environmentId:e[t]}}},isLegacyUser:m,isMultiKind:_,isSingleKind:g,readFallbackDirective:function(e){const t=e.get("x-ld-fd-fallback");if(null===t||"true"!==t.toLowerCase())return{fdv1Fallback:!1};const r=e.get("x-ld-fd-fallback-ttl");if(null===r)return{fdv1Fallback:!0};const i=parseInt(r,10);return Number.isNaN(i)?{fdv1Fallback:!0}:{fdv1Fallback:!0,fdv1FallbackTtlMs:1e3*Math.max(0,i)}},readGoodbyeFallbackDirective:function(e){const t=e?.protocolFallbackTTL;return"number"==typeof t&&Number.isFinite(t)?{fdv1Fallback:!0,fdv1FallbackTtlMs:1e3*Math.max(0,t)}:{fdv1Fallback:!1}},safeGetHooks:function(e,t,r){const i=[];return r.forEach(r=>{try{const n=r.getHooks?.(t);void 0===n?e.error(`Plugin ${xe(e,r)} returned undefined from getHooks.`):n&&n.length>0&&i.push(...n)}catch(t){e.error(`Exception thrown getting hooks for plugin ${xe(e,r)}. Unable to get hooks.`)}}),i},safeGetName:xe,safeRegisterPlugins:function(e,t,r,i){i.forEach(i=>{try{i.register(r,t)}catch(t){e.error(`Exception thrown registering plugin ${xe(e,i)}.`)}})},shouldSample:Ee});e.ApplicationTags=class{constructor(e){const t={},r=e?.application,i=e?.logger;r&&Object.entries(r).forEach(([e,r])=>{if(null!=r){const{valid:n,message:s}=Z(r,`application.${e}`);n?"versionName"===e?t["application-version-name"]=[r]:t[`application-${e}`]=[r]:i?.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=r,e.BasicLogger=G,e.ClientContext=class{constructor(e,t,r){this.platform=r,this.basicConfiguration={tags:t.tags,logger:t.logger,offline:t.offline,serviceEndpoints:t.serviceEndpoints,sdkKey:e}}},e.CompositeDataSource=class{constructor(e,t,r,i,n={[R.Valid]:{durationMS:3e5,transition:"recover"},[R.Interrupted]:{durationMS:12e4,transition:"fallback"}},s=new I(1e3,3e4)){this._logger=i,this._transitionConditions=n,this._backoff=s,this._fdv1FallbackEngaged=!1,this._stopped=!0,this._cancelTokens=[],this._cancellableDelay=e=>{let t;return{promise:new Promise((e,r)=>{t=e=>{e()}}),cancel(){t&&(clearTimeout(t),t=void 0)}}},this._externalTransitionPromise=new Promise(e=>{this._externalTransitionResolve=e}),this._initPhaseActive=e.length>0,this._initFactories=new M(!1,e),this._syncFactories=new M(!0,t),this._fdv1Synchronizers=new M(!0,r)}async start(e,t,r){if(!this._stopped)return void this._logger?.info("CompositeDataSource already running. Ignoring call to start.");this._stopped=!1,this._logger?.debug(`CompositeDataSource starting with (${this._initFactories.length()} initializers, ${this._syncFactories.length()} synchronizers).`);const i=this._wrapStatusCallbackWithSanitizer(t);let n;for(i(R.Initializing);;){const{dataSource:s,isPrimary:a,cullDSFactory:o}=this._pickDataSource(n),l=new Promise(t=>{if(s){let n,l=()=>{};const c=(e,r)=>{this._fdv1Synchronizers.length()>0?this._logger?.warn("Falling back to FDv1"):this._logger?.warn("FDv1 fallback was requested but no FDv1 fallback synchronizer is configured; data source will terminate"),this._fdv1FallbackEngaged=!0,this._syncFactories=this._fdv1Synchronizers,i(e,r),this._consumeCancelToken(l),t({transition:"switchToSync",err:r})},u=new x((r,n)=>{if(this._backoff.success(),e(r,n),n?.fallbackToFDv1&&!this._fdv1FallbackEngaged)return u.disable(),void c(R.Interrupted,void 0);r&&this._initPhaseActive&&(u.disable(),this._consumeCancelToken(l),i(R.Interrupted),t({transition:"switchToSync"}))},(e,r)=>{if(this._logger?.debug(`CompositeDataSource received state ${e} from underlying data source. Err is ${r}`),r||e===R.Closed){if(u.disable(),!1===r?.recoverable&&(this._logger?.debug(`Culling data source due to err ${r}`),o?.()),r instanceof L&&!this._fdv1FallbackEngaged)return void c(e,r);i(e,r),this._consumeCancelToken(l),t({transition:"fallback",err:r})}else if(i(e),e!==n){n=e,this._consumeCancelToken(l);const r=this._lookupTransitionCondition(e,a);if(r){const{promise:e,cancel:n}=this._cancellableDelay(r.durationMS);l=n,this._cancelTokens.push(l),e.then(()=>{this._consumeCancelToken(n),u.disable(),i(R.Interrupted),t({transition:r.transition})})}}});s.start((e,t)=>u.dataHandler(e,t),(e,t)=>u.statusHandler(e,t),r)}else t({transition:"stop",err:{name:"ExhaustedDataSources",message:"CompositeDataSource has exhausted all configured initializers and synchronizers."}})});let c=await Promise.race([l,this._externalTransitionPromise]);s?.stop();const u="switchToSync"===c.transition&&c.err instanceof L;if(c.err&&"stop"!==c.transition&&!u){const e=this._initPhaseActive?0:this._backoff.fail(),{promise:t,cancel:r}=this._cancellableDelay(e);this._cancelTokens.push(r);const i=t.then(()=>(this._consumeCancelToken(r),c));c=await Promise.race([i,this._externalTransitionPromise]),this._consumeCancelToken(r)}if(n=c.transition,"stop"===c.transition){t(R.Closed,c.err);break}}this._reset()}async stop(){this._cancelTokens.forEach(e=>e()),this._cancelTokens=[],this._externalTransitionResolve?.({transition:"stop"})}_reset(){this._stopped=!0,this._initPhaseActive=this._initFactories.length()>0,this._initFactories.reset(),this._syncFactories.reset(),this._fdv1Synchronizers.reset(),this._fdv1FallbackEngaged=!1,this._externalTransitionPromise=new Promise(e=>{this._externalTransitionResolve=e})}_pickDataSource(e){let t,r;switch(e){case"switchToSync":this._initPhaseActive=!1,this._syncFactories.reset(),r=0===this._syncFactories.pos(),t=this._syncFactories.next();break;case"recover":this._initPhaseActive?(this._initFactories.reset(),r=0===this._initFactories.pos(),t=this._initFactories.next()):(this._syncFactories.reset(),r=0===this._syncFactories.pos(),t=this._syncFactories.next());break;default:this._initPhaseActive&&this._initFactories.pos()>=this._initFactories.length()&&(this._initPhaseActive=!1,this._syncFactories.reset()),this._initPhaseActive?(r=0===this._initFactories.pos(),t=this._initFactories.next()):(r=0===this._syncFactories.pos(),t=this._syncFactories.next())}return t?{dataSource:t(),isPrimary:r,cullDSFactory:()=>{t&&this._syncFactories.remove(t)}}:{dataSource:void 0,isPrimary:r,cullDSFactory:void 0}}_lookupTransitionCondition(e,t){const r=this._transitionConditions[e];if(!t||"recover"!==r?.transition)return r}_consumeCancelToken(e){e();const t=this._cancelTokens.indexOf(e,0);t>-1&&this._cancelTokens.splice(t,1)}_wrapStatusCallbackWithSanitizer(e){let t,r,i=!1;return(n,s)=>{let a=n;if(n===R.Closed&&(a=R.Interrupted),a!==t||s!==r){if(a===R.Initializing){if(i)return;i=!0}t=a,r=s,e(a,s)}}}},e.Context=k,e.ContextFilter=P,e.DateValidator=d,e.DefaultBackoff=I,e.FactoryOrInstance=i,e.Function=l,e.KindValidator=h,e.LDClientError=se,e.LDFileDataSourceError=F,e.LDFlagDeliveryFallbackError=L,e.LDPollingError=A,e.LDStreamingError=C,e.LDTimeoutError=ae,e.LDUnexpectedResponseError=ne,e.NullableBoolean=c,e.NumberWithMinimum=a,e.OneOf=f,e.OptionMessages=X,e.SafeLogger=J,e.ServiceEndpoints=te,e.StringMatchingRegex=o,e.Type=n,e.TypeArray=s,e.TypeValidators=v,e.base64UrlEncode=(e,t)=>t.btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.cancelableTimedPromise=function(e,t){let r,i;return{promise:new Promise((e,t)=>{i=e,r=e=>{e()}}),cancel:()=>{i(),clearTimeout(r)}}},e.clone=function(e){return null==e?e:JSON.parse(JSON.stringify(e))},e.createSafeLogger=e=>{const t=new G({level:"info",destination:console.error,formatter:B});return e?new J(e,t):t},e.debounce=(e,t=5e3)=>{let r;return(...e)=>{clearTimeout(r),r=e=>{e()}}},e.deepCompact=ce,e.defaultHeaders=function(e,t,r,i=!0,n="user-agent",s){const{userAgentBase:a,version:o,wrapperName:l,wrapperVersion:c}=t.sdkData(),u={[n]:`${a??"NodeJSClient"}/${o}`};return i&&(u.authorization=e),l&&(u["x-launchdarkly-wrapper"]=c?`${l}/${c}`:l),r?.value&&(u["x-launchdarkly-tags"]=r.value),s&&(u["x-launchdarkly-instance-id"]=s),u},e.fastDeepEqual=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var i,n,s;if(Array.isArray(t)){if((i=t.length)!=r.length)return!1;for(n=i;0!==n--;)if(!e(t[n],r[n]))return!1;return!0}if(t instanceof Map&&r instanceof Map){if(t.size!==r.size)return!1;for(n of t.entries())if(!r.has(n[0]))return!1;for(n of t.entries())if(!e(n[1],r.get(n[0])))return!1;return!0}if(t instanceof Set&&r instanceof Set){if(t.size!==r.size)return!1;for(n of t.entries())if(!r.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(r)){if((i=t.length)!=r.length)return!1;for(n=i;0!==n--;)if(t[n]!==r[n])return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((i=(s=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(n=i;0!==n--;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=i;0!==n--;){var a=s[n];if(!e(t[a],r[a]))return!1}return!0}return t!=t&&r!=r},e.getEventsUri=ie,e.getPollingUri=function(e,t,r=[]){const i=ee(t),n=[...r];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),re(`${e.polling}/${i}`,n)},e.getStreamingUri=function(e,t,r){const i=ee(t),n=[...r];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),re(`${e.streaming}/${i}`,n)},e.httpErrorMessage=ue,e.internal=Re,e.isHttpLocallyRecoverable=le,e.isHttpRecoverable=oe,e.isNullish=p,e.noop=()=>{},e.secondsToMillis=function(e){return Math.trunc(1e3*e)},e.shouldRetry=function({status:e}){return!e||oe(e)},e.sleep=de,e.subsystem=U,e.timedPromise=(e,t)=>new Promise((e,t)=>{})}(a);var o={},l={},c={};Object.defineProperty(c,"__esModule",{value:!0});var u={};Object.defineProperty(u,"__esModule",{value:!0});var d,h={};Object.defineProperty(h,"__esModule",{value:!0}),h.IsMigrationStage=h.LDMigrationStage=void 0,function(e){e.Off="off",e.DualWrite="dualwrite",e.Shadow="shadow",e.Live="live",e.RampDown="rampdown",e.Complete="complete"}(d||(h.LDMigrationStage=d={})),h.IsMigrationStage=function(e){return Object.values(d).includes(e)};var f={};Object.defineProperty(f,"__esModule",{value:!0});var p,v={};Object.defineProperty(v,"__esModule",{value:!0}),v.LDConsistencyCheck=void 0,function(e){e[e.Inconsistent=0]="Inconsistent",e[e.Consistent=1]="Consistent",e[e.NotChecked=2]="NotChecked"}(p||(v.LDConsistencyCheck=p={})),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(c,e),i(u,e),i(h,e),i(f,e),i(v,e)}(l);var g={},_={};Object.defineProperty(_,"__esModule",{value:!0});var m={};Object.defineProperty(m,"__esModule",{value:!0});var y={};Object.defineProperty(y,"__esModule",{value:!0});var b={};Object.defineProperty(b,"__esModule",{value:!0});var E,S,w={};Object.defineProperty(w,"__esModule",{value:!0}),w.LDConcurrentExecution=w.LDSerialExecution=w.LDExecution=w.LDExecutionOrdering=void 0,function(e){e[e.Fixed=0]="Fixed",e[e.Random=1]="Random"}(E||(w.LDExecutionOrdering=E={})),function(e){e[e.Serial=0]="Serial",e[e.Concurrent=1]="Concurrent"}(S||(w.LDExecution=S={}));w.LDSerialExecution=class{constructor(e){this.ordering=e,this.type=S.Serial}};w.LDConcurrentExecution=class{constructor(){this.type=S.Concurrent}};var O={};Object.defineProperty(O,"__esModule",{value:!0}),O.isCustomOptions=O.isPollingOnlyOptions=O.isStreamingOnlyOptions=O.isStandardOptions=void 0,O.isStandardOptions=function(e){return"standard"===e.dataSourceOptionsType},O.isStreamingOnlyOptions=function(e){return"streamingOnly"===e.dataSourceOptionsType},O.isPollingOnlyOptions=function(e){return"pollingOnly"===e.dataSourceOptionsType},O.isCustomOptions=function(e){return"custom"===e.dataSourceOptionsType},function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(_,e),i(m,e),i(y,e),i(b,e),i(w,e),i(O,e)}(g);var k={};Object.defineProperty(k,"__esModule",{value:!0});var D={};Object.defineProperty(D,"__esModule",{value:!0});var T={};Object.defineProperty(T,"__esModule",{value:!0});var P={};Object.defineProperty(P,"__esModule",{value:!0});var I={};Object.defineProperty(I,"__esModule",{value:!0});var x={};Object.defineProperty(x,"__esModule",{value:!0});var R={},M={};Object.defineProperty(M,"__esModule",{value:!0});var F={};Object.defineProperty(F,"__esModule",{value:!0}),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(M,e),i(F,e)}(R);var A={},C={};Object.defineProperty(C,"__esModule",{value:!0});var L={};Object.defineProperty(L,"__esModule",{value:!0});var j={};Object.defineProperty(j,"__esModule",{value:!0});var N={};Object.defineProperty(N,"__esModule",{value:!0});var $={};Object.defineProperty($,"__esModule",{value:!0});var V={};Object.defineProperty(V,"__esModule",{value:!0});var U={};Object.defineProperty(U,"__esModule",{value:!0});var K={};Object.defineProperty(K,"__esModule",{value:!0});var z={};Object.defineProperty(z,"__esModule",{value:!0});var B={};Object.defineProperty(B,"__esModule",{value:!0}),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(C,e),i(L,e),i(j,e),i(N,e),i($,e),i(T,e),i(V,e),i(U,e),i(K,e),i(z,e),i(B,e)}(A);var H={},q={};Object.defineProperty(q,"__esModule",{value:!0});var G={};Object.defineProperty(G,"__esModule",{value:!0});var W={};Object.defineProperty(W,"__esModule",{value:!0}),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(q,e),i(G,e),i(P,e),i(W,e),i(I,e)}(H),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),e.subsystems=e.interfaces=e.integrations=void 0,i(l,e),i(g,e),i(k,e),i(D,e),i(T,e),i(P,e),i(I,e),i(x,e),e.integrations=R,e.interfaces=A,e.subsystems=H}(o);var J={},X={};Object.defineProperty(X,"__esModule",{value:!0});X.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 r=this._keyMap.get(e);void 0===r?(r=this._index(),this._keys[r]=e,this._keyMap.set(e,r),this._next[this._tail]=r,this._prev[r]=this._tail,this._tail=r,this._size+=1):this._setTail(r),this._values[r]=t,this._maxAge&&(this._lastUpdated[r]=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(J,"__esModule",{value:!0});const Y=a,Z=n,Q=X;J.default=class{constructor(e,t,r,i){this._store=e,this._logger=r,this._crypto=i,this.statusProvider=new Z.default(async()=>this._pollStoreAndUpdateStatus()),this._staleTimeMs=1e3*(Y.TypeValidators.Number.is(t.staleAfter)&&t.staleAfter>0?t.staleAfter:120);Y.TypeValidators.Number.is(t.statusPollInterval)&&t.statusPollInterval>0&&t.statusPollInterval;this._pollHandle=e?void 0:null,e&&(this._cache=new Q.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,r,i;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===(r=this._cache)||void 0===r||r.set(e,t)}catch(e){return null===(i=this._logger)||void 0===i||i.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,r;if(!this._store)return void this.statusProvider.setStatus({available:!1,stale:!1});let i;null===(e=this._logger)||void 0===e||e.debug("Querying Big Segment store status");try{const e=await this._store.getMetadata();i={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}`),i={available:!1,stale:!1}}const n=this.statusProvider.getStatus();n&&n.available===i.available&&n.stale===i.stale||(null===(r=this._logger)||void 0===r||r.debug("Big Segment store status changed from %s to %s",JSON.stringify(n),JSON.stringify(i)),this.statusProvider.setStatus(i),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 ee={};Object.defineProperty(ee,"__esModule",{value:!0}),ee.createPluginEnvironmentMetadata=void 0,ee.createPluginEnvironmentMetadata=function(e,t,r){const i={sdk:{name:e.info.sdkData().userAgentBase,version:e.info.sdkData().version},sdkKey:t};return e.info.sdkData().wrapperName&&(i.sdk.wrapperName=e.info.sdkData().wrapperName),e.info.sdkData().wrapperVersion&&(i.sdk.wrapperVersion=e.info.sdkData().wrapperVersion),r.applicationInfo&&(i.application=r.applicationInfo),i};var te={};Object.defineProperty(te,"__esModule",{value:!0}),te.createPayloadListener=void 0;te.createPayloadListener=(e,t,r=()=>{})=>i=>{const{initMetadata:n,payload:s}=i;if("full"===s.type)null==t||t.debug("Initializing all data");else{if(!(s.updates.length>0))return void(null==t||t.debug("Payload had no updates, ignoring."));null==t||t.debug("Applying updates")}const a={};s.updates.forEach(e=>{const r=(e=>{switch(e){case"flag":return"features";case"segment":return"segments";default:return e}})(e.kind);a[r]?a[r][e.key]=Object.assign(Object.assign({version:e.version},e.deleted&&{deleted:e.deleted}),e.object):a[r]={[e.key]:Object.assign(Object.assign({version:e.version},e.deleted&&{deleted:e.deleted}),e.object)},e.deleted?null==t||t.debug(`Deleting ${e.key} in ${e.kind}`):null==t||t.debug(`Updating ${e.key} in ${e.kind}`)}),e.applyChanges("full"===s.type,a,()=>{""!==s.state&&r()},n,s.state)};var re={},ie={},ne={};Object.defineProperty(ne,"__esModule",{value:!0});class se{static getKeyFromPath(e,t){return t.startsWith(e.streamApiPath)?t.substring(e.streamApiPath.length):void 0}}se.Features={namespace:"features",streamApiPath:"/flags/"},se.Segments={namespace:"segments",streamApiPath:"/segments/"},ne.default=se,Object.defineProperty(ie,"__esModule",{value:!0}),ie.deserializeSegment=ie.serializeSegment=ie.deserializeFlag=ie.serializeFlag=ie.deserializeDelete=ie.deserializePatch=ie.deserializePoll=ie.deserializeAll=ie.reviveFullPayload=ie.processSegment=ie.processFlag=ie.replacer=ie.nullReplacer=void 0;const ae=a,oe=ne,le=100;function ce(e,t){const r=[];if(null==e)return;const i=Object.entries(e).filter(([e,r])=>!(null==t?void 0:t.includes(e)));for(r.push(...i.map(([t,r])=>({key:t,value:r,parent:e})));r.length;){const e=r.pop();null!==e.value||Array.isArray(e.parent)?"object"==typeof e.value&&null!==e.value&&r.push(...Object.entries(e.value).map(([t,r])=>({key:t,value:r,parent:e.value}))):delete e.parent[e.key]}}function ue(e,t){if(!(t instanceof ae.AttributeReference||Array.isArray(t)&&t[0]&&t[0]instanceof ae.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 de(e){e&&e.bucketBy&&(e.bucketByAttributeReference=new ae.AttributeReference(e.bucketBy,!e.contextKind))}function he(e){var t;if(ce(e,["variations"]),e.fallthrough&&e.fallthrough.rollout){de(e.fallthrough.rollout)}null===(t=null==e?void 0:e.rules)||void 0===t||t.forEach(e=>{var t;de(e.rollout),null===(t=null==e?void 0:e.clauses)||void 0===t||t.forEach(e=>{e&&e.attribute?e.attributeReference=new ae.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ae.AttributeReference.InvalidReference)})})}function fe(e){var t,r,i,n,s;ce(e),(null===(t=null==e?void 0:e.included)||void 0===t?void 0:t.length)&&e.included.length>le&&(e.generated_includedSet=new Set(e.included),delete e.included),(null===(r=null==e?void 0:e.excluded)||void 0===r?void 0:r.length)&&e.excluded.length>le&&(e.generated_excludedSet=new Set(e.excluded),delete e.excluded),(null===(i=null==e?void 0:e.includedContexts)||void 0===i?void 0:i.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>le&&(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>le&&(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 ae.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 ae.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ae.AttributeReference.InvalidReference)})})}function pe(e){try{return JSON.parse(e)}catch(e){return}}function ve(e){const t=e;return Object.values((null==t?void 0:t.flags)||[]).forEach(e=>{he(e)}),Object.values((null==t?void 0:t.segments)||[]).forEach(e=>{fe(e)}),t}ie.nullReplacer=ce,ie.replacer=ue,ie.processFlag=he,ie.processSegment=fe,ie.reviveFullPayload=ve,ie.deserializeAll=function(e){const t=pe(e);if(t)return ve(null==t?void 0:t.data),t},ie.deserializePoll=function(e){const t=pe(e);if(t)return ve(t),t},ie.deserializePatch=function(e){const t=pe(e);if(t)return t.path.startsWith(oe.default.Features.streamApiPath)?(he(t.data),t.kind=oe.default.Features):t.path.startsWith(oe.default.Segments.streamApiPath)&&(fe(t.data),t.kind=oe.default.Segments),t},ie.deserializeDelete=function(e){const t=pe(e);if(t)return t.path.startsWith(oe.default.Features.streamApiPath)?t.kind=oe.default.Features:t.path.startsWith(oe.default.Segments.streamApiPath)&&(t.kind=oe.default.Segments),t},ie.serializeFlag=function(e){return JSON.stringify(e,ue)},ie.deserializeFlag=function(e){const t=pe(e);if(t)return he(t),t},ie.serializeSegment=function(e){return JSON.stringify(e,ue)},ie.deserializeSegment=function(e){const t=pe(e);if(t)return fe(t),t},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createStreamListeners=e.createDeleteListener=e.createPatchListener=e.createPutListener=void 0;const t=a,r=ie,i=ne,{initMetadataFromHeaders:n}=t.internal;e.createPutListener=(e,t,s=()=>{})=>({deserializeData:r.deserializeAll,processJson:async({data:{flags:r,segments:a}},o)=>{const l={[i.default.Features.namespace]:r,[i.default.Segments.namespace]:a};null==t||t.debug("Initializing all data"),e.init(l,s,n(o))}});e.createPatchListener=(e,t,n=()=>{})=>({deserializeData:r.deserializePatch,processJson:async({data:r,kind:s,path:a})=>{if(s){const o=i.default.getKeyFromPath(s,a);o&&(null==t||t.debug(`Updating ${o} in ${s.namespace}`),e.upsert(s,r,n))}}});e.createDeleteListener=(e,t,n=()=>{})=>({deserializeData:r.deserializeDelete,processJson:async({kind:r,path:s,version:a})=>{if(r){const o=i.default.getKeyFromPath(r,s);o&&(null==t||t.debug(`Deleting ${o} in ${r.namespace}`),e.upsert(r,{key:o,version:a,deleted:!0},n))}}});e.createStreamListeners=(t,r,i)=>{const n=new Map;return n.set("put",(0,e.createPutListener)(t,r,null==i?void 0:i.put)),n.set("patch",(0,e.createPatchListener)(t,r,null==i?void 0:i.patch)),n.set("delete",(0,e.createDeleteListener)(t,r,null==i?void 0:i.delete)),n}}(re);var ge={},_e={},me={};Object.defineProperty(me,"__esModule",{value:!0});me.default=class{constructor(){this._itemsByNamespace={}}get(e,t){var r;return null===(r=this._itemsByNamespace[e])||void 0===r?void 0:r[t]}set(e,t,r){e in this._itemsByNamespace||(this._itemsByNamespace[e]={}),this._itemsByNamespace[e][t]=r}remove(e,t){const r=this._itemsByNamespace[e];r&&delete r[t]}removeAll(){this._itemsByNamespace={}}enumerate(e){Object.entries(this._itemsByNamespace).forEach(([t,r])=>{Object.entries(r).forEach(([r,i])=>{e(t,r,i)})})}mergeFrom(e){e.enumerate(this.set.bind(this))}},Object.defineProperty(_e,"__esModule",{value:!0});const ye=me;_e.default=class{constructor(){this._dependenciesFrom=new ye.default,this._dependenciesTo=new ye.default}updateDependenciesFrom(e,t,r){const i=this._dependenciesFrom.get(e,t);null==i||i.enumerate((r,i)=>{const n=this._dependenciesTo.get(r,i);null==n||n.remove(e,t)}),this._dependenciesFrom.set(e,t,r),null==r||r.enumerate((r,i)=>{let n=this._dependenciesTo.get(r,i);n||(n=new ye.default,this._dependenciesTo.set(r,i,n)),n.set(e,t,!0)})}updateModifiedItems(e,t,r){if(!e.get(t,r)){e.set(t,r,!0);const i=this._dependenciesTo.get(t,r);null==i||i.enumerate((t,r)=>{this.updateModifiedItems(e,t,r)})}}reset(){this._dependenciesFrom.removeAll(),this._dependenciesTo.removeAll()}},Object.defineProperty(ge,"__esModule",{value:!0}),ge.computeDependencies=void 0;const be=ne,Ee=_e,Se=me;function we(e,t){var r,i;const n=new Se.default,s=e===be.default.Features.namespace,a=e===be.default.Segments.namespace;if(s){const i=t;null===(r=null==i?void 0:i.prerequisites)||void 0===r||r.forEach(t=>{n.set(e,t.key,!0)})}if(s||a){const e=t;null===(i=null==e?void 0:e.rules)||void 0===i||i.forEach(e=>{var t;null===(t=e.clauses)||void 0===t||t.forEach(e=>{"segmentMatch"===e.op&&e.values.forEach(e=>{n.set(be.default.Segments.namespace,e,!0)})})})}return n}ge.computeDependencies=we;ge.default=class{constructor(e,t,r){this._featureStore=e,this._hasEventListeners=t,this._onChange=r,this._dependencyTracker=new Ee.default}init(e,t,r){const i=this._hasEventListeners(),n=n=>{this._featureStore.init(e,()=>{Promise.resolve().then(()=>{if(this._dependencyTracker.reset(),Object.entries(e).forEach(([e,t])=>{Object.keys(t||{}).forEach(r=>{const i=t[r];this._dependencyTracker.updateDependenciesFrom(e,r,we(e,i))})}),i){const t=new Se.default;Object.keys(e).forEach(r=>{const i=(null==n?void 0:n[r])||{},s=e[r],a=Object.assign(Object.assign({},i),s);Object.keys(a).forEach(e=>{this.addIfModified(r,e,i&&i[e],s&&s[e],t)})}),this.sendChangeEvents(t)}}),null==t||t()},r)};i?this._featureStore.all(be.default.Features,e=>{this._featureStore.all(be.default.Segments,t=>{const r={[be.default.Features.namespace]:e,[be.default.Segments.namespace]:t};n(r)})}):n()}upsert(e,t,r){const{key:i}=t,n=this._hasEventListeners(),s=s=>{this._featureStore.upsert(e,t,()=>{Promise.resolve().then(()=>{if(this._dependencyTracker.updateDependenciesFrom(e.namespace,i,we(e.namespace,t)),n){const r=new Se.default;this.addIfModified(e.namespace,i,s,t,r),this.sendChangeEvents(r)}}),null==r||r()})};n?this._featureStore.get(e,i,s):s()}addIfModified(e,t,r,i,n){i&&r&&i.version<=r.version||this._dependencyTracker.updateModifiedItems(n,e,t)}sendChangeEvents(e){e.enumerate((e,t)=>{e===be.default.Features.namespace&&this._onChange(t)})}};var Oe={},ke={},De={};Object.defineProperty(De,"__esModule",{value:!0});De.default=class{constructor(e,t,r,i){this._filesystem=e,this._paths=t,this._watch=r,this._callback=i,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 r=await this._filesystem.getFileTimestamp(t);if(r===this._fileTimestamps[t])return;this._fileTimestamps[t]=r;const i=await this._filesystem.readFile(t);this._fileData[t]=i,this._debounceCallback()});this._watchers.push(t)})}close(){this._watchers.forEach(e=>e.close())}_debounceCallback(){this._debounceHandle||(this._debounceHandle=e=>{e()})}},Object.defineProperty(ke,"__esModule",{value:!0}),ke.makeFlagWithValue=void 0;const Te=ie,Pe=ne,Ie=De;function xe(e,t,r){return{key:e,on:!0,fallthrough:{variation:0},variations:[t],version:r}}ke.makeFlagWithValue=xe;ke.default=class{constructor(e,t,r,i=()=>{},n){var s;this._featureStore=r,this._initSuccessHandler=i,this._errorHandler=n,this._allData={},this._fileLoader=new Ie.default(t,e.paths,null!==(s=e.autoUpdate)&&void 0!==s&&s,e=>{var t,r;try{this._processFileData(e)}catch(e){null===(t=this._errorHandler)||void 0===t||t.call(this,e),null===(r=this._logger)||void 0===r||r.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 r;if(e.path.endsWith(".yml")||e.path.endsWith(".yaml")){if(!this._yamlParser)throw new Error(`Attempted to parse yaml file (${e.path}) without parser.`);r=this._yamlParser(e.data)}else r=JSON.parse(e.data);this._processParsedData(r,t)}),this._featureStore.init(this._allData,()=>{this._initSuccessHandler(),this._initSuccessHandler=()=>{}})}_processParsedData(e,t){Object.keys(e.flags||{}).forEach(t=>{(0,Te.processFlag)(e.flags[t]),this._addItem(Pe.default.Features,e.flags[t])}),Object.keys(e.flagValues||{}).forEach(r=>{var i,n;const s=null===(i=t[Pe.default.Features.namespace])||void 0===i?void 0:i[r];let{version:a}=null!=s?s:{version:1};s&&JSON.stringify(e.flagValues[r])!==JSON.stringify(null===(n=null==s?void 0:s.variations)||void 0===n?void 0:n[0])&&(a+=1);const o=xe(r,e.flagValues[r],a);(0,Te.processFlag)(o),this._addItem(Pe.default.Features,o)}),Object.keys(e.segments||{}).forEach(t=>{(0,Te.processSegment)(e.segments[t]),this._addItem(Pe.default.Segments,e.segments[t])})}},Object.defineProperty(Oe,"__esModule",{value:!0});const Re=a,Me=ie,Fe=ke,Ae=De;Oe.default=class{constructor(e,t,r){this._validateInputs(e,t),this._paths=e.paths,this._logger=r,this._filesystem=t.fileSystem,this._yamlParser=e.yamlParser}_validateInputs(e,t){if(!e.paths||0===e.paths.length)throw new Error("FileDataInitializerFDv2: paths are required");if(!t.fileSystem)throw new Error("FileDataInitializerFDv2: file system is required")}start(e,t){t(Re.subsystem.DataSourceState.Initializing);const r=Re.internal.initMetadataFromHeaders(void 0),i=new Re.internal.PayloadProcessor({flag:e=>((0,Me.processFlag)(e),e),segment:e=>((0,Me.processSegment)(e),e)},(e,r)=>{t(Re.subsystem.DataSourceState.Interrupted,new Re.LDPollingError(e,r))},this._logger),n=Re.internal.FDv1PayloadAdaptor(i);this._fileLoader=new Ae.default(this._filesystem,this._paths,!1,s=>{var a;try{const a=this._processFileData(s);i.addPayloadListener(t=>{e(!1,{initMetadata:r,payload:t})}),t(Re.subsystem.DataSourceState.Valid),n.processFullTransfer(a),t(Re.subsystem.DataSourceState.Closed)}catch(e){null===(a=this._logger)||void 0===a||a.error("File contained invalid data",e),t(Re.subsystem.DataSourceState.Closed,new Re.LDPollingError(Re.DataSourceErrorKind.InvalidData,"Malformed data in file response"))}}),this._fileLoader.loadAndWatch().catch(e=>{var r;null===(r=this._logger)||void 0===r||r.error("Error loading files",e),t(Re.subsystem.DataSourceState.Closed,new Re.LDPollingError(Re.DataSourceErrorKind.NetworkError,`Failed to load files: ${e instanceof Error?e.message:String(e)}`))})}_processFileData(e){return e.reduce((e,t)=>{var r,i,n;let s;if(t.path.endsWith(".yml")||t.path.endsWith(".yaml")){if(!this._yamlParser)throw new Error(`Attempted to parse yaml file (${t.path}) without parser.`);s=this._yamlParser(t.data)}else s=JSON.parse(t.data);const a={};return Object.entries(null!==(r=s.flagValues)&&void 0!==r?r:{}).forEach(([e,t])=>{a[e]=(0,Fe.makeFlagWithValue)(e,t,1)}),{segments:Object.assign(Object.assign({},e.segments),null!==(i=s.segments)&&void 0!==i?i:{}),flags:Object.assign(Object.assign(Object.assign({},e.flags),null!==(n=s.flags)&&void 0!==n?n:{}),a)}},{segments:{},flags:{}})}stop(){this._fileLoader&&this._fileLoader.close()}};var Ce={};Object.defineProperty(Ce,"__esModule",{value:!0});const Le=a,je=ie;Ce.default=class{constructor(e,t){this._requestor=e,this._logger=t,this._stopped=!1}start(e,t){var r;t(Le.subsystem.DataSourceState.Initializing),null===(r=this._logger)||void 0===r||r.debug("Performing initialization request to LaunchDarkly for feature flag data."),this._requestor.requestAllData((r,i,n,s)=>{var a,o,l;if(this._stopped)return;const c=()=>{var e;const i=null==r?void 0:r.status,n=r?(0,Le.httpErrorMessage)(r,"initializer","falling back to FDv1"):"Response header indicates to fallback to FDv1";null===(e=this._logger)||void 0===e||e.warn(n),t(Le.subsystem.DataSourceState.Closed,new Le.LDFlagDeliveryFallbackError(Le.DataSourceErrorKind.ErrorResponse,n,i))};if(r){if(s)return void c();const{status:e}=r,i=(0,Le.httpErrorMessage)(r,"initializer","initializer does not retry");return null===(a=this._logger)||void 0===a||a.error(i),void t(Le.subsystem.DataSourceState.Closed,new Le.LDPollingError(Le.DataSourceErrorKind.ErrorResponse,i,e))}if(!i)return s?void c():void t(Le.subsystem.DataSourceState.Closed,new Le.LDPollingError(Le.DataSourceErrorKind.InvalidData,"One shot initializer response missing body."));const u=Le.internal.initMetadataFromHeaders(n);try{const r=JSON.parse(i),n=new Le.internal.PayloadProcessor({flag:e=>((0,je.processFlag)(e),e),segment:e=>((0,je.processSegment)(e),e)},(e,r)=>{s?c():t(Le.subsystem.DataSourceState.Interrupted,new Le.LDPollingError(e,r))},this._logger);t(Le.subsystem.DataSourceState.Valid),n.addPayloadListener(t=>{var r;const i={initMetadata:u,payload:t};s&&(i.fallbackToFDv1=!0,null===(r=this._logger)||void 0===r||r.warn("Response header indicates to fallback to FDv1")),e("full"===t.type,i)}),n.processEvents(r.events),t(Le.subsystem.DataSourceState.Closed)}catch(e){if(null===(o=this._logger)||void 0===o||o.error("Response contained invalid data"),null===(l=this._logger)||void 0===l||l.debug(`${e} - Body follows: ${i}`),s)return void c();t(Le.subsystem.DataSourceState.Closed,new Le.LDPollingError(Le.DataSourceErrorKind.InvalidData,"Malformed data in polling response"))}})}stop(){this._stopped=!0}};var Ne={},$e={},Ve={},Ue={};Object.defineProperty(Ue,"__esModule",{value:!0}),Ue.default=function(e){return new Promise(t=>{e(e=>{t(e)})})},Object.defineProperty(Ve,"__esModule",{value:!0});const Ke=Ue;Ve.default=class{constructor(e){this._store=e}async get(e,t){return(0,Ke.default)(r=>{this._store.get(e,t,r)})}async all(e){return(0,Ke.default)(t=>{this._store.all(e,t)})}async init(e,t){return(0,Ke.default)(r=>{this._store.init(e,r,t)})}async delete(e,t,r){return(0,Ke.default)(i=>{this._store.delete(e,t,r,i)})}async upsert(e,t){return(0,Ke.default)(r=>{this._store.upsert(e,t,r)})}async initialized(){return(0,Ke.default)(e=>{this._store.initialized(e)})}close(){this._store.close()}getInitMetadata(){var e,t;return null===(t=(e=this._store).getInitMetaData)||void 0===t?void 0:t.call(e)}};var ze={};Object.defineProperty(ze,"__esModule",{value:!0});const Be=Ue;ze.default=class{constructor(e){this._store=e}async get(e,t){return(0,Be.default)(r=>{this._store.get(e,t,r)})}async all(e){return(0,Be.default)(t=>{this._store.all(e,t)})}async init(e,t){return(0,Be.default)(r=>{this._store.init(e,r,t)})}async delete(e,t,r){return(0,Be.default)(i=>{this._store.delete(e,t,r,i)})}async upsert(e,t){return(0,Be.default)(r=>{this._store.upsert(e,t,r)})}async initialized(){return(0,Be.default)(e=>{this._store.initialized(e)})}async applyChanges(e,t,r,i){return(0,Be.default)(n=>{this._store.applyChanges(e,t,n,r,i)})}close(){this._store.close()}getInitMetadata(){var e,t;return null===(t=(e=this._store).getInitMetaData)||void 0===t?void 0:t.call(e)}};var He={},qe={};function Ge(e){return Date.now()>e.expiration}Object.defineProperty(qe,"__esModule",{value:!0});qe.default=class{constructor(e){this._options=e,this._storage=new Map,this._checkIntervalHandle=void e.checkInterval}get(e){const t=this._storage.get(e);if(!t||!Ge(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)=>{Ge(e)&&this._storage.delete(t)})}get size(){return this._storage.size}};var We={};Object.defineProperty(We,"__esModule",{value:!0}),We.persistentStoreKinds=void 0;const Je=ie,Xe=ne;We.persistentStoreKinds={segments:{namespace:Xe.default.Segments.namespace,deserialize:e=>{const t=(0,Je.deserializeSegment)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Je.serializeSegment)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:0},features:{namespace:Xe.default.Features.namespace,deserialize:e=>{const t=(0,Je.deserializeFlag)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Je.serializeFlag)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:1}};var Ye={};Object.defineProperty(Ye,"__esModule",{value:!0});const Ze=We;function Qe(e,t){const r=[],i=new Set(Object.keys(t)),n=s=>{if(!i.has(s))return;i.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)}),r.push({key:s,item:e.serialize(a)})};for(;i.size>0;){const e=i.values().next().value;n(e)}return r}Ye.default=function(e){const t=[];return Object.keys(e).forEach(r=>{const i=Ze.persistentStoreKinds[r];t.push({key:i,item:Qe(i,e[r])})}),t.sort((e,t)=>e.key.priority-t.key.priority),t};var et={};Object.defineProperty(et,"__esModule",{value:!0});et.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,null==t||t()})}}},Object.defineProperty(He,"__esModule",{value:!0});const tt=qe,rt=We,it=Ye,nt=et;function st(e,t){return`${e.namespace}:${t}`}function at(e){return`$all:${e.namespace}`}const ot="$checkedInit";function lt(e){return!e||e.item.deleted?null:e.item}function ct(e){return{version:e,item:{version:e,deleted:!0}}}function ut(e,t){if(t.deleted||!t.serializedItem)return ct(t.version);const r=e.deserialize(t.serializedItem);return void 0===r?ct(t.version):0===r.version||r.version===t.version||void 0===r.item?r:{version:t.version,item:r.item}}He.default=class{constructor(e,t,r){this._core=e,this._logger=r,this._isInitialized=!1,this._queue=new nt.default,t&&(this._itemCache=new tt.default({ttl:t,checkInterval:600}),this._allItemsCache=new tt.default({ttl:t,checkInterval:600}))}init(e,t){this._queue.enqueue(t=>{this._core.init((0,it.default)(e),()=>{this._isInitialized=!0,this._itemCache&&(this._itemCache.clear(),this._allItemsCache.clear(),Object.keys(e).forEach(t=>{const r=rt.persistentStoreKinds[t],i=e[t];this._allItemsCache.set(at(r),i),Object.keys(i).forEach(e=>{const t=i[e],n={version:t.version,item:t};this._itemCache.set(st(r,e),n)})})),t()})},t)}get(e,t,r){if(this._itemCache){const i=this._itemCache.get(st(e,t));if(i)return void r(lt(i))}const i=rt.persistentStoreKinds[e.namespace];this._core.get(i,t,n=>{var s;if(n&&n.serializedItem){const a=ut(i,n);return null===(s=this._itemCache)||void 0===s||s.set(st(e,t),a),void r(lt(a))}r(null)})}initialized(e){var t;this._isInitialized?e(!0):(null===(t=this._itemCache)||void 0===t?void 0:t.get(ot))?e(!1):this._core.initialized(t=>{var r;this._isInitialized=t,this._isInitialized||null===(r=this._itemCache)||void 0===r||r.set(ot,!0),e(this._isInitialized)})}all(e,t){var r;const i=null===(r=this._allItemsCache)||void 0===r?void 0:r.get(at(e));if(i)return void t(i);const n=rt.persistentStoreKinds[e.namespace];this._core.getAll(n,r=>{var i;if(!r)return void t({});const s={};r.forEach(({key:e,item:t})=>{const r=lt(ut(n,t));r&&(s[e]=r)}),null===(i=this._allItemsCache)||void 0===i||i.set(at(e),s),t(s)})}upsert(e,t,r){this._queue.enqueue(r=>{this._allItemsCache&&this._allItemsCache.clear();const i=rt.persistentStoreKinds[e.namespace];this._core.upsert(i,t.key,i.serialize(t),(n,s)=>{var a,o,l;if(n&&(null===(a=this._logger)||void 0===a||a.error(`Persistent store returned error: ${n instanceof Error?n.message:n}`)),!n&&s)if(s.serializedItem){const r=ut(i,s);null===(o=this._itemCache)||void 0===o||o.set(st(e,t.key),r)}else s.deleted&&(null===(l=this._itemCache)||void 0===l||l.set(t.key,{key:t.key,version:s.version,deleted:!0}));r()})},r)}delete(e,t,r,i){this.upsert(e,{key:t,version:r,deleted:!0},i)}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()}};var dt={},ht={};Object.defineProperty(ht,"__esModule",{value:!0});ht.default=class{constructor(){this._allData={},this._initCalled=!1}get(e,t,r){const i=this._allData[e.namespace];if(i&&Object.prototype.hasOwnProperty.call(i,t)){const e=i[t];if(e&&!e.deleted)return null==r?void 0:r(e)}return null==r?void 0:r(null)}all(e,t){var r;const i={},n=null!==(r=this._allData[e.namespace])&&void 0!==r?r:{};Object.entries(n).forEach(([e,t])=>{t&&!t.deleted&&(i[e]=t)}),null==t||t(i)}init(e,t,r){this.applyChanges(!0,e,t,r)}delete(e,t,r,i){const n={key:t,version:r,deleted:!0};this.applyChanges(!1,{[e.namespace]:{[t]:n}},i)}upsert(e,t,r){this.applyChanges(!1,{[e.namespace]:{[t.key]:t}},r)}applyChanges(e,t,r,i,n){if(e)this._initCalled=!0,this._allData=t,this._initMetadata=i;else{const e={};Object.entries(this._allData).forEach(([t,r])=>{e[t]=Object.assign({},r)}),Object.entries(t).forEach(([t,r])=>{Object.keys(r||{}).forEach(i=>{let n=e[t];n||(n={},e[t]=n);const s=r[i];if(Object.hasOwnProperty.call(n,i)){const e=n[i];(!e||e.version<s.version)&&(n[i]=Object.assign({key:i},s))}else n[i]=Object.assign({key:i},s)})}),this._allData=e}this._selector=n,null==r||r()}initialized(e){return null==e?void 0:e(this._initCalled)}close(){}getDescription(){return"memory"}getInitMetaData(){return this._initMetadata}getSelector(){return this._selector}},Object.defineProperty(dt,"__esModule",{value:!0});const ft=ht;dt.default=class{constructor(e){this._nonTransPersistenceStore=e,this._activeStore=this._nonTransPersistenceStore,this._memoryStore=new ft.default}get(e,t,r){this._activeStore.get(e,t,r)}all(e,t){this._activeStore.all(e,t)}init(e,t){this.applyChanges(!0,e,t)}delete(e,t,r,i){const n={key:t,version:r,deleted:!0};this.applyChanges(!1,{[e.namespace]:{[t]:n}},i)}upsert(e,t,r){this.applyChanges(!1,{[e.namespace]:{[t.key]:t}},r)}applyChanges(e,t,r,i,n){this._memoryStore.applyChanges(e,t,()=>{if(e)this._activeStore=this._memoryStore,this._nonTransPersistenceStore.init(t,r);else{const e=[];Object.entries(t).forEach(([t,r])=>{Object.keys(r||{}).forEach(i=>{e.push({dataKind:{namespace:t},item:Object.assign({key:i},r[i])})})}),e.reduce((e,t)=>e.then(()=>new Promise(e=>{this._nonTransPersistenceStore.upsert(t.dataKind,t.item,e)})),Promise.resolve()).then(r)}},i,n)}initialized(e){this._activeStore.initialized(e)}close(){this._nonTransPersistenceStore.close(),this._memoryStore.close()}getDescription(){return"transactional persistent store"}getInitMetaData(){var e,t;return null===(t=(e=this._memoryStore).getInitMetaData)||void 0===t?void 0:t.call(e)}getSelector(){var e,t;return null===(t=(e=this._memoryStore).getSelector)||void 0===t?void 0:t.call(e)}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.reviveFullPayload=e.deserializePoll=e.TransactionalFeatureStore=e.PersistentDataStoreWrapper=e.AsyncTransactionalStoreFacade=e.AsyncStoreFacade=void 0;const t=Ve;e.AsyncStoreFacade=t.default;const r=ze;e.AsyncTransactionalStoreFacade=r.default;const i=He;e.PersistentDataStoreWrapper=i.default;const n=ie;Object.defineProperty(e,"deserializePoll",{enumerable:!0,get:function(){return n.deserializePoll}}),Object.defineProperty(e,"reviveFullPayload",{enumerable:!0,get:function(){return n.reviveFullPayload}});const s=dt;e.TransactionalFeatureStore=s.default}($e),Object.defineProperty(Ne,"__esModule",{value:!0});const pt=a,vt=$e,gt=ne,{initMetadataFromHeaders:_t}=pt.internal;Ne.default=class{constructor(e,t,r,i,n=()=>{},s){this._requestor=e,this._pollInterval=t,this._featureStore=r,this._logger=i,this._initSuccessHandler=n,this._errorHandler=s,this._stopped=!1}_poll(){var e;if(this._stopped)return;const t=e=>{var t,r,i;null===(t=this._logger)||void 0===t||t.error("Polling received invalid data"),null===(r=this._logger)||void 0===r||r.debug(`Invalid JSON follows: ${e}`),null===(i=this._errorHandler)||void 0===i||i.call(this,new pt.LDPollingError(pt.DataSourceErrorKind.InvalidData,"Malformed JSON data in polling response"))},r=Date.now();null===(e=this._logger)||void 0===e||e.debug("Polling LaunchDarkly for feature flag updates"),this._requestor.requestAllData((e,i,n)=>{var s,a,o,l;const c=Date.now()-r,u=Math.max(1e3*this._pollInterval-c,0);if(null===(s=this._logger)||void 0===s||s.debug("Elapsed: %d ms, sleeping for %d ms",c,u),e){const{status:t}=e;if(t&&!(0,pt.isHttpRecoverable)(t)){const r=(0,pt.httpErrorMessage)(e,"polling request");return null===(a=this._logger)||void 0===a||a.error(r),void(null===(o=this._errorHandler)||void 0===o||o.call(this,new pt.LDPollingError(pt.DataSourceErrorKind.ErrorResponse,r,t)))}null===(l=this._logger)||void 0===l||l.warn((0,pt.httpErrorMessage)(e,"polling request","will retry"))}else if(i){const e=(0,vt.deserializePoll)(i);if(e){const t={[gt.default.Features.namespace]:e.flags,[gt.default.Segments.namespace]:e.segments};return void this._featureStore.init(t,()=>{this._initSuccessHandler(),this._timeoutHandle=e=>{e()}},_t(n))}t(i)}this._timeoutHandle=e=>{e()}})}start(){this._poll()}stop(){this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this._stopped=!0}close(){this.stop()}};var mt={};Object.defineProperty(mt,"__esModule",{value:!0});const yt=a,bt=ie;mt.default=class{constructor(e,t=30,r,i=!1){this._requestor=e,this._pollInterval=t,this._logger=r,this._processResponseAsFDv1=i,this._stopped=!1}_poll(e,t,r){var i;if(this._stopped)return;const n=Date.now();var s;null===(i=this._logger)||void 0===i||i.debug("Polling LaunchDarkly for feature flag updates"),this._requestor.requestAllData((r,i,s,a)=>{var o,l,c,u,d,h;if(this._stopped)return;const f=Date.now()-n,p=Math.max(1e3*this._pollInterval-f,0),v=()=>{var e;const i=r instanceof yt.LDFlagDeliveryFallbackError?r:new yt.LDFlagDeliveryFallbackError(yt.DataSourceErrorKind.ErrorResponse,r?(0,yt.httpErrorMessage)(r,"polling request","falling back to FDv1"):"Response header indicates to fallback to FDv1",null==r?void 0:r.status);null===(e=this._logger)||void 0===e||e.warn(i.message),t(yt.subsystem.DataSourceState.Closed,i)};if(null===(o=this._logger)||void 0===o||o.debug("Elapsed: %d ms, sleeping for %d ms",f,p),r){if(a||r instanceof yt.LDFlagDeliveryFallbackError)return void v();const{status:e}=r;if(e&&!(0,yt.isHttpRecoverable)(e)){const i=(0,yt.httpErrorMessage)(r,"polling request");return null===(l=this._logger)||void 0===l||l.error(i),void t(yt.subsystem.DataSourceState.Closed,new yt.LDPollingError(yt.DataSourceErrorKind.ErrorResponse,i,e,!1))}const i=(0,yt.httpErrorMessage)(r,"polling request","will retry");return t(yt.subsystem.DataSourceState.Interrupted,new yt.LDPollingError(yt.DataSourceErrorKind.ErrorResponse,i,e)),null===(c=this._logger)||void 0===c||c.warn(i),void(this._timeoutHandle=e=>{e()})}const g=yt.internal.initMetadataFromHeaders(s);if(i)try{const r=new yt.internal.PayloadProcessor({flag:e=>((0,bt.processFlag)(e),e),segment:e=>((0,bt.processSegment)(e),e)},(e,r)=>{a?v():t(yt.subsystem.DataSourceState.Interrupted,new yt.LDPollingError(e,r))},this._logger);if(r.addPayloadListener(t=>{var r;const i={initMetadata:g,payload:t};a&&(i.fallbackToFDv1=!0,null===(r=this._logger)||void 0===r||r.warn("Response header indicates to fallback to FDv1")),e("full"===t.type,i)}),null===(u=this._logger)||void 0===u||u.debug(`Got body: ${i}`),this._processResponseAsFDv1){!function(e,t){yt.internal.FDv1PayloadAdaptor(e).useSelector("FDv1Fallback").processFullTransfer(t)}(r,JSON.parse(i))}else{const e=JSON.parse(i);r.processEvents(e.events)}if(a)return;t(yt.subsystem.DataSourceState.Valid)}catch(e){if(null===(d=this._logger)||void 0===d||d.error("Response contained invalid data"),null===(h=this._logger)||void 0===h||h.debug(`${r} - Body follows: ${i}`),a)return void v();t(yt.subsystem.DataSourceState.Interrupted,new yt.LDPollingError(yt.DataSourceErrorKind.InvalidData,"Malformed data in polling response"))}else if(a)return void v();this._timeoutHandle=e=>{e()}},(s=null==r?void 0:r())?[{key:"basis",value:s}]:[])}start(e,t,r){this._statusCallback=t,t(yt.subsystem.DataSourceState.Initializing),this._poll(e,t,r)}stop(){var e;this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),null===(e=this._statusCallback)||void 0===e||e.call(this,yt.subsystem.DataSourceState.Closed),this._stopped=!0,this._statusCallback=void 0}};var Et={};Object.defineProperty(Et,"__esModule",{value:!0});const St=a;Et.default=class{constructor(e,t,r,i="/sdk/latest-all",n,s){this._requests=t,this._path=i,this._logger=n,this._eTagCache={},this._headers=Object.assign({},r),this._serviceEndpoints=null!=s?s:e.serviceEndpoints,this._timeoutMs=1e3*e.timeout}async _requestWithETagCache(e,t){const r=this._eTagCache[e],i=null==r?void 0:r.etag,n=i?Object.assign(Object.assign({},t),{headers:Object.assign(Object.assign({},t.headers),{"if-none-match":i})}):t,s=await this._requests.fetch(e,n);if(304===s.status&&r)return{res:s,body:r.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,t=[]){var r,i;const n={method:"GET",headers:this._headers,timeout:this._timeoutMs},s=(0,St.getPollingUri)(this._serviceEndpoints,this._path,t);null===(r=this._logger)||void 0===r||r.debug(`Requestor making request to uri: ${s}`);try{const{res:t,body:r}=await this._requestWithETagCache(s,n);null===(i=this._logger)||void 0===i||i.debug(`Requestor got (possibly cached) body: ${JSON.stringify(r)}`);const a="true"===t.headers.get("x-ld-fd-fallback"),o=Object.fromEntries(t.headers.entries());if(200!==t.status&&304!==t.status){return e(a?new St.LDFlagDeliveryFallbackError(St.DataSourceErrorKind.ErrorResponse,"Response header indicates to fallback to FDv1.",t.status):new St.LDPollingError(St.DataSourceErrorKind.ErrorResponse,`Unexpected status code: ${t.status}`,t.status),void 0,o,a)}return e(void 0,304===t.status?null:r,o,a)}catch(t){return e(t,void 0,void 0,!1)}}};var wt={};Object.defineProperty(wt,"__esModule",{value:!0});const Ot=a;wt.default=class{constructor(e,t,r,i,n,s,a,o=1){this._listeners=i,this._diagnosticsManager=s,this._errorHandler=a,this._streamInitialReconnectDelay=o;const{basicConfiguration:l,platform:c}=e,{logger:u}=l,{requests:d}=c;this._headers=Object.assign({},n),this._logger=u,this._requests=d,this._streamUri=(0,Ot.getStreamingUri)(l.serviceEndpoints,t,r)}_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,r,i;return(0,Ot.shouldRetry)(e)?(null===(i=this._logger)||void 0===i||i.warn((0,Ot.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 Ot.LDStreamingError(Ot.DataSourceErrorKind.ErrorResponse,e.message,e.status)),null===(r=this._logger)||void 0===r||r.error((0,Ot.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=e=>{var t;this._initHeaders=e.headers,null===(t=this._logger)||void 0===t||t.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:r},i)=>{e.addEventListener(i,e=>{var n,s;if(null===(n=this._logger)||void 0===n||n.debug(`Received ${i} event`),null==e?void 0:e.data){this._logConnectionResult(!0);const{data:n}=e,s=t(n);if(!s)return void((e,t,r,i)=>{null==r||r.error(`Stream received invalid data in "${e}" message`),null==r||r.debug(`Invalid JSON follows: ${t}`),null==i||i(new Ot.LDStreamingError(Ot.DataSourceErrorKind.InvalidData,"Malformed JSON data in event stream"))})(i,n,this._logger,this._errorHandler);r(s,this._initHeaders)}else null===(s=this._errorHandler)||void 0===s||s.call(this,new Ot.LDStreamingError(Ot.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 kt={};Object.defineProperty(kt,"__esModule",{value:!0});const Dt=a,Tt=ie;kt.default=class{constructor(e,t,r,i,n,s=1,a){this._streamUriPath=t,this._parameters=r,this._diagnosticsManager=n,this._streamInitialReconnectDelay=s;const{basicConfiguration:o,platform:l}=e,{logger:c,serviceEndpoints:u}=o,{requests:d}=l;this._headers=Object.assign({},i),this._serviceEndpoints=null!=a?a:u,this._logger=c,this._requests=d}_logConnectionAttempt(){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,t){var r,i,n;if("true"===(null===(r=e.headers)||void 0===r?void 0:r["x-ld-fd-fallback"])){const r=new Dt.LDFlagDeliveryFallbackError(Dt.DataSourceErrorKind.ErrorResponse,"Response header indicates to fallback to FDv1",e.status);return t(Dt.subsystem.DataSourceState.Closed,r),!1}return(0,Dt.shouldRetry)(e)?(null===(n=this._logger)||void 0===n||n.warn((0,Dt.httpErrorMessage)(e,"streaming request","will retry")),this._logConnectionResult(!1),this._logConnectionAttempt(),t(Dt.subsystem.DataSourceState.Interrupted),!0):(null===(i=this._logger)||void 0===i||i.error((0,Dt.httpErrorMessage)(e,"streaming request")),this._logConnectionResult(!1),t(Dt.subsystem.DataSourceState.Closed,new Dt.LDStreamingError(Dt.DataSourceErrorKind.ErrorResponse,e.message,e.status,!1)),!1)}start(e,t,r){var i;this._logConnectionAttempt(),t(Dt.subsystem.DataSourceState.Initializing);const n=null==r?void 0:r(),s=n?[...this._parameters,{key:"basis",value:n}]:this._parameters,a=(0,Dt.getStreamingUri)(this._serviceEndpoints,this._streamUriPath,s);null===(i=this._logger)||void 0===i||i.debug(`Streaming processor opening event source to uri: ${a}`);let o=!1;const l=this._requests.createEventSource(a,{headers:this._headers,errorFilter:e=>this._retryAndHandleError(e,t),initialRetryDelayMillis:1e3*this._streamInitialReconnectDelay,readTimeoutMillis:3e5,retryResetIntervalMillis:6e4});this._eventSource=l;const c=new Dt.internal.PayloadStreamReader(l,{flag:e=>((0,Tt.processFlag)(e),e),segment:e=>((0,Tt.processSegment)(e),e)},(e,r)=>{var i;if(o){const e=new Dt.LDFlagDeliveryFallbackError(Dt.DataSourceErrorKind.ErrorResponse,"Response header indicates to fallback to FDv1");null===(i=this._logger)||void 0===i||i.warn(e.message),t(Dt.subsystem.DataSourceState.Closed,e)}else t(Dt.subsystem.DataSourceState.Interrupted,new Dt.LDStreamingError(e,r));this.stop()},this._logger);c.addPayloadListener(t=>{var r;this._logConnectionResult(!0);const i={initMetadata:this._initMetadata,payload:t};o&&(i.fallbackToFDv1=!0,null===(r=this._logger)||void 0===r||r.warn("Response header indicates to fallback to FDv1")),e("full"===t.type,i),o&&this.stop()}),l.onclose=()=>{var e;null===(e=this._logger)||void 0===e||e.info("Closed LaunchDarkly stream connection"),t(Dt.subsystem.DataSourceState.Closed)},l.onerror=()=>{},l.onopen=e=>{var r,i;null===(r=this._logger)||void 0===r||r.info("Opened LaunchDarkly stream connection"),this._initMetadata=Dt.internal.initMetadataFromHeaders(e.headers),"true"===(null===(i=e.headers)||void 0===i?void 0:i["x-ld-fd-fallback"])&&(o=!0),t(Dt.subsystem.DataSourceState.Valid)},l.onretrying=e=>{var t;null===(t=this._logger)||void 0===t||t.info(`Will retry stream connection in ${e.delayMillis} milliseconds`)}}stop(){var e;null===(e=this._eventSource)||void 0===e||e.close(),this._eventSource=void 0}close(){this.stop()}};var Pt={};Object.defineProperty(Pt,"__esModule",{value:!0});const It=ne,xt=ge,Rt=_e,Mt=me;Pt.default=class{constructor(e,t,r){this._featureStore=e,this._hasEventListeners=t,this._onChange=r,this._dependencyTracker=new Rt.default}init(e,t,r){this.applyChanges(!0,e,t,r)}upsert(e,t,r){this.applyChanges(!1,{[e.namespace]:{[t.key]:t}},r)}applyChanges(e,t,r,i,n){const s=this._hasEventListeners();let a={};s&&this._featureStore.all(It.default.Features,e=>{this._featureStore.all(It.default.Segments,t=>{a={[It.default.Features.namespace]:e,[It.default.Segments.namespace]:t}})}),(a=>{this._featureStore.applyChanges(e,t,()=>{Promise.resolve().then(()=>{if(e&&this._dependencyTracker.reset(),Object.entries(t).forEach(([e,t])=>{Object.keys(t||{}).forEach(r=>{const i=t[r];this._dependencyTracker.updateDependenciesFrom(e,r,(0,xt.computeDependencies)(e,i))})}),s){const r=new Mt.default;Object.keys(t).forEach(i=>{const n=a[i],s=t[i];let o;o=e?Object.assign(Object.assign({},n),s):Object.assign({},s),Object.keys(o).forEach(e=>{this.addIfModified(i,e,n&&n[e],s&&s[e],r)})}),this.sendChangeEvents(r)}}),null==r||r()},i,n)})(a)}addIfModified(e,t,r,i,n){i&&r&&i.version<=r.version||this._dependencyTracker.updateModifiedItems(n,e,t)}sendChangeEvents(e){e.enumerate((e,t)=>{e===It.default.Features.namespace&&this._onChange(t)})}};var Ft={},At={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultValues=e.DEFAULT_STREAM_RECONNECT_DELAY=e.DEFAULT_POLL_INTERVAL=void 0;const t=a,r=O,i=ht,n=dt,s={baseUri:t.TypeValidators.String,streamUri:t.TypeValidators.String,eventsUri:t.TypeValidators.String,timeout:t.TypeValidators.numberWithMin(1),capacity:t.TypeValidators.Number,logger:t.TypeValidators.Object,featureStore:t.TypeValidators.ObjectOrFactory,dataSystem:t.TypeValidators.Object,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[]",{}),enableEventCompression:t.TypeValidators.Boolean,dataSourceOptionsType:t.TypeValidators.String};e.DEFAULT_POLL_INTERVAL=30,e.DEFAULT_STREAM_RECONNECT_DELAY=1;const o={dataSourceOptionsType:"standard",streamInitialReconnectDelay:e.DEFAULT_STREAM_RECONNECT_DELAY,pollInterval:e.DEFAULT_POLL_INTERVAL},l={dataSourceOptionsType:"streamingOnly",streamInitialReconnectDelay:e.DEFAULT_STREAM_RECONNECT_DELAY},c={dataSourceOptionsType:"pollingOnly",pollInterval:e.DEFAULT_POLL_INTERVAL},u={dataSource:o};function d(r,i){const n=[],a=Object.assign({},i);return Object.keys(r).forEach(i=>{var o;const l=r[i],c=s[i];if(c)if(c.is(l))a[i]=l;else if("boolean"===c.getType())n.push(t.OptionMessages.wrongOptionTypeBoolean(i,typeof l)),a[i]=!!l;else if(c instanceof t.NumberWithMinimum&&t.TypeValidators.Number.is(l)){const{min:e}=c;n.push(t.OptionMessages.optionBelowMinimum(i,l,e)),a[i]=e}else n.push(t.OptionMessages.wrongOptionType(i,c.getType(),typeof l)),a[i]=e.defaultValues[i];else null===(o=r.logger)||void 0===o||o.warn(t.OptionMessages.unknownOption(i))}),{errors:n,validatedOptions:a}}e.defaultValues={baseUri:"https://sdk.launchdarkly.com",streamUri:"https://stream.launchdarkly.com",eventsUri:t.ServiceEndpoints.DEFAULT_EVENTS,stream:!0,streamInitialReconnectDelay:e.DEFAULT_STREAM_RECONNECT_DELAY,sendEvents:!0,timeout:10,capacity:1e4,flushInterval:5,pollInterval:e.DEFAULT_POLL_INTERVAL,offline:!1,useLdd:!1,allAttributesPrivate:!1,privateAttributes:[],contextKeysCapacity:1e3,contextKeysFlushInterval:300,diagnosticOptOut:!1,diagnosticRecordingInterval:900,featureStore:()=>new i.default,enableEventCompression:!1,dataSystem:u};const h={baseUri:t.TypeValidators.String,pollInterval:t.TypeValidators.numberWithMin(30)};function f(e,r){return Object.prototype.hasOwnProperty.call(e,"baseUri")?(delete r.baseUri,[t.OptionMessages.unknownOption("dataSystem.dataSource.baseUri")]):[]}function p(e){const i=[],n=Object.assign({},e);if(e.persistentStore&&!t.TypeValidators.ObjectOrFactory.is(e.persistentStore)&&(n.persistentStore=void 0,i.push(t.OptionMessages.wrongOptionType("persistentStore","LDFeatureStore",typeof e.persistentStore))),void 0!==e.fdv1Fallback&&null!==e.fdv1Fallback)if(t.TypeValidators.Object.is(e.fdv1Fallback)){const{errors:r,validatedOptions:s}=function(e){const r=[],i={};return Object.keys(e).forEach(n=>{const s=e[n],a=h[n];if(a)if(a.is(s))i[n]=s;else if(a instanceof t.NumberWithMinimum&&t.TypeValidators.Number.is(s)){const{min:e}=a;r.push(t.OptionMessages.optionBelowMinimum(`dataSystem.fdv1Fallback.${n}`,s,e)),i[n]=e}else r.push(t.OptionMessages.wrongOptionType(`dataSystem.fdv1Fallback.${n}`,a.getType(),typeof s));else r.push(t.OptionMessages.unknownOption(`dataSystem.fdv1Fallback.${n}`))}),{errors:r,validatedOptions:i}}(e.fdv1Fallback);n.fdv1Fallback=s,i.push(...r)}else n.fdv1Fallback=void 0,i.push(t.OptionMessages.wrongOptionType("dataSystem.fdv1Fallback","FDv1FallbackConfiguration",typeof e.fdv1Fallback));if(e.dataSource){let s,a;(0,r.isStandardOptions)(e.dataSource)?(({errors:s,validatedOptions:a}=d(e.dataSource,o)),s.push(...f(e.dataSource,a))):(0,r.isStreamingOnlyOptions)(e.dataSource)?(({errors:s,validatedOptions:a}=d(e.dataSource,l)),s.push(...f(e.dataSource,a))):(0,r.isPollingOnlyOptions)(e.dataSource)?(({errors:s,validatedOptions:a}=d(e.dataSource,c)),s.push(...f(e.dataSource,a))):(0,r.isCustomOptions)(e.dataSource)?(a=e.dataSource,s=[]):(a=o,s=[t.OptionMessages.wrongOptionType("dataSource","DataSourceOptions",typeof e.dataSource)]),n.dataSource=a,i.push(...s)}else n.dataSource=o;return{errors:i,validatedOptions:n}}e.default=class{constructor(r={},s={}){var a;r=r||{},this.logger=r.logger;const{errors:o,validatedOptions:l}=d(r,e.defaultValues),c=l;if(o.forEach(e=>{var t;null===(t=this.logger)||void 0===t||t.warn(e)}),function(e,r){var i,n,s;const{baseUri:a,streamUri:o,eventsUri:l}=e,c=null!=o,u=null!=a,d=null!=l;c===u&&c===d||(!c&&r.stream&&(null===(i=r.logger)||void 0===i||i.warn(t.OptionMessages.partialEndpoint("streamUri"))),u||null===(n=r.logger)||void 0===n||n.warn(t.OptionMessages.partialEndpoint("baseUri")),!d&&r.sendEvents&&(null===(s=r.logger)||void 0===s||s.warn(t.OptionMessages.partialEndpoint("eventsUri"))))}(r,c),r.dataSystem){const{errors:e,validatedOptions:s}=p(r.dataSystem),a=s;this.dataSystem={dataSource:a.dataSource,useLdd:a.useLdd,fdv1Fallback:a.fdv1Fallback,featureStoreFactory:e=>{const{persistentStore:r}=a;let s;return s=void 0===r?new i.default:t.TypeValidators.Function.is(r)?r(e):r,t.TypeValidators.Function.is(s.applyChanges)?s:new n.default(s)}},e.forEach(e=>{var t;null===(t=this.logger)||void 0===t||t.warn(e)})}this.serviceEndpoints=new t.ServiceEndpoints(c.streamUri,c.baseUri,c.eventsUri,s.analyticsEventPath,s.diagnosticEventPath,s.includeAuthorizationHeader,c.payloadFilterKey),this.eventsCapacity=c.capacity,this.timeout=c.timeout,this.bigSegments=c.bigSegments,this.flushInterval=c.flushInterval,this.pollInterval=c.pollInterval,this.proxyOptions=c.proxyOptions,this.offline=c.offline,this.stream=c.stream,this.streamInitialReconnectDelay=c.streamInitialReconnectDelay,this.useLdd=c.useLdd,this.sendEvents=c.sendEvents,this.allAttributesPrivate=c.allAttributesPrivate,this.privateAttributes=c.privateAttributes,this.contextKeysCapacity=c.contextKeysCapacity,this.contextKeysFlushInterval=c.contextKeysFlushInterval,this.tlsParams=c.tlsParams,this.diagnosticOptOut=c.diagnosticOptOut,this.wrapperName=c.wrapperName,this.payloadFilterKey=c.payloadFilterKey,this.wrapperVersion=c.wrapperVersion,this.tags=new t.ApplicationTags(c),this.diagnosticRecordingInterval=c.diagnosticRecordingInterval,t.TypeValidators.Function.is(c.updateProcessor)?this.updateProcessorFactory=c.updateProcessor:this.updateProcessorFactory=()=>c.updateProcessor,t.TypeValidators.Function.is(c.featureStore)?this.featureStoreFactory=c.featureStore:this.featureStoreFactory=()=>c.featureStore,this.hooks=c.hooks,this.enableEventCompression=c.enableEventCompression,this.getImplementationHooks=null!==(a=s.getImplementationHooks)&&void 0!==a?a:()=>[],this.applicationInfo=c.application}}}(At),Object.defineProperty(Ft,"__esModule",{value:!0});const Ct=a,Lt=o,jt=At;Ft.default=(e,t,r)=>{var i,n,s,a,o,l,c,u,d,h,f,p;let v,g,_;return(null===(i=e.dataSystem)||void 0===i?void 0:i.dataSource)?((0,Lt.isStandardOptions)(e.dataSystem.dataSource)||(0,Lt.isPollingOnlyOptions)(e.dataSystem.dataSource))&&e.dataSystem.dataSource.pollInterval&&(v=(0,Ct.secondsToMillis)(e.dataSystem.dataSource.pollInterval)):v=(0,Ct.secondsToMillis)(e.pollInterval),(null===(n=e.dataSystem)||void 0===n?void 0:n.dataSource)?((0,Lt.isStandardOptions)(e.dataSystem.dataSource)||(0,Lt.isStreamingOnlyOptions)(e.dataSystem.dataSource))&&e.dataSystem.dataSource.streamInitialReconnectDelay&&(g=(0,Ct.secondsToMillis)(e.dataSystem.dataSource.streamInitialReconnectDelay)):g=(0,Ct.secondsToMillis)(e.streamInitialReconnectDelay),_=(null===(s=e.dataSystem)||void 0===s?void 0:s.dataSource)?(0,Lt.isPollingOnlyOptions)(null===(a=e.dataSystem)||void 0===a?void 0:a.dataSource):!e.stream,Object.assign(Object.assign(Object.assign({customBaseURI:e.serviceEndpoints.polling!==jt.defaultValues.baseUri,customStreamURI:e.serviceEndpoints.streaming!==jt.defaultValues.streamUri,customEventsURI:e.serviceEndpoints.events!==jt.defaultValues.eventsUri,eventsCapacity:e.eventsCapacity,connectTimeoutMillis:(0,Ct.secondsToMillis)(e.timeout),socketTimeoutMillis:(0,Ct.secondsToMillis)(e.timeout),eventsFlushIntervalMillis:(0,Ct.secondsToMillis)(e.flushInterval)},v?{pollingIntervalMillis:v}:null),g?{reconnectTimeMillis:g}:null),{contextKeysFlushIntervalMillis:(0,Ct.secondsToMillis)(e.contextKeysFlushInterval),diagnosticRecordingIntervalMillis:(0,Ct.secondsToMillis)(e.diagnosticRecordingInterval),streamingDisabled:_,usingRelayDaemon:null!==(l=null===(o=e.dataSystem)||void 0===o?void 0:o.useLdd)&&void 0!==l?l:e.useLdd,offline:e.offline,allAttributesPrivate:e.allAttributesPrivate,contextKeysCapacity:e.contextKeysCapacity,usingProxy:!!(null===(u=(c=t.requests).usingProxy)||void 0===u?void 0:u.call(c)),usingProxyAuthenticator:!!(null===(h=(d=t.requests).usingProxyAuth)||void 0===h?void 0:h.call(d)),dataStoreType:null!==(p=null===(f=r.getDescription)||void 0===f?void 0:f.call(r))&&void 0!==p?p:"memory"})};var Nt={};Object.defineProperty(Nt,"__esModule",{value:!0}),Nt.allAsync=Nt.firstSeriesAsync=Nt.allSeriesAsync=Nt.firstResult=void 0,Nt.firstResult=function(e,t){let r;return null==e||e.some((e,i)=>(r=t(e,i),!!r)),r};function $t(e,t,r,i,n){e?i<(null==e?void 0:e.length)?t(e[i],i,s=>{if(r){if(!s)return void n(!1)}else if(s)return void n(!0);e.length>50?Promise.resolve().then(()=>{$t(e,t,r,i+1,n)}):$t(e,t,r,i+1,n)}):n(r):n(!1)}Nt.allSeriesAsync=function(e,t,r){$t(e,t,!0,0,r)},Nt.firstSeriesAsync=function(e,t,r){$t(e,t,!1,0,r)},Nt.allAsync=function(e,t,r){e?Promise.all(null==e?void 0:e.map(e=>new Promise(r=>{t(e,r)}))).then(e=>{r(e.every(e=>e))}):r(!1)};var Vt={},Ut={};Object.defineProperty(Ut,"__esModule",{value:!0});class Kt{static prerequisiteFailed(e){return{kind:"PREREQUISITE_FAILED",prerequisiteKey:e}}static ruleMatch(e,t){return{kind:"RULE_MATCH",ruleId:e,ruleIndex:t}}}Kt.Fallthrough={kind:"FALLTHROUGH"},Kt.Off={kind:"OFF"},Kt.TargetMatch={kind:"TARGET_MATCH"},Ut.default=Kt,Object.defineProperty(Vt,"__esModule",{value:!0});const zt=Ut;class Bt{constructor(e,t,r){this.isError=e,this.detail=t,this.message=r,this.isError=e,this.detail=t,this.message=r}get isOff(){return this.detail.reason.kind===zt.default.Off.kind}setDefault(e){this.detail.value=e}static forError(e,t,r){return new Bt(!0,{value:null!=r?r:null,variationIndex:null,reason:{kind:"ERROR",errorKind:e}},t)}static forSuccess(e,t,r){return new Bt(!1,{value:e,variationIndex:void 0===r?null:r,reason:t})}}Vt.default=Bt;var Ht={},qt={};Object.defineProperty(qt,"__esModule",{value:!0});qt.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,r,i,n="user",s){const a=function(e){return"string"==typeof e?e:Number.isInteger(e)?String(e):null}(e.valueForKind(r,n));if(null===a){return[0,e.kinds.indexOf(n)>=0]}const o=`${s?Number(s):`${t}.${i}`}.${a}`;return[parseInt(this._sha1Hex(o).substring(0,15),16)/0x1000000000000000,!0]}};var Gt={},Wt={};Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.getBucketBy=Wt.getOffVariation=Wt.getVariation=void 0;const Jt=a,Xt=Vt,{ErrorKinds:Yt}=Jt.internal,Zt=new Jt.AttributeReference("key");function Qt(e,t,r){return Jt.TypeValidators.Number.is(t)&&t>=0&&t<e.variations.length?Xt.default.forSuccess(e.variations[t],r,t):Xt.default.forError(Yt.MalformedFlag,"Invalid variation index in flag")}Wt.getVariation=Qt,Wt.getOffVariation=function(e,t){return Jt.TypeValidators.Number.is(e.offVariation)?Qt(e,e.offVariation,t):Xt.default.forSuccess(null,t)},Wt.getBucketBy=function(e,t){var r;return null!==(r=e?void 0:t)&&void 0!==r?r:Zt},Object.defineProperty(Gt,"__esModule",{value:!0});const er=a,tr=Nt,rr=Ut,ir=Wt;function nr(e,t,r){const i=r.key(t.contextKind);if(void 0!==i){if(t.values.indexOf(i)>=0)return(0,ir.getVariation)(e,t.variation,rr.default.TargetMatch)}}Gt.default=function(e,t){var r;return(null===(r=e.contextTargets)||void 0===r?void 0:r.length)?(0,tr.firstResult)(e.contextTargets,r=>{if(!r.contextKind||r.contextKind===er.Context.UserKind){const i=(e.targets||[]).find(e=>e.variation===r.variation);return i?nr(e,i,t):void 0}return nr(e,r,t)}):(0,tr.firstResult)(e.targets,r=>nr(e,r,t))};var sr={};Object.defineProperty(sr,"__esModule",{value:!0}),sr.default=function(e){return`${e.key}.g${e.generation}`};var ar={},or={},lr={exports:{}};var cr={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};var ur="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};!function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:i,MAX_LENGTH:n}=cr,s=ur,a=(t=e.exports={}).re=[],o=t.safeRe=[],l=t.src=[],c=t.t={};let u=0;const d="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",n],[d,i]],f=(e,t,r)=>{const i=(e=>{for(const[t,r]of h)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),n=u++;s(e,n,t),c[e]=n,l[n]=t,a[n]=new RegExp(t,r?"g":void 0),o[n]=new RegExp(i,r?"g":void 0)};f("NUMERICIDENTIFIER","0|[1-9]\\d*"),f("NUMERICIDENTIFIERLOOSE","\\d+"),f("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),f("MAINVERSION",`(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})`),f("MAINVERSIONLOOSE",`(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASEIDENTIFIER",`(?:${l[c.NUMERICIDENTIFIER]}|${l[c.NONNUMERICIDENTIFIER]})`),f("PRERELEASEIDENTIFIERLOOSE",`(?:${l[c.NUMERICIDENTIFIERLOOSE]}|${l[c.NONNUMERICIDENTIFIER]})`),f("PRERELEASE",`(?:-(${l[c.PRERELEASEIDENTIFIER]}(?:\\.${l[c.PRERELEASEIDENTIFIER]})*))`),f("PRERELEASELOOSE",`(?:-?(${l[c.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[c.PRERELEASEIDENTIFIERLOOSE]})*))`),f("BUILDIDENTIFIER",`${d}+`),f("BUILD",`(?:\\+(${l[c.BUILDIDENTIFIER]}(?:\\.${l[c.BUILDIDENTIFIER]})*))`),f("FULLPLAIN",`v?${l[c.MAINVERSION]}${l[c.PRERELEASE]}?${l[c.BUILD]}?`),f("FULL",`^${l[c.FULLPLAIN]}$`),f("LOOSEPLAIN",`[v=\\s]*${l[c.MAINVERSIONLOOSE]}${l[c.PRERELEASELOOSE]}?${l[c.BUILD]}?`),f("LOOSE",`^${l[c.LOOSEPLAIN]}$`),f("GTLT","((?:<|>)?=?)"),f("XRANGEIDENTIFIERLOOSE",`${l[c.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),f("XRANGEIDENTIFIER",`${l[c.NUMERICIDENTIFIER]}|x|X|\\*`),f("XRANGEPLAIN",`[v=\\s]*(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:${l[c.PRERELEASE]})?${l[c.BUILD]}?)?)?`),f("XRANGEPLAINLOOSE",`[v=\\s]*(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:${l[c.PRERELEASELOOSE]})?${l[c.BUILD]}?)?)?`),f("XRANGE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAIN]}$`),f("XRANGELOOSE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAINLOOSE]}$`),f("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),f("COERCERTL",l[c.COERCE],!0),f("LONETILDE","(?:~>?)"),f("TILDETRIM",`(\\s*)${l[c.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",f("TILDE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAIN]}$`),f("TILDELOOSE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAINLOOSE]}$`),f("LONECARET","(?:\\^)"),f("CARETTRIM",`(\\s*)${l[c.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",f("CARET",`^${l[c.LONECARET]}${l[c.XRANGEPLAIN]}$`),f("CARETLOOSE",`^${l[c.LONECARET]}${l[c.XRANGEPLAINLOOSE]}$`),f("COMPARATORLOOSE",`^${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]})$|^$`),f("COMPARATOR",`^${l[c.GTLT]}\\s*(${l[c.FULLPLAIN]})$|^$`),f("COMPARATORTRIM",`(\\s*)${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]}|${l[c.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",f("HYPHENRANGE",`^\\s*(${l[c.XRANGEPLAIN]})\\s+-\\s+(${l[c.XRANGEPLAIN]})\\s*$`),f("HYPHENRANGELOOSE",`^\\s*(${l[c.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[c.XRANGEPLAINLOOSE]})\\s*$`),f("STAR","(<|>)?=?\\s*\\*"),f("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),f("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(lr,lr.exports);var dr=lr.exports;const hr=Object.freeze({loose:!0}),fr=Object.freeze({});var pr=e=>e?"object"!=typeof e?hr:e:fr;const vr=/^[0-9]+$/,gr=(e,t)=>{const r=vr.test(e),i=vr.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};var _r={compareIdentifiers:gr,rcompareIdentifiers:(e,t)=>gr(t,e)};const mr=ur,{MAX_LENGTH:yr,MAX_SAFE_INTEGER:br}=cr,{safeRe:Er,t:Sr}=dr,wr=pr,{compareIdentifiers:Or}=_r;var kr=class e{constructor(t,r){if(r=wr(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>yr)throw new TypeError(`version is longer than ${yr} characters`);mr("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;const i=t.trim().match(r.loose?Er[Sr.LOOSE]:Er[Sr.FULL]);if(!i)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>br||this.major<0)throw new TypeError("Invalid major version");if(this.minor>br||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>br||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<br)return t}return e}):this.prerelease=[],this.build=i[5]?i[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(mr("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if("string"==typeof t&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),Or(this.major,t.major)||Or(this.minor,t.minor)||Or(this.patch,t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{const e=this.prerelease[r],i=t.prerelease[r];if(mr("prerelease compare",r,e,i),void 0===e&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===e)return-1;if(e!==i)return Or(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{const e=this.build[r],i=t.build[r];if(mr("prerelease compare",r,e,i),void 0===e&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===e)return-1;if(e!==i)return Or(e,i)}while(++r)}inc(e,t,r){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(r)?1:0;if(!t&&!1===r)throw new Error("invalid increment argument: identifier is empty");if(0===this.prerelease.length)this.prerelease=[e];else{let i=this.prerelease.length;for(;--i>=0;)"number"==typeof this.prerelease[i]&&(this.prerelease[i]++,i=-2);if(-1===i){if(t===this.prerelease.join(".")&&!1===r)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let i=[t,e];!1===r&&(i=[t]),0===Or(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};const Dr=kr;var Tr=(e,t,r=!1)=>{if(e instanceof Dr)return e;try{return new Dr(e,t)}catch(e){if(!r)return null;throw e}};const Pr=Tr;var Ir=(e,t)=>{const r=Pr(e,t);return r?r.version:null};const xr=Tr;var Rr=(e,t)=>{const r=xr(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};const Mr=kr;var Fr=(e,t,r,i,n)=>{"string"==typeof r&&(n=i,i=r,r=void 0);try{return new Mr(e instanceof Mr?e.version:e,r).inc(t,i,n).version}catch(e){return null}};const Ar=Tr;var Cr=(e,t)=>{const r=Ar(e,null,!0),i=Ar(t,null,!0),n=r.compare(i);if(0===n)return null;const s=n>0,a=s?r:i,o=s?i:r,l=!!a.prerelease.length;if(!!o.prerelease.length&&!l)return o.patch||o.minor?a.patch?"patch":a.minor?"minor":"major":"major";const c=l?"pre":"";return r.major!==i.major?c+"major":r.minor!==i.minor?c+"minor":r.patch!==i.patch?c+"patch":"prerelease"};const Lr=kr;var jr=(e,t)=>new Lr(e,t).major;const Nr=kr;var $r=(e,t)=>new Nr(e,t).minor;const Vr=kr;var Ur=(e,t)=>new Vr(e,t).patch;const Kr=Tr;var zr=(e,t)=>{const r=Kr(e,t);return r&&r.prerelease.length?r.prerelease:null};const Br=kr;var Hr=(e,t,r)=>new Br(e,r).compare(new Br(t,r));const qr=Hr;var Gr=(e,t,r)=>qr(t,e,r);const Wr=Hr;var Jr=(e,t)=>Wr(e,t,!0);const Xr=kr;var Yr=(e,t,r)=>{const i=new Xr(e,r),n=new Xr(t,r);return i.compare(n)||i.compareBuild(n)};const Zr=Yr;var Qr=(e,t)=>e.sort((e,r)=>Zr(e,r,t));const ei=Yr;var ti=(e,t)=>e.sort((e,r)=>ei(r,e,t));const ri=Hr;var ii=(e,t,r)=>ri(e,t,r)>0;const ni=Hr;var si=(e,t,r)=>ni(e,t,r)<0;const ai=Hr;var oi=(e,t,r)=>0===ai(e,t,r);const li=Hr;var ci=(e,t,r)=>0!==li(e,t,r);const ui=Hr;var di=(e,t,r)=>ui(e,t,r)>=0;const hi=Hr;var fi=(e,t,r)=>hi(e,t,r)<=0;const pi=oi,vi=ci,gi=ii,_i=di,mi=si,yi=fi;var bi=(e,t,r,i)=>{switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return pi(e,r,i);case"!=":return vi(e,r,i);case">":return gi(e,r,i);case">=":return _i(e,r,i);case"<":return mi(e,r,i);case"<=":return yi(e,r,i);default:throw new TypeError(`Invalid operator: ${t}`)}};const Ei=kr,Si=Tr,{safeRe:wi,t:Oi}=dr;var ki,Di,Ti,Pi,Ii,xi,Ri,Mi,Fi,Ai,Ci=(e,t)=>{if(e instanceof Ei)return e;if("number"==typeof e&&(e=String(e)),"string"!=typeof e)return null;let r=null;if((t=t||{}).rtl){let t;for(;(t=wi[Oi.COERCERTL].exec(e))&&(!r||r.index+r[0].length!==e.length);)r&&t.index+t[0].length===r.index+r[0].length||(r=t),wi[Oi.COERCERTL].lastIndex=t.index+t[1].length+t[2].length;wi[Oi.COERCERTL].lastIndex=-1}else r=e.match(wi[Oi.COERCE]);return null===r?null:Si(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,t)};function Li(){if(Pi)return Ti;function e(t){var r=this;if(r instanceof e||(r=new e),r.tail=null,r.head=null,r.length=0,t&&"function"==typeof t.forEach)t.forEach(function(e){r.push(e)});else if(arguments.length>0)for(var i=0,n=arguments.length;i<n;i++)r.push(arguments[i]);return r}function t(e,t,r){var i=t===e.head?new n(r,null,t,e):new n(r,t,t.next,e);return null===i.next&&(e.tail=i),null===i.prev&&(e.head=i),e.length++,i}function r(e,t){e.tail=new n(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function i(e,t){e.head=new n(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function n(e,t,r,i){if(!(this instanceof n))return new n(e,t,r,i);this.list=i,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,r?(r.prev=this,this.next=r):this.next=null}Pi=1,Ti=e,e.Node=n,e.create=e,e.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,r=e.prev;return t&&(t.prev=r),r&&(r.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=r),e.list.length--,e.next=null,e.prev=null,e.list=null,t},e.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},e.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},e.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)r(this,arguments[e]);return this.length},e.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)i(this,arguments[e]);return this.length},e.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},e.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},e.prototype.forEach=function(e,t){t=t||this;for(var r=this.head,i=0;null!==r;i++)e.call(t,r.value,i,this),r=r.next},e.prototype.forEachReverse=function(e,t){t=t||this;for(var r=this.tail,i=this.length-1;null!==r;i--)e.call(t,r.value,i,this),r=r.prev},e.prototype.get=function(e){for(var t=0,r=this.head;null!==r&&t<e;t++)r=r.next;if(t===e&&null!==r)return r.value},e.prototype.getReverse=function(e){for(var t=0,r=this.tail;null!==r&&t<e;t++)r=r.prev;if(t===e&&null!==r)return r.value},e.prototype.map=function(t,r){r=r||this;for(var i=new e,n=this.head;null!==n;)i.push(t.call(r,n.value,this)),n=n.next;return i},e.prototype.mapReverse=function(t,r){r=r||this;for(var i=new e,n=this.tail;null!==n;)i.push(t.call(r,n.value,this)),n=n.prev;return i},e.prototype.reduce=function(e,t){var r,i=this.head;if(arguments.length>1)r=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");i=this.head.next,r=this.head.value}for(var n=0;null!==i;n++)r=e(r,i.value,n),i=i.next;return r},e.prototype.reduceReverse=function(e,t){var r,i=this.tail;if(arguments.length>1)r=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");i=this.tail.prev,r=this.tail.value}for(var n=this.length-1;null!==i;n--)r=e(r,i.value,n),i=i.prev;return r},e.prototype.toArray=function(){for(var e=new Array(this.length),t=0,r=this.head;null!==r;t++)e[t]=r.value,r=r.next;return e},e.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,r=this.tail;null!==r;t++)e[t]=r.value,r=r.prev;return e},e.prototype.slice=function(t,r){(r=r||this.length)<0&&(r+=this.length),(t=t||0)<0&&(t+=this.length);var i=new e;if(r<t||r<0)return i;t<0&&(t=0),r>this.length&&(r=this.length);for(var n=0,s=this.head;null!==s&&n<t;n++)s=s.next;for(;null!==s&&n<r;n++,s=s.next)i.push(s.value);return i},e.prototype.sliceReverse=function(t,r){(r=r||this.length)<0&&(r+=this.length),(t=t||0)<0&&(t+=this.length);var i=new e;if(r<t||r<0)return i;t<0&&(t=0),r>this.length&&(r=this.length);for(var n=this.length,s=this.tail;null!==s&&n>r;n--)s=s.prev;for(;null!==s&&n>t;n--,s=s.prev)i.push(s.value);return i},e.prototype.splice=function(e,r,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var n=0,s=this.head;null!==s&&n<e;n++)s=s.next;var a=[];for(n=0;s&&n<r;n++)a.push(s.value),s=this.removeNode(s);null===s&&(s=this.tail),s!==this.head&&s!==this.tail&&(s=s.prev);for(n=0;n<i.length;n++)s=t(this,s,i[n]);return a},e.prototype.reverse=function(){for(var e=this.head,t=this.tail,r=e;null!==r;r=r.prev){var i=r.prev;r.prev=r.next,r.next=i}return this.head=t,this.tail=e,this};try{(Di?ki:(Di=1,ki=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}))(e)}catch(e){}return Ti}function ji(){if(Mi)return Ri;Mi=1;class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof n)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().split(/\s+/).join(" "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter(e=>!p(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&v(e[0])){this.set=[e];break}}this.format()}format(){return this.range=this.set.map(e=>e.join(" ").trim()).join("||").trim(),this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&h)|(this.options.loose&&f))+":"+e,i=r.get(t);if(i)return i;const a=this.options.loose,v=a?o[l.HYPHENRANGELOOSE]:o[l.HYPHENRANGE];e=e.replace(v,T(this.options.includePrerelease)),s("hyphen replace",e),e=e.replace(o[l.COMPARATORTRIM],c),s("comparator trim",e),e=e.replace(o[l.TILDETRIM],u),s("tilde trim",e),e=e.replace(o[l.CARETTRIM],d),s("caret trim",e);let g=e.split(" ").map(e=>_(e,this.options)).join(" ").split(/\s+/).map(e=>D(e,this.options));a&&(g=g.filter(e=>(s("loose invalid filter",e,this.options),!!e.match(o[l.COMPARATORLOOSE])))),s("range list",g);const m=new Map,y=g.map(e=>new n(e,this.options));for(const e of y){if(p(e))return[e];m.set(e.value,e)}m.size>1&&m.has("")&&m.delete("");const b=[...m.values()];return r.set(t,b),b}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(e=>g(e,r)&&t.set.some(t=>g(t,r)&&e.every(e=>t.every(t=>e.intersects(t,r)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new a(e,this.options)}catch(e){return!1}for(let t=0;t<this.set.length;t++)if(P(this.set[t],e,this.options))return!0;return!1}}Ri=e;const t=function(){if(xi)return Ii;xi=1;const e=Li(),t=Symbol("max"),r=Symbol("length"),i=Symbol("lengthCalculator"),n=Symbol("allowStale"),s=Symbol("maxAge"),a=Symbol("dispose"),o=Symbol("noDisposeOnSet"),l=Symbol("lruList"),c=Symbol("cache"),u=Symbol("updateAgeOnGet"),d=()=>1,h=(e,t,r)=>{const i=e[c].get(t);if(i){const t=i.value;if(f(e,t)){if(v(e,i),!e[n])return}else r&&(e[u]&&(i.value.now=Date.now()),e[l].unshiftNode(i));return t.value}},f=(e,t)=>{if(!t||!t.maxAge&&!e[s])return!1;const r=Date.now()-t.now;return t.maxAge?r>t.maxAge:e[s]&&r>e[s]},p=e=>{if(e[r]>e[t])for(let i=e[l].tail;e[r]>e[t]&&null!==i;){const t=i.prev;v(e,i),i=t}},v=(e,t)=>{if(t){const i=t.value;e[a]&&e[a](i.key,i.value),e[r]-=i.length,e[c].delete(i.key),e[l].removeNode(t)}};class g{constructor(e,t,r,i,n){this.key=e,this.value=t,this.length=r,this.now=i,this.maxAge=n||0}}const _=(e,t,r,i)=>{let s=r.value;f(e,s)&&(v(e,r),e[n]||(s=void 0)),s&&t.call(i,s.value,s.key,e)};return Ii=class{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[t]=e.max||1/0;const r=e.length||d;if(this[i]="function"!=typeof r?d:r,this[n]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[s]=e.maxAge||0,this[a]=e.dispose,this[o]=e.noDisposeOnSet||!1,this[u]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[t]=e||1/0,p(this)}get max(){return this[t]}set allowStale(e){this[n]=!!e}get allowStale(){return this[n]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[s]=e,p(this)}get maxAge(){return this[s]}set lengthCalculator(e){"function"!=typeof e&&(e=d),e!==this[i]&&(this[i]=e,this[r]=0,this[l].forEach(e=>{e.length=this[i](e.value,e.key),this[r]+=e.length})),p(this)}get lengthCalculator(){return this[i]}get length(){return this[r]}get itemCount(){return this[l].length}rforEach(e,t){t=t||this;for(let r=this[l].tail;null!==r;){const i=r.prev;_(this,e,r,t),r=i}}forEach(e,t){t=t||this;for(let r=this[l].head;null!==r;){const i=r.next;_(this,e,r,t),r=i}}keys(){return this[l].toArray().map(e=>e.key)}values(){return this[l].toArray().map(e=>e.value)}reset(){this[a]&&this[l]&&this[l].length&&this[l].forEach(e=>this[a](e.key,e.value)),this[c]=new Map,this[l]=new e,this[r]=0}dump(){return this[l].map(e=>!f(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)}).toArray().filter(e=>e)}dumpLru(){return this[l]}set(e,n,u){if((u=u||this[s])&&"number"!=typeof u)throw new TypeError("maxAge must be a number");const d=u?Date.now():0,h=this[i](n,e);if(this[c].has(e)){if(h>this[t])return v(this,this[c].get(e)),!1;const i=this[c].get(e).value;return this[a]&&(this[o]||this[a](e,i.value)),i.now=d,i.maxAge=u,i.value=n,this[r]+=h-i.length,i.length=h,this.get(e),p(this),!0}const f=new g(e,n,h,d,u);return f.length>this[t]?(this[a]&&this[a](e,n),!1):(this[r]+=f.length,this[l].unshift(f),this[c].set(e,this[l].head),p(this),!0)}has(e){if(!this[c].has(e))return!1;const t=this[c].get(e).value;return!f(this,t)}get(e){return h(this,e,!0)}peek(e){return h(this,e,!1)}pop(){const e=this[l].tail;return e?(v(this,e),e.value):null}del(e){v(this,this[c].get(e))}load(e){this.reset();const t=Date.now();for(let r=e.length-1;r>=0;r--){const i=e[r],n=i.e||0;if(0===n)this.set(i.k,i.v);else{const e=n-t;e>0&&this.set(i.k,i.v,e)}}}prune(){this[c].forEach((e,t)=>h(this,t,!1))}},Ii}(),r=new t({max:1e3}),i=pr,n=Ni(),s=ur,a=kr,{safeRe:o,t:l,comparatorTrimReplace:c,tildeTrimReplace:u,caretTrimReplace:d}=dr,{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:f}=cr,p=e=>"<0.0.0-0"===e.value,v=e=>""===e.value,g=(e,t)=>{let r=!0;const i=e.slice();let n=i.pop();for(;r&&i.length;)r=i.every(e=>n.intersects(e,t)),n=i.pop();return r},_=(e,t)=>(s("comp",e,t),e=E(e,t),s("caret",e),e=y(e,t),s("tildes",e),e=w(e,t),s("xrange",e),e=k(e,t),s("stars",e),e),m=e=>!e||"x"===e.toLowerCase()||"*"===e,y=(e,t)=>e.trim().split(/\s+/).map(e=>b(e,t)).join(" "),b=(e,t)=>{const r=t.loose?o[l.TILDELOOSE]:o[l.TILDE];return e.replace(r,(t,r,i,n,a)=>{let o;return s("tilde",e,t,r,i,n,a),m(r)?o="":m(i)?o=`>=${r}.0.0 <${+r+1}.0.0-0`:m(n)?o=`>=${r}.${i}.0 <${r}.${+i+1}.0-0`:a?(s("replaceTilde pr",a),o=`>=${r}.${i}.${n}-${a} <${r}.${+i+1}.0-0`):o=`>=${r}.${i}.${n} <${r}.${+i+1}.0-0`,s("tilde return",o),o})},E=(e,t)=>e.trim().split(/\s+/).map(e=>S(e,t)).join(" "),S=(e,t)=>{s("caret",e,t);const r=t.loose?o[l.CARETLOOSE]:o[l.CARET],i=t.includePrerelease?"-0":"";return e.replace(r,(t,r,n,a,o)=>{let l;return s("caret",e,t,r,n,a,o),m(r)?l="":m(n)?l=`>=${r}.0.0${i} <${+r+1}.0.0-0`:m(a)?l="0"===r?`>=${r}.${n}.0${i} <${r}.${+n+1}.0-0`:`>=${r}.${n}.0${i} <${+r+1}.0.0-0`:o?(s("replaceCaret pr",o),l="0"===r?"0"===n?`>=${r}.${n}.${a}-${o} <${r}.${n}.${+a+1}-0`:`>=${r}.${n}.${a}-${o} <${r}.${+n+1}.0-0`:`>=${r}.${n}.${a}-${o} <${+r+1}.0.0-0`):(s("no pr"),l="0"===r?"0"===n?`>=${r}.${n}.${a}${i} <${r}.${n}.${+a+1}-0`:`>=${r}.${n}.${a}${i} <${r}.${+n+1}.0-0`:`>=${r}.${n}.${a} <${+r+1}.0.0-0`),s("caret return",l),l})},w=(e,t)=>(s("replaceXRanges",e,t),e.split(/\s+/).map(e=>O(e,t)).join(" ")),O=(e,t)=>{e=e.trim();const r=t.loose?o[l.XRANGELOOSE]:o[l.XRANGE];return e.replace(r,(r,i,n,a,o,l)=>{s("xRange",e,r,i,n,a,o,l);const c=m(n),u=c||m(a),d=u||m(o),h=d;return"="===i&&h&&(i=""),l=t.includePrerelease?"-0":"",c?r=">"===i||"<"===i?"<0.0.0-0":"*":i&&h?(u&&(a=0),o=0,">"===i?(i=">=",u?(n=+n+1,a=0,o=0):(a=+a+1,o=0)):"<="===i&&(i="<",u?n=+n+1:a=+a+1),"<"===i&&(l="-0"),r=`${i+n}.${a}.${o}${l}`):u?r=`>=${n}.0.0${l} <${+n+1}.0.0-0`:d&&(r=`>=${n}.${a}.0${l} <${n}.${+a+1}.0-0`),s("xRange return",r),r})},k=(e,t)=>(s("replaceStars",e,t),e.trim().replace(o[l.STAR],"")),D=(e,t)=>(s("replaceGTE0",e,t),e.trim().replace(o[t.includePrerelease?l.GTE0PRE:l.GTE0],"")),T=e=>(t,r,i,n,s,a,o,l,c,u,d,h,f)=>`${r=m(i)?"":m(n)?`>=${i}.0.0${e?"-0":""}`:m(s)?`>=${i}.${n}.0${e?"-0":""}`:a?`>=${r}`:`>=${r}${e?"-0":""}`} ${l=m(c)?"":m(u)?`<${+c+1}.0.0-0`:m(d)?`<${c}.${+u+1}.0-0`:h?`<=${c}.${u}.${d}-${h}`:e?`<${c}.${u}.${+d+1}-0`:`<=${l}`}`.trim(),P=(e,t,r)=>{for(let r=0;r<e.length;r++)if(!e[r].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let r=0;r<e.length;r++)if(s(e[r].semver),e[r].semver!==n.ANY&&e[r].semver.prerelease.length>0){const i=e[r].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0};return Ri}function Ni(){if(Ai)return Fi;Ai=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(i,n){if(n=r(n),i instanceof t){if(i.loose===!!n.loose)return i;i=i.value}i=i.trim().split(/\s+/).join(" "),a("comparator",i,n),this.options=n,this.loose=!!n.loose,this.parse(i),this.semver===e?this.value="":this.value=this.operator+this.semver.version,a("comp",this)}parse(t){const r=this.options.loose?i[n.COMPARATORLOOSE]:i[n.COMPARATOR],s=t.match(r);if(!s)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==s[1]?s[1]:"","="===this.operator&&(this.operator=""),s[2]?this.semver=new o(s[2],this.options.loose):this.semver=e}toString(){return this.value}test(t){if(a("Comparator.test",t,this.options.loose),this.semver===e||t===e)return!0;if("string"==typeof t)try{t=new o(t,this.options)}catch(e){return!1}return s(t,this.operator,this.semver,this.options)}intersects(e,i){if(!(e instanceof t))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new l(e.value,i).test(this.value):""===e.operator?""===e.value||new l(this.value,i).test(e.semver):(!(i=r(i)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!i.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(s(this.semver,"<",e.semver,i)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(s(this.semver,">",e.semver,i)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}Fi=t;const r=pr,{safeRe:i,t:n}=dr,s=bi,a=ur,o=kr,l=ji();return Fi}const $i=ji();var Vi=(e,t,r)=>{try{t=new $i(t,r)}catch(e){return!1}return t.test(e)};const Ui=ji();var Ki=(e,t)=>new Ui(e,t).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" "));const zi=kr,Bi=ji();var Hi=(e,t,r)=>{let i=null,n=null,s=null;try{s=new Bi(t,r)}catch(e){return null}return e.forEach(e=>{s.test(e)&&(i&&-1!==n.compare(e)||(i=e,n=new zi(i,r)))}),i};const qi=kr,Gi=ji();var Wi=(e,t,r)=>{let i=null,n=null,s=null;try{s=new Gi(t,r)}catch(e){return null}return e.forEach(e=>{s.test(e)&&(i&&1!==n.compare(e)||(i=e,n=new qi(i,r)))}),i};const Ji=kr,Xi=ji(),Yi=ii;var Zi=(e,t)=>{e=new Xi(e,t);let r=new Ji("0.0.0");if(e.test(r))return r;if(r=new Ji("0.0.0-0"),e.test(r))return r;r=null;for(let t=0;t<e.set.length;++t){const i=e.set[t];let n=null;i.forEach(e=>{const t=new Ji(e.semver.version);switch(e.operator){case">":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":n&&!Yi(t,n)||(n=t);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}),!n||r&&!Yi(r,n)||(r=n)}return r&&e.test(r)?r:null};const Qi=ji();var en=(e,t)=>{try{return new Qi(e,t).range||"*"}catch(e){return null}};const tn=kr,rn=Ni(),{ANY:nn}=rn,sn=ji(),an=Vi,on=ii,ln=si,cn=fi,un=di;var dn=(e,t,r,i)=>{let n,s,a,o,l;switch(e=new tn(e,i),t=new sn(t,i),r){case">":n=on,s=cn,a=ln,o=">",l=">=";break;case"<":n=ln,s=un,a=on,o="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(an(e,t,i))return!1;for(let r=0;r<t.set.length;++r){const c=t.set[r];let u=null,d=null;if(c.forEach(e=>{e.semver===nn&&(e=new rn(">=0.0.0")),u=u||e,d=d||e,n(e.semver,u.semver,i)?u=e:a(e.semver,d.semver,i)&&(d=e)}),u.operator===o||u.operator===l)return!1;if((!d.operator||d.operator===o)&&s(e,d.semver))return!1;if(d.operator===l&&a(e,d.semver))return!1}return!0};const hn=dn;var fn=(e,t,r)=>hn(e,t,">",r);const pn=dn;var vn=(e,t,r)=>pn(e,t,"<",r);const gn=ji();var _n=(e,t,r)=>(e=new gn(e,r),t=new gn(t,r),e.intersects(t,r));const mn=Vi,yn=Hr;const bn=ji(),En=Ni(),{ANY:Sn}=En,wn=Vi,On=Hr,kn=[new En(">=0.0.0-0")],Dn=[new En(">=0.0.0")],Tn=(e,t,r)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===Sn){if(1===t.length&&t[0].semver===Sn)return!0;e=r.includePrerelease?kn:Dn}if(1===t.length&&t[0].semver===Sn){if(r.includePrerelease)return!0;t=Dn}const i=new Set;let n,s,a,o,l,c,u;for(const t of e)">"===t.operator||">="===t.operator?n=Pn(n,t,r):"<"===t.operator||"<="===t.operator?s=In(s,t,r):i.add(t.semver);if(i.size>1)return null;if(n&&s){if(a=On(n.semver,s.semver,r),a>0)return null;if(0===a&&(">="!==n.operator||"<="!==s.operator))return null}for(const e of i){if(n&&!wn(e,String(n),r))return null;if(s&&!wn(e,String(s),r))return null;for(const i of t)if(!wn(e,String(i),r))return!1;return!0}let d=!(!s||r.includePrerelease||!s.semver.prerelease.length)&&s.semver,h=!(!n||r.includePrerelease||!n.semver.prerelease.length)&&n.semver;d&&1===d.prerelease.length&&"<"===s.operator&&0===d.prerelease[0]&&(d=!1);for(const e of t){if(u=u||">"===e.operator||">="===e.operator,c=c||"<"===e.operator||"<="===e.operator,n)if(h&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===h.major&&e.semver.minor===h.minor&&e.semver.patch===h.patch&&(h=!1),">"===e.operator||">="===e.operator){if(o=Pn(n,e,r),o===e&&o!==n)return!1}else if(">="===n.operator&&!wn(n.semver,String(e),r))return!1;if(s)if(d&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===d.major&&e.semver.minor===d.minor&&e.semver.patch===d.patch&&(d=!1),"<"===e.operator||"<="===e.operator){if(l=In(s,e,r),l===e&&l!==s)return!1}else if("<="===s.operator&&!wn(s.semver,String(e),r))return!1;if(!e.operator&&(s||n)&&0!==a)return!1}return!(n&&c&&!s&&0!==a)&&(!(s&&u&&!n&&0!==a)&&(!h&&!d))},Pn=(e,t,r)=>{if(!e)return t;const i=On(e.semver,t.semver,r);return i>0?e:i<0||">"===t.operator&&">="===e.operator?t:e},In=(e,t,r)=>{if(!e)return t;const i=On(e.semver,t.semver,r);return i<0?e:i>0||"<"===t.operator&&"<="===e.operator?t:e};var xn=(e,t,r={})=>{if(e===t)return!0;e=new bn(e,r),t=new bn(t,r);let i=!1;e:for(const n of e.set){for(const e of t.set){const t=Tn(n,e,r);if(i=i||null!==t,t)continue e}if(i)return!1}return!0};const Rn=dr,Mn=cr,Fn=kr,An=_r,Cn=(e,t,r)=>{const i=[];let n=null,s=null;const a=e.sort((e,t)=>yn(e,t,r));for(const e of a){mn(e,t,r)?(s=e,n||(n=e)):(s&&i.push([n,s]),s=null,n=null)}n&&i.push([n,null]);const o=[];for(const[e,t]of i)e===t?o.push(e):t||e!==a[0]?t?e===a[0]?o.push(`<=${t}`):o.push(`${e} - ${t}`):o.push(`>=${e}`):o.push("*");const l=o.join(" || "),c="string"==typeof t.raw?t.raw:String(t);return l.length<c.length?l:t};var Ln={parse:Tr,valid:Ir,clean:Rr,inc:Fr,diff:Cr,major:jr,minor:$r,patch:Ur,prerelease:zr,compare:Hr,rcompare:Gr,compareLoose:Jr,compareBuild:Yr,sort:Qr,rsort:ti,gt:ii,lt:si,eq:oi,neq:ci,gte:di,lte:fi,cmp:bi,coerce:Ci,Comparator:Ni(),Range:ji(),satisfies:Vi,toComparators:Ki,maxSatisfying:Hi,minSatisfying:Wi,minVersion:Zi,validRange:en,outside:dn,gtr:fn,ltr:vn,intersects:_n,simplifyRange:Cn,subset:xn,SemVer:Fn,re:Rn.re,src:Rn.src,tokens:Rn.t,SEMVER_SPEC_VERSION:Mn.SEMVER_SPEC_VERSION,RELEASE_TYPES:Mn.RELEASE_TYPES,compareIdentifiers:An.compareIdentifiers,rcompareIdentifiers:An.rcompareIdentifiers};Object.defineProperty(or,"__esModule",{value:!0});const jn=Ln,Nn=a,$n=/^\d+(\.\d+)?(\.\d+)?/;function Vn(e){if(Nn.TypeValidators.String.is(e)&&!e.startsWith("v")){const t=(0,jn.parse)(e);if(t)return t;const r=$n.exec(e);if(r){let t=r[0];for(let e=1;e<r.length;e+=1)void 0===r[e]&&(t+=".0");return t+=e.substring(r[0].length),(0,jn.parse)(t)}}return null}function Un(e){return(t,r)=>{const i=Vn(t),n=Vn(r);return!!(i&&n&&e(i,n))}}function Kn(e,t,r){return(i,n)=>!(!t.is(i)||!t.is(n))&&(r?e(r(i),r(n)):e(i,n))}function zn(e){return"number"==typeof e?e:Date.parse(e)}const Bn={in:(e,t)=>e===t,endsWith:Kn((e,t)=>e.endsWith(t),Nn.TypeValidators.String),startsWith:Kn((e,t)=>e.startsWith(t),Nn.TypeValidators.String),matches:Kn((e,t)=>function(e,t){try{return new RegExp(e).test(t)}catch(e){return!1}}(t,e),Nn.TypeValidators.String),contains:Kn((e,t)=>e.indexOf(t)>-1,Nn.TypeValidators.String),lessThan:Kn((e,t)=>e<t,Nn.TypeValidators.Number),lessThanOrEqual:Kn((e,t)=>e<=t,Nn.TypeValidators.Number),greaterThan:Kn((e,t)=>e>t,Nn.TypeValidators.Number),greaterThanOrEqual:Kn((e,t)=>e>=t,Nn.TypeValidators.Number),before:Kn((e,t)=>e<t,Nn.TypeValidators.Date,zn),after:Kn((e,t)=>e>t,Nn.TypeValidators.Date,zn),semVerEqual:Un((e,t)=>0===e.compare(t)),semVerLessThan:Un((e,t)=>e.compare(t)<0),semVerGreaterThan:Un((e,t)=>e.compare(t)>0)};or.default=class{static is(e){return Object.prototype.hasOwnProperty.call(Bn,e)}static execute(e,t,r){var i,n;return null!==(n=null===(i=Bn[e])||void 0===i?void 0:i.call(Bn,t,r))&&void 0!==n&&n}},Object.defineProperty(ar,"__esModule",{value:!0}),ar.maybeNegate=void 0;const Hn=or;function qn(e,t){return e.negate?!t:t}function Gn(e,t,r){return r.some(r=>Hn.default.execute(e,t,r))}ar.maybeNegate=qn,ar.default=function(e,t){const r=t.valueForKind(e.attributeReference,e.contextKind);return null!=r&&(Array.isArray(r)?qn(e,r.some(t=>Gn(e.op,t,e.values))):qn(e,Gn(e.op,r,e.values)))};var Wn={};function Jn(e,t,r,i){if(t)for(let r=0;r<t.length;r+=1){const i=t[r],n=e.key(i.contextKind);if(n)if(i.generated_valuesSet){if(i.generated_valuesSet.has(n))return!0}else if(i.values.includes(n))return!0}if(i){const t=e.key("user");if(t&&i.has(t))return!0}else if(r){const t=e.key("user");if(t&&r.includes(t))return!0}return!1}Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.default=function(e,t){if(Jn(t,e.includedContexts,e.included,e.generated_includedSet))return!0;const r=Jn(t,e.excludedContexts,e.excluded,e.generated_excludedSet);return r?!r:void 0},Object.defineProperty(Ht,"__esModule",{value:!0});const Xn=a,Yn=qt,Zn=Nt,Qn=Vt,es=Gt,ts=sr,rs=ar,is=Wn,ns=Ut,ss=Wt,{ErrorKinds:as}=Xn.internal,os={HEALTHY:1,STALE:2,STORE_ERROR:3,NOT_CONFIGURED:4};function ls(e){return void 0!==e&&os[e]||0}function cs(e,t){return void 0!==e&&ls(e)>ls(t)?e:t}function us(e){return{error:!1,isMatch:e,result:void 0}}function ds(e){return{error:!0,isMatch:!1,result:e}}Ht.default=class{constructor(e,t){this._queries=t,this._bucketer=new Yn.default(e.crypto)}async evaluate(e,t,r){return new Promise(i=>{this.evaluateCb(e,t,i,r)})}evaluateCb(e,t,r,i){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,r(e)},!0,i)}_evaluateInternal(e,t,r,i,n,s,a){e.on?this._checkPrerequisites(e,t,r,i,i=>{if(i)return void n(i);const s=(0,es.default)(e,t);s?n(s):this._evaluateRules(e,t,r,r=>{n(r||this._variationForContext(e.fallthrough,t,e,ns.default.Fallthrough))})},s,a):n((0,ss.getOffVariation)(e,ns.default.Off))}_checkPrerequisites(e,t,r,i,n,s,a){let o;e.prerequisites&&e.prerequisites.length?(0,Zn.allSeriesAsync)(e.prerequisites,(n,l,c)=>{if(-1!==i.indexOf(n.key))return o=Qn.default.forError(as.MalformedFlag,`Prerequisite of ${e.key} causing a circular reference. This is probably a temporary condition due to an incomplete update.`),void c(!0);const u=[...i,n.key];this._queries.getFlag(n.key,i=>{if(!i)return o=(0,ss.getOffVariation)(e,ns.default.prerequisiteFailed(n.key)),void c(!1);this._evaluateInternal(i,t,r,u,l=>{var u,d;return null!==(u=r.events)&&void 0!==u||(r.events=[]),s&&(null!==(d=r.prerequisites)&&void 0!==d||(r.prerequisites=[]),r.prerequisites.push(i.key)),a&&r.events.push(a.evalEventServer(i,t,l.detail,null,e)),l.isError?(o=l,c(!1)):l.isOff||l.detail.variationIndex!==n.variation?(o=(0,ss.getOffVariation)(e,ns.default.prerequisiteFailed(n.key)),c(!1)):c(!0)},!1,a)})},()=>{n(o)}):n(void 0)}_evaluateRules(e,t,r,i){let n;(0,Zn.firstSeriesAsync)(e.rules,(i,s,a)=>{this._ruleMatchContext(e,i,s,t,r,[],e=>{n=e,a(!!e)})},()=>i(n))}_clauseMatchContext(e,t,r,i,n){let s;"segmentMatch"!==e.op?e.attributeReference.isValid?n(us((0,rs.default)(e,t))):n(ds(Qn.default.forError(as.MalformedFlag,"Invalid attribute reference in clause"))):(0,Zn.firstSeriesAsync)(e.values,(e,n,a)=>{this._queries.getSegment(e,e=>{if(e){if(r.includes(e.key))return s=Qn.default.forError(as.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=[...r,null==e?void 0:e.key];this.segmentMatchContext(e,t,i,n,e=>{e.error&&(s=e.result),a(e.error||e.isMatch)})}else a(!1)})},t=>n(s?ds(s):us((0,rs.maybeNegate)(e,t))))}_ruleMatchContext(e,t,r,i,n,s,a){if(!t.clauses)return void a(void 0);let o;(0,Zn.allSeriesAsync)(t.clauses,(e,t,r)=>{this._clauseMatchContext(e,i,s,n,e=>(o=e.result,r(e.error||e.isMatch)))},n=>a(o||(n?this._variationForContext(t,i,e,ns.default.ruleMatch(t.id,r)):void 0)))}_variationForContext(e,t,r,i){if(void 0===e)return Qn.default.forError(as.MalformedFlag,"Fallthrough variation undefined");if(void 0!==e.variation)return(0,ss.getVariation)(r,e.variation,i);if(e.rollout){const{rollout:n}=e,{variations:s}=n,a="experiment"===n.kind;if(s&&s.length){const e=(0,ss.getBucketBy)(a,n.bucketByAttributeReference);if(!e.isValid)return Qn.default.forError(as.MalformedFlag,"Invalid attribute reference for bucketBy in rollout");const[o,l]=this._bucketer.bucket(t,r.key,e,r.salt||"",n.contextKind,n.seed),c=Object.assign({},i);let u=0;for(let e=0;e<s.length;e+=1){const t=s[e];if(u+=t.weight/1e5,o<u)return a&&l&&!t.untracked&&(c.inExperiment=!0),(0,ss.getVariation)(r,t.variation,c)}const d=s[s.length-1];return a&&!d.untracked&&(c.inExperiment=!0),(0,ss.getVariation)(r,d.variation,c)}}return Qn.default.forError(as.MalformedFlag,"Variation/rollout object with no variation or rollout")}segmentRuleMatchContext(e,t,r,i,n,s){let a;(0,Zn.allSeriesAsync)(t.clauses,(e,t,s)=>{this._clauseMatchContext(e,r,n,i,e=>{a=e.result,s(e.error||e.isMatch)})},i=>{if(a)return s(ds(a));if(i){if(void 0===t.weight)return s(us(i));const n=(0,ss.getBucketBy)(!1,t.bucketByAttributeReference);if(!n.isValid)return s(ds(Qn.default.forError(as.MalformedFlag,"Invalid attribute reference in clause")));const[a]=this._bucketer.bucket(r,e.key,n,e.salt||"",t.rolloutContextKind);return s(us(a<t.weight/1e5))}return s(us(!1))})}simpleSegmentMatchContext(e,t,r,i,n){if(!e.unbounded){const r=(0,is.default)(e,t);if(void 0!==r)return void n(us(r))}let s;(0,Zn.firstSeriesAsync)(e.rules,(n,a,o)=>{this.segmentRuleMatchContext(e,n,t,r,i,e=>(s=e.result,o(e.error||e.isMatch)))},e=>n(s?ds(s):us(e)))}segmentMatchContext(e,t,r,i,n){if(!e.unbounded)return void this.simpleSegmentMatchContext(e,t,r,i,n);const s=e.unboundedContextKind||"user",a=t.key(s);if(a)return e.generation?void(r.bigSegmentsMembership&&r.bigSegmentsMembership[a]?this.bigSegmentMatchContext(r.bigSegmentsMembership[a],e,t,r).then(n):this._queries.getBigSegmentsMembership(a).then(i=>{if(r.bigSegmentsMembership=r.bigSegmentsMembership||{},i){const[e,t]=i;r.bigSegmentsMembership[a]=e,r.bigSegmentsStatus=cs(r.bigSegmentsStatus,t)}else r.bigSegmentsStatus=cs(r.bigSegmentsStatus,"NOT_CONFIGURED");this.bigSegmentMatchContext(r.bigSegmentsMembership[a],e,t,r).then(n)})):(r.bigSegmentsStatus=cs(r.bigSegmentsStatus,"NOT_CONFIGURED"),void n(us(!1)));n(us(!1))}bigSegmentMatchContext(e,t,r,i){const n=(0,ts.default)(t),s=null==e?void 0:e[n];return new Promise(e=>{null==s?this.simpleSegmentMatchContext(t,r,i,[],e):e(us(s))})}};var hs={};Object.defineProperty(hs,"__esModule",{value:!0});const fs=X;hs.default=class{constructor(e){this._contextKeysCache=new fs.default({max:e.contextKeysCapacity}),this.flushInterval=e.contextKeysFlushInterval}processContext(e){const{canonicalKey:t}=e,r=this._contextKeysCache.get(t);return this._contextKeysCache.set(t,!0),!r}flush(){this._contextKeysCache.clear()}};var ps={},vs={};Object.defineProperty(vs,"__esModule",{value:!0}),vs.default=function(e,t){if(t){if(t.inExperiment)return!0;switch(t.kind){case"RULE_MATCH":{const r=t.ruleIndex;if(void 0!==r){const t=e.rules||[];return r>=0&&r<t.length&&!!t[r].trackEvents}break}case"FALLTHROUGH":return!!e.trackEventsFallthrough}}return!1},Object.defineProperty(ps,"__esModule",{value:!0});const gs=a,_s=vs;class ms extends gs.internal.EventFactoryBase{evalEventServer(e,t,r,i,n){var s;const a=(0,_s.default)(e,r.reason);return super.evalEvent({addExperimentData:a,context:t,debugEventsUntilDate:e.debugEventsUntilDate,defaultVal:i,excludeFromSummaries:e.excludeFromSummaries,flagKey:e.key,prereqOfFlagKey:null==n?void 0:n.key,reason:r.reason,samplingRatio:e.samplingRatio,trackEvents:e.trackEvents||a,value:r.value,variation:null!==(s=r.variationIndex)&&void 0!==s?s:void 0,version:e.version})}}ps.default=ms;var ys={};Object.defineProperty(ys,"__esModule",{value:!0});ys.default=class{constructor(e,t){this._valid=e,this._withReasons=t,this._flagValues={},this._flagMetadata={}}addFlag(e,t,r,i,n,s,a,o){this._flagValues[e.key]=t;const l={};void 0!==r&&(l.variation=r);const c=a&&!n&&!s&&void 0===e.debugEventsUntilDate;c||(l.version=e.version),i&&(s||this._withReasons&&!c)&&(l.reason=i),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 bs={};Object.defineProperty(bs,"__esModule",{value:!0});const Es="unknown hook";bs.default=class{constructor(e,t){this._logger=e,this._hooks=[],this._hooks.push(...t)}async withEvaluationSeries(e,t,r,i,n,s){return 0===this._hooks.length?n():this.withEvaluationSeriesExtraDetail(e,t,r,i,async()=>({detail:await n()}),s).then(({detail:e})=>e)}async withEvaluationSeriesExtraDetail(e,t,r,i,n,s){if(0===this._hooks.length)return n();const{hooks:a,hookContext:o}=this._prepareHooks(e,t,r,i,s),l=this._executeBeforeEvaluation(a,o),c=await n();return this._executeAfterEvaluation(a,o,l,c.detail),c}_tryExecuteStage(e,t,r){var i;try{return r()}catch(r){return null===(i=this._logger)||void 0===i||i.error(`An error was encountered in "${e}" of the "${t}" hook: ${r}`),{}}}_hookName(e){var t,r;try{return null!==(t=null==e?void 0:e.getMetadata().name)&&void 0!==t?t:Es}catch(e){return null===(r=this._logger)||void 0===r||r.error("Exception thrown getting metadata for hook. Unable to get hook name."),Es}}_executeAfterEvaluation(e,t,r,i){var n;for(let s=e.length-1;s>=0;s-=1){const a=e[s],o=null!==(n=r[s])&&void 0!==n?n:{};this._tryExecuteStage("afterEvaluation",this._hookName(a),()=>{var e,r;return null!==(r=null===(e=null==a?void 0:a.afterEvaluation)||void 0===e?void 0:e.call(a,t,o,i))&&void 0!==r?r:{}})}}_executeBeforeEvaluation(e,t){return e.map(e=>this._tryExecuteStage("beforeEvaluation",this._hookName(e),()=>{var r,i;return null!==(i=null===(r=null==e?void 0:e.beforeEvaluation)||void 0===r?void 0:r.call(e,t,{}))&&void 0!==i?i:{}}))}_prepareHooks(e,t,r,i,n){return{hooks:[...this._hooks],hookContext:{flagKey:e,context:t,defaultValue:r,method:i,environmentId:n}}}addHook(e){this._hooks.push(e)}};var Ss={};Object.defineProperty(Ss,"__esModule",{value:!0});const ws=a;function Os(e){const t=e.old,r=e.new;return!(void 0!==t&&!ws.TypeValidators.Boolean.is(t))&&!(void 0!==r&&!ws.TypeValidators.Boolean.is(r))}function ks(e){if(ws.TypeValidators.String.is(e.key)&&""!==e.key){if("latency_ms"===e.key){if(!ws.TypeValidators.Object.is(e.values))return;if(!function(e){const t=e.old,r=e.new;return!(void 0!==t&&!ws.TypeValidators.Number.is(t)||void 0!==r&&!ws.TypeValidators.Number.is(r))}(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(!ws.TypeValidators.Object.is(e.values))return;if(!Os(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(!ws.TypeValidators.Boolean.is(e.value)||!ws.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(!ws.TypeValidators.Object.is(e.values))return;if(!Os(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}}}Ss.default=function(e){var t,r;if("migration_op"!==e.kind)return;if(r=e.operation,!ws.TypeValidators.String.is(r)||"read"!==r&&"write"!==r)return;if(!ws.TypeValidators.Number.is(e.creationDate))return;const i={};if(ws.TypeValidators.Object.is(e.context)){const t=ws.Context.fromLDContext(e.context);t.valid&&(i.context=t)}else ws.TypeValidators.Object.is(e.contextKeys)&&Object.keys(e.contextKeys).every(e=>ws.TypeValidators.Kind.is(e))&&Object.values(e.contextKeys).every(e=>ws.TypeValidators.String.is(e)&&""!==e)&&(i.contextKeys=Object.assign({},e.contextKeys));if(!i.context&&!i.contextKeys)return;const n=null!==(t=e.samplingRatio)&&void 0!==t?t:1;if(!ws.TypeValidators.Number.is(n))return;const s=function(e){if(!ws.TypeValidators.String.is(e.key)||""===e.key)return;if(!ws.TypeValidators.Object.is(e.reason))return;if(!ws.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}},r=e.reason,i=t.reason;return ws.TypeValidators.String.is(r.errorKind)&&(i.errorKind=r.errorKind),ws.TypeValidators.String.is(r.ruleId)&&(i.ruleId=r.ruleId),ws.TypeValidators.String.is(r.prerequisiteKey)&&(i.prerequisiteKey=r.prerequisiteKey),ws.TypeValidators.Boolean.is(r.inExperiment)&&(i.inExperiment=r.inExperiment),ws.TypeValidators.Number.is(r.ruleIndex)&&(i.ruleIndex=r.ruleIndex),ws.TypeValidators.String.is(r.bigSegmentsStatus)&&(i.bigSegmentsStatus=r.bigSegmentsStatus),void 0!==e.variation&&ws.TypeValidators.Number.is(e.variation)&&(t.variation=e.variation),void 0!==e.version&&ws.TypeValidators.Number.is(e.version)&&(t.version=e.version),t}(e.evaluation);var a;return s?Object.assign(Object.assign({kind:e.kind,operation:e.operation,creationDate:e.creationDate},i),{measurements:(a=e.measurements,a.map(ks).filter(e=>void 0!==e)),evaluation:s,samplingRatio:n}):void 0};var Ds={};Object.defineProperty(Ds,"__esModule",{value:!0});const Ts=a,Ps=l;function Is(e){return!Number.isNaN(e)}Ds.default=class{constructor(e,t,r,i,n,s,a,o,l,c){this._flagKey=e,this._context=t,this._defaultStage=r,this._stage=i,this._reason=n,this._checkRatio=s,this._variation=a,this._version=o,this._samplingRatio=l,this._logger=c,this._errors={old:!1,new:!1},this._wasInvoked={old:!1,new:!1},this._consistencyCheck=Ps.LDConsistencyCheck.NotChecked,this._latencyMeasurement={old:NaN,new:NaN}}op(e){this._operation=e}error(e){this._errors[e]=!0}consistency(e){var t,r;if(Ts.internal.shouldSample(null!==(t=this._checkRatio)&&void 0!==t?t:1))try{const t=e();this._consistencyCheck=t?Ps.LDConsistencyCheck.Consistent:Ps.LDConsistencyCheck.Inconsistent}catch(e){null===(r=this._logger)||void 0===r||r.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,r,i,n;if(!Ts.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(!Ts.Context.fromLDContext(this._context).valid)return void(null===(r=this._logger)||void 0===r||r.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===(i=this._logger)||void 0===i||i.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(),context:this._context,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,r,i;return!!this._wasInvoked[e]||(Number.isNaN(this._latencyMeasurement[e])?this._errors[e]?(null===(r=this._logger)||void 0===r||r.error(`${this._logTag()} ${this._errorConsistencyMessage(e)}`),!1):this._consistencyCheck===Ps.LDConsistencyCheck.NotChecked||(null===(i=this._logger)||void 0===i||i.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 r={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&&(r.values.old=!0),this._wasInvoked.new&&(r.values.new=!0),e.push(r)}_populateConsistency(e){var t;void 0!==this._consistencyCheck&&this._consistencyCheck!==Ps.LDConsistencyCheck.NotChecked&&e.push({key:"consistent",value:this._consistencyCheck===Ps.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=Is(this._latencyMeasurement.new),r=Is(this._latencyMeasurement.old);if(t||r){const i={};t&&(i.new=this._latencyMeasurement.new),r&&(i.old=this._latencyMeasurement.old),e.push({key:"latency_ms",values:i})}}},Object.defineProperty(s,"__esModule",{value:!0});const xs=a,Rs=o,Ms=O,Fs=J,As=ee,Cs=te,Ls=re,js=ge,Ns=Oe,$s=Ce,Vs=Ne,Us=mt,Ks=Et,zs=wt,Bs=kt,Hs=Pt,qs=Ft,Gs=Nt,Ws=Vt,Js=Ht,Xs=hs,Ys=ps,Zs=vs,Qs=ys,ea=bs,ta=Ss,ra=Ds,ia=At,na=ne,{ClientMessages:sa,ErrorKinds:aa,NullEventProcessor:oa}=xs.internal;var la;!function(e){e[e.Initializing=0]="Initializing",e[e.Initialized=1]="Initialized",e[e.Failed=2]="Failed"}(la||(la={}));function ca(e,t,r,i,n,s,a,o,l,c){var u,d,h,f,p;const{onUpdate:v,hasEventListeners:g}=i,_=new ea.default(r.logger,a);if(!e&&!r.offline)throw new Error("You must configure the client with an SDK key");const{logger:m}=r,y=(0,xs.defaultHeaders)(e,t.info,r.tags,!0,l,o),b=new xs.ClientContext(e,r,t),E=r.featureStoreFactory(b),S=new js.default(E,g,v);let w,O;!r.sendEvents||r.offline||r.diagnosticOptOut||(w=new xs.internal.DiagnosticsManager(e,t,(0,qs.default)(r,t,E))),O=!r.sendEvents||r.offline?new oa:new xs.internal.EventProcessor(Object.assign(Object.assign({},r),{redactAnonymousAllEvents:!0}),b,y,new Xs.default(r),w,c);const k=new Fs.default(null===(d=null===(u=r.bigSegments)||void 0===u?void 0:u.store)||void 0===d?void 0:d.call(u,b),null!==(h=r.bigSegments)&&void 0!==h?h:{},r.logger,t.crypto),D={getFlag(e,t){E.get(na.default.Features,e,e=>t(e))},getSegment(e,t){E.get(na.default.Segments,e,e=>t(e))},getBigSegmentsMembership:e=>k.getUserMembership(e)},T=new Js.default(t,D),P=(0,Ls.createStreamListeners)(S,m,{put:n});let I;return r.offline||r.useLdd||(I=null!==(p=null===(f=r.updateProcessorFactory)||void 0===f?void 0:f.call(r,b,S,n,s))&&void 0!==p?p:r.stream?new zs.default(b,"/all",[],P,y,w,s,r.streamInitialReconnectDelay):new Vs.default(new Ks.default(r,t.requests,y),r.pollInterval,S,r.logger,n,s)),{config:r,logger:m,evaluator:T,featureStore:E,updateProcessor:I,eventProcessor:O,bigSegmentsManager:k,hookRunner:_,onError:i.onError,onFailed:i.onFailed,onReady:i.onReady}}function ua(e,t){var r,i;return new xs.ServiceEndpoints(null!==(r=t.streaming)&&void 0!==r?r:e.streaming,null!==(i=t.polling)&&void 0!==i?i:e.polling,e.events,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,e.payloadFilterKey)}s.default=class{get logger(){return this._logger}constructor(e,t,r,i,n){this._sdkKey=e,this._platform=t,this._initState=la.Initializing,this._eventFactoryDefault=new Ys.default(!1),this._eventFactoryWithReasons=new Ys.default(!0);const s=new ia.default(r,n),a=!(null==n?void 0:n.disableBackgroundEventFlush);this.environmentMetadata=(0,As.createPluginEnvironmentMetadata)(t,e,s);const o=[];if(s.hooks&&o.push(...s.hooks),s.getImplementationHooks(this.environmentMetadata).forEach(e=>{o.push(e)}),s.dataSystem){let r,l;({config:this._config,logger:this._logger,evaluator:this._evaluator,featureStore:r,dataSource:this._dataSource,payloadListener:l,eventProcessor:this._eventProcessor,bigSegmentsManager:this._bigSegmentsManager,hookRunner:this._hookRunner,onError:this._onError,onFailed:this._onFailed,onReady:this._onReady}=function(e,t,r,i,n,s,a,o,l){var c,u,d,h,f,p;const{onUpdate:v,hasEventListeners:g}=i,_=new ea.default(r.logger,s);if(!e&&!r.offline)throw new Error("You must configure the client with an SDK key");const{logger:m}=r;void 0!==r.payloadFilterKey&&(null==m||m.warn("Payload filtering is not supported with the FDv2 data system; the configured payload filter has no effect on FDv2 requests"));const y=(0,xs.defaultHeaders)(e,t.info,r.tags,!0,o,a),b=new xs.ClientContext(e,r,t),E=r.dataSystem,S=E.featureStoreFactory(b),w=new Hs.default(S,g,v);let O,k;!r.sendEvents||r.offline||r.diagnosticOptOut||(O=new xs.internal.DiagnosticsManager(e,t,(0,qs.default)(r,t,S))),k=!r.sendEvents||r.offline?new oa:new xs.internal.EventProcessor(Object.assign(Object.assign({},r),{redactAnonymousAllEvents:!0}),b,y,new Xs.default(r),O,l);const D=new Fs.default(null===(u=null===(c=r.bigSegments)||void 0===c?void 0:c.store)||void 0===u?void 0:u.call(c,b),null!==(d=r.bigSegments)&&void 0!==d?d:{},r.logger,t.crypto),T={getFlag(e,t){S.get(na.default.Features,e,e=>t(e))},getSegment(e,t){S.get(na.default.Segments,e,e=>t(e))},getBigSegmentsMembership:e=>D.getUserMembership(e)},P=new Js.default(t,T);let I,x;if(!r.offline&&!r.dataSystem.useLdd){const e=[],i=[],s=[];if((0,Ms.isCustomOptions)(E.dataSource)){const{initializers:n=[],synchronizers:s=[]}=E.dataSource;n.forEach(i=>{switch(i.type){case"file":e.push(()=>new Ns.default(i,t,r.logger));break;case"polling":{const n=i.baseUri?ua(r.serviceEndpoints,{polling:i.baseUri}):void 0;e.push(()=>new $s.default(new Ks.default(r,t.requests,y,"/sdk/poll",r.logger,n),r.logger));break}default:throw new Error("Unsupported initializer type")}}),s.forEach(e=>{switch(e.type){case"streaming":{const{streamInitialReconnectDelay:t=ia.DEFAULT_STREAM_RECONNECT_DELAY}=e,n=e.baseUri?ua(r.serviceEndpoints,{streaming:e.baseUri}):void 0;i.push(()=>new Bs.default(b,"/sdk/stream",[],y,O,t,n));break}case"polling":{const{pollInterval:n=ia.DEFAULT_POLL_INTERVAL}=e,s=e.baseUri?ua(r.serviceEndpoints,{polling:e.baseUri}):void 0;i.push(()=>new Us.default(new Ks.default(r,t.requests,y,"/sdk/poll",r.logger,s),n,r.logger));break}default:throw new Error("Unsupported synchronizer type")}})}else{if((0,Ms.isStandardOptions)(E.dataSource)&&e.push(()=>new $s.default(new Ks.default(r,t.requests,y,"/sdk/poll",r.logger),r.logger)),(0,Ms.isStandardOptions)(E.dataSource)||(0,Ms.isStreamingOnlyOptions)(E.dataSource)){const e=E.dataSource.streamInitialReconnectDelay;i.push(()=>new Bs.default(b,"/sdk/stream",[],y,O,e))}let n=ia.DEFAULT_POLL_INTERVAL;((0,Ms.isStandardOptions)(E.dataSource)||(0,Ms.isPollingOnlyOptions)(E.dataSource))&&(n=null!==(h=E.dataSource.pollInterval)&&void 0!==h?h:ia.DEFAULT_POLL_INTERVAL,i.push(()=>new Us.default(new Ks.default(r,t.requests,y,"/sdk/poll",m),n,m)))}const a=E.fdv1Fallback;if(null!==a){const e=null!==(p=null!==(f=null==a?void 0:a.pollInterval)&&void 0!==f?f:r.pollInterval)&&void 0!==p?p:ia.DEFAULT_POLL_INTERVAL,i=(null==a?void 0:a.baseUri)?ua(r.serviceEndpoints,{polling:a.baseUri}):void 0;s.push(()=>new Us.default(new Ks.default(r,t.requests,y,"/sdk/latest-all",r.logger,i),e,r.logger,!0))}I=new xs.CompositeDataSource(e,i,s,m),x=(0,Cs.createPayloadListener)(w,m,n)}return{config:r,logger:m,evaluator:P,featureStore:S,dataSource:I,payloadListener:x,eventProcessor:k,bigSegmentsManager:D,hookRunner:_,onError:i.onError,onFailed:i.onFailed,onReady:i.onReady}}(e,t,s,i,()=>this._initSuccess(),o,null==n?void 0:n.instanceId,null==n?void 0:n.userAgentHeaderName,a)),this._featureStore=r,this.bigSegmentStatusProviderInternal=this._bigSegmentsManager.statusProvider,this._dataSource&&this._dataSource.start((e,t)=>{null==l||l(t)},(e,t)=>{e===xs.subsystem.DataSourceState.Closed&&t&&this._dataSourceErrorHandler(t)},()=>{var e;return null===(e=r.getSelector)||void 0===e?void 0:e.call(r)})}else({config:this._config,logger:this._logger,evaluator:this._evaluator,featureStore:this._featureStore,updateProcessor:this._updateProcessor,eventProcessor:this._eventProcessor,bigSegmentsManager:this._bigSegmentsManager,hookRunner:this._hookRunner,onError:this._onError,onFailed:this._onFailed,onReady:this._onReady}=ca(e,t,s,i,()=>this._initSuccess(),e=>this._dataSourceErrorHandler(e),o,null==n?void 0:n.instanceId,null==n?void 0:n.userAgentHeaderName,a)),this.bigSegmentStatusProviderInternal=this._bigSegmentsManager.statusProvider,this._updateProcessor&&this._updateProcessor.start()}initialized(){return this._initState===la.Initialized}waitForInitialization(e){var t,r;return void 0!==(null==e?void 0:e.timeout)||void 0===this._updateProcessor&&void 0===this._dataSource||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||void 0!==this._dataSource)&&(null===(r=this._logger)||void 0===r||r.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===la.Initialized?(this._initializedPromise=Promise.resolve(this),this._initializedPromise):this._initState===la.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,r,i){var n,s,a;return this._hookRunner.withEvaluationSeries(e,t,r,"LDClient.variation",()=>new Promise(i=>{this._evaluateIfPossible(e,t,r,this._eventFactoryDefault,e=>{i(e.detail)})}),null===(a=null===(s=(n=this._featureStore).getInitMetaData)||void 0===s?void 0:s.call(n))||void 0===a?void 0:a.environmentId).then(e=>(null==i||i(null,e.value),e.value))}variationDetail(e,t,r,i){var n,s,a;return this._hookRunner.withEvaluationSeries(e,t,r,"LDClient.variationDetail",()=>new Promise(n=>{this._evaluateIfPossible(e,t,r,this._eventFactoryWithReasons,e=>{n(e.detail),null==i||i(null,e.detail)})}),null===(a=null===(s=(n=this._featureStore).getInitMetaData)||void 0===s?void 0:s.call(n))||void 0===a?void 0:a.environmentId)}_typedEval(e,t,r,i,n,s){var a,o,l;return this._hookRunner.withEvaluationSeries(e,t,r,n,()=>new Promise(n=>{this._evaluateIfPossible(e,t,r,i,e=>{const t={value:e.detail.value,reason:e.detail.reason,variationIndex:e.detail.variationIndex};n(t)},s)}),null===(l=null===(o=(a=this._featureStore).getInitMetaData)||void 0===o?void 0:o.call(a))||void 0===l?void 0:l.environmentId)}async boolVariation(e,t,r){return(await this._typedEval(e,t,r,this._eventFactoryDefault,"LDClient.boolVariation",e=>[xs.TypeValidators.Boolean.is(e),xs.TypeValidators.Boolean.getType()])).value}async numberVariation(e,t,r){return(await this._typedEval(e,t,r,this._eventFactoryDefault,"LDClient.numberVariation",e=>[xs.TypeValidators.Number.is(e),xs.TypeValidators.Number.getType()])).value}async stringVariation(e,t,r){return(await this._typedEval(e,t,r,this._eventFactoryDefault,"LDClient.stringVariation",e=>[xs.TypeValidators.String.is(e),xs.TypeValidators.String.getType()])).value}jsonVariation(e,t,r){var i,n,s;return this._hookRunner.withEvaluationSeries(e,t,r,"LDClient.jsonVariation",()=>new Promise(i=>{this._evaluateIfPossible(e,t,r,this._eventFactoryDefault,e=>{i(e.detail)})}),null===(s=null===(n=(i=this._featureStore).getInitMetaData)||void 0===n?void 0:n.call(i))||void 0===s?void 0:s.environmentId).then(e=>e.value)}boolVariationDetail(e,t,r){return this._typedEval(e,t,r,this._eventFactoryWithReasons,"LDClient.boolVariationDetail",e=>[xs.TypeValidators.Boolean.is(e),xs.TypeValidators.Boolean.getType()])}numberVariationDetail(e,t,r){return this._typedEval(e,t,r,this._eventFactoryWithReasons,"LDClient.numberVariationDetail",e=>[xs.TypeValidators.Number.is(e),xs.TypeValidators.Number.getType()])}stringVariationDetail(e,t,r){return this._typedEval(e,t,r,this._eventFactoryWithReasons,"LDClient.stringVariationDetail",e=>[xs.TypeValidators.String.is(e),xs.TypeValidators.String.getType()])}jsonVariationDetail(e,t,r){var i,n,s;return this._hookRunner.withEvaluationSeries(e,t,r,"LDClient.jsonVariationDetail",()=>new Promise(i=>{this._evaluateIfPossible(e,t,r,this._eventFactoryWithReasons,e=>{i(e.detail)})}),null===(s=null===(n=(i=this._featureStore).getInitMetaData)||void 0===n?void 0:n.call(i))||void 0===s?void 0:s.environmentId)}async _migrationVariationInternal(e,t,r){var i;const n=await new Promise(i=>{this._evaluateIfPossible(e,t,r,this._eventFactoryWithReasons,({detail:t},n)=>{if(!(0,Rs.IsMigrationStage)(t.value)){const t=new Error(`Unrecognized MigrationState for "${e}"; returning default value.`);this._onError(t);const s={kind:"ERROR",errorKind:aa.WrongType};return void i({detail:{value:r,reason:s},flag:n})}i({detail:t,flag:n})})}),{detail:s,flag:a}=n,o=null===(i=null==a?void 0:a.migration)||void 0===i?void 0:i.checkRatio,l=null==a?void 0:a.samplingRatio;return{detail:s,migration:{value:s.value,tracker:new ra.default(e,t,r,s.value,s.reason,o,null===s.variationIndex?void 0:s.variationIndex,null==a?void 0:a.version,l,this._logger)}}}async migrationVariation(e,t,r){var i,n,s;return(await this._hookRunner.withEvaluationSeriesExtraDetail(e,t,r,"LDClient.migrationVariation",()=>this._migrationVariationInternal(e,t,r),null===(s=null===(n=(i=this._featureStore).getInitMetaData)||void 0===n?void 0:n.call(i))||void 0===s?void 0:s.environmentId)).migration}allFlagsState(e,t,r){var i,n,s;if(this._config.offline){null===(i=this._logger)||void 0===i||i.info("allFlagsState() called in offline mode. Returning empty state.");const e=new Qs.default(!1,!1).build();return null==r||r(null,e),Promise.resolve(e)}const a=xs.Context.fromLDContext(e);return a.valid?new Promise(e=>{const i=i=>this._featureStore.all(na.default.Features,n=>{const s=new Qs.default(i,!!(null==t?void 0:t.withReasons)),o=!!(null==t?void 0:t.clientSideOnly),l=!!(null==t?void 0:t.detailsOnlyForTrackedFlags);(0,Gs.allAsync)(Object.values(n),(e,t)=>{var r;const i=e;!o||(null===(r=i.clientSideAvailability)||void 0===r?void 0:r.usingEnvironmentId)?this._evaluator.evaluateCb(i,a,e=>{var r;e.isError&&this._onError(new Error(`Error for feature flag "${i.key}" while evaluating all flags: ${e.message}`));const n=(0,Zs.default)(i,e.detail.reason);s.addFlag(i,e.detail.value,null!==(r=e.detail.variationIndex)&&void 0!==r?r:void 0,e.detail.reason,i.trackEvents||n,n,l,e.prerequisites),t(!0)}):t(!0)},()=>{const t=s.build();null==r||r(null,t),e(t)})});this.initialized()?i(!0):this._featureStore.initialized(e=>{var t,r;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===(r=this._logger)||void 0===r||r.warn("Called allFlagsState before client initialization. Data store not available; returning empty state"),n=!1),i(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 Qs.default(!1,!1).build()))}secureModeHash(e){const t=xs.Context.fromLDContext(e),r=t.valid?t.canonicalKey:void 0;if(!this._platform.crypto.createHmac)throw new Error("Platform must implement createHmac");const i=this._platform.crypto.createHmac("sha256",this._sdkKey);if(void 0===r)throw new xs.LDClientError("Could not generate secure mode hash for invalid context");return i.update(r),i.digest("hex")}close(){var e,t;this._eventProcessor.close(),null===(e=this._updateProcessor)||void 0===e||e.close(),null===(t=this._dataSource)||void 0===t||t.stop(),this._featureStore.close(),this._bigSegmentsManager.close()}isOffline(){return this._config.offline}track(e,t,r,i){var n,s;const a=xs.Context.fromLDContext(t);a.valid?(void 0===i||xs.TypeValidators.Number.is(i)||null===(s=this._logger)||void 0===s||s.warn(sa.invalidMetricValue(typeof i)),this._eventProcessor.sendEvent(this._eventFactoryDefault.customEvent(e,a,r,i))):null===(n=this._logger)||void 0===n||n.warn(sa.MissingContextKeyNoEvent)}trackMigration(e){const t=(0,ta.default)(e);t&&this._eventProcessor.sendEvent(t)}identify(e){var t;const r=xs.Context.fromLDContext(e);r.valid?this._eventProcessor.sendEvent(this._eventFactoryDefault.identifyEvent(r)):null===(t=this._logger)||void 0===t||t.warn(sa.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,r,i,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(Ws.default.forError(aa.ClientNotReady,void 0,r));const l=xs.Context.fromLDContext(t);if(!l.valid)return this._onError(new xs.LDClientError(`${null!==(o=l.message)&&void 0!==o?o:"Context not valid;"} returning default value.`)),void n(Ws.default.forError(aa.UserNotSpecified,void 0,r));this._featureStore.get(na.default.Features,e,t=>{const a=t;if(!a){const t=new xs.LDClientError(`Unknown feature flag "${e}"; returning default value`);this._onError(t);const i=Ws.default.forError(aa.FlagNotFound,void 0,r);return this._eventProcessor.sendEvent(this._eventFactoryDefault.unknownFlagEvent(e,r,l)),void n(i)}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(r)),s){const[o,c]=s(t.detail.value);if(!o){const t=Ws.default.forError(aa.WrongType,`Did not receive expected type (${c}) evaluating feature flag "${e}"`,r);return this._sendEvalEvent(t,i,a,l,r),void n(t,a)}}this._sendEvalEvent(t,i,a,l,r),n(t,a)},i)})}_sendEvalEvent(e,t,r,i,n){var s;null===(s=e.events)||void 0===s||s.forEach(e=>{this._eventProcessor.sendEvent(Object.assign({},e))}),this._eventProcessor.sendEvent(t.evalEventServer(r,i,e.detail,n,void 0))}_evaluateIfPossible(e,t,r,i,n,s){this.initialized()?this._variationInternal(e,t,r,i,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,r,i,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(Ws.default.forError(aa.ClientNotReady,void 0,r))})}_dataSourceErrorHandler(e){var t;const r=401===e.code?new Error("Authentication failed. Double check your SDK key."):e;this._onError(r),this._onFailed(r),this.initialized()||(this._initState=la.Failed,this._rejectionReason=r,null===(t=this._initReject)||void 0===t||t.call(this,r))}_initSuccess(){var e;this.initialized()||(this._initState=la.Initialized,null===(e=this._initResolve)||void 0===e||e.call(this,this),this._onReady())}_clientWithTimeout(e,t,r){if(t){const i=(0,xs.cancelableTimedPromise)(t,"waitForInitialization");return Promise.race([e.then(()=>this),i.promise.then(()=>this)]).catch(e=>{throw e instanceof xs.LDTimeoutError&&(null==r||r.error(e.message)),e}).finally(()=>i.cancel())}return e}};var da={};Object.defineProperty(da,"__esModule",{value:!0}),da.createMigration=da.LDMigrationError=da.LDMigrationSuccess=void 0;const ha=o,fa=w;da.LDMigrationSuccess=function(e){return{success:!0,result:e}},da.LDMigrationError=function(e){return{success:!1,error:e}};class pa{constructor(e,t){var r,i;this._client=e,this._config=t,this._readTable={[ha.LDMigrationStage.Off]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[ha.LDMigrationStage.DualWrite]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[ha.LDMigrationStage.Shadow]:async e=>{const{fromOld:t,fromNew:r}=await this._doRead(e);return this._trackConsistency(e,t,r),t},[ha.LDMigrationStage.Live]:async e=>{const{fromNew:t,fromOld:r}=await this._doRead(e);return this._trackConsistency(e,r,t),t},[ha.LDMigrationStage.RampDown]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[ha.LDMigrationStage.Complete]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config))},this._writeTable={[ha.LDMigrationStage.Off]:async e=>({authoritative:await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config))}),[ha.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))}},[ha.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))}},[ha.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))}},[ha.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))}},[ha.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 fa.LDConcurrentExecution,this._latencyTracking=null===(r=this._config.latencyTracking)||void 0===r||r,this._errorTracking=null===(i=this._config.errorTracking)||void 0===i||i}async read(e,t,r,i){const n=await this._client.migrationVariation(e,t,r),s=await this._readTable[n.value]({payload:i,tracker:n.tracker});return n.tracker.op("read"),this._sendEvent(n.tracker),s}async write(e,t,r,i){const n=await this._client.migrationVariation(e,t,r),s=await this._writeTable[n.value]({payload:i,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,r){this._config.check&&t.success&&r.success&&e.tracker.consistency(()=>this._config.check(t.result,r.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)),r=this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[i,n]=await Promise.all([t,r]);return{fromOld:i,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)===fa.LDExecution.Serial){return this._execution.ordering===fa.LDExecutionOrdering.Fixed?this._readSequentialFixed(e):this._readSequentialRandom(e)}return this._readConcurrent(e)}async _doSingleOp(e,t,r){e.tracker.invoked(t);const i=await this._trackLatency(e.tracker,t,()=>async function(e){try{return await e()}catch(e){return{success:!1,error:e}}}(()=>r(e.payload)));return!i.success&&this._errorTracking&&e.tracker.error(t),Object.assign({origin:t},i)}async _trackLatency(e,t,r){if(!this._latencyTracking)return r();let i,n,s;"undefined"!=typeof performance?(i=performance.now(),s=await r(),n=performance.now()):(i=Date.now(),s=await r(),n=Date.now());const a=n-i;return e.latency(t,a),s}}da.createMigration=function(e,t){return new pa(e,t)};var va={},ga={};Object.defineProperty(ga,"__esModule",{value:!0});const _a=ke;ga.default=class{constructor(e){this._options=e}create(e,t,r,i){const n={paths:this._options.paths,autoUpdate:this._options.autoUpdate,logger:this._options.logger||e.basicConfiguration.logger,yamlParser:this._options.yamlParser};return new _a.default(n,e.platform.fileSystem,t,r,i)}getFactory(){return(e,t,r,i)=>this.create(e,t,r,i)}};var ma={},ya={},ba={},Ea={};!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}}(Ea);var Sa={};Object.defineProperty(Sa,"__esModule",{value:!0});const wa=a,Oa=Ea;class ka{constructor(e,t,r){this._flagBuilder=e,this._clauses=[],t&&(this._clauses=[...t]),void 0!==r&&(this._variation=r)}andMatch(e,t,...r){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new wa.AttributeReference(t),op:"in",values:r,negate:!1}),this}andNotMatch(e,t,...r){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new wa.AttributeReference(t),op:"in",values:r,negate:!0}),this}thenReturn(e){return wa.TypeValidators.Boolean.is(e)?(this._flagBuilder.booleanFlag(),this.thenReturn((0,Oa.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 ka(this._flagBuilder,this._clauses,this._variation)}}Sa.default=ka,Object.defineProperty(ba,"__esModule",{value:!0});const Da=a,Ta=Ea,Pa=Sa;class Ia{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[Ta.TRUE_VARIATION_INDEX]&&!1===this._data.variations[Ta.FALSE_VARIATION_INDEX]}booleanFlag(){return this._isBooleanFlag?this:this.variations(!0,!1).fallthroughVariation(Ta.TRUE_VARIATION_INDEX).offVariation(Ta.FALSE_VARIATION_INDEX)}variations(...e){return this._data.variations=[...e],this}on(e){return this._data.on=e,this}fallthroughVariation(e){return Da.TypeValidators.Boolean.is(e)?this.booleanFlag().fallthroughVariation((0,Ta.variationForBoolean)(e)):(this._data.fallthroughVariation=e,this)}offVariation(e){return Da.TypeValidators.Boolean.is(e)?this.booleanFlag().offVariation((0,Ta.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,r){return Da.TypeValidators.Boolean.is(r)?this.booleanFlag().variationForContext(e,t,(0,Ta.variationForBoolean)(r)):(this._data.targetsByVariation||(this._data.targetsByVariation={}),this._data.variations.forEach((i,n)=>{if(n===r){const r=this._data.targetsByVariation[n]||{};e in r||(r[e]=[]);-1!==r[e].indexOf(t)||r[e].push(t),this._data.targetsByVariation[n]=r}else{const r=this._data.targetsByVariation[n];if(r){const i=r[e];if(i){const n=i.indexOf(t);-1!==n&&(i.splice(n,1),i.length||delete r[e])}Object.keys(r).length||delete this._data.targetsByVariation[n]}}}),this)}clearRules(){return delete this._data.rules,this}clearAllTargets(){return delete this._data.targetsByVariation,this}ifMatch(e,t,...r){return new Pa.default(this).andMatch(e,t,...r)}ifNotMatch(e,t,...r){return new Pa.default(this).andNotMatch(e,t,...r)}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=[],r=[];Object.entries(this._data.targetsByVariation).forEach(([t,i])=>{Object.entries(i).forEach(([i,n])=>{const s=parseInt(t,10);e.push({contextKind:i,values:"user"===i?[]:n,variation:s}),"user"===i&&r.push({values:n,variation:s})})}),t.targets=r,t.contextTargets=e}return this._data.rules&&(t.rules=this._data.rules.map((e,t)=>e.build(String(t)))),t}clone(){return new Ia(this._key,this._data)}getKey(){return this._key}}ba.default=Ia;var xa={};Object.defineProperty(xa,"__esModule",{value:!0});xa.default=class{constructor(e,t,r,i,n){this._featureStore=e,this._onStop=i,this._listeners=n,this._flags=Object.assign({},t),this._segments=Object.assign({},r)}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(ya,"__esModule",{value:!0});const Ra=re,Ma=Ve,Fa=ie,Aa=ne,Ca=ba,La=xa;ya.default=class{constructor(){this._currentFlags={},this._currentSegments={},this._dataSources=[],this._flagBuilders={}}getFactory(){return(e,t,r,i)=>{const n=(0,Ra.createStreamListeners)(t,e.basicConfiguration.logger,{put:r}),s=new La.default(new Ma.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 Ca.default(e).booleanFlag()}update(e){const t=e.getKey(),r=this._currentFlags[t],i=r?r.version:0,n=e.build(i+1);return this._currentFlags[t]=n,this._flagBuilders[t]=e.clone(),Promise.all(this._dataSources.map(e=>e.upsert(Aa.default.Features,n)))}usePreconfiguredFlag(e){const t=JSON.parse(JSON.stringify(e)),r=this._currentFlags[t.key],i=Object.assign(Object.assign({},t),{version:r?r.version+1:t.version});return(0,Fa.processFlag)(i),this._currentFlags[t.key]=i,Promise.all(this._dataSources.map(e=>e.upsert(Aa.default.Features,i)))}usePreconfiguredSegment(e){const t=JSON.parse(JSON.stringify(e)),r=this._currentSegments[t.key],i=Object.assign(Object.assign({},t),{version:r?r.version+1:t.version});return(0,Fa.processSegment)(i),this._currentSegments[t.key]=i,Promise.all(this._dataSources.map(e=>e.upsert(Aa.default.Segments,i)))}},Object.defineProperty(ma,"__esModule",{value:!0}),ma.TestDataRuleBuilder=ma.TestDataFlagBuilder=ma.TestData=void 0;const ja=ya;ma.TestData=ja.default;const Na=ba;ma.TestDataFlagBuilder=Na.default;const $a=Sa;ma.TestDataRuleBuilder=$a.default,function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),e.FileDataSourceFactory=void 0;const n=ga;e.FileDataSourceFactory=n.default,i(ma,e),i(R,e)}(va);var Va={},Ua={};Object.defineProperty(Ua,"__esModule",{value:!0});Ua.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(Va,"__esModule",{value:!0}),Va.NullEventSource=void 0;const Ka=Ua;Va.NullEventSource=Ka.default;var za={};Object.defineProperty(za,"__esModule",{value:!0}),za.TtlCache=void 0;const Ba=qe;za.TtlCache=Ba.default,function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),e.createMigration=e.LDMigrationSuccess=e.LDMigrationError=e.BigSegmentStoreStatusProviderImpl=e.LDClientImpl=e.internalServer=e.platform=e.integrations=void 0;const l=n;e.BigSegmentStoreStatusProviderImpl=l.default;const c=s;e.LDClientImpl=c.default;const u=da;Object.defineProperty(e,"createMigration",{enumerable:!0,get:function(){return u.createMigration}}),Object.defineProperty(e,"LDMigrationError",{enumerable:!0,get:function(){return u.LDMigrationError}}),Object.defineProperty(e,"LDMigrationSuccess",{enumerable:!0,get:function(){return u.LDMigrationSuccess}}),e.integrations=va,e.platform=a,i(o,e),i($e,e),i(Va,e),i(a,e),e.internalServer=za}(i);var Ha={},qa={},Ga={};Object.defineProperty(Ga,"__esModule",{value:!0}),Ga.createCallbacks=void 0;Ga.createCallbacks=e=>({onError:t=>{var r;null===(r=null==e?void 0:e.error)||void 0===r||r.call(e,t.message)},onFailed:e=>{},onReady:()=>{},onUpdate:e=>{},hasEventListeners:()=>!1});var Wa={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createOptions=e.defaultOptions=void 0;const t=i;e.defaultOptions={stream:!1,sendEvents:!1,useLdd:!0,diagnosticOptOut:!0,logger:t.BasicLogger.get()};e.createOptions=t=>{var r;const i=Object.assign(Object.assign({},e.defaultOptions),t);return null===(r=i.logger)||void 0===r||r.debug(`Using LD options: ${JSON.stringify(i)}`),i}}(Wa);var Ja={},Xa=t&&t.__rest||function(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r};Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.validateOptions=void 0;Ja.validateOptions=(e,t)=>{const{featureStore:r,logger:i,sendEvents:n}=t,s=Xa(t,["featureStore","logger","sendEvents"]);if(!e)throw new Error("You must configure the client with a client key");if(!r||"object"!=typeof r||!r.get)throw new Error("You must configure the client with a feature store");if(!i)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},function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),i=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),i(Ga,e),i(Wa,e),i(Ja,e)}(qa),Object.defineProperty(Ha,"__esModule",{value:!0});const Ya=i,Za=qa;Ha.default=class extends Ya.LDClientImpl{constructor(e,t,r){const i=(0,Za.createOptions)(r);super(e,t,i,(0,Za.createCallbacks)(i.logger))}initialized(){return!0}waitForInitialization(){return Promise.resolve(this)}};var Qa={},eo={};Object.defineProperty(eo,"__esModule",{value:!0});eo.default=class{constructor(e){this._cacheTtlMs=e}get(){if(!(this._cacheTtlMs<0)&&void 0!==this._cache)return 0===this._cacheTtlMs||Date.now()<this._cache.expiration?this._cache.value:void(this._cache=void 0)}set(e){this._cache={value:e,expiration:Date.now()+this._cacheTtlMs}}},function(e){var r=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.EdgeFeatureStore=e.buildRootKey=void 0;const n=i,s=r(eo);e.buildRootKey=e=>`LD-Env-${e}`;e.EdgeFeatureStore=class{constructor(t,r,i,a,o){this._edgeProvider=t,this._sdkKey=r,this._description=i,this._logger=a,this.close=n.noop,this.delete=n.noop,this.upsert=n.noop,this._rootKey=(0,e.buildRootKey)(this._sdkKey),this._cache=new s.default(o)}async get(e,t,r){const{namespace:i}=e,n="features"===i?"flags":i;this._logger.debug(`Requesting ${t} from ${this._rootKey}.${n}`);try{const e=await this._getStorePayload();switch(i){case"features":r(e.flags[t]);break;case"segments":r(e.segments[t]);break;default:r(null)}}catch(e){this._logger.error(e),r(null)}}async all(e,t=n.noop){const{namespace:r}=e,i="features"===r?"flags":r;this._logger.debug(`Requesting all from ${this._rootKey}.${i}`);try{const e=await this._getStorePayload();switch(r){case"features":t(e.flags);break;case"segments":t(e.segments);break;default:throw new Error(`Unsupported DataKind: ${r}`)}}catch(e){this._logger.error(e),t({})}}async _getStorePayload(){let e=this._cache.get();if(void 0!==e)return e;const t=await this._edgeProvider.get(this._rootKey);if(!t)throw new Error(`${this._rootKey} is not found in KV.`);if(e=(0,n.deserializePoll)(t),!e)throw new Error(`Error deserializing ${this._rootKey}`);return this._cache.set(e),e}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}}}(Qa);var to={},ro={},io={};var no,so={exports:{}};so.exports=(no=no||function(e,r){var i;if("undefined"!=typeof window&&window.crypto&&(i=window.crypto),"undefined"!=typeof self&&self.crypto&&(i=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(i=globalThis.crypto),!i&&"undefined"!=typeof window&&window.msCrypto&&(i=window.msCrypto),!i&&void 0!==t&&t.crypto&&(i=t.crypto),!i)try{i=require("crypto")}catch(e){}var n=function(){if(i){if("function"==typeof i.getRandomValues)try{return i.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof i.randomBytes)try{return i.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},s=Object.create||function(){function e(){}return function(t){var r;return e.prototype=t,r=new e,e.prototype=null,r}}(),a={},o=a.lib={},l=o.Base={extend:function(e){var t=s(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},c=o.WordArray=l.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=t!=r?t:4*e.length},toString:function(e){return(e||d).stringify(this)},concat:function(e){var t=this.words,r=e.words,i=this.sigBytes,n=e.sigBytes;if(this.clamp(),i%4)for(var s=0;s<n;s++){var a=r[s>>>2]>>>24-s%4*8&255;t[i+s>>>2]|=a<<24-(i+s)%4*8}else for(var o=0;o<n;o+=4)t[i+o>>>2]=r[o>>>2];return this.sigBytes+=n,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=l.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],r=0;r<e;r+=4)t.push(n());return new c.init(t,e)}}),u=a.enc={},d=u.Hex={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n<r;n++){var s=t[n>>>2]>>>24-n%4*8&255;i.push((s>>>4).toString(16)),i.push((15&s).toString(16))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i<t;i+=2)r[i>>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new c.init(r,t/2)}},h=u.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],n=0;n<r;n++){var s=t[n>>>2]>>>24-n%4*8&255;i.push(String.fromCharCode(s))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i<t;i++)r[i>>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new c.init(r,t)}},f=u.Utf8={stringify:function(e){try{return decodeURIComponent(escape(h.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return h.parse(unescape(encodeURIComponent(e)))}},p=o.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new c.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=f.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r,i=this._data,n=i.words,s=i.sigBytes,a=this.blockSize,o=s/(4*a),l=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,u=e.min(4*l,s);if(l){for(var d=0;d<l;d+=a)this._doProcessBlock(n,d);r=n.splice(0,l),i.sigBytes-=u}return new c.init(r,u)},clone:function(){var e=l.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});o.Hasher=p.extend({cfg:l.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){p.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,r){return new e.init(r).finalize(t)}},_createHmacHelper:function(e){return function(t,r){return new v.HMAC.init(e,r).finalize(t)}}});var v=a.algo={};return a}(Math),no);var ao=so.exports;!function(e){return r=(t=e).lib,i=r.WordArray,n=r.Hasher,s=t.algo,a=[],o=s.SHA1=n.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],n=r[1],s=r[2],o=r[3],l=r[4],c=0;c<80;c++){if(c<16)a[c]=0|e[t+c];else{var u=a[c-3]^a[c-8]^a[c-14]^a[c-16];a[c]=u<<1|u>>>31}var d=(i<<5|i>>>27)+l+a[c];d+=c<20?1518500249+(n&s|~n&o):c<40?1859775393+(n^s^o):c<60?(n&s|n&o|s&o)-1894007588:(n^s^o)-899497514,l=o,o=s,s=n<<30|n>>>2,n=i,i=d}r[0]=r[0]+i|0,r[1]=r[1]+n|0,r[2]=r[2]+s|0,r[3]=r[3]+o|0,r[4]=r[4]+l|0},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;return t[i>>>5]|=128<<24-i%32,t[14+(i+64>>>9<<4)]=Math.floor(r/4294967296),t[15+(i+64>>>9<<4)]=r,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}}),t.SHA1=n._createHelper(o),t.HmacSHA1=n._createHmacHelper(o),e.SHA1;var t,r,i,n,s,a,o}(ao);!function(e){(function(t){var r=e,i=r.lib,n=i.WordArray,s=i.Hasher,a=r.algo,o=[],l=[];!function(){function e(e){for(var r=t.sqrt(e),i=2;i<=r;i++)if(!(e%i))return!1;return!0}function r(e){return 4294967296*(e-(0|e))|0}for(var i=2,n=0;n<64;)e(i)&&(n<8&&(o[n]=r(t.pow(i,.5))),l[n]=r(t.pow(i,1/3)),n++),i++}();var c=[],u=a.SHA256=s.extend({_doReset:function(){this._hash=new n.init(o.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],n=r[1],s=r[2],a=r[3],o=r[4],u=r[5],d=r[6],h=r[7],f=0;f<64;f++){if(f<16)c[f]=0|e[t+f];else{var p=c[f-15],v=(p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3,g=c[f-2],_=(g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10;c[f]=v+c[f-7]+_+c[f-16]}var m=i&n^i&s^n&s,y=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),b=h+((o<<26|o>>>6)^(o<<21|o>>>11)^(o<<7|o>>>25))+(o&u^~o&d)+l[f]+c[f];h=d,d=u,u=o,o=a+b|0,a=s,s=n,n=i,i=b+(y+m)|0}r[0]=r[0]+i|0,r[1]=r[1]+n|0,r[2]=r[2]+s|0,r[3]=r[3]+a|0,r[4]=r[4]+o|0,r[5]=r[5]+u|0,r[6]=r[6]+d|0,r[7]=r[7]+h|0},_doFinalize:function(){var e=this._data,r=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;return r[n>>>5]|=128<<24-n%32,r[14+(n+64>>>9<<4)]=t.floor(i/4294967296),r[15+(n+64>>>9<<4)]=i,e.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});r.SHA256=s._createHelper(u),r.HmacSHA256=s._createHmacHelper(u)})(Math),e.SHA256}(ao);!function(e){(function(){var t=e,r=t.lib.WordArray;function i(e,t,i){for(var n=[],s=0,a=0;a<t;a++)if(a%4){var o=i[e.charCodeAt(a-1)]<<a%4*2|i[e.charCodeAt(a)]>>>6-a%4*2;n[s>>>2]|=o<<24-s%4*8,s++}return r.create(n,s)}t.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,i=this._map;e.clamp();for(var n=[],s=0;s<r;s+=3)for(var a=(t[s>>>2]>>>24-s%4*8&255)<<16|(t[s+1>>>2]>>>24-(s+1)%4*8&255)<<8|t[s+2>>>2]>>>24-(s+2)%4*8&255,o=0;o<4&&s+.75*o<r;o++)n.push(i.charAt(a>>>6*(3-o)&63));var l=i.charAt(64);if(l)for(;n.length%4;)n.push(l);return n.join("")},parse:function(e){var t=e.length,r=this._map,n=this._reverseMap;if(!n){n=this._reverseMap=[];for(var s=0;s<r.length;s++)n[r.charCodeAt(s)]=s}var a=r.charAt(64);if(a){var o=e.indexOf(a);-1!==o&&(t=o)}return i(e,t,n)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(),e.enc.Base64}(ao);var oo=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(io,"__esModule",{value:!0});const lo=oo(ao);io.default=class{constructor(e){let t;switch(e){case"sha1":t=lo.default.algo.SHA1;break;case"sha256":t=lo.default.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=lo.default.enc.Base64;break;case"hex":r=lo.default.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}};var co={};!function(e){var t,r,i;r=(t=e).lib.Base,i=t.enc.Utf8,t.algo.HMAC=r.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=i.parse(t));var r=e.blockSize,n=4*r;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var s=this._oKey=t.clone(),a=this._iKey=t.clone(),o=s.words,l=a.words,c=0;c<r;c++)o[c]^=1549556828,l[c]^=909522486;s.sigBytes=a.sigBytes=n,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher,r=t.finalize(e);return t.reset(),t.finalize(this._oKey.clone().concat(r))}})}(ao);var uo=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(co,"__esModule",{value:!0});const ho=uo(ao);co.default=class{constructor(e,t){let r;switch(e){case"sha1":r=ho.default.algo.SHA1;break;case"sha256":r=ho.default.algo.SHA256;break;default:throw new Error("unsupported hash algorithm. Only sha1 and sha256 are supported.")}this._cryptoJSHmac=ho.default.algo.HMAC.create(r,t)}digest(e){const t=this._cryptoJSHmac.finalize();if("base64"===e)return t.toString(ho.default.enc.Base64);if("hex"===e)return t.toString(ho.default.enc.Hex);throw new Error("unsupported output encoding. Only base64 and hex are supported.")}update(e){return this._cryptoJSHmac.update(e),this}};var fo=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ro,"__esModule",{value:!0});const po=e,vo=fo(io),go=fo(co);ro.default=class{createHash(e){return new vo.default(e)}createHmac(e,t){return new go.default(e,t)}randomUUID(){const e=new Uint32Array(1);return po.crypto.getRandomValues(e),e.join()}};var _o={};Object.defineProperty(_o,"__esModule",{value:!0});const mo=i;class yo{constructor(){this.headers={},this.status=0}text(){return Promise.resolve("")}json(){return Promise.resolve({})}}_o.default=class{fetch(e,t={}){return Promise.resolve(new yo)}createEventSource(e,t){return new mo.NullEventSource(e,t)}getEventSourceCapabilities(){return{readTimeout:!1,headers:!1,customMethod:!1}}};var bo=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(to,"__esModule",{value:!0});const Eo=bo(ro),So=bo(_o);to.default=class{constructor(e){this.crypto=new Eo.default,this.requests=new So.default,this.info=e}};var wo={};Object.defineProperty(wo,"__esModule",{value:!0});class Oo{constructor(e,t,r){this._platformName=e,this._sdkName=t,this._sdkVersion=r}platformData(){return{name:this._platformName}}sdkData(){return{name:this._sdkName,version:this._sdkVersion,userAgentBase:"AkamaiEdgeSDK"}}}wo.default=(e,t,r)=>new Oo(e,t,r),function(e){var r=t&&t.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=t&&t.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)},s=t&&t.__rest||function(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r},a=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.init=e.EdgeFeatureStore=void 0;const o=i,l=a(Ha),c=Qa;Object.defineProperty(e,"EdgeFeatureStore",{enumerable:!0,get:function(){return c.EdgeFeatureStore}});const u=a(to),d=a(wo),h=qa;n(i,e);e.init=e=>{var t;const{sdkKey:r,options:i={},featureStoreProvider:n,platformName:a,sdkName:f,sdkVersion:p}=e,v=null!==(t=i.logger)&&void 0!==t?t:o.BasicLogger.get(),g=i,{cacheTtlMs:_}=g,m=s(g,["cacheTtlMs"]),y=new c.EdgeFeatureStore(n,r,"Akamai",v,null!=_?_:100),b=Object.assign({featureStore:y,logger:v},m);(0,h.validateOptions)(e.sdkKey,b);const E=(0,d.default)(a,f,p);return new l.default(r,new u.default(E),b)}}(r);exports.init=({options:e={},sdkKey:t,featureStoreProvider:i})=>r.init({sdkKey:t,options:e,featureStoreProvider:i,platformName:"Akamai EdgeWorker",sdkName:"@launchdarkly/akamai-server-base-sdk",sdkVersion:"3.0.34"});
2
2
  //# sourceMappingURL=bundle.cjs.js.map